Attest the paired worker start time before its final GO

This commit is contained in:
Kurt Himebauch committed 2026-12-03 12:41:05 -05:00
1 parent 773042fe08
commit 2feb35aa5e
11 files changed
+209 -52

No files matched your search

@@ -17,6 +17,8 @@ internal object FrameAcquireWorkerProbe {
private const val TEST_INTENT = "DD_THOR_WORKER_ACQUIRE_TEST=1"
private const val SHA = "09a56e234ac7605cae25ea0b69d02e2b04bc815bbb1a32bd5a61b64c11e88fdf"
private const val SIZE = 4272072L
internal const val RECEIPT_TAG = 0x44445046
internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES
private const val TTL_MS = 600_000L
internal data class Ticket(val owner: Int, val root: File, val configuredRoot: File, val binary: File, val expires: Long)
@@ -29,7 +31,7 @@ internal object FrameAcquireWorkerProbe {
private enum class Reason {
ENABLED, ARM_FILE, MATCH_ACK, MATCH_OWNER, MATCH_EXPIRED, MATCH_PATH, MATCH_ROOT,
MATCH_ARGV, MATCH_FILE, MATCH_DIGEST, QUALIFIED, PUBLISH_TICKET, PUBLISH_RESTAT,
PUBLISH_NATIVE, RESERVED
PUBLISH_NATIVE, PUBLISH_RECEIPT, RESERVED
}
private val reported = mutableSetOf<Stage>()
@Synchronized private fun breadcrumb(stage: Stage, reason: Reason) {
@@ -142,19 +144,52 @@ internal object FrameAcquireWorkerProbe {
return qualified
}
internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long =
if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L
internal fun parseSelfStat(stat: String, pid: Int): Long {
if (pid <= 1 || !stat.startsWith("$pid (")) return 0L
val comm = stat.lastIndexOf(')')
if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L
val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() }
if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L
val value = fields[19] // field 22 from field 3 (the single-character task state).
return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } }
?.toLongOrNull()?.takeIf { it > 0 } ?: 0L
}
internal fun selfStartTicks(pid: Int): Long = runCatching {
File("/proc/self/stat").inputStream().use { input ->
val bytes = ByteArray(4096)
var used = 0
while (used < bytes.size) {
val n = input.read(bytes, used, bytes.size - used)
if (n < 0) break
if (n == 0) return@runCatching 0L
used += n
}
if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L
else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid)
}
}.getOrDefault(0L)
/** Runs just before the final GO byte. Failure never changes ordinary launch. */
@Synchronized fun publish(q: Qualified, pid: Int) {
@Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) {
val t = q.ticket
if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) {
if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET)
return
}
intent = null // At most one candidate per explicitly armed session.
if (startTicks <= 0L) {
breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT)
return
}
val status = runCatching {
val st = Os.lstat(t.binary.path)
require(st.st_size == SIZE && st.st_dev == q.dev && st.st_ino == q.ino &&
st.st_mtime == q.mtime && st.st_ctime == q.ctime)
if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino)) {
if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) {
nativeOwner = t.owner
nativePid = pid
Reason.RESERVED
@@ -20,6 +20,7 @@ import android.system.Os
import android.system.OsConstants
import android.system.StructPollfd
import android.util.Log
import com.droiddeck.launcher.BuildConfig
import org.json.JSONObject
import java.io.DataInputStream
import java.io.File
@@ -45,7 +46,16 @@ open class GuestWorker : Service() {
val fillBinderFd = data.readInt() != 0
val go = data.readFileDescriptor()
val nice = data.readInt()
reply?.writeInt(Process.myPid())
val pid = Process.myPid()
reply?.writeInt(pid)
// Optional fixed-size receipt, on the exact local, non-exported worker's Binder.
// Nothing in the guest socket request populates these fields.
if (BuildConfig.FRAME_ACQUIRE_WORKER_PROBE && reply != null &&
Binder.getCallingUid() == Process.myUid() &&
data.dataAvail() == Int.SIZE_BYTES && data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG) {
reply.writeInt(pid)
reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))
}
Handler(Looper.getMainLooper()).post {
// The app writes a byte once it has the reply and has taken the launch on: an exec
// before then would end this process with the reply undelivered, and with none (the
@@ -436,7 +446,8 @@ object GuestWorkers {
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
confirmed: () -> Boolean = { true }, owner: Int = session,
nice: Int = Process.getThreadPriority(Process.myTid())): Int {
nice: Int = Process.getThreadPriority(Process.myTid()),
testWorker: FrameAcquireWorkerProbe.Qualified? = null): Int {
val app = context.applicationContext
if (guest && owner <= stopped) {
Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") +
@@ -472,13 +483,21 @@ object GuestWorkers {
data.writeInt(if (guest) 0 else 1)
data.writeFileDescriptor(go[0].fileDescriptor)
data.writeInt(nice)
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
val service = checkNotNull(slot.service)
if (testWorker != null) data.writeInt(FrameAcquireWorkerProbe.RECEIPT_TAG)
check(service.transact(GuestWorker.RUN, data, reply, 0))
// The worker has its own copy: with ours closed (and the request's, which holds one too),
// a worker that gave up leaves no reader
data.recycle()
data = null
go[0].close()
val pid = reply.readInt()
val startTicks = if (testWorker != null) {
val size = reply.dataAvail()
if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)
FrameAcquireWorkerProbe.validReceipt(pid, reply.readInt(), reply.readLong(), size)
else 0L
} else 0L
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
// would not find them.
val stopping = { guest && owner <= stopped }
@@ -507,7 +526,12 @@ object GuestWorkers {
// launching slot), or never.
val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
val accepted = answered && synchronized(authorizing) {
!stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
if (stopping() || !confirmed()) false
else {
if (testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, pid,
if (slot.service === service) startTicks else 0L)
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
}
}
val endedRunning = synchronized(slots) {
slot.launching = false
@@ -914,7 +938,6 @@ object GuestWorkers {
out.flush()
confirmedToHook = true
}.isSuccess
if (confirmed && testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, worker)
confirmed
}, commit = { started ->
worker = started
@@ -934,7 +957,7 @@ object GuestWorkers {
}
ended && line.toString() == "go"
}.getOrDefault(false)
})
}, testWorker = testWorker)
if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker)
handedOver = true
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
@@ -10,7 +10,7 @@ public final class WaylandCompositor {
private WaylandCompositor() {}
public static native boolean frameWorkerProbeEnabled();
public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino);
public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino, long startTicks);
public static native void frameWorkerProbeRevoke(int owner, int pid);
private static volatile Runnable firstFrameListener;