A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
feat(avf): add AVF/pKVM backend behind a VmEngine interface
ExTv00f2e5a6aa55
diff --git a/README.md b/README.mdindex 88e8bce..b1abdc7 100644--- a/README.md+++ b/README.md@@ -88,6 +88,56 @@ RAM and CPU changes take effect on the next start; everything else is hot.**Settings → Export Diagnostic Log** bundles app info, current settings, VM state, app logcat and the full QEMU console output into a single `log.txt` and shares it via the standard Android share sheet. Attach this to bug reports; it's almost always enough to diagnose a boot or container issue without ADB.+**Settings → About → AVF (pKVM) diagnostic** runs a six-line probe of the Android Virtualization Framework on your device — feature flag, permissions, system service reachability — and a smoke-start of a minimal VM to confirm the path actually works end-to-end. Tap it before opening an issue about KVM not engaging.++## Hardware acceleration (KVM / pKVM)++By default Podroid emulates the guest CPU in software (QEMU TCG). On the small set of Android devices that ship Google's **pKVM** (Pixel 8/9/10, a few others), Podroid can run the same VM under the **Android Virtualization Framework** (AVF) for near-native CPU performance — boot times drop from ~15 s to under 3 s, and CPU-bound container workloads run at host speed.++This requires three things, all under your control:++### 1. Check that your phone ships pKVM++```bash+adb shell pm list features | grep virtualization_framework+adb shell getprop ro.boot.hypervisor.vm.supported+adb shell getprop ro.boot.hypervisor.protected_vm.supported+```++If the first line returns `feature:android.software.virtualization_framework` and the two getprop lines return `1`, your device is supported. If any are empty, it's not — Podroid will silently fall back to QEMU/TCG and nothing else in this section applies.++Confirmed support: Pixel 8/8 Pro, Pixel 9/9 Pro/Pro XL, Pixel 10/10 Pro/Pro XL, Pixel Fold, Pixel Tablet.++### 2. Grant the two AVF permissions via ADB++The `MANAGE_VIRTUAL_MACHINE` and `USE_CUSTOM_VIRTUAL_MACHINE` permissions are `signature|preinstalled|development` — they can't be granted from the in-app UI, but `pm grant` works once per install:++```bash+adb shell pm grant com.excp.podroid android.permission.MANAGE_VIRTUAL_MACHINE+adb shell pm grant com.excp.podroid android.permission.USE_CUSTOM_VIRTUAL_MACHINE+```++The grants persist across reboots and in-place app updates. They survive `adb install -r` but **not** `adb install -d` followed by a full uninstall+reinstall.++### 3. Verify and select the backend in-app++Open **Settings → About → AVF (pKVM) diagnostic**. The dialog's bottom line should read:++```+Smoke test:+SUCCESS: AVF accepted our config, VM started + stopped cleanly.+```++Then **Settings → Advanced → Backend** picks how Podroid chooses at startup:++- **Auto** (default) — use AVF if the feature + permissions are both present, otherwise QEMU. The right choice for everyone.+- **AVF (KVM)** — force AVF. Useful for debugging; the VM will error explicitly if AVF rejects your config rather than silently falling back.+- **QEMU (TCG)** — force software emulation even on a pKVM device. Useful for reproducing user reports or testing the slow path.++Changing the backend requires a VM stop + restart (same as RAM/CPU changes).++If your phone has the feature but you haven't run the `pm grant` commands yet, the home screen shows a one-time hint banner with the commands ready to copy.+## Troubleshooting### "QEMU crashed (SIGKILL)" / VM dies when I switch to another appdiff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 17dc739..cb5265a 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -137,6 +137,11 @@ dependencies {implementation(project(":terminal-emulator"))implementation(project(":terminal-view"))+ // HiddenApiBypass — exempts our process from Android 14+ reflection filtering+ // so we can call the @SystemApi VirtualMachineManager constructors via+ // reflection on devices where the dev-grant path holds (Pixel 8+ etc.).+ implementation("org.lsposed.hiddenapibypass:hiddenapibypass:6.1")+// TestingtestImplementation(libs.junit)androidTestImplementation(libs.androidx.junit)diff --git a/app/proguard-rules.pro b/app/proguard-rules.proindex 4d5b49d..57bedda 100644--- a/app/proguard-rules.pro+++ b/app/proguard-rules.pro@@ -11,3 +11,9 @@-keepclassmembers class com.termux.terminal.TerminalSession {com.termux.terminal.TerminalEmulator mEmulator;}++# java.net.UnixDomainSocketAddress (JDK 16) is present on Android API 34+ at+# runtime but absent from the compile-time SDK stubs. ConsoleFanout uses it+# only on AVF/API-34 devices and is guarded by @RequiresApi(34). Suppress the+# R8 missing-class error so release builds succeed.+-dontwarn java.net.UnixDomainSocketAddressdiff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 73bec56..24caf2d 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -42,6 +42,19 @@<!-- Large heap for QEMU memory allocation --><uses-feature android:name="android.hardware.opengles.aep" android:required="false" />+ <!--+ Android Virtualization Framework (AVF / pKVM) opt-in. Both permissions+ are signature|*|development and can be granted to a side-loaded APK via+ `adb shell pm grant com.excp.podroid <name>` on pKVM-capable devices+ (Pixel 8/9/10 etc.). required="false" so the APK still installs on+ devices without AVF — runtime code falls back to QEMU/TCG.+ -->+ <uses-feature+ android:name="android.software.virtualization_framework"+ android:required="false" />+ <uses-permission android:name="android.permission.MANAGE_VIRTUAL_MACHINE" />+ <uses-permission android:name="android.permission.USE_CUSTOM_VIRTUAL_MACHINE" />+<applicationandroid:name=".PodroidApplication"android:allowBackup="true"diff --git a/app/src/main/java/com/excp/podroid/PodroidApplication.kt b/app/src/main/java/com/excp/podroid/PodroidApplication.ktindex 33a3bdd..4c017bd 100644--- a/app/src/main/java/com/excp/podroid/PodroidApplication.kt+++ b/app/src/main/java/com/excp/podroid/PodroidApplication.kt@@ -8,8 +8,10 @@package com.excp.podroidimport android.app.Application+import android.os.Buildimport android.util.Logimport dagger.hilt.android.HiltAndroidApp+import org.lsposed.hiddenapibypass.HiddenApiBypassimport java.io.Fileimport java.util.concurrent.Executorsimport java.util.concurrent.TimeUnit@@ -19,9 +21,28 @@ class PodroidApplication : Application() {override fun onCreate() {super.onCreate()+ exemptHiddenApi()extractAssets()}+ // Android 14+ hides @SystemApi reflection lookups (returning NoSuchMethod+ // even via getDeclared*). Two prefixes need exempting:+ // - Landroid/system/virtualmachine/ — AVF framework (AvfDiagnostics + AvfEngine)+ // - Ljava/net/UnixDomainSocketAddress — ConsoleFanout needs UDS.of(String)+ // which Android marks BLOCKED for untrusted_app even though the class+ // itself is on the bootclasspath.+ // No-op on sub-P; the exemption itself never throws.+ private fun exemptHiddenApi() {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return+ runCatching {+ HiddenApiBypass.addHiddenApiExemptions(+ "Landroid/system/virtualmachine/",+ "Landroid/system/UnixSocketAddress",+ "Ljava/net/UnixDomainSocketAddress",+ )+ }.onFailure { Log.w(TAG, "HiddenApiBypass exemption failed", it) }+ }+private fun extractAssets() {// Fan out the four top-level extractions across a small thread pool.// Disk-write throughput is the bottleneck for the squashfs (~41 MB),diff --git a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.ktindex c7cc550..92eeb40 100644--- a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt+++ b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt@@ -15,6 +15,7 @@ import androidx.datastore.preferences.core.intPreferencesKeyimport androidx.datastore.preferences.core.longPreferencesKeyimport androidx.datastore.preferences.core.stringPreferencesKeyimport androidx.datastore.preferences.preferencesDataStore+import com.excp.podroid.engine.EngineSelectionimport dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.first@@ -46,6 +47,8 @@ class SettingsRepository @Inject constructor(val KEY_HAPTICS_ENABLED = booleanPreferencesKey("haptics_enabled")val KEY_DYNAMIC_COLOR_ENABLED = booleanPreferencesKey("dynamic_color_enabled")val KEY_LAST_BOOT_DURATION_MS = longPreferencesKey("last_boot_duration_ms")+ val KEY_ENGINE_SELECTION = stringPreferencesKey("engine_selection")+ val KEY_AVF_HINT_DISMISSED = booleanPreferencesKey("avf_hint_dismissed")/*** Default tunable QEMU args — CPU model, accel tuning, RNG source, overcommit.@@ -103,6 +106,11 @@ class SettingsRepository @Inject constructor(val hapticsEnabled = pref(KEY_HAPTICS_ENABLED, true)val dynamicColorEnabled = pref(KEY_DYNAMIC_COLOR_ENABLED, false)val lastBootDurationMs = pref(KEY_LAST_BOOT_DURATION_MS, 0L)+ val avfHintDismissed = pref(KEY_AVF_HINT_DISMISSED, false)+ val engineSelection: Flow<EngineSelection> = context.dataStore.data.map { prefs ->+ runCatching { EngineSelection.valueOf(prefs[KEY_ENGINE_SELECTION] ?: "AUTO") }+ .getOrDefault(EngineSelection.AUTO)+ }suspend fun setDarkTheme(value: Boolean) = set(KEY_DARK_THEME, value)suspend fun setVmRamMb(value: Int) = set(KEY_VM_RAM, value)@@ -120,6 +128,8 @@ class SettingsRepository @Inject constructor(suspend fun setHapticsEnabled(value: Boolean) = set(KEY_HAPTICS_ENABLED, value)suspend fun setDynamicColorEnabled(value: Boolean) = set(KEY_DYNAMIC_COLOR_ENABLED, value)suspend fun setLastBootDurationMs(value: Long) = set(KEY_LAST_BOOT_DURATION_MS, value)+ suspend fun setEngineSelection(value: EngineSelection) = set(KEY_ENGINE_SELECTION, value.name)+ suspend fun setAvfHintDismissed(value: Boolean) = set(KEY_AVF_HINT_DISMISSED, value)// Snapshots used by non-Compose call sites (PodroidService, exporters).suspend fun getSshEnabledSnapshot() = sshEnabled.first()@@ -132,4 +142,5 @@ class SettingsRepository @Inject constructor(suspend fun getTerminalFontSnapshot() = terminalFont.first()suspend fun getQemuExtraArgsSnapshot() = qemuExtraArgs.first()suspend fun getKernelExtraCmdlineSnapshot() = kernelExtraCmdline.first()+ suspend fun getEngineSelectionSnapshot() = engineSelection.first()}diff --git a/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt b/app/src/main/java/com/excp/podroid/engine/BootStageDetector.ktnew file mode 100644index 0000000..4c0457b--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/BootStageDetector.kt@@ -0,0 +1,56 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ */+package com.excp.podroid.engine++import kotlinx.coroutines.flow.MutableStateFlow++/**+ * Engine-agnostic boot-progress detector. Both engines feed it raw guest+ * console bytes; it sets [bootStage] flow markers it observes and flips+ * [state] to Running when "Ready!" appears. Scans only the last 1024 chars+ * of an accumulating buffer to survive multi-byte split reads on fast+ * devices (see the history of detectBootStage in PodroidQemu pre-refactor).+ * One-shot: stops scanning after the first "Ready!" to keep [onReady] idempotent.+ */+class BootStageDetector(+ private val bootStage: MutableStateFlow<String>,+ private val state: MutableStateFlow<VmState>,+ private val onReady: () -> Unit,+) {+ private val buf = StringBuilder()+ private val maxScan = 1024+ private val maxKeep = 4096+ private var ready = false++ /**+ * Reset the one-shot guard + buffer. Called by engines at the start of+ * each VM run so a Stop → Start cycle's second boot can re-fire onReady.+ * Without this, the detector silently ignores the new boot stream because+ * `ready=true` from the previous run, and state stays Starting forever.+ */+ fun reset() {+ ready = false+ buf.clear()+ }++ fun feed(bytes: ByteArray, len: Int) {+ if (ready) return+ // Latin-1 decode is byte-safe (1 byte → 1 char) and the ASCII subset+ // matches UTF-8 exactly, so our pure-ASCII markers still match.+ buf.append(String(bytes, 0, len, Charsets.ISO_8859_1))+ if (buf.length > maxKeep) buf.delete(0, buf.length - maxKeep)+ val tail = if (buf.length > maxScan) buf.substring(buf.length - maxScan) else buf.toString()+ when {+ tail.contains("Ready!") -> { ready = true; bootStage.value = "Ready"; state.value = VmState.Running; onReady() }+ tail.contains("Almost ready") -> bootStage.value = "Almost ready..."+ tail.contains("Starting SSH") -> bootStage.value = "Starting SSH..."+ tail.contains("Configuring containers") -> bootStage.value = "Configuring containers..."+ tail.contains("Network found") -> bootStage.value = "Network found"+ tail.contains("Loading kernel modules") -> bootStage.value = "Loading kernel modules..."+ tail.contains("Mounting storage") -> bootStage.value = "Mounting storage..."+ tail.contains("Booting kernel") -> bootStage.value = "Booting kernel..."+ }+ }+}diff --git a/app/src/main/java/com/excp/podroid/engine/EngineModule.kt b/app/src/main/java/com/excp/podroid/engine/EngineModule.ktnew file mode 100644index 0000000..86a78f2--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/EngineModule.kt@@ -0,0 +1,53 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * Picks the VM backend at service-construction time. On Pixel 8+ with+ * `adb pm grant` for MANAGE_VIRTUAL_MACHINE + USE_CUSTOM_VIRTUAL_MACHINE,+ * uses AVF (KVM). Otherwise falls back to QEMU/TCG. User can override+ * via Settings → Backend.+ */+package com.excp.podroid.engine++import android.content.Context+import com.excp.podroid.data.repository.SettingsRepository+import com.excp.podroid.engine.avf.AvfDiagnostics+import com.excp.podroid.engine.avf.AvfEngine+import dagger.Module+import dagger.Provides+import dagger.hilt.InstallIn+import dagger.hilt.android.qualifiers.ApplicationContext+import dagger.hilt.components.SingletonComponent+import kotlinx.coroutines.runBlocking+import javax.inject.Provider+import javax.inject.Singleton++@Module+@InstallIn(SingletonComponent::class)+object EngineModule {++ @Provides+ @Singleton+ fun provideVmEngine(+ @ApplicationContext context: Context,+ settings: SettingsRepository,+ qemuProvider: Provider<QemuEngine>,+ avfProvider: Provider<AvfEngine>,+ ): VmEngine {+ val selection = runBlocking { settings.getEngineSelectionSnapshot() }+ val probe = AvfDiagnostics.probe(context)+ val pick = when {+ selection == EngineSelection.QEMU -> qemuProvider.get()+ // AVF forced: no capability check on purpose. If the device can't run+ // AVF, AvfEngine will surface the error so the user knows; silent+ // fallback to QEMU would mask their explicit choice.+ selection == EngineSelection.AVF -> avfProvider.get()+ probe.featureSupported &&+ probe.managePermissionGranted &&+ probe.customPermissionGranted -> avfProvider.get()+ else -> qemuProvider.get()+ }+ android.util.Log.i("EngineModule", "selected engine=${pick.backendId} selection=$selection feature=${probe.featureSupported} perms=${probe.managePermissionGranted}/${probe.customPermissionGranted}")+ return pick+ }+}diff --git a/app/src/main/java/com/excp/podroid/engine/EngineSelection.kt b/app/src/main/java/com/excp/podroid/engine/EngineSelection.ktnew file mode 100644index 0000000..5fb5db0--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/EngineSelection.kt@@ -0,0 +1,11 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ */+package com.excp.podroid.engine++/**+ * User-facing backend choice. Persisted in DataStore as the enum name string.+ * AUTO = detect AVF at startup, fall back to QEMU. 99% case.+ */+enum class EngineSelection { AUTO, AVF, QEMU }diff --git a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt b/app/src/main/java/com/excp/podroid/engine/QemuEngine.ktsimilarity index 91%rename from app/src/main/java/com/excp/podroid/engine/PodroidQemu.ktrename to app/src/main/java/com/excp/podroid/engine/QemuEngine.ktindex 941ea80..753af62 100644--- a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt+++ b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt@@ -6,10 +6,10 @@* sockets for the terminal layer:** serial.sock — QEMU -serial (ttyAMA0 in the VM). Boot-log sink only:- * PodroidQemu's monitorBootSerial coroutine connects here+ * QemuEngine's monitorBootSerial coroutine connects here* for the lifetime of the VM, streaming kernel messages* and init-podroid boot stages into console.log + the- * in-memory ring buffer used by detectBootStage().+ * in-memory ring buffer used by BootStageDetector.** terminal.sock — QEMU virtio-console (/dev/hvc0 in the VM). Primary* terminal I/O. getty runs on hvc0; the podroid-bridge@@ -50,22 +50,24 @@ import javax.inject.Singleton@SuppressLint("StaticFieldLeak") // ApplicationContext — lives as long as the process, no leak@Singleton-class PodroidQemu @Inject constructor(+class QemuEngine @Inject constructor(@ApplicationContext private val context: Context,private val settingsRepository: com.excp.podroid.data.repository.SettingsRepository,-) {+) : VmEngine {private val _state = MutableStateFlow<VmState>(VmState.Idle)- val state: StateFlow<VmState> = _state.asStateFlow()+ override val state: StateFlow<VmState> = _state.asStateFlow()private val _consoleText = MutableStateFlow("")- val consoleText: StateFlow<String> = _consoleText.asStateFlow()+ override val consoleText: StateFlow<String> = _consoleText.asStateFlow()private val _bootStage = MutableStateFlow("")private var _terminalSession: TerminalSession? = null- val terminalSession: TerminalSession? get() = _terminalSession- val bootStage: StateFlow<String> = _bootStage.asStateFlow()+ override val terminalSession: TerminalSession? get() = _terminalSession+ override val bootStage: StateFlow<String> = _bootStage.asStateFlow()++ override val backendId: String = "qemu"@Volatilevar process: Process? = null@@ -82,7 +84,7 @@ class PodroidQemu @Inject constructor(private val qmpSocketPath: String get() = "${context.filesDir.absolutePath}/qmp.sock"- val qmpClient: QmpClient by lazy { QmpClient(qmpSocketPath) }+ override val qmpClient: QmpClient? by lazy { QmpClient(qmpSocketPath) }private var ioScope: CoroutineScope? = null@@ -91,6 +93,11 @@ class PodroidQemu @Inject constructor(private val consoleBuilder = StringBuilder()private val maxConsoleSize = 64 * 1024+ private val bootStageDetector = BootStageDetector(_bootStage, _state) {+ persistBootDuration()+ autoStartBridge()+ }+/** Set once cleanup() has run for the current VM lifetime; reset by start(). */private val cleanedUp = AtomicBoolean(true)@@ -100,7 +107,7 @@ class PodroidQemu @Inject constructor(* terminal UI exists) and plug in the real ViewModel client later.*/@Volatile- var sessionClientDelegate: TerminalSessionClient? = null+ override var sessionClientDelegate: TerminalSessionClient? = nullprivate val proxySessionClient = object : TerminalSessionClient {override fun onTextChanged(s: TerminalSession) { sessionClientDelegate?.onTextChanged(s) }@@ -177,7 +184,7 @@ class PodroidQemu @Inject constructor(}}- fun createTerminalSession(client: TerminalSessionClient): TerminalSession {+ override fun createTerminalSession(client: TerminalSessionClient): TerminalSession {sessionClientDelegate = client// Session already auto-started during boot — just return it@@ -209,19 +216,7 @@ class PodroidQemu @Inject constructor(return sess}- /** All snapshotted settings the engine needs for a single VM launch. */- data class LaunchConfig(- val ramMb: Int = 512,- val cpus: Int = 1,- val sshEnabled: Boolean = false,- val androidIp: String = "unknown",- val storageSizeGb: Int = 2,- val storageAccessEnabled: Boolean = false,- val qemuExtraArgs: String = "",- val kernelExtraCmdline: String = "",- )-- suspend fun start(portForwards: List<PortForwardRule>, config: LaunchConfig) {+ override suspend fun start(portForwards: List<PortForwardRule>, config: VmConfig) {if (_state.value is VmState.Starting || _state.value is VmState.Running) {Log.w(TAG, "start() called while VM is ${_state.value}, ignoring")return@@ -240,6 +235,10 @@ class PodroidQemu @Inject constructor(consoleBuilder.clear()_consoleText.value = ""_bootStage.value = "Starting QEMU..."+ // Re-arm the one-shot detector so a Stop → Start cycle's second boot+ // can fire onReady again. Without this the new boot's "Ready!" marker+ // is silently ignored and state stays Starting forever.+ bootStageDetector.reset()// Clean up stale sockets from a previous run. qmp.sock must be// included — a leftover file from a crashed QEMU prevents the new@@ -373,7 +372,7 @@ class PodroidQemu @Inject constructor(// Streaming UTF-8 decoder — kept across read() calls so multi-byte// sequences split between chunks decode correctly instead of// surfacing as U+FFFD replacement chars in the in-memory console- // and breaking detectBootStage() matches.+ // and breaking BootStageDetector matches.val decoder = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)@@ -411,9 +410,7 @@ class PodroidQemu @Inject constructor(}charBuf.clear()- if (_bootStage.value != "Ready") {- detectBootStage()- }+ bootStageDetector.feed(readBuf, n)}}} catch (e: Exception) {@@ -425,38 +422,13 @@ class PodroidQemu @Inject constructor(}}- private fun detectBootStage() {- // Use the existing consoleBuilder as a stateful buffer.- // We only scan the last 1024 characters for performance, which is- // plenty for matching our short boot stage strings even if split.- val bufferLen = consoleBuilder.length- val scanLen = if (bufferLen > 1024) 1024 else bufferLen- val text = consoleBuilder.substring(bufferLen - scanLen)-- when {- text.contains("Ready!") -> {- _bootStage.value = "Ready"- persistBootDuration()- _state.value = VmState.Running- autoStartBridge()- }- text.contains("Almost ready") -> _bootStage.value = "Almost ready..."- text.contains("Starting SSH") -> _bootStage.value = "Starting SSH..."- text.contains("Configuring containers") -> _bootStage.value = "Configuring containers..."- text.contains("Network found") -> _bootStage.value = "Network found"- text.contains("Loading kernel modules") -> _bootStage.value = "Loading kernel modules..."- text.contains("Mounting storage") -> _bootStage.value = "Mounting storage..."- text.contains("Booting kernel") -> _bootStage.value = "Booting kernel..."- }- }-/*** Signal the VM to stop. Destroys the QEMU process; the start() coroutine's* proc.waitFor() will fall through and run cleanup() + set the final state.* Avoids the historical race where stop() and the start() exit-path both* called cleanup() concurrently and fought over _state.value.*/- fun stop() {+ override fun stop() {val proc = process ?: returnproc.destroy()try {@@ -490,7 +462,7 @@ class PodroidQemu @Inject constructor(private fun buildCommand(qemuExe: File,portForwards: List<PortForwardRule>,- config: LaunchConfig,+ config: VmConfig,): List<String> {val args = mutableListOf<String>()val userQemuExtras = config.qemuExtraArgs.trim()@@ -669,7 +641,7 @@ class PodroidQemu @Inject constructor(}companion object {- private const val TAG = "PodroidQemu"+ private const val TAG = "QemuEngine"/** Shared deadline for both start()'s socket-readiness loop and monitorBootSerial's wait. */private const val SOCKET_READY_TIMEOUT_MS = 10_000Ldiff --git a/app/src/main/java/com/excp/podroid/engine/VmEngine.kt b/app/src/main/java/com/excp/podroid/engine/VmEngine.ktnew file mode 100644index 0000000..f1e288d--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/VmEngine.kt@@ -0,0 +1,61 @@+/*+ * Podroid+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * This program is free software; you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation; either version 2 of the License, or+ * (at your option) any later version.+ */+package com.excp.podroid.engine++import com.excp.podroid.data.repository.PortForwardRule+import com.termux.terminal.TerminalSession+import com.termux.terminal.TerminalSessionClient+import kotlinx.coroutines.flow.StateFlow++/**+ * The seam between Podroid's UI/service layer and a concrete VM runtime+ * (QEMU/TCG today, AVF/pKVM on Pixel 8+ with `adb pm grant`). Implementations+ * are picked by `EngineFactory` at service-construction time and live for the+ * lifetime of the foreground service; swapping requires the VM to be stopped.+ */+interface VmEngine {+ val state: StateFlow<VmState>+ val bootStage: StateFlow<String>+ val consoleText: StateFlow<String>+ val terminalSession: TerminalSession?++ /** Identifier for logs + the diagnostic dialog. Stable, lowercase. */+ val backendId: String++ /** QEMU-specific. Null on backends that don't use QMP (e.g. AVF). */+ val qmpClient: QmpClient?++ /**+ * Proxy delegate forwarded to the terminal session client. Set by the+ * terminal UI layer so the engine can relay events before the UI attaches.+ */+ var sessionClientDelegate: TerminalSessionClient?++ suspend fun start(portForwards: List<PortForwardRule>, config: VmConfig)+ fun stop()++ /** Create (or return the pre-started) terminal session wired to the bridge. */+ fun createTerminalSession(client: TerminalSessionClient): TerminalSession+}++/**+ * Engine-agnostic launch parameters. Strict superset of PodroidQemu.LaunchConfig+ * so existing call sites don't change.+ */+data class VmConfig(+ val ramMb: Int = 512,+ val cpus: Int = 1,+ val sshEnabled: Boolean = false,+ val androidIp: String = "unknown",+ val storageSizeGb: Int = 2,+ val storageAccessEnabled: Boolean = false,+ val qemuExtraArgs: String = "",+ val kernelExtraCmdline: String = "",+)diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfDiagnostics.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfDiagnostics.ktnew file mode 100644index 0000000..7519236--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfDiagnostics.kt@@ -0,0 +1,204 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * AVF (Android Virtualization Framework) diagnostic + smoke-test entry point.+ *+ * The android.system.virtualmachine.* APIs are @SystemApi (only present in+ * the system-stub JAR, not the public SDK). We reach them via reflection so+ * a normal Gradle build still compiles on every device. On phones without+ * pKVM the reflective lookups simply fail and the probe reports "not+ * available" — no crash, no missing-class linker error.+ *+ * Purpose: validate the manifest+`adb pm grant` path on pKVM hardware+ * (Pixel 8/9/10) before investing in a real dual-backend rewrite. Reports+ * what's present, what's granted, whether the service is reachable, and+ * (optionally) attempts to create + start a minimal VM using our existing+ * Alpine kernel/initrd in filesDir.+ */+package com.excp.podroid.engine.avf++import android.content.Context+import android.content.pm.PackageManager+import java.io.File++/** One-line entries in the diagnostic report; UI just joins them. */+data class AvfReport(+ val featureSupported: Boolean,+ val managePermissionGranted: Boolean,+ val customPermissionGranted: Boolean,+ val virtApexPresent: Boolean,+ val managerClassPresent: Boolean,+ val serviceReachable: Boolean,+ val smokeTestResult: String?,+ val activeBackend: String = "?",+) {+ fun pretty(): String = buildString {+ appendLine("Active backend: $activeBackend")+ appendLine()+ appendLine("Feature: android.software.virtualization_framework = $featureSupported")+ appendLine("Perm: MANAGE_VIRTUAL_MACHINE granted = $managePermissionGranted")+ appendLine("Perm: USE_CUSTOM_VIRTUAL_MACHINE granted = $customPermissionGranted")+ appendLine("APEX: /apex/com.android.virt present = $virtApexPresent")+ appendLine("API: VirtualMachineManager class loadable = $managerClassPresent")+ appendLine("Service: reachable via system service = $serviceReachable")+ if (smokeTestResult != null) {+ appendLine()+ appendLine("Smoke test:")+ appendLine(smokeTestResult)+ }+ }+}++object AvfDiagnostics {++ private const val FEATURE = "android.software.virtualization_framework"+ private const val PERM_MANAGE = "android.permission.MANAGE_VIRTUAL_MACHINE"+ private const val PERM_CUSTOM = "android.permission.USE_CUSTOM_VIRTUAL_MACHINE"+ private const val CLS_MANAGER = "android.system.virtualmachine.VirtualMachineManager"+ private const val CLS_CONFIG = "android.system.virtualmachine.VirtualMachineConfig"+ private const val CLS_CUSTOM_CFG = "android.system.virtualmachine.VirtualMachineCustomImageConfig"++ /**+ * Read-only probe — never blocks, never touches the system service for+ * real (just checks reachability). Safe to call from anywhere.+ */+ fun probe(context: Context): AvfReport {+ val pm = context.packageManager+ val featureSupported = pm.hasSystemFeature(FEATURE)+ val managePermissionGranted = pm.checkPermission(PERM_MANAGE, context.packageName) ==+ PackageManager.PERMISSION_GRANTED+ val customPermissionGranted = pm.checkPermission(PERM_CUSTOM, context.packageName) ==+ PackageManager.PERMISSION_GRANTED+ val virtApexPresent = File("/apex/com.android.virt/bin").exists()+ val managerClassPresent = runCatching { Class.forName(CLS_MANAGER) }.isSuccess+ val serviceReachable = managerClassPresent && managePermissionGranted &&+ runCatching { getVirtualizationManager(context) != null }.getOrDefault(false)++ return AvfReport(+ featureSupported = featureSupported,+ managePermissionGranted = managePermissionGranted,+ customPermissionGranted = customPermissionGranted,+ virtApexPresent = virtApexPresent,+ managerClassPresent = managerClassPresent,+ serviceReachable = serviceReachable,+ smokeTestResult = null,+ )+ }++ /**+ * Attempts a real minimal-VM creation using our existing alpine kernel+ * + initrd. Returns a human-readable result string. Blocks for a few+ * seconds. Call off the UI thread.+ *+ * NOTE: this only validates that *creation* + *run* are accepted by the+ * framework — it does not stream the console or wait for guest boot.+ * The VM is stopped/deleted immediately.+ */+ fun runSmokeTest(context: Context): String {+ val pre = probe(context)+ if (!pre.featureSupported) return "skipped: feature flag not present (device does not ship AVF)"+ if (!pre.managePermissionGranted) return "skipped: MANAGE_VIRTUAL_MACHINE not granted (run: adb shell pm grant ${context.packageName} $PERM_MANAGE)"+ if (!pre.customPermissionGranted) return "skipped: USE_CUSTOM_VIRTUAL_MACHINE not granted (run: adb shell pm grant ${context.packageName} $PERM_CUSTOM)"+ if (!pre.managerClassPresent) return "FAILED: $CLS_MANAGER not on the boot classpath — system stub missing"++ val kernel = File(context.filesDir, "vmlinuz-virt")+ val initrd = File(context.filesDir, "initrd.img")+ if (!kernel.exists()) return "FAILED: kernel not extracted yet at ${kernel.absolutePath}"+ if (!initrd.exists()) return "FAILED: initrd not extracted yet at ${initrd.absolutePath}"++ return try {+ val vmm = getVirtualizationManager(context)+ ?: return "FAILED: VirtualMachineManager system service returned null"++ val customCfg = buildCustomImageConfig(kernel.absolutePath, initrd.absolutePath)+ val config = buildVirtualMachineConfig(context, customCfg)++ val name = "podroid-avf-smoke"+ val vm = invokeOrCreate(vmm, name, config)++ // Start + immediately stop. We're proving the framework accepts us,+ // not running a workload.+ runCatching {+ vm.javaClass.getMethod("run").invoke(vm)+ }.onFailure { e ->+ deleteSafely(vmm, name)+ return "FAILED at vm.run(): ${e.cause?.javaClass?.simpleName ?: e.javaClass.simpleName}: ${e.cause?.message ?: e.message}"+ }++ // Give the VM 1.5s to actually start (we just want to know whether+ // the framework rejected us — usually fails synchronously).+ Thread.sleep(1500)++ runCatching { vm.javaClass.getMethod("stop").invoke(vm) }+ deleteSafely(vmm, name)++ "SUCCESS: AVF accepted our config, VM started + stopped cleanly. The dev-grant path works on this device."+ } catch (e: Throwable) {+ val cause = e.cause ?: e+ "FAILED: ${cause.javaClass.simpleName}: ${cause.message}"+ }+ }++ private fun getVirtualizationManager(context: Context): Any? {+ // Context.getSystemService(Class) — but the class is loaded reflectively+ // so we can't call the typed overload at compile time.+ val mgrCls = Class.forName(CLS_MANAGER)+ val m = Context::class.java.getMethod("getSystemService", Class::class.java)+ return m.invoke(context, mgrCls)+ }++ private fun buildCustomImageConfig(kernelPath: String, initrdPath: String): Any {+ val builderCls = Class.forName("$CLS_CUSTOM_CFG\$Builder")+ val ctor = builderCls.getDeclaredConstructor().apply { isAccessible = true }+ val builder = ctor.newInstance()+ invokeSetter(builderCls, builder, "setName", String::class.java, "podroid-avf-smoke")+ invokeSetter(builderCls, builder, "setKernelPath", String::class.java, kernelPath)+ invokeSetter(builderCls, builder, "setInitrdPath", String::class.java, initrdPath)+ runCatching {+ invokeSetter(builderCls, builder, "setParams", String::class.java, "console=hvc0 panic=1")+ }+ val buildM = builderCls.getDeclaredMethod("build").apply { isAccessible = true }+ return buildM.invoke(builder)+ }++ private fun buildVirtualMachineConfig(context: Context, customCfg: Any): Any {+ val builderCls = Class.forName("$CLS_CONFIG\$Builder")+ val ctor = builderCls.getDeclaredConstructor(Context::class.java).apply { isAccessible = true }+ val builder = ctor.newInstance(context)+ val customCfgCls = Class.forName(CLS_CUSTOM_CFG)+ invokeSetter(builderCls, builder, "setCustomImageConfig", customCfgCls, customCfg)+ runCatching {+ invokeSetter(builderCls, builder, "setProtectedVm",+ Boolean::class.javaPrimitiveType!!, false)+ }+ runCatching {+ invokeSetter(builderCls, builder, "setMemoryBytes",+ Long::class.javaPrimitiveType!!, 256L * 1024 * 1024)+ }+ val buildM = builderCls.getDeclaredMethod("build").apply { isAccessible = true }+ return buildM.invoke(builder)+ }++ private fun invokeSetter(cls: Class<*>, target: Any, name: String, argType: Class<*>, arg: Any?) {+ val m = cls.getDeclaredMethod(name, argType).apply { isAccessible = true }+ m.invoke(target, arg)+ }++ private fun invokeOrCreate(vmm: Any, name: String, config: Any): Any {+ val cfgCls = Class.forName(CLS_CONFIG)+ return runCatching {+ val m = vmm.javaClass.getDeclaredMethod("getOrCreate", String::class.java, cfgCls)+ .apply { isAccessible = true }+ m.invoke(vmm, name, config)+ }.getOrElse {+ val m = vmm.javaClass.getDeclaredMethod("create", String::class.java, cfgCls)+ .apply { isAccessible = true }+ m.invoke(vmm, name, config)+ } ?: error("getOrCreate returned null")+ }++ private fun deleteSafely(vmm: Any, name: String) {+ runCatching { vmm.javaClass.getMethod("delete", String::class.java).invoke(vmm, name) }+ }+}diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.ktnew file mode 100644index 0000000..92739c5--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt@@ -0,0 +1,378 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * AvfEngine — VmEngine implementation backed by Android Virtualization Framework.+ *+ * Uses AvfReflect for all android.system.virtualmachine.* calls so the APK+ * compiles against the public SDK. On devices without pKVM the start() call+ * lands in the catch branch and transitions to VmState.Error.+ *+ * Terminal wiring: ConsoleFanout bridges AVF console streams to a filesystem+ * unix socket; libpodroid-bridge connects to that socket and splices PTY ↔+ * socket, same as the QEMU path. The ctrl socket is a dummy path (never bound)+ * — bridge tolerates the connect failure gracefully (no resize on AVF, MVP).+ */+package com.excp.podroid.engine.avf++import android.content.Context+import android.util.Log+import com.excp.podroid.data.repository.PortForwardRule+import com.excp.podroid.data.repository.SettingsRepository+import com.excp.podroid.engine.BootStageDetector+import com.excp.podroid.engine.QmpClient+import com.excp.podroid.engine.VmConfig+import com.excp.podroid.engine.VmEngine+import com.excp.podroid.engine.VmState+import com.excp.podroid.util.LogProxy+import com.termux.terminal.TerminalSession+import com.termux.terminal.TerminalSessionClient+import dagger.hilt.android.qualifiers.ApplicationContext+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import java.io.File+import javax.inject.Inject+import javax.inject.Singleton++@Singleton+class AvfEngine @Inject constructor(+ @ApplicationContext private val context: Context,+ @Suppress("UnusedPrivateMember") private val settingsRepository: SettingsRepository,+) : VmEngine {++ companion object {+ private const val TAG = "AvfEngine"+ // Use "podroid" as the VM name. The smoke-test in AvfDiagnostics used+ // "podroid-avf-smoke" — a different name — so there is no config+ // conflict between the two paths.+ private const val VM_NAME = "podroid"+ }++ private val _state = MutableStateFlow<VmState>(VmState.Idle)+ override val state: StateFlow<VmState> = _state.asStateFlow()++ private val _bootStage = MutableStateFlow("")+ override val bootStage: StateFlow<String> = _bootStage.asStateFlow()++ private val _consoleText = MutableStateFlow("")+ override val consoleText: StateFlow<String> = _consoleText.asStateFlow()++ override var terminalSession: TerminalSession? = null+ private set++ override val backendId: String = "avf"++ /** AVF has no QMP socket; port forwarding is deferred to a future milestone. */+ override val qmpClient: QmpClient? = null++ override var sessionClientDelegate: TerminalSessionClient? = null++ private val proxySessionClient = object : TerminalSessionClient {+ override fun onTextChanged(s: TerminalSession) { sessionClientDelegate?.onTextChanged(s) }+ override fun onTitleChanged(s: TerminalSession) { sessionClientDelegate?.onTitleChanged(s) }+ override fun onSessionFinished(s: TerminalSession) { sessionClientDelegate?.onSessionFinished(s) }+ override fun onCopyTextToClipboard(s: TerminalSession, text: String?) { sessionClientDelegate?.onCopyTextToClipboard(s, text) }+ override fun onPasteTextFromClipboard(s: TerminalSession?) { sessionClientDelegate?.onPasteTextFromClipboard(s) }+ override fun onBell(s: TerminalSession) { sessionClientDelegate?.onBell(s) }+ override fun onColorsChanged(s: TerminalSession) { sessionClientDelegate?.onColorsChanged(s) }+ override fun onTerminalCursorStateChange(state: Boolean) { sessionClientDelegate?.onTerminalCursorStateChange(state) }+ override fun setTerminalShellPid(s: TerminalSession, pid: Int) { sessionClientDelegate?.setTerminalShellPid(s, pid) }+ override fun getTerminalCursorStyle(): Int = sessionClientDelegate?.terminalCursorStyle ?: 0+ override fun getTerminalVersionString(): String? = sessionClientDelegate?.terminalVersionString+ override fun logError(tag: String?, msg: String?) = LogProxy.error(tag, TAG, msg)+ override fun logWarn(tag: String?, msg: String?) = LogProxy.warn(tag, TAG, msg)+ override fun logInfo(tag: String?, msg: String?) = LogProxy.info(tag, TAG, msg)+ override fun logDebug(tag: String?, msg: String?) = LogProxy.debug(tag, TAG, msg)+ override fun logVerbose(tag: String?, msg: String?) = LogProxy.verbose(tag, TAG, msg)+ override fun logStackTraceWithMessage(tag: String?, msg: String?, e: Exception?) =+ LogProxy.stackTraceWithMessage(tag, TAG, msg, e)+ override fun logStackTrace(tag: String?, e: Exception?) = LogProxy.stackTrace(tag, TAG, e)+ }++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private var vmHandle: Any? = null+ private var consoleStream: java.io.InputStream? = null+ private var consoleStreamInput: java.io.OutputStream? = null+ private var fanout: ConsoleFanout? = null++ val terminalSockPath: String get() = "${context.filesDir.absolutePath}/avf-terminal.sock"+ val ctrlSockPath: String get() = "${context.filesDir.absolutePath}/avf-ctrl.sock"++ private val detector = BootStageDetector(_bootStage, _state) {+ Log.i(TAG, "boot Ready! detected — bridge connects via ConsoleFanout")+ // Wipe the boot log from the emulator so the user sees a clean login+ // prompt. AVF only exposes one captured console stream, so unlike+ // QEMU (separate serial.sock for boot) every kernel byte ends up in+ // the PTY scrollback by the time Open Terminal is tapped. ESC c =+ // RIS (full terminal reset); ESC [2J + ESC [H clears + homes the+ // cursor in case the emulator silently ignores RIS.+ val reset = byteArrayOf(0x1b, 'c'.code.toByte(),+ 0x1b, '['.code.toByte(), '2'.code.toByte(), 'J'.code.toByte(),+ 0x1b, '['.code.toByte(), 'H'.code.toByte())+ android.os.Handler(android.os.Looper.getMainLooper()).post {+ runCatching { terminalSession?.emulator?.append(reset, reset.size) }+ }+ }++ override suspend fun start(portForwards: List<PortForwardRule>, config: VmConfig) {+ if (_state.value is VmState.Running || _state.value is VmState.Starting) return+ if (portForwards.isNotEmpty()) {+ Log.w(TAG, "${portForwards.size} port-forward rule(s) requested — ignored on AVF (future milestone)")+ }+ _state.value = VmState.Starting+ _bootStage.value = "Initializing AVF..."+ // Re-arm the one-shot detector so a Stop → Start cycle's second boot+ // can fire onReady again. Without this the new boot's "Ready!" marker+ // is silently ignored and state stays Starting forever.+ detector.reset()++ try {+ val mgr = AvfReflect.manager(context)+ val vmConfigObj = buildConfig(config)++ // AOSP canonical pattern: get-or-create, then attempt to update the+ // config on the existing VM. If AVF rejects the new config as+ // incompatible (e.g. vmOutputCaptured changed from a stale record),+ // delete the old VM and create a fresh one.+ val vm: Any = run {+ val existing = AvfReflect.getOrCreate(mgr, VM_NAME, vmConfigObj)+ runCatching { AvfReflect.setConfig(existing, vmConfigObj) }.fold(+ onSuccess = { existing },+ onFailure = {+ Log.w(TAG, "stale VM config detected (${it.message}); deleting + recreating")+ AvfReflect.delete(mgr, VM_NAME)+ AvfReflect.create(mgr, VM_NAME, vmConfigObj)+ },+ )+ }+ vmHandle = vm++ val cb = AvfReflect.newVmCallback(+ onError = { code, msg ->+ Log.e(TAG, "VM onError code=$code msg=$msg")+ _state.value = VmState.Error("AVF onError($code): ${msg ?: "no message"}")+ },+ onStopped = { reason ->+ Log.i(TAG, "VM onStopped reason=$reason")+ if (_state.value is VmState.Running) {+ _state.value = VmState.Stopped+ } else if (_state.value is VmState.Starting) {+ // Stopped during boot — surface as error so the UI shows it.+ _state.value = VmState.Error("VM exited during boot (reason=$reason)")+ }+ },+ onDied = { reason ->+ Log.w(TAG, "VM onDied reason=$reason")+ },+ )+ AvfReflect.setCallback(vm, java.util.concurrent.ForkJoinPool.commonPool(), cb)++ val inStream = AvfReflect.consoleOutput(vm)+ val outStream = AvfReflect.consoleInput(vm)+ consoleStream = inStream+ consoleStreamInput = outStream++ // Fan out: VM ↔ filesystem socket. The bridge subprocess connects to+ // that socket and splices PTY ↔ socket. BootStageDetector tees the+ // VM output to drive boot-stage + state transitions.+ val fo = ConsoleFanout(+ consoleOutput = inStream,+ consoleInput = outStream,+ socketPath = terminalSockPath,+ detector = detector,+ scope = scope,+ )+ fanout = fo+ fo.start()++ AvfReflect.run(vm)+ val status = runCatching { AvfReflect.getStatus(vm) }.getOrDefault(-1)+ Log.i(TAG, "vm.run() returned — VM booting (status=$status)")+ spawnBridge()+ } catch (e: Throwable) {+ val cause = e.cause ?: e+ Log.e(TAG, "AVF start failed", cause)+ _state.value = VmState.Error("AVF rejected: ${cause.javaClass.simpleName}: ${cause.message}")+ cleanup()+ }+ }++ /**+ * Spawn libpodroid-bridge.so unconditionally at VM start, NOT on demand.+ * The fanout's accept() loops until the bridge connects; without an early+ * bridge spawn, the VM's console output is never drained and BootStageDetector+ * never sees "Ready!". This matches QemuEngine's autoStartBridge pattern but+ * with inverse timing (QEMU spawns AFTER ready; AVF spawns BEFORE ready).+ */+ private fun spawnBridge() {+ android.os.Handler(android.os.Looper.getMainLooper()).post {+ if (terminalSession != null) return@post+ val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")+ if (!bridgeExe.exists()) {+ Log.e(TAG, "bridge missing at ${bridgeExe.absolutePath}")+ return@post+ }+ val sess = TerminalSession(+ bridgeExe.absolutePath,+ context.filesDir.absolutePath,+ arrayOf(bridgeExe.absolutePath, terminalSockPath, ctrlSockPath),+ null,+ 2000,+ proxySessionClient,+ )+ sess.updateSize(80, 24, 0, 0)+ terminalSession = sess+ Log.d(TAG, "AVF bridge auto-spawned")+ }+ }++ override fun stop() {+ vmHandle?.let { AvfReflect.stop(it) }+ _state.value = VmState.Stopped+ cleanup()+ }++ override fun createTerminalSession(client: TerminalSessionClient): TerminalSession {+ sessionClientDelegate = client+ terminalSession?.let {+ Log.d(TAG, "Returning auto-spawned AVF terminal session")+ return it+ }+ // start() hasn't reached spawnBridge yet — spawn synchronously as fallback.+ // (Should be rare: caller opens Terminal before VM start completes.)+ Log.w(TAG, "createTerminalSession called before bridge auto-spawn; spawning now")+ val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")+ if (!bridgeExe.exists()) {+ throw IllegalStateException("podroid-bridge not found at ${bridgeExe.absolutePath}")+ }+ val sess = TerminalSession(+ bridgeExe.absolutePath,+ context.filesDir.absolutePath,+ arrayOf(bridgeExe.absolutePath, terminalSockPath, ctrlSockPath),+ null,+ 2000,+ proxySessionClient,+ )+ sess.updateSize(80, 24, 0, 0)+ terminalSession = sess+ return sess+ }++ private fun cleanup() {+ // Close fanout first — drains its coroutines and closes the streams inside.+ runCatching { fanout?.close() }+ fanout = null+ runCatching { consoleStreamInput?.close() }+ consoleStreamInput = null+ runCatching { consoleStream?.close() }+ consoleStream = null+ // Tear down the old terminal session so the next start()'s spawnBridge+ // doesn't short-circuit on the stale reference and leave the fanout's+ // accept() blocked forever (visible as "stuck at Initializing AVF...").+ runCatching { terminalSession?.finishIfRunning() }+ terminalSession = null+ vmHandle = null+ }++ /**+ * Creates (or resizes) the persistent storage disk. Mirrors QemuEngine's+ * helper exactly so a VM can boot under either backend with the same+ * disk identity. The file is sparse — the actual disk allocation grows+ * as the guest writes blocks. Alpine's init formats it ext4 on first+ * boot via the standard initramfs path.+ */+ private fun ensureStorageImage(storageSizeGb: Int): File {+ val storageFile = File(context.filesDir, "storage.img")+ val desiredBytes = storageSizeGb.toLong() * 1024L * 1024L * 1024L+ if (storageFile.exists() && storageFile.length() == desiredBytes) return storageFile+ if (storageFile.exists()) {+ Log.d(TAG, "storage.img size mismatch — recreating")+ storageFile.delete()+ }+ try {+ java.io.RandomAccessFile(storageFile, "rw").use { it.setLength(desiredBytes) }+ Log.d(TAG, "Created storage.img (${storageSizeGb}GB)")+ } catch (e: Exception) {+ Log.e(TAG, "Failed to create storage.img", e)+ }+ return storageFile+ }++ /**+ * crosvm requires the raw ARM64 Image (magic `ARM\x64` at offset 0x38), not+ * the gzip-compressed `vmlinuz` that QEMU happily auto-decompresses. We+ * gunzip on-demand to a sibling .raw file and feed THAT to AVF.+ *+ * Skips decompression if the .raw file's mtime is newer than the source.+ * Returns the decompressed file (or the source if already raw).+ */+ private fun ensureRawKernel(source: File): File {+ val magic = ByteArray(4)+ source.inputStream().use { it.read(magic) }+ val isGzip = magic[0] == 0x1f.toByte() && magic[1] == 0x8b.toByte()+ if (!isGzip) return source++ val raw = File(source.parentFile, "${source.name}.raw")+ if (raw.exists() && raw.lastModified() >= source.lastModified()) return raw++ Log.d(TAG, "Decompressing ${source.name} → ${raw.name}")+ java.util.zip.GZIPInputStream(source.inputStream().buffered()).use { gz ->+ raw.outputStream().buffered().use { out -> gz.copyTo(out) }+ }+ raw.setLastModified(System.currentTimeMillis())+ return raw+ }++ private fun buildConfig(config: VmConfig): Any {+ val kernelSrc = File(context.filesDir, "vmlinuz-virt").also {+ require(it.exists()) { "kernel missing at ${it.absolutePath}" }+ }+ val kernel = ensureRawKernel(kernelSrc)+ val initrd = File(context.filesDir, "initrd.img").also {+ require(it.exists()) { "initrd missing at ${it.absolutePath}" }+ }+ val storage = ensureStorageImage(config.storageSizeGb)+ val squashfs = File(context.filesDir, "alpine-rootfs.squashfs").also {+ require(it.exists()) { "rootfs missing at ${it.absolutePath}" }+ }++ val cb = AvfReflect.newCustomBuilder()+ AvfReflect.setName(cb, VM_NAME)+ AvfReflect.setKernelPath(cb, kernel.absolutePath)+ AvfReflect.setInitrdPath(cb, initrd.absolutePath)+ // AVF picks the console device via setConsoleInputDevice on the outer+ // builder; the kernel discovers it through DT/ACPI tables crosvm sets up.+ // Don't pass `console=` here — it'll fight AVF's choice.+ // `podroid.tty=ttyS0` tells /usr/local/bin/podroid-getty to spawn+ // the login on PL011 serial (AVF's only console with an input fd).+ // The hvc0 getty becomes a no-op sleeper instead of dual-printing.+ //+ // `podroid.epoch=...` seeds the guest's wall clock from the host —+ // AVF doesn't wire an emulated RTC like QEMU TCG does, so without+ // this the VM boots at 1970-01-01 and TLS fails on every cert.+ val epoch = System.currentTimeMillis() / 1000+ AvfReflect.addParams(cb,+ "root=/dev/ram0 mitigations=off elevator=mq-deadline podroid.tty=ttyS0 podroid.epoch=$epoch ${config.kernelExtraCmdline}".trim()+ )+ AvfReflect.addDisk(cb, storage.absolutePath, writable = true)+ AvfReflect.addDisk(cb, squashfs.absolutePath, writable = false)+ AvfReflect.setNetworkSupported(cb, true)+ val customCfg = AvfReflect.build(cb)++ val vb = AvfReflect.newVmConfigBuilder(context)+ AvfReflect.setProtectedVm(vb, false)+ AvfReflect.setMemoryBytes(vb, config.ramMb.toLong() * 1024 * 1024)+ AvfReflect.setNumCpus(vb, config.cpus)+ AvfReflect.setDebugLevel(vb, AvfReflect.DEBUG_LEVEL_FULL)+ AvfReflect.setConsoleInputDevice(vb, "ttyS0") // AVF expects ttyS0+ AvfReflect.setConnectVmConsole(vb, false) // false: avoid inheriting Activity FDs (SurfaceFlinger sync fences → SELinux denial)+ AvfReflect.setVmOutputCaptured(vb, true)+ AvfReflect.setVmConsoleInputSupported(vb, true)+ AvfReflect.setCustomImageConfig(vb, customCfg)+ return AvfReflect.build(vb)+ }+}diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.ktnew file mode 100644index 0000000..de5add7--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt@@ -0,0 +1,218 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * Thin reflective wrappers over android.system.virtualmachine.*. Each call is+ * one Method.invoke with setAccessible(true) — Android 14+ requires+ * HiddenApiBypass (installed at app onCreate) for these to resolve.+ *+ * Returning `Any` keeps the call sites untyped at the framework boundary;+ * call sites pass these handles back into AvfReflect rather than poking at+ * the underlying objects directly.+ */+package com.excp.podroid.engine.avf++import android.content.Context+import java.lang.reflect.InvocationHandler+import java.lang.reflect.Method+import java.lang.reflect.Proxy+import java.util.concurrent.Executor++object AvfReflect {++ private const val PKG = "android.system.virtualmachine"+ private val MGR by lazy { Class.forName("$PKG.VirtualMachineManager") }+ private val CFG by lazy { Class.forName("$PKG.VirtualMachineConfig") }+ private val CFG_B by lazy { Class.forName("$PKG.VirtualMachineConfig\$Builder") }+ private val CUSTOM by lazy { Class.forName("$PKG.VirtualMachineCustomImageConfig") }+ private val CUSTOM_B by lazy { Class.forName("$PKG.VirtualMachineCustomImageConfig\$Builder") }+ private val DISK by lazy { runCatching { Class.forName("$PKG.VirtualMachineCustomImageConfig\$Disk") }.getOrNull() }++ fun manager(ctx: Context): Any {+ val m = Context::class.java.getMethod("getSystemService", Class::class.java)+ return m.invoke(ctx.applicationContext, MGR) ?: error("No VirtualMachineManager")+ }++ fun getOrCreate(mgr: Any, name: String, cfg: Any): Any =+ invokeDecl(mgr, "getOrCreate", String::class.java to name, CFG to cfg)+ ?: error("getOrCreate returned null")++ fun create(mgr: Any, name: String, cfg: Any): Any =+ invokeDecl(mgr, "create", String::class.java to name, CFG to cfg)+ ?: error("create returned null")++ /**+ * Attempts to replace an existing VM's config (analogous to `vm.config = config` in Kotlin).+ * Throws if AVF rejects the new config as incompatible — caller should+ * delete + recreate on that path.+ */+ fun setConfig(vm: Any, cfg: Any) {+ val m = vm.javaClass.getDeclaredMethod("setConfig", CFG).apply { isAccessible = true }+ m.invoke(vm, cfg)+ }++ fun delete(mgr: Any, name: String) {+ runCatching { invokeDecl(mgr, "delete", String::class.java to name) }+ }++ fun newVmConfigBuilder(ctx: Context): Any =+ CFG_B.getDeclaredConstructor(Context::class.java).apply { isAccessible = true }+ .newInstance(ctx)++ fun setProtectedVm(b: Any, value: Boolean) {+ invokeDecl(b, "setProtectedVm", Boolean::class.javaPrimitiveType!! to value)+ }++ fun setMemoryBytes(b: Any, bytes: Long) {+ invokeDecl(b, "setMemoryBytes", Long::class.javaPrimitiveType!! to bytes)+ }++ /** CPU topology values matching VirtualMachineConfig.CPU_TOPOLOGY_*. */+ const val CPU_TOPOLOGY_ONE_CPU: Int = 0+ const val CPU_TOPOLOGY_MATCH_HOST: Int = 1++ fun setNumCpus(b: Any, n: Int) {+ // AVF's setCpuTopology takes a CPU_TOPOLOGY_* constant — only 0 (one+ // CPU) or 1 (all host cores) are accepted. There is no fine-grained+ // count setter on the public AVF API. Map the user's requested count:+ // 1 → ONE_CPU; anything > 1 → MATCH_HOST (= all host cores).+ val topology = if (n <= 1) CPU_TOPOLOGY_ONE_CPU else CPU_TOPOLOGY_MATCH_HOST+ if (n > 1) android.util.Log.d(+ "AvfReflect",+ "AVF can't allocate a specific count of vCPUs; user requested $n → MATCH_HOST (all host cores)",+ )+ invokeDecl(b, "setCpuTopology", Int::class.javaPrimitiveType!! to topology)+ }++ fun setConsoleInputDevice(b: Any, device: String) {+ invokeDecl(b, "setConsoleInputDevice", String::class.java to device)+ }++ fun setConnectVmConsole(b: Any, value: Boolean) {+ invokeDecl(b, "setConnectVmConsole", Boolean::class.javaPrimitiveType!! to value)+ }++ fun setVmOutputCaptured(b: Any, value: Boolean) {+ invokeDecl(b, "setVmOutputCaptured", Boolean::class.javaPrimitiveType!! to value)+ }++ /**+ * AVF debug levels: NONE=0, FULL=1. Console input requires FULL.+ * Constant integer (not a reflective field read) since it's stable in the+ * public SystemApi.+ */+ const val DEBUG_LEVEL_FULL: Int = 1++ fun setDebugLevel(b: Any, level: Int) {+ invokeDecl(b, "setDebugLevel", Int::class.javaPrimitiveType!! to level)+ }++ fun setVmConsoleInputSupported(b: Any, value: Boolean) {+ // Older API revisions may not have this; tolerate absence.+ runCatching {+ invokeDecl(b, "setVmConsoleInputSupported", Boolean::class.javaPrimitiveType!! to value)+ }+ }++ fun setCustomImageConfig(b: Any, cfg: Any) {+ invokeDecl(b, "setCustomImageConfig", CUSTOM to cfg)+ }++ fun build(b: Any): Any = invokeDecl(b, "build")!!++ fun newCustomBuilder(): Any =+ CUSTOM_B.getDeclaredConstructor().apply { isAccessible = true }.newInstance()++ fun setName(b: Any, name: String) { invokeDecl(b, "setName", String::class.java to name) }+ fun setKernelPath(b: Any, p: String) { invokeDecl(b, "setKernelPath", String::class.java to p) }+ fun setInitrdPath(b: Any, p: String) { invokeDecl(b, "setInitrdPath", String::class.java to p) }+ /** Adds each whitespace-separated token of [params] via addParam(String). */+ fun addParams(b: Any, params: String) {+ val tokens = params.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }+ val m = b.javaClass.getDeclaredMethod("addParam", String::class.java)+ .apply { isAccessible = true }+ for (t in tokens) m.invoke(b, t)+ }++ fun addDisk(b: Any, path: String, writable: Boolean) {+ val diskCls = DISK ?: error("VirtualMachineCustomImageConfig\$Disk class not found on this device")+ val factoryName = if (writable) "RWDisk" else "RODisk"+ val factory = diskCls.getDeclaredMethod(factoryName, String::class.java)+ .apply { isAccessible = true }+ val disk = factory.invoke(null, path)+ ?: error("Disk.$factoryName($path) returned null")+ val addM = b.javaClass.getDeclaredMethod("addDisk", diskCls).apply { isAccessible = true }+ addM.invoke(b, disk)+ }++ fun setNetworkSupported(b: Any, value: Boolean) {+ val ok = runCatching { invokeDecl(b, "useNetwork", Boolean::class.javaPrimitiveType!! to value) }.isSuccess+ || runCatching { invokeDecl(b, "setNetworkSupported", Boolean::class.javaPrimitiveType!! to value) }.isSuccess+ if (!ok) android.util.Log.w("AvfReflect", "no useNetwork/setNetworkSupported on this AVF API; VM may have no network")+ }++ /**+ * Builds a Proxy of `android.system.virtualmachine.VirtualMachineCallback`.+ * The Java interface can't be implemented directly because it's @SystemApi+ * and we don't compile against the stubs.+ *+ * @param onError invoked when the VM hits a runtime error. Args: errorCode (Int), message (String?).+ * @param onStopped invoked when the VM exits cleanly. Arg: reason (Int).+ * @param onDied invoked for backend-level termination. Arg: reason (Int).+ */+ fun newVmCallback(+ onError: (Int, String?) -> Unit,+ onStopped: (Int) -> Unit,+ onDied: (Int) -> Unit,+ ): Any {+ val cls = Class.forName("$PKG.VirtualMachineCallback")+ val handler = InvocationHandler { _, method: Method, args: Array<Any?>? ->+ when (method.name) {+ "onError" -> {+ // signature: onError(VirtualMachine vm, int errorCode, String message)+ val code = args?.getOrNull(1) as? Int ?: -1+ val msg = args?.getOrNull(2) as? String+ onError(code, msg)+ }+ "onStopped" -> {+ val reason = args?.getOrNull(1) as? Int ?: -1+ onStopped(reason)+ }+ "onDied" -> {+ // some API revisions: onDied(VirtualMachine vm, int reason); others: onDied(int cid, int reason)+ val reason = args?.getOrNull((args.size - 1).coerceAtLeast(0)) as? Int ?: -1+ onDied(reason)+ }+ else -> Unit // ignore onPayload* — those are Microdroid-only+ }+ null+ }+ return Proxy.newProxyInstance(cls.classLoader, arrayOf(cls), handler)+ }++ fun setCallback(vm: Any, executor: Executor, callback: Any) {+ val cbCls = Class.forName("$PKG.VirtualMachineCallback")+ val m = vm.javaClass.getDeclaredMethod("setCallback", Executor::class.java, cbCls)+ .apply { isAccessible = true }+ m.invoke(vm, executor, callback)+ }++ fun getStatus(vm: Any): Int =+ invokeDecl(vm, "getStatus") as Int++ fun run(vm: Any) { invokeDecl(vm, "run") }+ fun stop(vm: Any) { runCatching { invokeDecl(vm, "stop") } }++ fun consoleOutput(vm: Any): java.io.InputStream =+ invokeDecl(vm, "getConsoleOutput") as java.io.InputStream++ fun consoleInput(vm: Any): java.io.OutputStream =+ invokeDecl(vm, "getConsoleInput") as java.io.OutputStream++ private fun invokeDecl(target: Any, name: String, vararg typedArgs: Pair<Class<*>, Any?>): Any? {+ val argTypes = typedArgs.map { it.first }.toTypedArray()+ val argVals = typedArgs.map { it.second }.toTypedArray()+ val m = target.javaClass.getDeclaredMethod(name, *argTypes).apply { isAccessible = true }+ return m.invoke(target, *argVals)+ }+}diff --git a/app/src/main/java/com/excp/podroid/engine/avf/ConsoleFanout.kt b/app/src/main/java/com/excp/podroid/engine/avf/ConsoleFanout.ktnew file mode 100644index 0000000..aba005e--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/avf/ConsoleFanout.kt@@ -0,0 +1,123 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ */+package com.excp.podroid.engine.avf++import android.annotation.SuppressLint+import android.os.Build+import android.system.Os+import android.system.OsConstants+import android.util.Log+import androidx.annotation.RequiresApi+import com.excp.podroid.engine.BootStageDetector+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import java.io.File+import java.io.FileDescriptor+import java.io.InputStream+import java.io.OutputStream++/**+ * Bridges AVF's console streams ↔ a filesystem unix-domain socket so the+ * existing `libpodroid-bridge.so` subprocess can splice PTY ↔ that socket+ * unchanged. Uses `android.system.Os` directly because Android 14's+ * ServerSocketChannel doesn't expose the ProtocolFamily factory needed for+ * NIO unix sockets, but Os.bind() accepts UnixDomainSocketAddress.+ *+ * AVF requires Android 14+ (Pixel 8+) so the @RequiresApi(34) on this class+ * is never violated at runtime — AvfEngine only constructs ConsoleFanout+ * when AvfDiagnostics says the framework is available.+ */+@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)+class ConsoleFanout(+ private val consoleOutput: InputStream,+ private val consoleInput: OutputStream,+ private val socketPath: String,+ private val detector: BootStageDetector,+ private val scope: CoroutineScope,+) {+ companion object { private const val TAG = "ConsoleFanout" }++ private var serverFd: FileDescriptor? = null+ private var clientFd: FileDescriptor? = null+ private val jobs = mutableListOf<Job>()+ @Volatile private var closed = false++ @SuppressLint("BlockedPrivateApi") // android.system.UnixSocketAddress is exempt via HiddenApiBypass+ fun start() {+ File(socketPath).delete() // stale socket blocks bind++ val fd = Os.socket(OsConstants.AF_UNIX, OsConstants.SOCK_STREAM, 0)+ val addrCls = Class.forName("android.system.UnixSocketAddress")+ val addr = addrCls.getDeclaredMethod("createFileSystem", String::class.java)+ .apply { isAccessible = true }+ .invoke(null, socketPath) as java.net.SocketAddress+ Os.bind(fd, addr)+ Os.listen(fd, 1)+ serverFd = fd++ jobs += scope.launch(Dispatchers.IO) {+ try {+ val client = Os.accept(fd, null /* peerAddress out-param */)+ Log.d(TAG, "bridge connected at $socketPath")+ clientFd = client+ startPumps(client)+ } catch (e: Exception) {+ if (!closed) Log.w(TAG, "accept failed: ${e.message}")+ }+ }+ }++ private fun startPumps(client: FileDescriptor) {+ // VM → (boot detector + bridge socket)+ jobs += scope.launch(Dispatchers.IO) {+ val buf = ByteArray(8192)+ try {+ while (true) {+ val n = consoleOutput.read(buf)+ if (n <= 0) break+ detector.feed(buf, n)+ var off = 0+ while (off < n) {+ val w = Os.write(client, buf, off, n - off)+ if (w <= 0) break+ off += w+ }+ }+ } catch (e: Exception) {+ if (!closed) Log.d(TAG, "vm→bridge pump ended: ${e.message}")+ } finally { close() }+ }++ // Bridge socket → VM+ jobs += scope.launch(Dispatchers.IO) {+ val buf = ByteArray(8192)+ try {+ while (true) {+ val n = Os.read(client, buf, 0, buf.size)+ if (n <= 0) break+ consoleInput.write(buf, 0, n)+ consoleInput.flush()+ }+ } catch (e: Exception) {+ if (!closed) Log.d(TAG, "bridge→vm pump ended: ${e.message}")+ } finally { close() }+ }+ }++ @Synchronized+ fun close() {+ if (closed) return+ closed = true+ jobs.forEach { runCatching { it.cancel() } }+ jobs.clear()+ runCatching { clientFd?.let { Os.close(it) } }+ runCatching { serverFd?.let { Os.close(it) } }+ runCatching { consoleOutput.close() }+ runCatching { consoleInput.close() }+ runCatching { File(socketPath).delete() }+ }+}diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.ktindex 287485c..3ba004d 100644--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt@@ -26,7 +26,8 @@ import com.excp.podroid.MainActivityimport com.excp.podroid.Rimport com.excp.podroid.data.repository.PortForwardRepositoryimport com.excp.podroid.data.repository.SettingsRepository-import com.excp.podroid.engine.PodroidQemu+import com.excp.podroid.engine.VmConfig+import com.excp.podroid.engine.VmEngineimport com.excp.podroid.engine.VmStateimport com.excp.podroid.util.NetworkUtilsimport com.excp.podroid.x11.X11Constants@@ -38,7 +39,7 @@ import javax.inject.Inject@AndroidEntryPointclass PodroidService : Service() {- @Inject lateinit var podroidQemu: PodroidQemu+ @Inject lateinit var engine: VmEngine@Inject lateinit var portForwardRepository: PortForwardRepository@Inject lateinit var settingsRepository: SettingsRepository@@ -78,7 +79,7 @@ class PodroidService : Service() {launchPodroid()}ACTION_STOP -> {- podroidQemu.stop()+ engine.stop()}}return START_NOT_STICKY@@ -94,9 +95,9 @@ class PodroidService : Service() {override fun onTaskRemoved(rootIntent: Intent?) {super.onTaskRemoved(rootIntent)// App swiped from recents — stop the VM gracefully- if (podroidQemu.state.value is VmState.Running ||- podroidQemu.state.value is VmState.Starting) {- podroidQemu.stop()+ if (engine.state.value is VmState.Running ||+ engine.state.value is VmState.Starting) {+ engine.stop()}}@@ -134,7 +135,7 @@ class PodroidService : Service() {/** Updates the notification text from a combined view of state + bootStage. */private suspend fun observeStateForNotification() {- combine(podroidQemu.state, podroidQemu.bootStage) { state, stage -> state to stage }+ combine(engine.state, engine.bootStage) { state, stage -> state to stage }.collect { (state, stage) ->when (state) {is VmState.Running -> updateNotification("VM is running")@@ -151,7 +152,7 @@ class PodroidService : Service() {*/private suspend fun observeStateForShutdown() {var seenActive = false- podroidQemu.state.collect { state ->+ engine.state.collect { state ->when (state) {is VmState.Starting, is VmState.Running -> seenActive = trueis VmState.Stopped, is VmState.Idle, is VmState.Error -> {@@ -190,7 +191,7 @@ class PodroidService : Service() {rules.add(com.excp.podroid.data.repository.PortForwardRule(X11Constants.AUDIO_PORT, X11Constants.AUDIO_PORT, "tcp"))}- val config = com.excp.podroid.engine.PodroidQemu.LaunchConfig(+ val config = VmConfig(ramMb = settingsRepository.getVmRamMbSnapshot(),cpus = settingsRepository.getVmCpusSnapshot(),sshEnabled = sshEnabled,@@ -200,7 +201,7 @@ class PodroidService : Service() {qemuExtraArgs = settingsRepository.getQemuExtraArgsSnapshot(),kernelExtraCmdline = settingsRepository.getKernelExtraCmdlineSnapshot(),)- podroidQemu.start(rules, config)+ engine.start(rules, config)} catch (e: Exception) {Log.e(TAG, "QEMU failed to start", e)}diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.ktindex cf61d9f..a67864f 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt@@ -16,6 +16,8 @@ import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Settingsimport androidx.compose.material.icons.filled.SystemUpdateimport androidx.compose.material3.AlertDialog+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaultsimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButton@@ -30,6 +32,7 @@ import androidx.compose.runtime.getValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.unit.dpimport androidx.hilt.lifecycle.viewmodel.compose.hiltViewModelimport androidx.lifecycle.compose.collectAsStateWithLifecycle@@ -60,6 +63,7 @@ fun HomeScreen(val updateInfo by viewModel.updateInfo.collectAsStateWithLifecycle()val meta by viewModel.meta.collectAsStateWithLifecycle()val uptimeTick by viewModel.uptimeTicker.collectAsStateWithLifecycle()+ val showAvfHint by viewModel.showAvfHint.collectAsStateWithLifecycle()val isRunning = vmState is VmState.Runningval isStarting = vmState is VmState.Starting@@ -119,6 +123,9 @@ fun HomeScreen(.padding(end = PodroidTokens.Spacing.XL2).verticalScroll(rememberScrollState()),) {+ if (showAvfHint) {+ AvfHintBanner(onDismiss = { viewModel.dismissAvfHint() })+ }HomeStatusBlock(isStarting, isRunning, vmState, bootStage, meta, uptimeLabel)HomeDataSection(isRunning, vmState, meta, phoneIp)}@@ -148,6 +155,9 @@ fun HomeScreen(verticalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.MD),) {Spacer(Modifier.height(PodroidTokens.Spacing.XL))+ if (showAvfHint) {+ AvfHintBanner(onDismiss = { viewModel.dismissAvfHint() })+ }HomeStatusBlock(isStarting, isRunning, vmState, bootStage, meta, uptimeLabel)HomeDataSection(isRunning, vmState, meta, phoneIp)Spacer(Modifier.weight(1f))@@ -167,6 +177,49 @@ fun HomeScreen(}}+@Composable+private fun AvfHintBanner(onDismiss: () -> Unit) {+ Card(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = PodroidTokens.Spacing.MD),+ colors = CardDefaults.cardColors(+ containerColor = MaterialTheme.colorScheme.surfaceVariant,+ ),+ ) {+ Column(+ modifier = Modifier.padding(PodroidTokens.Spacing.MD),+ verticalArrangement = Arrangement.spacedBy(PodroidTokens.Spacing.SM),+ ) {+ Text(+ "AVF (KVM) available on this device",+ style = MaterialTheme.typography.titleSmall,+ )+ Text(+ "Run these once to unlock hardware acceleration:",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Text(+ text = "adb shell pm grant com.excp.podroid \\\n" ++ " android.permission.MANAGE_VIRTUAL_MACHINE\n" ++ "adb shell pm grant com.excp.podroid \\\n" ++ " android.permission.USE_CUSTOM_VIRTUAL_MACHINE",+ fontFamily = FontFamily.Monospace,+ style = MaterialTheme.typography.bodySmall,+ )+ Row(+ horizontalArrangement = Arrangement.End,+ modifier = Modifier.fillMaxWidth(),+ ) {+ TextButton(onClick = onDismiss) {+ Text("Dismiss")+ }+ }+ }+ }+}+@Composableprivate fun HomeStatusBlock(isStarting: Boolean,diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.ktindex a32e9c0..a958654 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt@@ -8,7 +8,7 @@ import com.excp.podroid.data.repository.PortForwardRepositoryimport com.excp.podroid.data.repository.SettingsRepositoryimport com.excp.podroid.data.repository.UpdateInfoimport com.excp.podroid.data.repository.UpdateRepository-import com.excp.podroid.engine.PodroidQemu+import com.excp.podroid.engine.VmEngineimport com.excp.podroid.engine.VmStateimport com.excp.podroid.service.PodroidServiceimport com.excp.podroid.util.NetworkUtils@@ -51,16 +51,16 @@ data class HomeMeta(@HiltViewModelclass HomeViewModel @Inject constructor(@ApplicationContext private val context: Context,- private val podroidQemu: PodroidQemu,+ private val engine: VmEngine,private val settingsRepository: SettingsRepository,private val portForwardRepository: PortForwardRepository,private val updateRepository: UpdateRepository,) : ViewModel() {- val vmState: StateFlow<VmState> = podroidQemu.state+ val vmState: StateFlow<VmState> = engine.state.stateIn(viewModelScope, SharingStarted.Eagerly, VmState.Idle)- val bootStage: StateFlow<String> = podroidQemu.bootStage+ val bootStage: StateFlow<String> = engine.bootStage.stateIn(viewModelScope, SharingStarted.Eagerly, "")/** Aggregated metadata for the Home data sections. */@@ -102,6 +102,23 @@ class HomeViewModel @Inject constructor(private val _updateInfo = MutableStateFlow<UpdateInfo?>(null)val updateInfo: StateFlow<UpdateInfo?> = _updateInfo.asStateFlow()+ /**+ * True when AVF (pKVM) is present on this device but neither+ * MANAGE_VIRTUAL_MACHINE nor USE_CUSTOM_VIRTUAL_MACHINE have been granted+ * yet — and the user hasn't dismissed the banner.+ *+ * The AVF probe is fast (no IPC, no binder), so we derive it via a+ * simple map on the dismissed flow rather than a heavy combine.+ */+ private val _avfProbe = com.excp.podroid.engine.avf.AvfDiagnostics.probe(context)+ val showAvfHint: StateFlow<Boolean> = settingsRepository.avfHintDismissed+ .map { dismissed ->+ _avfProbe.featureSupported &&+ !_avfProbe.managePermissionGranted &&+ !dismissed+ }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)+private var runningSinceMs: Long? = nullinit {@@ -109,7 +126,7 @@ class HomeViewModel @Inject constructor(// Maintain runningSinceMs for the synchronous read path used by uptime formatter.viewModelScope.launch {var lastWasRunning = false- podroidQemu.state.collect { state ->+ engine.state.collect { state ->val nowRunning = state is VmState.Runningif (nowRunning && !lastWasRunning) runningSinceMs = System.currentTimeMillis()if (!nowRunning) runningSinceMs = null@@ -149,6 +166,10 @@ class HomeViewModel @Inject constructor(viewModelScope.launch { updateRepository.dismissUpdate(version) }}+ fun dismissAvfHint() {+ viewModelScope.launch { settingsRepository.setAvfHintDismissed(true) }+ }+fun startPodroid() = PodroidService.start(context)fun stopVm() = PodroidService.stop(context)@@ -157,7 +178,7 @@ class HomeViewModel @Inject constructor(PodroidService.stop(context)viewModelScope.launch {withTimeoutOrNull(10_000) {- podroidQemu.state.first { state ->+ engine.state.first { state ->state is VmState.Stopped || state is VmState.Idle || state is VmState.Error}}diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.ktindex 0b9ddc6..b7a1c91 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt@@ -56,7 +56,13 @@ import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModelimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport com.excp.podroid.BuildConfigimport com.excp.podroid.data.repository.PortForwardRule+import com.excp.podroid.engine.EngineSelectionimport com.excp.podroid.engine.VmState+import com.excp.podroid.engine.avf.AvfDiagnostics+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import androidx.compose.runtime.rememberCoroutineScope+import kotlinx.coroutines.withContextimport com.excp.podroid.ui.components.AdaptiveContainerimport com.excp.podroid.ui.components.PodroidDestructiveButtonimport com.excp.podroid.ui.components.PodroidGhostButton@@ -83,6 +89,10 @@ fun SettingsScreen(var advancedExpanded by remember { mutableStateOf(false) }var showAddDialog by remember { mutableStateOf(false) }var showResetDialog by remember { mutableStateOf(false) }+ var avfReportText by remember { mutableStateOf<String?>(null) }+ var avfRunning by remember { mutableStateOf(false) }+ val avfScope = rememberCoroutineScope()+ val ctx = LocalContext.currentval vmNotRunning = vmState !is VmState.Running && vmState !is VmState.StartingScaffold(@@ -208,6 +218,33 @@ fun SettingsScreen(onClick = { advancedExpanded = !advancedExpanded },)if (advancedExpanded) {+ PodroidSectionLabel("Backend")+ Spacer(Modifier.height(PodroidTokens.Spacing.SM))+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.padding(horizontal = PodroidTokens.Spacing.MD),+ ) {+ EngineSelection.entries.forEach { sel ->+ FilterChip(+ selected = ui.engineSelection == sel,+ onClick = { viewModel.setEngineSelection(sel) },+ enabled = vmNotRunning,+ label = {+ Text(+ when (sel) {+ EngineSelection.AUTO -> "Auto"+ EngineSelection.AVF -> "AVF (KVM)"+ EngineSelection.QEMU -> "QEMU (TCG)"+ },+ fontFamily = FontFamily.Monospace,+ )+ },+ shape = RoundedCornerShape(PodroidTokens.Radius.Chip),+ colors = PodroidChipColors(),+ )+ }+ }+ Spacer(Modifier.height(PodroidTokens.Spacing.MD))AdvancedFieldsBlock(qemuExtraArgs = ui.qemuExtraArgs,kernelExtraCmdline = ui.kernelExtraCmdline,@@ -230,6 +267,26 @@ fun SettingsScreen(text = "Export diagnostic log",onClick = { viewModel.exportConsoleLogs() },)+ Spacer(Modifier.height(PodroidTokens.Spacing.SM))+ PodroidGhostButton(+ text = if (avfRunning) "Running AVF diagnostic…" else "AVF (pKVM) diagnostic",+ onClick = {+ if (avfRunning) return@PodroidGhostButton+ avfRunning = true+ avfReportText = "Probing…"+ avfScope.launch {+ val probe = AvfDiagnostics.probe(ctx)+ val smoke = if (probe.featureSupported && probe.managePermissionGranted) {+ withContext(Dispatchers.IO) { AvfDiagnostics.runSmokeTest(ctx) }+ } else null+ avfReportText = probe.copy(+ smokeTestResult = smoke,+ activeBackend = viewModel.activeBackendId(),+ ).pretty()+ avfRunning = false+ }+ },+ )Spacer(Modifier.height(PodroidTokens.Spacing.XL2))}@@ -246,6 +303,23 @@ fun SettingsScreen()}+ avfReportText?.let { report ->+ AlertDialog(+ onDismissRequest = { avfReportText = null },+ title = { Text("AVF (pKVM) diagnostic") },+ text = {+ Text(+ text = report,+ fontFamily = FontFamily.Monospace,+ style = MaterialTheme.typography.bodySmall,+ )+ },+ confirmButton = {+ TextButton(onClick = { avfReportText = null }) { Text("Close") }+ },+ )+ }+if (showResetDialog) {AlertDialog(onDismissRequest = { showResetDialog = false },diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.ktindex fd56fe1..465bfb1 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt@@ -17,7 +17,8 @@ import com.excp.podroid.BuildConfigimport com.excp.podroid.data.repository.PortForwardRepositoryimport com.excp.podroid.data.repository.PortForwardRuleimport com.excp.podroid.data.repository.SettingsRepository-import com.excp.podroid.engine.PodroidQemu+import com.excp.podroid.engine.EngineSelection+import com.excp.podroid.engine.VmEngineimport com.excp.podroid.engine.VmStateimport com.excp.podroid.util.NetworkUtilsimport dagger.hilt.android.lifecycle.HiltViewModel@@ -52,6 +53,7 @@ data class SettingsUiState(val kernelExtraCmdline: String = SettingsRepository.DEFAULT_KERNEL_EXTRA_CMDLINE,val darkTheme: Boolean = false,val dynamicColorEnabled: Boolean = false,+ val engineSelection: EngineSelection = EngineSelection.AUTO,)@HiltViewModel@@ -59,7 +61,7 @@ class SettingsViewModel @Inject constructor(@ApplicationContext private val context: Context,private val settingsRepository: SettingsRepository,private val portForwardRepository: PortForwardRepository,- private val podroidQemu: PodroidQemu,+ private val engine: VmEngine,) : ViewModel() {val vmRamMb: StateFlow<Int> = settingsRepository.vmRamMb@@ -99,7 +101,8 @@ class SettingsViewModel @Inject constructor() { storageAccess, qemu, kernel, dark, dyn ->arrayOf(storageAccess, qemu, kernel, dark, dyn)},- ) { a, b ->+ settingsRepository.engineSelection,+ ) { a, b, engineSel ->SettingsUiState(vmRamMb = a[0] as Int,vmCpus = a[1] as Int,@@ -110,6 +113,7 @@ class SettingsViewModel @Inject constructor(kernelExtraCmdline = b[2] as String,darkTheme = b[3] as Boolean,dynamicColorEnabled = b[4] as Boolean,+ engineSelection = engineSel,)}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), SettingsUiState())@@ -143,7 +147,7 @@ class SettingsViewModel @Inject constructor(val portForwardRules: StateFlow<List<PortForwardRule>> = portForwardRepository.rules.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())- val vmState: StateFlow<VmState> = podroidQemu.state+ val vmState: StateFlow<VmState> = engine.state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), VmState.Idle)fun setDarkTheme(value: Boolean) {@@ -154,6 +158,10 @@ class SettingsViewModel @Inject constructor(viewModelScope.launch { settingsRepository.setDynamicColorEnabled(value) }}+ fun setEngineSelection(value: EngineSelection) {+ viewModelScope.launch { settingsRepository.setEngineSelection(value) }+ }+fun setVmRamMb(value: Int) {viewModelScope.launch { settingsRepository.setVmRamMb(value) }}@@ -184,8 +192,13 @@ class SettingsViewModel @Inject constructor(val rule = PortForwardRule(hostPort, guestPort, proto)if (existing.any { it.hostPort == hostPort && it.protocol == proto }) return@forEachportForwardRepository.addRule(rule)- if (podroidQemu.state.value is VmState.Running) {- podroidQemu.qmpClient.addPortForward(hostPort, guestPort, proto)+ if (engine.state.value is VmState.Running) {+ val qmp = engine.qmpClient+ if (qmp == null) {+ android.util.Log.w("SettingsVM", "port forwarding not supported by backend=${engine.backendId}")+ } else {+ qmp.addPortForward(hostPort, guestPort, proto)+ }}}}@@ -194,11 +207,19 @@ class SettingsViewModel @Inject constructor(/** Current LAN IP of the Android device — shown next to port forward rules. Cached for the VM lifetime. */val phoneIp: String by lazy { NetworkUtils.localIpv4() }+ /** Returns the ID string of the currently active VM backend (e.g. "qemu" or "avf"). */+ fun activeBackendId(): String = engine.backendId+fun removePortForward(rule: PortForwardRule) {viewModelScope.launch {portForwardRepository.removeRule(rule)- if (podroidQemu.state.value is VmState.Running) {- podroidQemu.qmpClient.removePortForward(rule.hostPort, rule.protocol)+ if (engine.state.value is VmState.Running) {+ val qmp = engine.qmpClient+ if (qmp == null) {+ android.util.Log.w("SettingsVM", "port forwarding not supported by backend=${engine.backendId}")+ } else {+ qmp.removePortForward(rule.hostPort, rule.protocol)+ }}}}@@ -302,8 +323,8 @@ class SettingsViewModel @Inject constructor(appendLine()appendLine("=== VM State ===")- appendLine("State: ${podroidQemu.state.value}")- appendLine("Boot stage: ${podroidQemu.bootStage.value.ifEmpty { "(none)" }}")+ appendLine("State: ${engine.state.value}")+ appendLine("Boot stage: ${engine.bootStage.value.ifEmpty { "(none)" }}")val storageFile = File(context.filesDir, "storage.img")appendLine("Storage img: " + if (storageFile.exists())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.ktindex e442ba1..93481d0 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@@ -40,7 +40,7 @@ import android.view.MotionEventimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.excp.podroid.data.repository.SettingsRepository-import com.excp.podroid.engine.PodroidQemu+import com.excp.podroid.engine.VmEngineimport com.excp.podroid.engine.VmStateimport com.excp.podroid.util.LogProxyimport com.termux.terminal.TerminalEmulator@@ -62,12 +62,12 @@ import javax.inject.Inject@HiltViewModelclass TerminalViewModel @Inject constructor(@ApplicationContext private val context: Context,- private val qemu: PodroidQemu,+ private val engine: VmEngine,private val settingsRepository: SettingsRepository,) : ViewModel() {- val vmState: StateFlow<VmState> = qemu.state- val bootStage: StateFlow<String> = qemu.bootStage+ val vmState: StateFlow<VmState> = engine.state+ val bootStage: StateFlow<String> = engine.bootStageval terminalFontSize: StateFlow<Int> = settingsRepository.terminalFontSize.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 20)@@ -636,7 +636,13 @@ class TerminalViewModel @Inject constructor(fun createSession() {if (attached) return- val sess = qemu.createTerminalSession(sessionClient)+ val sess = runCatching { engine.createTerminalSession(sessionClient) }+ .onFailure { e ->+ // AvfEngine throws UnsupportedOperationException until Task 11+ // wires the AVF bridge. Don't crash the UI — leave session null.+ android.util.Log.w(TAG, "createTerminalSession failed on ${engine.backendId}: ${e.message}")+ }+ .getOrNull() ?: returnsession = sessattached = true}@@ -762,9 +768,9 @@ class TerminalViewModel @Inject constructor(override fun onCleared() {super.onCleared()// Drop the proxy's pointer to this dead ViewModel — otherwise the singleton- // PodroidQemu keeps forwarding session events into a tombstoned client.- if (qemu.sessionClientDelegate === sessionClient) {- qemu.sessionClientDelegate = null+ // VmEngine keeps forwarding session events into a tombstoned client.+ if (engine.sessionClientDelegate === sessionClient) {+ engine.sessionClientDelegate = null}attached = false}diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.ktindex 0de1035..0434c73 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt@@ -6,7 +6,7 @@ package com.excp.podroid.ui.screens.x11import androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope-import com.excp.podroid.engine.PodroidQemu+import com.excp.podroid.engine.VmEngineimport com.excp.podroid.engine.VmStateimport com.excp.podroid.x11.AudioStreamerimport com.excp.podroid.x11.VncClient@@ -33,10 +33,10 @@ sealed interface X11ConnectionState {@HiltViewModelclass X11ViewModel @Inject constructor(- val podroidQemu: PodroidQemu,+ val engine: VmEngine,) : ViewModel() {- val vmState: StateFlow<VmState> = podroidQemu.state+ val vmState: StateFlow<VmState> = engine.stateprivate val _connection = MutableStateFlow<X11ConnectionState>(X11ConnectionState.Disconnected)val connection: StateFlow<X11ConnectionState> = _connection.asStateFlow()@@ -51,6 +51,12 @@ class X11ViewModel @Inject constructor(*/val framebuffer: IntArray = IntArray(X11Constants.FB_WIDTH * X11Constants.FB_HEIGHT)+ // Scratch buffer the RFB decoder writes into off the UI thread. We swap+ // it into [framebuffer] under a short lock so the UI never blocks on a+ // socket read (holding the framebuffer lock across recvfrom deadlocks+ // the main thread → ANR on screen open).+ private val scratch: IntArray = IntArray(X11Constants.FB_WIDTH * X11Constants.FB_HEIGHT)+private val _frameCounter = MutableStateFlow(0)val frameCounter: StateFlow<Int> = _frameCounter.asStateFlow()@@ -77,16 +83,17 @@ class X11ViewModel @Inject constructor(audio.start(viewModelScope)while (isActive) {- // Lock the framebuffer for the full RFB rect decode so the- // UI thread can't observe a half-written frame. The lock- // is uncontended ~99% of the time (UI grabs it only during- // setPixels, which is fast).+ // Decode into scratch off-lock so a blocking socket read+ // never holds the framebuffer lock (would deadlock the+ // UI thread → ANR). Swap under a short lock; the copy+ // is fast and uncontended.+ VncClient.readFramebufferUpdate(+ inp = inp,+ targetArgb = scratch,+ stride = X11Constants.FB_WIDTH,+ )synchronized(framebuffer) {- VncClient.readFramebufferUpdate(- inp = inp,- targetArgb = framebuffer,- stride = X11Constants.FB_WIDTH,- )+ System.arraycopy(scratch, 0, framebuffer, 0, framebuffer.size)}_frameCounter.value = _frameCounter.value + 1VncClient.requestFramebufferUpdate(out, incremental = true)diff --git a/app/src/main/java/com/excp/podroid/util/LogProxy.kt b/app/src/main/java/com/excp/podroid/util/LogProxy.ktindex 1880b9c..8d0238d 100644--- a/app/src/main/java/com/excp/podroid/util/LogProxy.kt+++ b/app/src/main/java/com/excp/podroid/util/LogProxy.kt@@ -3,7 +3,7 @@* Copyright (C) 2024-2026 Podroid contributors** Tiny shim for the seven log methods every Termux TerminalSessionClient and- * TerminalViewClient implementation has to override. Both PodroidQemu's proxy+ * TerminalViewClient implementation has to override. Both QemuEngine's proxy* client and TerminalViewModel's clients used to stamp the same boilerplate* twice — this is the single source of truth.*/diff --git a/build-rootfs/build-rootfs.sh b/build-rootfs/build-rootfs.shindex 598f682..9c5261e 100755--- a/build-rootfs/build-rootfs.sh+++ b/build-rootfs/build-rootfs.sh@@ -95,10 +95,11 @@ cp /work/files/etc/init.d/podroid-ready "$ROOTFS/etc/init.d/"cp /work/files/etc/init.d/podroid-x11 "$ROOTFS/etc/init.d/"chmod +x "$ROOTFS/etc/init.d/podroid-"*-# Copy /usr/local/bin scripts (resize daemon + login wrapper)+# Copy /usr/local/bin scripts (resize daemon + login wrapper + getty selector)mkdir -p "$ROOTFS/usr/local/bin"cp /work/files/usr/local/bin/podroid-resize "$ROOTFS/usr/local/bin/"cp /work/files/usr/local/bin/podroid-login "$ROOTFS/usr/local/bin/"+cp /work/files/usr/local/bin/podroid-getty "$ROOTFS/usr/local/bin/"chmod +x "$ROOTFS/usr/local/bin/podroid-"*mkdir -p "$ROOTFS/etc/conf.d"cp /work/files/etc/conf.d/podroid "$ROOTFS/etc/conf.d/"diff --git a/build-rootfs/files/etc/init.d/podroid-bootstrap b/build-rootfs/files/etc/init.d/podroid-bootstrapindex 97ed070..1a73557 100644--- a/build-rootfs/files/etc/init.d/podroid-bootstrap+++ b/build-rootfs/files/etc/init.d/podroid-bootstrap@@ -10,6 +10,17 @@ start() {ebegin "Loading kernel modules..."echo "Loading kernel modules..." > /dev/console+ # Seed the system clock from the host. AVF/crosvm doesn't wire an+ # emulated RTC the way QEMU TCG does, so without this the guest boots+ # at epoch (1970-01-01) and every TLS cert appears "not yet valid" —+ # `apk update` warns `server certificate not trusted`, curl/wget fail,+ # etc. AvfEngine passes `podroid.epoch=<unix-secs>` on the cmdline; we+ # parse it here. No-op when the marker is absent (QEMU path).+ PODROID_EPOCH=$(sed -n 's/.*podroid\.epoch=\([0-9]*\).*/\1/p' /proc/cmdline)+ if [ -n "$PODROID_EPOCH" ] && [ "$PODROID_EPOCH" -gt 0 ] 2>/dev/null; then+ date -s "@$PODROID_EPOCH" >/dev/null 2>&1+ fi+# Rootless podman needs / to be a shared mount so user namespaces can# propagate mount events. Without this, every rootless `podman run`# warns and may fail to mount /sys-as-fuse-overlayfs inside the userns.diff --git a/build-rootfs/files/etc/init.d/podroid-network b/build-rootfs/files/etc/init.d/podroid-networkindex 82b83f7..7cd629d 100644--- a/build-rootfs/files/etc/init.d/podroid-network+++ b/build-rootfs/files/etc/init.d/podroid-network@@ -18,16 +18,31 @@ start() {[ -n "$NETIF" ] && breaksleep 0.05done- if [ -n "$NETIF" ]; then- ip link set "$NETIF" up- ip addr add 10.0.2.15/24 dev "$NETIF" 2>/dev/null- ip route add default via 10.0.2.2 dev "$NETIF" 2>/dev/null- echo "Network found" > /dev/console- else+ if [ -z "$NETIF" ]; theneend 1 "no network interface"return 1fi- printf 'nameserver 10.0.2.3\nnameserver 8.8.8.8\nnameserver 1.1.1.1\n' \- > /etc/resolv.conf+ ip link set "$NETIF" up++ if grep -q 'podroid\.tty=ttyS0' /proc/cmdline 2>/dev/null; then+ # AVF backend: crosvm wires the guest to a TAP that Android's tethering+ # manager runs DHCP on. The lease decides our IP / gateway / DNS — the+ # SLIRP-style 10.0.2.15 hardcode won't sit on the right subnet (on+ # IPv6-only cellular w/ CLAT it lands on 192.0.0.x). udhcpc applies+ # everything via the default /usr/share/udhcpc/default.script.+ udhcpc -i "$NETIF" -t 8 -T 1 -A 1 -q -f -n 2>/dev/null || \+ udhcpc -i "$NETIF" -q -f -n 2>/dev/null || true+ # Belt-and-suspenders: if DHCP didn't write resolv.conf (busybox+ # variants differ), drop public DNS so apk/curl don't die silently.+ [ -s /etc/resolv.conf ] || printf 'nameserver 8.8.8.8\nnameserver 1.1.1.1\n' > /etc/resolv.conf+ else+ # QEMU/TCG backend: SLIRP's built-in DHCP also exists but hardcoding+ # is faster + matches every existing user's setup. Original behavior.+ ip addr add 10.0.2.15/24 dev "$NETIF" 2>/dev/null+ ip route add default via 10.0.2.2 dev "$NETIF" 2>/dev/null+ printf 'nameserver 10.0.2.3\nnameserver 8.8.8.8\nnameserver 1.1.1.1\n' \+ > /etc/resolv.conf+ fi+ echo "Network found" > /dev/consoleeend 0}diff --git a/build-rootfs/files/etc/inittab b/build-rootfs/files/etc/inittabindex 773c43a..0c11f12 100644--- a/build-rootfs/files/etc/inittab+++ b/build-rootfs/files/etc/inittab@@ -2,5 +2,9 @@::sysinit:/sbin/openrc boot::wait:/sbin/openrc default-hvc0::respawn:/sbin/getty -L -l /usr/local/bin/podroid-login 115200 hvc0 xterm-256color+# Two gettys are declared, but only one starts per boot — see /usr/local/bin/podroid-getty:+# the wrapper reads `podroid.tty=` from the kernel cmdline and sleeps the wrong tty+# instead of running getty there. This keeps the squashfs backend-agnostic.+hvc0::respawn:/usr/local/bin/podroid-getty hvc0+ttyS0::respawn:/usr/local/bin/podroid-getty ttyS0::shutdown:/sbin/openrc shutdowndiff --git a/build-rootfs/files/usr/local/bin/podroid-getty b/build-rootfs/files/usr/local/bin/podroid-gettynew file mode 100644index 0000000..93c0b77--- /dev/null+++ b/build-rootfs/files/usr/local/bin/podroid-getty@@ -0,0 +1,23 @@+#!/bin/sh+# Wrapper for inittab's per-tty getty lines. Two gettys (hvc0 + ttyS0) are+# declared because the backend isn't known at squashfs-build time; this+# script picks the right one at boot via the kernel cmdline marker:+#+# podroid.tty=hvc0 QEMU/TCG backend (virtio-console)+# podroid.tty=ttyS0 AVF/pKVM backend (PL011 serial, the only AVF console+# with an input side on Pixel's crosvm)+#+# If the marker is absent, default to hvc0 — that's QEMU's historical setup+# so legacy boots without the marker still get a login.+TTY="$1"+WANT=$(sed -n 's/.*podroid\.tty=\([a-zA-Z0-9]*\).*/\1/p' /proc/cmdline)+[ -z "$WANT" ] && WANT=hvc0++if [ "$TTY" = "$WANT" ]; then+ exec /sbin/getty -L -l /usr/local/bin/podroid-login 115200 "$TTY" xterm-256color+fi++# Wrong tty for this backend. Sleep instead of exiting so busybox init+# doesn't throttle us with "respawning too fast" — the inittab line will+# just stay parked until shutdown.+exec sleep 2147483647diff --git a/build-rootfs/files/usr/local/bin/podroid-login b/build-rootfs/files/usr/local/bin/podroid-loginindex 7fa8b10..7ce6dca 100644--- a/build-rootfs/files/usr/local/bin/podroid-login+++ b/build-rootfs/files/usr/local/bin/podroid-login@@ -1,11 +1,19 @@#!/bin/sh-# Replacement login shell for hvc0 getty. Restores the terminal size-# from /run/term_size (written by podroid-resize) before exec'ing the-# real login binary — virtio-console resets winsize to 0x0 on every-# getty respawn, so without this TUI apps can't render until the user-# triggers a host-side SIGWINCH.+# Replacement login shell for getty. Restores the terminal size from+# /run/term_size (written by podroid-resize on QEMU) before exec'ing the+# real login binary — virtio-console + PL011 serial both reset winsize+# to 0x0 on every getty respawn, so without this TUI apps (btop, htop,+# vim, less) bail with "Failed to get size of terminal".+#+# AVF doesn't run podroid-resize for ttyS0 (no SIGWINCH propagation+# channel yet), so /run/term_size won't exist there — fall back to a+# sensible default rather than leaving winsize at 0x0. The host-side+# TerminalView will overwrite this the moment the user touches the+# screen and triggers a real SIGWINCH.if [ -r /run/term_size ]; thenread _r _c < /run/term_size- [ -n "$_r" ] && [ -n "$_c" ] && stty rows "$_r" cols "$_c" 2>/dev/nullfi+[ -z "$_r" ] && _r=24+[ -z "$_c" ] && _c=80+stty rows "$_r" cols "$_c" 2>/dev/nullexec /bin/login "$@"