mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
Merge latest upstream main before Controller UI integration
# Conflicts: # app/src/main/java/com/droiddeck/launcher/SessionActivity.kt # app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt # app/src/main/java/com/droiddeck/launcher/input/PadBridge.java # app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt # app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt
This commit is contained in:
commit
ba5876bf6d
360 files changed
+34610
-1088
No files matched your search
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.gpu.AppVulkan
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdInputStream
|
||||
import com.github.luben.zstd.ZstdOutputStream
|
||||
@@ -199,9 +200,13 @@ object ComponentsManager {
|
||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
||||
}
|
||||
|
||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
|
||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
|
||||
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
||||
|
||||
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||
require(comp in COMPONENTS)
|
||||
if (file != null) requireSelectable(context, comp, managed)
|
||||
val state = loadState(context)
|
||||
val profiles = state.sub("profiles")
|
||||
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
|
||||
@@ -638,11 +643,21 @@ object ComponentsManager {
|
||||
return PreparedLaunchState(lines.toString(), keep)
|
||||
}
|
||||
|
||||
internal fun runtimeManaged(comp: String, systemPowerVr: Boolean): Boolean = comp == "dxvk" && systemPowerVr
|
||||
|
||||
private fun runtimeManaged(context: Context, comp: String): Boolean =
|
||||
runtimeManaged(comp, SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)))
|
||||
|
||||
private fun requireSelectable(context: Context, comp: String, managed: (String) -> Boolean = { runtimeManaged(context, it) }) {
|
||||
check(!managed(comp)) { context.getString(R.string.cmgr_powervr_dxvk_managed) }
|
||||
}
|
||||
|
||||
|
||||
fun swap(context: Context, protonId: String, file: String, auto: Boolean = false): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(packagesDir(context), safeName(file))
|
||||
val info = packageInfo(context, wcp)
|
||||
requireSelectable(context, info.comp)
|
||||
val state = loadState(context)
|
||||
if (inUse(context, p)) {
|
||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
|
||||
@@ -668,6 +683,7 @@ object ComponentsManager {
|
||||
}
|
||||
|
||||
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
|
||||
requireSelectable(context, comp)
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
|
||||
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) }
|
||||
@@ -693,7 +709,10 @@ object ComponentsManager {
|
||||
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
|
||||
}
|
||||
|
||||
fun applyQueued(context: Context): List<String> = synchronized(lock) {
|
||||
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
|
||||
fun applyQueued(context: Context): List<String> = applyQueued(context) { runtimeManaged(context, it) }
|
||||
|
||||
internal fun applyQueued(context: Context, managed: (String) -> Boolean): List<String> = synchronized(lock) {
|
||||
val state = loadState(context)
|
||||
val queued = state.sub("queued")
|
||||
if (queued.length() == 0) return emptyList()
|
||||
@@ -705,6 +724,7 @@ object ComponentsManager {
|
||||
val comps = queued.optJSONObject(pid) ?: continue
|
||||
for (comp in comps.keys().asSequence().toList()) {
|
||||
val q = comps.optJSONObject(comp) ?: continue
|
||||
if (managed(comp)) continue
|
||||
runCatching {
|
||||
if (q.optString("kind") == "original") {
|
||||
val v = q.optString("protonVersion")
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AtomicFile
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object EnhancedDiagnostics {
|
||||
const val MANIFEST_FILE = "enhanced-diagnostics.json"
|
||||
|
||||
private const val TAG = "EnhancedDiagnostics"
|
||||
private const val PREFS = "session"
|
||||
private const val ARMED = "enhancedDiagnosticsNext"
|
||||
private const val ACTIVE_RECORDS = "enhancedDiagnosticsActiveSessions"
|
||||
private const val SCHEMA = 1
|
||||
|
||||
fun isArmed(context: Context): Boolean =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(ARMED, false)
|
||||
|
||||
fun setArmed(context: Context, armed: Boolean): Boolean =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(ARMED, armed).commit()
|
||||
|
||||
fun isActive(context: Context, folder: File?): Boolean = activeAt(context, folder) != null
|
||||
|
||||
internal fun isCurrentSessionActive(context: Context): Boolean = isActive(context, SessionPaths.current())
|
||||
|
||||
fun manifest(context: Context, folder: File?): JSONObject? {
|
||||
val activeAt = activeAt(context, folder) ?: return null
|
||||
return buildManifest(folder!!, activeAt)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
internal fun consumeInto(context: Context, folder: File): Boolean {
|
||||
if (!isArmed(context)) return isActive(context, folder)
|
||||
if (!folder.isDirectory) return false
|
||||
val activatedAt = System.currentTimeMillis()
|
||||
if (!activateAndConsume(context, folder, activatedAt)) return false
|
||||
val marker = AtomicFile(File(folder, MANIFEST_FILE))
|
||||
val manifest = buildManifest(folder, activatedAt)
|
||||
val output = try {
|
||||
marker.startWrite()
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "could not start the informational enhanced diagnostics manifest", error)
|
||||
return true
|
||||
}
|
||||
try {
|
||||
output.write((manifest.toString() + "\n").toByteArray(Charsets.UTF_8))
|
||||
marker.finishWrite(output)
|
||||
} catch (error: Exception) {
|
||||
marker.failWrite(output)
|
||||
Log.w(TAG, "could not write the informational enhanced diagnostics manifest", error)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
internal fun clearRecordFor(context: Context, folder: File) {
|
||||
removeRecord(context, folder)
|
||||
}
|
||||
|
||||
private fun buildManifest(folder: File, activatedAt: Long) = JSONObject()
|
||||
.put("schema", SCHEMA)
|
||||
.put("profile", "enhanced")
|
||||
.put("sessionId", folder.name)
|
||||
.put("activatedAtEpochMs", activatedAt)
|
||||
.put("exportBundlesBounded", true)
|
||||
.put("rawCaptureByteBounded", false)
|
||||
.put("rawCaptureLimitation", "Game and component diagnostics may grow until the session ends")
|
||||
.put("collectorsRequested", JSONArray(listOf(
|
||||
"session", "graphics", "games", "processes", "audio", "network", "components",
|
||||
)))
|
||||
|
||||
private fun activeAt(context: Context, folder: File?): Long? {
|
||||
val path = trustedPath(context, folder) ?: return null
|
||||
return records(context).optLong(path, Long.MIN_VALUE).takeIf { it != Long.MIN_VALUE }
|
||||
}
|
||||
|
||||
private fun activateAndConsume(context: Context, folder: File, activatedAt: Long): Boolean {
|
||||
val path = trustedPath(context, folder) ?: return false
|
||||
val records = records(context)
|
||||
records.keys().asSequence().toList().forEach { known ->
|
||||
if (!File(known).isDirectory) records.remove(known)
|
||||
}
|
||||
records.put(path, activatedAt)
|
||||
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||
.putString(ACTIVE_RECORDS, records.toString())
|
||||
.putBoolean(ARMED, false)
|
||||
.commit()
|
||||
}
|
||||
|
||||
private fun removeRecord(context: Context, folder: File) {
|
||||
val path = runCatching { folder.canonicalPath }.getOrNull() ?: return
|
||||
val records = records(context)
|
||||
if (records.has(path)) {
|
||||
records.remove(path)
|
||||
saveRecords(context, records)
|
||||
}
|
||||
}
|
||||
|
||||
private fun trustedPath(context: Context, folder: File?): String? {
|
||||
if (folder == null || !SessionPaths.isSessionFolder(folder)) return null
|
||||
return runCatching {
|
||||
val canonical = folder.canonicalFile
|
||||
if (canonical.parentFile != SessionFiles.logDirectory(context).canonicalFile) null else canonical.path
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private fun records(context: Context): JSONObject {
|
||||
val text = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(ACTIVE_RECORDS, null)
|
||||
return runCatching { JSONObject(text ?: "{}") }.getOrDefault(JSONObject())
|
||||
}
|
||||
|
||||
private fun saveRecords(context: Context, records: JSONObject): Boolean =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
||||
.putString(ACTIVE_RECORDS, records.toString()).commit()
|
||||
}
|
||||
@@ -0,0 +1,975 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.FileInputStream
|
||||
import java.io.IOException
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.Channels
|
||||
import java.nio.channels.FileChannel
|
||||
import java.nio.channels.FileLock
|
||||
import java.nio.channels.OverlappingFileLockException
|
||||
import java.nio.channels.SeekableByteChannel
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.StandardOpenOption
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
import java.security.MessageDigest
|
||||
import java.util.Locale
|
||||
import java.util.UUID
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
internal data class EnhancedShareLimits(
|
||||
val maxFilesPerArchive: Int = 256,
|
||||
val maxDiscoveredFiles: Int = 768,
|
||||
val maxBytesPerFile: Long = 8L * 1024 * 1024,
|
||||
val maxBytesTotal: Long = 64L * 1024 * 1024,
|
||||
)
|
||||
|
||||
internal interface SecureSourceOpener {
|
||||
fun <T> withChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T?
|
||||
}
|
||||
|
||||
internal object EnhancedSessionLogShare {
|
||||
private enum class Category(val suffix: String) { SESSION("session"), GRAPHICS("graphics"), GAMES("games") }
|
||||
|
||||
internal class DiagnosticStageLease internal constructor(
|
||||
val directory: File,
|
||||
private val canonicalPath: String,
|
||||
private val channel: FileChannel,
|
||||
private val lock: FileLock,
|
||||
) : Closeable {
|
||||
override fun close() {
|
||||
synchronized(stageLifecycleMonitor) {
|
||||
activeStagePaths.remove(canonicalPath)
|
||||
try {
|
||||
lock.release()
|
||||
} finally {
|
||||
try {
|
||||
channel.close()
|
||||
} finally {
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class Candidate(
|
||||
val file: File,
|
||||
val anchor: File,
|
||||
val entry: String,
|
||||
val origin: String,
|
||||
val category: Category,
|
||||
val linePrefix: String? = null,
|
||||
)
|
||||
|
||||
private data class Record(
|
||||
val entry: String,
|
||||
val origin: String,
|
||||
val status: String,
|
||||
val sourceBytes: Long = 0,
|
||||
val capturedBytes: Long = 0,
|
||||
val reason: String? = null,
|
||||
)
|
||||
|
||||
private data class Snapshot(val file: File, val sourceBytes: Long, val truncated: Boolean)
|
||||
|
||||
private class StageUnavailableException(cause: Throwable) : IOException("Diagnostic staging directory is unavailable", cause)
|
||||
|
||||
private class SourceReadException(cause: Throwable) : IOException("Could not read diagnostic source", cause)
|
||||
|
||||
private data class CollectionResult(
|
||||
val candidates: List<Candidate>,
|
||||
val truncated: Boolean,
|
||||
val partial: Boolean,
|
||||
)
|
||||
|
||||
private data class ScanResult(
|
||||
val files: List<File>,
|
||||
val truncated: Boolean,
|
||||
val partial: Boolean = false,
|
||||
)
|
||||
|
||||
private data class LegacySource(val file: File, val root: File, val entry: String)
|
||||
|
||||
private data class LegacyDiscovery(
|
||||
val sources: List<LegacySource>,
|
||||
val truncated: Boolean,
|
||||
val partial: Boolean,
|
||||
)
|
||||
|
||||
private class Budget(val limit: Long, var remaining: Long = limit)
|
||||
|
||||
private val sourceOpenerOverride = object : ThreadLocal<SecureSourceOpener?>() {
|
||||
override fun initialValue(): SecureSourceOpener? = null
|
||||
}
|
||||
private val stageLifecycleMonitor = Any()
|
||||
private val activeStagePaths = mutableSetOf<String>()
|
||||
|
||||
internal fun acquireDiagnosticStage(context: Context, outputName: String): DiagnosticStageLease {
|
||||
val cache = context.cacheDir
|
||||
require(outputName.isNotBlank() && File(outputName).name == outputName)
|
||||
return withStageLifecycleLock(cache) {
|
||||
val stage = File(cache, "$outputName-${UUID.randomUUID()}.diagnostic-stage")
|
||||
if (!stage.mkdir()) throw IOException("Could not create the diagnostic staging directory")
|
||||
val channel = try {
|
||||
FileChannel.open(File(stage, ".active").toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)
|
||||
} catch (error: Exception) {
|
||||
stage.deleteRecursively()
|
||||
throw IOException("Could not create the diagnostic staging lock", error)
|
||||
}
|
||||
try {
|
||||
val lock = channel.tryLock()
|
||||
?: throw IOException("Could not lock the diagnostic staging directory")
|
||||
val canonicalPath = stage.canonicalPath
|
||||
activeStagePaths += canonicalPath
|
||||
DiagnosticStageLease(stage, canonicalPath, channel, lock)
|
||||
} catch (error: Exception) {
|
||||
channel.close()
|
||||
stage.deleteRecursively()
|
||||
throw IOException("Could not lock the diagnostic staging directory", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun cleanupAbandonedStages(context: Context) {
|
||||
val cache = context.cacheDir
|
||||
val canonicalCache = cache.canonicalFile
|
||||
withStageLifecycleLock(cache) {
|
||||
cache.listFiles()?.forEach { stage ->
|
||||
if (!stage.isDirectory || Files.isSymbolicLink(stage.toPath()) ||
|
||||
stage.canonicalFile.parentFile != canonicalCache || !isDiagnosticStage(stage.name)) return@forEach
|
||||
if (stage.canonicalPath in activeStagePaths) return@forEach
|
||||
val active = File(stage, ".active")
|
||||
if (Files.isSymbolicLink(active.toPath())) return@forEach
|
||||
val channel = runCatching {
|
||||
FileChannel.open(active.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
|
||||
}.getOrNull() ?: return@forEach
|
||||
val abandoned = try {
|
||||
channel.tryLock()?.let { lock -> lock.release(); true } ?: false
|
||||
} catch (_: OverlappingFileLockException) {
|
||||
false
|
||||
} finally {
|
||||
channel.close()
|
||||
}
|
||||
if (abandoned) stage.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isDiagnosticStage(name: String): Boolean {
|
||||
val suffix = ".diagnostic-stage"
|
||||
if (!name.endsWith(suffix)) return false
|
||||
val base = name.removeSuffix(suffix)
|
||||
val uuidStart = base.length - 36
|
||||
if (uuidStart < 2 || base[uuidStart - 1] != '-') return false
|
||||
return runCatching { UUID.fromString(base.substring(uuidStart)).toString() == base.substring(uuidStart) }
|
||||
.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun <T> withStageLifecycleLock(cache: File, block: () -> T): T = synchronized(stageLifecycleMonitor) {
|
||||
FileChannel.open(File(cache, ".diagnostic-stages.lock").toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
|
||||
.use { channel -> channel.lock().use { block() } }
|
||||
}
|
||||
|
||||
internal fun setSourceOpenerForTest(opener: SecureSourceOpener?) {
|
||||
if (opener == null) sourceOpenerOverride.remove() else sourceOpenerOverride.set(opener)
|
||||
}
|
||||
|
||||
internal fun hasSourceOpenerForTest(): Boolean = sourceOpenerOverride.get() != null
|
||||
|
||||
fun create(
|
||||
context: Context,
|
||||
folder: File,
|
||||
onProgress: ((Float) -> Unit)? = null,
|
||||
limits: EnhancedShareLimits = EnhancedShareLimits(),
|
||||
): List<File> {
|
||||
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
|
||||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
|
||||
return emptyList()
|
||||
}
|
||||
val out = SessionLogShare.shareDir(context).apply { deleteRecursively(); mkdirs() }
|
||||
val stageLease = acquireDiagnosticStage(context, out.name)
|
||||
val stage = stageLease.directory
|
||||
return try {
|
||||
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = false)
|
||||
val candidates = discovery.candidates
|
||||
val totalCandidates = candidates.size.coerceAtLeast(1)
|
||||
val share = limits.maxBytesTotal / Category.values().size
|
||||
val budgets = Category.values().associateWith { category ->
|
||||
Budget(if (category == Category.GAMES) limits.maxBytesTotal - share * 2 else share)
|
||||
}
|
||||
var completed = 0
|
||||
Category.values().map { category ->
|
||||
val budget = budgets.getValue(category)
|
||||
val records = ArrayList<Record>()
|
||||
val selected = candidates.filter { it.category == category }
|
||||
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
|
||||
val names = HashSet<String>()
|
||||
selected.forEachIndexed { index, candidate ->
|
||||
val safeEntry = safeEntry(candidate.entry)
|
||||
val record = when {
|
||||
index >= limits.maxFilesPerArchive -> Record(
|
||||
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
|
||||
)
|
||||
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
|
||||
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
|
||||
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
|
||||
}
|
||||
records += record
|
||||
completed++
|
||||
onProgress?.invoke((completed.toFloat() / totalCandidates).coerceIn(0f, 1f))
|
||||
}
|
||||
if (category == Category.SESSION) addTrustedActivation(context, folder, archive)?.let(records::add)
|
||||
if (selected.isEmpty()) records += Record("", category.suffix, "unavailable", reason = "no-matching-artifacts")
|
||||
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
|
||||
if (discovery.partial) records += Record("", "discovery", "truncated", reason = "filesystem-error")
|
||||
addManifest(
|
||||
archive, folder.name, category.suffix, records, limits, budget.limit, redactionLearningComplete,
|
||||
)
|
||||
}
|
||||
zip
|
||||
}
|
||||
} finally {
|
||||
stageLease.close()
|
||||
}
|
||||
}
|
||||
|
||||
fun createLegacy(
|
||||
context: Context,
|
||||
folder: File,
|
||||
onProgress: ((Float) -> Unit)? = null,
|
||||
outputDirectory: File = SessionLogShare.shareDir(context),
|
||||
limits: EnhancedShareLimits = EnhancedShareLimits(maxFilesPerArchive = 512),
|
||||
): File? {
|
||||
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
|
||||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
|
||||
return null
|
||||
}
|
||||
val out = outputDirectory.apply { deleteRecursively(); mkdirs() }
|
||||
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = true)
|
||||
val candidates = discovery.candidates.filter { it.linePrefix == null }
|
||||
if (candidates.isEmpty()) {
|
||||
out.deleteRecursively()
|
||||
return null
|
||||
}
|
||||
val stageLease = acquireDiagnosticStage(context, out.name)
|
||||
val stage = stageLease.directory
|
||||
val records = ArrayList<Record>()
|
||||
val budget = Budget(limits.maxBytesTotal)
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
return try {
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
|
||||
val names = HashSet<String>()
|
||||
candidates.forEachIndexed { index, candidate ->
|
||||
val safeEntry = safeEntry(candidate.entry)
|
||||
records += when {
|
||||
index >= limits.maxFilesPerArchive -> Record(
|
||||
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
|
||||
)
|
||||
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
|
||||
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
|
||||
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
|
||||
}
|
||||
onProgress?.invoke((index + 1f) / candidates.size)
|
||||
}
|
||||
addTrustedActivation(context, folder, archive)?.let(records::add)
|
||||
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
|
||||
if (discovery.partial) records += Record("", "discovery", "truncated", reason = "filesystem-error")
|
||||
addManifest(archive, folder.name, "all", records, limits, budget.limit, redactionLearningComplete)
|
||||
}
|
||||
zip
|
||||
} finally {
|
||||
stageLease.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun addTrustedActivation(
|
||||
context: Context,
|
||||
folder: File,
|
||||
archive: ZipOutputStream,
|
||||
): Record? {
|
||||
val manifest = EnhancedDiagnostics.manifest(context, folder) ?: return null
|
||||
val bytes = (manifest.toString(2) + "\n").toByteArray()
|
||||
val entry = "${folder.name}/${EnhancedDiagnostics.MANIFEST_FILE}"
|
||||
archive.putNextEntry(ZipEntry(entry))
|
||||
archive.write(bytes)
|
||||
archive.closeEntry()
|
||||
return Record(entry, "app-private-activation-state", "captured", bytes.size.toLong(), bytes.size.toLong())
|
||||
}
|
||||
|
||||
private fun addCandidate(
|
||||
archive: ZipOutputStream,
|
||||
candidate: Candidate,
|
||||
stage: File,
|
||||
budget: Budget,
|
||||
limits: EnhancedShareLimits,
|
||||
): Record {
|
||||
if (budget.remaining <= 0) {
|
||||
return Record(candidate.entry, candidate.origin, "omitted", reason = "bundle-byte-limit")
|
||||
}
|
||||
if (!stage.isDirectory || !stage.canWrite()) throw StageUnavailableException(IOException("staging path is not writable"))
|
||||
val snapshot = try {
|
||||
snapshot(candidate, stage, minOf(limits.maxBytesPerFile, budget.remaining))
|
||||
} catch (error: StageUnavailableException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
if (!stage.isDirectory || !stage.canWrite()) throw StageUnavailableException(error)
|
||||
val reportedError = (error as? SourceReadException)?.cause ?: error
|
||||
return Record(candidate.entry, candidate.origin, "error", reason = reportedError.javaClass.simpleName)
|
||||
} ?: return Record(candidate.entry, candidate.origin, "omitted", reason = "unsafe-or-unavailable-source")
|
||||
if (snapshot.file.length() == 0L && candidate.linePrefix != null) {
|
||||
snapshot.file.delete()
|
||||
return Record(
|
||||
candidate.entry,
|
||||
candidate.origin,
|
||||
if (snapshot.truncated) "truncated" else "unavailable",
|
||||
snapshot.sourceBytes,
|
||||
reason = if (snapshot.truncated) "no-matching-lines-in-bounded-scan" else "no-matching-lines",
|
||||
)
|
||||
}
|
||||
return try {
|
||||
budget.remaining -= snapshot.file.length()
|
||||
archive.putNextEntry(ZipEntry(candidate.entry))
|
||||
val writer = archive.bufferedWriter()
|
||||
LogRedactor.scrubForShare(snapshot.file, writer)
|
||||
writer.flush()
|
||||
archive.closeEntry()
|
||||
Record(
|
||||
candidate.entry,
|
||||
candidate.origin,
|
||||
if (snapshot.truncated) "truncated" else "captured",
|
||||
snapshot.sourceBytes,
|
||||
snapshot.file.length(),
|
||||
if (snapshot.truncated) "per-file-or-bundle-byte-limit" else null,
|
||||
)
|
||||
} finally {
|
||||
snapshot.file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun snapshot(candidate: Candidate, stage: File, limit: Long): Snapshot? {
|
||||
val rootPath = candidate.anchor.toPath().toAbsolutePath().normalize()
|
||||
val sourcePath = candidate.file.toPath().toAbsolutePath().normalize()
|
||||
if (!sourcePath.startsWith(rootPath) || sourcePath == rootPath || limit < 1) return null
|
||||
val target = try {
|
||||
File.createTempFile("diagnostic-", ".log", stage)
|
||||
} catch (error: Exception) {
|
||||
throw StageUnavailableException(error)
|
||||
}
|
||||
try {
|
||||
val relative = rootPath.relativize(sourcePath)
|
||||
return withSecureChannel(rootPath, relative) { input ->
|
||||
val size = readSource { input.size() }
|
||||
candidate.linePrefix?.let { prefix ->
|
||||
val truncated = filterChannel(input, target, prefix, size, TRACE_SCAN_BYTES, limit)
|
||||
return@withSecureChannel Snapshot(target, size, truncated)
|
||||
}
|
||||
writeStage {
|
||||
FileOutputStream(target).channel.use { output ->
|
||||
if (size <= limit) {
|
||||
copy(input, output, 0, size)
|
||||
} else {
|
||||
val marker = "\n<diagnostic file truncated: beginning and tail retained>\n".toByteArray()
|
||||
val content = (limit - marker.size).coerceAtLeast(0)
|
||||
copyCompleteHead(input, output, content / 2)
|
||||
val markerBytes = minOf(marker.size.toLong(), limit - output.position()).toInt()
|
||||
output.write(ByteBuffer.wrap(marker, 0, markerBytes))
|
||||
copyCompleteTail(input, output, size, (limit - output.position()).coerceAtLeast(0))
|
||||
}
|
||||
output.force(false)
|
||||
}
|
||||
}
|
||||
Snapshot(target, size, size > limit)
|
||||
} ?: target.delete().let { null }
|
||||
} catch (e: Exception) {
|
||||
if (e is StageUnavailableException) {
|
||||
target.delete()
|
||||
throw e
|
||||
}
|
||||
val targetWasPresent = target.exists()
|
||||
target.delete()
|
||||
if (!stage.isDirectory || !stage.canWrite() || !targetWasPresent) throw StageUnavailableException(e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun filterChannel(
|
||||
channel: SeekableByteChannel,
|
||||
target: File,
|
||||
prefix: String,
|
||||
sourceSize: Long,
|
||||
scanLimit: Long,
|
||||
outputLimit: Long,
|
||||
): Boolean {
|
||||
val wanted = prefix.toByteArray()
|
||||
var written = 0L
|
||||
var truncated = sourceSize > scanLimit
|
||||
writeStage {
|
||||
target.outputStream().buffered().use { output ->
|
||||
fun scan(start: Long, count: Long, discardPartialFirstLine: Boolean) {
|
||||
readSource { channel.position(start) }
|
||||
val input = BufferedInputStream(Channels.newInputStream(channel), COPY_BUFFER_BYTES)
|
||||
val line = ByteArrayOutputStream(1024)
|
||||
var oversized = false
|
||||
var scanned = 0L
|
||||
var discard = discardPartialFirstLine
|
||||
fun emit() {
|
||||
val bytes = line.toByteArray()
|
||||
if (!discard && !oversized && bytes.size >= wanted.size && wanted.indices.all { bytes[it] == wanted[it] }) {
|
||||
if (written + bytes.size + 1 <= outputLimit) {
|
||||
output.write(bytes)
|
||||
output.write('\n'.code)
|
||||
written += bytes.size + 1
|
||||
} else truncated = true
|
||||
}
|
||||
line.reset()
|
||||
oversized = false
|
||||
discard = false
|
||||
}
|
||||
while (scanned < count) {
|
||||
val value = readSource { input.read() }
|
||||
if (value < 0) break
|
||||
scanned++
|
||||
if (value == '\n'.code) emit()
|
||||
else if (!oversized && !discard) {
|
||||
if (line.size() >= LogRedactor.MAX_LINE_LENGTH) {
|
||||
oversized = true
|
||||
line.reset()
|
||||
} else line.write(value)
|
||||
}
|
||||
}
|
||||
if (start + scanned >= sourceSize && (line.size() > 0 || oversized)) emit()
|
||||
}
|
||||
|
||||
if (sourceSize <= scanLimit) {
|
||||
scan(0, sourceSize, false)
|
||||
} else {
|
||||
val head = scanLimit / 2
|
||||
val tail = scanLimit - head
|
||||
scan(0, head, false)
|
||||
scan((sourceSize - tail).coerceAtLeast(0), tail, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
return truncated
|
||||
}
|
||||
|
||||
private fun <T> withSecureChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
|
||||
sourceOpenerOverride.get()?.let { return it.withChannel(root, relative, block) }
|
||||
return withAndroidSecureChannel(root, relative, block)
|
||||
}
|
||||
|
||||
private fun <T> withAndroidSecureChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
|
||||
val opened = ArrayList<ParcelFileDescriptor>()
|
||||
var invokingBlock = false
|
||||
return try {
|
||||
val parts = relative.map { it.toString() }
|
||||
if (parts.isEmpty()) return null
|
||||
opened += openDirectoryDescriptor(root.toString()) ?: return null
|
||||
for (part in parts.dropLast(1)) {
|
||||
opened += openDirectoryDescriptor(procChild(opened.last(), part)) ?: return null
|
||||
}
|
||||
val leafFd = openDescriptor(procChild(opened.last(), parts.last())) ?: return null
|
||||
try {
|
||||
val stat = Os.fstat(leafFd)
|
||||
if (!OsConstants.S_ISREG(stat.st_mode) || stat.st_nlink != 1L) return null
|
||||
// Android's FileInputStream(FileDescriptor) is deliberately not the descriptor owner.
|
||||
FileInputStream(leafFd).use { stream ->
|
||||
invokingBlock = true
|
||||
block(stream.channel)
|
||||
}
|
||||
} finally {
|
||||
runCatching { Os.close(leafFd) }
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
if (invokingBlock) throw error
|
||||
null
|
||||
} finally {
|
||||
opened.asReversed().forEach { runCatching { it.close() } }
|
||||
}
|
||||
}
|
||||
|
||||
private fun openDescriptor(path: String): java.io.FileDescriptor? = runCatching {
|
||||
Os.open(
|
||||
path,
|
||||
OsConstants.O_RDONLY or OsConstants.O_CLOEXEC or OsConstants.O_NOFOLLOW or OsConstants.O_NONBLOCK,
|
||||
0,
|
||||
)
|
||||
}.getOrNull()
|
||||
|
||||
private fun openDirectoryDescriptor(path: String): ParcelFileDescriptor? {
|
||||
val fd = openDescriptor(path) ?: return null
|
||||
return try {
|
||||
if (!OsConstants.S_ISDIR(Os.fstat(fd).st_mode)) return null
|
||||
ParcelFileDescriptor.dup(fd)
|
||||
} finally {
|
||||
runCatching { Os.close(fd) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun procChild(directory: ParcelFileDescriptor, name: String): String =
|
||||
"/proc/self/fd/${directory.fd}/$name"
|
||||
|
||||
private fun copy(input: SeekableByteChannel, output: FileChannel, start: Long, count: Long) {
|
||||
readSource { input.position(start) }
|
||||
var left = count
|
||||
val buffer = ByteBuffer.allocate(64 * 1024)
|
||||
while (left > 0) {
|
||||
buffer.clear()
|
||||
buffer.limit(minOf(buffer.capacity().toLong(), left).toInt())
|
||||
val read = readSource { input.read(buffer) }
|
||||
if (read < 0) break
|
||||
buffer.flip()
|
||||
while (buffer.hasRemaining()) writeStage { output.write(buffer) }
|
||||
left -= read
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyCompleteHead(input: SeekableByteChannel, output: FileChannel, limit: Long) {
|
||||
if (limit <= 0) return
|
||||
copy(input, output, 0, limit)
|
||||
val copied = output.position()
|
||||
readSource { input.position(0) }
|
||||
val buffer = ByteBuffer.allocate(64 * 1024)
|
||||
var scanned = 0L
|
||||
var lastComplete = 0L
|
||||
while (scanned < copied) {
|
||||
buffer.clear()
|
||||
buffer.limit(minOf(buffer.capacity().toLong(), copied - scanned).toInt())
|
||||
val read = readSource { input.read(buffer) }
|
||||
if (read < 0) break
|
||||
buffer.flip()
|
||||
repeat(read) { index ->
|
||||
if (buffer.get(index) == '\n'.code.toByte()) lastComplete = scanned + index + 1
|
||||
}
|
||||
scanned += read
|
||||
}
|
||||
writeStage { output.truncate(lastComplete) }
|
||||
writeStage { output.position(lastComplete) }
|
||||
}
|
||||
|
||||
private fun copyCompleteTail(
|
||||
input: SeekableByteChannel,
|
||||
output: FileChannel,
|
||||
sourceSize: Long,
|
||||
limit: Long,
|
||||
) {
|
||||
if (limit <= 0 || sourceSize <= 0) return
|
||||
var start = (sourceSize - limit).coerceAtLeast(0)
|
||||
if (start > 0) {
|
||||
readSource { input.position(start) }
|
||||
val buffered = BufferedInputStream(Channels.newInputStream(input), COPY_BUFFER_BYTES)
|
||||
while (start < sourceSize) {
|
||||
val value = readSource { buffered.read() }
|
||||
if (value < 0) return
|
||||
start++
|
||||
if (value == '\n'.code) break
|
||||
}
|
||||
}
|
||||
copy(input, output, start, (sourceSize - start).coerceAtMost(limit))
|
||||
}
|
||||
|
||||
private inline fun <T> readSource(block: () -> T): T = try {
|
||||
block()
|
||||
} catch (error: Exception) {
|
||||
throw SourceReadException(error)
|
||||
}
|
||||
|
||||
private inline fun <T> writeStage(block: () -> T): T = try {
|
||||
block()
|
||||
} catch (error: SourceReadException) {
|
||||
throw error
|
||||
} catch (error: StageUnavailableException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
throw StageUnavailableException(error)
|
||||
}
|
||||
|
||||
private fun addManifest(
|
||||
archive: ZipOutputStream,
|
||||
sessionId: String,
|
||||
category: String,
|
||||
records: List<Record>,
|
||||
limits: EnhancedShareLimits,
|
||||
categoryBudget: Long,
|
||||
redactionLearningComplete: Boolean,
|
||||
) {
|
||||
val entries = JSONArray()
|
||||
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
|
||||
entries.put(JSONObject().apply {
|
||||
put("entry", record.entry)
|
||||
put("origin", record.origin)
|
||||
put("status", record.status)
|
||||
put("sourceBytes", record.sourceBytes)
|
||||
put("capturedBytes", record.capturedBytes)
|
||||
record.reason?.let { put("reason", it) }
|
||||
})
|
||||
}
|
||||
if (records.size > MAX_MANIFEST_RECORDS) {
|
||||
entries.put(JSONObject().apply {
|
||||
put("entry", "")
|
||||
put("origin", "manifest")
|
||||
put("status", "omitted")
|
||||
put("reason", "${records.size - MAX_MANIFEST_RECORDS} additional records")
|
||||
})
|
||||
}
|
||||
val manifest = JSONObject().apply {
|
||||
put("schema", 1)
|
||||
put("sessionId", sessionId)
|
||||
put("category", category)
|
||||
put("generatedAtMillis", System.currentTimeMillis())
|
||||
put("redactionLearning", if (redactionLearningComplete) "complete" else "incomplete")
|
||||
put("limits", JSONObject().apply {
|
||||
put("maxFilesPerArchive", limits.maxFilesPerArchive)
|
||||
put("maxDiscoveredFiles", limits.maxDiscoveredFiles)
|
||||
put("maxBytesPerFile", limits.maxBytesPerFile)
|
||||
put("budgetBasis", "raw-input-snapshot-bytes")
|
||||
put("maxRawInputBytesTotal", limits.maxBytesTotal)
|
||||
put("categoryRawInputBudgetBytes", categoryBudget)
|
||||
})
|
||||
put("entries", entries)
|
||||
}.toString(2) + "\n"
|
||||
archive.putNextEntry(ZipEntry("diagnostics-manifest.json"))
|
||||
archive.write(manifest.toByteArray())
|
||||
archive.closeEntry()
|
||||
}
|
||||
|
||||
private fun collect(context: Context, folder: File, maxFiles: Int, legacy: Boolean): CollectionResult {
|
||||
val out = LinkedHashMap<String, Candidate>()
|
||||
val categoryCounts = HashMap<Category, Int>()
|
||||
val perCategory = (maxFiles / Category.values().size).coerceAtLeast(1)
|
||||
var truncated = false
|
||||
var partial = false
|
||||
fun add(
|
||||
file: File,
|
||||
root: File,
|
||||
entry: String,
|
||||
origin: String,
|
||||
forcedCategory: Category? = null,
|
||||
linePrefix: String? = null,
|
||||
) {
|
||||
val safe = safeEntry(entry) ?: return
|
||||
val category = forcedCategory ?: category(entry.removePrefix("${folder.name}/"))
|
||||
if (out.size >= maxFiles || (categoryCounts[category] ?: 0) >= perCategory) {
|
||||
truncated = true
|
||||
return
|
||||
}
|
||||
val anchor = anchorFor(context, root)
|
||||
if (out.putIfAbsent(safe, Candidate(file, anchor, safe, origin, category, linePrefix)) == null) {
|
||||
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
|
||||
}
|
||||
}
|
||||
CRITICAL_SESSION_FILES.forEach { name ->
|
||||
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
|
||||
}
|
||||
File(folder, "session.log").takeIf { it.exists() }?.let { file ->
|
||||
add(
|
||||
file, folder, "${folder.name}/graphics/frame-trace.log", "guest-frame-trace",
|
||||
Category.GRAPHICS, "DROIDDECK_FRAME_TRACE ",
|
||||
)
|
||||
add(
|
||||
file, folder, "${folder.name}/graphics/process-trace.log", "guest-process-trace",
|
||||
Category.GRAPHICS, "DROIDDECK_PROCESS_TRACE ",
|
||||
)
|
||||
add(
|
||||
file, folder, "${folder.name}/games/game-lifecycle.log", "guest-game-lifecycle",
|
||||
Category.GAMES, "DROIDDECK_DIAGNOSTICS event=game_",
|
||||
)
|
||||
}
|
||||
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
|
||||
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
|
||||
val scan = directFiles(steam, remaining(maxFiles, out.size))
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
scan.files.forEach {
|
||||
add(it, steam, "${folder.name}/steam/${it.name}", "live-steam")
|
||||
}
|
||||
}
|
||||
val logs = LinuxRuntime.logDir(context)
|
||||
for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) {
|
||||
val scan = directFiles(root, remaining(maxFiles, out.size))
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
scan.files.asSequence().filter { recent(it) }
|
||||
.forEach { add(it, root, "$name/${it.name}", name) }
|
||||
}
|
||||
if (legacy) {
|
||||
val scan = legacyBattleNet(context)
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
scan.sources.forEach { source ->
|
||||
add(source.file, source.root, source.entry, "battlenet")
|
||||
}
|
||||
} else {
|
||||
battleNetRoots(context).forEach { (prefix, root) ->
|
||||
val scan = walk(root, remaining(maxFiles, out.size))
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
|
||||
.forEach { file ->
|
||||
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
|
||||
add(file, root, "battlenet/$prefix/$relative", "battlenet")
|
||||
}
|
||||
}
|
||||
}
|
||||
val sessionScan = walk(folder, remaining(maxFiles, out.size))
|
||||
truncated = truncated || sessionScan.truncated
|
||||
partial = partial || sessionScan.partial
|
||||
sessionScan.files.forEach { file ->
|
||||
val relative = file.toPath().toAbsolutePath().normalize()
|
||||
.let { folder.toPath().toAbsolutePath().normalize().relativize(it).joinToString("/") }
|
||||
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
|
||||
add(file, folder, "${folder.name}/$relative", "session")
|
||||
}
|
||||
return CollectionResult(out.values.toList(), truncated, partial)
|
||||
}
|
||||
|
||||
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
|
||||
|
||||
private fun walk(root: File, limit: Int): ScanResult {
|
||||
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
|
||||
val files = ArrayList<File>(limit)
|
||||
var truncated = false
|
||||
var partial = false
|
||||
var visited = 0
|
||||
val rootPath = root.toPath()
|
||||
val visitLimit = (limit * 4).coerceAtLeast(limit).coerceAtMost(MAX_DISCOVERY_VISITS)
|
||||
try {
|
||||
Files.walkFileTree(rootPath, object : SimpleFileVisitor<Path>() {
|
||||
private fun countVisit(): FileVisitResult {
|
||||
visited++
|
||||
return if (visited > visitLimit) {
|
||||
truncated = true
|
||||
FileVisitResult.TERMINATE
|
||||
} else FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult =
|
||||
if (dir == rootPath) FileVisitResult.CONTINUE else countVisit()
|
||||
|
||||
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
if (countVisit() == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE
|
||||
if (files.size >= limit) {
|
||||
truncated = true
|
||||
return FileVisitResult.TERMINATE
|
||||
}
|
||||
if (attrs.isRegularFile || Files.isSymbolicLink(file)) files += file.toFile()
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
|
||||
override fun visitFileFailed(file: Path, exc: IOException): FileVisitResult {
|
||||
partial = true
|
||||
return countVisit()
|
||||
}
|
||||
|
||||
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
|
||||
if (exc != null) partial = true
|
||||
return FileVisitResult.CONTINUE
|
||||
}
|
||||
})
|
||||
} catch (_: Exception) {
|
||||
partial = true
|
||||
}
|
||||
return ScanResult(files, truncated, partial)
|
||||
}
|
||||
|
||||
private fun directFiles(root: File, limit: Int): ScanResult {
|
||||
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
|
||||
val files = ArrayList<File>(limit)
|
||||
var truncated = false
|
||||
var partial = false
|
||||
try {
|
||||
Files.newDirectoryStream(root.toPath()).use { entries ->
|
||||
val iterator = entries.iterator()
|
||||
while (iterator.hasNext() && files.size < limit) {
|
||||
val path = iterator.next()
|
||||
if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(path)) {
|
||||
files += path.toFile()
|
||||
}
|
||||
}
|
||||
truncated = iterator.hasNext()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
partial = true
|
||||
}
|
||||
return ScanResult(files, truncated, partial)
|
||||
}
|
||||
|
||||
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
|
||||
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
||||
val data = File(drive, "ProgramData/Battle.net")
|
||||
return listOf(
|
||||
"droiddeck" to File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet"),
|
||||
"client" to File(drive, "users/steamuser/AppData/Local/Battle.net/Logs"),
|
||||
"agent" to File(data, "Agent"),
|
||||
"setup" to File(data, "Setup"),
|
||||
)
|
||||
}
|
||||
|
||||
private fun legacyBattleNet(context: Context): LegacyDiscovery {
|
||||
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
||||
val data = File(drive, "ProgramData/Battle.net")
|
||||
val agent = File(data, "Agent")
|
||||
val setup = File(data, "Setup")
|
||||
val agentChildren = childDirectories(agent, "Agent.")
|
||||
val setupChildren = childDirectories(setup, "")
|
||||
val scans = listOf(
|
||||
legacyNewest(
|
||||
"droiddeck",
|
||||
listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")),
|
||||
2,
|
||||
setOf("battlenet.log", "spawned.log"),
|
||||
),
|
||||
legacyNewest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6),
|
||||
legacyNewest(
|
||||
"agent", listOf(File(agent, "Logs")) + agentChildren.files.map { File(it, "Logs") }, 10,
|
||||
byDir = true,
|
||||
),
|
||||
legacyNewest("setup", setupChildren.files.map { File(it, "Logs") }, 3, byDir = true),
|
||||
)
|
||||
return LegacyDiscovery(
|
||||
scans.flatMap { it.sources },
|
||||
scans.any { it.truncated } || agentChildren.truncated || setupChildren.truncated,
|
||||
scans.any { it.partial } || agentChildren.partial || setupChildren.partial,
|
||||
)
|
||||
}
|
||||
|
||||
private fun legacyNewest(
|
||||
folder: String,
|
||||
roots: List<File>,
|
||||
count: Int,
|
||||
names: Set<String>? = null,
|
||||
byDir: Boolean = false,
|
||||
): LegacyDiscovery {
|
||||
val found = ArrayList<Pair<File, File>>()
|
||||
var truncated = false
|
||||
var partial = false
|
||||
roots.forEach { root ->
|
||||
val scan = directFiles(root, MAX_BATTLENET_SCAN)
|
||||
truncated = truncated || scan.truncated
|
||||
partial = partial || scan.partial
|
||||
found += scan.files.asSequence()
|
||||
.filter { recent(it) && it.name.endsWith(".log") && it.length() <= LEGACY_LOG_MAX_BYTES }
|
||||
.filter { names == null || it.name in names }
|
||||
.map { it to root }
|
||||
.toList()
|
||||
}
|
||||
val ordered = found.sortedByDescending { it.first.lastModified() }
|
||||
return LegacyDiscovery(
|
||||
ordered.take(count).map { (file, root) ->
|
||||
val relative = if (byDir) "$folder/${file.parentFile?.parentFile?.name}/${file.name}" else "$folder/${file.name}"
|
||||
LegacySource(file, root, "battlenet/$relative")
|
||||
},
|
||||
truncated || ordered.size > count,
|
||||
partial,
|
||||
)
|
||||
}
|
||||
|
||||
private fun childDirectories(root: File, prefix: String): ScanResult {
|
||||
if (!root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
|
||||
val found = ArrayList<File>()
|
||||
var truncated = false
|
||||
var partial = false
|
||||
try {
|
||||
Files.newDirectoryStream(root.toPath()).use { entries ->
|
||||
val iterator = entries.iterator()
|
||||
while (iterator.hasNext() && found.size < MAX_BATTLENET_DIRECTORIES) {
|
||||
val path = iterator.next()
|
||||
if (path.fileName.toString().startsWith(prefix) &&
|
||||
Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) found += path.toFile()
|
||||
}
|
||||
truncated = iterator.hasNext()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
partial = true
|
||||
}
|
||||
return ScanResult(found, truncated, partial)
|
||||
}
|
||||
|
||||
private fun recent(file: File): Boolean = file.lastModified() >= System.currentTimeMillis() - RECENT_MILLIS
|
||||
|
||||
private fun anchorFor(context: Context, root: File): File {
|
||||
val path = root.toPath().toAbsolutePath().normalize()
|
||||
for (anchor in listOf(context.filesDir, context.cacheDir)) {
|
||||
if (path.startsWith(anchor.toPath().toAbsolutePath().normalize())) return anchor
|
||||
}
|
||||
return root.parentFile ?: root
|
||||
}
|
||||
|
||||
private fun safeEntry(name: String): String? {
|
||||
if (name.any { it.code < 0x20 || it.code == 0x7f }) return null
|
||||
val normalized = name.replace('\\', '/').trimStart('/')
|
||||
val parts = normalized.split('/')
|
||||
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
|
||||
return parts.joinToString("/") { safeComponent(it) }
|
||||
}
|
||||
|
||||
private fun safeComponent(value: String): String {
|
||||
if (value in KNOWN_COMPONENTS || KNOWN_COMPONENT_PATTERNS.any { it.matches(value) }) return value
|
||||
val suffix = SAFE_SUFFIX.find(value)?.value.orEmpty().lowercase(Locale.US)
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())
|
||||
.take(8).joinToString("") { "%02x".format(Locale.US, it.toInt() and 0xff) }
|
||||
return "entry-$digest$suffix"
|
||||
}
|
||||
|
||||
private fun category(entry: String): Category {
|
||||
val value = entry.lowercase(Locale.US)
|
||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
|
||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
|
||||
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
||||
return Category.SESSION
|
||||
}
|
||||
|
||||
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
|
||||
private val KNOWN_COMPONENTS = setOf(
|
||||
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
|
||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
||||
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
||||
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
||||
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
|
||||
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
||||
)
|
||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
||||
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
||||
Regex("steam-[0-9]+\\.(?:log|txt)"),
|
||||
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
|
||||
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
|
||||
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
|
||||
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
|
||||
)
|
||||
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
|
||||
private val CRITICAL_SESSION_FILES = listOf(
|
||||
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
|
||||
"events.jsonl", "memory.csv", "capture.json", "crash.log",
|
||||
)
|
||||
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
|
||||
private const val COPY_BUFFER_BYTES = 64 * 1024
|
||||
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
|
||||
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||
private const val MAX_BATTLENET_SCAN = 64
|
||||
private const val MAX_BATTLENET_DIRECTORIES = 64
|
||||
private const val MAX_MANIFEST_RECORDS = 512
|
||||
private const val MAX_DISCOVERY_VISITS = 4096
|
||||
}
|
||||
@@ -117,8 +117,7 @@ object GameEnvironmentStore {
|
||||
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
|
||||
json.put(
|
||||
GAME_DEBUG_LOGS,
|
||||
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
|
||||
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
|
||||
gameDebugLogsOverride ?: SessionPrefs.gameDebugLogsEffective(context),
|
||||
)
|
||||
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
|
||||
}
|
||||
|
||||
@@ -48,7 +48,33 @@ object GameStorage {
|
||||
return when {
|
||||
pref == SessionPrefs.GAME_STORAGE_OFF -> null
|
||||
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
|
||||
else -> Option(SessionPrefs.gameStorageLabel(context), pref)
|
||||
else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) }
|
||||
}
|
||||
}
|
||||
|
||||
fun disconnected(context: Context): Boolean {
|
||||
val pref = SessionPrefs.gameStorage(context)
|
||||
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref))
|
||||
}
|
||||
|
||||
internal fun attached(path: File): Boolean =
|
||||
attached(path, runCatching { Environment.getExternalStorageState(path) }.getOrNull())
|
||||
|
||||
internal fun attached(
|
||||
path: File,
|
||||
state: String?,
|
||||
externalStoragePath: Boolean = isExternalStoragePath(path),
|
||||
): Boolean = when {
|
||||
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY -> true
|
||||
externalStoragePath -> false
|
||||
state == Environment.MEDIA_UNKNOWN || state == null -> path.isDirectory || path.parentFile?.isDirectory == true
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun isExternalStoragePath(path: File): Boolean {
|
||||
val absolute = path.absoluteFile.toPath().normalize()
|
||||
return listOf(File("/storage"), File("/mnt/media_rw")).any {
|
||||
absolute.startsWith(it.absoluteFile.toPath().normalize())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.system.Os
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.gpu.DriverBundle
|
||||
import com.droiddeck.launcher.gpu.DriverPairs
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipReleases
|
||||
import com.droiddeck.launcher.gpu.VulkanInfo
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* graphics-report.txt in each session's folder: which graphics path the session drew with and why,
|
||||
* the GPU and its device nodes, the environment the guest got, and at the end what the compositor
|
||||
* said about its driver. Written for a non-Adreno test report, where a black screen otherwise comes
|
||||
* with nothing to read; the Share logs zip takes the whole folder, so it travels with the logs.
|
||||
* Read-only: nothing here opens a GPU node or changes a setting.
|
||||
*/
|
||||
object GraphicsReport {
|
||||
const val FILE = "graphics-report.txt"
|
||||
const val GAMES_DIR = "games"
|
||||
|
||||
/** One file in games/ past this is cut to its first part at the session's end. */
|
||||
private const val GAME_FILE_MAX = 20L * 1024 * 1024
|
||||
/** All of games/ past this loses its oldest launches. */
|
||||
private const val GAMES_TOTAL_MAX = 120L * 1024 * 1024
|
||||
|
||||
/** The guest keys the report repeats: everything that decides which Vulkan driver loads. */
|
||||
private val ENV_PREFIXES = listOf(
|
||||
"VK_", "BL_VK", "BL_DRM", "BL_VKBRIDGE", "VKBRIDGE", "MESA_", "GALLIUM_", "ZINK", "TU_", "PANVK",
|
||||
"DROIDDECK_POWERVR", "DROIDDECK_HYBRIS", "BL_GAME_LOGS", "LIBGL_", "GAMESCOPE_DISABLE", "XWAYLAND",
|
||||
)
|
||||
|
||||
/** Per-game graphics logs and the guest's Vulkan summary: on for a non-Adreno GPU, or by Setup's switch. */
|
||||
fun detailed(context: Context): Boolean = !DeviceSupport.adreno() || SessionPrefs.detailedGraphicsLogs(context)
|
||||
|
||||
/** For finish(), which runs from the session's end without a context of its own. */
|
||||
@Volatile private var appContext: Context? = null
|
||||
|
||||
/** Writes the start of the report; never throws. */
|
||||
fun begin(context: Context, dir: File, guest: List<String>) {
|
||||
appContext = context.applicationContext
|
||||
runCatching { File(dir, FILE).writeText(start(context, guest)) }
|
||||
.onFailure { android.util.Log.w("GraphicsReport", "could not write $FILE", it) }
|
||||
}
|
||||
|
||||
private fun start(context: Context, guest: List<String>): String = buildString {
|
||||
val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
appendLine("== graphics report, session start $time")
|
||||
appendLine("build: ${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
|
||||
appendLine()
|
||||
val gpu = runCatching { GpuInfo.detect() }.getOrNull()
|
||||
appendLine("-- path")
|
||||
appendLine("path: " + path(context))
|
||||
appendLine("driver mode: " + SessionPrefs.gpuDriverMode(context))
|
||||
appendLine("display driver (compositor): " + SessionPrefs.androidDriver(context).ifEmpty {
|
||||
if (DeviceSupport.adreno()) "(auto: bundled Turnip)" else "(auto: the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"})"
|
||||
})
|
||||
val display = SessionPrefs.androidDriver(context)
|
||||
appendLine("display driver chosen by: " + when {
|
||||
display.isEmpty() -> "auto (or a pair on a non-Adreno GPU: the phone's own driver)"
|
||||
DriverBundle.containing(context, display, false) != null -> "pair (its display half)"
|
||||
else -> "user (picked on its own)"
|
||||
})
|
||||
val linux = SessionPrefs.linuxDriver(context)
|
||||
appendLine("runtime driver: " + linux.ifEmpty { "(runtime default)" })
|
||||
if (linux.isNotEmpty()) {
|
||||
val dir = com.droiddeck.launcher.gpu.LinuxVulkanDriverManager(context).getDriverDir(linux)
|
||||
appendLine("runtime driver dir: ${dir.path} (" + (dir.listFiles()?.filter { it.name.endsWith(".so") }?.joinToString { it.name } ?: "missing") + ")")
|
||||
}
|
||||
val prefs = context.getSharedPreferences("graphics_report", Context.MODE_PRIVATE)
|
||||
val previous = prefs.getString("lastDrivers", null)
|
||||
val now = "display ${SessionPrefs.androidDriver(context).ifEmpty { "(auto)" }}, runtime ${linux.ifEmpty { "(default)" }}, bridge ${DeviceSupport.vkBridge(context)}, venus ${VenusComponent.wanted(context)}"
|
||||
appendLine("previous session's drivers: " + (previous ?: "(none recorded)") + if (previous != null && previous != now) " << CHANGED" else "")
|
||||
prefs.edit().putString("lastDrivers", now).apply()
|
||||
DriverBundle.active(context)?.let { b ->
|
||||
appendLine("pair: ${b.name} ${b.version} (bundle ${b.id})")
|
||||
release(context, b.id)?.let { appendLine("pair release: $it") }
|
||||
}
|
||||
if (gpu != null) {
|
||||
val pairs = DriverPairs.from(TurnipReleases.cached(context))
|
||||
appendLine("auto would pick: " + (DriverPairs.recommendedKey(gpu, pairs) ?: "(no pair: system driver or bridge)"))
|
||||
}
|
||||
appendLine("frame generation: " + runCatching { com.droiddeck.launcher.gpu.FrameGen.mode(context).toString() }.getOrDefault("?") +
|
||||
" (engine=off means it is switched off in Play settings; a driver that fails LSFG's gates logs \"device gates\" below)")
|
||||
appendLine("mali bridge setting: " + SessionPrefs.vkBridge(context) + ", in use: " + DeviceSupport.vkBridge(context))
|
||||
val standIn = runCatching { com.droiddeck.launcher.runtime.LinuxRuntime.gpuStandIn(context) }.getOrNull()
|
||||
appendLine("render node for the guest: " + (standIn?.let { node ->
|
||||
com.droiddeck.launcher.runtime.LinuxRuntime.deviceNumbers(node)?.let { n -> "/dev/dri/renderD${n.substringAfter(':')} -> $node ($n)" } ?: node
|
||||
} ?: if (SystemVulkanDriver.isPowerVr()) "the system GPU's own /dev/dri node (#570)" else "none"))
|
||||
appendLine()
|
||||
appendLine("-- gpu")
|
||||
if (gpu != null) {
|
||||
appendLine("family: ${gpu.family} (${gpu.supportText})")
|
||||
appendLine("name: ${gpu.name}" + if (gpu.model > 0) ", model ${gpu.model} (${gpu.modelSource})" else "")
|
||||
}
|
||||
appendLine("vulkan device (app): " + (VulkanInfo.cachedOrNull()?.get("device") ?: "(not probed)"))
|
||||
appendLine("system vulkan hal: " + (SystemVulkanDriver.hal() ?: "none"))
|
||||
read("/sys/class/misc/mali0/device/gpuinfo")?.let { appendLine("mali gpuinfo: $it") }
|
||||
appendLine("android: ${Build.VERSION.RELEASE} (sdk ${Build.VERSION.SDK_INT}), ${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
val soc = if (Build.VERSION.SDK_INT >= 31) "${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}" else Build.HARDWARE
|
||||
appendLine("soc: $soc, board ${Build.BOARD}, hardware ${Build.HARDWARE}")
|
||||
appendLine("kernel: " + (System.getProperty("os.version") ?: "?"))
|
||||
appendLine()
|
||||
appendLine("-- gpu nodes (from the app; not opened)")
|
||||
val dri = File("/dev/dri").list()?.sorted()?.map { "/dev/dri/$it" }.orEmpty()
|
||||
for (path in listOf("/dev/kgsl-3d0", "/dev/mali0") + dri) appendLine(node(path))
|
||||
if (dri.isEmpty()) appendLine("/dev/dri: " + if (File("/dev/dri").exists()) "not listable" else "absent")
|
||||
appendLine()
|
||||
appendLine("-- guest environment (graphics)")
|
||||
guest.filter { e -> ENV_PREFIXES.any { e.startsWith(it) } }.sorted().forEach { appendLine(it) }
|
||||
appendLine()
|
||||
}
|
||||
|
||||
/** Which backend this session's Vulkan goes through, as the session decides it. */
|
||||
private fun path(context: Context): String = when {
|
||||
DeviceSupport.adreno() -> "Turnip (Adreno, KGSL)"
|
||||
VenusComponent.wanted(context) -> "Mali (Venus): Mesa Venus over vtest to the phone's own Vulkan driver, with the Mali compatibility layer"
|
||||
DeviceSupport.vkBridge(context) -> "Mali bridge (#517): the phone's own Vulkan driver through the bridge"
|
||||
DeviceSupport.openDriverActive(context) -> "open driver pair (PanVK / RADV)"
|
||||
SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)) && SystemVulkanDriver.isAvailable() ->
|
||||
"system Vulkan (#570): ${SystemVulkanDriver.gpuName()} driver through libhybris"
|
||||
SessionPrefs.linuxDriver(context).isNotEmpty() -> "imported runtime driver ${SessionPrefs.linuxDriver(context)}"
|
||||
else -> "none for this GPU (no Adreno, no system HAL, no pair, bridge off)"
|
||||
}
|
||||
|
||||
/** The release tag and download a pair bundle came from, when the last release check knows it. */
|
||||
private fun release(context: Context, bundleId: String): String? {
|
||||
val bundles = TurnipReleases.cached(context)?.assets?.filter { it.bundle }.orEmpty()
|
||||
val asset = bundles.firstOrNull { it.name.removeSuffix("-Pair.zip") == bundleId }
|
||||
?: bundles.firstOrNull { bundleId.startsWith(it.name.removeSuffix("-Pair.zip") + "-") }
|
||||
?: return null
|
||||
val installed = TurnipReleases.installedBuiltOn(context, asset)
|
||||
return "${asset.tag} ${asset.url}" +
|
||||
(if (installed.isNotEmpty()) ", installed build uploaded $installed" else "") +
|
||||
(if (asset.builtOn.isNotEmpty()) ", listed build uploaded ${asset.builtOn}" else "") +
|
||||
(if (TurnipReleases.updateAvailable(context, asset)) " << NEWER BUILD AVAILABLE" else "")
|
||||
}
|
||||
|
||||
private fun node(path: String): String {
|
||||
val f = File(path)
|
||||
if (!f.exists()) return "$path: absent"
|
||||
val access = (if (f.canRead()) "r" else "-") + (if (f.canWrite()) "w" else "-")
|
||||
val rdev = runCatching { Os.stat(path).st_rdev }.getOrNull()
|
||||
val numbers = rdev?.let { " ${major(it)}:${minor(it)}" }.orEmpty()
|
||||
val label = runCatching { String(Os.getxattr(path, "security.selinux")).trimEnd('\u0000') }.getOrNull()
|
||||
return "$path: $access$numbers" + (label?.let { " $it" } ?: "")
|
||||
}
|
||||
|
||||
/** Linux's dev_t split (glibc's gnu_dev_major / gnu_dev_minor). */
|
||||
internal fun major(dev: Long): Long = ((dev ushr 8) and 0xfff) or ((dev ushr 32) and 0xfffff000L)
|
||||
internal fun minor(dev: Long): Long = (dev and 0xff) or ((dev ushr 12) and 0xffffff00L)
|
||||
|
||||
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
/** The compositor's driver lines from the app's own log. */
|
||||
private val COMPOSITOR = Regex(
|
||||
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
|
||||
"""graphics driver|display driver|DD_PRESENT_FAULT|SystemVulkan|vkbridge|VkBridge|mali_gralloc|panvk|PanVK|radv|MESA|native buffer|first frame|present|""" +
|
||||
"""lsfg|FrameGen|device gates|AAudio|directaudio|pulse|gralloc|dma.?buf|modifier|import""",
|
||||
RegexOption.IGNORE_CASE,
|
||||
)
|
||||
|
||||
/** The session script's driver lines: what it exported, the bridge's self-test, vulkaninfo, gamescope's Vulkan errors. */
|
||||
private val GUEST = Regex("""== vulkan driver|== vkbridge|== vulkaninfo|vulkan:|panvk|PanVK|radv|primary node|No compatible|DRM format|kbase|AAUDIO|client sink|Xwayland|\(EE\)|glamor|XWAYLAND_NO_GLAMOR""", RegexOption.IGNORE_CASE)
|
||||
|
||||
/**
|
||||
* The end of the report, from the finished folder: the compositor's driver lines out of
|
||||
* app.log, and games/ held to its size limits. Never throws.
|
||||
*/
|
||||
fun finish(dir: File) {
|
||||
runCatching {
|
||||
val report = File(dir, FILE)
|
||||
if (!report.isFile) return
|
||||
val lines = File(dir, "app.log").takeIf { it.isFile }?.useLines { seq -> seq.filter { COMPOSITOR.containsMatchIn(it) }.take(400).toList() }.orEmpty()
|
||||
val games = File(dir, GAMES_DIR).listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty()
|
||||
val guestLines = File(dir, "session.log").takeIf { it.isFile }?.useLines { seq ->
|
||||
seq.filter { GUEST.containsMatchIn(it) }.take(200).toList()
|
||||
}.orEmpty()
|
||||
val fallbackLines = File(dir, "vkbridge-fallback").takeIf { it.isFile }?.readLines()?.map { it.trim() }?.filter { it.isNotEmpty() }
|
||||
val fellBack = fallbackLines?.firstOrNull()
|
||||
val fallbackReason = fallbackLines?.getOrNull(1).orEmpty()
|
||||
runCatching { SessionPrefs.setBridgeFellBack(appContext ?: return@runCatching, fellBack != null, fallbackReason) }
|
||||
val limits = File(dir, "limits.txt").takeIf { it.isFile }?.readText()?.trim()
|
||||
val audio = File(dir, "audio.log").takeIf { it.isFile }?.readText().orEmpty()
|
||||
report.appendText(buildString {
|
||||
limits?.let { appendLine("open files limit: $it") }
|
||||
fellBack?.let {
|
||||
if (fallbackReason == "memory") appendLine("!! MALI BRIDGE FELL BACK: memory sharing = none (no method passed the server's self-test); the session ran on $it")
|
||||
else appendLine("!! MALI BRIDGE FELL BACK: the self-test failed images or draws; the session ran on $it")
|
||||
}
|
||||
com.droiddeck.launcher.wayland.WaylandCompositor.compositorFault().takeIf { it.isNotEmpty() }?.let {
|
||||
appendLine("!! DISPLAY FAILED: $it")
|
||||
}
|
||||
com.droiddeck.launcher.wayland.WaylandCompositor.displayDriver().takeIf { it.isNotEmpty() }?.let {
|
||||
appendLine("display driver (as loaded): $it")
|
||||
}
|
||||
appContext?.let { ctx ->
|
||||
if (SessionPrefs.venus(ctx)) VenusComponent.hostVulkanTooOld(ctx)?.let {
|
||||
appendLine("!! VENUS OFF: the phone's driver reports Vulkan $it; gamescope needs 1.2 or newer, so the session did not use Venus")
|
||||
}
|
||||
}
|
||||
if (audio.contains("AAUDIO_ERROR_DISCONNECTED")) {
|
||||
appendLine("!! SOUND: Android refused the audio output (AAUDIO_ERROR_DISCONNECTED) - rebooting the phone usually fixes this")
|
||||
}
|
||||
if (guestLines.any { it.contains("vkbridge", ignoreCase = true) && it.contains("FAIL") }) {
|
||||
appendLine("!! MALI BRIDGE SELF-TEST FAILED: this GPU's driver did not pass the bridge's checks (see below)")
|
||||
}
|
||||
if (guestLines.any { it.contains("MEM_EXEC_INIT") }) {
|
||||
appendLine("note: kbase refused KBASE_IOCTL_MEM_EXEC_INIT with EPERM. That answer comes from the kbase driver")
|
||||
appendLine(" itself (proot does not filter ioctls; Android's seccomp would kill or return ENOSYS; SELinux")
|
||||
appendLine(" would return EACCES), so it is the kernel's policy for this context, not the session's.")
|
||||
}
|
||||
appendLine("-- driver lines from the session log (${guestLines.size})")
|
||||
guestLines.forEach { appendLine(it) }
|
||||
appendLine()
|
||||
appendLine("-- compositor and driver lines from app.log (${lines.size})")
|
||||
lines.forEach { appendLine(it) }
|
||||
appendLine()
|
||||
appendLine("-- game launches with detailed logs: ${games.size}")
|
||||
games.forEach { appendLine(it.name) }
|
||||
appendLine("== session end " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()))
|
||||
})
|
||||
capGames(File(dir, GAMES_DIR))
|
||||
}.onFailure { android.util.Log.w("GraphicsReport", "could not finish $FILE", it) }
|
||||
}
|
||||
|
||||
/** Cuts each file in [games] to [GAME_FILE_MAX] and drops the oldest launches past [GAMES_TOTAL_MAX]. */
|
||||
internal fun capGames(games: File, fileMax: Long = GAME_FILE_MAX, totalMax: Long = GAMES_TOTAL_MAX) {
|
||||
if (!games.isDirectory) return
|
||||
games.walkTopDown().filter { it.isFile && it.length() > fileMax }.forEach { f ->
|
||||
runCatching { java.io.RandomAccessFile(f, "rw").use { it.setLength(fileMax) } }
|
||||
}
|
||||
val launches = games.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty().toMutableList()
|
||||
fun size(d: File) = d.walkTopDown().filter { it.isFile }.sumOf { it.length() }
|
||||
var total = launches.sumOf { size(it) }
|
||||
while (total > totalMax && launches.size > 1) {
|
||||
val oldest = launches.removeAt(0)
|
||||
total -= size(oldest)
|
||||
FileUtils.delete(oldest)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
var stepText: String? = null
|
||||
var downloadAt = -1
|
||||
var downloadPercent = -1
|
||||
var applyingAt = -1
|
||||
var clientDownloadAt = -1
|
||||
var clientDownload: String? = null
|
||||
var clientPercent = -1
|
||||
@@ -99,10 +100,16 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
val done = m.groupValues[1].toLong()
|
||||
val total = maxOf(1L, m.groupValues[2].toLong())
|
||||
downloadPercent = (done * 100 / total).toInt()
|
||||
} else if (steam && UPDATE_APPLYING.matches(line)) {
|
||||
applyingAt = at
|
||||
}
|
||||
}
|
||||
}
|
||||
return when {
|
||||
applyingAt > stepAt && applyingAt > downloadAt -> Line(
|
||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1,
|
||||
Topic.STEAM, readable = true,
|
||||
)
|
||||
downloadAt > stepAt && downloadPercent >= 0 -> Line(
|
||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
|
||||
Topic.STEAM, readable = true,
|
||||
@@ -151,6 +158,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
|
||||
private const val TAIL_BYTES = 48L * 1024
|
||||
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
|
||||
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""")
|
||||
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
||||
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
|
||||
}
|
||||
|
||||
@@ -11,6 +11,22 @@ object OrphanReaper {
|
||||
|
||||
fun release(pid: Int) { kept.remove(pid) }
|
||||
|
||||
fun hasOtherProcesses(): Boolean = hasOtherProcesses(
|
||||
File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(),
|
||||
) { pid ->
|
||||
try {
|
||||
android.system.Os.kill(pid, 0)
|
||||
true
|
||||
} catch (error: android.system.ErrnoException) {
|
||||
error.errno != android.system.OsConstants.ESRCH && error.errno != android.system.OsConstants.EPERM
|
||||
} catch (error: SecurityException) {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
internal fun hasOtherProcesses(pids: List<Int>?, ownPid: Int, signalable: (Int) -> Boolean): Boolean =
|
||||
pids == null || pids.any { it > 1 && it != ownPid && signalable(it) }
|
||||
|
||||
fun reap(reason: String, matching: (String) -> Boolean = { true }): Int {
|
||||
val me = android.os.Process.myPid()
|
||||
val uid = android.os.Process.myUid()
|
||||
|
||||
@@ -11,4 +11,12 @@ object PipPolicy {
|
||||
height.toDouble() / width > 2.39 -> 100 to 239
|
||||
else -> width to height
|
||||
}
|
||||
|
||||
fun outputSize(width: Int, height: Int, outputWidth: Int, outputHeight: Int): Pair<Int, Int>? {
|
||||
if (width <= 0 || height <= 0 || outputWidth <= 0 || outputHeight <= 0) return null
|
||||
val scale = minOf(width.toFloat() / outputWidth, height.toFloat() / outputHeight)
|
||||
val fittedWidth = ((outputWidth * scale).toInt() and 1.inv()).coerceAtLeast(2)
|
||||
val fittedHeight = ((outputHeight * scale).toInt() and 1.inv()).coerceAtLeast(2)
|
||||
return fittedWidth to fittedHeight
|
||||
}
|
||||
}
|
||||
@@ -502,14 +502,20 @@ object SessionArtifacts {
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes the folders of sessions whose process died without its teardown. Returns true when
|
||||
* the newest of them ended because Android killed the app for memory, so the app can say so
|
||||
* (a game "crashing" on a phone with little free RAM is usually this, not a driver fault).
|
||||
*/
|
||||
@Synchronized
|
||||
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
|
||||
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false): Boolean {
|
||||
val stopWhenSessionStarts = !beforeGuestStart
|
||||
val parent = LinuxRuntime.logDir(context)
|
||||
val abandoned = parent.listFiles { f ->
|
||||
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
|
||||
}?.sortedWith(SessionPaths.chronological) ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
}?.sortedWith(SessionPaths.chronological) ?: return false
|
||||
if (abandoned.isEmpty()) return false
|
||||
var killedForMemory = false
|
||||
val current = SessionPaths.current()
|
||||
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
@@ -534,8 +540,10 @@ object SessionArtifacts {
|
||||
"audio.log, device.txt) were on disk already and are as they were left.\n" +
|
||||
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n" +
|
||||
(if (newest) exitReasons(context) else "")
|
||||
)
|
||||
if (newest && lastExitForMemory(context)) killedForMemory = true
|
||||
}
|
||||
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
|
||||
(runtimeExpired.exists() || !beforeGuestStart) &&
|
||||
@@ -593,7 +601,7 @@ object SessionArtifacts {
|
||||
break
|
||||
}
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
if (beforeGuestStart) return
|
||||
if (beforeGuestStart) break
|
||||
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
|
||||
val marked = markScrubbed(scrubbed)
|
||||
if (scrubbed.deferred) break
|
||||
@@ -604,6 +612,54 @@ object SessionArtifacts {
|
||||
Log.w(TAG, "could not finish $dir", e)
|
||||
}
|
||||
}
|
||||
// Whoever finishes the folder first (the agent provider starts before the activity) leaves
|
||||
// the notice for the launcher to show.
|
||||
if (killedForMemory) SessionPrefs.setMemoryKillNotice(context, true)
|
||||
return killedForMemory
|
||||
}
|
||||
|
||||
/** Android's newest record for this app's main process says it was killed for memory. */
|
||||
private fun lastExitForMemory(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < 30) return false
|
||||
return runCatching {
|
||||
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return false
|
||||
am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
|
||||
.firstOrNull { it.processName == context.packageName }
|
||||
?.reason == android.app.ApplicationExitInfo.REASON_LOW_MEMORY
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun exitReasons(context: Context): String {
|
||||
if (android.os.Build.VERSION.SDK_INT < 30) return ""
|
||||
return runCatching {
|
||||
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return ""
|
||||
val reasons = am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
|
||||
if (reasons.isEmpty()) return ""
|
||||
val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US)
|
||||
buildString {
|
||||
append("\nAndroid's record of how this app's recent processes ended (newest first):\n")
|
||||
reasons.forEach { r ->
|
||||
append(" ${fmt.format(java.util.Date(r.timestamp))} ${r.processName} pid ${r.pid}: reason ${reasonName(r.reason)}, " +
|
||||
"status ${r.status}, importance ${r.importance}, pss ${r.pss / 1024} MB, rss ${r.rss / 1024} MB" +
|
||||
(r.description?.let { " - $it" } ?: "") + "\n")
|
||||
}
|
||||
}
|
||||
}.getOrDefault("")
|
||||
}
|
||||
|
||||
private fun reasonName(reason: Int): String = when (reason) {
|
||||
android.app.ApplicationExitInfo.REASON_LOW_MEMORY -> "LOW_MEMORY (killed for memory)"
|
||||
android.app.ApplicationExitInfo.REASON_SIGNALED -> "SIGNALED"
|
||||
android.app.ApplicationExitInfo.REASON_CRASH -> "CRASH"
|
||||
android.app.ApplicationExitInfo.REASON_CRASH_NATIVE -> "CRASH_NATIVE"
|
||||
android.app.ApplicationExitInfo.REASON_ANR -> "ANR"
|
||||
android.app.ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> "EXCESSIVE_RESOURCE_USAGE"
|
||||
android.app.ApplicationExitInfo.REASON_USER_REQUESTED -> "USER_REQUESTED"
|
||||
android.app.ApplicationExitInfo.REASON_USER_STOPPED -> "USER_STOPPED"
|
||||
android.app.ApplicationExitInfo.REASON_EXIT_SELF -> "EXIT_SELF"
|
||||
android.app.ApplicationExitInfo.REASON_DEPENDENCY_DIED -> "DEPENDENCY_DIED"
|
||||
android.app.ApplicationExitInfo.REASON_OTHER -> "OTHER"
|
||||
else -> reason.toString()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
|
||||
@@ -40,10 +40,12 @@ object SessionFiles {
|
||||
WinComponents.publish(context)
|
||||
val files = arrayOf(
|
||||
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
|
||||
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
|
||||
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
|
||||
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
|
||||
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
|
||||
"usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat",
|
||||
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
|
||||
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
@@ -71,6 +73,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
||||
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
|
||||
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
|
||||
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
|
||||
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
|
||||
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
|
||||
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
|
||||
@@ -141,6 +144,8 @@ object SessionFiles {
|
||||
"usr/local/lib/mangoapp/libtraceevent.so.1",
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
val xclipse = listOf("libVkLayer_droiddeck_xclipse.so", "VkLayer_droiddeck_xclipse.json")
|
||||
.map { "usr/local/lib/droiddeck-xclipse/$it" }
|
||||
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||
@@ -164,12 +169,22 @@ object SessionFiles {
|
||||
val gpuLoad = listOf(
|
||||
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
|
||||
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
|
||||
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
|
||||
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_vram_cap.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json",
|
||||
)
|
||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
||||
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||
// The Mali compatibility layer (tools/venus/layer, David Cimo): an implicit Vulkan layer that
|
||||
// fills in the features DXVK requires and Mali lacks. Idle outside Wine and on GPUs that have them.
|
||||
// Never staged on an Adreno: an implicit layer is loaded into every Vulkan program there.
|
||||
val maliCompat = if (com.droiddeck.launcher.core.DeviceSupport.adreno()) emptyList() else listOf(
|
||||
"usr/local/lib/droiddeck-mali/libVkLayer_droiddeck_mali_compat.so",
|
||||
"usr/local/share/vulkan/implicit_layer.d/VkLayer_droiddeck_mali_compat.json",
|
||||
).map { it to it }
|
||||
val optional = (arrayOf(
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/bin/droiddeck-glprobe" to "usr/local/bin/droiddeck-glprobe",
|
||||
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
|
||||
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
|
||||
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
|
||||
@@ -178,7 +193,7 @@ object SessionFiles {
|
||||
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
|
||||
) + mangoapp + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
|
||||
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -11,14 +11,12 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
import java.util.ArrayList
|
||||
|
||||
object SessionLogShare {
|
||||
data class Details(val sizeBytes: Long, val modifiedAt: Long)
|
||||
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
var progress by mutableStateOf<Float?>(null)
|
||||
@@ -35,86 +33,55 @@ object SessionLogShare {
|
||||
}, "share-logs").start()
|
||||
}
|
||||
|
||||
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
|
||||
fun latest(context: Context): File? = sessions(context).lastOrNull()
|
||||
|
||||
fun sessions(context: Context): List<File> {
|
||||
val current = SessionPaths.current()?.takeIf { it.isDirectory && SessionPaths.isSessionFolder(it) }
|
||||
return (SessionPaths.sessionFolders(context) + listOfNotNull(current))
|
||||
.distinctBy { it.absoluteFile.toPath().normalize().toString() }
|
||||
.sortedWith(SessionPaths.chronological)
|
||||
}
|
||||
|
||||
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
|
||||
if (!folder.isDirectory) return null
|
||||
val files = folder.walkTopDown().filter { it.isFile }
|
||||
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
|
||||
if (files.isEmpty()) return null
|
||||
val out = shareDir(context).apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
val live = liveSteamLogs(context, folder)
|
||||
val logs = LinuxRuntime.logDir(context)
|
||||
val stores = recent(File(logs, STORES_DIR))
|
||||
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
|
||||
val battleNet = battleNetLogs(context)
|
||||
val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L)
|
||||
var done = 0L
|
||||
var shown = -1
|
||||
fun advance(f: File) {
|
||||
done += f.length()
|
||||
val percent = (done * 100 / total).toInt()
|
||||
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
|
||||
fun details(folder: File): Details {
|
||||
var size = 0L
|
||||
var modified = folder.lastModified()
|
||||
folder.walkTopDown().filter { it.isFile }.forEach { file ->
|
||||
size += file.length()
|
||||
modified = maxOf(modified, file.lastModified())
|
||||
}
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).invariantSeparatorsPath, f); advance(f) }
|
||||
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
|
||||
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
|
||||
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
|
||||
battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) }
|
||||
}
|
||||
return zip
|
||||
return Details(size, modified)
|
||||
}
|
||||
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
|
||||
z.putNextEntry(ZipEntry(name))
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubForShare(f, w)
|
||||
w.flush()
|
||||
z.closeEntry()
|
||||
fun deleteSession(context: Context, folder: File): Boolean {
|
||||
if (runCatching { SessionPaths.current()?.canonicalFile == folder.canonicalFile }.getOrDefault(false)) return false
|
||||
val knownSession = runCatching { folder.canonicalFile }.getOrNull() in sessions(context).mapNotNull { runCatching { it.canonicalFile }.getOrNull() }
|
||||
return knownSession && folder.isDirectory && folder.deleteRecursively()
|
||||
}
|
||||
|
||||
private fun liveSteamLogs(context: Context, folder: File): List<File> {
|
||||
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
|
||||
val logs = File(SessionPrefs.activeSteamRoot(context), "logs")
|
||||
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
|
||||
fun prepareEnhanced(context: Context, folder: () -> File?, done: (List<File>) -> Unit) {
|
||||
if (progress != null) return
|
||||
progress = 0f
|
||||
Thread({
|
||||
val zips = runCatching {
|
||||
folder()?.let { dir ->
|
||||
EnhancedSessionLogShare.create(context, dir, onProgress = { p ->
|
||||
main.post { if (progress != null) progress = p }
|
||||
})
|
||||
}.orEmpty()
|
||||
}.onFailure { Log.w("SessionLogShare", "could not package enhanced diagnostics", it) }
|
||||
.getOrDefault(emptyList())
|
||||
main.post { progress = null; done(zips) }
|
||||
}, "share-diagnostics").start()
|
||||
}
|
||||
|
||||
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||
|
||||
fun zipFolder(context: Context, folder: File, out: File = shareDir(context), onProgress: ((Float) -> Unit)? = null): File? {
|
||||
return EnhancedSessionLogShare.createLegacy(context, folder, onProgress, out)
|
||||
}
|
||||
|
||||
const val STORES_DIR = "stores"
|
||||
private const val RECENT_DAYS = 7
|
||||
|
||||
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
|
||||
|
||||
private const val BATTLENET_DIR = "battlenet"
|
||||
|
||||
private fun battleNetLogs(context: Context): List<Pair<String, File>> {
|
||||
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
|
||||
val data = File(drive, "ProgramData/Battle.net")
|
||||
fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") }
|
||||
return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) +
|
||||
newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) +
|
||||
newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) +
|
||||
newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true)
|
||||
}
|
||||
|
||||
private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> {
|
||||
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
|
||||
return dirs.flatMap { dir ->
|
||||
dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList()
|
||||
}.sortedByDescending { it.lastModified() }.take(count).map { f ->
|
||||
(if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f
|
||||
}
|
||||
}
|
||||
|
||||
private fun recent(dir: File): List<File> {
|
||||
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
|
||||
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
|
||||
}
|
||||
internal fun shareDir(context: Context): File = File(context.cacheDir, "share")
|
||||
|
||||
fun clear(context: Context) {
|
||||
shareDir(context).deleteRecursively()
|
||||
@@ -131,4 +98,19 @@ object SessionLogShare {
|
||||
send.clipData = ClipData.newRawUri(zip.name, uri)
|
||||
return Intent.createChooser(send, context.getString(R.string.logshare_chooser)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
|
||||
fun shareEnhancedIntent(context: Context, zips: List<File>): Intent {
|
||||
require(zips.isNotEmpty())
|
||||
val uris = ArrayList(zips.map { FileProvider.getUriForFile(context, context.packageName + ".logs", it) })
|
||||
val send = Intent(Intent.ACTION_SEND_MULTIPLE)
|
||||
.setType("application/zip")
|
||||
.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
|
||||
.putExtra(Intent.EXTRA_SUBJECT, zips.first().name.substringBeforeLast('-'))
|
||||
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
send.clipData = ClipData.newUri(context.contentResolver, zips.first().name, uris.first()).also { clip ->
|
||||
for (i in 1 until uris.size) clip.addItem(ClipData.Item(uris[i]))
|
||||
}
|
||||
return Intent.createChooser(send, context.getString(R.string.logshare_chooser))
|
||||
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,8 @@ object SessionPaths {
|
||||
@Synchronized
|
||||
fun beginOrCurrent(context: Context, label: String? = null): File {
|
||||
dir?.let { if (it.isDirectory) return it }
|
||||
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
|
||||
val enhanced = EnhancedDiagnostics.isArmed(context)
|
||||
val parent = if (SessionPrefs.logsEnabled(context) || enhanced) SessionFiles.logDirectory(context)
|
||||
else File(context.cacheDir, "session-logs")
|
||||
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
|
||||
val last = parent.listFiles()?.mapNotNull { f ->
|
||||
@@ -36,9 +37,13 @@ object SessionPaths {
|
||||
var number = last + 1
|
||||
var made = File(parent, "$day-${"%02d".format(Locale.US, number)}-$what")
|
||||
while (made.exists()) made = File(parent, "$day-${"%02d".format(Locale.US, ++number)}-$what")
|
||||
EnhancedDiagnostics.clearRecordFor(context, made)
|
||||
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
|
||||
dir = made
|
||||
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
|
||||
if (enhanced && !EnhancedDiagnostics.consumeInto(context, made)) {
|
||||
Log.e(TAG, "could not activate enhanced diagnostics for $made")
|
||||
}
|
||||
Log.i(TAG, "session logs: $made" + if (parent == SessionFiles.logDirectory(context)) "" else " (logs off: discarded at the end)")
|
||||
return made
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
@@ -504,6 +506,17 @@ object SessionPrefs {
|
||||
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun ensurePowerVrAutoDrivers(context: Context) {
|
||||
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return
|
||||
ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
|
||||
}
|
||||
|
||||
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
|
||||
if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
|
||||
prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
|
||||
}
|
||||
|
||||
fun gpuAutoInstalled(context: Context): Set<String> =
|
||||
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
|
||||
|
||||
@@ -775,8 +788,62 @@ object SessionPrefs {
|
||||
@JvmStatic
|
||||
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
|
||||
|
||||
fun venus(context: Context): Boolean = prefs(context).getBoolean("venus", false)
|
||||
|
||||
fun hostVulkanApi(context: Context): String = prefs(context).getString("hostVulkanApi", "").orEmpty()
|
||||
|
||||
fun setHostVulkanApi(context: Context, api: String) {
|
||||
if (api != hostVulkanApi(context)) prefs(context).edit().putString("hostVulkanApi", api).apply()
|
||||
}
|
||||
|
||||
fun bridgeFellBack(context: Context): Boolean = prefs(context).getBoolean("bridgeFellBack", false)
|
||||
|
||||
fun bridgeFellBackForMemory(context: Context): Boolean = prefs(context).getString("bridgeFallbackReason", "") == "memory"
|
||||
|
||||
fun setBridgeFellBack(context: Context, on: Boolean, reason: String = "") {
|
||||
prefs(context).edit().putBoolean("bridgeFellBack", on).putString("bridgeFallbackReason", if (on) reason else "").apply()
|
||||
}
|
||||
|
||||
fun steamGpuCompositing(context: Context): Boolean {
|
||||
if (!steamGpuCompositingAllowed()) {
|
||||
if (prefs(context).getBoolean("steamGpuCompositing", false))
|
||||
prefs(context).edit().putBoolean("steamGpuCompositing", false).apply()
|
||||
return false
|
||||
}
|
||||
return prefs(context).getBoolean("steamGpuCompositing", false)
|
||||
}
|
||||
|
||||
fun steamGpuCompositingAllowed(): Boolean =
|
||||
!com.droiddeck.launcher.core.DeviceSupport.adreno() && !com.droiddeck.launcher.core.DeviceSupport.mali()
|
||||
|
||||
fun setSteamGpuCompositing(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("steamGpuCompositing", on && steamGpuCompositingAllowed()).apply()
|
||||
}
|
||||
|
||||
fun takeMemoryKillNotice(context: Context): Boolean {
|
||||
val on = prefs(context).getBoolean("memoryKillNotice", false)
|
||||
if (on) prefs(context).edit().putBoolean("memoryKillNotice", false).apply()
|
||||
return on
|
||||
}
|
||||
|
||||
fun setMemoryKillNotice(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("memoryKillNotice", on).apply()
|
||||
}
|
||||
|
||||
fun maliFallbackByAuto(context: Context): String = prefs(context).getString("maliFallbackByAuto", "").orEmpty()
|
||||
|
||||
fun maliFallbackKnown(context: Context): Boolean = prefs(context).contains("maliFallbackByAuto")
|
||||
|
||||
fun setMaliFallbackByAuto(context: Context, route: String) {
|
||||
prefs(context).edit().putString("maliFallbackByAuto", route).apply()
|
||||
}
|
||||
|
||||
fun setVenus(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("venus", on).apply()
|
||||
}
|
||||
|
||||
fun setVkBridge(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("vkBridge", on).apply()
|
||||
prefs(context).edit().putBoolean("vkBridge", on).putBoolean("bridgeFellBack", false).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@@ -786,6 +853,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
|
||||
|
||||
fun setVkBridgeSafe(context: Context, on: Boolean) {
|
||||
@@ -824,7 +892,7 @@ object SessionPrefs {
|
||||
key = "logs",
|
||||
oldValue = logsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
|
||||
newEffective = gameDebugLogsEffective(context, on, gameDebugLogsEnabled(context)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -837,7 +905,7 @@ object SessionPrefs {
|
||||
key = "gameDebugLogsEnabled",
|
||||
oldValue = gameDebugLogsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
|
||||
newEffective = gameDebugLogsEffective(context, logsEnabled(context), on),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -850,8 +918,7 @@ object SessionPrefs {
|
||||
): Boolean {
|
||||
if (oldValue == newValue) return true
|
||||
val saved = prefs(context)
|
||||
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
|
||||
SessionPaths.currentSessionLogsRetained(context)
|
||||
val oldEffective = gameDebugLogsEffective(context)
|
||||
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
|
||||
if (oldEffective == newEffective) {
|
||||
if (saved.edit().putBoolean(key, newValue).commit()) return true
|
||||
@@ -887,6 +954,20 @@ object SessionPrefs {
|
||||
}
|
||||
}
|
||||
|
||||
fun detailedGraphicsLogs(context: Context): Boolean =
|
||||
prefs(context).getBoolean("detailedGraphicsLogs", false)
|
||||
|
||||
fun setDetailedGraphicsLogs(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("detailedGraphicsLogs", on).apply()
|
||||
}
|
||||
|
||||
internal fun gameDebugLogsEffective(
|
||||
context: Context,
|
||||
logs: Boolean = logsEnabled(context),
|
||||
gameLogs: Boolean = gameDebugLogsEnabled(context),
|
||||
): Boolean = EnhancedDiagnostics.isCurrentSessionActive(context) ||
|
||||
(logs && gameLogs && SessionPaths.currentSessionLogsRetained(context))
|
||||
|
||||
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
|
||||
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
@@ -405,6 +406,7 @@ class SessionService : Service() {
|
||||
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
|
||||
SessionLogCapture.stopFor(dir)
|
||||
try {
|
||||
GraphicsReport.finish(dir)
|
||||
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
|
||||
} finally {
|
||||
SessionPaths.release(this, dir)
|
||||
@@ -424,6 +426,21 @@ class SessionService : Service() {
|
||||
return lines
|
||||
}
|
||||
|
||||
/** Whether a kernel release ("6.1.157-android14-11") is older than [major].[minor]; false if unreadable. */
|
||||
internal fun kernelBefore(release: String, major: Int, minor: Int): Boolean {
|
||||
val m = Regex("""^(\d+)\.(\d+)""").find(release) ?: return false
|
||||
val (a, b) = m.destructured
|
||||
return a.toInt() < major || (a.toInt() == major && b.toInt() < minor)
|
||||
}
|
||||
|
||||
/** Whether the newest finished session's log shows Xwayland itself crashing. */
|
||||
private fun lastXwaylandCrashed(): Boolean = runCatching {
|
||||
val last = SessionPaths.sessionFolders(this).filter { it != SessionPaths.current() }.lastOrNull() ?: return false
|
||||
val log = File(last, "session.log").takeIf { it.isFile } ?: return false
|
||||
log.useLines { lines -> lines.any { it.contains("(EE) Segmentation fault") } } &&
|
||||
log.useLines { lines -> lines.any { it.contains("X11 I/O error") || it.contains("Xwayland", ignoreCase = true) } }
|
||||
}.getOrDefault(false)
|
||||
|
||||
private fun tuDebugOverride(): String? = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH)
|
||||
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }?.takeIf { it.isNotEmpty() }
|
||||
|
||||
@@ -435,6 +452,13 @@ class SessionService : Service() {
|
||||
|
||||
|
||||
private fun runSession(gen: Int) {
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(this)
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
|
||||
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
|
||||
if (SessionPrefs.venus(this)) VenusComponent.hostVulkanTooOld(this)?.let {
|
||||
Log.w(TAG, "venus: off for this session - the phone's driver reports Vulkan $it and gamescope needs 1.2 or newer; the session uses the PanVK pair or the bridge")
|
||||
}
|
||||
}
|
||||
SessionTerminal.clear()
|
||||
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)
|
||||
try {
|
||||
@@ -452,10 +476,19 @@ class SessionService : Service() {
|
||||
val stillStarting = { gen == sessionGen && SessionState.running }
|
||||
val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting)
|
||||
val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting)
|
||||
val systemVulkan = SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))
|
||||
val powerVrPack = !systemVulkan || (stillStarting() && AddonPack.POWERVR.await(this, stillStarting))
|
||||
if (!stillStarting()) {
|
||||
Log.i(TAG, "session stopped while add-on packs were downloading")
|
||||
return
|
||||
}
|
||||
if (!powerVrPack) {
|
||||
val message = getString(R.string.session_powervr_missing)
|
||||
Log.e(TAG, "powervr pack unavailable; the system graphics runtime cannot be prepared")
|
||||
failSession(gen, "POWERVR_MISSING", message, -1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
if (!directAudioPack) {
|
||||
Log.w(TAG, "directaudio pack unavailable; game audio drivers will not be staged")
|
||||
mainHandler.post {
|
||||
@@ -476,7 +509,21 @@ class SessionService : Service() {
|
||||
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
|
||||
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
||||
.getOrDefault(emptyList())
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
try {
|
||||
if (systemVulkan) {
|
||||
SystemVulkanDriver.prepare(this)
|
||||
if (!stillStarting()) {
|
||||
Log.i(TAG, "session stopped while the system graphics runtime was unpacking")
|
||||
return
|
||||
}
|
||||
pruneSystemVulkanRuntime()
|
||||
}
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "Could not prepare the session graphics runtime", error)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
SessionArtifacts.awaitCollections()
|
||||
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
|
||||
VacDiagnostics.arm(this)
|
||||
@@ -512,18 +559,32 @@ class SessionService : Service() {
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
.onFailure { Log.w(TAG, "forced components", it) }
|
||||
}
|
||||
addClientEnvironment(guest, steamHere, agentEnvironment)
|
||||
try {
|
||||
addClientEnvironment(guest, steamHere, agentEnvironment)
|
||||
} catch (e: IllegalStateException) {
|
||||
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
|
||||
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
|
||||
val fastPathAt = guest.size
|
||||
|
||||
val pulse = startAudio(guest, sessionDir, directAudioPack)
|
||||
startVkBridge(guest, sessionDir)
|
||||
if (VenusComponent.wanted(this)) {
|
||||
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
|
||||
}
|
||||
if (steamHere) {
|
||||
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
|
||||
encoder.attach(this)
|
||||
components.add(encoder)
|
||||
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
|
||||
}
|
||||
startVkBridge(guest, sessionDir)
|
||||
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "clocks.log")).let {
|
||||
it.attach(this)
|
||||
components.add(it)
|
||||
}
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
@@ -540,6 +601,7 @@ class SessionService : Service() {
|
||||
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||
guest.add("BL_LOG=" + sessionLog.path)
|
||||
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
|
||||
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
|
||||
|
||||
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
|
||||
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
||||
@@ -569,6 +631,10 @@ class SessionService : Service() {
|
||||
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
|
||||
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
|
||||
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
|
||||
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
|
||||
if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1")
|
||||
GraphicsReport.begin(this, sessionDir, guest)
|
||||
val shellGuest = ArrayList(guest).apply {
|
||||
add("SHELL=/bin/bash")
|
||||
add("TERM=xterm-256color")
|
||||
@@ -668,7 +734,14 @@ class SessionService : Service() {
|
||||
if (gen == sessionGen) components.clear()
|
||||
return
|
||||
}
|
||||
components.forEach { it.start() }
|
||||
try {
|
||||
components.forEach { it.start() }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Could not start the session components", e)
|
||||
failSession(gen, "COMPONENT_START_FAILED", e.message ?: "Session component could not be started", -1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
|
||||
val line = command.joinToString(" ") {
|
||||
it.replace("\\", "\\\\").replace(" ", "\\ ")
|
||||
@@ -768,6 +841,7 @@ class SessionService : Service() {
|
||||
SessionState.sessionId = sessionDir.name
|
||||
SessionState.eventsFile = File(sessionDir, "events.jsonl")
|
||||
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
|
||||
if (EnhancedDiagnostics.isActive(this, sessionDir)) SessionEvents.record("diagnostics.enhanced", mapOf("schema" to 1))
|
||||
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
|
||||
NetworkReport.write(this, File(sessionDir, "network.txt"))
|
||||
SessionLogCapture.start(File(sessionDir, "app.log"))
|
||||
@@ -810,7 +884,12 @@ class SessionService : Service() {
|
||||
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
|
||||
guest.add("GALLIUM_DRIVER=zink")
|
||||
guest.add("LIBGL_KOPPER_DRI2=true")
|
||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
val venus = VenusComponent.wanted(this)
|
||||
if (venus) {
|
||||
VenusComponent.guestEnv(this).forEach { guest.add(it) }
|
||||
} else {
|
||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
}
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this)
|
||||
SessionState.runtimeDriver = linuxDriverId
|
||||
com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting(
|
||||
@@ -819,11 +898,39 @@ class SessionService : Service() {
|
||||
?: SessionPrefs.androidDriver(this),
|
||||
linuxDriverId,
|
||||
)
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
val bridge = com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)
|
||||
if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) {
|
||||
SystemVulkanDriver.addEnvironment(this, guest)
|
||||
}
|
||||
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
|
||||
guest.add("XWAYLAND_NO_GLAMOR=1")
|
||||
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
|
||||
}
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) guest.add("BL_RAISE_NOFILE=1")
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
|
||||
val kernel = System.getProperty("os.version").orEmpty()
|
||||
val old = kernelBefore(kernel, 6, 6)
|
||||
val maliNode = LinuxRuntime.gpuStandIn(this) == LinuxRuntime.MALI_DEVICE
|
||||
if (old || maliNode) {
|
||||
guest.add("GAMESCOPE_DISABLE_EXPLICIT_SYNC=1")
|
||||
Log.i(TAG, "gamescope: explicit sync off (" + (if (old) "kernel $kernel has no SYNCOBJ_EVENTFD" else "Mali stand-in node has no syncobjs") + ")")
|
||||
}
|
||||
}
|
||||
if (!bridge && com.droiddeck.launcher.core.DeviceSupport.openDriverActive(this)) {
|
||||
if (SessionPrefs.steamGpuCompositing(this)) {
|
||||
Log.i(TAG, "steam: GPU web compositing (Setup's \"Steam interface: GPU drawing\")")
|
||||
} else {
|
||||
guest.add("BL_STEAM_SOFT_COMPOSITING=1")
|
||||
Log.i(TAG, "steam: software web compositing for the open driver pair (GPU raster kept)")
|
||||
}
|
||||
guest.add("BL_OPEN_DRIVER=1")
|
||||
LinuxRuntime.gpuStandIn(this)?.takeIf { it == LinuxRuntime.MALI_DEVICE }?.let { guest.add("BL_DRM_STANDIN=$it") }
|
||||
}
|
||||
val tuOverride = tuDebugOverride()
|
||||
val tuDriver = sysmemDriver(linuxDriverId)
|
||||
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
|
||||
if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
|
||||
if (SessionPrefs.zinkLazy(this)) {
|
||||
guest.add("ZINK_DESCRIPTORS=lazy")
|
||||
guest.add("ZINK_DEBUG=compact")
|
||||
@@ -872,20 +979,17 @@ class SessionService : Service() {
|
||||
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
|
||||
}
|
||||
|
||||
private fun noSteamGame(): Boolean =
|
||||
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
|
||||
|
||||
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
|
||||
val socket = File(filesDir, "vkbridge/server.sock")
|
||||
val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log"))
|
||||
bridge.attach(this)
|
||||
components.add(bridge)
|
||||
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "vkbridge-clocks.log")).let {
|
||||
it.attach(this)
|
||||
components.add(it)
|
||||
}
|
||||
guest.add("BL_VKBRIDGE=1")
|
||||
if (SessionPrefs.steamGpuCompositing(this)) guest.add("BL_STEAM_GPU_COMPOSITING=1")
|
||||
SessionPrefs.linuxDriver(this).takeIf { it.isNotEmpty() }
|
||||
?.let { runCatching { LinuxVulkanDriver.resolveIcdPath(this, it) }.getOrNull() }
|
||||
?.let { guest.add("BL_VKBRIDGE_FALLBACK_ICD=$it") }
|
||||
guest.add("VKBRIDGE_SOCKET=" + socket.path)
|
||||
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
|
||||
guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this))
|
||||
@@ -895,6 +999,8 @@ class SessionService : Service() {
|
||||
}
|
||||
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket")
|
||||
}
|
||||
private fun noSteamGame(): Boolean =
|
||||
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
|
||||
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
|
||||
val wantsDirectAudio = directAudioPack &&
|
||||
@@ -1832,6 +1938,12 @@ class SessionService : Service() {
|
||||
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
|
||||
}
|
||||
|
||||
/** Background-only: preserve old runtimes until all earlier guest processes are gone. */
|
||||
private fun pruneSystemVulkanRuntime() {
|
||||
runCatching { SystemVulkanDriver.pruneUnused(this, !OrphanReaper.hasOtherProcesses()) }
|
||||
.onFailure { Log.w(TAG, "could not prune unused system Vulkan runtimes", it) }
|
||||
}
|
||||
|
||||
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
|
||||
mainHandler.post {
|
||||
try {
|
||||
@@ -1971,10 +2083,12 @@ class SessionService : Service() {
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
killGuestLeftovers()
|
||||
pruneSystemVulkanRuntime()
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
}, "session-teardown").start()
|
||||
} else {
|
||||
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
|
||||
Thread({
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
|
||||
@@ -23,7 +23,7 @@ object SettingsReset {
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import java.io.PrintWriter
|
||||
|
||||
/**
|
||||
* Vulkan for the session on a Mali, through Venus (the "Mali (Venus)" route; by David Cimo,
|
||||
* DavidCimo/droiddeck-mali, ported to this branch).
|
||||
*
|
||||
* The guest's processes are glibc and cannot load the vendor's bionic driver. Instead they load
|
||||
* Mesa's Venus ICD (libvulkan_virtio.so), which serializes every Vulkan call over a unix socket to
|
||||
* virglrenderer's vtest server. The server runs here, on the Android side, and replays the calls
|
||||
* on the device's own Vulkan driver. Both ends of the socket are under the app's files directory,
|
||||
* which the session binds at its own path, so the same path works inside and out.
|
||||
*/
|
||||
class VenusComponent(private val logFile: File?) : SessionPart() {
|
||||
@Volatile private var pid = -1
|
||||
|
||||
override fun start() {
|
||||
val context = app()
|
||||
stageIcd(context)
|
||||
val libDir = context.applicationInfo.nativeLibraryDir
|
||||
val socket = socket(context)
|
||||
socket.delete()
|
||||
val env = arrayOf(
|
||||
"LD_LIBRARY_PATH=$libDir",
|
||||
// vtest forks a render server per client; this is where its executable is.
|
||||
"RENDER_SERVER_EXEC_PATH=$libDir/libvirgl_render_server.so",
|
||||
"TMPDIR=" + context.cacheDir.path,
|
||||
)
|
||||
val command = "$libDir/libvirgl_test_server.so --venus --no-virgl --socket-path " + socket.path
|
||||
val out = logFile?.let { runCatching { PrintWriter(java.io.FileWriter(it, true)) }.getOrNull() }
|
||||
pid = HostProcess.start(command, env, context.filesDir, { status ->
|
||||
Log.w(TAG, "vtest server exited: $status")
|
||||
out?.let { synchronized(it) { it.println("vtest server exited: $status"); it.flush() } }
|
||||
}, { line ->
|
||||
Log.i(TAG, line)
|
||||
out?.let { synchronized(it) { it.println(line); it.flush() } }
|
||||
})
|
||||
Log.i(TAG, "vtest server pid $pid on $socket")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
if (pid > 1) Process.killProcess(pid)
|
||||
pid = -1
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "Venus"
|
||||
private const val ASSET = "venus/libvulkan_virtio.so"
|
||||
private const val DIR = "venus"
|
||||
private const val LIB = "libvulkan_virtio.so"
|
||||
private const val ICD = "virtio_icd.json"
|
||||
|
||||
/**
|
||||
* The selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an
|
||||
* Adreno nor one the system-driver route covers (PowerVR, Xclipse), and the apk carries it.
|
||||
* It then replaces the Mali bridge and any open driver pair for the session.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun wanted(context: Context): Boolean =
|
||||
!DeviceSupport.adreno() && !com.droiddeck.launcher.gpu.SystemVulkanDriver.isAvailable() &&
|
||||
SessionPrefs.venus(context) && available(context) && hostVulkanTooOld(context) == null
|
||||
|
||||
/** The phone driver's Vulkan version when it is below 1.2: gamescope skips such a device, so Venus cannot run. */
|
||||
@JvmStatic
|
||||
fun hostVulkanTooOld(context: Context): String? {
|
||||
val api = com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull()?.get("api") ?: SessionPrefs.hostVulkanApi(context)
|
||||
val parts = api.split('.').mapNotNull { it.trim().toIntOrNull() }
|
||||
if (parts.size < 2) return null
|
||||
return api.takeIf { parts[0] < 1 || (parts[0] == 1 && parts[1] < 2) }
|
||||
}
|
||||
|
||||
/** Whether this apk carries the Venus component (tools/venus, venus.tzst). */
|
||||
@JvmStatic
|
||||
fun available(context: Context): Boolean = runCatching {
|
||||
context.assets.list(DIR)?.contains(LIB) == true &&
|
||||
File(context.applicationInfo.nativeLibraryDir, "libvirgl_test_server.so").isFile
|
||||
}.getOrDefault(false)
|
||||
|
||||
@JvmStatic
|
||||
fun socket(context: Context): File = File(File(context.filesDir, DIR), "vtest.sock")
|
||||
|
||||
/** What the guest needs to find the ICD and the server. */
|
||||
@JvmStatic
|
||||
fun guestEnv(context: Context): List<String> {
|
||||
val dir = File(context.filesDir, DIR)
|
||||
return listOf(
|
||||
"VK_ICD_FILENAMES=" + File(dir, ICD).path,
|
||||
"VN_DEBUG=vtest",
|
||||
"VTEST_SOCKET_NAME=" + socket(context).path,
|
||||
// Xwayland has no DRI3 without a DRM node, so swapchains present through shared memory.
|
||||
"MESA_VK_WSI_DEBUG=sw",
|
||||
// The Mali compatibility layer in every process but gamescope, not only Wine: Zink
|
||||
// (Steam's GL, Xwayland's glamor) requires robustness2's nullDescriptor, which the
|
||||
// layer stands in for. The session script checks it and falls back to llvmpipe.
|
||||
"DROIDDECK_MALI_COMPAT=1",
|
||||
"BL_VENUS=1",
|
||||
// gamescope's composite layout without immutable YCbCr samplers from the start
|
||||
// (patch 0930): a Mali-G615 refused every composite pipeline with them, and testing
|
||||
// that through Venus took the render server down.
|
||||
"GAMESCOPE_NO_YCBCR_SAMPLERS=1",
|
||||
)
|
||||
}
|
||||
|
||||
/** Copies the ICD out of the APK when it changed, and writes its manifest with an absolute path. */
|
||||
private fun stageIcd(context: Context) {
|
||||
val dir = File(context.filesDir, DIR).apply { mkdirs() }
|
||||
val lib = File(dir, LIB)
|
||||
// Copied again after every app update: the asset is compressed, so its size is unknown up front.
|
||||
val installed = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime
|
||||
if (!lib.isFile || lib.lastModified() < installed) {
|
||||
val tmp = File(dir, "$LIB.tmp")
|
||||
context.assets.open(ASSET).use { input -> tmp.outputStream().use { input.copyTo(it) } }
|
||||
if (!tmp.renameTo(lib)) throw java.io.IOException("could not move the Venus ICD into place")
|
||||
Log.i(TAG, "staged $lib (${lib.length()} bytes)")
|
||||
}
|
||||
if (!FileUtils.writeString(
|
||||
File(dir, ICD),
|
||||
"""{"file_format_version":"1.0.1","ICD":{"library_path":"${lib.path}","api_version":"1.4.354"}}""",
|
||||
)) throw java.io.IOException("could not write the Venus ICD manifest")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ object WinComponents {
|
||||
private const val MSI_CACHE = "$STORE/.packages"
|
||||
private val PROTON_PROVIDES = setOf("gecko", "mono", "cjkfonts", "powershell", "VulkanRT")
|
||||
private val NESTED_KEYS = setOf("url", "file_name", "file_checksum", "file_size")
|
||||
private val installLock = Any()
|
||||
|
||||
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
|
||||
|
||||
@@ -61,7 +62,7 @@ object WinComponents {
|
||||
class Component(
|
||||
val name: String, val description: String, val provider: String, val status: String,
|
||||
val dependencies: List<String>, val steps: List<Step>,
|
||||
val snapshot: String = "",
|
||||
val snapshot: String = "", val revision: Int = 0,
|
||||
)
|
||||
|
||||
enum class Support { READY, NEEDS_INSTALLER, UNSUPPORTED }
|
||||
@@ -127,7 +128,7 @@ object WinComponents {
|
||||
name, o.optString("description"), o.optString("provider"), o.optString("status"),
|
||||
(0 until deps.length()).map { deps.getString(it) }.filter { validId(it) },
|
||||
(0 until steps.length()).map { steps.getJSONObject(it).let { s -> Step(s.optString("action"), s) } },
|
||||
o.optString("snapshot"),
|
||||
o.optString("snapshot"), o.optInt("revision", 0).coerceAtLeast(0),
|
||||
)
|
||||
}
|
||||
if (listed.any { it.name == VCREDIST_ARM64 }) listed else listed + builtInArm64Runtime()
|
||||
@@ -170,15 +171,31 @@ object WinComponents {
|
||||
else -> true
|
||||
}
|
||||
|
||||
fun installed(context: Context, id: String): String? = runCatching {
|
||||
JSONObject(File(LinuxRuntime.rootDir(context), "$STORE/$id/component.json").readText()).optString("version", "?")
|
||||
internal fun installedVersion(directory: File, revision: Int): String? = runCatching {
|
||||
val meta = JSONObject(File(directory, "component.json").readText())
|
||||
if (meta.optInt("revision", 0) < revision) null else meta.optString("version", "?")
|
||||
}.getOrNull()
|
||||
|
||||
fun installedIds(context: Context): List<String> =
|
||||
File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
|
||||
.orEmpty().map { it.name }.filter { installed(context, it) != null }.sorted()
|
||||
fun installed(context: Context, id: String): String? = installedVersion(
|
||||
File(LinuxRuntime.rootDir(context), "$STORE/$id"), cached(context)?.firstOrNull { it.name == id }?.revision ?: 0,
|
||||
)
|
||||
|
||||
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
|
||||
internal fun downloadedIds(store: File): List<String> =
|
||||
store.listFiles { f -> f.isDirectory && validId(f.name) }.orEmpty()
|
||||
.filter { installedVersion(it, 0) != null }.map { it.name }.sorted()
|
||||
|
||||
fun downloadedIds(context: Context): List<String> = downloadedIds(File(LinuxRuntime.rootDir(context), STORE))
|
||||
|
||||
fun installedIds(context: Context): List<String> {
|
||||
val revisions = cached(context).orEmpty().associate { it.name to it.revision }
|
||||
return File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
|
||||
.orEmpty().filter { installedVersion(it, revisions[it.name] ?: 0) != null }.map { it.name }.sorted()
|
||||
}
|
||||
|
||||
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? =
|
||||
synchronized(installLock) { installLocked(context, c, all, onProgress) }
|
||||
|
||||
private fun installLocked(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
|
||||
if (support(c, all) != Support.READY) return "${c.name} cannot be installed here yet"
|
||||
val order = ArrayList<Component>()
|
||||
fun visit(x: Component, depth: Int) {
|
||||
@@ -353,7 +370,7 @@ object WinComponents {
|
||||
val version = msi?.optString("version")?.takeIf { it.isNotEmpty() }
|
||||
?: Regex("""\b(\d+\.\d+(\.\d+)*)\b""").find(c.description)?.value ?: "catalog"
|
||||
val meta = JSONObject()
|
||||
.put("id", c.name).put("version", version)
|
||||
.put("id", c.name).put("version", version).put("revision", c.revision)
|
||||
.put("overrides", JSONArray(overrides.distinct()))
|
||||
.put("requires", JSONArray(c.dependencies))
|
||||
msi?.let { meta.put("kind", it.optString("kind", "msi")).put("product", it.optString("product")).put("notes", it.optJSONArray("notes") ?: JSONArray()) }
|
||||
@@ -556,8 +573,7 @@ object WinComponents {
|
||||
matches.forEach { f -> f.copyTo(File(dest, f.name.lowercase()), overwrite = true) }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun uninstall(context: Context, id: String) {
|
||||
fun uninstall(context: Context, id: String) = synchronized(installLock) {
|
||||
require(validId(id))
|
||||
FileUtils.delete(File(LinuxRuntime.rootDir(context), "$STORE/$id"))
|
||||
save(context, selections(context).mapValues { (_, sel) -> Selection(sel.auto - id, sel.user - id) })
|
||||
|
||||
Reference in new issue
Block a user