mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 14:26:00 +00:00
Merge remote-tracking branch 'origin/main' into fix/steam-compat-pick-wins
This commit is contained in:
commit
a4abb797a7
140 files changed
+6314
-836
No files matched your search
@@ -40,6 +40,27 @@ class AuthorshipTest(unittest.TestCase):
|
||||
def test_bot_pr_author_is_rejected(self):
|
||||
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}}))
|
||||
|
||||
def test_people_named_like_assistants_are_not_bots(self):
|
||||
for author in ("Claudemirovsky <63046606+Claudemirovsky@users.noreply.github.com>",
|
||||
"Claude Monet <claude@example.com>", "Devin Smith <devin@example.com>",
|
||||
"Cody Allen <cody@example.com>", "Gemini Patel <gp@example.com>"):
|
||||
with self.subTest(author=author):
|
||||
self.assertEqual([], check.commit_violations("abc", self.commit(author=author)))
|
||||
self.assertEqual([], check.event_violations({"pull_request": {"user": {"login": "Claudemirovsky", "type": "User"}}}))
|
||||
|
||||
def test_assistant_identities_are_still_bots(self):
|
||||
for author in ("Claude Opus 5.5 <noreply@anthropic.com>", "Claude Code <cc@example.com>",
|
||||
"Cursor Agent <cursoragent@cursor.com>",
|
||||
"Devin AI <devin-ai-integration[bot]@users.noreply.github.com>",
|
||||
"Gemini <gemini@example.com>", "GPT-5 <a@example.com>"):
|
||||
with self.subTest(author=author):
|
||||
self.assertTrue(check.commit_violations("abc", self.commit(author=author)))
|
||||
for login in ("chatgpt-codex-connector", "Copilot", "claude"):
|
||||
with self.subTest(login=login):
|
||||
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": login, "type": "User"}}}))
|
||||
message = "Fix\n\nCo-authored-by: Claude Opus 5.5 <noreply@anthropic.com>\n"
|
||||
self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message))))
|
||||
|
||||
def test_missing_author_fails_closed(self):
|
||||
self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n"))
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import itertools
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CiChecksTest(unittest.TestCase):
|
||||
def test_independent_jobs_wait_only_for_the_pinned_source(self):
|
||||
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
|
||||
for name in ('xbox', 'components', 'python-tests'):
|
||||
self.assertEqual(jobs[name]['needs'], 'source')
|
||||
self.assertEqual(set(jobs['build']['needs']), {'source', 'components', 'xbox'})
|
||||
|
||||
def test_dependency_update_errors_block_installation(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
sudo = root / 'sudo'
|
||||
sudo.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$APT_LOG"\nexit "${APT_RESULT:-0}"\n')
|
||||
sudo.chmod(0o755)
|
||||
query = root / 'dpkg-query'
|
||||
query.write_text('#!/bin/sh\nexit 1\n')
|
||||
query.chmod(0o755)
|
||||
log = root / 'apt.log'
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], APT_LOG=str(log))
|
||||
installer = ROOT / 'tools/ci/install-ubuntu-packages.sh'
|
||||
result = subprocess.run(['bash', str(installer), 'qemu-user'], env=dict(env, APT_RESULT='17'))
|
||||
self.assertEqual(result.returncode, 17)
|
||||
self.assertEqual(len(log.read_text().splitlines()), 2)
|
||||
log.unlink()
|
||||
subprocess.run(['bash', str(installer), 'qemu-user'], env=env, check=True)
|
||||
update, install = log.read_text().splitlines()
|
||||
for command in (update, install):
|
||||
self.assertIn('Dir::Etc::sourceparts=-', command)
|
||||
self.assertIn('Acquire::https::Timeout=15', command)
|
||||
self.assertIn('Acquire::Retries=1', command)
|
||||
self.assertIn('APT::Update::Error-Mode=any', update)
|
||||
self.assertIn('install -y -q --no-install-recommends qemu-user', install)
|
||||
|
||||
def test_required_status_rejects_failed_cancelled_or_skipped_test_jobs(self):
|
||||
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
|
||||
gate = jobs['checks']
|
||||
self.assertEqual(gate['name'], 'Compile and test APK')
|
||||
self.assertEqual(set(gate['needs']), {'build', 'python-tests'})
|
||||
self.assertIn('always()', gate['if'])
|
||||
for build, python in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=2):
|
||||
with self.subTest(build=build, python=python):
|
||||
result = subprocess.run(
|
||||
['bash', '-c', gate['steps'][0]['run']],
|
||||
env=dict(os.environ, BUILD_RESULT=build, PYTHON_RESULT=python),
|
||||
capture_output=True)
|
||||
self.assertEqual(result.returncode == 0, build == python == 'success')
|
||||
for publisher in ('sign', 'packs'):
|
||||
self.assertIn('checks', jobs[publisher]['needs'])
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CiNdkTest(unittest.TestCase):
|
||||
def test_installed_ndk_must_match_the_declared_version(self):
|
||||
version = (ROOT / 'tools/ci/toolchains.env').read_text().strip().split('=', 1)[1]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
ndk = root / 'ndk' / version
|
||||
ndk.mkdir(parents=True)
|
||||
properties = ndk / 'source.properties'
|
||||
properties.write_text('Pkg.Revision = ' + version + '\n')
|
||||
output = root / 'environment'
|
||||
env = dict(os.environ, ANDROID_HOME=str(root), GITHUB_ENV=str(output))
|
||||
script = ROOT / 'tools/ci/resolve-ndk.sh'
|
||||
subprocess.run(['bash', str(script)], env=env, check=True)
|
||||
self.assertIn('NDK_VERSION=' + version, output.read_text())
|
||||
self.assertIn('ANDROID_NDK_HOME=' + str(ndk), output.read_text())
|
||||
properties.write_text('Pkg.Revision = unexpected\n')
|
||||
self.assertNotEqual(subprocess.run(['bash', str(script)], env=env).returncode, 0)
|
||||
@@ -0,0 +1,106 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location('component_prepare', Path(__file__).resolve().parents[1] / 'components/prepare.py')
|
||||
components = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(components)
|
||||
|
||||
|
||||
class ComponentPrepareTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name)
|
||||
self.fixture(self.root)
|
||||
|
||||
def fixture(self, root):
|
||||
for name in components.TREES:
|
||||
(root / name).mkdir(parents=True)
|
||||
(root / 'tools/components/recipes').mkdir(parents=True)
|
||||
(root / 'input.h').write_text('#define VALUE 1\n')
|
||||
(root / 'tools/components/recipes/fake.sh').write_text('printf binary > app/src/main/assets/linuxfs/demo.so\n')
|
||||
spec = dict(script='tools/components/recipes/fake.sh', inputs=['input.h', 'tools/components/recipes/fake.sh'],
|
||||
outputs=['app/src/main/assets/linuxfs/demo.so'])
|
||||
(root / components.REGISTRY).write_text(json.dumps(dict(fake=spec)))
|
||||
for name in components.LIBRARIES:
|
||||
(root / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
(root / name).write_bytes(b'library')
|
||||
subprocess.run(['git', 'init', '-q', str(root)], check=True)
|
||||
subprocess.run(['git', '-C', str(root), 'config', 'core.autocrlf', 'false'], check=True)
|
||||
subprocess.run(['git', '-C', str(root), 'add', '.'], check=True)
|
||||
subprocess.run(['git', '-C', str(root), '-c', 'user.name=Test Developer', '-c', 'user.email=test@example.test',
|
||||
'commit', '-qm', 'baseline'], check=True)
|
||||
|
||||
def test_recipe_failure_or_missing_output_does_not_succeed(self):
|
||||
script = self.root / 'tools/components/recipes/fake.sh'
|
||||
script.write_text('exit 7\n')
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
components.prepare('fake', self.root)
|
||||
script.write_text('exit 0\n')
|
||||
with self.assertRaisesRegex(ValueError, 'required outputs'):
|
||||
components.prepare('fake', self.root)
|
||||
|
||||
def test_identity_covers_source_and_recipe_changes(self):
|
||||
original = components.identity('fake', self.root)
|
||||
(self.root / 'input.h').write_text('#define VALUE 2\n')
|
||||
changed = components.identity('fake', self.root)
|
||||
self.assertNotEqual(original, changed)
|
||||
script = self.root / 'tools/components/recipes/fake.sh'
|
||||
script.write_text(script.read_text() + '\nprintf changed\n')
|
||||
self.assertNotEqual(changed, components.identity('fake', self.root))
|
||||
|
||||
def test_tool_requirements_are_installed_in_one_union(self):
|
||||
definitions = dict(one=dict(packages=['gcc', 'cmake']), two=dict(packages=['gcc', 'qemu-user']))
|
||||
with patch.object(components, 'registry', return_value=definitions), patch.object(components.subprocess, 'run') as run:
|
||||
components.prepare_tools(['one', 'two'], self.root)
|
||||
run.assert_called_once_with(['bash', 'tools/ci/install-ubuntu-packages.sh', 'cmake', 'gcc', 'qemu-user'],
|
||||
cwd=self.root, check=True)
|
||||
|
||||
def test_prepared_handoff_verifies_every_file_and_source_tree(self):
|
||||
components.prepare('fake', self.root)
|
||||
archive = self.root / 'prepared.tar.gz'
|
||||
components.pack(archive, self.root)
|
||||
tree = subprocess.check_output(['git', 'rev-parse', 'HEAD^{tree}'], cwd=self.root, text=True).strip()
|
||||
target = self.root / 'target'
|
||||
self.fixture(target)
|
||||
components.unpack(archive, tree, target)
|
||||
self.assertEqual((target / 'app/src/main/assets/linuxfs/demo.so').read_bytes(), b'binary')
|
||||
with self.assertRaisesRegex(ValueError, 'pinned source'):
|
||||
components.unpack(archive, 'wrong-tree', target)
|
||||
|
||||
def test_tampered_component_bytes_fail_handoff_verification(self):
|
||||
components.prepare('fake', self.root)
|
||||
archive = self.root / 'prepared.tar.gz'
|
||||
components.pack(archive, self.root)
|
||||
corrupt = self.root / 'corrupt.tar.gz'
|
||||
with tarfile.open(archive) as original, tarfile.open(corrupt, 'w:gz') as output:
|
||||
for entry in original:
|
||||
content = original.extractfile(entry).read()
|
||||
if entry.name.endswith('demo.so'):
|
||||
content = b'tampered'
|
||||
entry.size = len(content)
|
||||
output.addfile(entry, io.BytesIO(content))
|
||||
target = self.root / 'target'
|
||||
self.fixture(target)
|
||||
tree = subprocess.check_output(['git', 'rev-parse', 'HEAD^{tree}'], cwd=self.root, text=True).strip()
|
||||
with self.assertRaisesRegex(ValueError, 'file hashes'):
|
||||
components.unpack(corrupt, tree, target)
|
||||
|
||||
def test_archive_cannot_overwrite_source_through_traversal(self):
|
||||
archive = self.root / 'bad.tar.gz'
|
||||
with tarfile.open(archive, mode='w:gz') as tar:
|
||||
name = 'app/src/main/assets/linuxfs/../../../../../input.h'
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = 3
|
||||
tar.addfile(entry, io.BytesIO(b'bad'))
|
||||
with self.assertRaisesRegex(ValueError, 'Unsafe'):
|
||||
components.unpack(archive, 'tree', self.root)
|
||||
self.assertEqual((self.root / 'input.h').read_text(), '#define VALUE 1\n')
|
||||
@@ -1160,8 +1160,12 @@ class BundleTest(unittest.TestCase):
|
||||
except ImportError:
|
||||
self.skipTest("PyYAML is not installed")
|
||||
apk = yaml.safe_load((self.ROOT / ".github/workflows/build.yml").read_text())
|
||||
steps = {step.get("name"): step for step in apk["jobs"]["build"]["steps"]}
|
||||
bundle = steps["Bundle the droiddeck-esync packs"]
|
||||
steps = {step.get("name"): step for step in apk["jobs"]["components"]["steps"]}
|
||||
import json
|
||||
recipes = json.loads((self.ROOT / "tools/components/recipes.json").read_text())
|
||||
bundle = dict(steps["Bundle the droiddeck-esync packs"])
|
||||
self.assertIn("prepare.py esync", bundle["run"])
|
||||
bundle["run"] = (self.ROOT / recipes["esync"]["script"]).read_text()
|
||||
self.assertNotIn("if", bundle)
|
||||
self.assertIn("tools/droiddeck-esync/release.env", bundle["run"])
|
||||
self.assertIn('release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"', bundle["run"])
|
||||
@@ -1169,7 +1173,7 @@ class BundleTest(unittest.TestCase):
|
||||
self.assertIn('curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"', bundle["run"])
|
||||
self.assertIn("sha256sum -c -", bundle["run"])
|
||||
self.assertNotIn("revoked.txt", bundle["run"])
|
||||
stage = next(step for step in apk["jobs"]["build"]["steps"] if "overlay/usr/local/bin/droiddeck-*" in step.get("run", ""))
|
||||
stage = {"run": (self.ROOT / recipes["runtime"]["script"]).read_text()}
|
||||
self.assertIn("tools/linuxfs/overlay/usr/local/bin/droiddeck-* ", stage["run"])
|
||||
local = (self.ROOT / "tools/build_local.sh").read_text()
|
||||
self.assertIn("tools/linuxfs/overlay/usr/local/bin/droiddeck-* ", local)
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "../../app/src/main/cpp/adrenotools/src/hook/kgsl.h"
|
||||
#include "../../app/src/main/cpp/waylandcomp/src/gpu_clock_pin.h"
|
||||
|
||||
enum { NONE, OPEN, DEVICE, CONTEXT, CONSTRAINT, MEMORY, MAP, SYNC, SUBMIT, THREAD, WAIT };
|
||||
static atomic_int failure, descriptors, contexts, memories, mappings, submissions, waits;
|
||||
static atomic_bool timeout_wait;
|
||||
static bool legacy_core;
|
||||
static uint32_t commands[1024];
|
||||
|
||||
int __android_log_print(int priority, const char *tag, const char *format, ...) {
|
||||
(void)priority; (void)tag; (void)format;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __wrap_open(const char *path, int flags, ...) {
|
||||
(void)flags;
|
||||
assert(!strcmp(path, "/dev/kgsl-3d0"));
|
||||
if (atomic_load(&failure) == OPEN) { errno = EACCES; return -1; }
|
||||
assert(atomic_fetch_add(&descriptors, 1) == 0);
|
||||
return 91;
|
||||
}
|
||||
|
||||
int __wrap_close(int fd) {
|
||||
assert(fd == 91);
|
||||
assert(atomic_fetch_sub(&descriptors, 1) == 1);
|
||||
errno = EBADF;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void *__wrap_mmap(void *address, size_t size, int protection, int flags, int fd, off_t offset) {
|
||||
(void)address; (void)protection; (void)flags;
|
||||
assert(fd == 91 && size == sizeof(commands) && offset == (23 << 12));
|
||||
if (atomic_load(&failure) == MAP) { errno = EACCES; return MAP_FAILED; }
|
||||
assert(atomic_fetch_add(&mappings, 1) == 0);
|
||||
return commands;
|
||||
}
|
||||
|
||||
int __wrap_munmap(void *address, size_t size) {
|
||||
assert(address == commands && size == sizeof(commands));
|
||||
assert(atomic_fetch_sub(&mappings, 1) == 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef __ANDROID__
|
||||
int __wrap_ioctl(int fd, int request, ...) {
|
||||
#else
|
||||
int __wrap_ioctl(int fd, unsigned long request, ...) {
|
||||
#endif
|
||||
assert(fd == 91);
|
||||
va_list args;
|
||||
va_start(args, request);
|
||||
void *arg = va_arg(args, void *);
|
||||
va_end(args);
|
||||
int step = NONE;
|
||||
switch ((unsigned int)request) {
|
||||
case IOCTL_KGSL_DEVICE_GETPROPERTY: step = DEVICE; break;
|
||||
case IOCTL_KGSL_DRAWCTXT_CREATE: step = CONTEXT; break;
|
||||
case IOCTL_KGSL_SETPROPERTY: step = CONSTRAINT; break;
|
||||
case IOCTL_KGSL_GPUMEM_ALLOC_ID: step = MEMORY; break;
|
||||
case IOCTL_KGSL_GPUMEM_SYNC_CACHE: step = SYNC; break;
|
||||
case IOCTL_KGSL_GPU_COMMAND: step = SUBMIT; break;
|
||||
case IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: step = WAIT; break;
|
||||
}
|
||||
if (step && atomic_load(&failure) == step) { errno = EACCES; return -1; }
|
||||
switch ((unsigned int)request) {
|
||||
case IOCTL_KGSL_DEVICE_GETPROPERTY: {
|
||||
struct kgsl_device_getproperty *property = arg;
|
||||
assert(property->type == KGSL_PROP_DEVICE_INFO);
|
||||
((struct kgsl_devinfo *)property->value)->chip_id = legacy_core ? 0x04030000 : 0x07030000;
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_DRAWCTXT_CREATE: {
|
||||
struct kgsl_drawctxt_create *context = arg;
|
||||
assert(context->flags & KGSL_CONTEXT_PWR_CONSTRAINT);
|
||||
context->drawctxt_id = 17;
|
||||
atomic_fetch_add(&contexts, 1);
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_SETPROPERTY: {
|
||||
struct kgsl_device_getproperty *property = arg;
|
||||
assert(property->type == KGSL_PROP_PWR_CONSTRAINT);
|
||||
struct kgsl_device_constraint *constraint = property->value;
|
||||
assert(constraint->context_id == 17 && constraint->type == KGSL_CONSTRAINT_PWRLEVEL);
|
||||
assert(((struct kgsl_device_constraint_pwrlevel *)constraint->data)->level == KGSL_CONSTRAINT_PWR_MAX);
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_GPUMEM_ALLOC_ID: {
|
||||
struct kgsl_gpumem_alloc_id *memory = arg;
|
||||
memory->id = 23; memory->gpuaddr = 0x100000; memory->mmapsize = sizeof(commands);
|
||||
atomic_fetch_add(&memories, 1);
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_GPUMEM_SYNC_CACHE:
|
||||
assert(((struct kgsl_gpumem_sync_cache *)arg)->op == KGSL_GPUMEM_CACHE_CLEAN);
|
||||
break;
|
||||
case IOCTL_KGSL_GPU_COMMAND: {
|
||||
struct kgsl_gpu_command *command = arg;
|
||||
struct kgsl_command_object *object = (void *)(uintptr_t)command->cmdlist;
|
||||
assert(command->context_id == 17 && command->numcmds == 1);
|
||||
assert(command->flags & KGSL_CMDBATCH_PWR_CONSTRAINT);
|
||||
assert(object->id == 23 && object->gpuaddr == 0x100000 && object->size == 8);
|
||||
assert(commands[0] == (legacy_core ? 0xc0001000 : 0x70100001) && commands[1] == 0);
|
||||
command->timestamp = atomic_fetch_add(&submissions, 1) + 1;
|
||||
break;
|
||||
}
|
||||
case IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID:
|
||||
atomic_fetch_add(&waits, 1);
|
||||
if (atomic_load(&timeout_wait)) { errno = ETIMEDOUT; return -1; }
|
||||
break;
|
||||
case IOCTL_KGSL_DRAWCTXT_DESTROY:
|
||||
assert(atomic_fetch_sub(&contexts, 1) == 1);
|
||||
break;
|
||||
case IOCTL_KGSL_GPUMEM_FREE_ID:
|
||||
assert(atomic_fetch_sub(&memories, 1) == 1);
|
||||
break;
|
||||
default: assert(!"unexpected ioctl");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __real_pthread_create(pthread_t *, const pthread_attr_t *, void *(*)(void *), void *);
|
||||
int __wrap_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start)(void *), void *arg) {
|
||||
if (atomic_load(&failure) == THREAD) return EAGAIN;
|
||||
return __real_pthread_create(thread, attr, start, arg);
|
||||
}
|
||||
|
||||
static void assert_released(void) {
|
||||
assert(!atomic_load(&descriptors) && !atomic_load(&contexts));
|
||||
assert(!atomic_load(&memories) && !atomic_load(&mappings));
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
legacy_core = true;
|
||||
assert(gpu_clock_pin_set(true));
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
legacy_core = false;
|
||||
for (int step = OPEN; step <= THREAD; ++step) {
|
||||
atomic_store(&failure, step);
|
||||
assert(!gpu_clock_pin_set(true));
|
||||
assert(errno == (step == THREAD ? EAGAIN : EACCES));
|
||||
assert_released();
|
||||
}
|
||||
atomic_store(&failure, NONE);
|
||||
atomic_store(&submissions, 0);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
assert(gpu_clock_pin_set(true));
|
||||
for (int i = 0; i < 100 && atomic_load(&submissions) < 2; ++i) usleep(10000);
|
||||
assert(atomic_load(&submissions) > 1);
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
|
||||
atomic_store(&timeout_wait, true);
|
||||
atomic_store(&submissions, 0);
|
||||
atomic_store(&waits, 0);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
for (int i = 0; i < 100 && atomic_load(&waits) < 2; ++i) usleep(10000);
|
||||
assert(atomic_load(&waits) >= 2);
|
||||
assert(atomic_load(&submissions) == 1);
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
atomic_store(&timeout_wait, false);
|
||||
|
||||
atomic_store(&failure, WAIT);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
for (int i = 0; i < 100 && atomic_load(&descriptors); ++i) usleep(10000);
|
||||
assert_released();
|
||||
atomic_store(&failure, NONE);
|
||||
assert(gpu_clock_pin_set(true));
|
||||
assert(gpu_clock_pin_set(false));
|
||||
assert_released();
|
||||
puts("gpu clock pin: failure cleanup, renewal, bounded queue and restart passed");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class GpuClockPinTest(unittest.TestCase):
|
||||
@unittest.skipUnless(sys.platform.startswith('linux') and shutil.which('cc'), 'requires a Linux C compiler')
|
||||
def test_constraint_lifecycle(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
directory = pathlib.Path(tmp)
|
||||
(directory / 'android').mkdir()
|
||||
(directory / 'android/log.h').write_text(
|
||||
'#define ANDROID_LOG_WARN 5\n'
|
||||
'int __android_log_print(int, const char *, const char *, ...);\n')
|
||||
binary = directory / 'gpu-clock-pin-test'
|
||||
subprocess.run([
|
||||
'cc', '-std=c11', '-D_DEFAULT_SOURCE', '-D__user=', '-Wall', '-Wextra', '-Werror',
|
||||
'-I', str(directory), '-pthread',
|
||||
str(ROOT / 'tools/tests/test_gpu_clock_pin.c'),
|
||||
str(ROOT / 'app/src/main/cpp/waylandcomp/src/gpu_clock_pin.c'),
|
||||
'-Wl,--wrap=open,--wrap=close,--wrap=mmap,--wrap=munmap,--wrap=ioctl,--wrap=pthread_create',
|
||||
'-o', str(binary),
|
||||
], check=True)
|
||||
subprocess.run([str(binary)], check=True, timeout=10)
|
||||
@@ -0,0 +1,580 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <signal.h>
|
||||
#include <string.h>
|
||||
|
||||
int install_handler(int sig, void (*fn)(int, siginfo_t *, void *), void **seen) {
|
||||
struct sigaction sa, old;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = fn;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
if (sigaction(sig, &sa, NULL) != 0) return -1;
|
||||
if (sigaction(sig, NULL, &old) != 0) return -1;
|
||||
*seen = (void *)old.sa_sigaction;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int install_oneshot(int sig, void (*fn)(int, siginfo_t *, void *)) {
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = fn;
|
||||
sa.sa_flags = SA_SIGINFO | SA_RESTART | SA_RESETHAND;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
return sigaction(sig, &sa, NULL);
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/ioctl.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct sem_args { uint32_t count, max; };
|
||||
struct mutex_args { uint32_t owner, count; };
|
||||
struct event_args { uint32_t manual, signaled; };
|
||||
struct wait_args { uint64_t timeout, objs; uint32_t count, index, flags, owner, alert, pad; };
|
||||
#define NT_CREATE_SEM _IOW('N', 0x80, struct sem_args)
|
||||
#define NT_SEM_RELEASE _IOWR('N', 0x81, uint32_t)
|
||||
#define NT_WAIT_ANY _IOWR('N', 0x82, struct wait_args)
|
||||
#define NT_WAIT_ALL _IOWR('N', 0x83, struct wait_args)
|
||||
#define NT_CREATE_MUTEX _IOW('N', 0x84, struct mutex_args)
|
||||
#define NT_MUTEX_UNLOCK _IOWR('N', 0x85, struct mutex_args)
|
||||
#define NT_MUTEX_KILL _IOW('N', 0x86, uint32_t)
|
||||
#define NT_CREATE_EVENT _IOW('N', 0x87, struct event_args)
|
||||
#define NT_EVENT_SET _IOR('N', 0x88, uint32_t)
|
||||
#define NT_EVENT_RESET _IOR('N', 0x89, uint32_t)
|
||||
#define NT_EVENT_PULSE _IOR('N', 0x8a, uint32_t)
|
||||
#define NT_SEM_READ _IOR('N', 0x8b, struct sem_args)
|
||||
#define NT_MUTEX_READ _IOR('N', 0x8c, struct mutex_args)
|
||||
#define NT_EVENT_READ _IOR('N', 0x8d, struct event_args)
|
||||
|
||||
int install_handler(int sig, void (*fn)(int, siginfo_t *, void *), void **seen);
|
||||
int install_oneshot(int sig, void (*fn)(int, siginfo_t *, void *));
|
||||
|
||||
static int dev, fails;
|
||||
#define CHECK(name, cond) do { if (!(cond)) { printf("FAIL %s line %d errno %d\n", name, __LINE__, errno); fails++; } } while (0)
|
||||
|
||||
static uint64_t mono_ns(int64_t delta_ms) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec + (uint64_t)(delta_ms * 1000000);
|
||||
}
|
||||
|
||||
static int wait_on(unsigned long req, const int *objs, uint32_t count, uint32_t owner, int alert, uint64_t timeout, uint32_t *index) {
|
||||
struct wait_args w = {timeout, (uintptr_t)objs, count, 0xdead, 0, owner, (uint32_t)alert, 0};
|
||||
int r = ioctl(dev, req, &w);
|
||||
if (index) *index = w.index;
|
||||
return r < 0 ? errno : 0;
|
||||
}
|
||||
|
||||
static int event(int manual, int signaled) {
|
||||
struct event_args a = {(uint32_t)manual, (uint32_t)signaled};
|
||||
return ioctl(dev, NT_CREATE_EVENT, &a);
|
||||
}
|
||||
|
||||
static int sem(uint32_t count, uint32_t max) {
|
||||
struct sem_args a = {count, max};
|
||||
return ioctl(dev, NT_CREATE_SEM, &a);
|
||||
}
|
||||
|
||||
static int mutex(uint32_t owner, uint32_t count) {
|
||||
struct mutex_args a = {owner, count};
|
||||
return ioctl(dev, NT_CREATE_MUTEX, &a);
|
||||
}
|
||||
|
||||
static uint32_t prev_of(int fd, unsigned long req, uint32_t in) {
|
||||
uint32_t v = in;
|
||||
if (ioctl(fd, req, &v) < 0) return 0xffffffff;
|
||||
return v;
|
||||
}
|
||||
|
||||
static void semaphores(void) {
|
||||
struct sem_args bad = {3, 2}, r;
|
||||
CHECK("sem_create_invalid", ioctl(dev, NT_CREATE_SEM, &bad) < 0 && errno == EINVAL);
|
||||
int s = sem(2, 2);
|
||||
CHECK("sem_create", s >= 0);
|
||||
uint32_t idx;
|
||||
CHECK("sem_wait1", wait_on(NT_WAIT_ANY, &s, 1, 1, 0, 0, &idx) == 0 && idx == 0);
|
||||
CHECK("sem_wait2", wait_on(NT_WAIT_ANY, &s, 1, 1, 0, 0, &idx) == 0);
|
||||
CHECK("sem_empty", wait_on(NT_WAIT_ANY, &s, 1, 1, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("sem_release_prev", prev_of(s, NT_SEM_RELEASE, 1) == 0);
|
||||
CHECK("sem_overflow", prev_of(s, NT_SEM_RELEASE, 2) == 0xffffffff && errno == EOVERFLOW);
|
||||
CHECK("sem_read", ioctl(s, NT_SEM_READ, &r) == 0 && r.count == 1 && r.max == 2);
|
||||
close(s);
|
||||
}
|
||||
|
||||
static void mutexes(void) {
|
||||
struct mutex_args bad = {0, 1}, r, u;
|
||||
CHECK("mutex_create_invalid", ioctl(dev, NT_CREATE_MUTEX, &bad) < 0 && errno == EINVAL);
|
||||
int m = mutex(0, 0);
|
||||
uint32_t idx;
|
||||
CHECK("mutex_owner_zero", wait_on(NT_WAIT_ANY, &m, 1, 0, 0, 0, NULL) == EINVAL);
|
||||
CHECK("mutex_take", wait_on(NT_WAIT_ANY, &m, 1, 7, 0, 0, &idx) == 0 && idx == 0);
|
||||
CHECK("mutex_recurse", wait_on(NT_WAIT_ANY, &m, 1, 7, 0, 0, NULL) == 0);
|
||||
CHECK("mutex_other", wait_on(NT_WAIT_ANY, &m, 1, 8, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("mutex_read", ioctl(m, NT_MUTEX_READ, &r) == 0 && r.owner == 7 && r.count == 2);
|
||||
u = (struct mutex_args){8, 0};
|
||||
CHECK("mutex_unlock_eperm", ioctl(m, NT_MUTEX_UNLOCK, &u) < 0 && errno == EPERM);
|
||||
u = (struct mutex_args){0, 0};
|
||||
CHECK("mutex_unlock_einval", ioctl(m, NT_MUTEX_UNLOCK, &u) < 0 && errno == EINVAL);
|
||||
u = (struct mutex_args){7, 0};
|
||||
CHECK("mutex_unlock_prev", ioctl(m, NT_MUTEX_UNLOCK, &u) == 0 && u.count == 2);
|
||||
uint32_t who = 8;
|
||||
CHECK("mutex_kill_eperm", ioctl(m, NT_MUTEX_KILL, &who) < 0 && errno == EPERM);
|
||||
who = 7;
|
||||
CHECK("mutex_kill", ioctl(m, NT_MUTEX_KILL, &who) == 0);
|
||||
CHECK("mutex_read_dead", ioctl(m, NT_MUTEX_READ, &r) < 0 && errno == EOWNERDEAD && r.owner == 0 && r.count == 0);
|
||||
CHECK("mutex_abandoned", wait_on(NT_WAIT_ANY, &m, 1, 9, 0, 0, &idx) == EOWNERDEAD && idx == 0);
|
||||
CHECK("mutex_after_abandon", ioctl(m, NT_MUTEX_READ, &r) == 0 && r.owner == 9 && r.count == 1);
|
||||
close(m);
|
||||
}
|
||||
|
||||
static void events(void) {
|
||||
int a = event(0, 1), m = event(1, 0);
|
||||
struct event_args r;
|
||||
CHECK("auto_take", wait_on(NT_WAIT_ANY, &a, 1, 1, 0, 0, NULL) == 0);
|
||||
CHECK("auto_consumed", wait_on(NT_WAIT_ANY, &a, 1, 1, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("set_prev0", prev_of(m, NT_EVENT_SET, 0) == 0);
|
||||
CHECK("set_prev1", prev_of(m, NT_EVENT_SET, 0) == 1);
|
||||
CHECK("manual_kept", wait_on(NT_WAIT_ANY, &m, 1, 1, 0, 0, NULL) == 0 && wait_on(NT_WAIT_ANY, &m, 1, 1, 0, 0, NULL) == 0);
|
||||
CHECK("reset_prev", prev_of(m, NT_EVENT_RESET, 0) == 1);
|
||||
CHECK("pulse_prev", prev_of(m, NT_EVENT_PULSE, 0) == 0);
|
||||
CHECK("pulse_leaves_unsignaled", ioctl(m, NT_EVENT_READ, &r) == 0 && r.manual == 1 && r.signaled == 0);
|
||||
close(a);
|
||||
close(m);
|
||||
}
|
||||
|
||||
static void any_order(void) {
|
||||
int o[4] = {event(1, 0), sem(1, 5), event(1, 1), sem(0, 5)};
|
||||
int alert = event(0, 1);
|
||||
uint32_t idx;
|
||||
CHECK("any_lowest", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, &idx) == 0 && idx == 1);
|
||||
CHECK("any_next", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, &idx) == 0 && idx == 2);
|
||||
prev_of(o[2], NT_EVENT_RESET, 0);
|
||||
CHECK("any_alert", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, &idx) == 0 && idx == 4);
|
||||
CHECK("any_alert_consumed", wait_on(NT_WAIT_ANY, o, 4, 1, alert, 0, NULL) == ETIMEDOUT);
|
||||
int dup[3] = {o[3], o[0], o[3]};
|
||||
prev_of(o[3], NT_SEM_RELEASE, 1);
|
||||
CHECK("any_duplicate_lowest", wait_on(NT_WAIT_ANY, dup, 3, 1, 0, 0, &idx) == 0 && idx == 0);
|
||||
int many[65];
|
||||
for (int i = 0; i < 65; i++) many[i] = o[0];
|
||||
CHECK("any_too_many", wait_on(NT_WAIT_ANY, many, 65, 1, 0, 0, NULL) == EINVAL);
|
||||
int badfd = 0;
|
||||
CHECK("any_invalid_fd", wait_on(NT_WAIT_ANY, &badfd, 1, 1, 0, 0, NULL) == EINVAL);
|
||||
CHECK("any_timeout", wait_on(NT_WAIT_ANY, o, 1, 1, 0, mono_ns(30), NULL) == ETIMEDOUT);
|
||||
for (int i = 0; i < 4; i++) close(o[i]);
|
||||
close(alert);
|
||||
}
|
||||
|
||||
static void all_semantics(void) {
|
||||
int s = sem(1, 5), e = event(0, 0), m = mutex(0, 0);
|
||||
int o[3] = {s, e, m};
|
||||
struct sem_args sr;
|
||||
uint32_t idx;
|
||||
CHECK("all_not_ready", wait_on(NT_WAIT_ALL, o, 3, 4, 0, 0, NULL) == ETIMEDOUT);
|
||||
CHECK("all_untouched", ioctl(s, NT_SEM_READ, &sr) == 0 && sr.count == 1);
|
||||
prev_of(e, NT_EVENT_SET, 0);
|
||||
CHECK("all_ready", wait_on(NT_WAIT_ALL, o, 3, 4, 0, 0, &idx) == 0 && idx == 0);
|
||||
CHECK("all_took_sem", ioctl(s, NT_SEM_READ, &sr) == 0 && sr.count == 0);
|
||||
int dup[2] = {s, s};
|
||||
CHECK("all_duplicate", wait_on(NT_WAIT_ALL, dup, 2, 4, 0, 0, NULL) == EINVAL);
|
||||
int alert = event(1, 1);
|
||||
CHECK("all_alert", wait_on(NT_WAIT_ALL, o, 3, 4, alert, 0, &idx) == 0 && idx == 3);
|
||||
close(s);
|
||||
close(e);
|
||||
close(m);
|
||||
close(alert);
|
||||
}
|
||||
|
||||
static int wake_obj;
|
||||
static uint32_t wake_index;
|
||||
static int wake_ret;
|
||||
static void *waiter(void *p) {
|
||||
int all = (int)(intptr_t)p;
|
||||
int objs[2] = {wake_obj, wake_obj + 0};
|
||||
wake_ret = wait_on(all ? NT_WAIT_ALL : NT_WAIT_ANY, objs, 1, 3, 0, UINT64_MAX, &wake_index);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void cross_thread(void) {
|
||||
wake_obj = event(0, 0);
|
||||
pthread_t t;
|
||||
pthread_create(&t, NULL, waiter, NULL);
|
||||
usleep(30000);
|
||||
prev_of(wake_obj, NT_EVENT_SET, 0);
|
||||
pthread_join(t, NULL);
|
||||
CHECK("thread_wake", wake_ret == 0 && wake_index == 0);
|
||||
struct event_args r;
|
||||
CHECK("thread_auto_reset", ioctl(wake_obj, NT_EVENT_READ, &r) == 0 && r.signaled == 0);
|
||||
close(wake_obj);
|
||||
int s = sem(0, 10);
|
||||
wake_obj = s;
|
||||
pthread_t ts[3];
|
||||
for (int i = 0; i < 3; i++) pthread_create(&ts[i], NULL, waiter, NULL);
|
||||
usleep(30000);
|
||||
CHECK("sem_release_three", prev_of(s, NT_SEM_RELEASE, 3) == 0);
|
||||
for (int i = 0; i < 3; i++) pthread_join(ts[i], NULL);
|
||||
struct sem_args sr;
|
||||
CHECK("sem_all_taken", ioctl(s, NT_SEM_READ, &sr) == 0 && sr.count == 0);
|
||||
close(s);
|
||||
}
|
||||
|
||||
static void cross_process(void) {
|
||||
int sv[2];
|
||||
CHECK("socketpair", socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
|
||||
int inherited = event(0, 0);
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
uint32_t idx;
|
||||
int r1 = wait_on(NT_WAIT_ANY, &inherited, 1, 5, 0, mono_ns(5000), &idx);
|
||||
char c;
|
||||
struct iovec io = {&c, 1};
|
||||
char cbuf[CMSG_SPACE(sizeof(int))];
|
||||
struct msghdr msg = {0};
|
||||
msg.msg_iov = &io;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = cbuf;
|
||||
msg.msg_controllen = sizeof(cbuf);
|
||||
int got = -1;
|
||||
if (recvmsg(sv[1], &msg, 0) == 1) memcpy(&got, CMSG_DATA(CMSG_FIRSTHDR(&msg)), sizeof(int));
|
||||
int r2 = wait_on(NT_WAIT_ANY, &got, 1, 5, 0, mono_ns(5000), NULL);
|
||||
_exit(r1 == 0 && r2 == 0 ? 0 : 1);
|
||||
}
|
||||
usleep(30000);
|
||||
prev_of(inherited, NT_EVENT_SET, 0);
|
||||
int sent = sem(0, 1);
|
||||
char c = 'x';
|
||||
struct iovec io = {&c, 1};
|
||||
char cbuf[CMSG_SPACE(sizeof(int))];
|
||||
struct msghdr msg = {0};
|
||||
msg.msg_iov = &io;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = cbuf;
|
||||
msg.msg_controllen = sizeof(cbuf);
|
||||
struct cmsghdr *cm = CMSG_FIRSTHDR(&msg);
|
||||
cm->cmsg_level = SOL_SOCKET;
|
||||
cm->cmsg_type = SCM_RIGHTS;
|
||||
cm->cmsg_len = CMSG_LEN(sizeof(int));
|
||||
memcpy(CMSG_DATA(cm), &sent, sizeof(int));
|
||||
sendmsg(sv[0], &msg, 0);
|
||||
usleep(30000);
|
||||
prev_of(sent, NT_SEM_RELEASE, 1);
|
||||
int status = 0;
|
||||
waitpid(pid, &status, 0);
|
||||
CHECK("process_wake", WIFEXITED(status) && WEXITSTATUS(status) == 0);
|
||||
close(inherited);
|
||||
close(sent);
|
||||
close(sv[0]);
|
||||
close(sv[1]);
|
||||
}
|
||||
|
||||
static int ping_obj, pong_obj, stress_sem;
|
||||
static void *stress_ponger(void *p) {
|
||||
long n = (long)p;
|
||||
uint32_t v;
|
||||
for (long i = 0; i < n; i++) {
|
||||
if (wait_on(NT_WAIT_ANY, &ping_obj, 1, 21, 0, UINT64_MAX, NULL) != 0) return (void *)1;
|
||||
ioctl(pong_obj, NT_EVENT_SET, &v);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
static void *stress_hammer(void *p) {
|
||||
long n = (long)p;
|
||||
for (long i = 0; i < n; i++) {
|
||||
if (wait_on(NT_WAIT_ANY, &stress_sem, 1, 22, 0, UINT64_MAX, NULL) != 0) return (void *)1;
|
||||
uint32_t c = 1;
|
||||
ioctl(stress_sem, NT_SEM_RELEASE, &c);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void stress(void) {
|
||||
long rounds = 20000;
|
||||
ping_obj = event(0, 0);
|
||||
pong_obj = event(0, 0);
|
||||
pthread_t t;
|
||||
void *bad = NULL;
|
||||
pthread_create(&t, NULL, stress_ponger, (void *)rounds);
|
||||
uint32_t v;
|
||||
int ok = 1;
|
||||
for (long i = 0; i < rounds && ok; i++) {
|
||||
ioctl(ping_obj, NT_EVENT_SET, &v);
|
||||
ok = wait_on(NT_WAIT_ANY, &pong_obj, 1, 20, 0, UINT64_MAX, NULL) == 0;
|
||||
}
|
||||
pthread_join(t, &bad);
|
||||
CHECK("stress_pingpong", ok && bad == NULL);
|
||||
stress_sem = sem(1, 1);
|
||||
pthread_t th[4];
|
||||
for (int i = 0; i < 4; i++) pthread_create(&th[i], NULL, stress_hammer, (void *)5000L);
|
||||
int hammer_ok = 1;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
pthread_join(th[i], &bad);
|
||||
hammer_ok &= bad == NULL;
|
||||
}
|
||||
struct sem_args sr;
|
||||
CHECK("stress_contended", hammer_ok && ioctl(stress_sem, NT_SEM_READ, &sr) == 0 && sr.count == 1);
|
||||
close(ping_obj);
|
||||
close(pong_obj);
|
||||
close(stress_sem);
|
||||
}
|
||||
|
||||
static int busy_obj;
|
||||
static volatile int handled, stop_worker;
|
||||
static sem_t parked, unpark;
|
||||
static void reentrant(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
uint32_t v = 0;
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
handled++;
|
||||
}
|
||||
static void suspending(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
sem_post(&parked);
|
||||
while (sem_wait(&unpark) != 0) {}
|
||||
handled++;
|
||||
}
|
||||
static void *worker(void *p) {
|
||||
(void)p;
|
||||
uint32_t v;
|
||||
while (!stop_worker) {
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
wait_on(NT_WAIT_ANY, &busy_obj, 1, 11, 0, 0, NULL);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void signals(void) {
|
||||
void *seen = NULL;
|
||||
busy_obj = event(0, 0);
|
||||
CHECK("install_reentrant", install_handler(SIGUSR1, reentrant, &seen) == 0);
|
||||
CHECK("query_original", seen == (void *)reentrant);
|
||||
pthread_t w;
|
||||
stop_worker = 0;
|
||||
handled = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
pthread_kill(w, SIGUSR1);
|
||||
if (i % 64 == 0) usleep(100);
|
||||
}
|
||||
usleep(20000);
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("reentrant_ran", handled > 0);
|
||||
sem_init(&parked, 0, 0);
|
||||
sem_init(&unpark, 0, 0);
|
||||
CHECK("install_suspending", install_handler(SIGUSR1, suspending, &seen) == 0);
|
||||
stop_worker = 0;
|
||||
handled = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
uint32_t v;
|
||||
for (int i = 0; i < 300; i++) {
|
||||
pthread_kill(w, SIGUSR1);
|
||||
while (sem_wait(&parked) != 0) {}
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
wait_on(NT_WAIT_ANY, &busy_obj, 1, 12, 0, 0, NULL);
|
||||
sem_post(&unpark);
|
||||
}
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("suspend_ran", handled == 300);
|
||||
close(busy_obj);
|
||||
}
|
||||
|
||||
static volatile int burst_count;
|
||||
static void bursting(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
uint32_t v = 0;
|
||||
ioctl(busy_obj, NT_EVENT_SET, &v);
|
||||
__atomic_add_fetch(&burst_count, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
static void bursts(void) {
|
||||
void *seen = NULL;
|
||||
busy_obj = event(0, 0);
|
||||
for (int s = 0; s < 8; s++) CHECK("install_burst", install_handler(SIGRTMIN + s, bursting, &seen) == 0);
|
||||
pthread_t w;
|
||||
stop_worker = 0;
|
||||
burst_count = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
union sigval val = {0};
|
||||
int sent = 0;
|
||||
for (int i = 0; i < 400; i++) {
|
||||
for (int s = 0; s < 8; s++)
|
||||
if (pthread_sigqueue(w, SIGRTMIN + s, val) == 0) sent++;
|
||||
usleep(200);
|
||||
}
|
||||
for (int i = 0; i < 2000 && __atomic_load_n(&burst_count, __ATOMIC_RELAXED) < sent; i++) usleep(1000);
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("burst_all_handled", burst_count == sent && sent > 0);
|
||||
close(busy_obj);
|
||||
}
|
||||
|
||||
static volatile int oneshot_count;
|
||||
static void oneshot(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
__atomic_add_fetch(&oneshot_count, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
static void oneshots(void) {
|
||||
busy_obj = event(0, 0);
|
||||
pthread_t w;
|
||||
stop_worker = 0;
|
||||
oneshot_count = 0;
|
||||
pthread_create(&w, NULL, worker, NULL);
|
||||
int fired = 0;
|
||||
for (int i = 0; i < 300; i++) {
|
||||
if (install_oneshot(SIGWINCH, oneshot) != 0) break;
|
||||
int before = __atomic_load_n(&oneshot_count, __ATOMIC_RELAXED);
|
||||
pthread_kill(w, SIGWINCH);
|
||||
fired++;
|
||||
for (int j = 0; j < 2000 && __atomic_load_n(&oneshot_count, __ATOMIC_RELAXED) == before; j++) usleep(50);
|
||||
}
|
||||
stop_worker = 1;
|
||||
pthread_join(w, NULL);
|
||||
CHECK("oneshot_handlers_run", oneshot_count == fired && fired == 300);
|
||||
close(busy_obj);
|
||||
}
|
||||
|
||||
static int outer_obj, inner_obj, other_dev, other_obj;
|
||||
static volatile int nested_ok, nested_done, outer_done;
|
||||
static void nesting(int sig, siginfo_t *si, void *uc) {
|
||||
(void)sig; (void)si; (void)uc;
|
||||
uint32_t idx = 99;
|
||||
int ok = wait_on(NT_WAIT_ANY, &inner_obj, 1, 21, 0, mono_ns(50), &idx) == 0 && idx == 0;
|
||||
struct wait_args w = {mono_ns(2), (uintptr_t)&other_obj, 1, 0xdead, 0, 22, 0, 0};
|
||||
ok = ok && ioctl(other_dev, NT_WAIT_ANY, &w) < 0 && errno == ETIMEDOUT;
|
||||
nested_ok += ok;
|
||||
__atomic_store_n(&nested_done, 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
static void *outer_waiter(void *p) {
|
||||
struct wait_args w = {mono_ns(3000), (uintptr_t)&outer_obj, 1, 99, 0, 23, 0, 0};
|
||||
int r;
|
||||
do { r = ioctl(dev, NT_WAIT_ANY, &w); } while (r < 0 && errno == EINTR);
|
||||
*(int *)p = r == 0 && w.index == 0;
|
||||
__atomic_store_n(&outer_done, 1, __ATOMIC_RELEASE);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void nested_waits(void) {
|
||||
void *seen = NULL;
|
||||
other_dev = open("/dev/ntsync", O_RDWR | O_CLOEXEC);
|
||||
CHECK("second_device", other_dev >= 0);
|
||||
struct event_args ea = {0, 0};
|
||||
other_obj = ioctl(other_dev, NT_CREATE_EVENT, &ea);
|
||||
inner_obj = event(1, 1);
|
||||
CHECK("install_nesting", install_handler(SIGUSR2, nesting, &seen) == 0);
|
||||
int good = 0, early = 0;
|
||||
nested_ok = 0;
|
||||
for (int i = 0; i < 40; i++) {
|
||||
outer_obj = event(0, 0);
|
||||
int result = 0;
|
||||
pthread_t t;
|
||||
nested_done = outer_done = 0;
|
||||
pthread_create(&t, NULL, outer_waiter, &result);
|
||||
usleep(5000);
|
||||
pthread_kill(t, SIGUSR2);
|
||||
while (!__atomic_load_n(&nested_done, __ATOMIC_ACQUIRE)) usleep(200);
|
||||
usleep(5000);
|
||||
early += __atomic_load_n(&outer_done, __ATOMIC_ACQUIRE);
|
||||
uint32_t v = 0;
|
||||
ioctl(outer_obj, NT_EVENT_SET, &v);
|
||||
pthread_join(t, NULL);
|
||||
good += result;
|
||||
close(outer_obj);
|
||||
}
|
||||
CHECK("outer_wait_not_woken_by_nested_wait", early == 0);
|
||||
CHECK("outer_wait_survives_nested_waits", good == 40);
|
||||
CHECK("nested_waits_complete", nested_ok == 40);
|
||||
close(inner_obj);
|
||||
close(other_obj);
|
||||
close(other_dev);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
alarm(60);
|
||||
dev = open("/dev/ntsync", O_RDWR | O_CLOEXEC);
|
||||
if (dev < 0) {
|
||||
printf("no device %d\n", errno);
|
||||
return 1;
|
||||
}
|
||||
semaphores();
|
||||
mutexes();
|
||||
events();
|
||||
any_order();
|
||||
all_semantics();
|
||||
cross_thread();
|
||||
cross_process();
|
||||
stress();
|
||||
signals();
|
||||
bursts();
|
||||
oneshots();
|
||||
nested_waits();
|
||||
printf("done fails=%d\n", fails);
|
||||
return fails != 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NtsyncPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not shutil.which("cc"):
|
||||
raise unittest.SkipTest("no compiler")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), *sources, "-ldl"],
|
||||
check=True)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run(["cc", "-O1", "-pthread", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"),
|
||||
"-Wl,-rpath," + str(tmp)], check=True)
|
||||
cls.program = tmp / "prog"
|
||||
cls.preload = tmp / "libblsession.so"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self):
|
||||
env = dict(os.environ, LD_PRELOAD=str(self.preload), BL_SYNC="1")
|
||||
return subprocess.run([str(self.program)], env=env, capture_output=True, text=True, timeout=90)
|
||||
|
||||
def test_emulation_matches_the_ntsync_driver(self):
|
||||
out = self.run_program()
|
||||
self.assertEqual(out.returncode, 0, out.stdout + out.stderr)
|
||||
self.assertIn("done fails=0", out.stdout)
|
||||
|
||||
def test_repeated_runs_stay_consistent(self):
|
||||
for _ in range(3):
|
||||
out = self.run_program()
|
||||
self.assertEqual(out.returncode, 0, out.stdout + out.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,187 @@
|
||||
import copy
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location('preload_snapshots', Path(__file__).resolve().parents[1] / 'components/preloads.py')
|
||||
snapshots = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(snapshots)
|
||||
|
||||
|
||||
def archive(files):
|
||||
stream = io.BytesIO()
|
||||
with tarfile.open(fileobj=stream, mode='w:gz') as tar:
|
||||
for name, content in files.items():
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = len(content)
|
||||
tar.addfile(entry, io.BytesIO(content))
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
class PreloadSnapshotTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name)
|
||||
# Real repository inputs exercise the transitive include walker and build recipe.
|
||||
for group in snapshots.INPUTS:
|
||||
for name in snapshots.source_files(group):
|
||||
if name.startswith('@'):
|
||||
continue
|
||||
target = self.root / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes((snapshots.ROOT / name).read_bytes())
|
||||
recipe = 'tools/components/build-arm64-preloads.sh'
|
||||
(self.root / recipe).parent.mkdir(parents=True, exist_ok=True)
|
||||
(self.root / recipe).write_text((snapshots.ROOT / recipe).read_text())
|
||||
x86 = 'tools/components/recipes/x86-preloads.sh'
|
||||
(self.root / x86).parent.mkdir(parents=True, exist_ok=True)
|
||||
(self.root / x86).write_text((snapshots.ROOT / x86).read_text())
|
||||
(self.root / '.github/workflows').mkdir(parents=True)
|
||||
(self.root / '.github/workflows/build.yml').write_text((snapshots.ROOT / '.github/workflows/build.yml').read_text())
|
||||
self.git('init', '-q')
|
||||
self.git('config', 'core.autocrlf', 'false')
|
||||
self.git('config', 'user.name', 'Test Developer')
|
||||
self.git('config', 'user.email', 'test@example.test')
|
||||
self.git('add', '.')
|
||||
self.binaries = {name: ('verified-' + name).encode() for name in snapshots.FILES}
|
||||
self.content = archive(self.binaries)
|
||||
self.data = dict(version=1, origin=dict(run=123, commit='abc', artifact=456, artifact_sha256='0' * 64),
|
||||
groups={g: snapshots.source_files(g, self.root) for g in snapshots.INPUTS},
|
||||
arm64_recipe=snapshots.recipe(self.root), x86_recipe=snapshots.x86_recipe(self.root),
|
||||
archive_sha256=snapshots.sha(self.content),
|
||||
outputs={name: snapshots.sha(value) for name, value in self.binaries.items()})
|
||||
(self.root / snapshots.LOCK).write_text(json.dumps(self.data))
|
||||
self.git('add', '.')
|
||||
self.git('commit', '-qm', 'Approved baseline')
|
||||
self.base = self.git('rev-parse', 'HEAD').strip()
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.check_output(['git', *args], cwd=self.root, text=True)
|
||||
|
||||
def restore(self, base=None):
|
||||
with patch.dict(os.environ, COMPONENT_TRUSTED_BASE=base or self.base, FORCE_PRELOAD_REBUILD='false'), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', return_value=io.BytesIO(self.content)) as fetch, \
|
||||
patch.object(snapshots, 'prove_origin') as prove:
|
||||
result = snapshots.restore(self.root)
|
||||
return result, fetch, prove
|
||||
|
||||
def test_reviewed_unchanged_binaries_reused_and_written(self):
|
||||
result, fetch, prove = self.restore()
|
||||
self.assertEqual(result, dict(arm64=True, x86=True))
|
||||
prove.assert_not_called()
|
||||
fetch.assert_called_once()
|
||||
for name, value in self.binaries.items():
|
||||
self.assertEqual((self.root / 'app/src/main/assets/linuxfs' / name).read_bytes(), value)
|
||||
|
||||
def test_changed_common_source_requires_both_rebuilds(self):
|
||||
path = self.root / snapshots.COMMON[0]
|
||||
path.write_text(path.read_text() + '\n// Changed source\n')
|
||||
result, fetch, prove = self.restore()
|
||||
self.assertEqual(result, dict(arm64=False, x86=False))
|
||||
fetch.assert_not_called()
|
||||
prove.assert_not_called()
|
||||
|
||||
def test_new_transitive_header_is_an_input(self):
|
||||
source = self.root / snapshots.COMMON[0]
|
||||
source.write_text(source.read_text() + '\n#include "new-header.h"\n')
|
||||
header = source.with_name('new-header.h')
|
||||
header.write_text('#define VALUE 1\n')
|
||||
before = snapshots.source_files('arm64', self.root)
|
||||
header.write_text('#define VALUE 2\n')
|
||||
self.assertNotEqual(before, snapshots.source_files('arm64', self.root))
|
||||
|
||||
def test_changed_recipe_rebuilds_arm64_only(self):
|
||||
script = self.root / 'tools/components/build-arm64-preloads.sh'
|
||||
script.write_text(script.read_text().replace('-O2', '-O3'))
|
||||
result, _, _ = self.restore()
|
||||
self.assertEqual(result, dict(arm64=False, x86=True))
|
||||
|
||||
def test_shell_newline_changes_invalidate_the_recipe(self):
|
||||
script = self.root / 'tools/components/build-arm64-preloads.sh'
|
||||
original = snapshots.recipe(self.root)
|
||||
text = script.read_text()
|
||||
script.write_text(text.replace('-ldl\n', '-ldl ', 1))
|
||||
self.assertNotEqual(original, snapshots.recipe(self.root))
|
||||
|
||||
def test_x86_container_recipe_changes_rebuild_x86_only(self):
|
||||
script = self.root / 'tools/components/recipes/x86-preloads.sh'
|
||||
script.write_text(script.read_text().replace('debian:bullseye', 'debian:bookworm'))
|
||||
result, _, _ = self.restore()
|
||||
self.assertEqual(result, dict(arm64=True, x86=False))
|
||||
|
||||
def test_new_manifest_requires_main_build_proof(self):
|
||||
result, _, prove = self.restore('HEAD~1')
|
||||
self.assertTrue(all(result.values()))
|
||||
prove.assert_called_once()
|
||||
|
||||
def test_forged_binary_hash_cannot_prove_main_origin(self):
|
||||
data = copy.deepcopy(self.data)
|
||||
data['outputs']['libblsession.so'] = 'f' * 64
|
||||
with patch.object(snapshots, 'artifact_bytes', return_value=self.binaries):
|
||||
with self.assertRaisesRegex(ValueError, 'original main APK'):
|
||||
snapshots.prove_origin(data, self.root / 'cache', self.root)
|
||||
|
||||
def test_modified_input_policy_cannot_omit_producer_dependencies(self):
|
||||
data = copy.deepcopy(self.data)
|
||||
data['origin']['commit'] = self.base
|
||||
omitted = snapshots.COMMON[0]
|
||||
del data['groups']['arm64'][omitted]
|
||||
with patch.object(snapshots, 'artifact_bytes', return_value=self.binaries), \
|
||||
patch.object(snapshots, 'run', return_value=b''), \
|
||||
patch.object(snapshots, 'source_files', side_effect=lambda group, *args: data['groups'][group]), \
|
||||
patch.object(snapshots, 'producer_sources', return_value={omitted: self.data['groups']['arm64'][omitted]}):
|
||||
with self.assertRaisesRegex(ValueError, 'producing build dependency'):
|
||||
snapshots.prove_origin(data, self.root / 'cache', self.root)
|
||||
|
||||
def test_non_main_or_unsuccessful_run_cannot_prove_origin(self):
|
||||
build = dict(event='pull_request', head_branch='main', conclusion='success', head_sha='abc',
|
||||
path='.github/workflows/build.yml', repository=dict(full_name=snapshots.REPO))
|
||||
for field, value in [('event', 'pull_request'), ('head_branch', 'feature'), ('conclusion', 'failure')]:
|
||||
candidate = dict(build, event='push')
|
||||
candidate[field] = value
|
||||
with self.subTest(field=field), patch.object(snapshots, 'api', return_value=candidate):
|
||||
with self.assertRaisesRegex(ValueError, 'successful main'):
|
||||
snapshots.artifact_bytes(self.data['origin'], self.root / 'cache')
|
||||
|
||||
def test_corrupt_archive_is_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'):
|
||||
snapshots.unpack(self.content + b'tampered', self.data)
|
||||
|
||||
def test_missing_duplicate_or_traversal_entries_are_rejected(self):
|
||||
for files in ({}, {'../escaped': b'bad'}, {'libblsession.so': b'wrong'}):
|
||||
content = archive(files)
|
||||
data = dict(self.data, archive_sha256=snapshots.sha(content))
|
||||
with self.subTest(names=list(files)), self.assertRaises(ValueError):
|
||||
snapshots.unpack(content, data)
|
||||
|
||||
def test_missing_release_rebuilds_without_accepting_unverified_bytes(self):
|
||||
error = snapshots.urllib.error.HTTPError('https://example.test', 404, 'missing', {}, None)
|
||||
with patch.dict(os.environ, COMPONENT_TRUSTED_BASE=self.base), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', side_effect=error):
|
||||
self.assertEqual(snapshots.restore(self.root), dict(arm64=False, x86=False))
|
||||
|
||||
def test_transient_download_failure_rebuilds_but_integrity_errors_fail(self):
|
||||
errors = [TimeoutError('network'), snapshots.http.client.IncompleteRead(b'partial'),
|
||||
snapshots.urllib.error.HTTPError('https://example.test', 503, 'unavailable', {}, None)]
|
||||
for error in errors:
|
||||
with self.subTest(error=type(error).__name__), patch.dict(os.environ, COMPONENT_TRUSTED_BASE=self.base), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', side_effect=error):
|
||||
self.assertEqual(snapshots.restore(self.root), dict(arm64=False, x86=False))
|
||||
with patch.dict(os.environ, COMPONENT_TRUSTED_BASE=self.base), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen', return_value=io.BytesIO(b'corrupt')):
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'):
|
||||
snapshots.restore(self.root)
|
||||
|
||||
def test_manual_rebuild_does_not_download_snapshot(self):
|
||||
with patch.dict(os.environ, FORCE_PRELOAD_REBUILD='true'), \
|
||||
patch.object(snapshots.urllib.request, 'urlopen') as fetch:
|
||||
self.assertEqual(snapshots.restore(self.root), dict(arm64=False, x86=False))
|
||||
fetch.assert_not_called()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The XTest cursor path is enabled only for Steam sessions."""
|
||||
"""Gamescope composites the cursor only when a Steam session asks for it."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
@@ -8,29 +8,37 @@ import unittest
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
SOURCE = SESSION.read_text()
|
||||
MATCH = re.search(
|
||||
r'^ if \[ "\$mode" = steam \]; then\n.*?^ fi\n', SOURCE, re.M | re.S)
|
||||
r'^ if \[ "\$mode" = steam \] && \[ "\$\{BL_CURSOR_COMPOSITE:-0\}" = 1 \]; then\n.*?^ fi\n',
|
||||
SOURCE, re.M | re.S)
|
||||
assert MATCH is not None
|
||||
CURSOR_SETUP = MATCH.group(0)
|
||||
|
||||
|
||||
class SessionCursorRoutingTest(unittest.TestCase):
|
||||
def run_setup(self, mode, initial=None):
|
||||
def run_setup(self, mode, initial=None, composite=None):
|
||||
env = dict(os.environ, mode=mode)
|
||||
if initial is not None:
|
||||
env['gamescope_cursor_composite'] = initial
|
||||
else:
|
||||
env.pop('gamescope_cursor_composite', None)
|
||||
if composite is not None:
|
||||
env['BL_CURSOR_COMPOSITE'] = composite
|
||||
else:
|
||||
env.pop('BL_CURSOR_COMPOSITE', None)
|
||||
result = subprocess.run(
|
||||
['bash', '-c', CURSOR_SETUP + 'printf "%s\n" "${gamescope_cursor_composite-}"'],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_steam_enables_manual_composition_for_the_nested_cursor(self):
|
||||
self.assertEqual('2', self.run_setup('steam'))
|
||||
def test_steam_leaves_the_cursor_with_the_host_unless_asked(self):
|
||||
self.assertEqual('', self.run_setup('steam'))
|
||||
|
||||
def test_steam_composites_the_cursor_when_the_setting_is_on(self):
|
||||
self.assertEqual('2', self.run_setup('steam', composite='1'))
|
||||
|
||||
def test_other_sessions_keep_their_existing_cursor_composition(self):
|
||||
self.assertEqual('', self.run_setup('desktop'))
|
||||
self.assertEqual('1', self.run_setup('run', '1'))
|
||||
self.assertEqual('', self.run_setup('desktop', composite='1'))
|
||||
self.assertEqual('1', self.run_setup('run', '1', composite='1'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -56,7 +56,7 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
|
||||
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests))
|
||||
for channel in ('steamdeck_publicbeta',):
|
||||
for channel in ('steamdeck_publicbeta', 'steamdeck_stable'):
|
||||
archive = self.cdn / (channel + '.zip')
|
||||
with zipfile.ZipFile(archive, 'w') as package:
|
||||
package.writestr('steamrtarm64/steam', channel)
|
||||
@@ -68,12 +68,17 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def install(self, fail_host=None):
|
||||
def install(self, fail_host=None, *args, **extra):
|
||||
env = self.env if fail_host is None else dict(self.env, TEST_FAIL_HOST=fail_host)
|
||||
return subprocess.run(['bash', str(SCRIPT)], env=env, text=True, capture_output=True)
|
||||
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True)
|
||||
|
||||
def assert_installed(self, channel='steamdeck_publicbeta', fail_host=None, expected=None):
|
||||
result = self.install(fail_host)
|
||||
def channel(self, **extra):
|
||||
result = self.install(None, '--channel', **extra)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return result.stdout.strip()
|
||||
|
||||
def assert_installed(self, channel='steamdeck_publicbeta', fail_host=None, expected=None, **extra):
|
||||
result = self.install(fail_host, **extra)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(channel + '\n', (self.steam / 'package/beta').read_text())
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
|
||||
@@ -87,6 +92,7 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
'https://client-update.steamstatic.com/' + channel + '.zip',
|
||||
]
|
||||
self.assertEqual(expected, self.requests.read_text().splitlines())
|
||||
return result
|
||||
|
||||
def test_downloads_the_deck_beta_client(self):
|
||||
self.assert_installed()
|
||||
@@ -155,8 +161,80 @@ cp "$TEST_CDN/${url##*/}" "$out"
|
||||
self.requests.unlink()
|
||||
with (package / 'droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\nstart\n')
|
||||
self.assertEqual(0, self.install(BL_STEAM_CHANNEL='beta').returncode)
|
||||
self.assertFalse(self.requests.exists())
|
||||
|
||||
def test_the_default_channel_is_the_deck_beta(self):
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel())
|
||||
|
||||
def stable_requests(self, beta_manifest=True):
|
||||
stable = [
|
||||
'https://client-update.steamstatic.com/steam_client_steamdeck_stable_linuxarm64',
|
||||
'https://client-update.steamstatic.com/steamdeck_stable.zip',
|
||||
]
|
||||
if beta_manifest:
|
||||
stable.insert(0, 'https://client-update.steamstatic.com/steam_client_steamdeck_publicbeta_linuxarm64')
|
||||
return stable
|
||||
|
||||
def test_a_repaired_beta_client_that_still_shows_nothing_falls_back_to_stable(self):
|
||||
package = self.break_client(2)
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.requests.unlink()
|
||||
with (package / 'droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\n')
|
||||
result = self.assert_installed('steamdeck_stable', expected=self.stable_requests(False))
|
||||
self.assertIn("falling back to Valve's steamdeck_stable Steam client", result.stdout)
|
||||
self.assertEqual('steamdeck_stable\n', (package / 'droiddeck-channel').read_text())
|
||||
self.assertEqual('repaired\n', (package / 'droiddeck-unconfirmed').read_text())
|
||||
self.assertEqual('steamdeck_stable', self.channel())
|
||||
|
||||
def test_the_stable_fallback_is_not_repeated(self):
|
||||
self.test_a_repaired_beta_client_that_still_shows_nothing_falls_back_to_stable()
|
||||
self.requests.unlink()
|
||||
with (self.steam / 'package/droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\nstart\n')
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.assertFalse(self.requests.exists())
|
||||
self.assertEqual('steamdeck_stable\n', (self.steam / 'package/beta').read_text())
|
||||
|
||||
def test_a_pinned_beta_channel_never_falls_back(self):
|
||||
package = self.break_client(2)
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
with (package / 'droiddeck-unconfirmed').open('a') as marker:
|
||||
marker.write('start\nstart\n')
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel(BL_STEAM_CHANNEL='beta'))
|
||||
self.assertEqual(0, self.install(BL_STEAM_CHANNEL='beta').returncode)
|
||||
self.assertFalse((package / 'droiddeck-channel').exists())
|
||||
|
||||
def test_the_channel_setting_selects_stable(self):
|
||||
setting = self.home / '.config/droiddeck/steam-channel'
|
||||
setting.parent.mkdir(parents=True)
|
||||
setting.write_text('stable\n')
|
||||
self.assertEqual('steamdeck_stable', self.channel())
|
||||
self.assert_installed('steamdeck_stable', expected=self.stable_requests(False))
|
||||
self.assertFalse((self.steam / 'package/droiddeck-channel').exists())
|
||||
|
||||
def empty_beta_manifest(self):
|
||||
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
|
||||
'"linuxarm64"\n{\n\t"version" "123457"\n'
|
||||
'\t"client_steamrtarm64_linuxarm64"\n\t{\n'
|
||||
'\t\t"file" "client.zip"\n\t\t"sha2" "00"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def test_a_beta_manifest_without_an_arm64_client_falls_back_to_stable(self):
|
||||
self.empty_beta_manifest()
|
||||
result = self.assert_installed('steamdeck_stable', expected=self.stable_requests())
|
||||
self.assertIn('no client components in steam_client_steamdeck_publicbeta_linuxarm64', result.stderr)
|
||||
self.assertIn('client_steamrtarm64_linuxarm64', result.stderr)
|
||||
self.assertEqual('steamdeck_stable\n', (self.steam / 'package/droiddeck-channel').read_text())
|
||||
self.assertEqual('steamdeck_stable', self.channel())
|
||||
|
||||
def test_a_pinned_beta_manifest_without_an_arm64_client_fails_and_names_its_blocks(self):
|
||||
self.empty_beta_manifest()
|
||||
result = self.install(BL_STEAM_CHANNEL='beta')
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertIn('client_steamrtarm64_linuxarm64', result.stderr)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
|
||||
def test_requested_repair_runs_once_and_is_retried_until_it_completes(self):
|
||||
package = self.break_client(0)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
MODULE = runpy.run_path(str(BIN / 'droiddeck-steam-shaders'))
|
||||
apply = MODULE['apply']
|
||||
set_text = MODULE['set_text']
|
||||
parse = runpy.run_path(str(BIN / 'droiddeck-steam-ui-scale'))['parse']
|
||||
|
||||
THOR = '''"InstallConfigStore"
|
||||
{
|
||||
\t"Software"
|
||||
\t{
|
||||
\t\t"Valve"
|
||||
\t\t{
|
||||
\t\t\t"Steam"
|
||||
\t\t\t{
|
||||
\t\t\t\t"ShaderCacheManager"
|
||||
\t\t\t\t{
|
||||
\t\t\t\t\t"HasCurrentBucket"\t\t"1"
|
||||
\t\t\t\t\t"ProcessingQueue"\t\t"207140;848350;"
|
||||
\t\t\t\t\t"App"
|
||||
\t\t\t\t\t{
|
||||
\t\t\t\t\t}
|
||||
\t\t\t\t}
|
||||
\t\t\t}
|
||||
\t\t}
|
||||
\t}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def disabled(text):
|
||||
steam = parse(text).get('InstallConfigStore').get('Software').get('Valve').get('Steam')
|
||||
return steam.get('ShaderCacheManager').get('DisableShaderCache')
|
||||
|
||||
|
||||
class SteamShadersTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.config = self.root / 'config/config.vdf'
|
||||
self.config.parent.mkdir()
|
||||
|
||||
def test_off_adds_the_key_the_client_writes(self):
|
||||
text, changed = set_text(THOR, False)
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual('1', disabled(text))
|
||||
self.assertIn('\t\t\t\t\t"DisableShaderCache"\t\t"1"\n\t\t\t\t}', text)
|
||||
self.assertIn('"ProcessingQueue"\t\t"207140;848350;"', text)
|
||||
|
||||
def test_existing_value_is_replaced_in_place(self):
|
||||
off, _ = set_text(THOR, False)
|
||||
on, changed = set_text(off, True)
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual('0', disabled(on))
|
||||
self.assertEqual(off.replace('"DisableShaderCache"\t\t"1"', '"DisableShaderCache"\t\t"0"'), on)
|
||||
|
||||
def test_matching_value_leaves_the_file_alone(self):
|
||||
off, _ = set_text(THOR, False)
|
||||
self.assertEqual((off, False), set_text(off, False))
|
||||
|
||||
def test_missing_sections_are_created(self):
|
||||
text, changed = set_text('"InstallConfigStore"\n{\n}\n', False)
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual('1', disabled(text))
|
||||
|
||||
def test_apply_writes_config_and_creates_a_fresh_one(self):
|
||||
self.config.write_text(THOR)
|
||||
self.assertTrue(apply(self.root, False))
|
||||
self.assertEqual('1', disabled(self.config.read_text()))
|
||||
self.assertFalse(apply(self.root, False))
|
||||
fresh = Path(self.temp.name) / 'fresh'
|
||||
fresh.mkdir()
|
||||
self.assertTrue(apply(fresh, True))
|
||||
self.assertEqual('0', disabled((fresh / 'config/config.vdf').read_text()))
|
||||
|
||||
def test_invalid_config_is_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
set_text('"InstallConfigStore" {', False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,123 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
SHIM = BIN / 'droiddeck-steamrt-shim'
|
||||
SESSION = (BIN / 'droiddeck-session').read_text()
|
||||
X64 = (BIN / 'droiddeck-steam-x64').read_text()
|
||||
|
||||
|
||||
class SteamrtShimTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.client = self.root / 'steamrtarm64'
|
||||
self.client.mkdir()
|
||||
self.shim = self.root / 'shim'
|
||||
|
||||
def runtime(self, path):
|
||||
runtime = self.client / path
|
||||
(runtime / 'bin').mkdir(parents=True)
|
||||
(runtime / 'bin/steam-runtime-check-requirements').write_text('#!/bin/sh\nexit 1\n')
|
||||
(runtime / 'bin/steam-runtime-system-info').write_text('#!/bin/sh\necho info\n')
|
||||
(runtime / 'files').mkdir()
|
||||
(runtime / 'files/marker').write_text('runtime files')
|
||||
return runtime
|
||||
|
||||
def build(self):
|
||||
return subprocess.run(['bash', str(SHIM), str(self.client), str(self.shim)],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
|
||||
def sh(self, *args):
|
||||
return subprocess.run(['sh', *map(str, args)], capture_output=True, text=True, timeout=30)
|
||||
|
||||
def assert_shim(self):
|
||||
result = self.build()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(0, self.sh(self.shim / 'bin/steam-runtime-check-requirements').returncode)
|
||||
self.assertEqual('info\n', self.sh(self.shim / 'bin/steam-runtime-system-info').stdout)
|
||||
self.assertEqual('runtime files', (self.shim / 'files/marker').read_text())
|
||||
launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env=BL_SHIM_TEST=yes',
|
||||
f'--directory={self.root}', '--', 'sh', '-c', 'echo "$BL_SHIM_TEST $(basename "$PWD")"')
|
||||
self.assertEqual(f'yes {self.root.name}\n', launched.stdout)
|
||||
launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env', 'BL_SHIM_TEST=split',
|
||||
'--directory', self.root, '--', 'sh', '-c', 'echo "$BL_SHIM_TEST $(basename "$PWD")"')
|
||||
self.assertEqual(f'split {self.root.name}\n', launched.stdout)
|
||||
missing = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--directory', self.root / 'missing',
|
||||
'--', 'true')
|
||||
self.assertEqual(127, missing.returncode)
|
||||
|
||||
def test_a_client_without_a_container_gets_no_shim(self):
|
||||
self.shim.mkdir()
|
||||
self.assertEqual(1, self.build().returncode)
|
||||
self.assertFalse(self.shim.exists())
|
||||
|
||||
def test_the_pressure_vessel_runtime_is_shimmed(self):
|
||||
self.runtime('pv-runtime/steam-runtime-steamrt')
|
||||
self.assert_shim()
|
||||
|
||||
def test_a_requirements_probe_elsewhere_is_shimmed(self):
|
||||
self.runtime('steam-runtime')
|
||||
self.assert_shim()
|
||||
|
||||
def test_the_arm64_session_starts_a_containerized_client_through_the_shim(self):
|
||||
block = re.search(r'\n( +steam_client=\("\$steam_root/steamrtarm64/steam"\)\n.*?\n fi\n)', SESSION, re.S).group(1)
|
||||
stub = self.root / 'droiddeck-steamrt-shim'
|
||||
for status, shimmed in ((1, False), (0, True)):
|
||||
stub.write_text(f'#!/bin/bash\nexit {status}\n')
|
||||
stub.chmod(0o755)
|
||||
script = 'if :; then\n' + block + 'printf "%s\\n" "${steam_client[@]}"\n'
|
||||
env = dict(os.environ, HOME=str(self.root), steam_root='/steam',
|
||||
PATH=str(self.root) + os.pathsep + os.environ['PATH'])
|
||||
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
lines = result.stdout.splitlines()
|
||||
self.assertEqual('/steam/steamrtarm64/steam', lines[-1])
|
||||
self.assertEqual(shimmed, 'Valve containerized the arm64 Steam client' in result.stdout)
|
||||
self.assertEqual(shimmed, any(line.startswith('STEAM_RUNTIME_STEAMRT=') and
|
||||
line.endswith('/.droiddeck-steamrt-shim') for line in lines))
|
||||
|
||||
def test_both_clients_are_told_they_already_run_inside_the_container(self):
|
||||
guard = SESSION.index('export STEAM_STEAMRT_RECURSION_GUARD=1')
|
||||
self.assertLess(guard, SESSION.index('"${steam_client[@]}" "${_bl_ui[@]}"'))
|
||||
self.assertIn('-u STEAM_STEAMRT_RECURSION_GUARD', SESSION[:guard])
|
||||
self.assertIn('export STEAM_STEAMRT_RECURSION_GUARD=1', X64)
|
||||
self.assertIn('droiddeck-steamrt-shim "$STEAM_X64/steamrt64" "$X64_HOME/steamrt-shim" || rm -rf "$X64_HOME/steamrt-shim"', X64)
|
||||
|
||||
|
||||
class SessionChannelTest(unittest.TestCase):
|
||||
BLOCK = re.search(r'\n( +steam_channel=steamdeck_publicbeta\n.*?\n +fi\n)', SESSION, re.S).group(1)
|
||||
|
||||
def channel(self, x64, installer):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
stub = Path(temp) / 'droiddeck-steam-install'
|
||||
stub.write_text('#!/bin/bash\n' + installer + '\n')
|
||||
stub.chmod(0o755)
|
||||
env = dict(os.environ, steam_x64=x64, PATH=temp + os.pathsep + os.environ['PATH'])
|
||||
result = subprocess.run(['bash', '-c', self.BLOCK + 'echo "$steam_channel"\n'], env=env,
|
||||
capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_the_arm64_client_follows_the_installed_channel(self):
|
||||
self.assertEqual('steamdeck_stable', self.channel('0', '[ "$1" = --channel ] && echo steamdeck_stable'))
|
||||
|
||||
def test_an_installer_without_an_answer_keeps_the_deck_beta(self):
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel('0', 'exit 1'))
|
||||
|
||||
def test_the_x86_client_keeps_its_own_channel(self):
|
||||
self.assertEqual('steamdeck_publicbeta', self.channel('1', 'echo steamdeck_stable'))
|
||||
|
||||
def test_the_client_branch_on_disk_and_clientbeta_use_the_same_channel(self):
|
||||
self.assertIn('-clientbeta "$steam_channel"', SESSION)
|
||||
self.assertIn('echo "$steam_channel" > "$steam_beta"', SESSION)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,154 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
__attribute__((noinline)) int ntdll_open(const char *path) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return fd;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) int ntdll_openat(const char *path) {
|
||||
int fd = openat(AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return fd;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) FILE *ntdll_fopen(const char *path) {
|
||||
FILE *f = fopen(path, "r");
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return f;
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ptrace.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int ntdll_open(const char *path);
|
||||
int ntdll_openat(const char *path);
|
||||
FILE *ntdll_fopen(const char *path);
|
||||
|
||||
static void report(const char *name, int fd) {
|
||||
char link[64], target[256] = "", text[16384], *field;
|
||||
ssize_t n;
|
||||
long tracer = -1;
|
||||
if (fd < 0) {
|
||||
printf("%s failed\n", name);
|
||||
return;
|
||||
}
|
||||
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
|
||||
n = readlink(link, target, sizeof(target) - 1);
|
||||
target[n > 0 ? n : 0] = '\0';
|
||||
n = pread(fd, text, sizeof(text) - 1, 0);
|
||||
text[n > 0 ? n : 0] = '\0';
|
||||
if ((field = strstr(text, "\nTracerPid:\t")) != NULL) tracer = strtol(field + 12, NULL, 10);
|
||||
const char *kind = strncmp(target, "/proc/", 6) == 0 ? "proc"
|
||||
: strncmp(target, "/memfd:", 7) == 0 ? "memfd"
|
||||
: strncmp(target, "/tmp/.droiddeck-status-", 23) == 0 ? "copy" : target;
|
||||
printf("%s kind=%s tracer=%s rdonly=%d vm=%d\n", name, kind, tracer == 0 ? "hidden" : tracer > 0 ? "shown" : "missing",
|
||||
(fcntl(fd, F_GETFL) & O_ACCMODE) == O_RDONLY, strstr(text, "\nVmRSS:") != NULL);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
static void report_stream(const char *name, FILE *f) {
|
||||
if (f == NULL) {
|
||||
printf("%s failed\n", name);
|
||||
return;
|
||||
}
|
||||
report(name, dup(fileno(f)));
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int ready[2];
|
||||
if (pipe(ready) != 0) return 1;
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
char ok = ptrace(PTRACE_TRACEME, 0, NULL, NULL) == 0;
|
||||
if (write(ready[1], &ok, 1) != 1) _exit(1);
|
||||
for (;;) pause();
|
||||
}
|
||||
char ok = 0;
|
||||
if (read(ready[0], &ok, 1) != 1 || !ok) {
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
puts("no ptrace");
|
||||
return 0;
|
||||
}
|
||||
char other[64], self[64];
|
||||
snprintf(other, sizeof(other), "/proc/%d/status", (int)child);
|
||||
snprintf(self, sizeof(self), "/proc/%d/status", (int)getpid());
|
||||
report("main_other_open", open(other, O_RDONLY | O_CLOEXEC));
|
||||
report_stream("main_other_fopen", fopen(other, "r"));
|
||||
report("main_self_open", open("/proc/self/status", O_RDONLY | O_CLOEXEC));
|
||||
report("ntdll_other_open", ntdll_open(other));
|
||||
report("ntdll_other_openat", ntdll_openat(other));
|
||||
report_stream("ntdll_other_fopen", ntdll_fopen(other));
|
||||
report_stream("ntdll_self_fopen", ntdll_fopen(self));
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class TracerPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not shutil.which("cc"):
|
||||
raise unittest.SkipTest("no compiler")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), *sources, "-ldl"],
|
||||
check=True)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run(["cc", "-O1", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"), "-Wl,-rpath," + str(tmp)],
|
||||
check=True)
|
||||
env = dict(os.environ, LD_PRELOAD=str(tmp / "libblsession.so"))
|
||||
out = subprocess.run([str(tmp / "prog")], env=env, capture_output=True, text=True, timeout=60)
|
||||
if out.returncode != 0:
|
||||
raise AssertionError(out.stdout + out.stderr)
|
||||
if "no ptrace" in out.stdout:
|
||||
raise unittest.SkipTest("ptrace not allowed")
|
||||
cls.lines = dict(line.split(" ", 1) for line in out.stdout.splitlines())
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def test_other_programs_still_see_no_tracer(self):
|
||||
self.assertEqual(self.lines["main_other_open"], "kind=copy tracer=hidden rdonly=1 vm=1")
|
||||
self.assertEqual(self.lines["main_other_fopen"], "kind=copy tracer=hidden rdonly=1 vm=1")
|
||||
self.assertEqual(self.lines["main_self_open"], "kind=memfd tracer=hidden rdonly=0 vm=1")
|
||||
|
||||
def test_wine_reads_the_real_status_file(self):
|
||||
for name in ("ntdll_other_open", "ntdll_other_openat", "ntdll_other_fopen"):
|
||||
self.assertEqual(self.lines[name], "kind=proc tracer=shown rdonly=1 vm=1", name)
|
||||
self.assertEqual(self.lines["ntdll_self_fopen"], "kind=proc tracer=hidden rdonly=1 vm=1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,301 @@
|
||||
import ctypes
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#include <signal.h>
|
||||
__attribute__((noinline)) void syscall_dispatcher_return_slowpath(void) { raise(SIGUSR2); }
|
||||
void slowpath(void) {
|
||||
syscall_dispatcher_return_slowpath();
|
||||
__asm__ volatile("" ::: "memory");
|
||||
}
|
||||
void slowpath_other(int sig) {
|
||||
raise(sig);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <asm/sigcontext.h>
|
||||
#include <pthread.h>
|
||||
#include <setjmp.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
void slowpath(void);
|
||||
void slowpath_other(int sig);
|
||||
|
||||
static char altstack[65536];
|
||||
static char landing_stack[65536] __attribute__((aligned(16)));
|
||||
static volatile int mode;
|
||||
static int calls;
|
||||
static volatile int on_alt, usr2_blocked, usr1_blocked, code_ok, stack_ok;
|
||||
static volatile long handler_sp;
|
||||
static jmp_buf back;
|
||||
static uint64_t saved[31];
|
||||
static unsigned __int128 saved_v[32];
|
||||
static uint32_t saved_fpsr;
|
||||
|
||||
void landing(void);
|
||||
__asm__(".text\n.globl landing\n.type landing, %function\nlanding:\n"
|
||||
" sub sp, sp, #784\n"
|
||||
" stp x0, x1, [sp, #0]\n stp x2, x3, [sp, #16]\n stp x4, x5, [sp, #32]\n stp x6, x7, [sp, #48]\n"
|
||||
" stp x8, x9, [sp, #64]\n stp x10, x11, [sp, #80]\n stp x12, x13, [sp, #96]\n stp x14, x15, [sp, #112]\n"
|
||||
" stp x16, x17, [sp, #128]\n stp x18, x19, [sp, #144]\n stp x20, x21, [sp, #160]\n stp x22, x23, [sp, #176]\n"
|
||||
" stp x24, x25, [sp, #192]\n stp x26, x27, [sp, #208]\n stp x28, x29, [sp, #224]\n str x30, [sp, #240]\n"
|
||||
" add x9, sp, #256\n"
|
||||
" stp q0, q1, [x9, #0]\n stp q2, q3, [x9, #32]\n stp q4, q5, [x9, #64]\n stp q6, q7, [x9, #96]\n"
|
||||
" stp q8, q9, [x9, #128]\n stp q10, q11, [x9, #160]\n stp q12, q13, [x9, #192]\n stp q14, q15, [x9, #224]\n"
|
||||
" stp q16, q17, [x9, #256]\n stp q18, q19, [x9, #288]\n stp q20, q21, [x9, #320]\n stp q22, q23, [x9, #352]\n"
|
||||
" stp q24, q25, [x9, #384]\n stp q26, q27, [x9, #416]\n stp q28, q29, [x9, #448]\n stp q30, q31, [x9, #480]\n"
|
||||
" mrs x10, fpsr\n str w10, [sp, #768]\n"
|
||||
" mov x0, sp\n bl landed\n brk #0\n");
|
||||
|
||||
void landed(uint64_t *regs) {
|
||||
memcpy(saved, regs, sizeof(saved));
|
||||
memcpy(saved_v, regs + 32, sizeof(saved_v));
|
||||
saved_fpsr = *(uint32_t *)(regs + 96);
|
||||
longjmp(back, 1);
|
||||
}
|
||||
|
||||
static struct fpsimd_context *fpsimd_of(ucontext_t *uc) {
|
||||
struct _aarch64_ctx *c = (struct _aarch64_ctx *)uc->uc_mcontext.__reserved;
|
||||
while (c->magic) {
|
||||
if (c->magic == FPSIMD_MAGIC) return (struct fpsimd_context *)c;
|
||||
c = (struct _aarch64_ctx *)((char *)c + c->size);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void handler(int sig, siginfo_t *info, void *ctx) {
|
||||
ucontext_t *uc = ctx;
|
||||
sigset_t now;
|
||||
long sp = (long)&now;
|
||||
__atomic_add_fetch(&calls, 1, __ATOMIC_RELAXED);
|
||||
handler_sp = sp;
|
||||
on_alt = sp >= (long)altstack && sp < (long)altstack + (long)sizeof(altstack);
|
||||
pthread_sigmask(SIG_BLOCK, NULL, &now);
|
||||
usr2_blocked = sigismember(&now, SIGUSR2);
|
||||
usr1_blocked = sigismember(&now, SIGUSR1);
|
||||
code_ok = sig == SIGUSR2 && info->si_signo == SIGUSR2 && info->si_code == SI_TKILL && info->si_pid == getpid();
|
||||
stack_ok = uc->uc_stack.ss_sp == altstack && uc->uc_stack.ss_size == sizeof(altstack) && !(uc->uc_stack.ss_flags & SS_DISABLE);
|
||||
if (mode == 1) {
|
||||
struct fpsimd_context *fp = fpsimd_of(uc);
|
||||
for (int i = 0; i <= 28; i++) uc->uc_mcontext.regs[i] = 0x1000 + i;
|
||||
uc->uc_mcontext.regs[29] = 0x2900;
|
||||
uc->uc_mcontext.regs[30] = 0x3000;
|
||||
uc->uc_mcontext.sp = (uint64_t)(landing_stack + sizeof(landing_stack));
|
||||
uc->uc_mcontext.pc = (uint64_t)landing;
|
||||
uc->uc_mcontext.pstate = 0x60000000;
|
||||
for (int i = 0; i < 32; i++) fp->vregs[i] = ((unsigned __int128)(0x7700 + i) << 64) | (0x5500 + i);
|
||||
fp->fpsr = 0x8;
|
||||
}
|
||||
}
|
||||
|
||||
static void usr1(int sig, siginfo_t *info, void *ctx) {
|
||||
(void)sig;
|
||||
(void)info;
|
||||
(void)ctx;
|
||||
}
|
||||
|
||||
uint64_t kept_x[10];
|
||||
double kept_d[8];
|
||||
|
||||
static int keep_callee_saved(void) {
|
||||
uint64_t *out = kept_x;
|
||||
double *d = kept_d;
|
||||
__asm__ volatile(
|
||||
"mov x19, #19\n mov x20, #20\n mov x21, #21\n mov x22, #22\n mov x23, #23\n"
|
||||
"mov x24, #24\n mov x25, #25\n mov x26, #26\n mov x27, #27\n mov x28, #28\n"
|
||||
"fmov d8, #1.0\n fmov d9, #2.0\n fmov d10, #3.0\n fmov d11, #4.0\n"
|
||||
"fmov d12, #5.0\n fmov d13, #6.0\n fmov d14, #7.0\n fmov d15, #8.0\n"
|
||||
"bl slowpath\n"
|
||||
"adrp x0, kept_x\n add x0, x0, :lo12:kept_x\n"
|
||||
"stp x19, x20, [x0, #0]\n stp x21, x22, [x0, #16]\n stp x23, x24, [x0, #32]\n"
|
||||
"stp x25, x26, [x0, #48]\n stp x27, x28, [x0, #64]\n"
|
||||
"adrp x0, kept_d\n add x0, x0, :lo12:kept_d\n"
|
||||
"stp d8, d9, [x0, #0]\n stp d10, d11, [x0, #16]\n stp d12, d13, [x0, #32]\n stp d14, d15, [x0, #48]\n"
|
||||
:
|
||||
:
|
||||
: "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
|
||||
"x16", "x17", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x30",
|
||||
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
|
||||
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30",
|
||||
"v31", "memory", "cc");
|
||||
for (int i = 0; i < 10; i++)
|
||||
if (out[i] != (uint64_t)(19 + i)) return 0;
|
||||
for (int i = 0; i < 8; i++)
|
||||
if (d[i] != (double)(i + 1)) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void *stress(void *arg) {
|
||||
(void)arg;
|
||||
for (int i = 0; i < 2000; i++) slowpath();
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
stack_t ss = {.ss_sp = altstack, .ss_size = sizeof(altstack), .ss_flags = 0};
|
||||
struct sigaction sa;
|
||||
sigset_t mask, now;
|
||||
sigaltstack(&ss, NULL);
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaddset(&sa.sa_mask, SIGUSR1);
|
||||
sigaction(SIGUSR2, &sa, NULL);
|
||||
sa.sa_sigaction = usr1;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGUSR1, &sa, NULL);
|
||||
|
||||
if (argc > 1 && strcmp(argv[1], "bench") == 0) {
|
||||
int n = argc > 2 ? atoi(argv[2]) : 20000;
|
||||
struct timespec a, b;
|
||||
clock_gettime(CLOCK_MONOTONIC, &a);
|
||||
for (int i = 0; i < n; i++) slowpath();
|
||||
clock_gettime(CLOCK_MONOTONIC, &b);
|
||||
printf("%.2f us per raise, alt %d\n", ((b.tv_sec - a.tv_sec) * 1e9 + (b.tv_nsec - a.tv_nsec)) / 1e3 / n, on_alt);
|
||||
return 0;
|
||||
}
|
||||
|
||||
mode = 0;
|
||||
calls = 0;
|
||||
int kept = keep_callee_saved();
|
||||
pthread_sigmask(SIG_BLOCK, NULL, &now);
|
||||
printf("returned calls=%d kept=%d usr2_blocked=%d usr1_blocked=%d code=%d stack=%d after_usr2=%d after_usr1=%d\n",
|
||||
calls, kept, usr2_blocked, usr1_blocked, code_ok, stack_ok, sigismember(&now, SIGUSR2),
|
||||
sigismember(&now, SIGUSR1));
|
||||
printf("path %s\n", on_alt ? "kernel" : "inline");
|
||||
|
||||
mode = 1;
|
||||
calls = 0;
|
||||
if (!setjmp(back)) {
|
||||
slowpath();
|
||||
printf("redirect did not happen\n");
|
||||
} else {
|
||||
int ok = 1;
|
||||
for (int i = 0; i <= 28; i++)
|
||||
if (saved[i] != (uint64_t)(0x1000 + i)) ok = 0;
|
||||
if (saved[29] != 0x2900 || saved[30] != 0x3000) ok = 0;
|
||||
for (int i = 0; i < 32; i++)
|
||||
if (saved_v[i] != (((unsigned __int128)(0x7700 + i) << 64) | (0x5500 + i))) ok = 0;
|
||||
printf("redirect calls=%d regs=%d fpsr=%u\n", calls, ok, saved_fpsr & 0x8);
|
||||
}
|
||||
mode = 0;
|
||||
|
||||
sigemptyset(&mask);
|
||||
sigaddset(&mask, SIGUSR2);
|
||||
pthread_sigmask(SIG_BLOCK, &mask, NULL);
|
||||
calls = 0;
|
||||
slowpath();
|
||||
int while_blocked = calls;
|
||||
pthread_sigmask(SIG_UNBLOCK, &mask, NULL);
|
||||
printf("blocked during=%d after=%d\n", while_blocked, calls);
|
||||
|
||||
calls = 0;
|
||||
slowpath_other(SIGUSR1);
|
||||
raise(SIGUSR2);
|
||||
printf("other calls=%d main_path=%s\n", calls, on_alt ? "kernel" : "inline");
|
||||
|
||||
calls = 0;
|
||||
pthread_t t[4];
|
||||
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, stress, NULL);
|
||||
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
|
||||
printf("threads calls=%d\n", calls);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def has_gcs_hwcap():
|
||||
try:
|
||||
getauxval = ctypes.CDLL(None).getauxval
|
||||
except (AttributeError, OSError):
|
||||
return False
|
||||
getauxval.restype = ctypes.c_ulong
|
||||
getauxval.argtypes = [ctypes.c_ulong]
|
||||
return bool(getauxval(16) & (1 << 32))
|
||||
|
||||
|
||||
def runner():
|
||||
if platform.machine() in ("aarch64", "arm64") and shutil.which("gcc") and not has_gcs_hwcap():
|
||||
return "gcc", []
|
||||
if shutil.which("aarch64-linux-gnu-gcc") and shutil.which("qemu-aarch64") and Path("/usr/aarch64-linux-gnu").is_dir():
|
||||
return "aarch64-linux-gnu-gcc", ["qemu-aarch64", "-cpu", "neoverse-n1", "-L", "/usr/aarch64-linux-gnu"]
|
||||
return None, None
|
||||
|
||||
|
||||
class Usr2PreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"),
|
||||
*sources, "-ldl"], check=True)
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run([cls.cc, "-O1", "-U_FORTIFY_SOURCE", "-pthread", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"),
|
||||
"-Wl,-rpath," + str(tmp)], check=True)
|
||||
cls.program = tmp / "prog"
|
||||
cls.preload = tmp / "libblsession.so"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self, preload):
|
||||
env = dict(os.environ)
|
||||
env.pop("LD_PRELOAD", None)
|
||||
cmd = list(self.prefix) + [str(self.program)]
|
||||
if preload:
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + ["-E", "LD_PRELOAD=" + str(self.preload), str(self.program)]
|
||||
else:
|
||||
env["LD_PRELOAD"] = str(self.preload)
|
||||
out = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return out.stdout.splitlines()
|
||||
|
||||
def test_a_ntdll_raise_runs_the_handler_without_a_kernel_signal(self):
|
||||
lines = self.run_program(True)
|
||||
self.assertIn("path inline", lines)
|
||||
self.assertIn("returned calls=1 kept=1 usr2_blocked=1 usr1_blocked=1 code=1 stack=1 after_usr2=0 after_usr1=0", lines)
|
||||
|
||||
def test_b_context_the_handler_writes_is_the_one_that_resumes(self):
|
||||
self.assertIn("redirect calls=1 regs=1 fpsr=8", self.run_program(True))
|
||||
|
||||
def test_c_behaves_like_the_kernel_signal(self):
|
||||
stock = [line for line in self.run_program(False) if not line.startswith("path ")]
|
||||
inline = [line for line in self.run_program(True) if not line.startswith("path ")]
|
||||
self.assertIn("returned calls=1 kept=1 usr2_blocked=1 usr1_blocked=1 code=1 stack=1 after_usr2=0 after_usr1=0", stock)
|
||||
self.assertEqual(stock, inline)
|
||||
|
||||
def test_d_blocked_other_signals_and_other_callers_use_the_kernel(self):
|
||||
lines = self.run_program(True)
|
||||
self.assertIn("blocked during=0 after=1", lines)
|
||||
self.assertIn("other calls=1 main_path=kernel", lines)
|
||||
self.assertIn("threads calls=8000", lines)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -31,14 +31,14 @@ class XboxBuildSourceTest(unittest.TestCase):
|
||||
git('switch', '-q', 'main')
|
||||
(root / 'backend').write_text('merged backend')
|
||||
git('commit', '-qam', 'backend changed after branch')
|
||||
for name in ('xbox', 'apk'):
|
||||
for name in ('source', 'xbox', 'components', 'apk', 'tests', 'dispatch'):
|
||||
git('clone', '-q', str(root), str(root / name))
|
||||
git('checkout', '-q', head, cwd=root / name)
|
||||
output = root / 'output'
|
||||
env['GITHUB_OUTPUT'] = str(output)
|
||||
subprocess.run(['bash', '-c', step('xbox', 'Pin and merge the APK source')], cwd=root / 'xbox', env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step('source', 'Pin and merge the APK source')], cwd=root / 'source', env=env, check=True, capture_output=True)
|
||||
base = output.read_text().strip().split('=', 1)[1]
|
||||
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'xbox')
|
||||
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'source')
|
||||
(root / 'backend').write_text('newer main, after backend build')
|
||||
git('commit', '-qam', 'main advanced again')
|
||||
env.update(BUILD_BASE_SHA=base, XBOX_SOURCE_TREE=tree)
|
||||
@@ -46,3 +46,19 @@ class XboxBuildSourceTest(unittest.TestCase):
|
||||
subprocess.run(['bash', '-c', step('build', 'Verify backend and APK source match')], cwd=root / 'apk', env=env, check=True, capture_output=True)
|
||||
self.assertEqual((root / 'apk/backend').read_text(), 'merged backend')
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'apk'), tree)
|
||||
|
||||
subprocess.run(['bash', '-c', step('python-tests', 'Merge the pinned APK base')], cwd=root / 'tests', env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step('python-tests', 'Verify backend and test source match')], cwd=root / 'tests', env=env, check=True, capture_output=True)
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'tests'), tree)
|
||||
|
||||
env['SOURCE_TREE'] = tree
|
||||
for job in ('xbox', 'components'):
|
||||
subprocess.run(['bash', '-c', step(job, 'Merge the pinned APK base')], cwd=root / job, env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step(job, 'Verify pinned source tree')], cwd=root / job, env=env, check=True, capture_output=True)
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / job), tree)
|
||||
|
||||
trusted = root / 'trusted-output'
|
||||
env['GITHUB_OUTPUT'] = str(trusted)
|
||||
subprocess.run(['bash', '-c', step('source', 'Resolve trusted manifest base')], cwd=root / 'dispatch', env=env, check=True, capture_output=True)
|
||||
self.assertEqual(trusted.read_text().strip(), 'base-sha=' + git('rev-parse', 'main'))
|
||||
self.assertNotEqual(git('rev-parse', 'HEAD', cwd=root / 'dispatch'), git('rev-parse', 'main'))
|
||||
Reference in new issue
Block a user