A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
fix: wakelock race, Android 14+ crash, restart race, socket cleanup, diagnostic log
ExTvea425db1e035
diff --git a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt b/app/src/main/java/com/excp/podroid/engine/PodroidQemu.ktindex f1a4fbc..8d4cc20 100644--- a/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt+++ b/app/src/main/java/com/excp/podroid/engine/PodroidQemu.kt@@ -99,8 +99,10 @@ class PodroidQemu @Inject constructor(return _terminalSession!!}+ // Release the boot monitor connection so QEMU re-listens on serial.sock.+ // No sleep needed — podroid-bridge has its own connect retry loop+ // (50 × 200ms = up to 10s), so the handoff is race-free.releaseSerial()- Thread.sleep(500)val bridgeExe = File(context.applicationInfo.nativeLibraryDir, "libpodroid-bridge.so")if (!bridgeExe.exists()) {@@ -154,9 +156,12 @@ class PodroidQemu @Inject constructor(_consoleText.value = ""_bootStage.value = "Starting QEMU..."- // Clean up stale sockets from a previous run+ // Clean up stale sockets from a previous run. qmp.sock must be+ // included — a leftover file from a crashed QEMU prevents the new+ // process from binding its QMP server socket.File(serialSockPath).delete()File(ctrlSockPath).delete()+ File(qmpSocketPath).delete()try {val cmd = buildCommand(qemuExe, portForwards, ramMb, cpus, sshEnabled, androidIp)@@ -208,8 +213,9 @@ class PodroidQemu @Inject constructor(Thread.sleep(200)}if (_state.value != VmState.Running) {- Log.w(TAG, "Socket timeout — proceeding anyway")- _state.value = VmState.Running+ Log.e(TAG, "Socket timeout — QEMU sockets not ready after ${timeoutMs}ms")+ proc.destroyForcibly()+ throw RuntimeException("QEMU failed to create sockets within ${timeoutMs / 1000}s")}diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.ktindex 255db65..210d2be 100644--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt@@ -15,10 +15,13 @@ import android.app.PendingIntentimport android.app.Serviceimport android.content.Contextimport android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Buildimport android.os.IBinderimport android.os.PowerManagerimport android.util.Logimport androidx.core.app.NotificationCompat+import androidx.core.app.ServiceCompatimport com.excp.podroid.MainActivityimport com.excp.podroid.Rimport com.excp.podroid.data.repository.PortForwardRepository@@ -51,7 +54,20 @@ class PodroidService : Service() {override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {when (intent?.action) {ACTION_START -> {- startForeground(NOTIFICATION_ID, buildNotification("Starting VM..."))+ // Android 14+ (API 34) requires the foregroundServiceType argument+ // when the manifest declares foregroundServiceType="specialUse";+ // otherwise Android throws MissingForegroundServiceTypeException.+ val fgType = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE+ } else {+ 0+ }+ ServiceCompat.startForeground(+ this,+ NOTIFICATION_ID,+ buildNotification("Starting VM..."),+ fgType,+ )acquireWakeLock()launchPodroid()}@@ -119,16 +135,31 @@ class PodroidService : Service() {}}launch {+ // Terminal states: release resources and shut down the service.+ // Error must be included here — otherwise a failed boot leaves the+ // wakelock held and the foreground notification stuck on "Starting...".+ //+ // StateFlow replays its current value on subscription, so this+ // collector fires immediately with whatever state is already set.+ // At service-start time the current state is Idle (QEMU hasn't+ // been launched yet), which used to match this branch and+ // instantly release the wakelock we just acquired. Guard with+ // a "seenActive" flag so cleanup only runs on a real+ // active → terminal transition.+ var seenActive = falsepodroidQemu.state.collect { state ->when (state) {- is VmState.Stopped, is VmState.Idle -> {- releaseWakeLock()- if (android.os.Build.VERSION.SDK_INT >= 33) {- stopForeground(STOP_FOREGROUND_REMOVE)- } else {- @Suppress("DEPRECATION") stopForeground(true)+ is VmState.Starting, is VmState.Running -> seenActive = true+ is VmState.Stopped, is VmState.Idle, is VmState.Error -> {+ if (seenActive) {+ releaseWakeLock()+ if (Build.VERSION.SDK_INT >= 33) {+ stopForeground(STOP_FOREGROUND_REMOVE)+ } else {+ @Suppress("DEPRECATION") stopForeground(true)+ }+ stopSelf()}- stopSelf()}else -> {}}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 fc1078a..e542f06 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@@ -12,13 +12,14 @@ import com.excp.podroid.engine.VmStateimport com.excp.podroid.service.PodroidServiceimport dagger.hilt.android.lifecycle.HiltViewModelimport dagger.hilt.android.qualifiers.ApplicationContext-import kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.SharingStartedimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.stateInimport kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNullimport javax.inject.Inject@HiltViewModel@@ -79,7 +80,16 @@ class HomeViewModel @Inject constructor(fun restartVm() {PodroidService.stop(context)viewModelScope.launch {- delay(2000)+ // Wait for the VM to actually stop before starting again.+ // A fixed delay could race QEMU shutdown — await the terminal+ // state instead, with a safety timeout.+ withTimeoutOrNull(10_000) {+ podroidQemu.state.first { state ->+ state is VmState.Stopped ||+ state is VmState.Idle ||+ state is VmState.Error+ }+ }PodroidService.start(context)}}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 cf42ae7..ff82082 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@@ -388,8 +388,14 @@ fun SettingsScreen() {Icon(Icons.Default.Share, contentDescription = null)Spacer(Modifier.width(8.dp))- Text("Export Console Log")+ Text("Export Diagnostic Log")}+ Text(+ text = "Shares log.txt with app info, settings, VM state, app logcat, and QEMU console output. Attach this when reporting bugs.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(top = 4.dp),+ )Spacer(Modifier.height(8.dp))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 3272f3e..71df6a2 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@@ -8,9 +8,11 @@ package com.excp.podroid.ui.screens.settingsimport android.content.Contextimport android.content.Intent+import android.os.Buildimport androidx.core.content.FileProviderimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope+import com.excp.podroid.BuildConfigimport com.excp.podroid.data.repository.PortForwardRepositoryimport com.excp.podroid.data.repository.PortForwardRuleimport com.excp.podroid.data.repository.SettingsRepository@@ -18,12 +20,17 @@ import com.excp.podroid.engine.PodroidQemuimport com.excp.podroid.engine.VmStateimport dagger.hilt.android.lifecycle.HiltViewModelimport dagger.hilt.android.qualifiers.ApplicationContext+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.SharingStartedimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.stateInimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContextimport java.io.File+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Localeimport javax.inject.Inject@HiltViewModel@@ -130,24 +137,142 @@ class SettingsViewModel @Inject constructor(}}+ /**+ * Build a single log.txt containing everything a maintainer would need+ * to triage a user bug report:+ * - App + device info+ * - Current settings snapshot+ * - VM state + boot stage+ * - Port forward rules+ * - App logcat (filtered to this process — only Podroid tags)+ * - QEMU console.log (serial output from the VM, if the VM has run)+ *+ * Written to filesDir/log.txt and shared via the system share sheet.+ */fun exportConsoleLogs() {- val logFile = File(context.filesDir, "console.log")- if (!logFile.exists()) return-- val uri = FileProvider.getUriForFile(- context,- "${context.packageName}.fileprovider",- logFile,- )- val intent = Intent(Intent.ACTION_SEND).apply {- type = "text/plain"- putExtra(Intent.EXTRA_STREAM, uri)- putExtra(Intent.EXTRA_SUBJECT, "Podroid Console Log")- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ viewModelScope.launch {+ val logFile = withContext(Dispatchers.IO) {+ val file = File(context.filesDir, "log.txt")+ file.writeText(buildDiagnosticLog())+ file+ }++ val uri = FileProvider.getUriForFile(+ context,+ "${context.packageName}.fileprovider",+ logFile,+ )+ val intent = Intent(Intent.ACTION_SEND).apply {+ type = "text/plain"+ putExtra(Intent.EXTRA_STREAM, uri)+ putExtra(Intent.EXTRA_SUBJECT, "Podroid Diagnostic Log")+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ context.startActivity(Intent.createChooser(intent, "Share diagnostic log").apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ })+ }+ }++ private suspend fun buildDiagnosticLog(): String = withContext(Dispatchers.IO) {+ val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US).format(Date())+ val ram = runCatching { settingsRepository.getVmRamMbSnapshot() }.getOrDefault(-1)+ val cpus = runCatching { settingsRepository.getVmCpusSnapshot() }.getOrDefault(-1)+ val storage = runCatching { settingsRepository.getStorageSizeGbSnapshot() }.getOrDefault(-1)+ val ssh = runCatching { settingsRepository.getSshEnabledSnapshot() }.getOrDefault(false)+ val storageAccess = runCatching { settingsRepository.getStorageAccessEnabledSnapshot() }.getOrDefault(false)+ val theme = runCatching { settingsRepository.getTerminalColorThemeSnapshot() }.getOrDefault("default")+ val font = runCatching { settingsRepository.getTerminalFontSnapshot() }.getOrDefault("default")+ val rules = runCatching { portForwardRepository.getRulesSnapshot() }.getOrDefault(emptyList())++ buildString {+ appendLine("=== Podroid Diagnostic Log ===")+ appendLine("Generated: $timestamp")+ appendLine()++ appendLine("=== App ===")+ appendLine("Version: ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")+ appendLine("Build type: ${BuildConfig.BUILD_TYPE}")+ appendLine("App ID: ${BuildConfig.APPLICATION_ID}")+ appendLine("QEMU version: ${BuildConfig.QEMU_VERSION}")+ appendLine()++ appendLine("=== Device ===")+ appendLine("Manufacturer: ${Build.MANUFACTURER}")+ appendLine("Model: ${Build.MODEL}")+ appendLine("Device: ${Build.DEVICE}")+ appendLine("Product: ${Build.PRODUCT}")+ appendLine("Android: ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})")+ appendLine("ABIs: ${Build.SUPPORTED_ABIS.joinToString()}")+ appendLine("Fingerprint: ${Build.FINGERPRINT}")+ appendLine()++ appendLine("=== Settings ===")+ appendLine("VM RAM: $ram MB")+ appendLine("VM CPUs: $cpus")+ appendLine("Storage size: $storage GB")+ appendLine("SSH enabled: $ssh")+ appendLine("Downloads sharing: $storageAccess")+ appendLine("Terminal theme: $theme")+ appendLine("Terminal font: $font")+ appendLine()++ appendLine("=== VM State ===")+ appendLine("State: ${podroidQemu.state.value}")+ appendLine("Boot stage: ${podroidQemu.bootStage.value.ifEmpty { "(none)" }}")+ val storageFile = File(context.filesDir, "storage.img")+ appendLine(+ "Storage img: " + if (storageFile.exists())+ "${storageFile.absolutePath} (${storageFile.length() / (1024 * 1024)} MB)"+ else "(not created)"+ )+ appendLine()++ appendLine("=== Port Forward Rules (${rules.size}) ===")+ if (rules.isEmpty()) {+ appendLine("(none)")+ } else {+ rules.forEach { rule ->+ appendLine("${rule.protocol.uppercase()} localhost:${rule.hostPort} -> VM:${rule.guestPort}")+ }+ }+ appendLine()++ appendLine("=== App Logcat (this process) ===")+ append(captureAppLogcat())+ appendLine()++ appendLine("=== QEMU Console Log ===")+ val consoleFile = File(context.filesDir, "console.log")+ if (consoleFile.exists() && consoleFile.length() > 0) {+ append(consoleFile.readText())+ if (!consoleFile.readText().endsWith("\n")) appendLine()+ } else {+ appendLine("(no console.log — VM has not been started this session)")+ }+ appendLine()++ appendLine("=== End of Log ===")+ }+ }++ /**+ * Dump the current process's logcat buffer. Apps on Android 4.1+ can only+ * read their own logs, so --pid filtering is redundant for security but+ * keeps the output focused on Podroid tags.+ */+ private fun captureAppLogcat(): String {+ return try {+ val pid = android.os.Process.myPid().toString()+ val proc = Runtime.getRuntime().exec(+ arrayOf("logcat", "-d", "-v", "time", "-t", "2000", "--pid=$pid")+ )+ val output = proc.inputStream.bufferedReader().use { it.readText() }+ proc.waitFor()+ if (output.isBlank()) "(logcat returned no lines)\n" else output+ } catch (e: Exception) {+ "(failed to capture logcat: ${e.message})\n"}- context.startActivity(Intent.createChooser(intent, "Share console log").apply {- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- })}}