mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40358e3b02 | ||
|
|
3cc5787d99 | ||
|
|
d8b05a8b30 | ||
|
|
525843c56c | ||
|
|
fa17d909ce | ||
|
|
5d276ab461 | ||
|
|
0859268591 | ||
|
|
20b0358162 | ||
|
|
65ebefc38f |
No files matched your search
@@ -16,7 +16,7 @@ object DeviceInfo {
|
||||
val vk = VulkanInfo.query()
|
||||
val gpu = GpuInfo.detect()
|
||||
return listOf(
|
||||
chip(), gpu(context, gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
chip(), gpu(context, gpu), npu(context), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
).filter { it.rows.isNotEmpty() }
|
||||
}
|
||||
|
||||
@@ -51,6 +51,10 @@ object DeviceInfo {
|
||||
add("Family", read("/sys/devices/soc0/family"))
|
||||
})
|
||||
|
||||
private fun npu(context: Context) = Section("NPU", NpuInfo.rows(
|
||||
NpuInfo.detect(context.applicationInfo.nativeLibraryDir?.let(::File)),
|
||||
))
|
||||
|
||||
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||
add("GPU", gpu.name)
|
||||
add("Family", gpu.family.label(gpu.name))
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** What this device's Qualcomm Hexagon NPU would offer a neural upscaler, and whether the app can reach it. */
|
||||
object NpuInfo {
|
||||
enum class Hexagon(val arch: String, val vtcmMb: Int) {
|
||||
V68("v68", 4), V69("v69", 4), V73("v73", 4), V75("v75", 8), V79("v79", 8), V81("v81", 8),
|
||||
}
|
||||
|
||||
enum class Access { OPEN, BROKERED, NO_NODE, DENIED }
|
||||
|
||||
data class Status(
|
||||
val hexagon: Hexagon?,
|
||||
val node: String?,
|
||||
val access: Access,
|
||||
val qnnRuntime: Boolean,
|
||||
) {
|
||||
val usable: Boolean get() = hexagon != null && (access == Access.OPEN || access == Access.BROKERED) && qnnRuntime
|
||||
}
|
||||
|
||||
private val BY_MODEL = mapOf(
|
||||
"SM8350" to Hexagon.V68, "SM8450" to Hexagon.V69, "SM8475" to Hexagon.V69,
|
||||
"SM8550" to Hexagon.V73, "QCS8550" to Hexagon.V73, "SM8650" to Hexagon.V75,
|
||||
"SM8750" to Hexagon.V79, "SM8850" to Hexagon.V81,
|
||||
)
|
||||
private val BY_PLATFORM = mapOf(
|
||||
"lahaina" to Hexagon.V68, "taro" to Hexagon.V69, "cape" to Hexagon.V69, "kalama" to Hexagon.V73,
|
||||
"pineapple" to Hexagon.V75, "sun" to Hexagon.V79, "canoe" to Hexagon.V81,
|
||||
)
|
||||
|
||||
// The compute DSP is the one that runs HTP graphs; /dev/adsprpc-smd is the pre-5.x name of the same service.
|
||||
internal val NODES = listOf("/dev/fastrpc-cdsp", "/dev/adsprpc-smd", "/dev/cdsprpc-smd")
|
||||
// Qualcomm's dspservice hands an app a FastRPC fd over binder when the node itself is closed to apps.
|
||||
internal const val DSP_SERVICE_MANIFEST = "/vendor/etc/vintf/manifest/vendor.qti.hardware.dsp-service.xml"
|
||||
internal val QNN_LIBS = listOf("libQnnHtp.so", "libQnnSystem.so")
|
||||
|
||||
fun hexagon(
|
||||
model: String = SocNames.model(),
|
||||
platform: String = GpuInfo.systemProperty("ro.board.platform"),
|
||||
): Hexagon? = BY_MODEL[SocNames.normalizedModel(model)] ?: BY_PLATFORM[platform.trim().lowercase()]
|
||||
|
||||
/** `canWrite` is access(2) for the app's own uid, so it answers for DAC but not SELinux. */
|
||||
internal fun access(nodes: List<File>, broker: File = File(DSP_SERVICE_MANIFEST)): Pair<File?, Access> {
|
||||
val present = nodes.firstOrNull { it.exists() } ?: return null to Access.NO_NODE
|
||||
val access = when {
|
||||
present.canRead() && present.canWrite() -> Access.OPEN
|
||||
broker.exists() -> Access.BROKERED
|
||||
else -> Access.DENIED
|
||||
}
|
||||
return present to access
|
||||
}
|
||||
|
||||
fun detect(nativeLibDir: File?, hexagon: Hexagon? = hexagon()): Status {
|
||||
val (node, access) = access(NODES.map(::File))
|
||||
val qnn = nativeLibDir != null && QNN_LIBS.all { File(nativeLibDir, it).exists() }
|
||||
return Status(hexagon, node?.path, access, qnn)
|
||||
}
|
||||
|
||||
fun rows(status: Status): List<Pair<String, String>> = buildList {
|
||||
add("Hexagon" to (status.hexagon?.let { "${it.arch} (${it.vtcmMb} MB VTCM)" } ?: "not recognised"))
|
||||
add("FastRPC node" to when (status.access) {
|
||||
Access.NO_NODE -> "none found"
|
||||
Access.OPEN -> "${status.node} (app can open it)"
|
||||
Access.BROKERED -> "${status.node} (closed to apps; the DSP service can hand over a descriptor)"
|
||||
Access.DENIED -> "${status.node} (app cannot open it)"
|
||||
})
|
||||
add("QNN runtime" to if (status.qnnRuntime) "bundled" else "not bundled")
|
||||
add("Neural upscaling" to if (status.usable) "possible" else "not available")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** Finds the processes a session left running, also once proot is gone and they belong to init. */
|
||||
object GuestLeftovers {
|
||||
private const val MARKER = "DD_DEBUG_DIR="
|
||||
|
||||
fun find(rootfs: String, ended: File?, skip: Set<Int>): Set<Int> {
|
||||
val marker = ended?.let { MARKER + it.path }
|
||||
val parents = HashMap<Int, Int>()
|
||||
val matched = HashSet<Int>()
|
||||
File("/proc").listFiles { f -> f.name.all { it.isDigit() } }?.forEach { proc ->
|
||||
val pid = proc.name.toIntOrNull() ?: return@forEach
|
||||
parentOf(proc)?.let { parents[pid] = it }
|
||||
if (pid in skip) return@forEach
|
||||
val exe = runCatching { File(proc, "exe").canonicalPath }.getOrNull()
|
||||
// proot runs a guest through its loader, which is then the process's executable
|
||||
if (exe?.startsWith(rootfs) == true ||
|
||||
marker != null && carries(runCatching { File(proc, "environ").readBytes() }.getOrNull(), marker)) {
|
||||
matched.add(pid)
|
||||
}
|
||||
}
|
||||
return withDescendants(matched, parents) - skip
|
||||
}
|
||||
|
||||
internal fun carries(environ: ByteArray?, marker: String): Boolean {
|
||||
if (environ == null) return false
|
||||
val wanted = marker.toByteArray()
|
||||
var start = 0
|
||||
while (start < environ.size) {
|
||||
var end = start
|
||||
while (end < environ.size && environ[end] != 0.toByte()) end++
|
||||
if (end - start == wanted.size && (0 until wanted.size).all { environ[start + it] == wanted[it] }) return true
|
||||
start = end + 1
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
internal fun withDescendants(roots: Set<Int>, parents: Map<Int, Int>): Set<Int> {
|
||||
val out = HashSet(roots)
|
||||
var grew = true
|
||||
while (grew) {
|
||||
grew = false
|
||||
for ((pid, ppid) in parents) if (pid > 1 && ppid in out && out.add(pid)) grew = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun parentOf(proc: File): Int? {
|
||||
val stat = runCatching { File(proc, "stat").readText() }.getOrNull() ?: return null
|
||||
return stat.substringAfterLast(") ").split(' ').getOrNull(1)?.toIntOrNull()
|
||||
}
|
||||
}
|
||||
@@ -1888,21 +1888,11 @@ class SessionService : Service() {
|
||||
File(directory, STEAM_GAME_REQUEST + ".tmp").delete()
|
||||
}
|
||||
|
||||
private fun killGuestLeftovers() {
|
||||
val me = android.os.Process.myPid()
|
||||
private fun killGuestLeftovers(ended: File?) {
|
||||
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
|
||||
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
|
||||
val spared = OrphanReaper.spared()
|
||||
var killed = 0
|
||||
for (proc in procs) {
|
||||
val pid = proc.name.toIntOrNull() ?: continue
|
||||
if (pid == me || pid in spared) continue
|
||||
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
|
||||
if (!exe.startsWith(rootfs)) continue
|
||||
android.os.Process.killProcess(pid)
|
||||
killed++
|
||||
}
|
||||
if (killed > 0) Log.w(TAG, "killed $killed guest process(es) proot no longer tracked")
|
||||
val leftovers = GuestLeftovers.find(rootfs, ended, OrphanReaper.spared() + android.os.Process.myPid())
|
||||
leftovers.forEach { android.os.Process.killProcess(it) }
|
||||
if (leftovers.isNotEmpty()) Log.w(TAG, "killed ${leftovers.size} guest process(es) proot no longer tracked")
|
||||
}
|
||||
|
||||
private fun killStragglers() {
|
||||
@@ -2388,7 +2378,7 @@ class SessionService : Service() {
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
killGuestLeftovers()
|
||||
killGuestLeftovers(ended)
|
||||
pruneSystemVulkanRuntime()
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class NpuInfoTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun modelPicksTheHexagonGenerationAndFallsBackToThePlatform() {
|
||||
assertEquals(NpuInfo.Hexagon.V79, NpuInfo.hexagon("SM8750", "sun"))
|
||||
assertEquals(NpuInfo.Hexagon.V81, NpuInfo.hexagon("QTI SM8850", ""))
|
||||
assertEquals(NpuInfo.Hexagon.V73, NpuInfo.hexagon("", "Kalama"))
|
||||
assertNull(NpuInfo.hexagon("MT6989", "mt6989"))
|
||||
}
|
||||
|
||||
@Test fun nodeAccessSeparatesMissingFromDenied() {
|
||||
assertEquals(NpuInfo.Access.NO_NODE, NpuInfo.access(listOf(File(tmp.root, "nope"))).second)
|
||||
val node = tmp.newFile("fastrpc-cdsp")
|
||||
assertEquals(NpuInfo.Access.OPEN, NpuInfo.access(listOf(File(tmp.root, "nope"), node)).second)
|
||||
node.setWritable(false)
|
||||
val absent = File(tmp.root, "no-broker")
|
||||
if (!node.canWrite()) {
|
||||
assertEquals(NpuInfo.Access.DENIED, NpuInfo.access(listOf(node), absent).second)
|
||||
assertEquals(NpuInfo.Access.BROKERED, NpuInfo.access(listOf(node), tmp.newFile("dsp-service.xml")).second)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun usableNeedsChipNodeAndRuntime() {
|
||||
val ok = NpuInfo.Status(NpuInfo.Hexagon.V79, "/dev/fastrpc-cdsp", NpuInfo.Access.OPEN, true)
|
||||
assertTrue(ok.usable)
|
||||
assertTrue(ok.copy(access = NpuInfo.Access.BROKERED).usable)
|
||||
assertFalse(ok.copy(access = NpuInfo.Access.DENIED).usable)
|
||||
assertFalse(ok.copy(qnnRuntime = false).usable)
|
||||
assertFalse(ok.copy(hexagon = null).usable)
|
||||
}
|
||||
|
||||
@Test fun runtimeIsBundledOnlyWhenEveryLibraryIsPresent() {
|
||||
NpuInfo.QNN_LIBS.dropLast(1).forEach { File(tmp.root, it).createNewFile() }
|
||||
assertFalse(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
|
||||
File(tmp.root, NpuInfo.QNN_LIBS.last()).createNewFile()
|
||||
assertTrue(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GuestLeftoversTest {
|
||||
private fun environ(vararg entries: String) = entries.joinToString("\u0000", postfix = "\u0000").toByteArray()
|
||||
|
||||
@Test
|
||||
fun aProcessOfTheEndedSessionCarriesItsFolder() {
|
||||
val marker = "DD_DEBUG_DIR=/data/logs/2026-11-28-85-steam"
|
||||
assertTrue(GuestLeftovers.carries(environ("HOME=/home/deck", marker, "TERM=xterm"), marker))
|
||||
assertTrue(GuestLeftovers.carries(environ(marker), marker))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anotherSessionsFolderOrALongerPathIsNotTheEndedSession() {
|
||||
val marker = "DD_DEBUG_DIR=/data/logs/2026-11-28-85-steam"
|
||||
assertFalse(GuestLeftovers.carries(environ("DD_DEBUG_DIR=/data/logs/2026-11-28-86-steam"), marker))
|
||||
assertFalse(GuestLeftovers.carries(environ("$marker-2"), marker))
|
||||
assertFalse(GuestLeftovers.carries(environ("X$marker"), marker))
|
||||
assertFalse(GuestLeftovers.carries(null, marker))
|
||||
assertFalse(GuestLeftovers.carries(ByteArray(0), marker))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatAMatchedProcessStartedGoesWithIt() {
|
||||
// 10 was proot's child and now belongs to init; 12 cleared its environment; 20 is unrelated
|
||||
val parents = mapOf(10 to 1, 11 to 10, 12 to 11, 13 to 12, 20 to 1, 21 to 20)
|
||||
assertEquals(setOf(10, 11, 12, 13), GuestLeftovers.withDescendants(setOf(10), parents))
|
||||
assertEquals(emptySet<Int>(), GuestLeftovers.withDescendants(emptySet(), parents))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
# Neural upscaling on the Hexagon NPU
|
||||
|
||||
Reference: [Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale), a Winlator fork that
|
||||
runs AMD FSR 4 on the Qualcomm Hexagon HTP through QNN, with GPU (DP4a) FSR 4 / XeSS / FSR 3.1 fallbacks. This note
|
||||
records what carries over to DroidDeck, what does not, and what has been built so far.
|
||||
|
||||
## How the reference works
|
||||
|
||||
A Vulkan layer in the game's process intercepts the game's own upscaler calls (FSR 2/3/4, DLSS through an NGX
|
||||
bridge, XeSS) via replacement DLLs. Those calls hand over colour, depth, motion vectors, exposure and jitter. The
|
||||
layer runs the FSR 4 network (INT8, compiled on the device by `libQnnHtpPrepare.so`) on the NPU, with Vulkan passes
|
||||
before and after it and `AHardwareBuffer` for the hand-off.
|
||||
|
||||
## What carries over, what does not
|
||||
|
||||
| Piece | In DroidDeck |
|
||||
|---|---|
|
||||
| Game-side hook (DLL replacement, NGX/FFX bridges) | The guest runs Steam under FEX and Proton, so the same Windows-side bridge DLLs could apply, but nothing in the repo loads them yet. |
|
||||
| Temporal inputs (depth, motion vectors, jitter) | Only exist inside the guest. The Wayland compositor (`waylandcomp`, where FSR 1 / SGSR / frame generation run) sees a finished colour frame, so FSR 4 cannot run there. A compositor-side network would have to be a spatial-only super-resolution model, a different thing from FSR 4. |
|
||||
| QNN runtime and skel libraries | Qualcomm's, not redistributable here. They would come from the user's own QAIRT SDK or a runtime download. |
|
||||
| FSR 4 weights | AMD's. The reference ships them in its APK; DroidDeck should not copy them without a licence check. |
|
||||
| DP4a GPU path | Independent of the NPU and the most portable part. Needs the same guest-side hook. |
|
||||
|
||||
## Findings: the NPU is reachable from an unprivileged app
|
||||
|
||||
Tested on the Retroid Pocket Duo (SM8750, Hexagon v79) and the AYANEO Pocket FIT Elite (SM8750P, stock, no root).
|
||||
|
||||
**The node is closed, but there is a supported way around it.**
|
||||
|
||||
- `/dev/fastrpc-cdsp` is `0664 system:system` and the two `-secure` nodes are `0644`. A real app uid (checked with
|
||||
`run-as` as uid 10185) fails `access(W_OK)`. This is Qualcomm's own `ueventd` setting, not an OEM quirk.
|
||||
- Qualcomm's `libcdsprpc.so` is not loadable by an app on this firmware: `libcdsprpc.so` and even `libOpenCL.so` fail
|
||||
with "not found" from an app namespace, with or without `<uses-native-library>`, and a copy would need private
|
||||
system libraries (`libutils`, `libhidlbase`, `libcutils`). So QNN stubs that `dlopen("libcdsprpc.so")` fail today.
|
||||
- The vendor AIDL service `vendor.qti.hardware.dsp.IDspService/default` (process `dspservice`, uid `system`) opens
|
||||
the node on behalf of callers. From the app, `AServiceManager_checkService` returns it,
|
||||
`getNewDSPSession(int)` returns an `IDspManager`, and `openSession(DSPDomain)` returns a `FastrpcDev` whose
|
||||
`NativeHandle` carries an open descriptor for `/dev/fastrpc-cdsp`. `readlink` on it gives `/dev/fastrpc-cdsp`.
|
||||
- On that descriptor, from the app: `FASTRPC_IOCTL_GET_DSP_INFO` (`_IOWR('R', 13, ...)`) succeeds and reports
|
||||
unsigned-PD support (attribute 1 = 1). `FASTRPC_IOCTL_INIT_ATTACH` returns `EACCES`, and the kernel logs "untrusted
|
||||
app trying to attach to privileged DSP PD". That is the expected outcome: an app must create an unsigned PD
|
||||
(`INIT_CREATE`) instead of attaching to the root PD.
|
||||
|
||||
Wire format that worked (transaction codes are the AIDL order): `IDspService` 1 = `getNewDSPSession(int)`;
|
||||
`IDspManager` 2 = `openSession`. The `in DSPDomain` argument is written as `[1 (non-null)][size][domain]`; domain 3 is
|
||||
the compute DSP. The reply is `[status][1][size][int][int][NativeHandle: size, fd count, fds, int count]`.
|
||||
`tools/experiments/npu-fastrpc-probe` reproduces all of it; results go to logcat tag `NPUPROBE`.
|
||||
|
||||
### AYN Thor (QCS8550, Hexagon v73, Android 13, release-keys): closed
|
||||
|
||||
- `/dev/adsprpc-smd` is `0664 system:system` and `open(O_RDWR)` from an app gives `EACCES`. There is no
|
||||
`/dev/fastrpc-cdsp`.
|
||||
- There is no `IDspService` here. `checkService` returns null, and SELinux logs a `find` denial for
|
||||
`untrusted_app` on `default_android_service`.
|
||||
- `dlopen("libcdsprpc.so")` fails with "not found" even with `<uses-native-library>` declared.
|
||||
- So no route was found on this device without root. SELinux is enforcing here, which is the case the 8 Elite tests
|
||||
could not cover.
|
||||
|
||||
### How BananaNative's PR (moceure/BananaNative #703) gets in
|
||||
|
||||
It declares `<uses-native-library android:name="libcdsprpc.so" android:required="false"/>`, then
|
||||
`dlopen("libcdsprpc.so")`, `remote_handle_control(4, {domain 3, enable 1})` to request an unsigned PD, and an
|
||||
`ADSP_LIBRARY_PATH` that puts the app's own `adsp` directory first so the DSP can load the HTP skel from the app.
|
||||
That only works on firmware that exposes the vendor library to apps; its logs are from a Xiaomi phone on a v81 SoC.
|
||||
It does not work on the three Qualcomm-reference style builds tried here (Duo, FIT Elite, Thor), where the library is
|
||||
invisible to app namespaces. Useful from it, if the NPU path goes ahead: a process-wide ref-counted QNN HTP runtime
|
||||
shared by two users, zero-copy `AHardwareBuffer` DMA-BUF registration, a thermal power tier (turbo, balanced, low)
|
||||
with hysteresis, and clamping the ADPF target duration to the frame-generated output period so the PowerHAL does not
|
||||
halve a 2x frame-generated game. Its MIT-licensed GLSL for flow, splat and blend is a possible reference for DD-FG.
|
||||
Its QNN graph binaries come from a companion repo; where they derive from is a licence question.
|
||||
|
||||
Caveats:
|
||||
|
||||
- SELinux is permissive on both devices (dev-keys builds). On an enforcing production build, `untrusted_app` may not
|
||||
be allowed to find `IDspService`, and that has not been tried.
|
||||
- Nothing has run on the NPU yet. A descriptor and a capability query are not a graph execution.
|
||||
- The reference fork does not need any of this on devices where the node is world-writable.
|
||||
|
||||
## vk-fsr4 (han39835/vk-fsr4, GPL-3.0): FSR 4 INT8 on the GPU, no NPU
|
||||
|
||||
An implicit Vulkan layer plus a drop-in replacement for AMD's `amd_fidelityfx_upscaler_vk` provider. It runs FSR 4.1.2
|
||||
as INT8 compute shaders on any Vulkan GPU with `shaderInt8` and `shaderIntegerDotProduct` (DP4a), and keeps the
|
||||
cooperative-matrix FP8 path for RDNA 3/4. Aimed at AMD and Linux, but nothing in the INT8 path is vendor specific.
|
||||
|
||||
- **Assets:** 31 MB of precompiled SPIR-V for INT8 (1080, 2160 and 4320 tiers, each in `native` and `ultraperf`) plus
|
||||
quantised weights. The DXIL from AMD's DLL was converted to SPIR-V at build time with `dxil-spirv`, which is not
|
||||
linked into the provider. The tools to repeat that are in the repo (`tools/extract`, `tools/convert`).
|
||||
- **Two entry points.** As an FFX provider, games that already call FSR 3/4 through the FFX API get FSR 4 with the
|
||||
game's own motion vectors, depth and jitter: the exact inputs, and the most robust option. As a layer without the
|
||||
API (`F4_MV=1`), it guesses which descriptor holds the motion vectors by fingerprinting Unreal TSR layouts. The
|
||||
author says other engines "may or may not match", so only the provider mode is worth building on.
|
||||
- **Licence, checked:** the author's claim that the 4.1.2 DLL is MIT licensed holds up. AMD's FidelityFX SDK 2.4.0
|
||||
`license.md` starts with a restrictive default (binary-only redistribution, no reverse engineering) "except as noted
|
||||
below". It then lists the files "subject to" an MIT licence, and that list includes
|
||||
`signedbin/amd_fidelityfx_upscaler_dx12.dll` and `amd_fidelityfx_upscaler_vk.dll`. So the 4.1.x shaders and weights
|
||||
are redistributable with the MIT notice, which removes the AMD half of the earlier licence concern for that version.
|
||||
Which SDK version a given weights file came from still has to be pinned (the repo pins 4.1.2.4555 by SHA-256).
|
||||
Qualcomm's QNN libraries are a separate matter. This is a reading of the licence file, not legal advice.
|
||||
- **Frame generation:** FSR 4.0.2 ML frame generation is bundled but needs RDNA 4 WMMA, so it is not usable here.
|
||||
- **Fit with DroidDeck:** GPL-3.0, same as DroidDeck. The provider route would sit in the guest, in front of
|
||||
vkd3d-proton, where the game's FFX calls arrive. It needs no NPU access, so it works on the Thor.
|
||||
- **Risk to check first:** the INT8 plan marks most passes `require_wave32`. Adreno runs 64 or 128 wide waves, so
|
||||
either the passes can run at those widths or they need the variants the Winlator fork's Adreno path uses
|
||||
(`dvj5411/fsr4vk`). Also unmeasured: INT8 FSR 4 on a handheld GPU may cost more than it saves at 1080p to 4K.
|
||||
|
||||
## Built so far
|
||||
|
||||
- `gpu/NpuInfo.kt`: maps the SoC model or board platform to a Hexagon generation (v68 to v81, with the VTCM size the
|
||||
reference caps `vtcmSizeInMB` to), checks whether the app's uid can open the FastRPC node (or the DSP service that
|
||||
can hand it over), and whether the QNN libraries are bundled. Shown as an "NPU" section in Device info.
|
||||
- `NpuInfoTest`.
|
||||
|
||||
## Next steps, in order
|
||||
|
||||
1. Create an unsigned PD on the brokered descriptor (`INIT_CREATE`, with the DSP-side `fastrpc_shell_unsigned_3`) and
|
||||
invoke one remote call. Qualcomm's open-source userspace library (`quic/fastrpc`, BSD-3) implements this; it would
|
||||
be built as the app's own `libcdsprpc.so`, with the device open replaced by the binder call above. QNN stubs
|
||||
resolve `libcdsprpc.so` from the app's library directory, so they would pick it up unchanged.
|
||||
2. Run a QNN HTP graph with the user's own QAIRT libraries (v79 skel for the 8 Elite) to prove an end-to-end NPU run.
|
||||
3. Check the binder route on an enforcing 8 Elite build and on an 8 Elite Gen 5 device. Thor (v73) has no route at all.
|
||||
4. Decide the hook point. Guest-side (Winlator's approach) is the only one that can run FSR 4; compositor-side
|
||||
limits it to spatial super-resolution.
|
||||
5. GPU-only FSR 4.1.2 INT8 (DP4a) as an FFX provider in the guest (see vk-fsr4), since it needs no NPU access and
|
||||
exercises the same plumbing. First measure: wave size on Adreno, and cost per frame on the Thor.
|
||||
6. Per-architecture QNN cache directories (`v73/`, `v75/`, `v79/`, `v81/`) and a fallback to the GPU path whenever
|
||||
`NpuInfo.usable` is false.
|
||||
7. Pin the exact AMD SDK version for any weights that ship (4.1.2.4555 is MIT per the SDK 2.4.0 licence file), keep
|
||||
the MIT notice with them, and review Qualcomm's QNN licence separately before anything of theirs is bundled or
|
||||
downloaded.
|
||||
@@ -0,0 +1,10 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.probe.npu">
|
||||
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="34"/>
|
||||
<application android:label="npuprobe" android:hasCode="false" android:debuggable="true">
|
||||
<uses-native-library android:name="libcdsprpc.so" android:required="false"/>
|
||||
<activity android:name="android.app.NativeActivity" android:exported="true">
|
||||
<meta-data android:name="android.app.lib_name" android:value="npuprobe"/>
|
||||
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds a Java-less NativeActivity APK that asks the vendor dspservice for a FastRPC fd and probes it.
|
||||
# Usage: build.sh <out.apk>; then: adb install -r out.apk; adb shell am start -n dev.probe.npu/android.app.NativeActivity
|
||||
# Results go to logcat, tag NPUPROBE.
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
out=${1:?out.apk}
|
||||
bt=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)
|
||||
work=$(mktemp -d "$HOME/.cache/npu-probe-build.XXXXXX")
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mkdir -p "$work/lib/arm64-v8a"
|
||||
clang=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android34-clang
|
||||
"$clang" -shared -fPIC "$here/probe.c" -o "$work/lib/arm64-v8a/libnpuprobe.so" -llog -landroid -lbinder_ndk -ldl
|
||||
"$bt/aapt2" link -o "$work/base.apk" --manifest "$here/AndroidManifest.xml" -I "$ANDROID_HOME/platforms/android-34/android.jar"
|
||||
(cd "$work" && zip -q -u base.apk lib/arm64-v8a/libnpuprobe.so)
|
||||
"$bt/zipalign" -f 4 "$work/base.apk" "$work/aligned.apk"
|
||||
"$bt/apksigner" sign --ks "$HOME/.android/debug.keystore" --ks-pass pass:android --key-pass pass:android \
|
||||
--ks-key-alias androiddebugkey --out "$out" "$work/aligned.apk"
|
||||
@@ -0,0 +1,100 @@
|
||||
#include <android/native_activity.h>
|
||||
#include <android/log.h>
|
||||
#include <android/binder_ibinder.h>
|
||||
#include <android/binder_parcel.h>
|
||||
#include <android/binder_status.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <string.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#define L(...) do { char b[600]; snprintf(b, sizeof b, __VA_ARGS__); __android_log_write(ANDROID_LOG_INFO, "NPUPROBE", b); } while (0)
|
||||
static void *oc(void *a){return a;} static void od(void *a){} static binder_status_t ot(AIBinder *b, transaction_code_t c, const AParcel *i, AParcel *o){return STATUS_UNKNOWN_TRANSACTION;}
|
||||
|
||||
|
||||
typedef uint32_t remote_handle;
|
||||
/* Route A: what BananaNative does: dlopen the vendor libcdsprpc from the app namespace. */
|
||||
static void route_dlopen(void) {
|
||||
void *h = dlopen("libcdsprpc.so", RTLD_NOW | RTLD_LOCAL);
|
||||
L("A dlopen(libcdsprpc.so) = %s", h ? "ok" : dlerror());
|
||||
if (!h) return;
|
||||
int (*ctl)(int, void *, uint32_t) = dlsym(h, "remote_handle_control");
|
||||
int (*cap)(int, uint32_t, uint32_t *) = dlsym(h, "fastrpc_get_cap");
|
||||
int (*opn)(int, const char *, remote_handle *) = dlsym(h, "remote_handle_open_domain");
|
||||
L("A syms control=%p get_cap=%p open_domain=%p", ctl, cap, opn);
|
||||
if (ctl) { struct { uint32_t domain, enable; } req = {3, 1}; L("A unsigned-pd control r=%d", ctl(4, &req, sizeof req)); }
|
||||
if (cap) for (uint32_t i = 0; i < 3; i++) { uint32_t v = 0xdead; int r = cap(3, i, &v); L("A get_cap(cdsp,%u) r=0x%x v=%u", i, r, v); }
|
||||
if (opn) { remote_handle rh = 0; errno = 0; int r = opn(3, "file:///libhalide_hexagon_remote_skel.so?halide_hexagon_initialize_kernels&_modver=1.0", &rh); L("A open_domain r=0x%x errno=%d", r, errno); }
|
||||
}
|
||||
static void dump_dev(AParcel *r) {
|
||||
int32_t v[16]; int n = 0;
|
||||
int32_t pos = AParcel_getDataPosition(r), size = AParcel_getDataSize(r);
|
||||
L("reply pos=%d size=%d", pos, size);
|
||||
for (int i = 0; i < 12 && AParcel_getDataPosition(r) < size; i++) { int32_t x; if (AParcel_readInt32(r, &x) != STATUS_OK) break; v[n++] = x; L(" int[%d]=%d (0x%x)", i, x, x); }
|
||||
}
|
||||
|
||||
void ANativeActivity_onCreate(ANativeActivity *a, void *s, size_t n) {
|
||||
L("uid=%d", getuid());
|
||||
route_dlopen();
|
||||
{ const char *nodes[] = {"/dev/fastrpc-cdsp", "/dev/adsprpc-smd"};
|
||||
for (int i = 0; i < 2; i++) { int f = open(nodes[i], O_RDWR | O_CLOEXEC); L("direct open(%s) fd=%d errno=%d", nodes[i], f, errno); if (f >= 0) close(f); } }
|
||||
const char *name = "vendor.qti.hardware.dsp.IDspService/default";
|
||||
AIBinder *(*chk)(const char *) = dlsym(RTLD_DEFAULT, "AServiceManager_checkService");
|
||||
L("dlsym checkService=%p", chk);
|
||||
if (!chk) return;
|
||||
AIBinder *svc = chk(name);
|
||||
L("checkService(%s)=%p", name, svc);
|
||||
if (!svc) { L("no service (denied or absent)"); return; }
|
||||
AIBinder_Class *cs = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspService", oc, od, ot);
|
||||
AIBinder_associateClass(svc, cs);
|
||||
AIBinder_Class *cm = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspManager", oc, od, ot);
|
||||
AParcel *in = NULL, *out = NULL;
|
||||
AIBinder_prepareTransaction(svc, &in);
|
||||
AParcel_writeInt32(in, 3);
|
||||
binder_status_t st = AIBinder_transact(svc, 1, &in, &out, 0);
|
||||
AStatus *as = NULL; AIBinder *mgr = NULL;
|
||||
if (st == STATUS_OK) { AParcel_readStatusHeader(out, &as); AParcel_readStrongBinder(out, &mgr); }
|
||||
L("getNewDSPSession: st=%d mgr=%p", st, mgr);
|
||||
if (!mgr) return;
|
||||
AIBinder_associateClass(mgr, cm);
|
||||
int doms[] = {3, 0};
|
||||
for (int di = 0; di < 2; di++) {
|
||||
AParcel *i2 = NULL, *o2 = NULL;
|
||||
AIBinder_prepareTransaction(mgr, &i2);
|
||||
AParcel_writeInt32(i2, 1); /* non-null */
|
||||
int32_t start = AParcel_getDataPosition(i2);
|
||||
AParcel_writeInt32(i2, 0); AParcel_writeInt32(i2, doms[di]);
|
||||
int32_t end = AParcel_getDataPosition(i2);
|
||||
AParcel_setDataPosition(i2, start); AParcel_writeInt32(i2, end - start); AParcel_setDataPosition(i2, end);
|
||||
st = AIBinder_transact(mgr, 2, &i2, &o2, 0);
|
||||
L("openSession(domain %d): st=%d", doms[di], st);
|
||||
if (st != STATUS_OK) continue;
|
||||
AStatus *s2 = NULL; AParcel_readStatusHeader(o2, &s2);
|
||||
L(" ex=%d", s2 ? AStatus_getExceptionCode(s2) : -1);
|
||||
int32_t nn, sz, a1, b1, hsz, nf, ni;
|
||||
AParcel_readInt32(o2, &nn); AParcel_readInt32(o2, &sz); AParcel_readInt32(o2, &a1); AParcel_readInt32(o2, &b1);
|
||||
AParcel_readInt32(o2, &hsz); AParcel_readInt32(o2, &nf);
|
||||
L(" nonnull=%d size=%d a=%d b=%d handleSize=%d nfds=%d", nn, sz, a1, b1, hsz, nf);
|
||||
for (int k = 0; k < nf && k < 4; k++) {
|
||||
int fd = -1; binder_status_t rs = AParcel_readParcelFileDescriptor(o2, &fd);
|
||||
char path[256] = "?"; char lp[64]; snprintf(lp, sizeof lp, "/proc/self/fd/%d", fd); ssize_t r = readlink(lp, path, sizeof path - 1); if (r > 0) path[r] = 0;
|
||||
L(" fd[%d]=%d (rs=%d) -> %s", k, fd, rs, path);
|
||||
if (fd >= 0) {
|
||||
struct { uint32_t domain, attr, cap, rsv[4]; } cap;
|
||||
for (uint32_t at = 0; at < 4; at++) { cap.domain = 3; cap.attr = at; cap.cap = 0xdead; memset(cap.rsv, 0, sizeof cap.rsv); errno = 0;
|
||||
int ir = ioctl(fd, _IOWR('R', 13, cap), &cap); L(" GET_DSP_INFO attr=%u r=%d errno=%d cap=%u", at, ir, errno, cap.cap); }
|
||||
errno = 0; int ar = ioctl(fd, _IO('R', 4)); L(" INIT_ATTACH r=%d errno=%d", ar, errno);
|
||||
uint32_t info = 3; errno = 0; int gr = ioctl(fd, _IOWR('R', 8, uint32_t), &info); L(" GETINFO(R,8) r=%d errno=%d info=%u", gr, errno, info);
|
||||
}
|
||||
}
|
||||
AParcel_readInt32(o2, &ni);
|
||||
L(" nints=%d", ni);
|
||||
}
|
||||
L("done");
|
||||
}
|
||||
@@ -444,3 +444,33 @@ starts there as before, but no motion is sent for it. The fake pointer position
|
||||
With the patch, the Duo starts with only the bottom bar under the parked pointer hovered and controller focus on the
|
||||
first tile (4 of 4 starts), and returns from a game the same way (3 of 3). Making 0100 ignore the X server's initial
|
||||
pointer instead was tried and rejected: the centre motion still arrived, and the header or search bar ended up hovered.
|
||||
|
||||
## 0143 wlserver: only the first finger drives the emulated mouse
|
||||
|
||||
In the Hover, Left, Right, Middle and Trackpad touch click modes every finger warped the X pointer and any finger lifting
|
||||
released the click. With a second finger down the pointer jumped between both fingers on every frame while the button
|
||||
stayed held, so a dragged item followed whichever finger moved last, and lifting the second finger dropped it under the
|
||||
first. The first finger of a gesture now owns the emulated mouse: only it moves the pointer and only its lift releases the
|
||||
click. Fingers that land while it is down are ignored, and so are the others once it lifts, until every finger is up.
|
||||
Touches the click modes never claimed (Passthrough, Disabled, no focused surface) still release a held click when they
|
||||
lift, and the nested pointer (`bAlwaysWarpCursor`) moves the pointer as before. `tools/tests/test_gamescope_touch_click_owner.py`
|
||||
compiles the rule from this patch.
|
||||
|
||||
## 0144 steamcompmgr: motion into the screen edge does not decide the pointer hold
|
||||
|
||||
0133 compares the motion gamescope sends with how the X pointer moves. At the edge of the X screen the pointer cannot move
|
||||
further, so a drawn-cursor game whose pointer sat at an edge while touch or mouse motion pushed outward counted as
|
||||
holding the pointer: the hold stayed on, every such frame restarted the 30 frames needed to release it, and touch drags
|
||||
kept turning into relative motion with no button held. The sent motion is now clamped to what the pointer can reach
|
||||
inside the X screen before it is compared, so motion into an edge counts as no motion. A recentring game is detected as
|
||||
before, since its pointer stays away from the edges. `tools/tests/test_gamescope_pointer_hold_edge.py` compiles the rule
|
||||
from this patch with the 0133 rule.
|
||||
|
||||
## 0145 steamcompmgr: touch-down warps do not decide the pointer hold
|
||||
|
||||
In click mode every touch-down warps the X pointer to the finger. 0133 read that jump as the pointer not following the
|
||||
sent motion, so each new stroke on a drawn-cursor game restarted the 30 following frames needed to release the hold.
|
||||
Short strokes never released it, and taps kept landing at the relative pointer instead of under the finger. wlserver now
|
||||
counts its touch-down warps, and a frame that contains one is left out of the hold decision. Touch drags, mouse motion
|
||||
and mouse warps still count, so a drag on a game that follows the pointer releases the hold and a recentring game is
|
||||
still held. `tools/tests/test_gamescope_pointer_hold_touch_down.py` compiles the rule with the 0133 rule.
|
||||
@@ -0,0 +1,75 @@
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
index 9740875..cb72051 100644
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3283,6 +3283,38 @@ static void apply_touchscreen_orientation(GamescopePanelOrientation orientation,
|
||||
*y = ty;
|
||||
}
|
||||
|
||||
+struct TouchClickState
|
||||
+{
|
||||
+ std::set<int> ids;
|
||||
+ int nOwner = -1;
|
||||
+};
|
||||
+
|
||||
+static TouchClickState s_TouchClick;
|
||||
+
|
||||
+static bool touch_click_claim( TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ if ( state.ids.empty() )
|
||||
+ state.nOwner = nTouchId;
|
||||
+ state.ids.insert( nTouchId );
|
||||
+ return state.nOwner == nTouchId;
|
||||
+}
|
||||
+
|
||||
+static bool touch_click_drives( const TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ return state.nOwner == nTouchId;
|
||||
+}
|
||||
+
|
||||
+static bool touch_click_lift( TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ const bool bTracked = state.ids.erase( nTouchId ) > 0;
|
||||
+ if ( state.nOwner == nTouchId )
|
||||
+ {
|
||||
+ state.nOwner = -1;
|
||||
+ return true;
|
||||
+ }
|
||||
+ return !bTracked && state.nOwner < 0;
|
||||
+}
|
||||
+
|
||||
void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool bAlwaysWarpCursor, gamescope::IBackendConnector* connector )
|
||||
{
|
||||
assert( wlserver_is_lock_held() );
|
||||
@@ -3333,9 +3365,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
|
||||
}
|
||||
else if ( eMode == gamescope::TouchClickModes::Trackpad )
|
||||
{
|
||||
- wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
|
||||
+ if ( touch_click_drives( s_TouchClick, touch_id ) )
|
||||
+ wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
|
||||
}
|
||||
- else
|
||||
+ else if ( bAlwaysWarpCursor || touch_click_drives( s_TouchClick, touch_id ) )
|
||||
{
|
||||
g_bPendingTouchMovement = true;
|
||||
|
||||
@@ -3389,7 +3422,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
|
||||
{
|
||||
return;
|
||||
}
|
||||
- else
|
||||
+ else if ( touch_click_claim( s_TouchClick, touch_id ) )
|
||||
{
|
||||
g_bPendingTouchMovement = true;
|
||||
|
||||
@@ -3417,7 +3450,8 @@ void wlserver_touchup( int touch_id, uint32_t time )
|
||||
|
||||
// Release whatever the touch pressed even if its surface is gone, or the seat keeps the button down.
|
||||
bool bReleasedAny = false;
|
||||
- for ( int i = 0; i < WLSERVER_BUTTON_COUNT; i++ )
|
||||
+ const bool bClickTouch = touch_click_lift( s_TouchClick, touch_id );
|
||||
+ for ( int i = 0; bClickTouch && i < WLSERVER_BUTTON_COUNT; i++ )
|
||||
{
|
||||
if ( wlserver.button_held[ i ] == true )
|
||||
{
|
||||
@@ -0,0 +1,28 @@
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index e98d320..85af598 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -3245,6 +3245,11 @@ static bool pointer_hold_step( PointerHold &state, bool bConstrained, double flS
|
||||
return state.bHeld;
|
||||
}
|
||||
|
||||
+static double pointer_reach( int nFrom, double flDelta, int nSize )
|
||||
+{
|
||||
+ return std::clamp( nFrom + flDelta, 0.0, double( std::max( nSize - 1, 0 ) ) ) - nFrom;
|
||||
+}
|
||||
+
|
||||
static bool s_bPointerHeld = false;
|
||||
|
||||
static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool bHinted )
|
||||
@@ -3311,7 +3316,10 @@ static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool
|
||||
|
||||
if ( s_bTracking )
|
||||
{
|
||||
- s_bPointerHeld = pointer_hold_step( s_Hold, true, flDX, flDY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
+ const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
|
||||
+ const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
|
||||
+ const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
|
||||
+ s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -0,0 +1,73 @@
|
||||
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
|
||||
--- a/src/wlserver.hpp
|
||||
+++ b/src/wlserver.hpp
|
||||
@@ -173,6 +173,7 @@
|
||||
double flFollowDY = 0.0;
|
||||
double flSentDX = 0.0;
|
||||
double flSentDY = 0.0;
|
||||
+ uint64_t ulTouchDownWarps = 0;
|
||||
|
||||
bool button_held[ WLSERVER_BUTTON_COUNT ];
|
||||
std::set <uint32_t> touch_down_ids;
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3429,6 +3429,7 @@
|
||||
if ( eMode != gamescope::TouchClickModes::Trackpad )
|
||||
{
|
||||
wlserver_mousewarp( tx, ty, time, false, true );
|
||||
+ wlserver.ulTouchDownWarps++;
|
||||
}
|
||||
|
||||
uint32_t button = TouchClickModeToLinuxButton( eMode );
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -3263,6 +3263,7 @@
|
||||
static bool s_bHinted = false;
|
||||
static const steamcompmgr_win_t *s_pWindow = nullptr;
|
||||
static const struct wlr_pointer_constraint_v1 *s_pConstraint = nullptr;
|
||||
+ static uint64_t s_ulTouchDownWarps = 0;
|
||||
|
||||
wlserver_lock();
|
||||
const double flX = wlserver.mouse_surface_cursorx;
|
||||
@@ -3272,8 +3273,12 @@
|
||||
const struct wlr_pointer_constraint_v1 *pConstraint = wlserver.GetCursorConstraint();
|
||||
wlserver.flSentDX = 0.0;
|
||||
wlserver.flSentDY = 0.0;
|
||||
+ const uint64_t ulTouchDownWarps = wlserver.ulTouchDownWarps;
|
||||
wlserver_unlock();
|
||||
|
||||
+ const bool bTouchDown = ulTouchDownWarps != s_ulTouchDownWarps;
|
||||
+ s_ulTouchDownWarps = ulTouchDownWarps;
|
||||
+
|
||||
if ( !bConstrained || !pFocus->cursor )
|
||||
{
|
||||
s_bTracking = false;
|
||||
@@ -3314,19 +3319,19 @@
|
||||
int nRootY = 0;
|
||||
pFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
|
||||
|
||||
- if ( s_bTracking )
|
||||
+ if ( !s_bTracking )
|
||||
+ {
|
||||
+ s_Hold = PointerHold{};
|
||||
+ s_Hold.bHeld = bHinted;
|
||||
+ s_bPointerHeld = bHinted;
|
||||
+ }
|
||||
+ else if ( !bTouchDown )
|
||||
{
|
||||
const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
|
||||
const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
|
||||
const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
|
||||
s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
}
|
||||
- else
|
||||
- {
|
||||
- s_Hold = PointerHold{};
|
||||
- s_Hold.bHeld = bHinted;
|
||||
- s_bPointerHeld = bHinted;
|
||||
- }
|
||||
|
||||
s_bTracking = true;
|
||||
s_flSeatX = flX;
|
||||
@@ -10,6 +10,7 @@ export SHELL=/bin/bash
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export QTWEBENGINE_DISABLE_SANDBOX=1
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
export KWIN_USE_OVERLAYS=0
|
||||
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
|
||||
|
||||
@@ -12,6 +12,7 @@ fi
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export QTWEBENGINE_DISABLE_SANDBOX=1
|
||||
if [ -s /etc/ld.so.preload ]; then
|
||||
preload=$(tr -s '\n' ':' < /etc/ld.so.preload)
|
||||
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
|
||||
|
||||
@@ -6,7 +6,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
RUN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-appimage-run"
|
||||
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI")
|
||||
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI", "QTWEBENGINE_DISABLE_SANDBOX")
|
||||
QUICK = ("usr/lib/libQt6Quick.so.6", "usr/lib/libvulkan.so.1", "usr/plugins/platforms/libqwayland-generic.so")
|
||||
RUN_MODE = {"GAMESCOPE_WAYLAND_DISPLAY": "gamescope-0", "WAYLAND_DISPLAY": "gamescope-0", "DISPLAY": ":0",
|
||||
"QT_QPA_PLATFORM": "xcb", "SDL_VIDEODRIVER": "x11", "XDG_SESSION_TYPE": "x11"}
|
||||
@@ -128,6 +128,11 @@ class AppImageRunTest(unittest.TestCase):
|
||||
self.assertEqual("wayland;xcb", env["QT_QPA_PLATFORM"])
|
||||
|
||||
|
||||
def test_a_web_engine_app_starts_as_root_in_either_session(self):
|
||||
for session in (RUN_MODE, DESKTOP):
|
||||
env, _ = self.launch(session)
|
||||
self.assertEqual("1", env["QTWEBENGINE_DISABLE_SANDBOX"])
|
||||
|
||||
def test_a_program_drops_the_sessions_sysmem_like_a_steam_game(self):
|
||||
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem", DROIDDECK_GAME_TU_DEBUG=""))
|
||||
self.assertEqual("unset", env["TU_DEBUG"])
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
DESKTOP = (TOOLS / "linuxfs/desktop/droiddeck-desktop").read_text()
|
||||
PACKAGES = (TOOLS / "ubuntu/packages-desktop.txt").read_text().split()
|
||||
SANDBOXES = ("MOZ_DISABLE_CONTENT_SANDBOX", "MOZ_SHM_NO_SEALS", "QTWEBENGINE_DISABLE_SANDBOX")
|
||||
|
||||
|
||||
class DesktopRootAppsTest(unittest.TestCase):
|
||||
def desktop_environment(self):
|
||||
head = DESKTOP[:DESKTOP.index("\nexport KWIN_COMPOSE=")]
|
||||
env = {k: v for k, v in os.environ.items() if k not in SANDBOXES}
|
||||
probe = "".join('echo %s=${%s-unset}\n' % (name, name) for name in SANDBOXES)
|
||||
result = subprocess.run(["bash", "-c", head + "\nsh -c '" + probe + "'"], env=env,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return dict(line.split("=", 1) for line in result.stdout.splitlines())
|
||||
|
||||
def test_web_engine_apps_start_as_root_like_firefox(self):
|
||||
self.assertEqual({name: "1" for name in SANDBOXES}, self.desktop_environment())
|
||||
|
||||
def test_the_sandbox_switches_are_set_before_plasma(self):
|
||||
self.assertLess(DESKTOP.index("export QTWEBENGINE_DISABLE_SANDBOX=1"),
|
||||
DESKTOP.index("dbus-run-session -- startplasma-wayland"))
|
||||
|
||||
def test_software_sources_gets_the_modules_it_imports(self):
|
||||
self.assertIn("software-properties-qt", PACKAGES)
|
||||
for module in ("pyqt6-dev-tools", "ubuntu-drivers-common"):
|
||||
self.assertIn(module, PACKAGES)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,102 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
HOLD = ROOT / "tools/gamescope/patches/0133-constraint-relative-when-held.patch"
|
||||
EDGE = ROOT / "tools/gamescope/patches/0144-pointer-hold-ignores-motion-into-the-edge.patch"
|
||||
|
||||
|
||||
def added_source(patch):
|
||||
return "\n".join(line[1:] for line in patch.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
|
||||
|
||||
|
||||
def block(text, start):
|
||||
begin = text.index(start)
|
||||
return text[begin:text.index("\n}", begin) + 3]
|
||||
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
static const uint64_t FRAME = 16'666'667ul;
|
||||
|
||||
struct Pointer {
|
||||
PointerHold hold;
|
||||
int x;
|
||||
int width;
|
||||
uint64_t now = 1'000'000'000ul;
|
||||
bool step(double seatDX, int pointerDX) {
|
||||
now += FRAME;
|
||||
const double reach = pointer_reach(x, seatDX, width);
|
||||
x += pointerDX;
|
||||
return pointer_hold_step(hold, true, reach, 0.0, pointerDX, 0.0, now);
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
assert(pointer_reach(1279, 26.0, 1280) == 0.0);
|
||||
assert(pointer_reach(1270, 26.0, 1280) == 9.0);
|
||||
assert(pointer_reach(0, -13.0, 1280) == 0.0);
|
||||
assert(pointer_reach(640, -13.0, 1280) == -13.0);
|
||||
assert(pointer_reach(5, 3.0, 0) == -5.0);
|
||||
|
||||
Pointer pinned{{}, 1279, 1280};
|
||||
for (int i = 0; i < 20; i++) assert(!pinned.step(26.0, 0));
|
||||
|
||||
Pointer release{{}, 1279, 1280};
|
||||
release.hold.bHeld = true;
|
||||
for (int i = 0; i < 20; i++) assert(release.step(26.0, 0));
|
||||
for (int i = 0; i < 10; i++) assert(release.step(-13.0, -13));
|
||||
for (int i = 0; i < 10; i++) assert(release.step(13.0, 13));
|
||||
assert(release.x == 1279);
|
||||
for (int i = 0; i < 20; i++) assert(release.step(26.0, 0));
|
||||
for (int i = 0; i < 9; i++) assert(release.step(-13.0, -13));
|
||||
assert(!release.step(-13.0, -13));
|
||||
bool held = false;
|
||||
|
||||
Pointer recentre{{}, 640, 1280};
|
||||
held = false;
|
||||
for (int i = 0; i < 3; i++) held = recentre.step(26.0, 0);
|
||||
assert(held);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class GamescopePointerHoldEdgeTest(unittest.TestCase):
|
||||
def test_motion_into_the_screen_edge_neither_holds_nor_resets_the_release(self):
|
||||
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("no C++ compiler")
|
||||
hold = added_source(HOLD)
|
||||
edge = added_source(EDGE)
|
||||
source = PREAMBLE + "\n".join([
|
||||
block(hold, "struct PointerHold"),
|
||||
block(hold, "static bool pointer_hold_step"),
|
||||
block(edge, "static double pointer_reach"),
|
||||
]) + MAIN
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "pointer_hold_edge.cpp"
|
||||
exe = Path(tmp) / "pointer_hold_edge"
|
||||
src.write_text(source)
|
||||
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
def test_the_hold_rule_compares_against_the_reachable_motion(self):
|
||||
edge = added_source(EDGE)
|
||||
self.assertIn("pointer_reach( s_nRootX, flDX, pCtx->root_width )", edge)
|
||||
self.assertIn("pointer_reach( s_nRootY, flDY, pCtx->root_height )", edge)
|
||||
self.assertIn("pointer_hold_step( s_Hold, true, flReachX, flReachY,", edge)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,109 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
HOLD = ROOT / "tools/gamescope/patches/0133-constraint-relative-when-held.patch"
|
||||
DOWN = ROOT / "tools/gamescope/patches/0145-pointer-hold-skips-touch-down-warps.patch"
|
||||
|
||||
|
||||
def added_source(patch):
|
||||
return "\n".join(line[1:] for line in patch.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
|
||||
|
||||
|
||||
def block(text, start):
|
||||
begin = text.index(start)
|
||||
return text[begin:text.index("\n}", begin) + 3]
|
||||
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
static const uint64_t FRAME = 16'666'667ul;
|
||||
|
||||
struct Session {
|
||||
PointerHold hold;
|
||||
uint64_t now = 1'000'000'000ul;
|
||||
bool skipTouchDown;
|
||||
bool frame(double seatDX, double pointerDX, bool touchDown) {
|
||||
now += FRAME;
|
||||
if (touchDown && skipTouchDown) return hold.bHeld;
|
||||
return pointer_hold_step(hold, true, seatDX, 0.0, pointerDX, 0.0, now);
|
||||
}
|
||||
void held() {
|
||||
hold = PointerHold{};
|
||||
hold.bHeld = true;
|
||||
}
|
||||
bool strokes() {
|
||||
held();
|
||||
bool result = true;
|
||||
for (int i = 0; i < 17; i++) result = frame(80.0, 80.0, false);
|
||||
result = frame(41.0, -1106.0, true);
|
||||
for (int i = 0; i < 15; i++) result = frame(73.3, 73.0, false);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Session counted{{}, 1'000'000'000ul, false};
|
||||
assert(counted.strokes());
|
||||
|
||||
Session skipped{{}, 1'000'000'000ul, true};
|
||||
assert(!skipped.strokes());
|
||||
|
||||
Session drag{{}, 1'000'000'000ul, true};
|
||||
drag.held();
|
||||
bool result = drag.frame(41.0, -1106.0, true);
|
||||
assert(result);
|
||||
for (int i = 0; i < 29; i++) result = drag.frame(12.0, 12.0, false);
|
||||
assert(result);
|
||||
result = drag.frame(12.0, 12.0, false);
|
||||
assert(!result);
|
||||
|
||||
Session recentre{{}, 1'000'000'000ul, true};
|
||||
for (int i = 0; i < 3; i++) result = recentre.frame(26.0, 0.0, false);
|
||||
assert(result);
|
||||
result = recentre.frame(-400.0, 300.0, true);
|
||||
assert(result);
|
||||
for (int i = 0; i < 40; i++) result = recentre.frame(12.0, 0.0, false);
|
||||
assert(result);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class GamescopePointerHoldTouchDownTest(unittest.TestCase):
|
||||
def test_touch_down_is_skipped_and_touch_drags_release_the_hold(self):
|
||||
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("no C++ compiler")
|
||||
hold = added_source(HOLD)
|
||||
source = PREAMBLE + "\n".join([
|
||||
block(hold, "struct PointerHold"),
|
||||
block(hold, "static bool pointer_hold_step"),
|
||||
]) + MAIN
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "pointer_hold_touch_down.cpp"
|
||||
exe = Path(tmp) / "pointer_hold_touch_down"
|
||||
src.write_text(source)
|
||||
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
def test_only_touch_down_warps_are_skipped(self):
|
||||
added = added_source(DOWN)
|
||||
self.assertIn(" \t\t\t\twlserver_mousewarp( tx, ty, time, false, true );\n+\t\t\t\twlserver.ulTouchDownWarps++;", DOWN.read_text())
|
||||
self.assertEqual(1, added.count("wlserver.ulTouchDownWarps++"))
|
||||
self.assertIn("const bool bTouchDown = ulTouchDownWarps != s_ulTouchDownWarps;", added)
|
||||
self.assertIn("else if ( !bTouchDown )", added)
|
||||
self.assertNotIn("bFromTouch )\n\t\twlserver.ulTouchDownWarps++", added)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,121 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCH = ROOT / "tools/gamescope/patches/0143-touch-click-first-finger-drives.patch"
|
||||
|
||||
|
||||
def added_source():
|
||||
return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
|
||||
|
||||
|
||||
def block(text, start):
|
||||
begin = text.index(start)
|
||||
return text[begin:text.index("\n}", begin) + 3]
|
||||
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <cassert>
|
||||
#include <set>
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
struct Pointer {
|
||||
TouchClickState state;
|
||||
int warps = 0;
|
||||
int presses = 0;
|
||||
int releases = 0;
|
||||
void down(int id) { if (touch_click_claim(state, id)) { warps++; presses++; } }
|
||||
void move(int id, bool nested = false) { if (nested || touch_click_drives(state, id)) warps++; }
|
||||
void up(int id) { if (touch_click_lift(state, id)) releases++; }
|
||||
};
|
||||
|
||||
int main() {
|
||||
Pointer tap;
|
||||
tap.down(1);
|
||||
tap.move(1);
|
||||
tap.up(1);
|
||||
assert(tap.presses == 1 && tap.releases == 1 && tap.warps == 2);
|
||||
|
||||
Pointer drag;
|
||||
drag.down(1);
|
||||
drag.move(1);
|
||||
drag.down(2);
|
||||
drag.move(2);
|
||||
drag.move(1);
|
||||
drag.up(2);
|
||||
assert(drag.presses == 1 && drag.releases == 0 && drag.warps == 3);
|
||||
drag.move(1);
|
||||
drag.up(1);
|
||||
assert(drag.releases == 1 && drag.warps == 4);
|
||||
|
||||
Pointer handover;
|
||||
handover.down(1);
|
||||
handover.down(2);
|
||||
handover.up(1);
|
||||
assert(handover.releases == 1);
|
||||
handover.move(2);
|
||||
handover.down(3);
|
||||
handover.move(3);
|
||||
assert(handover.warps == 1 && handover.presses == 1);
|
||||
handover.up(3);
|
||||
handover.up(2);
|
||||
assert(handover.releases == 1);
|
||||
handover.down(4);
|
||||
handover.move(4);
|
||||
handover.up(4);
|
||||
assert(handover.presses == 2 && handover.releases == 2 && handover.warps == 3);
|
||||
|
||||
Pointer nested;
|
||||
nested.move(0, true);
|
||||
nested.down(1);
|
||||
nested.move(0, true);
|
||||
assert(nested.warps == 3);
|
||||
|
||||
Pointer stray;
|
||||
stray.up(7);
|
||||
assert(stray.releases == 1);
|
||||
stray.down(1);
|
||||
stray.up(7);
|
||||
assert(stray.releases == 1);
|
||||
stray.up(1);
|
||||
assert(stray.releases == 2);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class GamescopeTouchClickOwnerTest(unittest.TestCase):
|
||||
def test_only_the_first_finger_drives_the_emulated_mouse(self):
|
||||
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("no C++ compiler")
|
||||
added = added_source()
|
||||
helpers = "\n".join(block(added, start) for start in (
|
||||
"struct TouchClickState",
|
||||
"static bool touch_click_claim",
|
||||
"static bool touch_click_drives",
|
||||
"static bool touch_click_lift",
|
||||
))
|
||||
source = PREAMBLE + helpers + MAIN
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "touch_click_owner.cpp"
|
||||
exe = Path(tmp) / "touch_click_owner"
|
||||
src.write_text(source)
|
||||
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
def test_the_patch_gates_every_finger_path(self):
|
||||
added = added_source()
|
||||
self.assertIn("else if ( bAlwaysWarpCursor || touch_click_drives( s_TouchClick, touch_id ) )", added)
|
||||
self.assertIn("if ( touch_click_drives( s_TouchClick, touch_id ) )", added)
|
||||
self.assertIn("else if ( touch_click_claim( s_TouchClick, touch_id ) )", added)
|
||||
self.assertIn("bClickTouch && i < WLSERVER_BUTTON_COUNT", added)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,5 +1,6 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -54,12 +55,70 @@ FORKER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *name;
|
||||
static _Atomic int done;
|
||||
static _Atomic int parked_word;
|
||||
static _Atomic pid_t parked_tid;
|
||||
|
||||
// the host's futex call: 202 on x86-64, where qemu-user runs, 98 on aarch64
|
||||
static int blocked_futex(const char *path, unsigned long *addr) {
|
||||
unsigned long nr = 0;
|
||||
FILE *f = fopen(path, "r");
|
||||
int got = f && fscanf(f, "%lu %lx", &nr, addr) == 2;
|
||||
if (f) fclose(f);
|
||||
return got && (nr == 202 || nr == 98);
|
||||
}
|
||||
|
||||
static void *park(void *arg) {
|
||||
parked_tid = (pid_t)syscall(SYS_gettid);
|
||||
while (!parked_word) syscall(SYS_futex, &parked_word, 0 /* FUTEX_WAIT */, 0, NULL, NULL, 0);
|
||||
return arg;
|
||||
}
|
||||
|
||||
// How far qemu-user moved the guest in the host's address space (its guest_base; 0 natively): a
|
||||
// thread parked on a futex this program knows shows that futex's host address in its syscall file,
|
||||
// which qemu-user passes through unlike /proc/self/maps.
|
||||
static long guest_base(void) {
|
||||
char path[96];
|
||||
unsigned long addr = 0;
|
||||
while (!parked_tid) usleep(1000);
|
||||
snprintf(path, sizeof(path), "/proc/%d/task/%d/syscall", (int)getpid(), (int)parked_tid);
|
||||
for (int i = 0; i < 5000; i++) {
|
||||
if (blocked_futex(path, &addr) && addr) return (long)(addr - (unsigned long)&parked_word);
|
||||
usleep(1000);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// A child that hangs in qemu-user itself: a fork while another thread is inside the emulator's
|
||||
// own locks (its mmap() handling) can leave the child waiting on a futex in qemu's memory, which no
|
||||
// guest lock is. The child's blocking call shows the host's address; under qemu-user this
|
||||
// program's /proc/self/maps lists the guest's mappings only, and a futex outside all of them, once
|
||||
// moved back by the guest base, is the emulator's. Natively every futex is in the process's own
|
||||
// mappings: never counted. Seen on x86 runners; there is no emulator on a device.
|
||||
static int stuck_in_emulator(pid_t pid, long base) {
|
||||
char path[64], line[512];
|
||||
unsigned long addr = 0;
|
||||
snprintf(path, sizeof(path), "/proc/%d/syscall", (int)pid);
|
||||
if (base < 0 || !blocked_futex(path, &addr)) return 0;
|
||||
addr -= (unsigned long)base;
|
||||
FILE *f = fopen("/proc/self/maps", "r");
|
||||
if (!f) return 0;
|
||||
int guest = 0;
|
||||
while (!guest && fgets(line, sizeof(line), f)) {
|
||||
unsigned long start, end;
|
||||
if (sscanf(line, "%lx-%lx", &start, &end) == 2 && addr >= start && addr < end) guest = 1;
|
||||
}
|
||||
fclose(f);
|
||||
return !guest;
|
||||
}
|
||||
|
||||
static void *churn(void *arg) {
|
||||
while (!done) {
|
||||
@@ -71,24 +130,40 @@ static void *churn(void *arg) {
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
name = argv[1];
|
||||
pthread_t thread;
|
||||
pthread_t parked, thread;
|
||||
if (pthread_create(&parked, NULL, park, NULL) != 0) return 1;
|
||||
long base = guest_base();
|
||||
printf("base\t%ld\n", base);
|
||||
if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1;
|
||||
int finished = 0;
|
||||
int finished = 0, emulator = 0;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) break;
|
||||
if (pid == 0) {
|
||||
alarm(10);
|
||||
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
|
||||
_exit(sem == SEM_FAILED || sem_close(sem) != 0);
|
||||
}
|
||||
int status;
|
||||
if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
|
||||
int status = 0, stalled = 0;
|
||||
pid_t r;
|
||||
for (int waited = 0; (r = waitpid(pid, &status, WNOHANG)) == 0; waited++) {
|
||||
if (waited == 1000) { // 10 s
|
||||
stalled = stuck_in_emulator(pid, base);
|
||||
kill(pid, SIGKILL);
|
||||
}
|
||||
usleep(10000);
|
||||
}
|
||||
if (r != pid) continue;
|
||||
if (stalled) emulator++;
|
||||
else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
|
||||
}
|
||||
done = 1;
|
||||
pthread_join(thread, NULL);
|
||||
parked_word = 1;
|
||||
syscall(SYS_futex, &parked_word, 1 /* FUTEX_WAKE */, 1, NULL, NULL, 0);
|
||||
pthread_join(parked, NULL);
|
||||
sem_unlink(name);
|
||||
printf("finished\t%d\n", finished);
|
||||
printf("emulator\t%d\n", emulator);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
@@ -116,7 +191,7 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_hooked(self, program, *args):
|
||||
def run_hooked(self, program, *args, timeout=120):
|
||||
hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
@@ -124,9 +199,17 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return dict(line.split("\t") for line in out.stdout.splitlines())
|
||||
# its own process group, so a timeout also ends a child still blocked once the program is gone
|
||||
proc = subprocess.Popen(cmd + [str(program), *args], env=env, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, start_new_session=True)
|
||||
try:
|
||||
stdout, stderr = proc.communicate(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(proc.pid, signal.SIGKILL)
|
||||
proc.communicate()
|
||||
raise
|
||||
self.assertEqual(proc.returncode, 0, stderr)
|
||||
return dict(line.split("\t") for line in stdout.splitlines())
|
||||
|
||||
def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self):
|
||||
name = f"/ddsem-{os.getpid()}"
|
||||
@@ -139,7 +222,20 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
|
||||
source.write_text(FORKER)
|
||||
forker = self.probe.with_name("forker")
|
||||
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True)
|
||||
self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}"))
|
||||
name = f"/ddsem-fork-{os.getpid()}"
|
||||
# left by a run that did not get to sem_unlink(), it would fail the other tests' empty /dev/shm
|
||||
self.addCleanup(lambda: (self.shm / f"sem.{name[1:]}").unlink(missing_ok=True))
|
||||
# 200 forks under a loaded qemu-user, and 10 s for each child that hangs in the emulator
|
||||
result = self.run_hooked(forker, name, timeout=300)
|
||||
# every child opened one, but for one now and then that hung in qemu-user itself (a fork during
|
||||
# the emulator's own locking), which a native run never has
|
||||
if self.prefix:
|
||||
self.assertNotEqual("-1", result.get("base"), result)
|
||||
else:
|
||||
self.assertEqual("0", result.get("base"), result)
|
||||
emulator = int(result.get("emulator", "0"))
|
||||
self.assertEqual(200, int(result.get("finished", "0")) + emulator, result)
|
||||
self.assertLessEqual(emulator, 0 if not self.prefix else 3, result)
|
||||
|
||||
def test_a_created_semaphore_keeps_its_name_and_mode(self):
|
||||
name = f"ddsem-kept-{os.getpid()}"
|
||||
|
||||
@@ -215,6 +215,7 @@ power-profiles-daemon
|
||||
powerdevil
|
||||
ppa-purge
|
||||
print-manager
|
||||
pyqt6-dev-tools
|
||||
python3-dbus
|
||||
python3-launchpadlib
|
||||
python3-setuptools
|
||||
@@ -241,6 +242,7 @@ software-properties-qt
|
||||
squashfs-tools
|
||||
synaptic
|
||||
systemsettings
|
||||
ubuntu-drivers-common
|
||||
udisks2
|
||||
unrar-free
|
||||
upower
|
||||
|
||||
Reference in new issue
Block a user