mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-25 07:46:01 +00:00
Merge main (c298da6f) into feat/bionic-runtime
One conflict: .github/workflows/build.yml. This branch had a step that fetched Robolectric's Android jars from a DroidDeck-CI release because Maven Central answered the runners with HTTP 429; main now caches those jars (#3127, #3134), so build.yml is main's again and this pull request no longer changes it. ProtonMenu, ProtonExtras, SessionService, SessionOverlay and droiddeck-game-env merged cleanly; test_game_environment.py and test_proton_extra.py pass (207 tests).
This commit is contained in:
commit
cc5de0ba63
308 files changed
+14468
-3934
No files matched your search
@@ -21,6 +21,8 @@ static VkPipelineColorBlendAttachmentState driver_attachments[4];
|
||||
static uint32_t driver_attachment_count;
|
||||
static VkColorBlendEquationEXT driver_equations[4];
|
||||
static uint32_t driver_equation_count;
|
||||
static VkCompareOp driver_depth_op, driver_pipeline_depth_op;
|
||||
static VkBool32 driver_depth_test;
|
||||
|
||||
#define MAIN 1
|
||||
#define VOID 2
|
||||
@@ -182,6 +184,25 @@ static void test_spirv(const char *directory)
|
||||
assert(!spirv_strip_dual_source(truncated, 5, &out));
|
||||
}
|
||||
|
||||
static void test_handle_map_null_key(void)
|
||||
{
|
||||
struct handle_map map = {0};
|
||||
int first, second;
|
||||
map_put(&map, 0x1000, &first);
|
||||
map_put(&map, 0x2000, &second);
|
||||
for (int i = 0; i < 1000; i++)
|
||||
assert(!map_remove(&map, 0));
|
||||
map_put(&map, 0, &first);
|
||||
assert(map.count == 2 && !map_get(&map, 0));
|
||||
for (uint64_t key = 1; key <= 30; key++) {
|
||||
map_put(&map, 0x100000 + key, &first);
|
||||
assert(map_remove(&map, 0x100000 + key) == &first);
|
||||
}
|
||||
assert(map.count == 2 && map.capacity == 64);
|
||||
assert(map_get(&map, 0x1000) == &first && map_get(&map, 0x2000) == &second);
|
||||
map_free(&map);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
|
||||
VkInstance *instance)
|
||||
{
|
||||
@@ -286,10 +307,27 @@ static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPip
|
||||
const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext;
|
||||
assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
|
||||
capture_code(module->pCode, module->codeSize);
|
||||
if (infos[0].pDepthStencilState)
|
||||
driver_pipeline_depth_op = infos[0].pDepthStencilState->depthCompareOp;
|
||||
pipelines[0] = (VkPipeline)0x2000;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_begin_command_buffer(VkCommandBuffer cmd, const VkCommandBufferBeginInfo *info)
|
||||
{
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_set_depth_test(VkCommandBuffer cmd, VkBool32 enable)
|
||||
{
|
||||
driver_depth_test = enable;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_set_depth_op(VkCommandBuffer cmd, VkCompareOp op)
|
||||
{
|
||||
driver_depth_op = op;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count,
|
||||
const VkColorBlendEquationEXT *equations)
|
||||
{
|
||||
@@ -323,6 +361,9 @@ static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const
|
||||
MOCK("vkDestroyShaderModule", mock_destroy_shader_module);
|
||||
MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines);
|
||||
MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation);
|
||||
MOCK("vkBeginCommandBuffer", mock_begin_command_buffer);
|
||||
MOCK("vkCmdSetDepthTestEnable", mock_set_depth_test);
|
||||
MOCK("vkCmdSetDepthCompareOp", mock_set_depth_op);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -461,9 +502,75 @@ static void test_capable_device(void)
|
||||
destroy_device(device);
|
||||
}
|
||||
|
||||
static void create_depth_pipeline(VkDevice device, const VkPipelineDepthStencilStateCreateInfo *depth,
|
||||
const VkDynamicState *dynamic, uint32_t dynamic_count)
|
||||
{
|
||||
struct spirv plain;
|
||||
fragment_shader(&plain, 0x00010000, false);
|
||||
VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0,
|
||||
plain.n * sizeof(uint32_t), plain.w};
|
||||
VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, &module, 0,
|
||||
VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL};
|
||||
VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
|
||||
VK_FALSE, VK_LOGIC_OP_COPY, 1, &plain_attachment, {0}};
|
||||
VkPipelineDynamicStateCreateInfo states = {VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, NULL, 0,
|
||||
dynamic_count, dynamic};
|
||||
VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1,
|
||||
.pStages = &stage, .pDepthStencilState = depth, .pColorBlendState = &blend,
|
||||
.pDynamicState = dynamic_count ? &states : NULL};
|
||||
VkPipeline pipeline;
|
||||
driver_pipeline_depth_op = VK_COMPARE_OP_MAX_ENUM;
|
||||
PFN_vkCreateGraphicsPipelines create =
|
||||
(PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines");
|
||||
assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS);
|
||||
}
|
||||
|
||||
static void test_depth_compare_op(void)
|
||||
{
|
||||
VkDevice device;
|
||||
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
|
||||
assert(create_device((VkPhysicalDevice)&mock_lacking, NULL, &enabled, &device) == VK_SUCCESS);
|
||||
PFN_vkBeginCommandBuffer begin = (PFN_vkBeginCommandBuffer)layer_gdpa(device, "vkBeginCommandBuffer");
|
||||
PFN_vkCmdSetDepthTestEnable set_test =
|
||||
(PFN_vkCmdSetDepthTestEnable)layer_gdpa(device, "vkCmdSetDepthTestEnable");
|
||||
PFN_vkCmdSetDepthCompareOp set_op = (PFN_vkCmdSetDepthCompareOp)layer_gdpa(device, "vkCmdSetDepthCompareOp");
|
||||
assert((PFN_vkVoidFunction)set_test != (PFN_vkVoidFunction)mock_set_depth_test);
|
||||
assert((PFN_vkVoidFunction)set_op != (PFN_vkVoidFunction)mock_set_depth_op);
|
||||
|
||||
VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer;
|
||||
VkCommandBufferBeginInfo begin_info = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
|
||||
assert(begin(cmd, &begin_info) == VK_SUCCESS);
|
||||
set_op(cmd, VK_COMPARE_OP_LESS);
|
||||
assert(driver_depth_op == VK_COMPARE_OP_LESS);
|
||||
set_test(cmd, VK_FALSE);
|
||||
assert(!driver_depth_test && driver_depth_op == VK_COMPARE_OP_ALWAYS);
|
||||
set_op(cmd, VK_COMPARE_OP_NEVER);
|
||||
assert(driver_depth_op == VK_COMPARE_OP_ALWAYS);
|
||||
set_test(cmd, VK_TRUE);
|
||||
assert(driver_depth_test && driver_depth_op == VK_COMPARE_OP_NEVER);
|
||||
set_test(cmd, VK_FALSE);
|
||||
assert(begin(cmd, &begin_info) == VK_SUCCESS);
|
||||
set_op(cmd, VK_COMPARE_OP_GREATER);
|
||||
assert(driver_depth_op == VK_COMPARE_OP_GREATER);
|
||||
|
||||
VkPipelineDepthStencilStateCreateInfo depth = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
|
||||
.depthCompareOp = VK_COMPARE_OP_NEVER};
|
||||
create_depth_pipeline(device, &depth, NULL, 0);
|
||||
assert(driver_pipeline_depth_op == VK_COMPARE_OP_ALWAYS && depth.depthCompareOp == VK_COMPARE_OP_NEVER);
|
||||
const VkDynamicState dynamic[] = {VK_DYNAMIC_STATE_DEPTH_COMPARE_OP};
|
||||
create_depth_pipeline(device, &depth, dynamic, 1);
|
||||
assert(driver_pipeline_depth_op == VK_COMPARE_OP_NEVER);
|
||||
depth.depthTestEnable = VK_TRUE;
|
||||
depth.depthCompareOp = VK_COMPARE_OP_LESS;
|
||||
create_depth_pipeline(device, &depth, NULL, 0);
|
||||
assert(driver_pipeline_depth_op == VK_COMPARE_OP_LESS);
|
||||
destroy_device(device);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
test_spirv(argc > 1 ? argv[1] : NULL);
|
||||
test_handle_map_null_key();
|
||||
|
||||
setenv("WINEPREFIX", "/nonexistent", 1);
|
||||
unsetenv("DROIDDECK_MALI_COMPAT");
|
||||
@@ -482,6 +589,7 @@ int main(int argc, char **argv)
|
||||
|
||||
test_lacking_device();
|
||||
test_capable_device();
|
||||
test_depth_compare_op();
|
||||
|
||||
((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL);
|
||||
free(driver_code);
|
||||
|
||||
@@ -146,6 +146,24 @@ class AppImageRunTest(unittest.TestCase):
|
||||
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem"))
|
||||
self.assertEqual("sysmem", env["TU_DEBUG"])
|
||||
|
||||
def test_an_arm64_app_uses_the_sessions_gl_libraries(self):
|
||||
(self.dir / "arch").write_text("arm64")
|
||||
self.bundle("usr/lib/libGLESv2.so.2", "usr/lib/libEGL.so.1", "usr/lib/libglfw.so.3", "usr/lib/libGLESv2.so.2.1.0")
|
||||
_, log = self.launch(RUN_MODE)
|
||||
lib = self.dir / "app/usr/lib"
|
||||
self.assertEqual(["libGLESv2.so.2.1.0", "libglfw.so.3"], sorted(p.name for p in lib.iterdir()))
|
||||
self.assertEqual(["libEGL.so.1", "libGLESv2.so.2"], sorted(p.name for p in (self.dir / "bundled-gl/usr/lib").iterdir()))
|
||||
self.assertIn("the session's libGLESv2.so.2 replaces the bundled one", log)
|
||||
_, log = self.launch(RUN_MODE)
|
||||
self.assertNotIn("replaces the bundled one", log)
|
||||
|
||||
def test_other_architectures_keep_their_gl_libraries(self):
|
||||
(self.dir / "arch").write_text("x86_64")
|
||||
self.bundle("usr/lib/libGLESv2.so.2")
|
||||
self.launch(RUN_MODE)
|
||||
self.assertTrue((self.dir / "app/usr/lib/libGLESv2.so.2").exists())
|
||||
self.assertFalse((self.dir / "bundled-gl").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1413,7 +1413,8 @@ class AgentJobTest(Harness):
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(os.path.isdir(folder))
|
||||
cmd = self.started[0]
|
||||
self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"])
|
||||
self.assertEqual(cmd[:4], ["/usr/local/bin/droiddeck-headless", str(self.tmp / "cache" / "agent-runtime"), "--log",
|
||||
str(self.tmp / "cache" / "agent.log")])
|
||||
self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"])
|
||||
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
|
||||
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
|
||||
@@ -1641,16 +1642,6 @@ class AgentJobTest(Harness):
|
||||
path.write_bytes(json.dumps({"state": 1004}).encode("utf-8"))
|
||||
self.assertEqual(BNET["read_status"](str(path)), {"state": 1004})
|
||||
|
||||
def test_a_large_agent_log_is_rotated_before_a_job(self):
|
||||
self.install()
|
||||
os.makedirs(self.tmp / "cache")
|
||||
log = self.tmp / "cache" / "agent.log"
|
||||
log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1))
|
||||
self.files = {".game": json.dumps({"installed": False})}
|
||||
BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0)
|
||||
self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1)
|
||||
self.assertEqual(log.stat().st_size, 0)
|
||||
|
||||
def test_it_queues_behind_another_battle_net_job(self):
|
||||
self.install()
|
||||
self.files = {".game": json.dumps({"installed": False})}
|
||||
@@ -1681,13 +1672,11 @@ class AgentJobTest(Harness):
|
||||
self.assertEqual(self.lines[0], ("STATE", "waiting"))
|
||||
self.assertEqual(self.lines[1], ("STATE", "starting"))
|
||||
|
||||
def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self):
|
||||
def test_the_agent_keeps_the_display_gamescope_gives_it_and_launches_through_the_shared_headless_helper(self):
|
||||
self.install()
|
||||
os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1")
|
||||
self.files = {".game": json.dumps({"installed": False})}
|
||||
BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0)
|
||||
self.assertNotIn("DISPLAY", self.envs[0])
|
||||
self.assertNotIn("WAYLAND_DISPLAY", self.envs[0])
|
||||
self.assertEqual(self.started[0][0], BNET["HEADLESS"])
|
||||
self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0")
|
||||
os.environ["DISPLAY"] = ":0"
|
||||
self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0")
|
||||
|
||||
@@ -138,6 +138,27 @@ class BinfmtPreloadTest(unittest.TestCase):
|
||||
program = self.file("arm64", bytes(arm64))
|
||||
self.assertEqual(self.run_program("execve", program), (3, "errno %d" % errno.ENOEXEC, None))
|
||||
|
||||
def arm64_appimage(self, name, filesystem):
|
||||
image = bytearray(128)
|
||||
image[0:4], image[4], image[5], image[8:11], image[18] = b"\x7fELF", 2, 1, b"AI\x02", 183
|
||||
image[0x28:0x30] = (64).to_bytes(8, "little")
|
||||
image[0x3A:0x3C], image[0x3C:0x3E] = (32).to_bytes(2, "little"), (1).to_bytes(2, "little")
|
||||
image[96:102] = filesystem
|
||||
return self.file(name, bytes(image))
|
||||
|
||||
def test_an_arm64_appimage_goes_to_the_handler(self):
|
||||
program = self.arm64_appimage("App.AppImage", b"hsqs\0\0")
|
||||
for how in ("execve", "execvp"):
|
||||
self.log.unlink(missing_ok=True)
|
||||
target = program if how == "execve" else program.name
|
||||
self.assertEqual(self.run_program(how, target, "--x"), (7, "", ["--exec", str(program), "--x"]))
|
||||
self.log.unlink()
|
||||
self.assertEqual(self.run_program("spawn", program, "y"), (0, "exit 7", ["--exec", str(program), "y"]))
|
||||
|
||||
def test_an_appimage_runtime_without_a_filesystem_keeps_its_error(self):
|
||||
runtime = self.arm64_appimage("uruntime", bytes(6))
|
||||
self.assertEqual(self.run_program("execve", runtime), (3, "errno %d" % errno.ENOEXEC, None))
|
||||
|
||||
def test_a_script_runs_as_itself(self):
|
||||
script = self.file("script.sh", b"#!/bin/sh\nexit 5\n")
|
||||
self.assertEqual(self.run_program("execve", script), (5, "", None))
|
||||
@@ -188,6 +209,24 @@ class BinfmtPreloadTest(unittest.TestCase):
|
||||
code = self.chromium_script()
|
||||
self.assertEqual(self.run_program("execve", code, "--version"), (0, "--no-sandbox\n--version", None))
|
||||
|
||||
def test_a_chromium_app_named_on_path_receives_no_sandbox(self):
|
||||
(self.dir / "code").symlink_to(self.chromium_script())
|
||||
for how in ("execvp", "execvpe", "spawnp"):
|
||||
out = self.run_program(how, "code", "--version")
|
||||
self.assertEqual(out[1].splitlines()[:2], ["--no-sandbox", "--version"], how)
|
||||
|
||||
def test_a_path_match_that_cannot_run_does_not_decide_the_flags(self):
|
||||
stale = self.dir / "stale"
|
||||
stale.mkdir()
|
||||
(stale / "util").write_text("#!/bin/sh\n")
|
||||
(stale / "chrome-sandbox").touch()
|
||||
util = self.dir / "util"
|
||||
util.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n")
|
||||
util.chmod(0o755)
|
||||
for how in ("execvp", "execvpe", "spawnp"):
|
||||
out = self.run_program(how, "util", "--version", PATH=f"{stale}:{self.dir}:/usr/bin:/bin")
|
||||
self.assertEqual(out[1].splitlines()[:1], ["--version"], how)
|
||||
|
||||
def test_the_hand_off_switch_works_without_the_desktop(self):
|
||||
tool = self.x86()
|
||||
for how in ("execve", "execvp"):
|
||||
|
||||
@@ -107,6 +107,51 @@ int main(void) {
|
||||
}
|
||||
"""
|
||||
|
||||
EARLY_LIBRARY = r"""
|
||||
#include <pthread.h>
|
||||
#include <time.h>
|
||||
|
||||
pthread_mutex_t early_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
__attribute__((constructor)) static void early_start(void) {
|
||||
struct timespec ts;
|
||||
pthread_mutex_lock(&early_lock);
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
pthread_mutex_unlock(&early_lock);
|
||||
}
|
||||
"""
|
||||
|
||||
EARLY_PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern pthread_mutex_t early_lock;
|
||||
|
||||
int open(const char *path, int flags, ...) {
|
||||
va_list args;
|
||||
va_start(args, flags);
|
||||
mode_t mode = (mode_t)va_arg(args, int);
|
||||
va_end(args);
|
||||
pthread_mutex_lock(&early_lock);
|
||||
pthread_mutex_unlock(&early_lock);
|
||||
return (int)syscall(SYS_openat, AT_FDCWD, path, flags, mode);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct timespec mono, boot;
|
||||
clock_gettime(CLOCK_MONOTONIC, &mono);
|
||||
clock_gettime(CLOCK_BOOTTIME, &boot);
|
||||
printf("gap %lld\n", (long long)(((boot.tv_sec - mono.tv_sec) * 1000000000LL + boot.tv_nsec - mono.tv_nsec) / 1000000LL));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
SHIFT_MS = 10000
|
||||
|
||||
|
||||
@@ -128,6 +173,13 @@ class ClockPausePreloadTest(unittest.TestCase):
|
||||
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True)
|
||||
cls.other = build / "kwin_wayland"
|
||||
shutil.copy(cls.shell, cls.other)
|
||||
(build / "early.c").write_text(EARLY_LIBRARY)
|
||||
(build / "early_program.c").write_text(EARLY_PROGRAM)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-pthread", "-o", str(build / "libearly.so"),
|
||||
str(build / "early.c")], check=True)
|
||||
cls.early = build / "early_program"
|
||||
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.early), str(build / "early_program.c"),
|
||||
"-L", str(build), "-learly", "-Wl,-rpath," + str(build)], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
@@ -153,6 +205,11 @@ class ClockPausePreloadTest(unittest.TestCase):
|
||||
self.assertGreaterEqual(paused[name], 50, name)
|
||||
self.assertLess(paused[name], 1000, name)
|
||||
|
||||
def test_clock_read_inside_a_library_constructor_does_not_reenter_the_program(self):
|
||||
plain = self.run_program(self.early, 0)
|
||||
paused = self.run_program(self.early, SHIFT_MS)
|
||||
self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50)
|
||||
|
||||
def test_program_without_preload_keeps_the_real_clock(self):
|
||||
plain = self.run_program(self.other, 0, preload=False)
|
||||
paused = self.run_program(self.other, SHIFT_MS, preload=False)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
COMPONENTS = Path(__file__).resolve().parents[1] / 'components'
|
||||
sys.path.insert(0, str(COMPONENTS))
|
||||
spec = importlib.util.spec_from_file_location('component_reuse', COMPONENTS / 'reuse.py')
|
||||
reuse = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(reuse)
|
||||
prepare = reuse.prepare
|
||||
|
||||
|
||||
class ComponentReuseTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
(self.root / 'tools/ci').mkdir(parents=True)
|
||||
(self.root / 'tools/ci/toolchains.env').write_text('CI_ANDROID_NDK_VERSION=30.0.1\n')
|
||||
self.local = {'runtime': 'a', 'proot': 'b'}
|
||||
self.unregistered, self.submodules = [], []
|
||||
for patcher in [mock.patch.object(prepare, 'registry', lambda root: dict.fromkeys(self.local)),
|
||||
mock.patch.object(prepare, 'identity', lambda name, root: self.local[name]),
|
||||
mock.patch.object(reuse, 'unregistered_changes', lambda tree, root: self.unregistered),
|
||||
mock.patch.object(reuse, 'edited_submodules', lambda root: self.submodules)]:
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.archive = self.root / 'prepared-components.tar.gz'
|
||||
self.contents = {name + '/file': name.encode() for name in prepare.TREES}
|
||||
self.contents.update({name: b'library' for name in prepare.LIBRARIES})
|
||||
|
||||
def write_archive(self, recipes, contents=None):
|
||||
contents = contents or self.contents
|
||||
manifest = dict(version=1, source_tree='tree', run='42', recipes=recipes,
|
||||
files={name: hashlib.sha256(data).hexdigest() for name, data in self.contents.items()})
|
||||
with tarfile.open(self.archive, 'w:gz') as archive:
|
||||
for name, data in list(contents.items()) + [(prepare.MANIFEST, json.dumps(manifest).encode())]:
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = len(data)
|
||||
entry.mode = 0o644
|
||||
archive.addfile(entry, io.BytesIO(data))
|
||||
|
||||
def test_matching_components_replace_local_ones(self):
|
||||
stale = self.root / prepare.TREES[0] / 'left-over'
|
||||
stale.parent.mkdir(parents=True)
|
||||
stale.write_text('from an older local build')
|
||||
self.write_archive(dict(self.local))
|
||||
self.assertTrue(reuse.reuse(self.archive, self.root))
|
||||
self.assertEqual(b'library', (self.root / prepare.LIBRARIES[0]).read_bytes())
|
||||
self.assertFalse(stale.exists())
|
||||
|
||||
def test_a_changed_component_is_not_reused(self):
|
||||
self.write_archive(dict(self.local, proot='other'))
|
||||
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
|
||||
self.assertFalse(reuse.reuse(self.archive, self.root))
|
||||
self.assertIn('proot', stdout.getvalue())
|
||||
self.assertFalse((self.root / prepare.LIBRARIES[0]).exists())
|
||||
|
||||
def test_a_tampered_file_is_rejected_and_local_outputs_survive(self):
|
||||
local = self.root / prepare.LIBRARIES[0]
|
||||
local.parent.mkdir(parents=True)
|
||||
local.write_bytes(b'local build')
|
||||
self.write_archive(dict(self.local), dict(self.contents, **{prepare.LIBRARIES[0]: b'tampered'}))
|
||||
with self.assertRaisesRegex(ValueError, 'do not match'):
|
||||
reuse.reuse(self.archive, self.root)
|
||||
self.assertEqual(b'local build', local.read_bytes())
|
||||
|
||||
def test_changed_sources_ci_builds_outside_recipes_are_not_reused(self):
|
||||
self.unregistered = ['tools/linuxfs/xclipse-layer/xclipse_layer.c']
|
||||
self.write_archive(dict(self.local))
|
||||
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
|
||||
self.assertFalse(reuse.reuse(self.archive, self.root))
|
||||
self.assertIn('xclipse_layer.c', stdout.getvalue())
|
||||
|
||||
def test_an_edited_submodule_is_not_reused(self):
|
||||
self.submodules = ['external/MaliBridge']
|
||||
self.write_archive(dict(self.local))
|
||||
with mock.patch('sys.stdout', new_callable=io.StringIO):
|
||||
self.assertFalse(reuse.reuse(self.archive, self.root))
|
||||
|
||||
def test_identities_use_the_ci_runner_and_ndk(self):
|
||||
seen = {}
|
||||
with mock.patch.object(prepare, 'identity', lambda name, root: seen.update(
|
||||
arch=reuse.os.environ['RUNNER_ARCH'], ndk=reuse.os.environ['NDK_VERSION']) or 'x'):
|
||||
reuse.identities(reuse.ci_environment('X64', self.root), self.root)
|
||||
self.assertEqual({'arch': 'X64', 'ndk': '30.0.1'}, seen)
|
||||
@@ -1,17 +1,67 @@
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge"
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
HELPER = BIN / "droiddeck-curseforge"
|
||||
HEADLESS = BIN / "droiddeck-headless"
|
||||
URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
||||
|
||||
|
||||
class HeadlessTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.bin = self.tmp / "bin"
|
||||
self.bin.mkdir()
|
||||
self.seen = self.tmp / "seen"
|
||||
gamescope = self.bin / "gamescope"
|
||||
gamescope.write_text(
|
||||
"#!/bin/bash\n"
|
||||
"printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"GAMESCOPE=${GAMESCOPE_WAYLAND_DISPLAY-}\" "
|
||||
"\"XAUTH=${XAUTHORITY-}\" \"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n"
|
||||
"echo logged-by-gamescope\n" % shlex.quote(str(self.seen)))
|
||||
gamescope.chmod(0o755)
|
||||
|
||||
def env(self, extra=None):
|
||||
base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DISPLAY=":0", WAYLAND_DISPLAY="wayland-0",
|
||||
GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", XAUTHORITY="/run/xauth")
|
||||
base.update(extra or {})
|
||||
return base
|
||||
|
||||
def run_headless(self, *args, env=None):
|
||||
return subprocess.run(["bash", str(HEADLESS), *args], env=self.env(env), capture_output=True, text=True, timeout=30)
|
||||
|
||||
def test_it_runs_the_command_in_headless_gamescope_with_a_private_runtime_and_no_session_display(self):
|
||||
runtime = self.tmp / "runtime"
|
||||
out = self.run_headless(str(runtime), "--", "prog", "arg one")
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual(["DISPLAY=", "WAYLAND=", "GAMESCOPE=", "XAUTH=", "RUNTIME=%s" % runtime, "--backend", "headless",
|
||||
"-w", "640", "-h", "480", "--", "prog", "arg one"], self.seen.read_text().splitlines())
|
||||
self.assertEqual(0o700, runtime.stat().st_mode & 0o777)
|
||||
|
||||
def test_output_goes_to_the_log_which_rotates_when_large(self):
|
||||
log = self.tmp / "agent.log"
|
||||
log.write_bytes(b"x" * 100)
|
||||
self.assertEqual(0, self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog").returncode)
|
||||
self.assertTrue(log.read_text().endswith("logged-by-gamescope\n"))
|
||||
self.assertEqual(100, log.stat().st_size - len("logged-by-gamescope\n"))
|
||||
self.assertFalse((self.tmp / "agent.log.1").exists())
|
||||
self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog", env={"DD_HEADLESS_LOG_LIMIT": "50"})
|
||||
self.assertEqual(100 + len("logged-by-gamescope\n"), (self.tmp / "agent.log.1").stat().st_size)
|
||||
self.assertEqual("logged-by-gamescope\n", log.read_text())
|
||||
|
||||
def test_bad_arguments_are_refused(self):
|
||||
self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "prog").returncode)
|
||||
self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "--").returncode)
|
||||
self.assertEqual(2, self.run_headless().returncode)
|
||||
|
||||
|
||||
class CurseForgeHelperTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
@@ -21,18 +71,23 @@ class CurseForgeHelperTest(unittest.TestCase):
|
||||
self.dir = self.tmp / "curseforge"
|
||||
(self.dir / "app").mkdir(parents=True)
|
||||
self.state = self.tmp / "state"
|
||||
self.bin = self.tmp / "bin"
|
||||
self.bin.mkdir()
|
||||
self.runner = self.tmp / "runner"
|
||||
self.seen = self.tmp / "seen"
|
||||
self.runner.write_text(
|
||||
"#!/bin/bash\n"
|
||||
"printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" "
|
||||
"\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n"
|
||||
"printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" "
|
||||
"\"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n"
|
||||
"mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
|
||||
"echo 'Debugger listening on %s'\n"
|
||||
"echo 'For help, see: https://nodejs.org/en/docs/inspector'\n"
|
||||
"exec sleep 60\n"
|
||||
"echo 'Debugger listening on %s' >&2\n"
|
||||
"echo 'For help, see: https://nodejs.org/en/docs/inspector' >&2\n"
|
||||
"sleep 60\n"
|
||||
% (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL))
|
||||
self.runner.chmod(0o755)
|
||||
gamescope = self.bin / "gamescope"
|
||||
gamescope.write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@"\n')
|
||||
gamescope.chmod(0o755)
|
||||
|
||||
def fake(self, pid, *argv):
|
||||
d = self.proc / str(pid)
|
||||
@@ -40,15 +95,27 @@ class CurseForgeHelperTest(unittest.TestCase):
|
||||
(d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv))
|
||||
|
||||
def env(self, extra=None):
|
||||
base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")}
|
||||
base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner),
|
||||
DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x")
|
||||
base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DD_PROC=str(self.proc),
|
||||
DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), DD_HEADLESS_RUN=str(HEADLESS),
|
||||
DD_CURSEFORGE_WAIT="10", DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", XDG_RUNTIME_DIR="/run/user/session",
|
||||
DBUS_SESSION_BUS_ADDRESS="unix:path=/x")
|
||||
base.update(extra or {})
|
||||
return base
|
||||
|
||||
def run_helper(self, *args, env=None):
|
||||
return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60)
|
||||
|
||||
def launch(self, directory=None):
|
||||
holder = subprocess.Popen(["bash", str(HELPER), "start", str(directory or self.dir)], env=self.env(),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
self.addCleanup(self.finish, holder)
|
||||
return holder, holder.stdout.readline().strip()
|
||||
|
||||
def finish(self, holder):
|
||||
if holder.poll() is None:
|
||||
holder.kill()
|
||||
holder.communicate()
|
||||
|
||||
def stop(self):
|
||||
self.run_helper("stop", str(self.dir))
|
||||
|
||||
@@ -64,86 +131,56 @@ class CurseForgeHelperTest(unittest.TestCase):
|
||||
time.sleep(0.1)
|
||||
return False
|
||||
|
||||
def test_the_desktop_x_display_is_found_from_xwayland(self):
|
||||
self.fake(40, "/usr/bin/kwin_wayland", ":9")
|
||||
self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5")
|
||||
out = self.run_helper("display", "")
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines())
|
||||
|
||||
def test_the_session_display_wins(self):
|
||||
self.fake(41, "/usr/bin/Xwayland", ":3")
|
||||
out = self.run_helper("display", "", env={"DISPLAY": ":0"})
|
||||
self.assertEqual(":0", out.stdout.splitlines()[0])
|
||||
|
||||
def test_no_display_is_reported(self):
|
||||
out = self.run_helper("start", str(self.dir))
|
||||
self.assertEqual(4, out.returncode)
|
||||
|
||||
def test_a_running_instance_without_the_inspector_is_busy(self):
|
||||
self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox")
|
||||
out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
|
||||
out = self.run_helper("start", str(self.dir))
|
||||
self.assertEqual(3, out.returncode)
|
||||
self.assertEqual("busy", out.stdout.strip())
|
||||
self.stop()
|
||||
self.assertTrue((self.proc / "50").exists())
|
||||
|
||||
def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self):
|
||||
self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc")
|
||||
out = self.run_helper("start", str(self.dir))
|
||||
def test_start_runs_the_app_in_headless_gamescope_with_a_secret_inspector_and_no_session_display(self):
|
||||
holder, url = self.launch()
|
||||
self.addCleanup(self.stop)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual(URL, out.stdout.strip())
|
||||
self.assertEqual(URL, url)
|
||||
seen = self.seen.read_text().splitlines()
|
||||
self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir),
|
||||
"--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen)
|
||||
self.assertEqual(["DISPLAY=", "WAYLAND=", "DBUS=", "RUNTIME=%s/runtime" % self.state, str(self.dir), "--minimized",
|
||||
"--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen)
|
||||
self.assertEqual(0o700, self.state.stat().st_mode & 0o777)
|
||||
self.assertEqual(0o700, (self.state / "runtime").stat().st_mode & 0o777)
|
||||
self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777)
|
||||
again = self.run_helper("start", str(self.dir))
|
||||
self.assertEqual(URL, again.stdout.strip())
|
||||
pid = self.pid()
|
||||
_, again = self.launch()
|
||||
self.assertEqual(URL, again)
|
||||
|
||||
def test_start_holds_the_app_until_it_is_stopped(self):
|
||||
holder, url = self.launch()
|
||||
self.assertEqual(URL, url)
|
||||
app = self.pid()
|
||||
time.sleep(1)
|
||||
self.assertIsNone(holder.poll())
|
||||
os.kill(app, 0)
|
||||
self.stop()
|
||||
self.assertEqual(0, holder.wait(timeout=30))
|
||||
self.assertTrue(self.gone(app), "the app is still running")
|
||||
|
||||
def test_stop_ends_the_app_and_the_gamescope_it_ran_in(self):
|
||||
(self.bin / "gamescope").write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@" &\nwait\n')
|
||||
self.assertEqual(URL, self.launch()[1])
|
||||
gamescope = self.pid()
|
||||
app = int(next(self.proc.iterdir()).name)
|
||||
self.assertNotEqual(gamescope, app)
|
||||
os.kill(app, 0)
|
||||
self.stop()
|
||||
self.assertFalse((self.state / "pid").exists())
|
||||
self.assertTrue(self.gone(pid), "the started instance is still running")
|
||||
self.assertTrue(self.gone(gamescope), "gamescope is still running")
|
||||
self.assertTrue(self.gone(app), "the app is still running")
|
||||
|
||||
def test_hold_keeps_the_app_until_it_is_signalled(self):
|
||||
held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self.addCleanup(self.end, held)
|
||||
for _ in range(100):
|
||||
if (self.state / "pid").exists() and self.seen.exists():
|
||||
break
|
||||
time.sleep(0.1)
|
||||
pid = self.pid()
|
||||
time.sleep(1)
|
||||
self.assertIsNone(held.poll())
|
||||
held.send_signal(signal.SIGTERM)
|
||||
self.assertEqual(0, held.wait(timeout=30))
|
||||
self.assertTrue(self.gone(pid), "hold left the app running")
|
||||
self.assertFalse((self.state / "pid").exists())
|
||||
|
||||
def end(self, held):
|
||||
if held.poll() is None:
|
||||
held.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
held.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
held.kill()
|
||||
held.wait()
|
||||
record = self.state / "pid"
|
||||
if record.exists():
|
||||
try:
|
||||
os.killpg(self.pid(), signal.SIGKILL)
|
||||
except (ProcessLookupError, PermissionError):
|
||||
pass
|
||||
|
||||
def test_a_launch_for_another_directory_is_busy(self):
|
||||
def test_a_launch_for_another_directory_is_busy_and_left_alone(self):
|
||||
other = self.tmp / "other"
|
||||
(other / "app").mkdir(parents=True)
|
||||
first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
|
||||
self.addCleanup(self.stop)
|
||||
self.assertEqual(0, first.returncode, first.stderr)
|
||||
out = self.run_helper("start", str(other), env={"DISPLAY": ":0"})
|
||||
self.assertEqual(URL, self.launch()[1])
|
||||
out = self.run_helper("start", str(other))
|
||||
self.assertEqual(3, out.returncode)
|
||||
self.assertEqual("busy", out.stdout.strip())
|
||||
pid = self.pid()
|
||||
@@ -151,22 +188,25 @@ class CurseForgeHelperTest(unittest.TestCase):
|
||||
self.assertEqual(pid, self.pid())
|
||||
os.kill(pid, 0)
|
||||
|
||||
def test_hold_ends_when_the_app_exits(self):
|
||||
proc = shlex.quote(str(self.proc))
|
||||
self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
|
||||
"echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc))
|
||||
out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
|
||||
capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
def test_each_launch_starts_a_fresh_log(self):
|
||||
first, _ = self.launch()
|
||||
self.stop()
|
||||
first.wait(timeout=30)
|
||||
self.addCleanup(self.stop)
|
||||
self.assertEqual(URL, self.launch()[1])
|
||||
self.assertEqual(1, (self.state / "log").read_text().count("Debugger listening"))
|
||||
self.assertTrue((self.state / "log.1").exists())
|
||||
|
||||
def test_stop_without_a_launch_is_quiet(self):
|
||||
out = self.run_helper("stop", str(self.dir))
|
||||
self.assertEqual(0, out.returncode)
|
||||
self.assertEqual("", out.stderr)
|
||||
self.assertEqual("", out.stdout)
|
||||
|
||||
def test_bad_arguments_are_refused(self):
|
||||
self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode)
|
||||
self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode)
|
||||
self.assertEqual(2, self.run_helper("hold", str(self.dir)).returncode)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c"
|
||||
SYSROOT = Path("/usr/aarch64-linux-gnu")
|
||||
|
||||
LIBRARY = r"""
|
||||
int dd_probe_value(void) { return 7; }
|
||||
"""
|
||||
|
||||
HOOK = r"""
|
||||
#include <unistd.h>
|
||||
|
||||
__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); }
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
int dd_probe_value(void);
|
||||
|
||||
int main(int argc, char **argv, char **envp) {
|
||||
if (dd_probe_value() != 7) return 4;
|
||||
if (argc > 1 && strcmp(argv[1], "again") == 0) {
|
||||
for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]);
|
||||
printf("\n%s\n", (char *)getauxval(AT_EXECFN));
|
||||
return 0;
|
||||
}
|
||||
char *next[] = {"first", "again", "x y", NULL};
|
||||
syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0);
|
||||
return 3;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def ndk_clang():
|
||||
sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk")
|
||||
for ndk in sorted((sdk / "ndk").glob("*"), reverse=True):
|
||||
clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang"
|
||||
if clang.exists():
|
||||
return str(clang)
|
||||
return shutil.which("clang")
|
||||
|
||||
|
||||
class DdexecReexecTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cc, prefix = runner()
|
||||
clang = ndk_clang()
|
||||
if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir():
|
||||
raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap")
|
||||
cls.qemu = list(prefix[:3]) if prefix else []
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.loader = tmp / "libddexec.so"
|
||||
subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding",
|
||||
"-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib",
|
||||
"-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic",
|
||||
"-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True)
|
||||
cls.libdir = tmp / "own-lib"
|
||||
cls.libdir.mkdir()
|
||||
(tmp / "lib.c").write_text(LIBRARY)
|
||||
subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")],
|
||||
check=True)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
cls.program = tmp / "prog"
|
||||
subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"],
|
||||
check=True)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "usr/lib").mkdir(parents=True)
|
||||
(cls.root / "lib").mkdir()
|
||||
shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1")
|
||||
(tmp / "hook.c").write_text(HOOK)
|
||||
subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")],
|
||||
check=True)
|
||||
probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True)
|
||||
if probe.returncode != 0:
|
||||
raise unittest.SkipTest("bwrap cannot create a namespace here")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def env(self, real_exe, library_path=None, root=SYSROOT):
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))}
|
||||
env["DDNATV_ROOT"] = str(root)
|
||||
env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib")
|
||||
if real_exe:
|
||||
env["DDNATV_REAL_EXE"] = str(real_exe)
|
||||
if library_path:
|
||||
env["DDNATV_LIBRARY_PATH"] = library_path
|
||||
return env
|
||||
|
||||
def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT):
|
||||
jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"]
|
||||
parent = str(Path(execfn).parent)
|
||||
jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn]
|
||||
start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn]
|
||||
cmd = jail + start + ["again", "x y"]
|
||||
return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120)
|
||||
|
||||
def test_reexec_through_proc_self_exe_runs_the_guest_program(self):
|
||||
out = self.reexec("/proc/self/exe", self.program)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
|
||||
|
||||
def test_reexec_through_thread_self_exe_runs_the_guest_program(self):
|
||||
out = self.reexec("/proc/thread-self/exe", self.program)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
|
||||
|
||||
def test_reexec_finds_libraries_through_the_recorded_library_path(self):
|
||||
out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}")
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
|
||||
|
||||
def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self):
|
||||
out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines())
|
||||
|
||||
def test_reexec_without_a_known_program_fails_cleanly(self):
|
||||
out = self.reexec("/proc/self/exe", None)
|
||||
self.assertEqual(127, out.returncode)
|
||||
self.assertIn("DDNATV_REAL_EXE", out.stderr)
|
||||
|
||||
def test_a_started_program_keeps_its_own_arguments(self):
|
||||
ldso = SYSROOT / "lib/ld-linux-aarch64.so.1"
|
||||
cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}",
|
||||
str(self.program), "again", "a"]
|
||||
out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines())
|
||||
|
||||
def test_the_usage_check_still_applies_outside_a_reexec(self):
|
||||
out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program),
|
||||
capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(127, out.returncode)
|
||||
self.assertIn("usage", out.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,11 +1,8 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-desktop-gpu"
|
||||
PREFIX = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
|
||||
FLAGS = " --no-sandbox --ozone-platform=x11"
|
||||
|
||||
|
||||
def load():
|
||||
@@ -24,12 +21,6 @@ class DesktopChromiumAppsTest(unittest.TestCase):
|
||||
self.gpu = load()
|
||||
self.electron = self.app("lib/chat/chat", sandbox=True)
|
||||
self.plain = self.app("lib/editor/editor", sandbox=False)
|
||||
bin_dir = self.root / "bin"
|
||||
bin_dir.mkdir()
|
||||
(bin_dir / "chat").symlink_to(self.electron)
|
||||
old_path = os.environ.get("PATH", "")
|
||||
os.environ["PATH"] = "%s:%s" % (bin_dir, old_path)
|
||||
self.addCleanup(os.environ.__setitem__, "PATH", old_path)
|
||||
|
||||
def app(self, relative, sandbox):
|
||||
path = self.root / relative
|
||||
@@ -49,34 +40,17 @@ class DesktopChromiumAppsTest(unittest.TestCase):
|
||||
def exec_lines(self, text):
|
||||
return [l[5:] for l in text.splitlines() if l.startswith("Exec=")]
|
||||
|
||||
def test_an_electron_app_starts_without_the_sandbox_on_x11(self):
|
||||
out = self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron))
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS + " %U",
|
||||
PREFIX + str(self.electron) + FLAGS + " --new"])
|
||||
self.assertIn("X-DroidDeck-GPU=1", out)
|
||||
self.assertIn("Actions=new;", out)
|
||||
self.assertNotIn("droiddeck-window", out)
|
||||
def test_electron_apps_keep_their_own_entries(self):
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron)))
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain))))
|
||||
|
||||
def test_a_command_on_the_path_is_followed_to_its_install_folder(self):
|
||||
out = self.gpu["wrap"](self.entry("chat %U"))
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + "chat" + FLAGS + " %U"])
|
||||
def test_an_electron_game_goes_to_the_gpu_as_installed(self):
|
||||
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;", actions="%s --new" % self.electron))
|
||||
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + str(self.electron), str(self.electron),
|
||||
"droiddeck-gpu %s --new" % self.electron])
|
||||
|
||||
def test_a_quoted_program_keeps_its_quotes(self):
|
||||
out = self.gpu["wrap"](self.entry('"%s" %%U' % self.electron))
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + '"%s"' % self.electron + FLAGS + " %U"])
|
||||
|
||||
def test_other_apps_are_left_alone(self):
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%F" % self.plain)))
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry("missing-program %F")))
|
||||
|
||||
def test_an_electron_game_goes_to_the_gpu_and_keeps_a_window_action(self):
|
||||
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"))
|
||||
fixed = PREFIX + str(self.electron) + FLAGS
|
||||
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + fixed, fixed])
|
||||
|
||||
def test_with_the_gpu_off_electron_apps_are_still_fixed(self):
|
||||
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)
|
||||
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS])
|
||||
def test_with_the_gpu_off_no_entry_is_written(self):
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False))
|
||||
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False))
|
||||
|
||||
def test_games_that_are_not_chromium_are_unchanged(self):
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
|
||||
DESKTOP = (Path(__file__).resolve().parents[1] / 'linuxfs/desktop/droiddeck-desktop').read_text()
|
||||
START = 'if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then'
|
||||
LINE = '\n [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0\n'
|
||||
|
||||
|
||||
class DesktopFirefoxSoftwareTest(unittest.TestCase):
|
||||
def firefox_environment(self, gl_present):
|
||||
head = DESKTOP[:DESKTOP.index('\n', DESKTOP.index('export MOZ_ENABLE_WAYLAND=1'))]
|
||||
head = head[head.rindex('\n') + 1:]
|
||||
block = DESKTOP[DESKTOP.index(START):]
|
||||
block = block[block.index('\n') + 1:block.index('\n if [ -z "${KWIN_RENDER_NODES:-}" ]')]
|
||||
environment = {key: value for key, value in os.environ.items()
|
||||
if key not in ('DD_STEAM_GL_PRESENT', 'MOZ_ENABLE_WAYLAND', 'MOZ_ACCELERATED')}
|
||||
if gl_present is not None:
|
||||
environment['DD_STEAM_GL_PRESENT'] = gl_present
|
||||
script = head + '\n' + block + '\nsh -c \'echo "wayland:${MOZ_ENABLE_WAYLAND:-unset} accelerated:${MOZ_ACCELERATED:-unset}"\''
|
||||
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True,
|
||||
text=True, timeout=5)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return result.stdout.strip().splitlines()[-1]
|
||||
|
||||
def test_system_powervr_desktop_runs_firefox_on_wayland_with_software_rendering(self):
|
||||
self.assertEqual('wayland:1 accelerated:0', self.firefox_environment('1'))
|
||||
|
||||
def test_other_drivers_keep_firefox_hardware_rendering(self):
|
||||
self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment(None))
|
||||
self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment('0'))
|
||||
|
||||
def test_override_is_set_before_plasma(self):
|
||||
self.assertLess(DESKTOP.index(LINE), DESKTOP.index('dbus-run-session -- startplasma-wayland'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -348,6 +348,28 @@ class AgentTest(unittest.TestCase):
|
||||
self.assertEqual("INVALID_TARGET", caught.exception.code)
|
||||
connect.assert_not_called()
|
||||
|
||||
def test_one_shot_inspector_eval_prints_the_session_answer_without_a_launch_dir(self):
|
||||
import contextlib
|
||||
import io
|
||||
url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
|
||||
seen = {}
|
||||
|
||||
def evaluate(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, command_line_api=False):
|
||||
seen.update(expression=expression, timeout=timeout, inspector=inspector, api=command_line_api)
|
||||
return {"target": "inspector", "type": "string", "value": "ok", "description": None}
|
||||
|
||||
out = io.StringIO()
|
||||
with patch.dict(os.environ, {}, clear=False), patch.object(agent, "cdp_eval", evaluate), contextlib.redirect_stdout(out):
|
||||
os.environ.pop("DD_LAUNCH_DIR", None)
|
||||
self.assertEqual(0, agent.main(["--cdp-inspector", url, "12.5", "1 + 1"]))
|
||||
self.assertEqual({"target": "inspector", "type": "string", "value": "ok", "description": None, "ok": True}, json.loads(out.getvalue()))
|
||||
self.assertEqual({"expression": "1 + 1", "timeout": 12.5, "inspector": url, "api": True}, seen)
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
self.assertEqual(0, agent.main(["--cdp-inspector", "ws://example.com:9229/x", "5", "1"]))
|
||||
self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"])
|
||||
self.assertEqual(2, agent.main(["--cdp-inspector", url]))
|
||||
|
||||
def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self):
|
||||
class Lost:
|
||||
def __init__(self, *args, **kwargs):
|
||||
|
||||
@@ -526,6 +526,21 @@ class PrepareTest(FexTestCase):
|
||||
for name in names:
|
||||
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode())
|
||||
|
||||
def test_opengl_dispatch_library_comes_from_the_newer_runtime_when_the_base_lacks_it(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
FEX["materialize"](str(sniper))
|
||||
provider = self.graphics(sniper)
|
||||
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
|
||||
self.write(sniper / "files/lib" / arch / "libGLdispatch.so.0", b"base dispatch")
|
||||
self.write(provider / "files/lib" / arch / "libOpenGL.so.0.0.0", b"opengl " + arch.encode())
|
||||
os.symlink("libOpenGL.so.0.0.0", provider / "files/lib" / arch / "libOpenGL.so.0")
|
||||
fex, _ = self.quiet(FEX["prepare"])
|
||||
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
|
||||
root = Path(fex["rootfs"]) / "lib" / arch
|
||||
self.assertEqual((root / "libOpenGL.so.0").read_bytes(), b"opengl " + arch.encode())
|
||||
self.assertEqual((root / "libGLdispatch.so.0").read_bytes(), b"base dispatch")
|
||||
|
||||
def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
@@ -1008,6 +1023,73 @@ class ExtractTest(FexTestCase):
|
||||
self.assertIn("-no-xattrs", commands[-1])
|
||||
self.assertTrue(Path("squashfs-root/AppRun").is_file())
|
||||
|
||||
def seven_zip(self, tool, which, works=True):
|
||||
commands = []
|
||||
|
||||
def call(argv, **kwargs):
|
||||
commands.append(argv)
|
||||
if argv[0] != "/usr/bin/7z" or not works:
|
||||
return 2
|
||||
(self.work / "squashfs-root").mkdir()
|
||||
(self.work / "squashfs-root/AppRun").touch()
|
||||
return 0
|
||||
|
||||
with mock.patch.dict(G, {
|
||||
"URUNTIME": tool,
|
||||
"prepare": lambda: None,
|
||||
"fex_install": lambda: None,
|
||||
"steam_running": lambda: False,
|
||||
"want_fex": lambda: None,
|
||||
}), mock.patch("shutil.which", side_effect=lambda name: which.get(name)), \
|
||||
mock.patch("subprocess.call", side_effect=call):
|
||||
status, said = self.quiet(FEX["extract"], "image.AppImage")
|
||||
return status, said, commands
|
||||
|
||||
def test_without_proot_the_shipped_runtime_reads_the_open_image(self):
|
||||
self.write(self.image, elf(183) + b"payload", 0o755)
|
||||
tool = self.uruntime('cmp "$TARGET_APPIMAGE" "%s" || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image)
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
|
||||
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
|
||||
self.assertEqual((status, said), (0, ""))
|
||||
self.assertEqual([], commands)
|
||||
self.assertTrue(Path("squashfs-root/AppRun").is_file())
|
||||
|
||||
def test_without_proot_runtime_failure_falls_back_to_7zip(self):
|
||||
self.write(self.image, elf(183) + b"payload", 0o755)
|
||||
tool = self.uruntime("exit 1\n")
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
|
||||
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
|
||||
self.assertEqual(status, 0)
|
||||
self.assertIn("uruntime could not extract it (status 1)", said)
|
||||
self.assertEqual("/usr/bin/7z", commands[-1][0])
|
||||
self.assertTrue(Path("squashfs-root/AppRun").is_file())
|
||||
|
||||
def test_with_proot_the_shipped_runtime_is_still_tried_first(self):
|
||||
ran = self.tmp / "uruntime-ran"
|
||||
tool = self.uruntime("touch %s\nexit 1\n" % ran)
|
||||
env = {k: v for k, v in os.environ.items() if k != "DDNATV_ROOT"}
|
||||
with mock.patch.dict(os.environ, env, clear=True):
|
||||
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
|
||||
self.assertEqual(status, 0)
|
||||
self.assertTrue(ran.exists())
|
||||
self.assertIn("uruntime could not extract it (status 1)", said)
|
||||
self.assertEqual("/usr/bin/7z", commands[-1][0])
|
||||
|
||||
def test_unsquashfs_is_preferred_over_7zip(self):
|
||||
tool = self.uruntime("exit 1\n")
|
||||
status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"})
|
||||
self.assertEqual(status, 0)
|
||||
self.assertIn("unsquashfs could not extract it (status 2)", said)
|
||||
self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands])
|
||||
|
||||
def test_a_7zip_failure_leaves_nothing_unpacked(self):
|
||||
tool = self.uruntime("exit 1\n")
|
||||
status, said, _ = self.seven_zip(tool, {"7z": "/usr/bin/7z"}, works=False)
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("7-Zip could not extract it (status 2)", said)
|
||||
self.assertNotIn("no unsquashfs", said)
|
||||
self.assertFalse(os.path.lexists("squashfs-root"))
|
||||
|
||||
|
||||
class LaunchTest(FexTestCase):
|
||||
def test_the_guest_environment(self):
|
||||
@@ -1055,6 +1137,12 @@ class LaunchTest(FexTestCase):
|
||||
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
|
||||
self.assertNotIn("GLIBC_TUNABLES", guest)
|
||||
|
||||
def test_host_iconv_modules_stay_on_the_host(self):
|
||||
guest = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/r/usr/lib/aarch64-linux-gnu/gconv"})
|
||||
self.assertEqual(guest["GCONV_PATH"], "")
|
||||
own = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/opt/gconv"})
|
||||
self.assertEqual(own["GCONV_PATH"], "/opt/gconv")
|
||||
|
||||
def test_proton_runs_in_the_runtime_its_manifest_requires(self):
|
||||
self.fex_tool()
|
||||
self.runtime()
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATCH = REPO / "tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch"
|
||||
SYSCALLS = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp"
|
||||
INTERPRETER = "Source/Tools/FEXInterpreter/FEXInterpreter.cpp"
|
||||
|
||||
|
||||
def lines(sign):
|
||||
return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)]
|
||||
|
||||
|
||||
class FexFdExecTest(unittest.TestCase):
|
||||
def test_only_the_execve_handler_and_the_interpreter_change(self):
|
||||
self.assertEqual([INTERPRETER, SYSCALLS], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
|
||||
|
||||
def test_a_descriptor_exec_keeps_the_callers_argv0(self):
|
||||
self.assertIn("if (!NeedsLoaderFD) {", lines("-"))
|
||||
self.assertIn("if (!NeedsLoaderFD && !IsFDExec) {", lines("+"))
|
||||
|
||||
def test_an_anonymous_program_reports_its_recovered_path(self):
|
||||
self.assertIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, "<Anonymous>");', lines("-"))
|
||||
self.assertIn("FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath);", lines("+"))
|
||||
|
||||
def test_the_config_name_stays_anonymous(self):
|
||||
self.assertNotIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, "<Anonymous>");', lines("-"))
|
||||
|
||||
def test_no_comments_are_added(self):
|
||||
self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,29 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0015-gl-thunk-overlays-libopengl.patch"
|
||||
|
||||
|
||||
def hunk(sign):
|
||||
lines = [line for line in PATCH.read_text().splitlines() if not line.startswith(("diff ", "index ", "--- ", "+++ ", "@@"))]
|
||||
return re.findall(r'"([^"]+)"', "\n".join(line[1:] for line in lines if line[:1] in (" ", sign)))
|
||||
|
||||
|
||||
class FexGlThunkOverlayTest(unittest.TestCase):
|
||||
def test_libopengl_joins_the_gl_overlay(self):
|
||||
before, after = hunk("-"), hunk("+")
|
||||
self.assertNotIn("@PREFIX_LIB@/libOpenGL.so.0", before)
|
||||
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0", after)
|
||||
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0.0.0", after)
|
||||
self.assertEqual([path for path in before if path.startswith("@PREFIX_LIB@/libGL.")],
|
||||
[path for path in after if path.startswith("@PREFIX_LIB@/libGL.")])
|
||||
self.assertLess(after.index("@PREFIX_LIB@/libGL.so.1.7.0"), after.index("Vulkan"))
|
||||
self.assertLess(after.index("@PREFIX_LIB@/libOpenGL.so.0.0.0"), after.index("Vulkan"))
|
||||
|
||||
def test_patch_touches_only_the_thunks_database(self):
|
||||
self.assertEqual(["Data/ThunksDB.json"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0014-guest-preload-drops-host-libraries.patch"
|
||||
|
||||
HARNESS = r"""
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <elf.h>
|
||||
#include <fcntl.h>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
namespace fextl { using string = std::string; }
|
||||
namespace ELFLoader {
|
||||
struct ELFContainer {
|
||||
enum ELFType { TYPE_NONE, TYPE_X86_64, TYPE_X86_32, TYPE_OTHER_ELF };
|
||||
static ELFType GetELFType(const std::string& Filename) {
|
||||
int FD = open(Filename.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (FD == -1) return TYPE_NONE;
|
||||
Elf64_Ehdr Header {};
|
||||
ssize_t Read = pread(FD, &Header, sizeof(Header), 0);
|
||||
close(FD);
|
||||
if (Read < (ssize_t)sizeof(Header) || memcmp(Header.e_ident, ELFMAG, SELFMAG) != 0) return TYPE_NONE;
|
||||
if (Header.e_machine == EM_X86_64) return TYPE_X86_64;
|
||||
if (Header.e_machine == EM_386) return TYPE_X86_32;
|
||||
return TYPE_OTHER_ELF;
|
||||
}
|
||||
};
|
||||
}
|
||||
struct Loader {
|
||||
static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { return RootFS + File; }
|
||||
GUEST_PRELOAD
|
||||
};
|
||||
int main(int argc, char** argv) {
|
||||
std::printf("%s", Loader::GuestPreload(argv[1], argv[2]).c_str());
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def x86_compiler():
|
||||
for name in ("x86_64-linux-gnu-gcc", "gcc"):
|
||||
path = shutil.which(name)
|
||||
if path and subprocess.run([path, "-dumpmachine"], capture_output=True, text=True).stdout.startswith("x86_64"):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
X86_CC = x86_compiler()
|
||||
|
||||
|
||||
def patch_function():
|
||||
lines = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
body = "\n".join(lines)
|
||||
first = body.index(" static fextl::string GuestPreload(")
|
||||
last = body.index("\n }\n", first) + len("\n }\n")
|
||||
return body[first:last]
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("g++") and X86_CC and shutil.which("aarch64-linux-gnu-gcc"), "needs g++, an x86-64 gcc and aarch64-linux-gnu-gcc")
|
||||
class FexGuestPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.dir = Path(cls.tmp.name)
|
||||
source = cls.dir / "harness.cpp"
|
||||
source.write_text(HARNESS.replace("GUEST_PRELOAD", patch_function()))
|
||||
cls.binary = cls.dir / "harness"
|
||||
subprocess.run(["g++", "-std=c++20", "-O1", "-o", str(cls.binary), str(source)], check=True)
|
||||
stub = cls.dir / "stub.c"
|
||||
stub.write_text("int stub(void) { return 0; }\n")
|
||||
cls.host = cls.dir / "host"
|
||||
cls.rootfs = cls.dir / "rootfs"
|
||||
cls.shadow = cls.host / "lib/libshadow.so"
|
||||
cls.rootfs_shadow = Path(str(cls.rootfs) + str(cls.shadow))
|
||||
for folder in (cls.host / "lib", cls.rootfs_shadow.parent):
|
||||
folder.mkdir(parents=True)
|
||||
cls.compile("aarch64-linux-gnu-gcc", stub, cls.host / "lib/libhost.so")
|
||||
cls.compile(X86_CC, stub, cls.host / "lib/libguest.so")
|
||||
cls.compile("aarch64-linux-gnu-gcc", stub, cls.shadow)
|
||||
cls.compile(X86_CC, stub, cls.rootfs_shadow)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
@staticmethod
|
||||
def compile(compiler, source, output):
|
||||
subprocess.run([compiler, "-shared", "-fPIC", "-o", str(output), str(source)], check=True)
|
||||
|
||||
def preload(self, value, rootfs=None):
|
||||
root = str(self.rootfs) if rootfs is None else rootfs
|
||||
return subprocess.run([str(self.binary), value, root], check=True, capture_output=True, text=True).stdout
|
||||
|
||||
def test_host_libraries_leave_the_guest_list(self):
|
||||
host, guest = self.host / "lib/libhost.so", self.host / "lib/libguest.so"
|
||||
self.assertEqual(str(guest), self.preload(f"{host}:{guest}"))
|
||||
self.assertEqual("", self.preload(str(host)))
|
||||
|
||||
def test_rootfs_copy_decides_before_the_host_path(self):
|
||||
self.assertEqual(str(self.shadow), self.preload(str(self.shadow)))
|
||||
self.assertEqual("", self.preload(str(self.shadow), ""))
|
||||
|
||||
def test_names_missing_files_and_separators_are_kept(self):
|
||||
missing = str(self.dir / "missing.so")
|
||||
guest = str(self.host / "lib/libguest.so")
|
||||
self.assertEqual(f"libgamemodeauto.so.0:{missing}:{guest}",
|
||||
self.preload(f" libgamemodeauto.so.0::{missing} {guest}:"))
|
||||
|
||||
def test_patch_adds_no_comments(self):
|
||||
added = [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
self.assertFalse([line for line in added if line.startswith(("//", "/*"))])
|
||||
self.assertEqual(["Source/Tools/FEXInterpreter/ELFCodeLoader.h"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,148 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATCH = REPO / "tools/fex/patches/0016-identity-syscalls-through-libc.patch"
|
||||
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
|
||||
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
|
||||
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
|
||||
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
|
||||
IDENTITY = {"getuid", "getgid", "geteuid", "getegid", "setuid", "setgid", "setreuid", "setregid", "getgroups",
|
||||
"setgroups", "setresuid", "getresuid", "setresgid", "getresgid", "setfsuid", "setfsgid", "fchown"}
|
||||
|
||||
|
||||
def changed():
|
||||
removed, added = {}, {}
|
||||
for line in PATCH.read_text().splitlines():
|
||||
found = REGISTER.search(line)
|
||||
if found and line[:1] in "+-":
|
||||
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
|
||||
return removed, added
|
||||
|
||||
|
||||
class FexIdentitySyscallsTest(unittest.TestCase):
|
||||
def test_only_the_passthrough_table_changes(self):
|
||||
self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH])
|
||||
|
||||
def test_each_identity_syscall_keeps_its_arity_and_goes_through_libc(self):
|
||||
removed, added = changed()
|
||||
self.assertEqual(sorted(removed), sorted(added))
|
||||
self.assertEqual(IDENTITY, {number for _, _, number in added.values()})
|
||||
for name, (template, arity, number) in added.items():
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
|
||||
self.assertEqual("SyscallPathPassthrough", template)
|
||||
|
||||
def test_the_new_template_calls_the_libc_syscall(self):
|
||||
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
self.assertEqual([" uint64_t Result = ::syscall(syscall_num);"], [line for line in added if "Result =" in line])
|
||||
self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))])
|
||||
|
||||
def test_every_routed_syscall_is_answered_by_the_hook(self):
|
||||
hook = HOOK.read_text()
|
||||
for number in IDENTITY:
|
||||
with self.subTest(number=number):
|
||||
self.assertIn(f"number == __NR_{number})", hook)
|
||||
|
||||
|
||||
PROBE = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
unsigned int r = 7, e = 7, s = 7;
|
||||
long rc = syscall(SYS_getresuid, &r, &e, &s);
|
||||
printf("getresuid %ld %u %u %u\n", rc, r, e, s);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresuid, NULL, &e, &s);
|
||||
printf("getresuid-null %ld %d\n", rc, errno);
|
||||
r = e = s = 7;
|
||||
rc = syscall(SYS_getresgid, &r, &e, &s);
|
||||
printf("getresgid %ld %u %u %u\n", rc, r, e, s);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresgid, &r, NULL, &s);
|
||||
printf("getresgid-null %ld %d\n", rc, errno);
|
||||
unsigned int *locked = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresuid, &r, &e, locked);
|
||||
printf("getresuid-readonly %ld %d\n", rc, errno);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getresgid, locked, &e, &s);
|
||||
printf("getresgid-readonly %ld %d\n", rc, errno);
|
||||
gid_t groups[8];
|
||||
rc = syscall(SYS_getgroups, 8, groups);
|
||||
printf("getgroups %ld %u\n", rc, rc > 0 ? groups[0] : 99u);
|
||||
errno = 0;
|
||||
rc = syscall(SYS_getgroups, 8, locked);
|
||||
printf("getgroups-readonly %ld %d\n", rc, errno);
|
||||
int fd = open(argv[1], O_RDONLY);
|
||||
printf("fchown %ld\n", syscall(SYS_fchown, fd, 4321, 4321));
|
||||
printf("getuid %ld\n", syscall(SYS_getuid));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookIdentityTest(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)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
|
||||
(tmp / "root").mkdir()
|
||||
cls.file = tmp / "owned"
|
||||
cls.file.write_text("")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def probe(self):
|
||||
hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root"), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe"), str(self.file)], env=env,
|
||||
capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_the_hook_answers_identity_syscalls_as_root(self):
|
||||
result = self.probe()
|
||||
self.assertEqual("0 0 0 0", result["getresuid"])
|
||||
self.assertEqual("0 0 0 0", result["getresgid"])
|
||||
self.assertEqual("1 0", result["getgroups"])
|
||||
self.assertEqual("-1 14", result["getgroups-readonly"])
|
||||
self.assertEqual("0", result["fchown"])
|
||||
self.assertEqual("0", result["getuid"])
|
||||
|
||||
def test_a_missing_pointer_still_faults(self):
|
||||
result = self.probe()
|
||||
self.assertEqual("-1 14", result["getresuid-null"])
|
||||
self.assertEqual("-1 14", result["getresgid-null"])
|
||||
self.assertEqual("-1 14", result["getresuid-readonly"])
|
||||
self.assertEqual("-1 14", result["getresgid-readonly"])
|
||||
self.assertEqual(os.stat(self.file).st_uid, os.getuid())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,49 @@
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch"
|
||||
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
|
||||
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
|
||||
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
|
||||
|
||||
|
||||
def changed():
|
||||
removed, added = {}, {}
|
||||
for line in PATCH.read_text().splitlines():
|
||||
found = REGISTER.search(line)
|
||||
if found and line[:1] in "+-":
|
||||
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
|
||||
return removed, added
|
||||
|
||||
|
||||
class FexPathSyscallsTest(unittest.TestCase):
|
||||
def test_only_the_passthrough_table_changes(self):
|
||||
self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH])
|
||||
|
||||
def test_each_path_syscall_keeps_its_arity_and_goes_through_libc(self):
|
||||
removed, added = changed()
|
||||
self.assertEqual(sorted(removed), sorted(added))
|
||||
self.assertGreater(len(added), 10)
|
||||
for name, (template, arity, number) in added.items():
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
|
||||
self.assertEqual("SyscallPathPassthrough", template)
|
||||
|
||||
def test_the_new_templates_call_the_libc_syscall(self):
|
||||
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
calls = [line for line in added if "syscall(" in line and "Result" in line]
|
||||
self.assertEqual(5, len(calls))
|
||||
self.assertTrue(all("::syscall(syscall_num" in line for line in calls))
|
||||
self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))])
|
||||
|
||||
def test_every_routed_syscall_is_rewritten_by_the_hook(self):
|
||||
hook = HOOK.read_text()
|
||||
for name, (_, _, number) in changed()[1].items():
|
||||
with self.subTest(name=name):
|
||||
self.assertIn(f"number == __NR_{number})", hook)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,117 @@
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
||||
PATCH = FEX / "patches/0009-signal-handler-escape-frees-host-stack.patch"
|
||||
PROBE = FEX / "probes/signal-handler-escape.c"
|
||||
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
|
||||
CONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
|
||||
THREADS = "Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h"
|
||||
FIELDS = ["PrevGuestFrame", "GuestFrameEnd", "GuestInterruptedSP", "GuestAltBase", "GuestAltEnd"]
|
||||
|
||||
|
||||
def files():
|
||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
|
||||
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
|
||||
|
||||
|
||||
def hunks(section):
|
||||
return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M)
|
||||
|
||||
|
||||
def added(body):
|
||||
return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
|
||||
|
||||
def removed(body):
|
||||
return [line for line in body.splitlines() if line.startswith("-") and not line.startswith("---")]
|
||||
|
||||
|
||||
class SignalHandlerEscapeTest(unittest.TestCase):
|
||||
def test_only_signal_state_files_change(self):
|
||||
self.assertEqual(sorted(files()), sorted([CONTEXT, DELEGATOR, THREADS]))
|
||||
|
||||
def test_nothing_is_removed(self):
|
||||
for name, section in files().items():
|
||||
self.assertEqual(removed(section), [], name)
|
||||
|
||||
def test_added_code_has_no_comments(self):
|
||||
for name, section in files().items():
|
||||
for line in added(section):
|
||||
self.assertFalse("//" in line or "/*" in line, f"{name}: {line}")
|
||||
|
||||
def test_both_context_backups_record_the_guest_frame(self):
|
||||
lines = added(files()[CONTEXT])
|
||||
self.assertEqual(lines, [f"uint64_t {field};" for field in FIELDS] * 2)
|
||||
|
||||
def test_each_thread_keeps_its_frame_chain(self):
|
||||
self.assertEqual([line for line in added(files()[THREADS]) if line], ["uint64_t GuestFrames {};", "uint32_t GuestFrameCount {};"])
|
||||
|
||||
def test_delivery_pushes_and_reclaims_only_left_frames_at_the_dispatch_level(self):
|
||||
found = hunks(files()[DELEGATOR])
|
||||
delivery = "".join(body for function, body in found if "HandleDispatcherGuestSignal" in function)
|
||||
lines = added(delivery)
|
||||
self.assertIn("#ifdef ARCHITECTURE_arm64", lines)
|
||||
gate = " ".join(lines)
|
||||
self.assertIn("WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames", gate)
|
||||
self.assertIn("Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1", gate)
|
||||
self.assertIn("GuestLeftFrame(Newest, OldGuestSP", gate)
|
||||
self.assertIn("ContextBackup->PrevSP = HostTop;", lines)
|
||||
self.assertIn("Frame->SignalHandlerRefCounter -= LeftFrames;", lines)
|
||||
self.assertIn("SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup);", lines)
|
||||
self.assertIn("++SignalInfo.GuestFrameCount;", lines)
|
||||
self.assertLess(lines.index("#endif"), lines.index("ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;"))
|
||||
|
||||
def test_signal_return_pops_its_frame_and_any_newer_ones(self):
|
||||
found = hunks(files()[DELEGATOR])
|
||||
restore = "".join(body for function, body in found if "RestoreThreadState" in function)
|
||||
lines = added(restore)
|
||||
self.assertIn("if (Entry == OldSP) {", lines)
|
||||
self.assertIn("SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;", lines)
|
||||
self.assertIn("Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;", lines)
|
||||
self.assertNotIn("TYPE_PAUSE", " ".join(lines))
|
||||
|
||||
def test_thread_stop_clears_the_chain(self):
|
||||
found = hunks(files()[DELEGATOR])
|
||||
pause = "".join(body for function, body in found if "HandleSignalPause" in function)
|
||||
self.assertEqual(added(pause), ["ThreadObject->SignalInfo.GuestFrames = 0;", "ThreadObject->SignalInfo.GuestFrameCount = 0;"])
|
||||
|
||||
def test_patch_follows_the_syscall_state_patch_on_every_release(self):
|
||||
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
|
||||
self.assertEqual(names[names.index(PATCH.name) - 1], "0008-signal-return-restores-syscall-state.patch")
|
||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
||||
self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text())
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
||||
class SignalHandlerEscapeProbeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
||||
if not compiler:
|
||||
raise unittest.SkipTest("no C compiler")
|
||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-escape-"))
|
||||
cls.binary = cls.tmp / "probe"
|
||||
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def test_native_kernel_survives_every_escape(self):
|
||||
result = subprocess.run([str(self.binary), "20000"], capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
counts = dict(part.split("=") for part in result.stdout.split())
|
||||
for phase in ("onstack", "offstack", "mixed", "returns", "outer"):
|
||||
self.assertEqual(counts[phase], "20000", phase)
|
||||
self.assertEqual(counts["nested"], "60000")
|
||||
self.assertEqual(counts["wrong"], "0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,134 @@
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
||||
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
|
||||
PROBE = FEX / "probes/signal-register-update.c"
|
||||
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
|
||||
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
|
||||
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
|
||||
|
||||
|
||||
def files():
|
||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
|
||||
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
|
||||
|
||||
|
||||
def added(section):
|
||||
return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
|
||||
|
||||
def removed(section):
|
||||
return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")]
|
||||
|
||||
|
||||
def helper():
|
||||
lines = added(files()[FRAMES])
|
||||
start = next(i for i, line in enumerate(lines) if line.startswith("void SignalDelegator::ResumeWithGuestGPRs("))
|
||||
end = lines.index("#endif", start)
|
||||
return lines[start:end + 1]
|
||||
|
||||
|
||||
class SignalRegisterUpdateTest(unittest.TestCase):
|
||||
def test_only_signal_frame_files_change(self):
|
||||
self.assertEqual(sorted(files()), sorted([FRAMES, HEADER]))
|
||||
|
||||
def test_patch_only_adds_code(self):
|
||||
for name, section in files().items():
|
||||
self.assertEqual(removed(section), [], name)
|
||||
|
||||
def test_added_code_has_no_comments(self):
|
||||
for name, section in files().items():
|
||||
for line in added(section):
|
||||
self.assertNotIn("//", line, name)
|
||||
self.assertNotIn("/*", line, name)
|
||||
|
||||
def test_helper_is_declared_once(self):
|
||||
self.assertEqual(sum(line.startswith("void ResumeWithGuestGPRs(") for line in added(files()[HEADER])), 1)
|
||||
|
||||
def test_only_changed_registers_are_written_back(self):
|
||||
body = helper()
|
||||
self.assertIn("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {", body)
|
||||
self.assertEqual(body[body.index("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {") + 1], "continue;")
|
||||
|
||||
def test_spilled_registers_go_to_the_frame_and_live_ones_to_host_registers(self):
|
||||
body = helper()
|
||||
self.assertIn("const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));", body)
|
||||
self.assertIn("Frame->State.gregs[i] = GuestGPRs[i];", body)
|
||||
self.assertIn("ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);", body)
|
||||
self.assertIn("for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {", body)
|
||||
|
||||
def test_signals_outside_jit_code_are_left_alone(self):
|
||||
body = helper()
|
||||
guard = body.index("if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {")
|
||||
self.assertEqual(body[guard + 1], "return;")
|
||||
self.assertEqual(body[2], "#ifdef ARCHITECTURE_arm64")
|
||||
|
||||
def test_every_frame_type_applies_registers_when_rip_is_unchanged(self):
|
||||
lines = added(files()[FRAMES])
|
||||
calls = [line for line in lines if line.startswith("ResumeWithGuestGPRs(")]
|
||||
self.assertEqual(calls, [
|
||||
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);",
|
||||
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);",
|
||||
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);",
|
||||
])
|
||||
branches = [lines[i + 1] for i, line in enumerate(lines[:-1]) if line == "} else {" and lines[i + 1].startswith("uint64_t GuestGPRs[")]
|
||||
self.assertEqual(branches, ["uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];", "uint64_t GuestGPRs[8];", "uint64_t GuestGPRs[8];"])
|
||||
|
||||
def test_registers_are_stored_by_guest_register_index(self):
|
||||
lines = added(files()[FRAMES])
|
||||
x64 = [m.group(1) for line in lines for m in [re.fullmatch(r"COPY_REG\((\w+)\);", line)] if m]
|
||||
self.assertEqual(sorted(x64), sorted(X64_ORDER))
|
||||
self.assertIn("#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];", lines)
|
||||
legacy = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->sc\.(\w+);", "\n".join(lines))
|
||||
self.assertEqual(sorted(legacy), sorted((r, r[1:].lower()) for r in X64_ORDER[:8]))
|
||||
rt = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->uc\.uc_mcontext\.gregs\[FEXCore::x86::FEX_REG_(\w+)\];", "\n".join(lines))
|
||||
self.assertEqual(sorted(rt), sorted((r, r) for r in X64_ORDER[:8]))
|
||||
|
||||
def test_patch_follows_the_thunk_patch_on_every_release(self):
|
||||
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
|
||||
self.assertEqual(names[names.index(PATCH.name) - 1], "0011-thunk-calls-mark-spilled-state.patch")
|
||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
|
||||
class SignalRegisterUpdateProbeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
||||
if not cls.compiler:
|
||||
raise unittest.SkipTest("no C compiler")
|
||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-regs-"))
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def build(self, *flags):
|
||||
binary = self.tmp / ("probe" + "".join(flags))
|
||||
result = subprocess.run([self.compiler, "-O2", *flags, "-o", str(binary), str(PROBE)], capture_output=True, text=True)
|
||||
return binary if result.returncode == 0 else None
|
||||
|
||||
def check(self, binary, *args):
|
||||
result = subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
self.assertIn("seen=1", result.stdout)
|
||||
|
||||
def test_native_kernel_applies_handler_register_changes(self):
|
||||
self.check(self.build())
|
||||
|
||||
def test_native_kernel_applies_handler_register_changes_in_32_bit_frames(self):
|
||||
binary = self.build("-m32")
|
||||
if binary is None:
|
||||
self.skipTest("no 32-bit toolchain")
|
||||
self.check(binary)
|
||||
self.check(binary, "legacy")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,78 @@
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
||||
PATCH = FEX / "patches/0008-signal-return-restores-syscall-state.patch"
|
||||
PROBE = FEX / "probes/async-signal-context.c"
|
||||
RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;"
|
||||
|
||||
|
||||
def hunks():
|
||||
text = PATCH.read_text()
|
||||
files = re.findall(r"^diff --git a/(\S+) ", text, re.M)
|
||||
return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M)
|
||||
|
||||
|
||||
class SignalReturnSyscallStateTest(unittest.TestCase):
|
||||
def test_only_the_signal_delegator_changes(self):
|
||||
files, found = hunks()
|
||||
self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"])
|
||||
self.assertEqual(len(found), 1)
|
||||
|
||||
def test_only_returns_to_jit_code_restore_the_saved_syscall_state(self):
|
||||
_, found = hunks()
|
||||
function, body = found[0]
|
||||
self.assertIn("SignalDelegator::RestoreThreadState", function)
|
||||
lines = body.splitlines()
|
||||
added = [line[1:].strip() for line in lines if line.startswith("+")]
|
||||
removed = [line for line in lines if line.startswith("-")]
|
||||
self.assertEqual(added, [RESTORE])
|
||||
self.assertEqual(removed, [])
|
||||
context = [line[1:].strip() for line in lines]
|
||||
self.assertEqual(context[0], "auto Frame = Thread->CurrentFrame;")
|
||||
in_jit = context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")
|
||||
restore = context.index(RESTORE)
|
||||
self.assertLess(in_jit, restore)
|
||||
self.assertEqual(context[restore + 1], "}")
|
||||
self.assertLess(restore, context.index("RestoreFrame_x64(Thread, Context, Frame, ucontext);"))
|
||||
|
||||
def test_thread_pause_returns_are_untouched(self):
|
||||
_, found = hunks()
|
||||
body = found[0][1]
|
||||
self.assertNotIn("TYPE_PAUSE", "".join(line for line in body.splitlines() if line.startswith("+")))
|
||||
|
||||
def test_patch_is_applied_to_every_release(self):
|
||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
||||
self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text())
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
||||
class AsyncSignalContextProbeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
||||
if not compiler:
|
||||
raise unittest.SkipTest("no C compiler")
|
||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-async-signal-"))
|
||||
cls.binary = cls.tmp / "probe"
|
||||
subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def test_native_kernel_reports_the_interrupted_registers(self):
|
||||
result = subprocess.run([str(self.binary), "500"], capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
counts = dict(part.split("=") for part in result.stdout.split())
|
||||
self.assertGreaterEqual(int(counts["matched"]), 500)
|
||||
self.assertEqual(counts["stale"], "0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,147 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATCH = REPO / "tools/fex/patches/0018-socket-credentials-through-libc.patch"
|
||||
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
|
||||
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
|
||||
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
|
||||
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL_X64\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
|
||||
ROUTED = {"sendmsg", "recvmsg", "getsockopt"}
|
||||
|
||||
|
||||
def changed():
|
||||
removed, added = {}, {}
|
||||
for line in PATCH.read_text().splitlines():
|
||||
found = REGISTER.search(line)
|
||||
if found and line[:1] in "+-":
|
||||
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
|
||||
return removed, added
|
||||
|
||||
|
||||
class FexSocketCredentialsTest(unittest.TestCase):
|
||||
def test_only_the_passthrough_table_changes(self):
|
||||
self.assertEqual([PASSTHROUGH], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
|
||||
|
||||
def test_each_socket_call_keeps_its_arity_and_goes_through_libc(self):
|
||||
removed, added = changed()
|
||||
self.assertEqual(ROUTED, set(removed))
|
||||
self.assertEqual(ROUTED, set(added))
|
||||
for name, (template, arity, number) in added.items():
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(name, number)
|
||||
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
|
||||
self.assertEqual("SyscallPathPassthrough", template)
|
||||
|
||||
def test_every_routed_call_is_answered_by_the_hook(self):
|
||||
hook = HOOK.read_text()
|
||||
for number in ROUTED:
|
||||
with self.subTest(number=number):
|
||||
self.assertIn(f"number == __NR_{number})", hook)
|
||||
|
||||
|
||||
PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(void) {
|
||||
int sv[2], on = 1;
|
||||
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 2;
|
||||
setsockopt(sv[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
|
||||
struct ucred sent = {getpid(), (uid_t)syscall(SYS_getuid), (gid_t)syscall(SYS_getgid)};
|
||||
char byte = 0, ctrl[CMSG_SPACE(sizeof(struct ucred))];
|
||||
struct iovec iov = {&byte, 1};
|
||||
struct msghdr msg = {0};
|
||||
msg.msg_iov = &iov;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = ctrl;
|
||||
msg.msg_controllen = sizeof(ctrl);
|
||||
struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
|
||||
c->cmsg_level = SOL_SOCKET;
|
||||
c->cmsg_type = SCM_CREDENTIALS;
|
||||
c->cmsg_len = CMSG_LEN(sizeof(sent));
|
||||
memcpy(CMSG_DATA(c), &sent, sizeof(sent));
|
||||
errno = 0;
|
||||
long rc = syscall(SYS_sendmsg, sv[0], &msg, 0);
|
||||
printf("sendmsg %ld %d %u\n", rc, errno, sent.uid);
|
||||
char in_ctrl[CMSG_SPACE(sizeof(struct ucred))];
|
||||
struct msghdr in = {0};
|
||||
in.msg_iov = &iov;
|
||||
in.msg_iovlen = 1;
|
||||
in.msg_control = in_ctrl;
|
||||
in.msg_controllen = sizeof(in_ctrl);
|
||||
rc = syscall(SYS_recvmsg, sv[1], &in, MSG_DONTWAIT);
|
||||
struct ucred got = {0, 99, 99};
|
||||
for (c = CMSG_FIRSTHDR(&in); c; c = CMSG_NXTHDR(&in, c))
|
||||
if (c->cmsg_type == SCM_CREDENTIALS) memcpy(&got, CMSG_DATA(c), sizeof(got));
|
||||
printf("recvmsg %ld %u\n", rc, got.uid);
|
||||
struct ucred peer = {0, 99, 99};
|
||||
socklen_t len = sizeof(peer);
|
||||
rc = syscall(SYS_getsockopt, sv[1], SOL_SOCKET, SO_PEERCRED, &peer, &len);
|
||||
printf("peercred %ld %u\n", rc, peer.uid);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookSocketCredentialsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if os.getuid() == 0:
|
||||
raise unittest.SkipTest("root may send any credentials")
|
||||
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)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
|
||||
(tmp / "root").mkdir()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def probe(self, hooked):
|
||||
hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root")}
|
||||
if hooked:
|
||||
hook_env["LD_PRELOAD"] = str(self.hook)
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe")], env=env, capture_output=True, text=True,
|
||||
timeout=120)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_root_credentials_sent_through_the_raw_call_reach_the_peer_as_root(self):
|
||||
result = self.probe(hooked=True)
|
||||
self.assertEqual("1 0 0", result["sendmsg"])
|
||||
self.assertEqual("1 0", result["recvmsg"])
|
||||
self.assertEqual("0 0", result["peercred"])
|
||||
|
||||
def test_without_the_hook_the_kernel_keeps_the_real_ids(self):
|
||||
result = self.probe(hooked=False)
|
||||
self.assertEqual(f"1 0 {os.getuid()}", result["sendmsg"])
|
||||
self.assertEqual(f"1 {os.getuid()}", result["recvmsg"])
|
||||
self.assertEqual(f"0 {os.getuid()}", result["peercred"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,67 @@
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
||||
PATCH = FEX / "patches/0010-syscall-exit-resets-host-stack.patch"
|
||||
PROBE = FEX / "probes/syscall-host-stack.c"
|
||||
BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp"
|
||||
|
||||
|
||||
def hunks():
|
||||
text = PATCH.read_text()
|
||||
files = re.findall(r"^diff --git a/(\S+) ", text, re.M)
|
||||
return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M)
|
||||
|
||||
|
||||
class SyscallHostStackTest(unittest.TestCase):
|
||||
def test_only_the_branch_ops_change(self):
|
||||
files, found = hunks()
|
||||
self.assertEqual(files, [BRANCH_OPS])
|
||||
self.assertEqual(len(found), 2)
|
||||
|
||||
def test_both_ops_that_leave_the_block_reset_the_stack_after_spilling(self):
|
||||
_, found = hunks()
|
||||
for (function, body), op in zip(found, ("DEF_OP(Syscall)", "DEF_OP(ThreadRemoveCodeEntry)")):
|
||||
lines = body.splitlines()
|
||||
added = [line[1:].strip() for line in lines if line.startswith("+")]
|
||||
self.assertEqual([line for line in added if line], ["ResetStack();"], op)
|
||||
self.assertEqual([line for line in lines if line.startswith("-")], [], op)
|
||||
context = [line[1:].strip() for line in lines]
|
||||
self.assertIn(op, function + " " + " ".join(context))
|
||||
self.assertLess(context.index("SpillStaticRegs(TMP1);"), context.index("ResetStack();"), op)
|
||||
|
||||
def test_patch_is_skipped_once_upstream_ships_it(self):
|
||||
self.assertEqual(PATCH.read_text().splitlines()[0], "Fixed-upstream: FEX-2612")
|
||||
self.assertIn("Fixed-upstream: FEX-", (FEX / "build-in-arch.sh").read_text())
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
||||
class SyscallHostStackProbeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
||||
if not compiler:
|
||||
raise unittest.SkipTest("no C compiler")
|
||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-syscall-stack-"))
|
||||
cls.binary = cls.tmp / "probe"
|
||||
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def test_native_kernel_runs_every_syscall(self):
|
||||
result = subprocess.run([str(self.binary), "200000"], capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
counts = dict(part.split("=") for part in result.stdout.split())
|
||||
self.assertIn(counts["mode"], ("avx", "mmx"))
|
||||
self.assertEqual(counts["syscalls"], "200000")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,124 @@
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
FEX = Path(__file__).resolve().parents[1] / "fex"
|
||||
PATCH = FEX / "patches/0011-thunk-calls-mark-spilled-state.patch"
|
||||
PROBE = FEX / "probes/vdso-signal-state.c"
|
||||
CORE = "FEXCore/Source/Interface/Core/Core.cpp"
|
||||
BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp"
|
||||
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
|
||||
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
|
||||
MARK = "str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));"
|
||||
CLEAR = "str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));"
|
||||
RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;"
|
||||
|
||||
|
||||
def files():
|
||||
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
|
||||
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
|
||||
|
||||
|
||||
def hunks(section):
|
||||
return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M)
|
||||
|
||||
|
||||
def added(body):
|
||||
return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
|
||||
|
||||
def removed(body):
|
||||
return [line[1:].strip() for line in body.splitlines() if line.startswith("-") and not line.startswith("---")]
|
||||
|
||||
|
||||
def context(body):
|
||||
return [line[1:].strip() for line in body.splitlines() if line[:1] in (" ", "+")]
|
||||
|
||||
|
||||
class ThunkSignalStateTest(unittest.TestCase):
|
||||
def test_only_signal_state_files_change(self):
|
||||
self.assertEqual(sorted(files()), sorted([BRANCH_OPS, CORE, DELEGATOR, FRAMES]))
|
||||
|
||||
def test_added_code_has_no_new_comments(self):
|
||||
for name, section in files().items():
|
||||
moved = set(removed(section))
|
||||
for line in added(section):
|
||||
if "//" in line or "/*" in line:
|
||||
self.assertIn(line, moved, f"{name}: {line}")
|
||||
|
||||
def test_thunk_call_marks_all_state_spilled_until_the_refill(self):
|
||||
section = files()[BRANCH_OPS]
|
||||
lines = context(section)
|
||||
self.assertEqual([line for line in added(section) if line], ["LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);", MARK, CLEAR])
|
||||
self.assertEqual(removed(section), [])
|
||||
self.assertLess(lines.index("PushDynamicRegs(TMP1);"), lines.index(MARK))
|
||||
self.assertLess(lines.index(MARK), lines.index("InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);"))
|
||||
refill = lines.index("FillStaticRegs({")
|
||||
self.assertEqual(lines[refill + 1:refill + 3], [".NZCV = false,", "});"])
|
||||
self.assertLess(refill, lines.index(CLEAR))
|
||||
|
||||
def test_fully_spilled_state_is_never_respilled_from_host_registers(self):
|
||||
found = hunks(files()[DELEGATOR])
|
||||
spill = "".join(body for function, body in found if "SpillSRA" in function or "IgnoreMask" in body)
|
||||
lines = context(spill)
|
||||
guard = lines.index("if ((IgnoreMask & 0xFFFF) == 0xFFFF) {")
|
||||
self.assertIn("RestoreRIPFromHostPC", lines[guard - 2])
|
||||
self.assertEqual(lines[guard + 1], "return;")
|
||||
self.assertIn("for (size_t i = 0; i < Config.SRAGPRCount; i++) {", lines[guard + 2:guard + 5])
|
||||
|
||||
def test_every_guest_signal_saves_and_clears_the_mark(self):
|
||||
section = files()[DELEGATOR]
|
||||
lines = added(section)
|
||||
self.assertIn("ContextBackup->InSyscallInfo = Frame->InSyscallInfo;", lines)
|
||||
self.assertIn("Frame->InSyscallInfo = 0;", lines)
|
||||
self.assertIn(RESTORE, lines)
|
||||
self.assertIn("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {", removed(section))
|
||||
self.assertNotIn("TYPE_PAUSE", " ".join(lines))
|
||||
|
||||
def test_redirected_returns_restart_with_no_mark(self):
|
||||
section = files()[FRAMES]
|
||||
self.assertEqual(added(section), ["Frame->InSyscallInfo = 0;"] * 3)
|
||||
self.assertEqual(removed(section), [RESTORE] * 3)
|
||||
|
||||
def test_guest_callbacks_run_with_no_mark(self):
|
||||
lines = added(files()[CORE])
|
||||
self.assertEqual(lines[1:3], ["const auto InSyscallInfo = Frame->InSyscallInfo;", "Frame->InSyscallInfo = 0;"])
|
||||
self.assertEqual(lines[-1], "Frame->InSyscallInfo = InSyscallInfo;")
|
||||
self.assertIn("ExecuteJITCallback(Frame, RIP);", lines[-2])
|
||||
|
||||
def test_patch_follows_the_host_stack_patch_on_every_release(self):
|
||||
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
|
||||
self.assertEqual(names[names.index(PATCH.name) - 1], "0010-syscall-exit-resets-host-stack.patch")
|
||||
self.assertNotIn("Fixed-upstream", PATCH.read_text())
|
||||
|
||||
|
||||
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
|
||||
class VdsoSignalStateProbeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
||||
if not compiler:
|
||||
raise unittest.SkipTest("no C compiler")
|
||||
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-vdso-signal-"))
|
||||
cls.binary = cls.tmp / "probe"
|
||||
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def test_native_kernel_keeps_registers_across_interrupted_clock_calls(self):
|
||||
result = subprocess.run([str(self.binary), "1"], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
counts = dict(part.split("=") for part in result.stdout.split())
|
||||
self.assertGreater(int(counts["calls"]), 0)
|
||||
self.assertGreater(int(counts["alarms"]), 0)
|
||||
self.assertEqual(counts["bad"], "0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1977,6 +1977,18 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "1771300", env), {"VKD3D_FEATURE_LEVEL": "12_1", "VKD3D_SHADER_MODEL": "6_9"})
|
||||
self.assertEqual(MODULE["engine_fixes"](str(exe), [], "42")[0], {})
|
||||
|
||||
def test_hades_ii_runs_at_feature_level_12_2_from_steam_and_xbox_unless_the_game_overrides_it(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for exe in (Path(tmp) / "Hades II/Ship/Hades2.exe", Path(tmp) / "Xbox/Hades II/Hades2.exe"):
|
||||
exe.parent.mkdir(parents=True)
|
||||
exe.touch()
|
||||
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
|
||||
self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2"}, str(exe))
|
||||
self.assertTrue(notes)
|
||||
config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"})
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Hades/x64/Hades.exe", [])[0], {})
|
||||
|
||||
def test_unity_players_keep_tso_over_the_preset(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
def game(*names):
|
||||
|
||||
@@ -43,15 +43,11 @@ class HdrLiveSwitchTest(unittest.TestCase):
|
||||
def test_the_gate_follows_the_display_not_the_setting(self):
|
||||
text = (APP / "SessionActivity.kt").read_text()
|
||||
start = text.index("val attached = CompositorHost.isStarted")
|
||||
block = text[start:text.index("CompositorHost.start(", start)]
|
||||
block = text[start:text.index("DriverSetupLog.write", start)]
|
||||
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
|
||||
self.assertNotIn("SessionPrefs.hdr", block)
|
||||
self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")])
|
||||
self.assertIn("capable, false", request)
|
||||
self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block)
|
||||
host = (APP / "wayland/CompositorHost.kt").read_text()
|
||||
gate = host[host.index("fun applyHdr("):]
|
||||
gate = gate[:gate.index("\n }")]
|
||||
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate)
|
||||
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block)
|
||||
|
||||
def test_both_switches_apply_to_the_running_session(self):
|
||||
helper = (APP / "session/SessionHdr.kt").read_text()
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
RECORDER = r"""
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int execve(const char *path, char *const argv[], char *const envp[]) {
|
||||
const char *exe = "-";
|
||||
for (int i = 0; envp && envp[i]; i++)
|
||||
if (strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) exe = envp[i] + 16;
|
||||
printf("exe\t%s\n", exe);
|
||||
fflush(stdout);
|
||||
_exit(0);
|
||||
}
|
||||
"""
|
||||
|
||||
PROBE = r"""
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) return 0;
|
||||
char *args[] = {argv[1], NULL};
|
||||
execv(argv[1], args);
|
||||
perror("execv");
|
||||
return 1;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookExecTargetTest(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)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "recorder.c").write_text(RECORDER)
|
||||
cls.recorder = tmp / "recorder.so"
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
opt = cls.root / "opt"
|
||||
(opt / "real").mkdir(parents=True)
|
||||
(opt / "nest").mkdir()
|
||||
(cls.root / "lib").mkdir()
|
||||
(cls.root / "lib/ld-linux-aarch64.so.1").write_bytes(b"")
|
||||
shutil.copy(cls.probe, opt / "real/prog")
|
||||
shutil.copy(cls.probe, opt / "real/.l2s.prog0001")
|
||||
os.symlink("./real", opt / "rel")
|
||||
os.symlink("/opt/real", opt / "abs")
|
||||
os.symlink("../rel", opt / "nest/sub")
|
||||
os.symlink("rel/prog", opt / "link")
|
||||
os.symlink(".l2s.prog0001", opt / "real/hard")
|
||||
cls.real = str(opt / "real/prog")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def exe(self, program):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe), program], env=env, capture_output=True, text=True, timeout=120)
|
||||
for line in out.stdout.splitlines():
|
||||
if line.startswith("exe\t"):
|
||||
return line.split("\t", 1)[1]
|
||||
self.fail(out.stdout + out.stderr)
|
||||
|
||||
def test_a_program_reached_through_a_relative_directory_link_is_named_by_its_real_path(self):
|
||||
self.assertEqual(self.real, self.exe("/opt/rel/prog"))
|
||||
|
||||
def test_a_program_reached_through_a_guest_absolute_directory_link_is_named_by_its_real_path(self):
|
||||
self.assertEqual(self.real, self.exe("/opt/abs/prog"))
|
||||
|
||||
def test_links_that_climb_with_dot_dot_resolve_like_the_kernel(self):
|
||||
self.assertEqual(self.real, self.exe("/opt/nest/sub/./prog"))
|
||||
|
||||
def test_a_link_to_the_program_itself_still_resolves(self):
|
||||
self.assertEqual(self.real, self.exe("/opt/link"))
|
||||
|
||||
def test_a_plain_path_is_unchanged(self):
|
||||
self.assertEqual(self.real, self.exe("/opt/real/prog"))
|
||||
|
||||
def test_a_missing_directory_is_not_skipped_by_dot_dot(self):
|
||||
self.assertNotEqual(self.real, self.exe("/opt/missing/../real/prog"))
|
||||
|
||||
def test_a_file_is_not_used_as_a_directory(self):
|
||||
self.assertNotEqual(self.real, self.exe("/opt/real/prog/../prog"))
|
||||
|
||||
def test_a_proot_hard_link_keeps_its_own_name(self):
|
||||
self.assertEqual(str(self.root / "opt/real/hard"), self.exe("/opt/real/hard"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,140 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
RECORDER = r"""
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
int execve(const char *path, char *const argv[], char *const envp[]) {
|
||||
if (access(path, F_OK) != 0) { errno = ENOENT; return -1; }
|
||||
if (access(path, X_OK) != 0) { errno = EACCES; return -1; }
|
||||
char head[2] = {0};
|
||||
int fd = open(path, O_RDONLY);
|
||||
if (fd >= 0) { if (read(fd, head, 2) < 0) head[0] = 0; close(fd); }
|
||||
if (memcmp(head, "#!", 2) != 0 && memcmp(head, "\177E", 2) != 0) {
|
||||
errno = ENOEXEC;
|
||||
return -1;
|
||||
}
|
||||
printf("call");
|
||||
for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]);
|
||||
printf("\n");
|
||||
fflush(stdout);
|
||||
_exit(0);
|
||||
}
|
||||
"""
|
||||
|
||||
PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int ret;
|
||||
if (strcmp(argv[1], "vpe") == 0) {
|
||||
char path[4096];
|
||||
snprintf(path, sizeof(path), "PATH=%s", argv[2]);
|
||||
char *envp[] = {path, NULL};
|
||||
ret = execvpe(argv[3], argv + 3, envp);
|
||||
} else {
|
||||
ret = execvp(argv[2], argv + 2);
|
||||
}
|
||||
printf("ret\t%d\t%s\n", ret, strerror(errno));
|
||||
return 1;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookExecvpTest(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(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "recorder.c").write_text(RECORDER)
|
||||
cls.recorder = tmp / "recorder.so"
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
cls.dirs = Path("/opt/probe")
|
||||
for name in ("bin", "opt/probe/locked", "opt/probe/open", "opt/probe/work"):
|
||||
(cls.root / name).mkdir(parents=True)
|
||||
(tmp / "sh.c").write_text("int main(void) { return 0; }\n")
|
||||
subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True)
|
||||
cls.script("locked/tool", 0o644)
|
||||
cls.script("open/tool", 0o755, "#!/bin/sh\n")
|
||||
cls.script("open/plain", 0o755)
|
||||
cls.script("work/here", 0o755)
|
||||
|
||||
@classmethod
|
||||
def script(cls, name, mode, text="echo plain\n"):
|
||||
path = cls.root / "opt/probe" / name
|
||||
path.write_text(text)
|
||||
path.chmod(mode)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def call(self, *argv, cwd=None):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe), *argv], env=env, cwd=cwd, capture_output=True, text=True,
|
||||
timeout=120)
|
||||
for line in out.stdout.splitlines():
|
||||
if line.startswith("call\t"):
|
||||
return line.split("\t")[1:]
|
||||
if line.startswith("ret\t"):
|
||||
return line.split("\t")[1:]
|
||||
self.fail(out.stdout + out.stderr)
|
||||
|
||||
def test_a_script_without_a_shebang_runs_through_sh(self):
|
||||
plain = str(self.dirs / "open/plain")
|
||||
self.assertEqual(["/bin/sh", plain, "a"], self.call("vp", plain, "a"))
|
||||
|
||||
def test_path_search_runs_a_script_without_a_shebang_through_sh(self):
|
||||
plain = str(self.dirs / "open/plain")
|
||||
self.assertEqual(["/bin/sh", plain, "a"], self.call("vpe", str(self.dirs / "open"), "plain", "a"))
|
||||
|
||||
def test_a_denied_entry_earlier_in_path_is_skipped(self):
|
||||
path = f"{self.dirs / 'locked'}:{self.dirs / 'open'}"
|
||||
call = self.call("vpe", path, "tool", "x")
|
||||
self.assertTrue(call[-2].endswith("/opt/probe/open/tool"), call)
|
||||
self.assertEqual("x", call[-1])
|
||||
|
||||
def test_only_denied_entries_report_permission_denied(self):
|
||||
self.assertEqual(["-1", os.strerror(13)], self.call("vpe", str(self.dirs / "locked"), "tool"))
|
||||
|
||||
def test_an_empty_path_entry_means_the_current_directory(self):
|
||||
here = self.call("vpe", f"{self.dirs / 'open'}:", "here", cwd=self.root / "opt/probe/work")
|
||||
self.assertEqual(["/bin/sh", "here"], here)
|
||||
|
||||
def test_a_bare_name_is_not_run_from_the_current_directory_without_an_empty_entry(self):
|
||||
missing = self.call("vpe", str(self.dirs / "open"), "here", cwd=self.root / "opt/probe/work")
|
||||
self.assertEqual(["-1", os.strerror(2)], missing)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,147 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
MAIN = r"""
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"probe/quiet"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func main() {
|
||||
_, _, errno := syscall.RawSyscall(syscall.SYS_SETREUID, ^uintptr(0), 0, 0)
|
||||
euid, _ := quiet.Call(syscall.SYS_GETEUID, 0, 0, 0)
|
||||
fmt.Println(syscall.Getuid(), syscall.Getgid(), int(euid), errno == 0)
|
||||
}
|
||||
"""
|
||||
|
||||
QUIET = """#include "textflag.h"
|
||||
|
||||
TEXT ·Call(SB),NOSPLIT,$0-48
|
||||
\tMOVD\ta1+8(FP), R0
|
||||
\tMOVD\ta2+16(FP), R1
|
||||
\tMOVD\ta3+24(FP), R2
|
||||
\tMOVD\t$0, R3
|
||||
\tMOVD\t$0, R4
|
||||
\tMOVD\t$0, R5
|
||||
\tMOVD\ttrap+0(FP), R8
|
||||
\tSVC
|
||||
\tMOVD\tR0, r1+32(FP)
|
||||
\tMOVD\tR1, r2+40(FP)
|
||||
\tRET
|
||||
"""
|
||||
|
||||
QUIET_GO = """package quiet
|
||||
|
||||
func Call(trap, a1, a2, a3 uintptr) (r1, r2 uintptr)
|
||||
"""
|
||||
|
||||
CGO = """package main
|
||||
|
||||
import "C"
|
||||
"""
|
||||
|
||||
LAUNCHER = r"""
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
execv(argv[1], argv + 1);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookGoIdentityTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
if not shutil.which("go"):
|
||||
raise unittest.SkipTest("no Go toolchain")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "launcher.c").write_text(LAUNCHER)
|
||||
cls.launcher = tmp / "launcher"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.launcher), str(tmp / "launcher.c")], check=True)
|
||||
src = tmp / "src"
|
||||
src.mkdir()
|
||||
(src / "go.mod").write_text("module probe\n\ngo 1.19\n")
|
||||
(src / "main.go").write_text(MAIN)
|
||||
(src / "quiet").mkdir()
|
||||
(src / "quiet/quiet.go").write_text(QUIET_GO)
|
||||
(src / "quiet/quiet_arm64.s").write_text(QUIET)
|
||||
(src / "cgo.go").write_text(CGO)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "usr/bin").mkdir(parents=True)
|
||||
cls.go_env = {**os.environ, "GOOS": "linux", "GOARCH": "arm64", "GOCACHE": str(tmp / "gocache"),
|
||||
"GOPATH": str(tmp / "gopath"), "GOFLAGS": "-buildvcs=false", "GOTOOLCHAIN": "local"}
|
||||
cls.static = cls.root / "usr/bin/go-static"
|
||||
subprocess.run(["go", "build", "-o", str(cls.static), "."], cwd=src, check=True, capture_output=True,
|
||||
env={**cls.go_env, "CGO_ENABLED": "0"})
|
||||
cls.dynamic = cls.root / "usr/bin/go-dynamic"
|
||||
built = subprocess.run(["go", "build", "-o", str(cls.dynamic), "."], cwd=src, capture_output=True,
|
||||
env={**cls.go_env, "CGO_ENABLED": "1", "CC": cls.cc})
|
||||
if built.returncode != 0:
|
||||
cls.dynamic = None
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def prepare(self, program):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
subprocess.run(cmd + [str(self.launcher), str(program)], env=env, capture_output=True, timeout=120)
|
||||
return b"CXGOSYS1" in program.read_bytes()
|
||||
|
||||
def run_go(self, program):
|
||||
cmd = list(self.prefix) + [str(program)]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return result.stdout.split()
|
||||
|
||||
def check_identity(self, program):
|
||||
before = self.run_go(program)
|
||||
if os.getuid() != 0:
|
||||
self.assertNotEqual(before[0], "0")
|
||||
self.assertEqual(before[3], "false")
|
||||
self.assertTrue(self.prepare(program))
|
||||
self.assertEqual(self.run_go(program), ["0", "0", "0", "true"])
|
||||
moved = self.root.with_name("root-away")
|
||||
self.root.rename(moved)
|
||||
try:
|
||||
away = self.run_go(moved / program.relative_to(self.root))
|
||||
finally:
|
||||
moved.rename(self.root)
|
||||
if os.getuid() != 0:
|
||||
self.assertEqual(away, before)
|
||||
|
||||
def test_static_go_program_sees_the_session_identity(self):
|
||||
self.check_identity(self.static)
|
||||
|
||||
def test_dynamic_go_program_sees_the_session_identity(self):
|
||||
if self.dynamic is None:
|
||||
self.skipTest("no cgo cross build")
|
||||
self.check_identity(self.dynamic)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,232 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1"
|
||||
GUEST_TOOL = "/usr/local/bin/tool"
|
||||
BOUND_DIR = "/opt/runtime"
|
||||
ANDROID_DIR = "/opt/android"
|
||||
HOST_SHELL = "/data/local/tmp/droiddeck-hook-probe-sh"
|
||||
|
||||
RECORDER = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <spawn.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(const char *path, char *const argv[], char *const envp[]) {
|
||||
printf("call\t%s", path);
|
||||
for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]);
|
||||
printf("\n");
|
||||
for (int i = 0; envp && envp[i]; i++)
|
||||
if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20);
|
||||
else if (strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) printf("envpath\t%s\n", envp[i] + 16);
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,
|
||||
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
|
||||
show(path, argv, envp);
|
||||
if (pid) *pid = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int execve(const char *path, char *const argv[], char *const envp[]) {
|
||||
show(path, argv, envp);
|
||||
_exit(0);
|
||||
}
|
||||
"""
|
||||
|
||||
PROBE = r"""
|
||||
#include <spawn.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 3) return 2;
|
||||
if (strcmp(argv[1], "spawn") == 0) {
|
||||
pid_t pid;
|
||||
posix_spawn_file_actions_t actions;
|
||||
posix_spawn_file_actions_init(&actions);
|
||||
posix_spawn_file_actions_adddup2(&actions, 1, 1);
|
||||
int ret = posix_spawn(&pid, argv[2], &actions, NULL, argv + 2, environ);
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
printf("ret\t%d\n", ret);
|
||||
return 0;
|
||||
}
|
||||
execve(argv[2], argv + 2, environ);
|
||||
printf("ret\t-1\n");
|
||||
return 1;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def guest_loader(prefix):
|
||||
roots = [Path(prefix[prefix.index("-L") + 1])] if prefix and "-L" in prefix else [Path("/")]
|
||||
for root in roots:
|
||||
for name in ("lib/ld-linux-aarch64.so.1", "lib64/ld-linux-aarch64.so.1", "usr/lib/ld-linux-aarch64.so.1"):
|
||||
if (root / name).exists():
|
||||
return root / name
|
||||
return None
|
||||
|
||||
|
||||
class NativeHookLdsoSpawnTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
loader = guest_loader(cls.prefix)
|
||||
if loader is None:
|
||||
raise unittest.SkipTest("no aarch64 glibc loader to put in the rootfs")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "recorder.c").write_text(RECORDER)
|
||||
cls.recorder = tmp / "recorder.so"
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
for guest, source in ((GUEST_LDSO, loader), (GUEST_TOOL, cls.probe)):
|
||||
host = cls.root / guest.lstrip("/")
|
||||
host.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy(source, host)
|
||||
host.chmod(0o755)
|
||||
(cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True)
|
||||
cls.runtime = tmp / "runtime"
|
||||
cls.runtime.mkdir()
|
||||
shutil.copy(cls.probe, cls.runtime / "bash")
|
||||
(cls.runtime / "bash").chmod(0o755)
|
||||
cls.android = tmp / "root-android"
|
||||
cls.android.mkdir()
|
||||
subprocess.run([cls.cc, "-O1", "-Wl,--dynamic-linker=/system/bin/linker64", "-o", str(cls.android / "sh"),
|
||||
str(tmp / "probe.c")], check=True)
|
||||
for name, interpreter in (("bound.sh", f"{BOUND_DIR}/bash"), ("host.sh", HOST_SHELL),
|
||||
("android.sh", f"{ANDROID_DIR}/sh")):
|
||||
script = cls.root / "opt" / name
|
||||
script.parent.mkdir(exist_ok=True)
|
||||
script.write_text(f"#!{interpreter}\n")
|
||||
script.chmod(0o755)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def call(self, how, *argv, binds=None, real_exe=None, ld_library_path=None):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
|
||||
if binds:
|
||||
hook_env["DDNATV_BINDS"] = binds
|
||||
if real_exe:
|
||||
hook_env["DDNATV_REAL_EXE"] = real_exe
|
||||
if ld_library_path is not None:
|
||||
hook_env["LD_LIBRARY_PATH"] = ld_library_path
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120)
|
||||
calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")]
|
||||
self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")]
|
||||
self.env_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("envpath\t")]
|
||||
self.assertEqual(1, len(calls), out.stdout + out.stderr)
|
||||
if how == "spawn":
|
||||
self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr)
|
||||
return calls[0]
|
||||
|
||||
def test_spawned_ldso_list_loads_the_program_from_the_rootfs(self):
|
||||
call = self.call("spawn", GUEST_LDSO, "--list", GUEST_TOOL)
|
||||
argv = call[1:]
|
||||
self.assertEqual(str(self.root / GUEST_TOOL.lstrip("/")), argv[-1])
|
||||
self.assertEqual("--list", argv[-2])
|
||||
self.assertIn("--library-path", argv[:-2])
|
||||
|
||||
def test_spawn_and_exec_start_ldso_with_the_same_arguments(self):
|
||||
for args in (("--list", GUEST_TOOL), (GUEST_TOOL, "x"), ("--library-path", "/opt/own", "--list", GUEST_TOOL)):
|
||||
with self.subTest(args=args):
|
||||
self.assertEqual(self.call("exec", GUEST_LDSO, *args), self.call("spawn", GUEST_LDSO, *args))
|
||||
|
||||
def test_a_callers_own_library_path_is_kept(self):
|
||||
call = self.call("spawn", GUEST_LDSO, "--library-path", "/opt/own", "--list", GUEST_TOOL)
|
||||
self.assertEqual([GUEST_LDSO, "--library-path", "/opt/own", "--list", str(self.root / GUEST_TOOL.lstrip("/"))], call[1:])
|
||||
|
||||
def test_ldso_without_a_program_is_spawned_unchanged(self):
|
||||
call = self.call("spawn", GUEST_LDSO, "--version")
|
||||
self.assertEqual([GUEST_LDSO, "--version"], call[1:])
|
||||
|
||||
def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self):
|
||||
self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x"))
|
||||
|
||||
def test_guest_library_environment_is_preserved(self):
|
||||
for how in ("exec", "spawn"):
|
||||
for value in (None, "", "/custom/lib:/other/lib"):
|
||||
with self.subTest(how=how, value=value):
|
||||
argv = self.call(how, GUEST_TOOL, ld_library_path=value)[1:]
|
||||
self.assertEqual([] if value is None else [value], self.env_paths)
|
||||
self.assertIn(str(self.root / "usr/lib/aarch64-linux-gnu"), argv[argv.index("--library-path") + 1])
|
||||
|
||||
def test_a_program_started_through_ldso_records_its_library_path(self):
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
argv = self.call(how, GUEST_TOOL, "x")[1:]
|
||||
self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths)
|
||||
|
||||
def test_ldso_started_by_name_records_no_library_path(self):
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
self.call(how, GUEST_LDSO, "--list", GUEST_TOOL)
|
||||
self.assertEqual([], self.library_paths)
|
||||
|
||||
def test_a_program_from_a_bind_starts_itself_again_through_proc_self_exe(self):
|
||||
bash = str(self.runtime / "bash")
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/proc/self/exe", "x", binds=f"/proc:/proc|{self.runtime}:{BOUND_DIR}", real_exe=bash)
|
||||
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
|
||||
self.assertEqual([bash, "x"], call[-2:])
|
||||
|
||||
def test_a_rootfs_program_starts_itself_again_through_proc_self_exe(self):
|
||||
tool = str(self.root / GUEST_TOOL.lstrip("/"))
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/proc/self/exe", "x", binds="/proc:/proc", real_exe=tool)
|
||||
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
|
||||
self.assertEqual([tool, "x"], call[-2:])
|
||||
|
||||
def test_a_script_interpreter_from_a_bind_runs_as_a_guest_program(self):
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/opt/bound.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
|
||||
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
|
||||
self.assertEqual([str(self.runtime / "bash"), str(self.root / "opt/bound.sh"), "x"], call[-3:])
|
||||
|
||||
def test_a_script_interpreter_outside_the_rootfs_and_its_binds_stays_on_the_host(self):
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
|
||||
self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call)
|
||||
|
||||
def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self):
|
||||
sh = str(self.android / "sh")
|
||||
for how in ("exec", "spawn"):
|
||||
with self.subTest(how=how):
|
||||
call = self.call(how, "/opt/android.sh", "x", binds=f"{self.android}:{ANDROID_DIR}")
|
||||
self.assertEqual([sh, sh, str(self.root / "opt/android.sh"), "x"], call)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -12,14 +12,54 @@ PROBE = r"""
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char cwd[4096];
|
||||
for (int i = 1; i < argc; i++) {
|
||||
struct stat st;
|
||||
if (strncmp(argv[i], "env:", 4) == 0) {
|
||||
const char *value = getenv(argv[i] + 4);
|
||||
printf("%s\t%s\n", argv[i], value ? value : "-");
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "parent:", 7) == 0) {
|
||||
char dir[4096];
|
||||
snprintf(dir, sizeof(dir), "%s", argv[i] + 7);
|
||||
char *rel = strchr(dir, '|'), *want = NULL;
|
||||
if (rel) *rel++ = 0;
|
||||
if (rel && (want = strchr(rel, '|'))) *want++ = 0;
|
||||
int fd = open(dir, O_RDONLY | O_DIRECTORY);
|
||||
struct stat expected;
|
||||
int ok = fd >= 0 && fstatat(fd, rel ? rel : "..", &st, 0) == 0 && stat(want ? want : "/", &expected) == 0;
|
||||
printf("%s\t%d\n", argv[i], ok && st.st_dev == expected.st_dev && st.st_ino == expected.st_ino);
|
||||
if (fd >= 0) close(fd);
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "fork:", 5) == 0) {
|
||||
fflush(stdout);
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
int p[2];
|
||||
char path[64], data[8] = "-";
|
||||
if (pipe(p) == 0 && write(p[1], "x", 1) == 1 && dup2(p[0], 63) == 63) {
|
||||
snprintf(path, sizeof(path), "%s/63", argv[i] + 5);
|
||||
int fd = open(path, O_RDONLY);
|
||||
ssize_t n = fd >= 0 ? read(fd, data, sizeof(data) - 1) : -1;
|
||||
if (n > 0) data[n] = 0;
|
||||
if (fd >= 0) close(fd);
|
||||
}
|
||||
printf("%s\t%s\n", argv[i], data);
|
||||
fflush(stdout);
|
||||
_exit(0);
|
||||
}
|
||||
waitpid(pid, NULL, 0);
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "cd:", 3) == 0) {
|
||||
int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL;
|
||||
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
|
||||
@@ -76,6 +116,8 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
cls.root = tmp / "root"
|
||||
cls.library = tmp / "storage/PC GAMES"
|
||||
(cls.root / "etc").mkdir(parents=True)
|
||||
(cls.root / "deep/er/est").mkdir(parents=True)
|
||||
(cls.root / "linked").symlink_to("deep/er/est")
|
||||
(cls.root / "etc/hostname").write_text("rootfs")
|
||||
(cls.root / "mnt/library/Some Game").mkdir(parents=True)
|
||||
(cls.root / "mnt/library/Some Game/game.txt").write_text("mount point")
|
||||
@@ -117,10 +159,11 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_probe(self, *args):
|
||||
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
|
||||
def run_probe(self, *args, binds=None):
|
||||
if binds is None:
|
||||
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
@@ -131,6 +174,18 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_dev_fd_in_a_forked_child_names_the_child_descriptors(self):
|
||||
out = self.run_probe("fork:/dev/fd", binds="/proc/self/fd:/dev/fd")
|
||||
self.assertEqual(["x"], out["fork:/dev/fd"])
|
||||
|
||||
def test_a_mount_named_through_proc_self_root_reports_its_guest_path(self):
|
||||
arg = f"cd:{GAME}/"
|
||||
self.assertEqual(self.run_probe(arg, binds=f"/proc/self/root{self.library}:/mnt/library")[arg], [GAME])
|
||||
|
||||
def test_a_proc_mount_that_names_no_process_reports_its_guest_path(self):
|
||||
arg = "cd:/mnt/sys/kernel/"
|
||||
self.assertEqual(self.run_probe(arg, binds="/proc/self/root/proc/sys:/mnt/sys")[arg], ["/mnt/sys/kernel"])
|
||||
|
||||
def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self):
|
||||
path = f"/pfx/native/dosdevices/z:{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
|
||||
@@ -147,6 +202,42 @@ class NativeHookMountTest(unittest.TestCase):
|
||||
path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
|
||||
|
||||
def test_glibc_locale_and_iconv_data_come_from_the_rootfs(self):
|
||||
result = self.run_probe("env:LOCPATH", "env:GCONV_PATH")
|
||||
self.assertEqual(result["env:LOCPATH"], [f"{self.root}/usr/lib/locale"])
|
||||
self.assertEqual(result["env:GCONV_PATH"], [f"{self.root}/usr/lib/aarch64-linux-gnu/gconv"])
|
||||
|
||||
def test_parent_of_root_stays_at_root(self):
|
||||
self.assertEqual(self.run_probe("parent:/")["parent:/"], ["1"])
|
||||
|
||||
def test_parent_of_root_without_mounts_stays_at_root(self):
|
||||
self.assertEqual(self.run_probe("parent:/", binds="")["parent:/"], ["1"])
|
||||
|
||||
def test_parent_of_mount_ancestor_is_guest_root(self):
|
||||
self.assertEqual(self.run_probe("parent:/mnt")["parent:/mnt"], ["1"])
|
||||
|
||||
def test_parent_walks_from_any_directory_stay_at_root(self):
|
||||
cases = ["parent:/etc|../..", "parent:/mnt/library|../../..", "parent:/|../etc/.."]
|
||||
self.assertEqual(self.run_probe(*cases), {case: ["1"] for case in cases})
|
||||
|
||||
def test_parent_walk_from_a_linked_mount_ancestor_follows_the_real_directory(self):
|
||||
binds = f"{self.library}:/linked/library"
|
||||
case = "parent:/linked|../..|/deep"
|
||||
self.assertEqual(self.run_probe(case, binds=binds)[case], ["1"])
|
||||
|
||||
def test_absolute_paths_above_root_stay_at_root(self):
|
||||
result = self.run_probe("cd:/..", "cd:/etc/../..", "/../etc/hostname")
|
||||
self.assertEqual(result["cd:/.."], [str(self.root)])
|
||||
self.assertEqual(result["cd:/etc/../.."], [str(self.root)])
|
||||
self.assertEqual(result["/../etc/hostname"], ["1", "rootfs"])
|
||||
|
||||
def test_relative_parent_of_cwd_stays_in_guest(self):
|
||||
result = self.run_probe("cd:/", "cd:..", "cd:./../..", "../etc/hostname", f"cd:{GAME}", "cd:../..")
|
||||
self.assertEqual(result["cd:.."], [str(self.root)])
|
||||
self.assertEqual(result["cd:./../.."], [str(self.root)])
|
||||
self.assertEqual(result["cd:../.."], [str(self.root / "mnt")])
|
||||
self.assertEqual(result["../etc/hostname"], ["1", "rootfs"])
|
||||
|
||||
def test_rootfs_paths_outside_mounts_are_unchanged(self):
|
||||
paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"]
|
||||
result = self.run_probe(*paths)
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <semaphore.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); }
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *name = argv[1];
|
||||
sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1);
|
||||
show("create", sem != SEM_FAILED);
|
||||
show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST);
|
||||
sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1);
|
||||
int value = -1;
|
||||
show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1);
|
||||
show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL);
|
||||
show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN);
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
sem_t *other = sem_open(name, 0);
|
||||
_exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1);
|
||||
}
|
||||
int status = 0;
|
||||
waitpid(child, &status, 0);
|
||||
show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0);
|
||||
show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL);
|
||||
show("unlink", sem_unlink(name) == 0);
|
||||
show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
KEEP = r"""
|
||||
#include <fcntl.h>
|
||||
#include <semaphore.h>
|
||||
int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; }
|
||||
"""
|
||||
|
||||
FORKER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *name;
|
||||
static _Atomic int done;
|
||||
|
||||
static void *churn(void *arg) {
|
||||
while (!done) {
|
||||
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
|
||||
if (sem != SEM_FAILED) sem_close(sem);
|
||||
}
|
||||
return arg;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
name = argv[1];
|
||||
pthread_t thread;
|
||||
if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1;
|
||||
int finished = 0;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) break;
|
||||
if (pid == 0) {
|
||||
alarm(10);
|
||||
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
|
||||
_exit(sem == SEM_FAILED || sem_close(sem) != 0);
|
||||
}
|
||||
int status;
|
||||
if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
|
||||
}
|
||||
done = 1;
|
||||
pthread_join(thread, NULL);
|
||||
sem_unlink(name);
|
||||
printf("finished\t%d\n", finished);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone")
|
||||
|
||||
|
||||
class NativeHookNamedSemaphoresTest(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(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.shm = tmp / "root/tmp/shm"
|
||||
cls.shm.mkdir(parents=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_hooked(self, program, *args):
|
||||
hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return dict(line.split("\t") for line in out.stdout.splitlines())
|
||||
|
||||
def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self):
|
||||
name = f"/ddsem-{os.getpid()}"
|
||||
self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name))
|
||||
self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists())
|
||||
self.assertEqual([], list(self.shm.iterdir()))
|
||||
|
||||
def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self):
|
||||
source = self.probe.with_name("forker.c")
|
||||
source.write_text(FORKER)
|
||||
forker = self.probe.with_name("forker")
|
||||
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True)
|
||||
self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}"))
|
||||
|
||||
def test_a_created_semaphore_keeps_its_name_and_mode(self):
|
||||
name = f"ddsem-kept-{os.getpid()}"
|
||||
source = self.probe.with_name("keep.c")
|
||||
source.write_text(KEEP)
|
||||
keep = self.probe.with_name("keep")
|
||||
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True)
|
||||
self.run_hooked(keep, name)
|
||||
made = self.shm / f"sem.{name}"
|
||||
self.addCleanup(made.unlink)
|
||||
umask = os.umask(0)
|
||||
os.umask(umask)
|
||||
self.assertEqual([made.name], [p.name for p in self.shm.iterdir()])
|
||||
self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,189 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); }
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *dir = argv[1];
|
||||
char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX];
|
||||
snprintf(p, sizeof(p), "%s/made", dir);
|
||||
show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755));
|
||||
snprintf(p, sizeof(p), "%s/made/file", dir);
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
|
||||
show("openat", fd);
|
||||
if (fd >= 0) close((int)fd);
|
||||
show("truncate", syscall(SYS_truncate, p, 4));
|
||||
show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600));
|
||||
show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0));
|
||||
fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC);
|
||||
show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1);
|
||||
if (fd >= 0) close((int)fd);
|
||||
snprintf(q, sizeof(q), "%s/made/moved", dir);
|
||||
show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q));
|
||||
show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0));
|
||||
snprintf(q, sizeof(q), "%s/made/link", dir);
|
||||
show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q));
|
||||
show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0));
|
||||
snprintf(q, sizeof(q), "%s/made/sock", dir);
|
||||
struct sockaddr_un addr = {.sun_family = AF_UNIX}, extra = {.sun_family = AF_UNIX};
|
||||
size_t len = strlen(q);
|
||||
int fits = len + sizeof("-extra") <= sizeof(addr.sun_path);
|
||||
if (fits) {
|
||||
memcpy(addr.sun_path, q, len);
|
||||
memcpy(extra.sun_path, q, len);
|
||||
memcpy(extra.sun_path + len, "-extra", sizeof("-extra"));
|
||||
}
|
||||
int server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
show("bind", fits ? syscall(SYS_bind, server, &addr, sizeof(addr)) : -1);
|
||||
listen(server, 1);
|
||||
show("connect", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1);
|
||||
close(client);
|
||||
close(server);
|
||||
syscall(SYS_unlinkat, AT_FDCWD, q, 0);
|
||||
server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
show("bind-length", fits ? syscall(SYS_bind, server, &extra, offsetof(struct sockaddr_un, sun_path) + len) : -1);
|
||||
listen(server, 1);
|
||||
show("connect-length", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1);
|
||||
close(client);
|
||||
close(server);
|
||||
syscall(SYS_unlinkat, AT_FDCWD, q, 0);
|
||||
snprintf(q, sizeof(q), "%s/made", dir);
|
||||
show("chdir", syscall(SYS_chdir, q));
|
||||
show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1);
|
||||
show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0));
|
||||
show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR));
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
ALLOCATOR = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern void *__libc_malloc(size_t);
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static int ready;
|
||||
|
||||
void *malloc(size_t size) {
|
||||
if (!ready) {
|
||||
pthread_mutex_lock(&lock);
|
||||
if (!ready) {
|
||||
long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC);
|
||||
if (fd >= 0) close((int)fd);
|
||||
ready = 1;
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
return __libc_malloc(size);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
puts("ready");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
EARLY = r"""
|
||||
#include <stdlib.h>
|
||||
|
||||
__attribute__((constructor)) static void early(void) { free(malloc(1)); }
|
||||
"""
|
||||
|
||||
CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat",
|
||||
"bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir")
|
||||
|
||||
|
||||
class NativeHookPathSyscallsTest(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(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "opt").mkdir(parents=True)
|
||||
(tmp / "allocator.c").write_text(ALLOCATOR)
|
||||
cls.allocator = tmp / "allocator"
|
||||
subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True)
|
||||
(tmp / "early.c").write_text(EARLY)
|
||||
cls.early = tmp / "early.so"
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self, argv, hook_env):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120)
|
||||
|
||||
def run_probe(self, guest_dir, hook=True):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {}
|
||||
out = self.run_program([str(self.probe), guest_dir], hook_env)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()}
|
||||
|
||||
def test_guest_paths_through_syscall_land_in_the_root(self):
|
||||
results = self.run_probe("/opt")
|
||||
for call in CALLS:
|
||||
with self.subTest(call=call):
|
||||
self.assertEqual(1, results[call])
|
||||
self.assertEqual([], list((self.root / "opt").iterdir()))
|
||||
|
||||
def test_paths_already_in_the_root_are_kept(self):
|
||||
results = self.run_probe(str(self.root / "opt"))
|
||||
for call in CALLS:
|
||||
with self.subTest(call=call):
|
||||
self.assertEqual(1, results[call])
|
||||
|
||||
def test_without_the_hook_guest_paths_reach_the_host(self):
|
||||
results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False)
|
||||
self.assertEqual(0, results["mkdirat"])
|
||||
self.assertEqual(0, results["openat"])
|
||||
self.assertEqual(0, results["chdir"])
|
||||
|
||||
def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc",
|
||||
"LD_PRELOAD": f"{self.hook}:{self.early}"}
|
||||
out = self.run_program([str(self.allocator)], hook_env)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual("ready", out.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -57,6 +57,16 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
(cls.root / "usr/bin").mkdir(parents=True)
|
||||
cls.kwin = cls.root / "usr/bin/kwin_wayland"
|
||||
shutil.copy(tmp / "sleeper", cls.kwin)
|
||||
cls.runtime = tmp / "runtime"
|
||||
cls.runtime.mkdir()
|
||||
cls.bound = cls.runtime / "chrome"
|
||||
shutil.copy(tmp / "sleeper", cls.bound)
|
||||
cls.shadowed = cls.runtime / "bin/chrome"
|
||||
cls.shadowed.parent.mkdir()
|
||||
shutil.copy(tmp / "sleeper", cls.shadowed)
|
||||
cls.override = tmp / "override"
|
||||
cls.override.mkdir()
|
||||
shutil.copy(tmp / "sleeper", cls.override / "chrome")
|
||||
# The child's /proc/<pid>/exe must name the loader, as DroidDeck's libddexec.so does.
|
||||
cls.loader = tmp / "lib/libddexec.so"
|
||||
cls.loader.parent.mkdir()
|
||||
@@ -85,8 +95,10 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
self.assertEqual("ready", child.stdout.readline().strip())
|
||||
return child.pid
|
||||
|
||||
def readlink(self, *paths):
|
||||
def readlink(self, *paths, binds=None):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
if binds:
|
||||
hook_env["DDNATV_BINDS"] = binds
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
@@ -108,6 +120,17 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
at = f"at:/proc/{pid}"
|
||||
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(at)[at])
|
||||
|
||||
def test_a_guest_program_from_a_bind_is_named_by_its_guest_path(self):
|
||||
pid = self.start(loader=True, real_exe=str(self.bound), program=self.bound)
|
||||
link = f"/proc/{pid}/exe"
|
||||
self.assertEqual("/app/extra/chrome", self.readlink(link, binds=f"/proc:/proc|{self.runtime}:/app/extra")[link])
|
||||
|
||||
def test_a_guest_program_shadowed_by_a_nested_bind_keeps_its_own_path(self):
|
||||
pid = self.start(loader=True, real_exe=str(self.shadowed), program=self.shadowed)
|
||||
link = f"/proc/{pid}/exe"
|
||||
binds = f"/proc:/proc|{self.runtime}:/app|{self.override}:/app/bin"
|
||||
self.assertEqual(str(self.shadowed), self.readlink(link, binds=binds)[link])
|
||||
|
||||
def test_a_program_named_only_in_the_environment_is_not_believed(self):
|
||||
pid = self.start(loader=True, real_exe=str(self.kwin))
|
||||
link = f"/proc/{pid}/exe"
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import errno
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(const char *name, ssize_t len, const char *buf) {
|
||||
printf("%s\t%zd\t%.*s\n", name, len, len > 0 ? (int)len : 0, buf);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *link = argv[1];
|
||||
struct stat st;
|
||||
if (lstat(link, &st) != 0) return 2;
|
||||
char *exact = malloc((size_t)st.st_size + 1);
|
||||
show("sized", readlink(link, exact, (size_t)st.st_size), exact);
|
||||
char full[4096];
|
||||
show("full", readlink(link, full, sizeof(full)), full);
|
||||
char small[4];
|
||||
show("small", readlink(link, small, sizeof(small)), small);
|
||||
show("sized-at", readlinkat(AT_FDCWD, link, exact, (size_t)st.st_size), exact);
|
||||
errno = 0;
|
||||
ssize_t zero = readlink(link, full, 0);
|
||||
int zero_errno = errno;
|
||||
printf("zero\t%zd\t%d\n", zero, zero_errno);
|
||||
errno = 0;
|
||||
zero = readlinkat(AT_FDCWD, link, full, 0);
|
||||
zero_errno = errno;
|
||||
printf("zero-at\t%zd\t%d\n", zero, zero_errno);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookReadlinkTest(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(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "bin").mkdir(parents=True)
|
||||
(cls.root / "etc/alternatives").mkdir(parents=True)
|
||||
(cls.root / "bin/nano").write_text("")
|
||||
os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor")
|
||||
os.symlink("/bin/nano", cls.root / "etc/alternatives/guest")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def read(self, link):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_a_buffer_sized_from_lstat_gets_the_guest_target(self):
|
||||
result = self.read("/etc/alternatives/editor")
|
||||
self.assertEqual(["9", "/bin/nano"], result["sized"])
|
||||
self.assertEqual(["9", "/bin/nano"], result["sized-at"])
|
||||
self.assertEqual(["9", "/bin/nano"], result["full"])
|
||||
|
||||
def test_a_short_buffer_gets_the_start_of_the_guest_target(self):
|
||||
self.assertEqual(["4", "/bin"], self.read("/etc/alternatives/editor")["small"])
|
||||
|
||||
def test_a_guest_target_is_unchanged(self):
|
||||
result = self.read("/etc/alternatives/guest")
|
||||
self.assertEqual(["9", "/bin/nano"], result["sized"])
|
||||
self.assertEqual(["4", "/bin"], result["small"])
|
||||
|
||||
def test_a_zero_sized_buffer_is_rejected(self):
|
||||
result = self.read("/etc/alternatives/editor")
|
||||
self.assertEqual(["-1", str(errno.EINVAL)], result["zero"])
|
||||
self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,144 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static uint64_t current(void) {
|
||||
uint64_t mask = 0;
|
||||
syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask));
|
||||
return mask;
|
||||
}
|
||||
|
||||
struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; };
|
||||
|
||||
static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; }
|
||||
|
||||
static long raw_sigaction(int sig, const struct kact *act, struct kact *old) {
|
||||
register long x8 __asm__("x8") = SYS_rt_sigaction;
|
||||
register long x0 __asm__("x0") = sig;
|
||||
register long x1 __asm__("x1") = (long)act;
|
||||
register long x2 __asm__("x2") = (long)old;
|
||||
register long x3 __asm__("x3") = 8;
|
||||
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
|
||||
return x0;
|
||||
}
|
||||
|
||||
static void handlers(void) {
|
||||
struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel;
|
||||
syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8);
|
||||
syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8);
|
||||
raw_sigaction(SIGSYS, NULL, &kernel);
|
||||
printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own);
|
||||
struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 };
|
||||
syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8);
|
||||
raw_sigaction(SIGUSR1, NULL, &kernel);
|
||||
printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own);
|
||||
}
|
||||
|
||||
static void show(const char *how) {
|
||||
uint64_t mask = current();
|
||||
printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1))));
|
||||
uint64_t none = 0;
|
||||
syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none));
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
uint64_t all = ~0ULL;
|
||||
sigset_t set;
|
||||
sigfillset(&set);
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all));
|
||||
else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all));
|
||||
else if (strcmp(argv[i], "syscall-unblock") == 0) {
|
||||
syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all));
|
||||
uint64_t usr1 = 1ULL << (SIGUSR1 - 1);
|
||||
syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1));
|
||||
}
|
||||
else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL);
|
||||
else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL);
|
||||
else if (strcmp(argv[i], "sigaction") == 0) {
|
||||
handlers();
|
||||
continue;
|
||||
}
|
||||
show(argv[i]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask")
|
||||
|
||||
|
||||
class NativeHookSigsysMaskTest(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)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
cls.probe = tmp / "probe"
|
||||
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.root = tmp / "root"
|
||||
cls.root.mkdir()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def masks(self, *ways, hook=True):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe), *ways], env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()}
|
||||
|
||||
def test_blocking_every_signal_leaves_sigsys_open(self):
|
||||
masks = self.masks(*WAYS)
|
||||
for way in WAYS:
|
||||
with self.subTest(way=way):
|
||||
self.assertEqual((0, 1), masks[way])
|
||||
|
||||
def test_unblocking_is_unchanged(self):
|
||||
self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"])
|
||||
|
||||
def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self):
|
||||
seen = self.masks("sigaction")
|
||||
self.assertEqual((1, 0), seen["sigaction"])
|
||||
self.assertEqual((1,), seen["sigaction-usr1"])
|
||||
|
||||
def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self):
|
||||
self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"])
|
||||
|
||||
def test_without_the_hook_every_signal_is_blocked(self):
|
||||
masks = self.masks(*WAYS, hook=False)
|
||||
for way in WAYS:
|
||||
with self.subTest(way=way):
|
||||
self.assertEqual((1, 1), masks[way])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,6 +1,7 @@
|
||||
import importlib.util
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import subprocess
|
||||
import tarfile
|
||||
@@ -122,6 +123,40 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
runtime.verify(self.root, stale_sources_ok=True)
|
||||
self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue())
|
||||
|
||||
def helper(self, content):
|
||||
source = self.root / 'tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper'
|
||||
source.parent.mkdir(parents=True, exist_ok=True)
|
||||
source.write_text(content)
|
||||
staged = self.root / 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper'
|
||||
staged.parent.mkdir(parents=True, exist_ok=True)
|
||||
staged.write_text(content)
|
||||
return source, staged
|
||||
|
||||
def test_an_edited_helper_script_needs_no_new_preparation(self):
|
||||
self.helper('old helper')
|
||||
runtime.record(self.root)
|
||||
self.helper('new helper')
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_a_staged_helper_that_lags_its_source_is_rejected(self):
|
||||
source, _ = self.helper('old helper')
|
||||
runtime.record(self.root)
|
||||
source.write_text('new helper')
|
||||
with self.assertRaisesRegex(ValueError, 'not a current copy'):
|
||||
runtime.verify(self.root, stale_sources_ok=True)
|
||||
|
||||
def test_a_manifest_that_hashed_helper_scripts_still_verifies(self):
|
||||
source, staged = self.helper('old helper')
|
||||
runtime.record(self.root)
|
||||
manifest = self.root / runtime.MANIFEST
|
||||
data = json.loads(manifest.read_text())
|
||||
data['sources']['tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper'] = 'old'
|
||||
data['outputs']['assets/linuxfs/usr/local/bin/droiddeck-test-helper'] = {
|
||||
'path': 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper', 'sha256': 'old'}
|
||||
manifest.write_text(json.dumps(data))
|
||||
self.helper('new helper')
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_dev_loop_still_rejects_changed_outputs(self):
|
||||
runtime.record(self.root)
|
||||
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
@@ -37,13 +38,28 @@ class AppImageExecTest(unittest.TestCase):
|
||||
path.chmod(0o755)
|
||||
return path
|
||||
|
||||
def launch(self):
|
||||
def launch(self, **extra):
|
||||
script = self.dir / "exec"
|
||||
script.write_text(EXEC.read_text().replace(URUNTIME, str(self.uruntime)).replace(FEX, str(self.fex)))
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN")}
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN", "DDNATV_ROOT")}
|
||||
env.update(extra)
|
||||
return subprocess.run(["bash", str(script), str(self.image), "--no-gui"], env=env,
|
||||
capture_output=True, text=True, timeout=30).stdout.splitlines()
|
||||
|
||||
def native(self, **extra):
|
||||
return self.launch(DDNATV_ROOT=str(self.dir / "rootfs"), XDG_CACHE_HOME=str(self.cache), **extra)
|
||||
|
||||
def unpacker(self, works=True, apprun=None):
|
||||
self.cache = self.dir / "cache"
|
||||
self.unpacks = self.dir / "unpacks"
|
||||
apprun = apprun or "#!/bin/sh\nprintf '%s\\n' \"APPIMAGE=$APPIMAGE APPDIR=$APPDIR TARGET=${TARGET_APPIMAGE:-}\" apprun \"$@\"\n"
|
||||
self.fex.write_text(
|
||||
"#!/bin/sh\n[ \"$1\" = extract ] || exit 9\necho \"$2\" >> %s\n" % self.unpacks +
|
||||
("mkdir -p squashfs-root\ncat > squashfs-root/AppRun <<'EOF'\n%sEOF\nchmod +x squashfs-root/AppRun\n" % apprun if works else "exit 1\n"))
|
||||
|
||||
def unpacked_dirs(self):
|
||||
return [d for d in self.cache.glob("droiddeck-appimage/*") if d.is_dir()]
|
||||
|
||||
def test_an_arm64_image_runs_through_the_shipped_runtime(self):
|
||||
self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch())
|
||||
|
||||
@@ -61,6 +77,116 @@ class AppImageExecTest(unittest.TestCase):
|
||||
self.fex.unlink()
|
||||
self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch())
|
||||
|
||||
def test_without_proot_an_arm64_image_is_unpacked_once_and_runs_from_its_apprun(self):
|
||||
self.unpacker()
|
||||
expected = ["== appimage: unpacking %s" % self.image]
|
||||
ran = ["APPIMAGE=%s APPDIR=%s/squashfs-root TARGET=" % (self.image, "%s"), "apprun", "--no-gui"]
|
||||
first = self.native()
|
||||
self.assertEqual(expected, first[:1])
|
||||
[unpacked] = self.unpacked_dirs()
|
||||
ran[0] = ran[0] % unpacked
|
||||
self.assertEqual(ran, first[1:])
|
||||
self.assertEqual(ran, self.native())
|
||||
self.assertEqual([str(self.image)], self.unpacks.read_text().splitlines())
|
||||
|
||||
def test_without_proot_a_changed_image_is_unpacked_again(self):
|
||||
self.unpacker()
|
||||
self.native()
|
||||
os.utime(self.image, (1, 1))
|
||||
self.assertEqual("apprun", self.native()[2])
|
||||
self.assertEqual(2, len(self.unpacks.read_text().splitlines()))
|
||||
self.assertEqual(1, len(self.unpacked_dirs()))
|
||||
|
||||
def test_without_proot_a_same_size_change_within_one_second_is_unpacked_again(self):
|
||||
self.unpacker()
|
||||
os.utime(self.image, ns=(1_000_000_100_000_000, 1_000_000_100_000_000))
|
||||
self.native()
|
||||
os.utime(self.image, ns=(1_000_000_900_000_000, 1_000_000_900_000_000))
|
||||
self.assertEqual("apprun", self.native()[2])
|
||||
self.assertEqual(2, len(self.unpacks.read_text().splitlines()))
|
||||
self.assertEqual(1, len(self.unpacked_dirs()))
|
||||
|
||||
def hold(self, unpacked):
|
||||
handle = open(unpacked / "source")
|
||||
self.addCleanup(handle.close)
|
||||
fcntl.flock(handle, fcntl.LOCK_SH)
|
||||
return handle
|
||||
|
||||
def test_without_proot_a_running_copy_survives_an_update_until_it_exits(self):
|
||||
self.unpacker()
|
||||
self.native()
|
||||
[old] = self.unpacked_dirs()
|
||||
running = self.hold(old)
|
||||
os.utime(self.image, (1, 1))
|
||||
self.assertEqual("apprun", self.native()[2])
|
||||
self.assertTrue((old / "squashfs-root/AppRun").exists())
|
||||
[new] = [d for d in self.unpacked_dirs() if d != old]
|
||||
running.close()
|
||||
self.assertEqual("apprun", self.native()[1])
|
||||
self.assertEqual([new], self.unpacked_dirs())
|
||||
|
||||
def test_without_proot_a_running_copy_of_a_removed_image_is_kept(self):
|
||||
self.unpacker()
|
||||
self.native()
|
||||
[old] = self.unpacked_dirs()
|
||||
self.hold(old)
|
||||
self.image.unlink()
|
||||
self.image = self.dir / "dolphin.AppImage"
|
||||
self.machine(183)
|
||||
self.native()
|
||||
self.assertTrue((old / "squashfs-root/AppRun").exists())
|
||||
self.assertEqual(2, len(self.unpacked_dirs()))
|
||||
|
||||
def test_without_proot_the_running_application_holds_its_copy(self):
|
||||
self.unpacker(apprun="#!/bin/sh\nflock -n -x \"$APPDIR/../source\" true && echo free || echo held\n")
|
||||
self.assertEqual(["held"], self.native()[1:])
|
||||
|
||||
def test_without_proot_nothing_runs_when_the_cache_cannot_be_locked(self):
|
||||
self.unpacker()
|
||||
tools = self.dir / "tools"
|
||||
tools.mkdir()
|
||||
(tools / "flock").write_text("#!/bin/sh\nexit 1\n")
|
||||
(tools / "flock").chmod(0o755)
|
||||
self.assertEqual([], self.native(PATH="%s:%s" % (tools, os.environ["PATH"])))
|
||||
self.assertFalse(self.unpacks.exists())
|
||||
|
||||
def test_without_proot_the_unpacked_copy_of_a_removed_image_is_dropped(self):
|
||||
self.unpacker()
|
||||
self.native()
|
||||
[old] = self.unpacked_dirs()
|
||||
self.image.unlink()
|
||||
self.image = self.dir / "dolphin.AppImage"
|
||||
self.machine(183)
|
||||
self.native()
|
||||
self.assertFalse(old.exists())
|
||||
self.assertEqual(1, len(self.unpacked_dirs()))
|
||||
|
||||
def test_without_proot_a_linked_cache_entry_and_its_target_survive(self):
|
||||
self.unpacker()
|
||||
outside = self.dir / "outside"
|
||||
outside.mkdir()
|
||||
(outside / "source").write_text("%s\n" % (self.dir / "gone.AppImage"))
|
||||
(outside / "keep").write_text("data")
|
||||
link = self.cache / "droiddeck-appimage" / "linked"
|
||||
link.parent.mkdir(parents=True)
|
||||
link.symlink_to(outside, target_is_directory=True)
|
||||
self.assertEqual("apprun", self.native()[2])
|
||||
self.assertTrue(link.is_symlink())
|
||||
self.assertEqual("data", (outside / "keep").read_text())
|
||||
|
||||
def test_without_proot_an_image_that_cannot_be_unpacked_runs_nothing(self):
|
||||
self.unpacker(works=False)
|
||||
out = self.native()
|
||||
self.assertNotIn("uruntime", out)
|
||||
self.assertNotIn("apprun", out)
|
||||
self.assertEqual([], self.unpacked_dirs())
|
||||
self.assertEqual([], list(self.cache.glob("droiddeck-appimage/.unpack.*")))
|
||||
|
||||
def test_without_proot_an_x86_image_still_starts_under_fex(self):
|
||||
self.machine(62)
|
||||
self.cache = self.dir / "cache"
|
||||
self.assertEqual(["TARGET= EXTRACT=1", "fex", "run", "--mode", "on", "--", str(self.image), "--no-gui"], self.native())
|
||||
|
||||
def test_the_session_starts_images_through_the_shared_launcher(self):
|
||||
script = ("set -u\n"
|
||||
"run_program() { printf '%%s\\n' \"$@\"; exit 0; }\n"
|
||||
|
||||
@@ -50,3 +50,10 @@ class SessionAssetsTest(unittest.TestCase):
|
||||
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/sub/login1"'
|
||||
self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'],
|
||||
assets.check_extraction(self.overlay, mapping))
|
||||
|
||||
def test_stage_refreshes_a_changed_helper(self):
|
||||
target = self.root / 'main'
|
||||
assets.stage(target, self.overlay)
|
||||
self.helper.write_bytes(b'new helper')
|
||||
assets.stage(target, self.overlay)
|
||||
self.assertEqual(b'new helper', (target / self.name).read_bytes())
|
||||
@@ -2,8 +2,10 @@ import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
@@ -12,6 +14,8 @@ SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/dr
|
||||
|
||||
|
||||
class SteamInstallTest(unittest.TestCase):
|
||||
parallel = '1'
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
@@ -47,19 +51,29 @@ if host_fail and host_fail in url:
|
||||
action = []
|
||||
plan = os.environ.get('TEST_PLAN')
|
||||
if plan and os.path.exists(plan):
|
||||
lines = open(plan).read().splitlines()
|
||||
for n, line in enumerate(lines):
|
||||
if line.split()[0] == name:
|
||||
action = line.split()[1:]
|
||||
del lines[n]
|
||||
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
|
||||
break
|
||||
import fcntl
|
||||
with open(plan + '.lock', 'w') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
lines = open(plan).read().splitlines()
|
||||
for n, line in enumerate(lines):
|
||||
if line.split()[0] == name:
|
||||
action = line.split()[1:]
|
||||
del lines[n]
|
||||
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
|
||||
break
|
||||
if action[:1] == ['fail']:
|
||||
done(int(action[1]), '000')
|
||||
if action[:1] == ['http']:
|
||||
done(22, action[1])
|
||||
if action[:1] == ['killworker']:
|
||||
import signal
|
||||
os.kill(os.getppid(), signal.SIGKILL)
|
||||
import time
|
||||
time.sleep(6)
|
||||
if action[:1] == ['norange'] and offset:
|
||||
done(33)
|
||||
import time
|
||||
time.sleep(float(os.environ.get('TEST_SLEEP', '0')))
|
||||
data = open(os.path.join(os.environ['TEST_CDN'], name), 'rb').read()
|
||||
end = int(action[1]) if action[:1] == ['cut'] else len(data)
|
||||
with open(out, 'ab' if offset else 'wb') as target:
|
||||
@@ -79,7 +93,8 @@ done(28 if end < len(data) else 0)
|
||||
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),
|
||||
TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0')
|
||||
TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0',
|
||||
DD_STEAM_PARALLEL=self.parallel)
|
||||
for channel in ('steamdeck_publicbeta', 'steamdeck_stable'):
|
||||
archive = self.cdn / (channel + '.zip')
|
||||
with zipfile.ZipFile(archive, 'w') as package:
|
||||
@@ -92,9 +107,13 @@ done(28 if end < len(data) else 0)
|
||||
f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def install(self, fail_host=None, *args, **extra):
|
||||
def install(self, fail_host=None, *args, timeout=None, **extra):
|
||||
env = self.env if fail_host is None else dict(self.env, TEST_FAIL_HOST=fail_host)
|
||||
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True)
|
||||
try:
|
||||
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True,
|
||||
timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.fail(f'the installer did not finish within {timeout} s')
|
||||
|
||||
def channel(self, **extra):
|
||||
result = self.install(None, '--channel', **extra)
|
||||
@@ -314,6 +333,130 @@ done(28 if end < len(data) else 0)
|
||||
def download(self):
|
||||
return self.steam / 'package/droiddeck-download'
|
||||
|
||||
def cache_manifest(self):
|
||||
plain = b'plain-package'
|
||||
packed = b'packed-package'
|
||||
(self.cdn / 'a.zip.1111').write_bytes(plain)
|
||||
(self.cdn / 'b.zip.vz.2222_14').write_bytes(packed)
|
||||
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
|
||||
'"linuxarm64"\n{\n\t"version" "123456"\n'
|
||||
'\t"a_all"\n\t{\n'
|
||||
f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(plain)}"\n\t\t"sha2" "{hashlib.sha256(plain).hexdigest()}"\n'
|
||||
'\t}\n'
|
||||
'\t"b_all"\n\t{\n'
|
||||
'\t\t"file" "b.zip.9999"\n\t\t"size" "99"\n\t\t"sha2" "00"\n'
|
||||
'\t\t"zipvz" "b.zip.vz.2222_14"\n'
|
||||
f'\t\t"sha2vz" "{hashlib.sha256(packed).hexdigest()}"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def test_the_cache_pass_keeps_every_package_under_the_names_steam_looks_for(self):
|
||||
self.cache_manifest()
|
||||
result = self.install(None, '--cache')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
package = self.steam / 'package'
|
||||
self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes())
|
||||
self.assertEqual(b'packed-package', (package / 'b.zip.vz.2222_14').read_bytes())
|
||||
self.assertFalse((package / 'b.zip.9999').exists())
|
||||
self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text())
|
||||
|
||||
PREAPPLY = SCRIPT.with_name('droiddeck-steam-preapply')
|
||||
|
||||
def real_cache_manifest(self):
|
||||
import io
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, 'w') as z:
|
||||
z.writestr('steamrtarm64/steam', b'client')
|
||||
data = out.getvalue()
|
||||
(self.cdn / 'a.zip.1111').write_bytes(data)
|
||||
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
|
||||
'"linuxarm64"\n{\n\t"version" "123456"\n\t"a_all"\n\t{\n'
|
||||
f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(data)}"\n\t\t"sha2" "{hashlib.sha256(data).hexdigest()}"\n'
|
||||
'\t}\n}\n')
|
||||
|
||||
def test_the_cache_pass_applies_the_update_so_steam_has_nothing_to_extract(self):
|
||||
self.real_cache_manifest()
|
||||
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY))
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
package = self.steam / 'package'
|
||||
name = 'steam_client_steamdeck_publicbeta_linuxarm64'
|
||||
self.assertEqual(b'client', (self.steam / 'steamrtarm64/steam').read_bytes())
|
||||
self.assertTrue(os.access(self.steam / 'steamrtarm64/steam', os.X_OK))
|
||||
self.assertIn('steamrtarm64/steam,6;', (package / (name + '.installed')).read_text())
|
||||
self.assertEqual((self.cdn / name).read_text(), (package / (name + '.manifest')).read_text())
|
||||
self.assertFalse((package / 'a.zip.1111').exists())
|
||||
self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text())
|
||||
|
||||
def test_an_applied_update_finishes_the_install_without_fetching_the_plain_packages_again(self):
|
||||
self.real_cache_manifest()
|
||||
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY))
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
package = self.steam / 'package'
|
||||
self.assertEqual('123456\n', (package / 'droiddeck-installed').read_text())
|
||||
self.assertEqual('steamdeck_publicbeta\n', (package / 'beta').read_text())
|
||||
self.assertEqual((self.steam / 'linuxarm64').resolve(), (self.home / '.steam/sdkarm64').resolve())
|
||||
self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', 'a.zip.1111'], self.requested())
|
||||
again = self.install(None)
|
||||
self.assertEqual(0, again.returncode, again.stderr)
|
||||
self.assertEqual(2, len(self.requested()))
|
||||
|
||||
def test_a_failed_apply_clears_the_cache_marker_and_the_old_record_so_it_is_retried(self):
|
||||
self.real_cache_manifest()
|
||||
package = self.steam / 'package'
|
||||
package.mkdir(parents=True)
|
||||
name = 'steam_client_steamdeck_publicbeta_linuxarm64'
|
||||
(package / (name + '.installed')).write_text('old\n')
|
||||
failing = self.root / 'failing-apply'
|
||||
failing.write_text('import sys\nsys.exit(1)\n')
|
||||
failing.chmod(0o755)
|
||||
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(failing))
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertFalse((package / (name + '.installed')).exists())
|
||||
self.assertFalse((package / 'droiddeck-cached').exists())
|
||||
self.assertEqual((self.cdn / 'a.zip.1111').read_bytes(), (package / 'a.zip.1111').read_bytes())
|
||||
|
||||
def test_cancelling_the_cache_pass_stops_the_apply_helper(self):
|
||||
self.real_cache_manifest()
|
||||
pidfile = self.root / 'apply.pid'
|
||||
slow = self.root / 'slow-apply'
|
||||
slow.write_text(f'import os, time\nopen({str(pidfile)!r}, "w").write(str(os.getpid()))\ntime.sleep(30)\n')
|
||||
slow.chmod(0o755)
|
||||
process = subprocess.Popen(['bash', str(SCRIPT), '--cache'], env=dict(self.env, DD_STEAM_PREAPPLY=str(slow)),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
for _ in range(100):
|
||||
if pidfile.exists() and pidfile.read_text().strip():
|
||||
break
|
||||
time.sleep(0.1)
|
||||
helper = int(pidfile.read_text())
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
time.sleep(0.3)
|
||||
with self.assertRaises(ProcessLookupError):
|
||||
os.kill(helper, 0)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-cached').exists())
|
||||
|
||||
def test_a_cache_pass_that_cannot_apply_the_update_keeps_the_packages_for_steam(self):
|
||||
self.cache_manifest()
|
||||
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY))
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
package = self.steam / 'package'
|
||||
self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes())
|
||||
self.assertFalse(list(package.glob('*.installed')))
|
||||
self.assertFalse(list(package.glob('*.manifest')))
|
||||
|
||||
def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self):
|
||||
self.cache_manifest()
|
||||
self.assertEqual(0, self.install(None, '--cache').returncode)
|
||||
requests = len(self.requests.read_text().splitlines())
|
||||
self.assertEqual(0, self.install(None, '--cache').returncode)
|
||||
self.assertEqual(requests + 1, len(self.requests.read_text().splitlines()))
|
||||
|
||||
def test_a_cached_package_is_not_fetched_again(self):
|
||||
self.cache_manifest()
|
||||
(self.steam / 'package').mkdir(parents=True)
|
||||
(self.steam / 'package/a.zip.1111').write_bytes(b'plain-package')
|
||||
self.assertEqual(0, self.install(None, '--cache').returncode)
|
||||
self.assertNotIn('a.zip.1111', self.requests.read_text())
|
||||
|
||||
def test_progress_is_counted_in_megabytes_across_parts(self):
|
||||
self.two_parts()
|
||||
result = self.install()
|
||||
@@ -415,5 +558,212 @@ done(28 if end < len(data) else 0)
|
||||
self.assertFalse(self.download.exists())
|
||||
|
||||
|
||||
class SteamInstallParallelTest(SteamInstallTest):
|
||||
"""The same behaviour with several connections at once."""
|
||||
parallel = '4'
|
||||
test_progress_is_counted_in_megabytes_across_parts = None
|
||||
|
||||
def many_parts(self, count=10):
|
||||
return self.publish(**{f'p{i}_all': 300_000 for i in range(count)})
|
||||
|
||||
def test_many_parts_arrive_and_unpack_together(self):
|
||||
self.many_parts()
|
||||
result = self.install()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
for i in range(10):
|
||||
self.assertTrue((self.steam / f'parts/p{i}_all').is_file(), i)
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
|
||||
self.assertFalse(self.download.exists())
|
||||
|
||||
def test_every_part_is_requested_once_when_several_arrive_together(self):
|
||||
files = self.many_parts()
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
requested = self.requested()
|
||||
for name in files.values():
|
||||
self.assertEqual(1, requested.count(name), name)
|
||||
|
||||
def test_one_part_that_no_cdn_has_fails_the_install_and_leaves_no_ready_marker(self):
|
||||
files = self.many_parts()
|
||||
missing = files['p4_all']
|
||||
self.plan_for(missing, 'http 404', 'http 404', 'http 404')
|
||||
result = self.install()
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
self.assertIn('failed on every CDN', result.stderr)
|
||||
|
||||
def test_a_retry_after_a_failure_finishes_what_is_left(self):
|
||||
files = self.many_parts()
|
||||
self.plan_for(files['p4_all'], 'http 404', 'http 404', 'http 404')
|
||||
self.assertNotEqual(0, self.install().returncode)
|
||||
self.assertEqual(0, self.install().returncode)
|
||||
self.assertTrue((self.steam / 'parts/p4_all').is_file())
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
|
||||
|
||||
def test_progress_is_reported_while_several_parts_arrive(self):
|
||||
self.many_parts()
|
||||
result = self.install(TEST_SLEEP='1.2', **{})
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
lines = [line for line in result.stdout.splitlines() if 'downloading Steam:' in line and ' of ' in line]
|
||||
self.assertGreaterEqual(len(lines), 2, result.stdout)
|
||||
self.assertIn(' MB', lines[-1])
|
||||
|
||||
def test_packages_are_unpacked_one_at_a_time(self):
|
||||
source = SCRIPT.read_text()
|
||||
region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
|
||||
self.assertNotIn('unzip -qo', region)
|
||||
self.assertIn('unzip_alone', region)
|
||||
self.assertIn('"$flock_command" 9', source)
|
||||
|
||||
def unzip_alone_script(self):
|
||||
source = SCRIPT.read_text()
|
||||
start = source.index('unzip_alone() {')
|
||||
function = source[start:source.index('\n}\n', start) + 3]
|
||||
return 'state=$1\nsteam_root=$2\nflock_command=flock\n' + function + '\nunzip_alone "$3"\n'
|
||||
|
||||
def unzip_alone_archive(self, name='one.zip', entry='steamrtarm64/steam'):
|
||||
archive = self.root / name
|
||||
with zipfile.ZipFile(archive, 'w') as package:
|
||||
package.writestr(entry, 'client')
|
||||
self.steam.mkdir(parents=True, exist_ok=True)
|
||||
(self.root / 'state').mkdir(exist_ok=True)
|
||||
return archive
|
||||
|
||||
def run_unzip_alone(self, archive, timeout, env=None):
|
||||
arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)]
|
||||
try:
|
||||
return subprocess.run(arguments, text=True, capture_output=True, timeout=timeout, env=env)
|
||||
except subprocess.TimeoutExpired:
|
||||
return None
|
||||
|
||||
def hold_the_lock(self):
|
||||
"""Starts a process that holds the unzip lock and returns once it says it has it."""
|
||||
ready = self.root / 'holder-ready'
|
||||
holder = subprocess.Popen(
|
||||
['flock', str(self.root / 'state/unzip.lock'), 'sh', '-c', f'touch {ready}; sleep 60'], start_new_session=True)
|
||||
self.addCleanup(lambda: os.killpg(holder.pid, signal.SIGKILL) if holder.poll() is None else None)
|
||||
deadline = time.monotonic() + 10
|
||||
while not ready.exists():
|
||||
self.assertLess(time.monotonic(), deadline, 'the holder never took the lock')
|
||||
time.sleep(0.05)
|
||||
return holder
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_a_package_waits_for_a_worker_that_is_unpacking(self):
|
||||
archive = self.unzip_alone_archive()
|
||||
self.hold_the_lock()
|
||||
self.assertIsNone(self.run_unzip_alone(archive, timeout=4), 'unzip_alone did not wait for the holder')
|
||||
self.assertFalse((self.steam / 'steamrtarm64/steam').exists())
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_a_worker_killed_while_unpacking_hands_the_lock_on(self):
|
||||
archive = self.unzip_alone_archive()
|
||||
holder = self.hold_the_lock()
|
||||
os.killpg(holder.pid, signal.SIGKILL)
|
||||
holder.wait()
|
||||
result = self.run_unzip_alone(archive, timeout=20)
|
||||
self.assertIsNotNone(result, 'the lock of a killed worker was never handed on')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertTrue((self.steam / 'steamrtarm64/steam').is_file())
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_several_workers_never_unpack_at_the_same_moment(self):
|
||||
log = self.root / 'unzip.log'
|
||||
fake = self.bin / 'unzip'
|
||||
fake.write_text('''#!/usr/bin/env python3
|
||||
import os, sys, time
|
||||
log = os.environ['TEST_UNZIP_LOG']
|
||||
with open(log, 'a') as out:
|
||||
out.write(f'start {os.getpid()}\\n')
|
||||
time.sleep(0.3)
|
||||
with open(log, 'a') as out:
|
||||
out.write(f'end {os.getpid()}\\n')
|
||||
''')
|
||||
fake.chmod(0o755)
|
||||
archive = self.unzip_alone_archive()
|
||||
env = dict(self.env, TEST_UNZIP_LOG=str(log))
|
||||
arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)]
|
||||
workers = [subprocess.Popen(arguments, env=env) for _ in range(8)]
|
||||
for worker in workers:
|
||||
self.assertEqual(0, worker.wait(timeout=60))
|
||||
lines = log.read_text().split()
|
||||
events = lines[0::2]
|
||||
self.assertEqual(['start', 'end'] * 8, events, 'two workers unpacked at the same time')
|
||||
|
||||
def test_without_flock_the_downloads_go_one_at_a_time(self):
|
||||
self.two_parts()
|
||||
result = self.install(DD_STEAM_FLOCK='flock-that-is-not-installed')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
# Only the sequential path counts parts as (1/2) and (2/2).
|
||||
self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout)
|
||||
self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout)
|
||||
|
||||
def test_workers_do_not_claim_packages_with_mkdir(self):
|
||||
source = SCRIPT.read_text()
|
||||
region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
|
||||
self.assertNotIn('mkdir "$state/claim', region)
|
||||
self.assertIn('claim_next', region)
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_racing_workers_never_get_the_same_package(self):
|
||||
source = SCRIPT.read_text()
|
||||
start = source.index('claim_next() {')
|
||||
function = source[start:source.index('\n}\n', start) + 3]
|
||||
state = self.root / 'claims'
|
||||
state.mkdir()
|
||||
(state / 'next').write_text('1\n')
|
||||
script = 'state=$1\ncount=$2\nflock_command=flock\n' + function + 'while :; do n=$(claim_next); [ "$n" -gt 0 ] || exit 0; echo "$n"; done\n'
|
||||
workers = [subprocess.Popen(['bash', '-c', script, 'bash', str(state), '300'], stdout=subprocess.PIPE, text=True)
|
||||
for _ in range(8)]
|
||||
claimed = []
|
||||
for worker in workers:
|
||||
out, _ = worker.communicate(timeout=120)
|
||||
self.assertEqual(0, worker.returncode)
|
||||
claimed += [int(n) for n in out.split()]
|
||||
self.assertEqual(sorted(claimed), list(range(1, 301)), 'a package was claimed twice or never')
|
||||
|
||||
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
|
||||
def test_a_counter_that_cannot_be_used_fails_the_claim(self):
|
||||
source = SCRIPT.read_text()
|
||||
start = source.index('claim_next() {')
|
||||
function = source[start:source.index('\n}\n', start) + 3]
|
||||
for broken in ('directory', 'empty', 'text'):
|
||||
state = self.root / f'claims-{broken}'
|
||||
state.mkdir()
|
||||
if broken == 'directory':
|
||||
(state / 'next').mkdir()
|
||||
else:
|
||||
(state / 'next').write_text('' if broken == 'empty' else 'abc\n')
|
||||
script = 'state=$1\ncount=5\nflock_command=flock\n' + function + 'n=$(claim_next) && echo "claimed $n" || echo failed\n'
|
||||
result = subprocess.run(['bash', '-c', script, 'bash', str(state)], text=True, capture_output=True, timeout=30)
|
||||
self.assertEqual('failed', result.stdout.strip(), f'{broken}: {result.stdout!r} {result.stderr!r}')
|
||||
|
||||
def test_a_claim_that_fails_fails_the_install_instead_of_leaving_packages_unclaimed(self):
|
||||
self.many_parts()
|
||||
# false is found like a flock would be, but it never takes the lock, so every claim fails.
|
||||
result = self.install(DD_STEAM_FLOCK='false', timeout=60)
|
||||
self.assertNotEqual(0, result.returncode, result.stdout)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
|
||||
def test_the_parallel_workers_use_no_process_substitution(self):
|
||||
source = SCRIPT.read_text()
|
||||
region = source[source.index('fetch_one() {'):source.index('fetch_manifest() {')]
|
||||
self.assertNotIn('<(', region)
|
||||
reporter = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
|
||||
self.assertNotIn('kill -0', reporter)
|
||||
|
||||
def test_a_worker_killed_from_outside_fails_the_install_instead_of_hanging_it(self):
|
||||
files = self.many_parts()
|
||||
self.plan_for(files['p3_all'], 'killworker')
|
||||
result = self.install(timeout=40, DD_STEAM_STALL='3')
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
|
||||
|
||||
def test_the_cache_pass_with_several_connections_keeps_every_package(self):
|
||||
self.cache_manifest()
|
||||
result = self.install(None, '--cache')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-cached').read_text())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,157 @@
|
||||
import hashlib
|
||||
import io
|
||||
import lzma
|
||||
from pathlib import Path
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply'
|
||||
NAME = 'steam_client_steamdeck_publicbeta_linuxarm64'
|
||||
|
||||
|
||||
def zip_bytes(entries):
|
||||
out = io.BytesIO()
|
||||
with zipfile.ZipFile(out, 'w') as z:
|
||||
for name, data, mode, stamp in entries:
|
||||
info = zipfile.ZipInfo(name, stamp)
|
||||
info.external_attr = mode << 16
|
||||
z.writestr(info, data)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def vzip(data):
|
||||
packer = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[
|
||||
{'id': lzma.FILTER_LZMA1, 'dict_size': 1 << 20, 'lc': 3, 'lp': 0, 'pb': 2}])
|
||||
body = packer.compress(data) + packer.flush()
|
||||
props = (2 * 5 + 0) * 9 + 3
|
||||
return (b'VZa' + b'\0\0\0\0' + bytes([props]) + struct.pack('<I', 1 << 20) + body
|
||||
+ struct.pack('<II', zlib.crc32(data) & 0xFFFFFFFF, len(data)) + b'zv')
|
||||
|
||||
|
||||
class SteamPreapplyTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
root = Path(self.temp.name)
|
||||
self.packages = root / 'packages'
|
||||
self.packages.mkdir()
|
||||
self.steam = root / 'Steam'
|
||||
self.manifest = root / 'manifest'
|
||||
|
||||
def write_manifest(self, blocks):
|
||||
text = '"linuxarm64"\n{\n\t"version"\t\t"42"\n'
|
||||
for block, attrs in blocks.items():
|
||||
text += f'\t"{block}"\n\t{{\n'
|
||||
for key, value in attrs.items():
|
||||
text += f'\t\t"{key}"\t\t"{value}"\n'
|
||||
text += '\t}\n'
|
||||
self.manifest.write_text(text + '}\n')
|
||||
|
||||
def run_script(self):
|
||||
return subprocess.run([sys.executable, '-I', str(SCRIPT), str(self.packages), str(self.steam),
|
||||
str(self.manifest), NAME], text=True, capture_output=True)
|
||||
|
||||
def installed(self):
|
||||
return (self.steam / 'package' / (NAME + '.installed')).read_text().split('\n')
|
||||
|
||||
def prepare(self):
|
||||
stamp = (2025, 5, 17, 10, 30, 0)
|
||||
plain = zip_bytes([
|
||||
('bin/', b'', 0o40755, stamp),
|
||||
('bin/Tool', b'tool', 0o100755, stamp),
|
||||
('bin\\Backslash.txt', b'bs', 0o100644, stamp),
|
||||
('lib/libx.so.1', b'libx', 0o100644, stamp),
|
||||
('lib/libx.so', b'libx.so.1', 0o120777, stamp),
|
||||
])
|
||||
packed = zip_bytes([('data/z_file', b'zed', 0o100644, stamp), ('data/A_file', b'aaa', 0o100644, stamp)])
|
||||
(self.packages / 'a.zip.1111').write_bytes(plain)
|
||||
(self.packages / 'b.zip.vz.2222_14').write_bytes(vzip(packed))
|
||||
self.write_manifest({
|
||||
'a_all': {'file': 'a.zip.1111', 'size': len(plain), 'sha2': '00'},
|
||||
'b_all': {'file': 'b.zip.9999', 'size': 99, 'sha2': '00', 'zipvz': 'b.zip.vz.2222_14', 'sha2vz': '00'},
|
||||
})
|
||||
|
||||
def test_extracts_every_package_including_packed_ones(self):
|
||||
self.prepare()
|
||||
result = self.run_script()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(b'tool', (self.steam / 'bin/Tool').read_bytes())
|
||||
self.assertTrue(os.access(self.steam / 'bin/Tool', os.X_OK))
|
||||
self.assertEqual(b'bs', (self.steam / 'bin/Backslash.txt').read_bytes())
|
||||
self.assertEqual('libx.so.1', os.readlink(self.steam / 'lib/libx.so'))
|
||||
self.assertEqual(b'zed', (self.steam / 'data/z_file').read_bytes())
|
||||
|
||||
def test_records_what_steams_updater_records(self):
|
||||
self.prepare()
|
||||
self.assertEqual(0, self.run_script().returncode)
|
||||
stamp = 1747477800 + 28800
|
||||
crc = lambda data: zlib.crc32(data) & 0xFFFFFFFF
|
||||
lines = self.installed()
|
||||
self.assertEqual([
|
||||
f'bin/,-1;{stamp};0',
|
||||
f'bin/Backslash.txt,2;{stamp};{crc(b"bs")}',
|
||||
f'bin/Tool,4;{stamp};{crc(b"tool")}',
|
||||
f'data/A_file,3;{stamp};{crc(b"aaa")}',
|
||||
f'data/z_file,3;{stamp};{crc(b"zed")}',
|
||||
f'lib/libx.so,-2;{stamp};{crc(b"libx.so.1")}',
|
||||
f'lib/libx.so.1,4;{stamp};{crc(b"libx")}',
|
||||
'OSVER=-184',
|
||||
'VERSION=3',
|
||||
], lines[:-2])
|
||||
body = ''.join(line + '\n' for line in lines[:-2])
|
||||
self.assertEqual('SHA1=' + hashlib.sha1(body.encode()).hexdigest().upper(), lines[-2])
|
||||
self.assertEqual('', lines[-1])
|
||||
|
||||
def test_a_missing_package_leaves_no_record_so_steam_extracts_for_itself(self):
|
||||
self.prepare()
|
||||
(self.packages / 'b.zip.vz.2222_14').unlink()
|
||||
result = self.run_script()
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
|
||||
|
||||
def test_a_corrupt_package_leaves_no_record(self):
|
||||
self.prepare()
|
||||
packed = (self.packages / 'b.zip.vz.2222_14').read_bytes()
|
||||
(self.packages / 'b.zip.vz.2222_14').write_bytes(packed[:-12] + b'\0' * 12)
|
||||
self.assertNotEqual(0, self.run_script().returncode)
|
||||
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
|
||||
|
||||
|
||||
def package_with(self, entries):
|
||||
(self.packages / 'a.zip.1111').write_bytes(zip_bytes(entries))
|
||||
self.write_manifest({'a_all': {'file': 'a.zip.1111', 'size': 1, 'sha2': '00'}})
|
||||
|
||||
def test_a_path_that_leaves_the_steam_root_is_refused(self):
|
||||
stamp = (2025, 5, 17, 10, 30, 0)
|
||||
for name in ('../outside', '/abs/outside', 'a/../../outside'):
|
||||
with self.subTest(name=name):
|
||||
self.package_with([(name, b'x', 0o100644, stamp)])
|
||||
self.assertNotEqual(0, self.run_script().returncode)
|
||||
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
|
||||
self.assertFalse((Path(self.temp.name) / 'outside').exists())
|
||||
|
||||
def test_a_file_cannot_be_written_through_a_symlink_that_leaves_the_steam_root(self):
|
||||
stamp = (2025, 5, 17, 10, 30, 0)
|
||||
target = Path(self.temp.name) / 'elsewhere'
|
||||
target.mkdir()
|
||||
self.package_with([('link', str(target).encode(), 0o120777, stamp), ('link/file', b'x', 0o100644, stamp)])
|
||||
self.assertNotEqual(0, self.run_script().returncode)
|
||||
self.assertFalse((target / 'file').exists())
|
||||
|
||||
def test_a_symlink_inside_the_steam_root_still_carries_files(self):
|
||||
stamp = (2025, 5, 17, 10, 30, 0)
|
||||
self.package_with([('real/', b'', 0o40755, stamp), ('alias', b'real', 0o120777, stamp),
|
||||
('alias/file', b'x', 0o100644, stamp)])
|
||||
self.assertEqual(0, self.run_script().returncode)
|
||||
self.assertEqual(b'x', (self.steam / 'real/file').read_bytes())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,6 +1,7 @@
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
@@ -20,7 +21,15 @@ def load(name):
|
||||
shortcuts = load('droiddeck-steam-shortcuts')
|
||||
|
||||
APPID = 0x87654321
|
||||
GUEST = '/root/Games/PC/Example'
|
||||
GUEST = os.path.join(tempfile.mkdtemp(prefix='droiddeck-shortcuts-'), 'Games/PC/Example')
|
||||
|
||||
|
||||
def installed(*paths):
|
||||
"""Creates the files the writer checks, so a Steam edit to one of them is kept."""
|
||||
for path in paths:
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(path).touch()
|
||||
return paths[0]
|
||||
|
||||
|
||||
class ShortcutsTest(unittest.TestCase):
|
||||
@@ -34,7 +43,7 @@ class ShortcutsTest(unittest.TestCase):
|
||||
self.listing = self.root / 'added-games.json'
|
||||
|
||||
def game(self, exe='Example.exe', seen=0, appid=APPID, name='Example'):
|
||||
path = GUEST + '/' + exe
|
||||
path = installed(GUEST + '/' + exe)
|
||||
return dict(name=name, exe=path, folder=GUEST, dir=path.rsplit('/', 1)[0], appid=appid, seen=seen)
|
||||
|
||||
def run_writer(self, *games):
|
||||
@@ -54,10 +63,32 @@ class ShortcutsTest(unittest.TestCase):
|
||||
if value['appid'] & 0xFFFFFFFF == appid:
|
||||
value.update(fields)
|
||||
path.write_bytes(shortcuts.write({'shortcuts': data}))
|
||||
if fields.get('Exe'):
|
||||
target = Path(shortcuts.unquoted(fields['Exe']))
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.touch()
|
||||
|
||||
def record(self):
|
||||
return json.loads((self.config / shortcuts.RECORD).read_text())
|
||||
|
||||
def patched(self, **constants):
|
||||
for name, value in constants.items():
|
||||
old = getattr(shortcuts, name)
|
||||
setattr(shortcuts, name, value)
|
||||
self.addCleanup(setattr, shortcuts, name, old)
|
||||
|
||||
def merge_target(self, exe, **edits):
|
||||
"""Runs merge against a Steam-edited target, with the app's exe recorded as the base."""
|
||||
fresh = shortcuts.shortcut(self.game())
|
||||
current = dict(fresh, Exe=exe, **edits)
|
||||
state = {
|
||||
'app': {field: fresh[field] for field in shortcuts.FIELDS},
|
||||
'steam': {field: current.get(field, '') for field in ('AppName', 'Exe', 'StartDir', 'LaunchOptions')},
|
||||
'rev': 1,
|
||||
}
|
||||
entry, _ = shortcuts.merge(fresh, current, state, 0)
|
||||
return entry
|
||||
|
||||
def test_settings_changed_in_steam_survive_its_restart(self):
|
||||
self.run_writer(self.game())
|
||||
edits = dict(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s"' % GUEST, LaunchOptions='DXVK_HUD=1 %command%',
|
||||
@@ -82,6 +113,68 @@ class ShortcutsTest(unittest.TestCase):
|
||||
self.run_writer(self.game())
|
||||
self.assertEqual(1, self.record()['games'][str(APPID)]['rev'])
|
||||
|
||||
def test_a_steam_target_whose_file_is_gone_goes_back_to_the_apps(self):
|
||||
self.run_writer(self.game())
|
||||
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST)
|
||||
Path(shortcuts.unquoted('"%s/bin/Other.exe"' % GUEST)).unlink()
|
||||
entry = self.run_writer(self.game())[APPID]
|
||||
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
|
||||
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
|
||||
self.assertEqual('"%s/Example.exe"' % GUEST, self.record()['games'][str(APPID)]['steam']['Exe'])
|
||||
|
||||
def test_a_steam_target_whose_internal_folder_is_gone_goes_back_to_the_apps(self):
|
||||
games = self.root / 'games'
|
||||
(games / 'Stores').mkdir(parents=True)
|
||||
self.patched(INTERNAL_ROOTS=(str(games / 'Stores'),))
|
||||
entry = self.merge_target('"%s/old-version/Other.exe"' % (games / 'Stores'), StartDir='"%s/data"' % GUEST)
|
||||
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
|
||||
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
|
||||
|
||||
def test_a_steam_target_on_an_unmounted_card_is_kept(self):
|
||||
card = self.root / 'card'
|
||||
card.mkdir()
|
||||
self.patched(REMOVABLE_ROOTS=(str(card),))
|
||||
entry = self.merge_target('"%s/steamapps/common/Other.exe"' % card)
|
||||
self.assertEqual('"%s/steamapps/common/Other.exe"' % card, entry['Exe'])
|
||||
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
|
||||
|
||||
def test_a_steam_target_under_a_bare_card_mountpoint_is_kept(self):
|
||||
card = self.root / 'card'
|
||||
card.mkdir()
|
||||
self.patched(REMOVABLE_ROOTS=(str(card),))
|
||||
entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST)
|
||||
self.assertEqual('"%s/Other.exe"' % card, entry['Exe'])
|
||||
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
|
||||
|
||||
def test_a_steam_target_is_classified_by_its_resolved_path(self):
|
||||
games = self.root / 'games'
|
||||
stores = games / 'Stores'
|
||||
stores.mkdir(parents=True)
|
||||
card = self.root / 'card'
|
||||
card.mkdir()
|
||||
self.patched(INTERNAL_ROOTS=(str(stores),), REMOVABLE_ROOTS=(str(card),))
|
||||
target = '"%s/../../card/Other.exe"' % stores
|
||||
entry = self.merge_target(target, StartDir='"%s/data"' % GUEST)
|
||||
self.assertEqual(target, entry['Exe'])
|
||||
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
|
||||
|
||||
def test_a_steam_target_under_a_bare_store_mountpoint_is_kept(self):
|
||||
stores = self.root / 'stores'
|
||||
mount = stores / 'abcd1234'
|
||||
mount.mkdir(parents=True)
|
||||
self.patched(REMOVABLE_FAMILIES=(str(stores),))
|
||||
entry = self.merge_target('"%s/Other.exe"' % mount, StartDir='"%s/data"' % GUEST)
|
||||
self.assertEqual('"%s/Other.exe"' % mount, entry['Exe'])
|
||||
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
|
||||
|
||||
def test_a_steam_target_under_a_mounted_card_goes_back_to_the_apps(self):
|
||||
card = self.root / 'card'
|
||||
(card / 'steamapps').mkdir(parents=True)
|
||||
self.patched(REMOVABLE_ROOTS=(str(card),))
|
||||
entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST)
|
||||
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
|
||||
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
|
||||
|
||||
def test_the_app_taking_steams_target_keeps_steams_start_in(self):
|
||||
self.run_writer(self.game())
|
||||
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST)
|
||||
|
||||
@@ -16,6 +16,8 @@ initialize_native_resolution = MODULE['initialize_native_resolution']
|
||||
NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION']
|
||||
seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game']
|
||||
initialize_screensaver = MODULE['initialize_screensaver']
|
||||
seed_bouncing_logo = MODULE['seed_bouncing_logo']
|
||||
initialize_screensaver_choice = MODULE['initialize_screensaver_choice']
|
||||
|
||||
|
||||
class SteamUiScaleTest(unittest.TestCase):
|
||||
@@ -182,6 +184,16 @@ class SteamScreensaverTest(unittest.TestCase):
|
||||
self.assertEqual('0', screensaver.get('WhileInGame'))
|
||||
self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated)
|
||||
|
||||
def test_fresh_client_gets_the_bouncing_logo(self):
|
||||
self.assertTrue(initialize_screensaver_choice(self.root))
|
||||
screensaver = parse(self.config.read_text()).get('InstallConfigStore').get('Customization').get('Screensaver')
|
||||
self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver'))
|
||||
self.assertTrue(self.config.with_name('droiddeck-screensaver-choice-initialized').exists())
|
||||
|
||||
def test_a_screensaver_already_picked_is_kept(self):
|
||||
text = '"InstallConfigStore" { "Customization" { "Screensaver" { "CurrentScreensaver" "other" } } }'
|
||||
self.assertEqual((text, False), seed_bouncing_logo(text))
|
||||
|
||||
def test_users_choice_is_kept(self):
|
||||
text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }'
|
||||
self.assertEqual((text, False), seed_no_screensaver_in_game(text))
|
||||
|
||||
@@ -113,12 +113,12 @@ int main(void) {
|
||||
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
|
||||
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14;
|
||||
uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
|
||||
if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15;
|
||||
if (bpl != 4096 || size != 4096 * 2304 * 3 / 2) return 15;
|
||||
r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF };
|
||||
if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16;
|
||||
int out[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 };
|
||||
struct create_dumb c = { .height = 2304, .width = 4096, .bpp = 16 };
|
||||
if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17;
|
||||
struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC };
|
||||
if (drm_ioctl(card, 0xc00c642d, &h)) return 18;
|
||||
@@ -148,7 +148,7 @@ int main(void) {
|
||||
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp };
|
||||
if (call(VIDIOC_DQBUF, &cb)) return 25;
|
||||
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0);
|
||||
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size);
|
||||
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 2304], cp.bytesused == size);
|
||||
munmap(m, size);
|
||||
pf = (struct pollfd){ .fd = vfd, .events = 0x306 };
|
||||
if (poll(&pf, 1, 0) != 1) return 26;
|
||||
@@ -166,7 +166,7 @@ int main(void) {
|
||||
size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
|
||||
r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF };
|
||||
if (call(VIDIOC_REQBUFS, &r)) return 31;
|
||||
struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 };
|
||||
struct create_dumb big = { .height = 2304, .width = 4096, .bpp = 16 };
|
||||
if (drm_ioctl(card, 0xc02064b2, &big)) return 32;
|
||||
struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC };
|
||||
if (drm_ioctl(card, 0xc00c642d, &bh)) return 33;
|
||||
@@ -183,7 +183,7 @@ int main(void) {
|
||||
struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp };
|
||||
if (call(VIDIOC_DQBUF, &db)) return 37;
|
||||
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
|
||||
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]);
|
||||
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]);
|
||||
dd_vdec_closed(vfd);
|
||||
return 0;
|
||||
}
|
||||
@@ -261,7 +261,7 @@ class VdecEmulatorTest(unittest.TestCase):
|
||||
self.assertEqual(done.stdout.split('\n')[:6],
|
||||
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
|
||||
self.assertEqual([c[1:6] for c in server.configs],
|
||||
[(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)])
|
||||
[(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)])
|
||||
self.assertEqual([p[:3] for p in server.packets],
|
||||
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
VDEC = ROOT / 'tools/linuxfs/preload/vdec.c'
|
||||
|
||||
|
||||
class Bits:
|
||||
def __init__(self):
|
||||
self.bits = []
|
||||
|
||||
def u(self, value, count):
|
||||
self.bits += [(value >> (count - 1 - i)) & 1 for i in range(count)]
|
||||
|
||||
def ue(self, value):
|
||||
value += 1
|
||||
length = value.bit_length()
|
||||
self.u(0, length - 1)
|
||||
self.u(value, length)
|
||||
|
||||
def bytes(self):
|
||||
bits = self.bits + [1]
|
||||
while len(bits) % 8:
|
||||
bits.append(0)
|
||||
raw = bytes(int(''.join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8))
|
||||
out = bytearray()
|
||||
for i, byte in enumerate(raw):
|
||||
if len(out) >= 2 and out[-1] == 0 and out[-2] == 0 and byte <= 3:
|
||||
out.append(3)
|
||||
out.append(byte)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def sps(width_mbs, height_units, profile=100, frame_mbs_only=1, poc_type=2):
|
||||
b = Bits()
|
||||
b.u(profile, 8)
|
||||
b.u(0, 8)
|
||||
b.u(51, 8)
|
||||
b.ue(0)
|
||||
if profile in (100, 110, 122, 244):
|
||||
b.ue(1)
|
||||
b.ue(0)
|
||||
b.ue(0)
|
||||
b.u(0, 1)
|
||||
b.u(0, 1)
|
||||
b.ue(0)
|
||||
b.ue(poc_type)
|
||||
if poc_type == 0:
|
||||
b.ue(4)
|
||||
b.ue(1)
|
||||
b.u(0, 1)
|
||||
b.ue(width_mbs - 1)
|
||||
b.ue(height_units - 1)
|
||||
b.u(frame_mbs_only, 1)
|
||||
if not frame_mbs_only:
|
||||
b.u(0, 1)
|
||||
b.u(1, 1)
|
||||
b.u(0, 1)
|
||||
return b'\x00\x00\x00\x01\x67' + b.bytes() + b'\x00\x00\x00\x01\x65\x88\x84\x00'
|
||||
|
||||
|
||||
def hevc_sps(width, height, sub_layers_minus1=0):
|
||||
b = Bits()
|
||||
b.u(0, 4)
|
||||
b.u(sub_layers_minus1, 3)
|
||||
b.u(1, 1)
|
||||
b.u(0, 88)
|
||||
b.u(93, 8)
|
||||
for _ in range(sub_layers_minus1):
|
||||
b.u(0, 2)
|
||||
if sub_layers_minus1:
|
||||
for _ in range(sub_layers_minus1, 8):
|
||||
b.u(0, 2)
|
||||
b.ue(0)
|
||||
b.ue(1)
|
||||
b.ue(width)
|
||||
b.ue(height)
|
||||
b.u(0, 1)
|
||||
return b'\x00\x00\x00\x01\x42\x01' + b.bytes() + b'\x00\x00\x00\x01\x26\x01\xaf'
|
||||
|
||||
|
||||
DRIVER = r'''
|
||||
#include "vdec.c"
|
||||
#include <stdio.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
FILE *f = fopen(argv[1], "rb");
|
||||
static uint8_t data[4096];
|
||||
size_t n = fread(data, 1, sizeof data, f);
|
||||
uint32_t w = 0, h = 0;
|
||||
int rc = argc > 2 ? vd_stream_size_h265(data, n, &w, &h) : vd_stream_size_h264(data, n, &w, &h);
|
||||
printf("%d %u %u\n", rc, w, h);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class StreamSizeTest(unittest.TestCase):
|
||||
def run_driver(self, data, hevc=False):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
(tmp / 'driver.c').write_text(DRIVER)
|
||||
(tmp / 'stream.bin').write_bytes(data)
|
||||
exe = tmp / 'driver'
|
||||
subprocess.run(['gcc', '-std=gnu11', '-DDD_VDEC_ANY_ARCH', '-I', str(VDEC.parent), '-o', str(exe), str(tmp / 'driver.c'), str(VDEC.parent / 'venc.c'), '-ldl', '-lpthread'],
|
||||
check=True, capture_output=True, text=True)
|
||||
return subprocess.run([str(exe), str(tmp / 'stream.bin')] + (['h265'] if hevc else []), check=True, capture_output=True, text=True).stdout.split()
|
||||
|
||||
def test_reads_an_ultrawide_stream_size(self):
|
||||
self.assertEqual(['0', '3440', '1440'], self.run_driver(sps(215, 90)))
|
||||
|
||||
def test_reads_a_small_stream_size(self):
|
||||
self.assertEqual(['0', '800', '464'], self.run_driver(sps(50, 29)))
|
||||
|
||||
def test_interlaced_streams_double_the_height(self):
|
||||
self.assertEqual(['0', '1920', '1088'], self.run_driver(sps(120, 34, frame_mbs_only=0)))
|
||||
|
||||
def test_baseline_profile_has_no_chroma_fields(self):
|
||||
self.assertEqual(['0', '1280', '720'], self.run_driver(sps(80, 45, profile=66)))
|
||||
|
||||
def test_emulation_prevention_bytes_are_removed(self):
|
||||
self.assertEqual(['0', '256', '256'], self.run_driver(sps(16, 16, profile=66)))
|
||||
|
||||
def test_reads_an_h265_stream_size(self):
|
||||
self.assertEqual(['0', '3440', '1440'], self.run_driver(hevc_sps(3440, 1440), hevc=True))
|
||||
|
||||
def test_h265_sizes_round_up_to_sixteen(self):
|
||||
self.assertEqual(['0', '1920', '1088'], self.run_driver(hevc_sps(1920, 1080, sub_layers_minus1=2), hevc=True))
|
||||
|
||||
def test_a_truncated_sps_is_rejected(self):
|
||||
self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x67\x64\x00\x33\xac\xb4\x02\x80\x2d')[0])
|
||||
|
||||
def test_a_stream_without_an_sps_is_left_alone(self):
|
||||
self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x65\x88\x84\x00\x00\x01')[0])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -15,8 +15,11 @@ int main(int argc, char **argv) {
|
||||
const char *mode = getenv("TEST_NODE_MODE_CHILD");
|
||||
static char node[64];
|
||||
snprintf(node, sizeof node, "ELECTRON_RUN_AS_NODE=%s", mode ? mode : "");
|
||||
char *node_env[] = {node, NULL};
|
||||
char *plain_env[] = {"PATH=/usr/bin", NULL};
|
||||
const char *x = getenv("TEST_DISPLAY");
|
||||
static char display[64];
|
||||
snprintf(display, sizeof display, "DISPLAY=%s", x ? x : "");
|
||||
char *node_env[] = {node, x ? display : NULL, NULL};
|
||||
char *plain_env[] = {"PATH=/usr/bin", x ? display : NULL, NULL};
|
||||
char *const *envp = mode ? node_env : plain_env;
|
||||
char *const *out = dd_webhelper_argv(argv[1], argv + 1, (char *const *)envp);
|
||||
for (int i = 0; out[i]; i++) printf("%s\n", out[i]);
|
||||
@@ -42,8 +45,10 @@ class WebhelperPreloadTest(unittest.TestCase):
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def argv(self, *args, spec=None, node_child=False, parent_node=False):
|
||||
env = {k: v for k, v in os.environ.items() if k != "DD_WEBHELPER_ARGS"}
|
||||
def argv(self, *args, spec=None, node_child=False, parent_node=False, display=None):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("DD_WEBHELPER_ARGS", "TEST_DISPLAY")}
|
||||
if display is not None:
|
||||
env["TEST_DISPLAY"] = display
|
||||
env.pop("ELECTRON_RUN_AS_NODE", None)
|
||||
if spec is not None:
|
||||
env["DD_WEBHELPER_ARGS"] = spec
|
||||
@@ -104,6 +109,50 @@ class WebhelperPreloadTest(unittest.TestCase):
|
||||
chrome = self.chromium("chromium-parent-mode", "chrome")
|
||||
self.assertEqual(self.argv(chrome, parent_node=True), [chrome, "--no-sandbox"])
|
||||
|
||||
def test_a_link_to_an_electron_app_gets_the_sandbox_flag(self):
|
||||
app = self.chromium("vesktop", "vesktop")
|
||||
link = self.tmp / "bin-vesktop"
|
||||
link.symlink_to(app)
|
||||
self.assertEqual(self.argv(str(link), "%U"), [str(link), "--no-sandbox", "%U"])
|
||||
|
||||
def test_an_app_whose_sandbox_helper_is_one_folder_up_gets_the_flag(self):
|
||||
root = self.tmp / "nested"
|
||||
(root / "bin").mkdir(parents=True)
|
||||
(root / "chrome-sandbox").touch()
|
||||
(root / "bin/app").touch()
|
||||
self.assertEqual(self.argv(str(root / "bin/app")), [str(root / "bin/app"), "--no-sandbox"])
|
||||
|
||||
def test_a_chromium_app_starting_a_program_from_its_own_folder_leaves_it_alone(self):
|
||||
handler = self.chromium("chrome-app", "chrome_crashpad_handler")
|
||||
browser = self.tmp / "chrome-app/chrome"
|
||||
shutil.copy(self.program, browser)
|
||||
out = subprocess.run([str(browser), handler, "--database=/tmp/x"], env={"TEST_DISPLAY": ":0"},
|
||||
capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
self.assertEqual([handler, "--database=/tmp/x"], out)
|
||||
|
||||
def test_a_chromium_app_starting_another_chromium_app_still_flags_it(self):
|
||||
other = self.chromium("other-app", "chrome")
|
||||
editor = self.tmp / "editor-app/code"
|
||||
self.chromium("editor-app", "code")
|
||||
shutil.copy(self.program, editor)
|
||||
out = subprocess.run([str(editor), other], env={}, capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
self.assertEqual([other, "--no-sandbox"], out)
|
||||
|
||||
def test_with_an_x_display_chromium_apps_use_x11(self):
|
||||
chrome = self.chromium("chromium-x11", "chrome")
|
||||
self.assertEqual(self.argv(chrome, "--new-window", display=":0"),
|
||||
[chrome, "--no-sandbox", "--ozone-platform=x11", "--new-window"])
|
||||
self.assertEqual(self.argv(chrome, "--no-sandbox", display=":0"),
|
||||
[chrome, "--ozone-platform=x11", "--no-sandbox"])
|
||||
|
||||
def test_an_explicit_platform_and_sandbox_choice_is_kept(self):
|
||||
chrome = self.chromium("chromium-own-flags", "chrome")
|
||||
own = [chrome, "--no-sandbox", "--ozone-platform=wayland"]
|
||||
self.assertEqual(self.argv(*own, display=":0"), own)
|
||||
|
||||
def test_other_programs_with_an_x_display_are_left_alone(self):
|
||||
self.assertEqual(self.argv("/usr/bin/steam", display=":0"), ["/usr/bin/steam"])
|
||||
|
||||
def test_stock_turns_it_off(self):
|
||||
args = [WEBHELPER, "--enable-features=A"]
|
||||
self.assertEqual(self.argv(*args, spec="stock"), args)
|
||||
|
||||
@@ -123,7 +123,8 @@ static int64_t now_ns(void) { return 0; }
|
||||
static struct surface *g_hud_surface, *g_hud_shm;
|
||||
static int64_t g_hud_shm_ns, g_hud_last_ns;
|
||||
static int g_hud_new;
|
||||
static void droiddeck_on_game_frame(void) {}
|
||||
static void __attribute__((unused)) droiddeck_on_game_frame(void) {}
|
||||
static void __attribute__((unused)) droiddeck_on_compositor_frame(void) {}
|
||||
struct client_info { int asked_feedback, shm_frames; };
|
||||
struct wl_shm_buffer { int w, h, stride; const void *data; };
|
||||
#define WL_SHM_FORMAT_ARGB8888 0
|
||||
|
||||
Reference in new issue
Block a user