Files
DroidDeck/tools/prepare_windows_runtime.py
+13 83eda433c8 Add VITURE XR controls, head tracking, and SteamVR (#732)
* Add VITURE glasses support: hardware control, 3D, head tracking

Glasses get their own controller over the MCU (permission, 120 Hz default, brightness, volume, sunblock, 2D/3D) and the game moves onto them when plugged in. The IMU drives Cardboard head tracking and the SteamVR driver. 3D falls back to one eye's view on phones that can't send the 3840x1080 signal. Options open from a glasses button in game and on the Steam page.

* Drop the glasses settings like Steam's: Play-style button, Settings lip, tabs

* Hang the glasses Settings lip over the top of the button

* Space glasses MCU commands so the IMU rate sticks, fit fixed resolutions to the glasses

* Keep Steam alive with SteamVR registered, run SteamVR at the glasses' rate, keep the glasses lip on top

* Fit VR games on the glasses: full view, seated origin at the head, pad hands reach with the d-pad

* Let the pad hands reach a metre out so buttons with deep colliders press

* Show every VR frame in order at 120 fps: wait for SteamVR's GPU work, present only finished copies, skip the grace on idle shared counters

* Glasses: SteamVR starts and stops with them, closer view with a field of view setting, Recenter on the pad

* Glasses: SteamVR field of view defaults to 90°

* VR pad hands: sticks move and aim the hands, left stick click switches the sticks to the game, d-pad pulls a held hand

* Glasses: Play SteamVR beside the glasses button instead of starting SteamVR with them, pad hands drawn as Index controllers and off while other VR controllers are connected, glasses sheet tabs sized like Steam's

* Track glasses mode, refresh-aware glasses window, align Play SteamVR with Play Steam

* Fix 3D on the glasses: full-res SteamVR presenter, revert VR 3D at session end, coalesce vsync ticks, no session restart after end

* Address review: glasses output after installs and session end, VR revert retry, display fallback, presenter swapchain retry, agent hex checks, drawer bumpers, glasses translations, docs

* Harden VITURE stereo negotiation and output refresh tracking

* Localize stereo recovery feedback and record Astra reconnect tests

* Improve test failure diagnostics and refresh Astra firmware findings

* Handle VITURE docks separately and reject truncated USB frames

* Glasses: remember a 3D fallback per model, docks as display only, VR timing fixes

- A 3D attempt that ends at the 640x480 fallback is remembered for that glasses
  model, so Play SteamVR no longer blacks out the glasses after every restart;
  Retry clears it and "3D for VR games" stays reachable
- A VITURE Mobile Dock on its own no longer counts as glasses; through a dock
  Play SteamVR is hidden and the sheet shows the output and why there is no control
- HDR is probed on the glasses when the session starts there
- Glasses frames with a mismatched checksum are marked in the status frame log
- SteamVR layer and driver vblank counters stay monotonic across refresh changes;
  one-eye render scale applies from activation and on mono/3D switches
- Compositor binds announce the refresh clients were last told; the presenter
  retries a failed first swapchain
- Dead strings and helpers removed; docs updated

* Glasses: drop USB frames with a bad checksum

* Glasses: count frames dropped for a bad checksum

* Feat/viture xr (#907)

* Add RayNeo Air and GT support to the XR glasses pipeline

* Add RayNeo Air and GT support to the XR glasses pipeline

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Document confirmed XREAL 1S brightness control

* Document confirmed XREAL 1S brightness control

* Fix SteamVR glasses defaults and rendering controls

* Fix SteamVR glasses defaults and rendering controls

* chore: keep only the 3 newest session log folders (#852)

* chore: add agent comment rules (#748)

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* fix: wireless ADB page names the child-process switch the way Android shows it (#848)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru (#850)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru

- mode_added_art_hint: now mentions Steam then SteamGridDB (all four locales).
- wincomp_needs_installer / wincomp_installers_note: es and ko still described
  the old "coming soon" behaviour; align with the current English text.
- summary_remove_game: was still English in all four locales.

Machine-assisted translation; native-speaker review is welcome.

* l10n(es): say registro, not grabación, for the missing installer record

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* fix: a failed cloud save recovery no longer ends the app (#846)

The cloud-recovery thread started at every app start had nothing to
catch an error, so one went to CrashHandler, which halts the process
with status 2. In unit tests the thread can outlive the test that
started it, fail on the torn-down preferences, and take the whole test
run down. The error is now logged and the thread ends.

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>

* fix: an interrupted Linux runtime download resumes instead of starting again (#847)

* fix: an interrupted Linux runtime download resumes instead of starting again

installOnce() asked the downloader to resume but always deleted the archive in its finally block, so the next attempt began at zero. The archive is now named after the release version and checksum, a failed download keeps what it fetched, and archives of other releases (and the old fixed name) are removed. A checksum or extraction failure still deletes the file.

* test: Downloader resumes a cut-off download from the bytes it kept

Starts a socket server that promises the whole file, hangs up part way and then answers a Range request, and checks that the second downloadFile call resumes with the right offset and ends with identical bytes.

* fix: a resumed download discards a 206 that does not start where the kept bytes end

Downloader appended every 206 response to the partial file without
looking at Content-Range. A server or proxy that answers a Range request
with a different offset would leave a corrupt file. Check that the range
starts at the kept length; otherwise delete the partial file and start
again without a Range header.

Adds a test with a server that answers the Range request from offset 0.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings (#849)

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings

Adds the strings values-de, values-it and values-pt were missing (14 each) and the six that values-fr, values-es and values-ru were missing. Machine-assisted drafts that follow each file's existing register and terms; native review is welcome.

* l10n: correct missing active swap translations

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: droiddeckctl reaches variant-package builds (recover #842) (#854)

fix: droiddeckctl reaches builds shipped under a variant package

The provider authority and the start Activity's component were fixed to
com.droiddeck.launcher, so droiddeckctl could not talk to the antutu,
ludashi or pubg builds from tools/release/variants.txt. DROIDDECK_PACKAGE
now picks the package; the Activity's class name stays the same in every
variant.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* feat: droiddeckctl reports on-screen pacing (recover #843) (#855)

feat: droiddeckctl pacing reports the frames that reached the screen

Reads SurfaceFlinger's timestats for the game's layer (or the session's
SurfaceView) over a capture: frames on screen, fps on screen, the
present-to-present histogram and how many intervals were off the usual
cadence. Records split by a refresh-rate change are summed. A game's own fps
counter counts frames handed over, so it can't show dropped or doubled frames.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* fix: Steam can restart more than twice in a session (#754)

* fix: Steam can restart more than twice in a session

Every exit 42 counted toward the cap that stops an update which will
not install, and the count was never cleared, so the third restart of
a session ended it however far apart they were. A client that ran for
a minute before asking is not that loop: the count starts again.

* fix: measure the client's run time as it exits

The time spent collecting logs and checking FEX after the client exits
counted toward its run, so a slow cleanup could make a quick exit 42
look like a long one and clear the count.

---------

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* fix: the front end keeps its page when the Fold is folded or unfolded (#832)

* fix: the front end keeps its page when the Fold is folded or unfolded

MainActivity, FileManagerActivity, FilePickerActivity and StoreLoginActivity did not declare the screen-size configuration changes, so folding or unfolding a foldable recreated them and dropped their in-memory state. They now handle orientation, screenSize, screenLayout, smallestScreenSize and density themselves, like SessionActivity already does. uiMode is left out on purpose.

* fix: store login keeps rebuilding its toolbar when the display density changes

StoreLoginActivity builds its toolbar in code with dp-to-pixel values taken at creation time and has no onConfigurationChanged. It no longer declares density in configChanges, so a density change recreates it as before this PR. Size and layout changes are still handled in place.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* Release pointer buttons without replaying stale motion (#803)

* Fix cursor warping on native touch down

* Preserve input cleanup without replaying stale pointer motion

---------

Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>

* l10n: translate the strings added since #284 into zh-CN, zh-HK, zh-TW and ja (#539)

* l10n: translate the 184 strings added since #284 (zh-CN/HK/TW, ja)

The stores, cloud saves, Windows components, Steam touch, desktop
removal and background-downloads strings landed after #284's
translation snapshot, so every one of them fell back to English.
Translate all 184 into Simplified Chinese, Traditional Chinese
(Taiwan and Hong Kong) and Japanese, keeping each locale file's own
vocabulary (工作階段/會話, 解除安裝/卸載, 元件/組件, 設定).

Also fix four Hong Kong strings that kept the simplified 着色器.

* l10n(zh): fix stale and ambiguous strings found in review

Severe: summary_remove_game was untranslated English in all three
files; mode_added_art_hint, wincomp_installers_note and
wincomp_needs_installer still described the pre-#480/#492 English.

Also: distinguish the Setup wizard from Android system settings in
zh-HK/zh-TW (初始設定 / 系統設定 / Android 設定), unify library as
收藏庫, component as 組件 in zh-HK, session as 會話 in zh-HK, account
as 帳戶 in zh-HK, Trending as 趋势/趨勢, Forget as 清除, reword the
re-applied-at-launch, action-failed and already-in-Games strings, and
play as 執行/開啟遊戲 in zh-TW/zh-HK.

* l10n(ja): fix stale and ambiguous strings found in review

---------

Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* Rebuild and verify Windows VR runtime components

* Rebuild and verify Windows VR runtime components

* Add top, bottom, and centered picture positions for Steam sessions (#871)

* fix: dependency scan ignores folders above the game folder (#859)

* DroidDeck-Proton: get releases from the Droid-Deck org repo

DroidDeck-Proton is now built and released on Droid-Deck/DroidDeck-Proton
(11-9.1 is Latest there), so the Components page, the update check and the
guest installer read releases from the org repo instead of The412Banner's.

* feat: low-latency controller and touch toggles in the session drawer (#808)

* fix: SteamGridDB lookups no longer stick as "no match" after a failure; add a search to the art chooser (#876)

* feat: Steam home wall fills from the signed-in library instead of store picks (#878)

* test: cover GPU family and support classification (#880)

* Fix local builds on Linux failing after the first Comet build (#866)

* feat: sort the store library and installed tabs, and switch between card and list views (#798)

* feat: three-finger tap toggles Steam's on-screen keyboard in game mode (#782)

* fix: keep Quest-patched Turnip as the auto default (#853)

* Fix deploy_local.sh and droiddeckctl not finding a phone connected over wireless debugging (#864)

* fix: keep proot sessions alive when the kernel loses fork events (#457)

* fix(quest): correct desktop and Steam display corruption across sessions (#733)

fix(quest): stabilize desktop and Steam layer presentation

Keep Quest SDR scenes and the black backdrop off the Android Vulkan swapchain regardless of session order or HDR preferences. Only report the first frame after client content is submitted.

Add backdrop lifecycle and first-frame regression coverage. Record the user's successful Quest 3 Test 2 result.

Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: keep SteamVR syscall hooks and report Steam crashes (#905)

* fix: preserve SteamVR syscall hooks

* fix: report Steam crashes through gamescope

* fix: honor glasses pacing and resolution in SteamVR launches

---------

Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>

* Glasses: keep a pending 2D restore and the SteamVR recovery offer, show Play SteamVR only with a picture

* Translate the glasses calibration, XREAL and SteamVR recovery strings

* SteamVR recovery: give a finished teardown time to collect logs before restarting

* Credit the projects the XR glasses support builds on

* Joy-Cons: SteamVR hands from their gyro while SteamVR runs, one combined pad otherwise

* Headsets: settings badge on Play SteamVR instead of a top-right button, both shown only once connected

* Hand tracking: camera-tracked Joy-Cons and bare hands in SteamVR, drawn as white gloves

- Joy-Con movement from the accelerometer (report reordering, per-Joy-Con calibration, zero-velocity updates)
- MediaPipe pose and hand landmarks from the device camera, placement check, per-hand Kalman filter with the Joy-Con
- No controller connected: bare camera hands with Quest-style gestures, 1€ filtered, rendered as a white glove model built from a distance field
- SteamVR safe mode cleared before each start so one crash no longer blocks the driver

---------

Co-authored-by: MaxsTechReview <6025299+maxjivi05@users.noreply.github.com>
Co-authored-by: informalTechCode <informaltechyt@gmail.com>
Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>
2026-10-17 13:17:05 -04:00

341 lines
18 KiB
Python

"""Prepare the audited Windows runtime from a pinned APK and rebuilt replacements.
The donor was built from a CI merge, not just the PR head. Only unchanged
components are reused. Session helpers come from this checkout, libblsession
must be rebuilt for all three architectures, Gamescope comes from the current
checksum-pinned release, and the VR components are rebuilt in Docker (or reused
from a verified build manifest). Store engines are omitted (build with skipRust).
"""
import argparse
import hashlib
import io
import json
from pathlib import Path, PurePosixPath
import shutil
import struct
import subprocess
import sys
import tarfile
import tempfile
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/release'))
import runtime_inputs as runtime
from check_session_assets import source_assets
sys.path.insert(0, str(ROOT / 'tools/vr'))
import build_windows as vr_build
DONOR_SHA256 = 'b7efef6442f384446bdd1750cec21f0eda61b370bc21d9f55187448e5c256760'
DONOR_PR_SOURCE = 'bdf876d47cc9bb6fa810d014370da5bbb3c28039'
DONOR_MAIN_SOURCE = '46fac69438ed428f2ca43ea935cd47790264f380'
DONOR_TREE = 'ddbca4d572b809fb969be0cf80ef83d6ef6580ce'
DONOR_REVISION = 'cf24c5f2c771633ea426046006c2b977c7bd7d32'
DONOR_CERT_SHA256 = 'b241ea7d77822d39b89d3227e06f3ecf62adec6cbfd38ad06196787991b5d3f0'
DONOR_URL = 'https://github.com/Droid-Deck/DroidDeck-CI/releases/download/pr-732/DroidDeck-PR.732-bdf876d.apk'
AUDITED_SOURCE = '1dc66bf9be64a404c80400049c0803614814461b'
LOCAL_BUILD_PLUMBING = {'app/build.gradle', 'tools/release/runtime_inputs.py'}
# These Android-only inputs are compiled by Gradle, never taken from the donor.
# Keep this list explicit so unrelated native or Linux runtime edits still fail.
LOCAL_ANDROID_SOURCES = {'app/src/main/cpp/CMakeLists.txt',
'app/src/main/cpp/viture/sdk_bridge.cpp',
'app/src/main/cpp/viture/display_modes.h',
'app/src/main/cpp/waylandcomp/src/cardboard.c'}
# These audited helper updates are copied from this checkout by runtime.record().
# Permit them only while source_assets() still guarantees that staging path.
LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat',
'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr'}
VR_PREFIX = 'assets/linuxfs/usr/local/lib/droiddeck-vr/'
CHECK_PATHS = list(dict.fromkeys(runtime.SOURCE_PATHS + [
'app/src/main/cpp', 'app/src/main/jniLibs', 'app/src/main/rust/stores', 'tools/vr']))
REBUILT = {'libblsession.so': 183, 'x86_64/libblsession.so': 62, 'i386/libblsession.so': 3}
REBUILT_SHA256 = {
'libblsession.so': '1093ce33ca6d0a17a2eec7b3a3cc53969b01ffc459aef16b320cd3857825b738',
'x86_64/libblsession.so': 'd0a558fee1ac4d5b898170a96b03e15610d9835e7097425027b8c31728da870a',
'i386/libblsession.so': '785d8d9bf1fa20d083a7fed65d064c7580684d7065530d95a648e2d32901d2a2',
}
JNI = ('libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so')
PREPARED = ('pulseaudio.tzst',
'graphics_driver/adrenotools-turnip25.1.0-quest1.tzst',
'graphics_driver/adrenotools-turnip26.3.0-a6xx.tzst',
'graphics_driver/adrenotools-turnip26.3.0-quest2.tzst')
def git(*args):
return subprocess.check_output(['git', '-C', str(ROOT), *args])
def changed(base, target=None):
args = ['diff', '--no-ext-diff', '--ignore-cr-at-eol', '--name-only', '-z', base]
if target:
args.append(target)
return set(filter(None, git(*args, '--', *CHECK_PATHS).decode().split('\0')))
def check_sources():
# A branch label alone is insufficient: CI merged this main commit into it.
if git('merge-tree', '--write-tree', DONOR_PR_SOURCE, DONOR_MAIN_SOURCE).decode().splitlines()[0] != DONOR_TREE:
raise ValueError('The donor CI merge does not match the audited source tree')
helper_sources = {path.relative_to(ROOT).as_posix() for path in source_assets()}
reviewed = LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | (LOCAL_SESSION_HELPERS & helper_sources)
unexpected = {p for p in changed(AUDITED_SOURCE, 'HEAD') - reviewed if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Sources changed since the component audit:\n' + '\n'.join(sorted(unexpected)))
local = changed('HEAD')
untracked = set(filter(None, git('ls-files', '--others', '--exclude-standard', '-z',
'--', *CHECK_PATHS).decode().split('\0')))
unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES)
if not vr_build.is_source(p)}
if unexpected:
raise ValueError('Unreviewed runtime/native/Rust changes:\n' + '\n'.join(sorted(unexpected)))
classifications = {}
for path in sorted(changed(DONOR_TREE, 'HEAD') | local | untracked):
if vr_build.is_source(path):
action = 'VR component rebuilt from current source and verified; never imported from donor'
elif path in LOCAL_ANDROID_SOURCES:
action = 'Android native source compiled by Gradle; not imported from donor'
elif path.startswith('app/src/main/rust/stores/'):
action = 'store engines omitted; Gradle must use skipRust=true'
elif path in helper_sources:
action = 'restaged from current source with LF line endings'
elif path in {'tools/linuxfs/preload/net.c', 'tools/linuxfs/preload/webhelper.c'}:
action = 'all three libblsession libraries rebuilt from current source'
elif path == 'tools/gamescope/release.env':
action = 'current checksum-pinned Gamescope archive replaces donor'
elif path in {'tools/build_local.sh', 'tools/directaudio/fetch.sh'}:
action = 'audited download/build cache plumbing; component inputs unchanged'
elif path == 'app/src/main/cpp/waylandcomp/src/compositor.c':
action = 'Android native library rebuilt by Gradle; not imported'
elif path in LOCAL_BUILD_PLUMBING:
action = 'local Windows build plumbing; changes recorded below'
else:
raise ValueError('Unclassified donor source difference: ' + path)
classifications[path] = action
return classifications
def validate_relative(name):
path = PurePosixPath(name)
if path.is_absolute() or not path.parts or any(part in {'.', '..'} or ':' in part for part in path.parts):
raise ValueError('Unsafe archive member: ' + name)
if '\\' in name:
raise ValueError('Backslash in archive member: ' + name)
return path
def checked_output(relative):
validate_relative(relative)
target = (ROOT / relative).resolve()
if not target.is_relative_to(ROOT.resolve()):
raise ValueError('Output escapes the checkout: ' + relative)
if git('ls-files', '--', relative).strip():
raise ValueError('Refusing to overwrite tracked file: ' + relative)
return target
def read_gamescope(path):
pins = dict(line.split('=', 1) for line in (ROOT / 'tools/gamescope/release.env').read_text().splitlines()
if line and not line.startswith('#'))
if runtime.digest(path) != pins['GAMESCOPE_SHA256']:
raise ValueError('Gamescope archive checksum does not match tools/gamescope/release.env')
data = subprocess.run(['zstd', '-dc', str(path)], capture_output=True, check=True).stdout
files = {}
with tarfile.open(fileobj=io.BytesIO(data)) as archive:
for member in archive:
name = member.name.removeprefix('./')
validate_relative(name)
if member.isdir():
continue
if not member.isfile():
raise ValueError('Gamescope archive contains a non-regular member: ' + name)
if name in files:
raise ValueError('Duplicate Gamescope archive member: ' + name)
files[name] = archive.extractfile(member).read()
if set(files) != {'usr/local/bin/gamescope'}:
raise ValueError('Unexpected Gamescope archive payload: ' + ', '.join(files))
return files, pins
def validate_rebuilt(path, machine):
data = path.read_bytes()
if len(data) < 20 or data[:4] != b'\x7fELF' or data[5] != 1 or struct.unpack('<H', data[18:20])[0] != machine:
raise ValueError('Replacement has the wrong ELF architecture: ' + str(path))
return data
def validate_tracked_assets(package, llvm_strip):
checked = {}
for prefix, apk_prefix in [('app/src/main/jniLibs/', 'lib/'),
('app/src/main/assets/desktop-removal/', 'assets/desktop-removal/')]:
tracked = filter(None, git('ls-files', '-z', '--', prefix).decode().split('\0'))
for name in tracked:
archive_name = apk_prefix + name.removeprefix(prefix)
content = (ROOT / name).read_bytes()
donor_content = package.read(archive_name)
verification = 'identical bytes'
if content != donor_content:
if prefix != 'app/src/main/jniLibs/':
raise ValueError('Tracked bytes differ from the donor: ' + name +
' (text inputs must be checked out with LF)')
# AGP strips prebuilt JNI libraries during packaging. Verify that
# deterministic transformation on a temporary copy, never the source.
with tempfile.TemporaryDirectory(prefix='droiddeck-strip-check-') as temp:
stripped = Path(temp) / 'library.so'
subprocess.run([str(llvm_strip), '--strip-unneeded', '-o', str(stripped),
str(ROOT / name)], check=True, capture_output=True)
if stripped.read_bytes() != donor_content:
raise ValueError('Stripped tracked binary differs from donor: ' + name)
verification = 'identical after NDK llvm-strip --strip-unneeded'
checked[name] = {'source_sha256': hashlib.sha256(content).hexdigest(),
'packaged_sha256': hashlib.sha256(donor_content).hexdigest(),
'verification': verification}
return checked
def prepare(apk, rebuilt_dir, gamescope, llvm_strip=None, rebuilt_vr=None, vk_include=None, vr_image=vr_build.IMAGE):
classifications = check_sources()
if runtime.digest(apk) != DONOR_SHA256:
raise ValueError('Donor APK checksum mismatch')
gamescope_files, pins = read_gamescope(gamescope)
replacements = {name: validate_rebuilt(rebuilt_dir / name, machine) for name, machine in REBUILT.items()}
for name, data in replacements.items():
if hashlib.sha256(data).hexdigest() != REBUILT_SHA256[name]:
raise ValueError('Replacement does not match the audited local rebuild: ' + name)
if vk_include is None:
if llvm_strip is None:
raise ValueError('Set --vk-include or --llvm-strip to locate the NDK Vulkan headers')
vk_include = llvm_strip.parent.parent / 'sysroot/usr/include'
if rebuilt_vr is None:
vr_files, vr_manifest = vr_build.build(ROOT / 'build/windows-setup/vr', vk_include, root=ROOT, image=vr_image)
else:
vr_files, vr_manifest = vr_build.validate(rebuilt_vr, vk_include, root=ROOT)
helpers = source_assets()
helper_assets = set(helpers.values())
plan = {}
origins = {}
with ZipFile(apk) as package:
names = package.namelist()
if len(set(names)) != len(names):
raise ValueError('Donor APK has duplicate ZIP entries')
tracked = validate_tracked_assets(package, llvm_strip)
excluded = {'assets/linuxfs/' + name for name in REBUILT}
excluded.update('assets/linuxfs/' + name for name in gamescope_files)
excluded.update(helper_assets)
for name in names:
if name.endswith('/') or name in excluded or name.startswith(VR_PREFIX):
continue
if name.startswith(('assets/linuxfs/', 'assets/directaudio/', 'assets/droiddeck-esync/')):
target = 'app/src/main/' + name
checked_output(target)
plan[target] = package.read(name)
origins[target] = 'verified donor APK'
for name in JNI:
target = 'app/src/main/jniLibs/arm64-v8a/' + name
checked_output(target)
plan[target] = package.read('lib/arm64-v8a/' + name)
origins[target] = 'verified donor APK'
for name in PREPARED:
target = 'app/build/prepared-assets/' + name
checked_output(target)
plan[target] = package.read('assets/' + name)
origins[target] = 'verified donor APK'
for name, data in replacements.items():
target = 'app/src/main/assets/linuxfs/' + name
checked_output(target)
plan[target] = data
origins[target] = 'locally rebuilt libblsession'
for name, data in gamescope_files.items():
target = 'app/src/main/assets/linuxfs/' + name
checked_output(target)
plan[target] = data
origins[target] = 'checksum-pinned Gamescope release'
for name, data in vr_files.items():
target = 'app/src/main/' + VR_PREFIX + name
checked_output(target)
plan[target] = data
origins[target] = 'VR rebuilt from current source; source and output checksums verified'
# Do not silently retain unrelated files from a prior preparation.
expected = set(plan) | {'app/src/main/' + name for name in helper_assets}
for tree in ('linuxfs', 'directaudio', 'droiddeck-esync'):
base = ROOT / 'app/src/main/assets' / tree
for path in base.rglob('*'):
if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts):
if path.relative_to(ROOT).as_posix() not in expected:
raise ValueError('Unexpected existing generated asset: ' + str(path))
for source in helpers:
data = source.read_bytes()
normalized = data.replace(b'\r\n', b'\n')
if data != normalized:
source.write_bytes(normalized)
for target, data in plan.items():
path = checked_output(target)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
runtime.record()
runtime.verify()
provenance = {
'version': 1,
'donor': {'url': DONOR_URL, 'sha256': DONOR_SHA256, 'signer_sha256': DONOR_CERT_SHA256,
'pr_source': DONOR_PR_SOURCE, 'main_source': DONOR_MAIN_SOURCE,
'source_tree': DONOR_TREE, 'embedded_revision': DONOR_REVISION},
'source_commit': git('rev-parse', 'HEAD').decode().strip(),
'classified_differences': classifications,
'build_plumbing': {name: {'sha256': runtime.digest(ROOT / name),
'diff': git('diff', 'HEAD', '--', name).decode()}
for name in sorted(LOCAL_BUILD_PLUMBING)},
'android_sources_built_by_gradle': {name: runtime.digest(ROOT / name)
for name in sorted(LOCAL_ANDROID_SOURCES)
if (ROOT / name).is_file()},
'stores': 'omitted; use -PskipRust=true',
'gamescope': {'repo': pins['GAMESCOPE_REPO'], 'tag': pins['GAMESCOPE_TAG'],
'archive_sha256': pins['GAMESCOPE_SHA256']},
'tracked_files_verified': tracked,
'vr_build': vr_manifest,
'outputs': {name: {'origin': origins[name], 'sha256': hashlib.sha256(data).hexdigest()}
for name, data in sorted(plan.items())},
'preload_sources': {path.relative_to(ROOT).as_posix(): runtime.digest(path)
for path in sorted((ROOT / 'tools/linuxfs/preload').glob('*.c'))},
'preload_build_scripts': {path.relative_to(ROOT).as_posix(): {
'sha256': runtime.digest(path), 'script': path.read_text()}
for path in sorted((ROOT / 'build/windows-setup').glob('build-preloads-*.sh'))},
'runtime_manifest_sha256': runtime.digest(ROOT / runtime.MANIFEST),
}
output = ROOT / 'app/build/windows-runtime-provenance.json'
output.write_text(json.dumps(provenance, indent=2, sort_keys=True) + '\n', encoding='utf-8')
print('Runtime inputs verified; donor components, rebuilt preloads, rebuilt VR and pinned Gamescope recorded.')
print('Store engines omitted: build with -PskipRust=true.')
print(output)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apk', type=Path, default=ROOT / 'build/windows-setup/DroidDeck-PR.732-bdf876d.apk')
parser.add_argument('--rebuilt-linuxfs', type=Path, default=ROOT / 'build/windows-setup/rebuilt-linuxfs')
parser.add_argument('--gamescope', type=Path, default=ROOT / 'build/windows-setup/gamescope.tzst')
parser.add_argument('--llvm-strip', type=Path, default=Path.home() /
'AppData/Local/Android/Sdk/ndk/27.3.13750724/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-strip.exe')
parser.add_argument('--rebuilt-vr', type=Path, help='Reuse a VR build with vr-build.json; default rebuilds in Docker')
parser.add_argument('--vk-include', type=Path, help='NDK Vulkan headers; defaults to the sysroot beside --llvm-strip')
parser.add_argument('--vr-image', default=vr_build.IMAGE, help='Docker compiler image for a fresh VR build')
parser.add_argument('--check-sources', action='store_true', help='Audit source differences without extracting files')
args = parser.parse_args()
zstd = ROOT / 'build/windows-setup/tools/zstd/zstd.exe'
if not shutil.which('zstd') and zstd.is_file():
import os
os.environ['PATH'] = str(zstd.parent) + os.pathsep + os.environ.get('PATH', '')
try:
if args.check_sources:
print(json.dumps(check_sources(), indent=2, sort_keys=True))
else:
prepare(args.apk.resolve(), args.rebuilt_linuxfs.resolve(), args.gamescope.resolve(), args.llvm_strip.resolve(),
args.rebuilt_vr.resolve() if args.rebuilt_vr else None,
args.vk_include.resolve() if args.vk_include else None, args.vr_image)
except (ValueError, OSError, subprocess.CalledProcessError, KeyError) as error:
parser.exit(1, str(error) + '\n')
if __name__ == '__main__':
main()