chore: merge main into feat/lse-emu

This commit is contained in:
Kurt Himebauch committed 2026-11-24 00:23:06 -05:00
commit 83f9067a51
609 files changed
+46314 -8272

No files matched your search

+548
View File
@@ -0,0 +1,548 @@
#include "mali_compat.h"
#include <spirv/unified1/spirv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OPCODE(word) ((word) & 0xffffu)
#define LENGTH(word) ((word) >> 16)
static const uint32_t newer[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000a, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000,
0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006, 0x00000003,
0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x00040020, 0x00000007, 0x00000006,
0x00000005, 0x0004003b, 0x00000007, 0x00000003, 0x00000006, 0x00030021, 0x00000008, 0x00000004,
0x00050036, 0x00000004, 0x00000001, 0x00000000, 0x00000008, 0x000200f8, 0x00000009, 0x00011140,
0x00010038,
};
static const size_t newer_count = sizeof(newer) / sizeof(uint32_t);
static const uint32_t readonly_parameter[] = {
SpvMagicNumber, 0x00010600, 0, 13, 0,
(2u << 16) | SpvOpCapability, SpvCapabilityShader,
(3u << 16) | SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450,
(5u << 16) | SpvOpEntryPoint, SpvExecutionModelFragment, 7, 0x6e69616d, 0,
(3u << 16) | SpvOpExecutionMode, 7, SpvExecutionModeOriginUpperLeft,
(3u << 16) | SpvOpDecorate, 3, SpvDecorationBlock,
(5u << 16) | SpvOpMemberDecorate, 3, 0, SpvDecorationOffset, 0,
(3u << 16) | SpvOpDecorate, 10, SpvDecorationNonWritable,
(4u << 16) | SpvOpDecorate, 12, SpvDecorationDescriptorSet, 0,
(4u << 16) | SpvOpDecorate, 12, SpvDecorationBinding, 0,
(2u << 16) | SpvOpTypeVoid, 1,
(3u << 16) | SpvOpTypeFloat, 2, 32,
(3u << 16) | SpvOpTypeStruct, 3, 2,
(4u << 16) | SpvOpTypePointer, 4, SpvStorageClassStorageBuffer, 3,
(4u << 16) | SpvOpVariable, 4, 12, SpvStorageClassStorageBuffer,
(3u << 16) | SpvOpTypeFunction, 5, 1,
(4u << 16) | SpvOpTypeFunction, 6, 1, 4,
(5u << 16) | SpvOpFunction, 1, 7, 0, 5,
(2u << 16) | SpvOpLabel, 8,
(1u << 16) | SpvOpReturn,
(1u << 16) | SpvOpFunctionEnd,
(5u << 16) | SpvOpFunction, 1, 9, 0, 6,
(3u << 16) | SpvOpFunctionParameter, 4, 10,
(2u << 16) | SpvOpLabel, 11,
(1u << 16) | SpvOpReturn,
(1u << 16) | SpvOpFunctionEnd,
};
static const uint32_t older[] = {
0x07230203, 0x00010300, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013,
0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, 0x00000003, 0x00000004,
0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, 0x00000003, 0x00050036,
0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, 0x000100fd, 0x00010038,
};
static const size_t older_count = sizeof(older) / sizeof(uint32_t);
static const uint32_t capability[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x00000046, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006,
0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007,
0x000100fd, 0x00010038,
};
static const size_t capability_count = sizeof(capability) / sizeof(uint32_t);
static const uint32_t memory[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x000014e1, 0x0003000e, 0x00000000, 0x00000003, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006,
0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007,
0x000100fd, 0x00010038,
};
static const size_t memory_count = sizeof(memory) / sizeof(uint32_t);
static const uint32_t zinklike[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000017, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000,
0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040015, 0x00000006, 0x00000020,
0x00000001, 0x00040017, 0x00000007, 0x00000005, 0x00000004, 0x0003001e, 0x00000008, 0x00000007,
0x00040020, 0x00000009, 0x00000003, 0x00000005, 0x0004003b, 0x00000009, 0x00000002, 0x00000003,
0x00040020, 0x0000000a, 0x00000006, 0x00000008, 0x00040020, 0x0000000b, 0x00000007, 0x00000008,
0x0004003b, 0x0000000a, 0x00000003, 0x00000006, 0x00040020, 0x0000000c, 0x00000006, 0x00000005,
0x00040020, 0x0000000d, 0x00000007, 0x00000005, 0x0004002b, 0x00000005, 0x0000000e, 0x3f800000,
0x0004002b, 0x00000006, 0x0000000f, 0x00000000, 0x00030021, 0x00000010, 0x00000004, 0x00050036,
0x00000004, 0x00000001, 0x00000000, 0x00000010, 0x000200f8, 0x00000011, 0x0004003b, 0x0000000b,
0x00000012, 0x00000007, 0x00060041, 0x0000000d, 0x00000013, 0x00000012, 0x0000000f, 0x0000000f,
0x0003003e, 0x00000013, 0x0000000e, 0x0004003d, 0x00000005, 0x00000014, 0x00000013, 0x00070050,
0x00000007, 0x00000015, 0x00000014, 0x00000014, 0x00000014, 0x00000014, 0x00040041, 0x00000009,
0x00000016, 0x00000002, 0x0003003e, 0x00000016, 0x00000014, 0x000100fd, 0x00010038,
};
static const size_t zinklike_count = sizeof(zinklike) / sizeof(uint32_t);
static const uint32_t nonuniform[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x000014b5, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004,
0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001,
0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd,
0x00010038,
};
static const size_t nonuniform_count = sizeof(nonuniform) / sizeof(uint32_t);
static const uint32_t nonuniform_extension[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
0x000014b5, 0x0008000a, 0x5f565053, 0x5f545845, 0x63736564, 0x74706972, 0x695f726f, 0x7865646e,
0x00676e69, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d,
0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e,
0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005,
0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004,
0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001,
0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd,
0x00010038,
};
static const size_t nonuniform_extension_count = sizeof(nonuniform_extension) / sizeof(uint32_t);
static const uint32_t select_struct[] = {
0x07230203, 0x00010600, 0x00070000, 0x00000011, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013,
0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x0004001e, 0x00000006,
0x00000005, 0x00000005, 0x00040020, 0x00000007, 0x00000003, 0x00000005, 0x0004003b, 0x00000007,
0x00000002, 0x00000003, 0x0004002b, 0x00000005, 0x00000008, 0x3f800000, 0x0004002b, 0x00000005,
0x00000009, 0x00000000, 0x00030029, 0x00000004, 0x0000000a, 0x0005002c, 0x00000006, 0x0000000b,
0x00000008, 0x00000009, 0x0005002c, 0x00000006, 0x0000000c, 0x00000009, 0x00000008, 0x00030021,
0x0000000d, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x0000000d, 0x000200f8,
0x0000000e, 0x000600a9, 0x00000006, 0x0000000f, 0x0000000a, 0x0000000b, 0x0000000c, 0x00050051,
0x00000005, 0x00000010, 0x0000000f, 0x00000000, 0x0003003e, 0x00000002, 0x00000010, 0x000100fd,
0x00010038,
};
static const size_t select_struct_count = sizeof(select_struct) / sizeof(uint32_t);
static const uint32_t select_scalar[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000d, 0x00000000, 0x00020011, 0x00000001, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002,
0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013,
0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006,
0x00000003, 0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x0004002b, 0x00000005,
0x00000007, 0x3f800000, 0x0004002b, 0x00000005, 0x00000008, 0x00000000, 0x00030029, 0x00000004,
0x00000009, 0x00030021, 0x0000000a, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000,
0x0000000a, 0x000200f8, 0x0000000b, 0x000600a9, 0x00000005, 0x0000000c, 0x00000009, 0x00000007,
0x00000008, 0x0003003e, 0x00000002, 0x0000000c, 0x000100fd, 0x00010038,
};
static const size_t select_scalar_count = sizeof(select_scalar) / sizeof(uint32_t);
static const uint32_t nonsemantic[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000b,
0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003,
0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003,
0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020,
0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b,
0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005,
0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b,
0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038,
};
static const size_t nonsemantic_count = sizeof(nonsemantic) / sizeof(uint32_t);
static const uint32_t nonsemantic_extension[] = {
0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000a,
0x5f565053, 0x5f52484b, 0x5f6e6f6e, 0x616d6573, 0x6369746e, 0x666e695f, 0x0000006f, 0x0008000b,
0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e,
0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003,
0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003,
0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020,
0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b,
0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005,
0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b,
0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038,
};
static const size_t nonsemantic_extension_count = sizeof(nonsemantic_extension) / sizeof(uint32_t);
static int failures;
static void check(int condition, const char *what)
{
if (!condition) {
printf("FAIL: %s\n", what);
failures++;
}
}
static size_t count_opcodes(const uint32_t *words, size_t count, uint32_t opcode)
{
size_t found = 0;
for (size_t i = 5; i < count; i += LENGTH(words[i])) {
if (OPCODE(words[i]) == opcode)
found++;
}
return found;
}
static size_t interface_size(const uint32_t *words, size_t count)
{
for (size_t i = 5; i < count; i += LENGTH(words[i])) {
if (OPCODE(words[i]) != SpvOpEntryPoint)
continue;
size_t length = LENGTH(words[i]);
size_t name = 3;
while (name < length) {
uint32_t word = words[i + name];
if (!(word & 0xff) || !(word & 0xff00) || !(word & 0xff0000) || !(word & 0xff000000))
break;
name++;
}
return length - (name + 1);
}
return 0;
}
static void write_module(const char *path, const struct spirv_code *code)
{
FILE *out = fopen(path, "wb");
if (!out) {
printf("FAIL: %s cannot be written\n", path);
failures++;
return;
}
fwrite(code->words, sizeof(uint32_t), code->count, out);
fclose(out);
}
static struct device test_device;
static int failed_allocations;
static bool fail_allocations;
static int driver_calls;
static bool chain_was_layer_owned;
static VkStructureType first_link;
static uint32_t driver_version;
static uint32_t driver_subgroup_size;
void *test_calloc(size_t count, size_t size)
{
if (fail_allocations) {
failed_allocations++;
return NULL;
}
if (size && count > SIZE_MAX / size)
return NULL;
size_t bytes = count * size;
void *memory = malloc(bytes > 0 ? bytes : 1);
if (memory)
memset(memory, 0, bytes);
return memory;
}
struct device *device_from_handle(const void *dispatchable)
{
return &test_device;
}
void layer_log(const char *format, ...)
{
}
void *map_get(const struct handle_map *map, uint64_t key)
{
return NULL;
}
void map_put(struct handle_map *map, uint64_t key, void *value)
{
}
void *map_remove(struct handle_map *map, uint64_t key)
{
return NULL;
}
static void read_stage(const VkPipelineShaderStageCreateInfo *stage, const void *app_chain)
{
driver_calls++;
chain_was_layer_owned = stage->pNext != app_chain;
first_link = stage->pNext ? ((const VkBaseInStructure *)stage->pNext)->sType : VK_STRUCTURE_TYPE_MAX_ENUM;
driver_version = 0;
driver_subgroup_size = 0;
for (const VkBaseInStructure *s = stage->pNext; s; s = s->pNext) {
if (s->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO)
driver_subgroup_size = ((const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo *)s)->requiredSubgroupSize;
if (s->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) {
const VkShaderModuleCreateInfo *info = (const VkShaderModuleCreateInfo *)s;
driver_version = spirv_version(info->pCode, info->codeSize / sizeof(uint32_t));
}
}
}
static const void *expected_chain;
static VkResult VKAPI_CALL driver_compute(VkDevice device, VkPipelineCache cache, uint32_t count,
const VkComputePipelineCreateInfo *infos,
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
{
read_stage(&infos[0].stage, expected_chain);
return VK_SUCCESS;
}
static VkResult VKAPI_CALL driver_graphics(VkDevice device, VkPipelineCache cache, uint32_t count,
const VkGraphicsPipelineCreateInfo *infos,
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
{
read_stage(&infos[0].pStages[0], expected_chain);
return VK_SUCCESS;
}
static const VkShaderModuleCreateInfo app_module = {
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = sizeof(newer),
.pCode = newer,
};
static const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo app_subgroup = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO,
.pNext = &app_module,
.requiredSubgroupSize = 16,
};
static const VkApplicationInfo app_unknown = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pNext = &app_module,
};
static const VkPipelineShaderStageCreateInfo app_fragment = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.pNext = &app_subgroup,
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
.pName = "main",
};
static void check_pipelines(void)
{
VkDevice device = (VkDevice)&test_device;
VkPipeline pipeline = VK_NULL_HANDLE;
pthread_mutex_init(&test_device.lock, NULL);
test_device.CreateComputePipelines = driver_compute;
test_device.CreateGraphicsPipelines = driver_graphics;
VkComputePipelineCreateInfo compute = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.pNext = &app_subgroup,
.stage = VK_SHADER_STAGE_COMPUTE_BIT,
.pName = "main"},
};
expected_chain = &app_subgroup;
check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS,
"a compute pipeline with inline code behind another structure is created");
check(chain_was_layer_owned, "the compute stage gets the layer's own chain");
check(first_link == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO,
"the compute stage keeps its chain order");
check(driver_subgroup_size == 16, "the compute stage keeps its required subgroup size");
check(driver_version == 0x00010300u, "the compute stage's inline code reaches the driver as SPIR-V 1.3");
check(app_module.pCode == newer && app_module.codeSize == sizeof(newer),
"the application's shader module create info is untouched");
check(compute.stage.pNext == &app_subgroup, "the application's compute stage is untouched");
compute.stage.pNext = &app_module;
expected_chain = &app_module;
check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS,
"a compute pipeline with inline code first in its chain is created");
check(chain_was_layer_owned && driver_version == 0x00010300u,
"inline code first in the chain reaches the driver as SPIR-V 1.3");
compute.stage.pNext = &app_unknown;
expected_chain = &app_unknown;
check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS,
"a compute pipeline behind an unknown structure is created");
check(!chain_was_layer_owned && driver_version == 0x00010600u,
"a chain the layer cannot copy reaches the driver as the application wrote it");
VkGraphicsPipelineCreateInfo graphics = {
.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
.stageCount = 1,
.pStages = &app_fragment,
};
expected_chain = &app_subgroup;
check(CreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics, NULL, &pipeline) == VK_SUCCESS,
"a graphics pipeline with inline code behind another structure is created");
check(chain_was_layer_owned && driver_subgroup_size == 16 && driver_version == 0x00010300u,
"the graphics stage reaches the driver capped with its chain intact");
check(app_fragment.pNext == &app_subgroup && graphics.pStages == &app_fragment,
"the application's graphics stages are untouched");
driver_calls = 0;
failed_allocations = 0;
fail_allocations = true;
VkPipeline compute_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2};
VkPipeline graphics_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2};
VkResult compute_result = CreateComputePipelines(device, VK_NULL_HANDLE, 2, &compute, NULL, compute_outputs);
VkResult graphics_result = CreateGraphicsPipelines(device, VK_NULL_HANDLE, 2, &graphics, NULL, graphics_outputs);
fail_allocations = false;
check(failed_allocations > 0, "the allocations were made to fail");
check(compute_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a compute pipeline without memory reports it");
check(graphics_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a graphics pipeline without memory reports it");
check(compute_outputs[0] == VK_NULL_HANDLE && compute_outputs[1] == VK_NULL_HANDLE,
"failed compute pipeline outputs are cleared");
check(graphics_outputs[0] == VK_NULL_HANDLE && graphics_outputs[1] == VK_NULL_HANDLE,
"failed graphics pipeline outputs are cleared");
check(driver_calls == 0, "the driver is not called without memory");
pthread_mutex_destroy(&test_device.lock);
}
int main(int argc, char **argv)
{
struct spirv_code capped = {0};
check(spirv_cap_version(newer, newer_count, &capped), "a SPIR-V 1.6 module is capped");
check(capped.words != NULL, "the capped module is there");
if (capped.words) {
check(capped.words[1] == 0x00010300u, "the capped module is SPIR-V 1.3");
check(interface_size(capped.words, capped.count) == 1,
"the entry point lists only the input and output variables");
check(count_opcodes(capped.words, capped.count, SpvOpKill) == 1, "the discard is an OpKill");
check(count_opcodes(capped.words, capped.count, SpvOpTerminateInvocation) == 0,
"no OpTerminateInvocation is left");
if (argc > 1)
write_module(argv[1], &capped);
free(capped.words);
}
struct spirv_code kept = {0};
check(!spirv_cap_version(older, older_count, &kept), "a SPIR-V 1.3 module is left alone");
check(kept.words == NULL, "the untouched module is not handed back");
check(!spirv_cap_version(capability, capability_count, &kept),
"a module with a capability from SPIR-V 1.5 is left alone");
check(!spirv_cap_version(memory, memory_count, &kept), "a module with the Vulkan memory model is left alone");
check(!spirv_cap_version(nonuniform, nonuniform_count, &kept),
"a module with ShaderNonUniform and no SPV_EXT_descriptor_indexing is left alone");
check(!spirv_cap_version(select_struct, select_struct_count, &kept),
"a module selecting a structure is left alone");
check(!spirv_cap_version(nonsemantic, nonsemantic_count, &kept),
"a module importing a NonSemantic set without SPV_KHR_non_semantic_info is left alone");
uint32_t private_readonly[sizeof(zinklike) / sizeof(uint32_t) + 3];
size_t declaration = 5;
while (OPCODE(zinklike[declaration]) != SpvOpTypeVoid)
declaration += LENGTH(zinklike[declaration]);
memcpy(private_readonly, zinklike, declaration * sizeof(uint32_t));
private_readonly[declaration] = (3u << 16) | SpvOpDecorate;
private_readonly[declaration + 1] = 3;
private_readonly[declaration + 2] = SpvDecorationNonWritable;
memcpy(private_readonly + declaration + 3, zinklike + declaration,
(zinklike_count - declaration) * sizeof(uint32_t));
check(!spirv_cap_version(private_readonly, zinklike_count + 3, &kept),
"a private NonWritable variable is left alone");
if (argc > 6) {
struct spirv_code source = {.words = private_readonly, .count = zinklike_count + 3};
write_module(argv[6], &source);
}
uint32_t converted[sizeof(zinklike) / sizeof(uint32_t) + 9];
size_t function = declaration;
while (OPCODE(zinklike[function]) != SpvOpFunction)
function += LENGTH(zinklike[function]);
memcpy(converted, zinklike, function * sizeof(uint32_t));
const uint32_t conversion[] = {(4u << 16) | SpvOpTypeInt, 23, 32, 0,
(5u << 16) | SpvOpSpecConstantOp, 23, 24, SpvOpUConvert, 15};
memcpy(converted + function, conversion, sizeof(conversion));
memcpy(converted + function + 9, zinklike + function, (zinklike_count - function) * sizeof(uint32_t));
converted[3] = 25;
check(!spirv_cap_version(converted, zinklike_count + 9, &kept),
"a specialization UConvert without its extension is left alone");
if (argc > 7) {
struct spirv_code source = {.words = converted, .count = zinklike_count + 9};
write_module(argv[7], &source);
}
check(kept.words == NULL, "no rejected module is handed back");
struct spirv_code extension = {0};
check(spirv_cap_version(nonuniform_extension, nonuniform_extension_count, &extension),
"a module declaring SPV_EXT_descriptor_indexing for ShaderNonUniform is capped");
if (extension.words) {
check(extension.words[1] == 0x00010300u, "the module with the extension is SPIR-V 1.3");
if (argc > 3)
write_module(argv[3], &extension);
free(extension.words);
}
struct spirv_code scalar = {0};
check(spirv_cap_version(select_scalar, select_scalar_count, &scalar), "a module selecting a scalar is capped");
if (scalar.words) {
check(count_opcodes(scalar.words, scalar.count, SpvOpSelect) == 1, "the scalar select is kept");
if (argc > 4)
write_module(argv[4], &scalar);
free(scalar.words);
}
struct spirv_code debug = {0};
check(spirv_cap_version(nonsemantic_extension, nonsemantic_extension_count, &debug),
"a module declaring SPV_KHR_non_semantic_info for its NonSemantic import is capped");
if (debug.words) {
check(debug.words[1] == 0x00010300u, "the module with the NonSemantic import is SPIR-V 1.3");
if (argc > 5)
write_module(argv[5], &debug);
free(debug.words);
}
struct spirv_code guest = {0};
check(spirv_cap_version(zinklike, zinklike_count, &guest), "a guest module with a private global is capped");
if (guest.words) {
check(guest.words[1] == 0x00010300u, "the guest module is SPIR-V 1.3");
check(interface_size(guest.words, guest.count) == 1,
"the guest module lists only the input and output variables");
check(count_opcodes(guest.words, guest.count, SpvOpFunction) == 1, "the guest module keeps its function");
if (argc > 2)
write_module(argv[2], &guest);
free(guest.words);
}
struct spirv_code parameter = {0};
size_t parameter_count = sizeof(readonly_parameter) / sizeof(uint32_t);
check(spirv_cap_version(readonly_parameter, parameter_count, &parameter),
"a NonWritable storage buffer parameter is capped");
if (parameter.words) {
check(count_opcodes(parameter.words, parameter.count, SpvOpFunctionParameter) == 1,
"the storage buffer parameter is preserved");
if (argc > 8)
write_module(argv[8], &parameter);
free(parameter.words);
}
uint32_t incompatible_parameter[sizeof(readonly_parameter) / sizeof(uint32_t)];
memcpy(incompatible_parameter, readonly_parameter, sizeof(readonly_parameter));
for (size_t i = 5; i < parameter_count; i += LENGTH(incompatible_parameter[i])) {
if (OPCODE(incompatible_parameter[i]) == SpvOpTypePointer) {
incompatible_parameter[i + 2] = SpvStorageClassPrivate;
check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept),
"a NonWritable Private parameter is left alone");
incompatible_parameter[i + 2] = SpvStorageClassFunction;
check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept),
"a NonWritable Function parameter is left alone");
}
}
check_pipelines();
if (failures)
printf("%d check(s) failed\n", failures);
else
printf("mali compat spirv ok\n");
return failures ? 1 : 0;
}
+318
View File
@@ -0,0 +1,318 @@
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "wayland-util.h"
void wl_list_init(struct wl_list *list) { list->prev = list->next = list; }
void wl_list_insert(struct wl_list *list, struct wl_list *elm) {
elm->prev = list;
elm->next = list->next;
list->next = elm;
elm->next->prev = elm;
}
void wl_list_remove(struct wl_list *elm) {
elm->prev->next = elm->next;
elm->next->prev = elm->prev;
elm->next = elm->prev = NULL;
}
int wl_list_empty(const struct wl_list *list) { return list->next == list; }
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
struct wl_resource { struct wl_list listeners; int acquired, releases, errors; };
struct dmabuf_buffer { int unused; };
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE };
struct surface {
struct wl_list link;
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
int64_t next_release_ns;
int releases_pending;
enum surface_role role;
struct surface *parent;
int sub_desync;
};
#define TFD_TIMER_ABSTIME 1
static struct wl_list g_surfaces;
static struct wl_list g_pending_releases;
static int g_release_timer_fd = 3;
static int g_fps_limit;
static int64_t g_refresh_ns = 8333333;
static int g_release_unpaced;
static int64_t g_now = 1000000000LL;
static int64_t g_armed;
static struct dmabuf_buffer g_buf;
static int64_t now_ns(void) { return g_now; }
static void perf_note_release(int64_t since) { (void)since; }
static int buffer_release_blocked(struct wl_resource *b) { (void)b; return 0; }
static int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *r, struct surface *s, int paced) {
(void)b; (void)r; (void)s; (void)paced;
return 0;
}
static void dmabuf_buffer_unref(struct dmabuf_buffer *b) { (void)b; }
static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) {
wl_list_insert(r->listeners.prev, &l->link);
}
static int timerfd_settime(int fd, int flags, const struct itimerspec *its, struct itimerspec *old) {
(void)fd; (void)flags; (void)old;
g_armed = (int64_t)its->it_value.tv_sec * 1000000000LL + its->it_value.tv_nsec;
return 0;
}
static void send_buffer_release(struct wl_resource *b) {
b->releases++;
if (b->acquired) b->acquired = 0;
else b->errors++;
}
#include "release.inc"
static void present(struct wl_resource *b) { b->acquired = 1; }
static void commit(struct surface *s, struct wl_resource *b) {
if (s->dmabuf != b) {
drop_dmabuf(s, 1);
if (b) {
pending_releases_cancel(b);
s->dmabuf = b;
s->dmabuf_buf = &g_buf;
wl_resource_add_destroy_listener(b, &s->dmabuf_destroy);
}
}
pending_releases_apply(s);
}
static void timer_fires(int64_t at) {
if (g_now < at) g_now = at;
release_due_buffers();
arm_release_timer();
}
static void surface_init(struct surface *s, enum surface_role role, struct surface *parent) {
memset(s, 0, sizeof(*s));
s->role = role;
s->parent = parent;
wl_list_insert(g_surfaces.prev, &s->link);
}
static void buffer_init(struct wl_resource *b) {
memset(b, 0, sizeof(*b));
wl_list_init(&b->listeners);
}
static void check(const struct wl_resource *b, int releases) {
if (b->releases != releases || b->errors) {
fprintf(stderr, "releases %d (want %d), released while not acquired %d\n", b->releases, releases, b->errors);
exit(1);
}
}
static void moved_between_planes(void) {
struct surface root, low, high;
struct wl_resource a, b, c;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&low, ROLE_SUBSURFACE, &root);
surface_init(&high, ROLE_SUBSURFACE, &root);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
present(&a); present(&b);
commit(&high, &a);
commit(&low, &b);
commit(&root, NULL);
present(&a); present(&b);
commit(&high, NULL);
timer_fires(g_now);
check(&a, 0);
commit(&low, &a);
timer_fires(g_now);
commit(&root, &b);
timer_fires(g_now + 100000000LL);
check(&a, 0);
check(&b, 0);
present(&c);
commit(&high, NULL);
commit(&low, NULL);
commit(&root, &c);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&b, 1);
check(&c, 0);
}
static void reattached_before_release(void) {
struct surface s;
struct wl_resource a, b, c;
surface_init(&s, ROLE_TOPLEVEL, NULL);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
g_fps_limit = 60;
present(&a); commit(&s, &a);
present(&b); commit(&s, &b);
present(&a); commit(&s, &a);
present(&c); commit(&s, &c);
timer_fires(g_now + 1000000000LL);
check(&a, 1);
check(&b, 1);
check(&c, 0);
}
static void desync_child_not_held(void) {
struct surface root, child;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&child, ROLE_SUBSURFACE, &root);
child.sub_desync = 1;
buffer_init(&a); buffer_init(&b);
present(&a); commit(&child, &a);
present(&b); commit(&child, &b);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&b, 0);
}
static void toplevel_pacing_kept(void) {
struct surface s;
struct wl_resource a, b, c;
surface_init(&s, ROLE_TOPLEVEL, NULL);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
g_fps_limit = 60;
const int64_t interval = 1000000000LL / 60;
present(&a); commit(&s, &a);
present(&b); commit(&s, &b);
present(&c); commit(&s, &c);
const int64_t start = g_now;
timer_fires(g_now);
check(&a, 1);
check(&b, 0);
assert(g_armed == start + interval);
timer_fires(start + interval / 2);
check(&b, 0);
timer_fires(g_armed);
check(&b, 1);
check(&c, 0);
}
static void unpaced_sync_child(void) {
struct surface root, low, high;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&low, ROLE_SUBSURFACE, &root);
surface_init(&high, ROLE_SUBSURFACE, &root);
buffer_init(&a); buffer_init(&b);
g_release_unpaced = 1;
present(&a); commit(&high, &a); commit(&root, NULL);
present(&a);
commit(&high, NULL);
check(&a, 0);
commit(&low, &a);
commit(&root, NULL);
check(&a, 0);
commit(&low, NULL);
check(&a, 0);
commit(&root, NULL);
check(&a, 1);
present(&b); commit(&root, &b);
commit(&root, NULL);
check(&b, 1);
}
static void holder_destroyed(void) {
struct surface root, child;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&child, ROLE_SUBSURFACE, &root);
buffer_init(&a); buffer_init(&b);
present(&a); commit(&child, &a); commit(&root, NULL);
present(&b); commit(&child, &b);
timer_fires(g_now + 100000000LL);
check(&a, 0);
child.parent = NULL;
wl_list_remove(&root.link);
pending_releases_forget_surface(&root);
check(&a, 1);
}
static void cycled_faster_than_releases(void) {
struct surface s;
struct wl_resource a, b, c;
struct wl_resource *order[3] = {&a, &b, &c};
surface_init(&s, ROLE_TOPLEVEL, NULL);
buffer_init(&a); buffer_init(&b); buffer_init(&c);
g_fps_limit = 60;
const int64_t interval = 1000000000LL / 60;
for (int i = 0; i < 30; i++) {
present(order[i % 3]);
commit(&s, order[i % 3]);
assert(s.releases_pending <= 2);
assert(g_armed <= g_now + 3 * interval);
}
timer_fires(g_now + 1000000000LL);
check(&a, 1);
check(&b, 1);
check(&c, 0);
}
static void desync_parent_holds_sync_grandchild(void) {
struct surface root, middle, child;
struct wl_resource a, b;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&middle, ROLE_SUBSURFACE, &root);
surface_init(&child, ROLE_SUBSURFACE, &middle);
middle.sub_desync = 1;
buffer_init(&a); buffer_init(&b);
present(&a); commit(&child, &a); commit(&middle, NULL);
present(&b); commit(&child, &b);
timer_fires(g_now + 100000000LL);
check(&a, 0);
commit(&middle, NULL);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&b, 0);
}
static void set_desync_frees_held_release(void) {
struct surface root, outer, inner;
struct wl_resource a, b, c, d;
surface_init(&root, ROLE_TOPLEVEL, NULL);
surface_init(&outer, ROLE_SUBSURFACE, &root);
surface_init(&inner, ROLE_SUBSURFACE, &outer);
buffer_init(&a); buffer_init(&b); buffer_init(&c); buffer_init(&d);
present(&a); commit(&inner, &a); commit(&root, NULL);
present(&b); commit(&inner, &b);
present(&c); commit(&outer, &c); commit(&root, NULL);
present(&d); commit(&outer, &d);
inner.sub_desync = 1;
pending_releases_rehold(&inner);
timer_fires(g_now + 100000000LL);
check(&a, 1);
check(&c, 0);
outer.sub_desync = 1;
pending_releases_rehold(&outer);
timer_fires(g_now + 100000000LL);
check(&c, 1);
check(&b, 0);
check(&d, 0);
}
int main(int argc, char **argv) {
assert(argc == 2);
wl_list_init(&g_surfaces);
wl_list_init(&g_pending_releases);
if (!strcmp(argv[1], "moved")) moved_between_planes();
else if (!strcmp(argv[1], "reattached")) reattached_before_release();
else if (!strcmp(argv[1], "cycled")) cycled_faster_than_releases();
else if (!strcmp(argv[1], "desync")) desync_child_not_held();
else if (!strcmp(argv[1], "toplevel")) toplevel_pacing_kept();
else if (!strcmp(argv[1], "unpaced")) unpaced_sync_child();
else if (!strcmp(argv[1], "destroyed")) holder_destroyed();
else if (!strcmp(argv[1], "nested")) desync_parent_holds_sync_grandchild();
else if (!strcmp(argv[1], "set-desync")) set_desync_frees_held_release();
else return 2;
return 0;
}
+18
View File
@@ -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()
+39 -53
View File
@@ -6,7 +6,6 @@ import re
import runpy
import shutil
import tempfile
import threading
import time
import unittest
from unittest import mock
@@ -93,8 +92,6 @@ class IdTest(unittest.TestCase):
self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000)
found = re.search(r"const val APP_ID = (\d+)L", KOTLIN.read_text())
self.assertEqual(found.group(1), BNET["APP_ID"])
for name in ("FEX_REQUEST", "FEX_RESULT"):
self.assertIn('const val %s = "%s"' % (name, BNET[name]), KOTLIN.read_text())
class ProtonRunOptionsTest(Temp):
@@ -180,7 +177,7 @@ class ConfigAndMenuTest(Temp):
self.assertEqual(config["Client"]["Streaming"]["StreamingEnabled"], "false")
self.assertEqual(config["Client"]["GameLaunchWindowBehavior"], "2")
self.assertIsNone(BNET["write_config"](root))
path.write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "0"}, "Games": {"osi": {}}}')
path.write_text('{"Client": {"HardwareAcceleration": "false"}, "Games": {"osi": {}}}')
self.assertEqual(BNET["write_config"](root), "launch 32-bit")
config = json.loads(path.read_text())
self.assertEqual(config, {"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "2"},
@@ -189,6 +186,29 @@ class ConfigAndMenuTest(Temp):
self.assertEqual(BNET["write_config"](root), "acceleration 32-bit")
self.assertEqual(json.loads(path.read_text())["Client"]["HardwareAcceleration"], "false")
def test_a_launch_behavior_the_player_chose_is_kept(self):
root = str(self.tmp)
path = self.config_path()
path.parent.mkdir(parents=True)
for behavior in ("0", "1"):
with self.subTest(behavior):
path.write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "%s"}, '
'"Games": {"s1": {"Run64Bit": "false", "Run64BitSet": "true"}}}' % behavior)
self.assertIsNone(BNET["write_config"](root))
self.assertEqual(json.loads(path.read_text())["Client"]["GameLaunchWindowBehavior"], behavior)
self.assertTrue(BNET["keeps_open"](root))
def test_only_a_launch_behavior_other_than_exit_keeps_battle_net_open(self):
root = str(self.tmp)
self.assertFalse(BNET["keeps_open"](root))
path = self.config_path()
path.parent.mkdir(parents=True)
for text in ("{not json", "[1, 2]", '{"Client": "x"}', '{"Client": {}}',
'{"Client": {"GameLaunchWindowBehavior": "2"}}'):
with self.subTest(text):
path.write_text(text)
self.assertFalse(BNET["keeps_open"](root))
def test_starcraft_starts_its_32_bit_client_until_a_player_picks_one(self):
root = str(self.tmp)
BNET["write_config"](root)
@@ -656,6 +676,7 @@ class TidyTest(unittest.TestCase):
"say": lambda message: None,
"stop": lambda found, wait=0: self.stopped.append(sorted(pid for pid, _ in found)),
"notify": lambda title, body, icon=None: self.notified.append(title),
"keeps_open": lambda root: False,
})
patcher.start()
self.addCleanup(patcher.stop)
@@ -672,6 +693,14 @@ class TidyTest(unittest.TestCase):
self.assertEqual(self.stopped, [[1, 2, 3]])
self.assertEqual(self.notified, [])
def test_battle_net_the_player_set_to_stay_open_is_left_open(self):
up = [self.CLIENT, self.PAGE, self.AGENT, self.WINE]
tidy = BNET["Tidy"](settle=20, gone=30)
with mock.patch.dict(BNET, {"keeps_open": lambda root: True}):
closed = self.run_tidy(tidy, [(0, up), (5, up + [self.GAME]), (25, up + [self.GAME]), (60, up + [self.GAME])])
self.assertEqual(closed, [False, False, False, False])
self.assertEqual(self.stopped, [])
def test_battle_net_beside_a_game_signing_in_with_its_token_is_left_open(self):
d4 = (6, ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-nostreamline", "-sso", "-launch", "-uid", "fenris"])
up = [self.CLIENT, self.PAGE, self.AGENT]
@@ -729,36 +758,6 @@ class TidyTest(unittest.TestCase):
self.assertEqual(self.stopped, [])
class FexRequestTest(Temp):
def answer(self, text, delay=0.2):
def respond():
request = self.tmp / BNET["FEX_REQUEST"]
deadline = time.monotonic() + 5
while not request.exists() and time.monotonic() < deadline:
time.sleep(0.02)
self.requested = request.read_text()
request.unlink()
time.sleep(delay)
(self.tmp / (BNET["FEX_RESULT"] + ".tmp")).write_text(text + "\n")
os.replace(self.tmp / (BNET["FEX_RESULT"] + ".tmp"), self.tmp / BNET["FEX_RESULT"])
thread = threading.Thread(target=respond)
thread.start()
self.addCleanup(thread.join)
def test_the_apps_answer_comes_back(self):
(self.tmp / BNET["FEX_RESULT"]).write_text("ok an-old-answer\n")
self.answer("ok FEXCore-2610-d2rfix28-linux.wcp")
self.assertEqual(BNET["ask_fex"](str(self.tmp), wait=5), "ok FEXCore-2610-d2rfix28-linux.wcp")
self.assertEqual(self.requested, "appid=%s\n" % BNET["APP_ID"])
self.assertFalse((self.tmp / BNET["FEX_RESULT"]).exists())
def test_no_answer_or_no_session_starts_without_one(self):
with mock.patch.dict(BNET, {"say": lambda message: None}):
self.assertIsNone(BNET["ask_fex"](str(self.tmp), wait=0.3))
self.assertIsNone(BNET["ask_fex"](None))
self.assertIsNone(BNET["ask_fex"](str(self.tmp / "gone")))
class OpenTest(Temp):
def setUp(self):
super().setUp()
@@ -767,7 +766,6 @@ class OpenTest(Temp):
self.alive = []
self.menu = self.tmp / "droiddeck-battlenet.desktop"
patcher = mock.patch.dict(BNET, {
"ask_fex": lambda launch_dir, wait=0: "ok fex.wcp",
"say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])),
"wine_processes": lambda pfx, proc="/proc": list(self.alive),
"stop": lambda processes, wait=0: self.calls.append(("stop", [pid for pid, _ in processes])) or self.alive.clear(),
@@ -956,7 +954,6 @@ class Harness(Temp):
self.states = []
self.last = []
patcher = mock.patch.dict(BNET, {
"ask_fex": lambda launch_dir, wait=0: self.calls.append(("fex",)) or "ok fex.wcp",
"say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])),
"wine_processes": self.processes,
"stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))),
@@ -987,7 +984,7 @@ class LaunchTest(Harness):
self.states = [[], [], up, up + [(40, self.GAME)], up, up]
self.assertEqual(BNET["launch"](self.root, "Fen"), 0)
self.assertEqual(self.calls, [
("fex",), ("start", "Battle.net Launcher.exe", None),
("start", "Battle.net Launcher.exe", None),
("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]),
("stop", [10, 11, 12, 13, 14, 30]),
])
@@ -1002,7 +999,7 @@ class LaunchTest(Harness):
with mock.patch.dict(BNET, {"GAME_SETTLE": 0}):
self.assertEqual(BNET["launch"](self.root, "Fen"), 0)
self.assertEqual(self.calls, [
("fex",), ("start", "Battle.net Launcher.exe", None),
("start", "Battle.net Launcher.exe", None),
("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]),
("stop", [10, 11, 12, 13, 14, 30]),
("stop", [50]),
@@ -1416,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"})
@@ -1644,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})}
@@ -1684,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")
+39
View File
@@ -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"):
+2 -1
View File
@@ -19,7 +19,8 @@ class CdpGuardTest(unittest.TestCase):
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"),
str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl",
"-o", str(cls.library)],
input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
input=b"int dd_udevmon_stand_in(int fd) { return 0; }\n"
b"int dd_udevmon_bind(int fd, const void *addr, unsigned len, void *real, int *rc) { return 0; }", check=True, capture_output=True)
@classmethod
def tearDownClass(cls):
+5 -5
View File
@@ -115,15 +115,15 @@ class CiChecksTest(unittest.TestCase):
jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']
gate = jobs['checks']
self.assertEqual(gate['name'], 'Compile and test APK')
self.assertEqual(set(gate['needs']), {'build', 'python-tests'})
self.assertEqual(set(gate['needs']), {'build', 'python-tests', 'store-tests'})
self.assertIn('!cancelled()', gate['if'])
for build, python in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=2):
with self.subTest(build=build, python=python):
for build, python, store in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=3):
with self.subTest(build=build, python=python, store=store):
result = subprocess.run(
['bash', '-c', gate['steps'][0]['run']],
env=dict(os.environ, BUILD_RESULT=build, PYTHON_RESULT=python),
env=dict(os.environ, BUILD_RESULT=build, PYTHON_RESULT=python, STORE_RESULT=store),
capture_output=True)
self.assertEqual(result.returncode == 0, build == python == 'success')
self.assertEqual(result.returncode == 0, build == python == store == 'success')
for publisher in ('sign', 'packs'):
self.assertIn('checks', jobs[publisher]['needs'])
+49 -198
View File
@@ -18,6 +18,15 @@ def run_bash(script, env=None):
return subprocess.run(['bash', '-c', script], capture_output=True, text=True, timeout=10, env=env)
def state_source():
source = SCRIPT.read_text()
start = source.index(' declare -A _dd_deaf=()')
return source[start:source.index(' while kill -0', start)]
STATE = state_source()
class ClientZramFocusTest(unittest.TestCase):
def test_the_hidden_epic_launcher_is_compressed_with_the_client(self):
with tempfile.TemporaryDirectory() as tmp:
@@ -78,217 +87,59 @@ class ClientZramFocusTest(unittest.TestCase):
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('|6000021 6000022 6000020|0', result.stdout.strip())
def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self):
source = SCRIPT.read_text()
start = source.index(' _dd_focus=1\n')
stop = source.index(' dd_watch_nap\n', start)
body = source[start:stop]
harness = '''
_dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_unpack=0 _dd_apps=" 413150"
_dd_pids=(123)
dd_game_focused() { [ "$focused" = 1 ]; }
dd_over_cap() { return 1; }
dd_client_can_pageout() { return 0; }
dd_client_can_readback() { return 0; }
dd_zram_send() { echo "send:$1"; }
tick() {
SECONDS=$1 _dd_game=$2 focused=$3
''' + body + '''
}
tick 0 1 1
tick 5 1 0
tick 30 1 1
echo "refocus:$_dd_packed"
tick 49 1 1
tick 50 1 1
tick 55 1 0
tick 60 0 0
'''
result = run_bash(harness)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['refocus:-1', 'send:1', 'send:0'], result.stdout.splitlines())
def monitor_harness(self):
source = SCRIPT.read_text()
start = source.index(' dd_zram_scan\n dd_memory_read\n')
stop = source.index(' dd_watch_nap\n', start)
return '''
_dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_measured=-1 _dd_unpack=0 _dd_capped=-1 _dd_backoff=30
_dd_apps=" 413150"
_dd_pids=(123)
TICK = '''
dd_zram_scan() { _dd_game=$game _dd_pids=(10) _dd_others=() _dd_apps=" 413150"; }
dd_game_focused() { return $focus; }
dd_memory_read() { _dd_available=$((available * 1024)) _dd_mem_total=$((7168 * 1024)) _dd_floor=$((896 * 1024)); _dd_target=$((target * 1024)) _dd_swap_room=$((4096 * 1024)) _dd_saving=500 _dd_rate=0 _dd_psi=0; }
dd_zram_trim() { echo "trim:$NOW"; _dd_trimmed=$((64 * 1024)); }
dd_zram_usage() { _dd_swap=$((64 * 1024)); }
dd_session_others() { :; }
step() { :; }
dd_zram_scan() { :; }
dd_memory_read() { :; }
dd_client_pressure() { :; }
dd_client_pressure_finish() { :; }
dd_session_pressure() { :; }
dd_client_can_pageout() { return 0; }
dd_client_can_readback() { [ "${readback:-1}" = 1 ]; }
dd_game_focused() { [ "$focused" = 1 ] && return 0; [ "$focused" = 2 ] && return 2; return 1; }
dd_cap_due() { [ "$cap_due" = 1 ]; }
dd_over_cap() { [ "$over_cap" = 1 ]; }
dd_zram_send() { echo "send:$1:$3"; }
tick() {
SECONDS=$1 _dd_game=$2 focused=$3 over_cap=$4 cap_due=$5
''' + source[start:stop] + '\n}\n'
kill() { echo "back:$NOW"; }
game=1 focus=0 available=1500 target=1600
run() { for NOW in $(seq "$1" "$2"); do dd_memory_tick; done; }
'''
def test_client_toggle_still_disables_automatic_compression(self):
result = run_bash(self.monitor_harness() + '''
DD_ZRAM_CLIENT=0
tick 0 1 1 0 0
tick 25 1 1 0 0
tick 30 0 0 0 0
''')
def tick(self, body):
functions = '\n'.join(function_source(name) for name in (
'dd_memory_need', 'dd_memory_relieve', 'dd_memory_note', 'dd_client_readback', 'dd_memory_tick'))
with tempfile.TemporaryDirectory() as tmp:
script = (functions + self.TICK + body).replace('/tmp/.dd-zram', tmp + '/ctl')
result = run_bash(('NOW=0\nset -u\n' + STATE + script).replace('SECONDS', 'NOW'))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual('', result.stdout)
return result.stdout.splitlines()
def test_a_new_game_restarts_the_compression_delay(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
_dd_apps=" 413150 1245620"
tick 15 1 1 0 0
tick 20 1 1 0 0
echo "starting:$_dd_packed"
tick 34 1 1 0 0
tick 35 1 1 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['starting:-1', 'send:1:client'], result.stdout.splitlines())
def test_the_client_behind_a_game_is_trimmed_while_memory_is_short_of_the_target(self):
self.assertEqual(['trim:0', 'trim:1', 'trim:2'], self.tick('run 0 2\navailable=1700; run 3 9\n'))
def test_ram_cap_can_still_compress_an_unfocused_client(self):
result = run_bash(self.monitor_harness() + '''
DD_ZRAM_CLIENT=0 DD_RAM_CAP_MB=1024
dd_zram_usage() { _dd_rss=$((768 * 1024)); }
tick 0 1 0 1 1
echo "cap:$_dd_packed:$_dd_since:$_dd_backoff"
tick 5 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'send:1:session', 'cap:0:-1:60', 'send:0:client'], result.stdout.splitlines())
def test_nothing_is_requested_while_the_app_holds_the_control_file(self):
self.assertEqual(['trim:3'], self.tick(
': > /tmp/.dd-zram.hold; run 0 2\nrm /tmp/.dd-zram.hold; run 3 3\n'))
def test_game_exit_defers_restore_until_the_session_is_under_the_ram_cap(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
tick 20 1 1 0 0
tick 25 1 0 0 0
tick 30 0 0 1 0
echo "deferred:$_dd_unpack:$_dd_packed"
tick 35 0 0 0 0
echo "restored:$_dd_unpack"
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'deferred:1:-1', 'send:0:client', 'restored:0'], result.stdout.splitlines())
def test_nothing_is_read_back_while_memory_is_still_needed(self):
self.assertEqual(['trim:0'], self.tick(
'run 0 0\ngame=0 available=4000; dd_memory_need() { _dd_need=1 _dd_hard=0 _dd_force=0; }\n'
'dd_memory_relieve() { dd_memory_need; }; run 1 40\n'))
def test_game_exit_defers_readback_under_pressure_even_without_a_ram_cap(self):
result = run_bash(self.monitor_harness() + """
tick 0 1 1 0 0
tick 20 1 1 0 0
readback=0
tick 25 0 0 0 0
echo "deferred:$_dd_unpack"
readback=1
tick 30 0 0 0 0
echo "restored:$_dd_unpack"
""")
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'deferred:1', 'send:0:client', 'restored:0'], result.stdout.splitlines())
def test_game_exit_reads_the_client_back_after_a_quiet_half_minute(self):
self.assertEqual(['trim:0', 'back:30'], self.tick('run 0 0\ngame=0 available=4000; run 1 40\n'))
def test_client_in_front_of_a_running_game_is_read_back_and_compressed_again_later(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
tick 20 1 1 0 0
tick 25 1 0 0 0
echo "away:$_dd_packed"
tick 30 1 0 0 0
echo "read:$_dd_packed:$_dd_unpack"
tick 35 1 0 0 0
tick 40 1 1 0 0
tick 55 1 1 0 0
tick 60 1 1 0 0
echo "again:$_dd_packed"
tick 65 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'away:20', 'send:0:client', 'read:-1:0', 'send:1:client', 'again:60', 'send:0:client'],
result.stdout.splitlines())
def test_unknown_focus_keeps_the_client_compressed(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
tick 20 1 1 0 0
tick 25 1 2 0 0
tick 40 1 2 0 0
echo "unknown:$_dd_packed:$_dd_unpack"
tick 45 1 0 0 0
tick 48 1 2 0 0
tick 52 1 0 0 0
tick 56 1 0 0 0
echo "flicker:$_dd_packed"
tick 57 1 0 0 0
echo "read:$_dd_packed"
tick 60 0 2 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'unknown:20:1', 'flicker:20', 'send:0:client', 'read:-1'],
result.stdout.splitlines())
def test_client_in_front_of_a_running_game_is_read_back_and_trimmed_again_later(self):
self.assertEqual(['trim:0', 'back:30', 'trim:60'],
self.tick('run 0 0\nfocus=1 available=4000; run 1 44\nfocus=0 available=1500; run 45 60\n'))
def test_a_short_look_at_the_client_keeps_it_compressed(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
tick 20 1 1 0 0
tick 25 1 0 0 0
tick 28 1 1 0 0
tick 30 1 0 0 0
tick 34 1 0 0 0
echo "packed:$_dd_packed"
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'packed:20'], result.stdout.splitlines())
self.assertEqual(['trim:0'], self.tick('run 0 0\navailable=4000; run 1 34\nfocus=1; run 35 38\nfocus=0; run 39 60\n'))
def test_client_in_front_waits_for_memory_and_a_ram_cap_keeps_it_compressed(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
tick 20 1 1 0 0
readback=0
tick 25 1 0 0 0
tick 35 1 0 0 0
echo "tight:$_dd_packed"
readback=1
tick 40 1 0 0 0
echo "eased:$_dd_packed"
_dd_ram_cap=1048576
tick 60 1 1 0 0
tick 80 1 1 0 0
tick 85 1 0 0 0
tick 100 1 0 0 0
echo "capped:$_dd_packed"
tick 105 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'tight:20', 'send:0:client', 'eased:-1', 'send:1:client', 'capped:80', 'send:0:client'],
result.stdout.splitlines())
def test_unknown_focus_keeps_the_client_compressed(self):
self.assertEqual(['trim:0'], self.tick('run 0 0\nfocus=2 available=4000; run 1 60\n'))
def test_client_in_front_without_compression_reads_nothing_back(self):
result = run_bash(self.monitor_harness() + '''
DD_ZRAM_CLIENT=0
tick 0 1 1 0 0
tick 25 1 0 0 0
tick 40 1 0 0 0
tick 45 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual('', result.stdout)
def test_client_in_front_waits_for_memory(self):
self.assertEqual(['trim:0', 'back:50'], self.tick('run 0 0\nfocus=1 available=1800 target=896; run 1 49\navailable=2500; run 50 60\n'))
def test_a_client_that_was_never_trimmed_reads_nothing_back(self):
self.assertEqual([], self.tick('focus=1 available=4000; run 0 60\n'))
def test_scan_keeps_the_running_game_and_ignores_steams_own_reaper(self):
temp = tempfile.TemporaryDirectory()
+57
View File
@@ -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)
+93
View File
@@ -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)
+213
View File
@@ -0,0 +1,213 @@
import os
import shlex
import shutil
import subprocess
import tempfile
import time
import unittest
from pathlib import Path
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())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.proc = self.tmp / "proc"
self.proc.mkdir()
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-}\" \"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' >&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)
d.mkdir()
(d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv))
def env(self, extra=None):
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))
def pid(self):
return int((self.state / "pid").read_text().split()[0])
def gone(self, pid):
for _ in range(50):
try:
os.kill(pid, 0)
except ProcessLookupError:
return True
time.sleep(0.1)
return False
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))
self.assertEqual(3, out.returncode)
self.assertEqual("busy", out.stdout.strip())
self.stop()
self.assertTrue((self.proc / "50").exists())
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(URL, url)
seen = self.seen.read_text().splitlines()
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.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(gamescope), "gamescope is still running")
self.assertTrue(self.gone(app), "the app is still running")
def test_a_launch_for_another_directory_is_busy_and_left_alone(self):
other = self.tmp / "other"
(other / "app").mkdir(parents=True)
self.addCleanup(self.stop)
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()
self.run_helper("stop", str(other))
self.assertEqual(pid, self.pid())
os.kill(pid, 0)
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__":
unittest.main()
+154
View File
@@ -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()
+9 -35
View File
@@ -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,29 @@
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
DESKTOP = ROOT / "tools/linuxfs/desktop/droiddeck-desktop"
SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/display_buffers.c"
class DesktopDisplayBuffersTest(unittest.TestCase):
def test_clearing_the_runtime_directory_keeps_what_the_compositor_serves(self):
socket = re.search(r'#define DISPLAY_BUFFERS_SOCKET "([^"]+)"', SOURCE.read_text()).group(1)
lines = [line for line in DESKTOP.read_text().splitlines() if line.startswith('find "$XDG_RUNTIME_DIR"')]
self.assertEqual(len(lines), 1)
with tempfile.TemporaryDirectory() as directory:
runtime = Path(directory) / "runtime"
(runtime / "dbus-1").mkdir(parents=True)
kept = ["wayland-0", "wayland-0.lock", "keymap.xkb", socket]
for name in kept + ["wayland-1", "pipewire-0", "dbus-1/session"]:
(runtime / name).write_text("")
subprocess.run(["bash", "-c", lines[0]], env={"XDG_RUNTIME_DIR": str(runtime), "PATH": "/usr/bin:/bin"},
check=True, timeout=20)
self.assertEqual(sorted(path.name for path in runtime.iterdir()), sorted(kept))
if __name__ == "__main__":
unittest.main()
+199 -11
View File
@@ -24,6 +24,7 @@ FAKE = r"""
int real_opendirs;
int real_accesses;
int real_stats;
static void coarse(const char *path, struct stat *st) {
if (getenv("COARSE") && strstr(path, "/fuse/") && S_ISDIR(st->st_mode)) {
@@ -33,25 +34,44 @@ static void coarse(const char *path, struct stat *st) {
}
}
int stat(const char *path, struct stat *st) {
static int (*next)(const char *, struct stat *);
if (!next) next = dlsym(RTLD_NEXT, "stat");
char folded[4096];
static const char *fold_case(const char *path, char *folded, size_t size) {
const char *fold = getenv("FOLD");
const char *upper = fold ? strstr(path, "/STEAMAPPS") : NULL;
if (!upper && fold && !strcmp(fold, "all")) upper = strcasestr(path, "/steamapps/");
if (upper && strlen(path) < sizeof(folded)) {
strcpy(folded, path);
memcpy(folded + (upper - path) + 1, "steamapps", 9);
if (!strcmp(fold, "all"))
for (char *c = folded + (upper - path); *c; c++) if (*c >= 'A' && *c <= 'Z') *c += 'a' - 'A';
path = folded;
}
if (!upper || strlen(path) >= size) return path;
strcpy(folded, path);
memcpy(folded + (upper - path) + 1, "steamapps", 9);
if (!strcmp(fold, "all"))
for (char *c = folded + (upper - path); *c; c++) if (*c >= 'A' && *c <= 'Z') *c += 'a' - 'A';
return folded;
}
static int fold_stat(const char *name, const char *path, struct stat *st) {
int (*next)(const char *, struct stat *) = dlsym(RTLD_NEXT, name);
char folded[4096];
if (strstr(path, "/fuse/")) real_stats++;
int r = next(path, st);
if (r != 0) r = next(fold_case(path, folded, sizeof(folded)), st);
return r;
}
int stat(const char *path, struct stat *st) {
int r = fold_stat("stat", path, st);
if (r == 0) coarse(path, st);
return r;
}
int lstat(const char *path, struct stat *st) {
return fold_stat("lstat", path, st);
}
int __xstat64(int version, const char *path, struct stat64 *st) {
static int (*next)(int, const char *, struct stat64 *);
if (!next) next = dlsym(RTLD_NEXT, "__xstat64");
if (strstr(path, "/fuse/")) real_stats++;
return next ? next(version, path, st) : stat64(path, st);
}
int fstat(int fd, struct stat *st) {
static int (*next)(int, struct stat *);
if (!next) next = dlsym(RTLD_NEXT, "fstat");
@@ -221,6 +241,7 @@ static void stress(const char *dir) {
int main(int argc, char **argv) {
int *opens = dlsym(RTLD_DEFAULT, "real_opendirs");
int *accesses = dlsym(RTLD_DEFAULT, "real_accesses");
int *stats = dlsym(RTLD_DEFAULT, "real_stats");
for (int i = 1; i < argc; i++) {
const char *op = argv[i], *a = argv[i + 1];
if (!strcmp(op, "list")) { list(a); i++; }
@@ -309,6 +330,27 @@ int main(int argc, char **argv) {
printf("%d %d\n", r, r ? errno : 0);
i++;
}
else if (!strcmp(op, "accessat")) {
int r = faccessat(STDIN_FILENO, a, F_OK, 0);
printf("%d %d\n", r, r ? errno : 0);
i++;
}
else if (!strcmp(op, "xstat")) {
int (*old)(int, const char *, struct stat64 *) = dlsym(RTLD_DEFAULT, "__xstat64");
struct stat64 st;
int r = old ? old(0, a, &st) : -2;
printf("%d %d\n", r, r ? errno : 0);
i++;
}
else if (!strcmp(op, "inode")) {
DIR *d = opendir(a);
struct dirent *e;
while (d && (e = readdir(d)))
if (!strcmp(e->d_name, argv[i + 2])) printf("%llu\n", (unsigned long long)e->d_ino);
if (d) closedir(d);
i += 2;
}
else if (!strcmp(op, "stats")) printf("%d\n", stats ? *stats : -1);
else if (!strcmp(op, "accesses")) printf("%d\n", accesses ? *accesses : -1);
else if (!strcmp(op, "opens")) printf("%d\n", opens ? *opens : -1);
}
@@ -675,6 +717,152 @@ class DirCachePreloadTest(unittest.TestCase):
"access", s / "x.bundle", "accesses", "opens", between=churn)
self.assertEqual([s.name, "a.bundle,b.bundle", s.name, "a.bundle,b.bundle", "-1 2", "0", "3"], out)
def test_absolute_paths_checked_against_a_descriptor_are_answered_from_the_listing(self):
s = self.staging
out = self.run_program("list", s, "accessat", s / "x.bundle", "accessat", s / "y.bundle", "accesses",
"accessat", s / "a.bundle", "accessat", s / "a.bundle", "accesses",
"create", s / "x.bundle", "accessat", s / "x.bundle")
self.assertEqual(["-1 2", "-1 2", "0", "0 0", "0 0", "1", "0 0"], out[1:])
def test_absolute_paths_checked_against_a_descriptor_elsewhere_reach_the_filesystem(self):
s = self.staging
other = self.run_program("list", s, "accessat", s / "x.bundle", "accessat", s / "x.bundle", "accesses",
program=self.other)
self.assertEqual(["-1 2", "-1 2", "2"], other[1:])
off = self.run_program("list", s, "accessat", s / "x.bundle", "accessat", s / "x.bundle", "accesses",
env={"DD_NO_DIR_CACHE": "1", "DD_NO_PATH_CACHE": "1"})
self.assertEqual(["-1 2", "-1 2", "2"], off[1:])
def test_missing_names_asked_through_the_old_stat_entry_are_answered_from_the_listing(self):
s = self.staging
out = self.run_program("list", s, "stats", "xstat", s / "x.bundle", "stats", "xstat", s / "a.bundle", "stats",
"create", s / "x.bundle", "xstat", s / "x.bundle")
self.assertEqual(["-1 2", out[1], "0 0", str(int(out[1]) + 1), "0 0"], out[2:])
other = self.run_program("list", s, "stats", "xstat", s / "z.bundle", "stats", program=self.other)
self.assertEqual(["-1 2", str(int(other[1]) + 1)], other[2:])
def test_folders_that_differ_only_in_case_stay_cached_together(self):
s = self.staging
names = ["Content/Data", "content/data", "Content/Characters", "content/characters"]
for name in names:
(s / name).mkdir(parents=True)
checks = [op for name in names for op in ("access", s / name)]
out = self.run_program(*checks, "accesses", *checks, *checks, "accesses")
self.assertEqual(out[4], out[-1])
def test_a_cached_listing_is_served_without_asking_the_filesystem(self):
s = self.staging
out = self.run_program("list", s, "stats", "list", s, "list", s, "access", s / "x.bundle", "stats", "opens")
self.assertEqual(out[1], out[-2])
self.assertEqual("1", out[-1])
def test_own_changes_in_a_cached_folder_do_not_ask_the_filesystem(self):
s = self.staging
out = self.run_program(
"list", s, "stats",
"create", s / "c.bundle", "rename", s / "c.bundle", s / "d.bundle", "unlink", s / "a.bundle", "stats",
"list", s, "raw", s, "opens")
self.assertEqual(out[1], out[2])
self.assertEqual(["b.bundle,d.bundle", "b.bundle,d.bundle", "1"], out[3:])
def test_own_changes_in_a_folder_never_listed_do_not_ask_the_filesystem(self):
s = self.staging
out = self.run_program("stats", "create", s / "c.bundle", "rename", s / "c.bundle", s / "d.bundle",
"unlink", s / "d.bundle", "stats", "list", s, "raw", s)
self.assertEqual(out[0], out[1])
self.assertEqual(["a.bundle,b.bundle", "a.bundle,b.bundle"], out[2:])
def test_a_differently_cased_folder_is_checked_once(self):
s = self.staging
upper = Path(str(s).replace("downloading", "DOWNLOADING"))
out = self.run_program("list", s, "access", upper / "x.bundle", "stats",
"access", upper / "y.bundle", "access", upper / "z.bundle", "stats", "accesses",
env={"FOLD": "all"})
self.assertEqual(out[2], out[5])
self.assertEqual("0", out[-1])
def test_a_folder_reached_through_a_link_follows_the_link(self):
s = self.staging
other = self.lib / "elsewhere" / s.name
other.mkdir(parents=True)
(other / "x.bundle").touch()
link = self.lib / "DOWNLOADING"
link.symlink_to("downloading")
def repoint():
link.unlink()
link.symlink_to("elsewhere")
out = self.run_paused("list", s, "access", link / s.name / "x.bundle", "pause",
"access", link / s.name / "x.bundle", between=repoint, env={"FOLD": "all"})
self.assertEqual(["-1 2", "0 0"], out[1:])
def test_a_linked_last_component_follows_the_link(self):
s = self.staging
other = self.lib / "elsewhere" / s.name
other.mkdir(parents=True)
(other / "x.bundle").touch()
twin = self.lib / "DOWNLOADING"
twin.mkdir()
link = twin / s.name
link.symlink_to(s)
def repoint():
link.unlink()
link.symlink_to(other)
out = self.run_paused("list", s, "access", link / "x.bundle", "pause",
"access", link / "x.bundle", between=repoint, env={"FOLD": "all"})
self.assertEqual(["-1 2", "0 0"], out[1:])
def test_a_folder_reached_through_a_parent_step_is_checked_each_time(self):
s = self.staging
other = self.lib / "elsewhere"
(other / "branch").mkdir(parents=True)
(other / s.parent.name / s.name).mkdir(parents=True)
(other / s.parent.name / s.name / "x.bundle").touch()
(self.lib / "branch").mkdir()
twin = self.lib / "BRANCH"
twin.mkdir()
listed = self.lib / "branch" / ".." / s.parent.name / s.name
through = twin / ".." / s.parent.name / s.name
def repoint():
twin.rmdir()
twin.symlink_to(other / "branch")
out = self.run_paused("list", listed, "access", through / "x.bundle", "pause",
"access", through / "x.bundle", between=repoint, env={"FOLD": "all"})
self.assertEqual(["-1 2", "0 0"], out[1:])
def test_a_permission_change_on_the_folder_or_above_it_is_noticed(self):
s = self.staging
for target in (s, s.parent):
with self.subTest(target=target.name):
out = self.run_paused("list", s, "opens", "pause", "list", s, "opens",
between=lambda: target.chmod(0o700))
self.assertEqual(int(out[1]) + 1, int(out[3]))
def test_a_permission_change_on_a_file_keeps_the_listing(self):
s = self.staging
out = self.run_paused("list", s, "opens", "pause", "list", s, "opens",
between=lambda: (s / "a.bundle").chmod(0o600))
self.assertEqual(out[1], out[3])
def test_opening_an_existing_link_keeps_its_entry(self):
s = self.staging
(s / "l.bundle").symlink_to("a.bundle")
out = self.run_program("list", s, "create", s / "l.bundle", "inode", s, "l.bundle", "raw", s)
self.assertEqual(str((s / "l.bundle").lstat().st_ino), out[1])
def test_changes_made_around_the_cache_after_own_changes_are_noticed(self):
s = self.staging
out = self.run_program("list", s, "create", s / "c.bundle", "sneak", s / "y.bundle", "list", s, "raw", s,
"access", s / "y.bundle")
self.assertEqual(out[1], out[2])
self.assertIn("y.bundle", out[1])
self.assertEqual("0 0", out[3])
def test_misses_outside_the_client_or_fuse_steamapps_reach_the_filesystem(self):
s = self.staging
other = self.run_program("list", s, "access", s / "x.bundle", "access", s / "y.bundle", "accesses",
+55
View File
@@ -348,6 +348,45 @@ 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):
pass
def send(self, text):
raise BrokenPipeError("closed")
def close(self):
pass
with patch.object(agent, "WebSocket", Lost), patch.object(
agent, "cdp_targets", return_value=[{"title": "SharedJSContext", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]):
with self.assertRaises(agent.AgentError) as caught:
agent.cdp_eval(str(self.dir), "1")
self.assertEqual("DEVTOOLS_UNREACHABLE", caught.exception.code)
def test_cdp_without_a_port(self):
os.environ.pop("DD_CDP_PORT", None)
self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"])
@@ -368,6 +407,22 @@ class AgentTest(unittest.TestCase):
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
self.assertEqual("NO_TARGET", missing["error"]["code"])
def test_cdp_eval_on_a_secret_inspector_url(self):
server = FakeDevTools({"result": {"result": {"type": "string", "value": "ok"}}})
server.start()
self.addCleanup(server.server.close)
os.environ.pop("DD_CDP_PORT", None)
url = "ws://127.0.0.1:%d/0f8fad5b-d9cb-469f-a165-70867728950e" % server.port
answer = self.ask({"kind": "cdp", "expression": "require('electron')", "inspector": url, "commandLineApi": True})
self.assertTrue(answer["ok"], answer)
self.assertEqual("inspector", answer["target"])
self.assertTrue(server.seen[0]["params"]["includeCommandLineAPI"])
def test_cdp_refuses_inspector_urls_without_a_session_id(self):
for url in ("ws://127.0.0.1:9229/", "ws://127.0.0.1:9229/json/list", "ws://10.0.0.2:9229/0f8fad5b-d9cb-469f-a165-70867728950e",
"ws://127.0.0.1:80/0f8fad5b-d9cb-469f-a165-70867728950e", "ws://127.0.0.1:9229/0f8fad5b-d9cb-469f-a165-70867728950e/x", 9229):
self.assertEqual("INVALID_REQUEST", self.ask({"kind": "cdp", "expression": "1", "inspector": url})["error"]["code"])
def test_steam_selection(self):
with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate:
answer = self.ask({"kind": "steam-selection"})
+4 -4
View File
@@ -1318,7 +1318,7 @@ class StoreLaunchClientTest(unittest.TestCase):
(self.folder / ".droiddeck-store.json").write_text(json.dumps(sidecar))
with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \
mock.patch.dict(S, {"client_wanted": lambda: calls.append("wanted") or True,
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}):
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}):
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
self.assertNotIn("wanted", calls)
self.assertNotIn("epic-code", calls)
@@ -1341,7 +1341,7 @@ class StoreLaunchClientTest(unittest.TestCase):
with mock.patch.dict(os.environ, env), \
mock.patch.dict(S, {"client_wanted": lambda: True,
"through_client": lambda folder, sidecar, timeout=0: calls.append("client") or "timeout",
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True, "code": True}}):
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True, "code": True}}):
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
self.assertEqual(["client", "epic-code", "cloud-down"], calls)
@@ -1356,7 +1356,7 @@ class StoreLaunchClientTest(unittest.TestCase):
(self.folder / ".droiddeck-epic-code").write_text("stale")
with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \
mock.patch.dict(S, {"client_wanted": lambda: True, "through_client": through,
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}):
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}):
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
self.assertEqual(["client", "cloud-down"], calls)
self.assertFalse((self.folder / ".droiddeck-epic-code").exists())
@@ -1368,7 +1368,7 @@ class StoreLaunchClientTest(unittest.TestCase):
with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "DROIDDECK_EPIC_HANDLED": "1",
"STEAM_COMPAT_DATA_PATH": ""}), \
mock.patch.dict(S, {"client_wanted": lambda: calls.append("wanted") or True,
"ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}):
"ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}):
S["main"]([str(self.folder / ".droiddeck-launch.bat")])
self.assertEqual(["cloud-down"], calls)
self.assertTrue((self.folder / ".droiddeck-epic-args").exists())
+21
View File
@@ -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()
@@ -1055,6 +1070,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()
+54
View File
@@ -274,6 +274,60 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual(0, code)
self.assertEqual(489830, out["focus"]["focusedApp"])
LIBRARY = {"ok": True, "command": "library", "games": [
{"id": "9227380185612091392", "name": "TimeSplitters Future Perfect", "source": "xbox", "storeId": "9N51S9QZMSB6", "folder": "/g/ts"},
{"id": "12302733539203571712", "name": "Dead Space (2008)", "source": "ea", "storeId": "DR:105641400", "folder": "/g/ds"},
{"id": "12302733539203571999", "name": "Dead Space 2", "source": "ea", "storeId": "DR:1", "folder": "/g/ds2"},
]}
def test_launch_by_name_opens_the_game_link_and_waits_for_a_game(self):
self.configure({"library": self.LIBRARY, "state": [state(focused=769, focusable=[769]), state(focused=7, focusable=[7, 769])]})
code, out = self.run_ctl("launch", "--game", "timesplitters", "--wait", "--timeout", "5")
self.assertEqual(0, code)
self.assertEqual("TimeSplitters Future Perfect", out["game"]["name"])
self.assertEqual(7, out["focus"]["focusedApp"])
started = [e["args"] for e in self.calls() if e["args"][:3] == ["shell", "am", "start"]]
self.assertIn("droiddeck://game/9227380185612091392", started[0])
self.assertIn("com.droiddeck.launcher/com.droiddeck.launcher.FrontEndActivity", started[0])
self.assertFalse(self.calls("launch"))
def test_launch_by_name_refuses_an_ambiguous_or_missing_game(self):
self.configure({"library": self.LIBRARY})
code, out = self.run_ctl("launch", "--game", "dead space")
self.assertNotEqual(0, code)
self.assertEqual("GAME_AMBIGUOUS", out["error"]["code"])
self.assertIn("Dead Space 2 (12302733539203571999)", out["error"]["message"])
code, out = self.run_ctl("launch", "--game", "12302733539203571712")
self.assertEqual(0, code)
self.assertEqual("ea", out["game"]["source"])
code, out = self.run_ctl("launch", "--game", "halo")
self.assertEqual("GAME_NOT_FOUND", out["error"]["code"])
code, out = self.run_ctl("launch")
self.assertEqual("INVALID_ARGUMENTS", out["error"]["code"])
self.assertFalse([e for e in self.calls() if e["args"][:3] == ["shell", "am", "start"] and "droiddeck://game/12302733539203571999" in e["args"]])
def test_quit_without_an_app_quits_the_focused_game(self):
self.configure({"state": state(focused=4040, focusable=[4040, 769]), "quit": {"ok": True, "command": "quit"}})
code, _ = self.run_ctl("quit")
self.assertEqual(0, code)
self.assertEqual(4040, self.calls("quit")[0]["request"]["appId"])
self.configure({"state": state(focused=769, focusable=[769])})
code, out = self.run_ctl("quit")
self.assertEqual("NO_FOCUSED_GAME", out["error"]["code"])
self.assertEqual(1, len(self.calls("quit")))
def test_library_xodus_and_cloud_pass_their_requests(self):
self.configure({"library": self.LIBRARY, "xodus": {"ok": True, "command": "xodus", "exit": 0, "stdout": "{}", "stderr": ""},
"cloud": {"ok": True, "command": "cloud", "result": "ok", "files": 2, "reason": "downloaded"}})
self.assertEqual(0, self.run_ctl("library", "--source", "ea", "--query", "dead")[0])
self.assertEqual({"query": "dead", "source": "ea"}, self.calls("library")[0]["request"])
self.assertEqual(0, self.run_ctl("xodus", "--timeout", "30", "--", "license", "abc", "--market", "US")[0])
self.assertEqual({"args": ["license", "abc", "--market", "US"], "timeout": 30.0}, self.calls("xodus")[0]["request"])
code, out = self.run_ctl("cloud", "down", "ubisoft", "92c79ab6", "--force")
self.assertEqual(0, code)
self.assertEqual("downloaded", out["reason"])
self.assertEqual({"direction": "down", "store": "ubisoft", "id": "92c79ab6", "force": True}, self.calls("cloud")[0]["request"])
def test_start_reuse_keeps_a_running_session(self):
running = state(focused=769)
running["session"]["mode"] = "steam"
+91
View File
@@ -0,0 +1,91 @@
import json
import unittest
from test_droiddeckctl import FakeAdbTest, ctl
def key_frames(commands):
found = []
for command in commands:
if command["command"] == "inject":
events = command["events"]
found.append({code: value for code, value in zip(events[1::3], events[2::3]) if code != "SYN_REPORT"})
return found
class GamepadTest(FakeAdbTest):
def setUp(self):
super().setUp()
self.configure({})
def gamepad(self, *argv):
return self.run_ctl("input", "gamepad", *argv)
def script(self):
[call] = [c for c in self.calls() if c["args"][:3] == ["shell", "uinput", "-"]]
return [json.loads(line) for line in call["stdin"].splitlines()]
def test_buttons_are_pressed_in_order_on_a_real_looking_gamepad(self):
code, out = self.gamepad("b", "rb", "--hold", "50", "--gap", "100")
self.assertEqual(0, code)
self.assertEqual({"ok": True, "command": "input", "type": "gamepad", "buttons": ["b", "rb"], "deviceSerial": "fake-1"},
{k: v for k, v in out.items() if k != "ms"})
self.assertFalse(self.calls("input"))
commands = self.script()
register = commands[0]
bits = {c["type"]: c["data"] for c in register["configuration"]}
self.assertEqual(("register", "usb", ["EV_KEY", "EV_ABS"]), (register["command"], register["bus"], bits["UI_SET_EVBIT"]))
self.assertFalse(register["name"].lower().startswith(("uinput-", "uinput_")))
self.assertTrue({"BTN_SOUTH", "BTN_EAST", "BTN_TL", "BTN_TR", "BTN_START"} <= set(bits["UI_SET_KEYBIT"]))
self.assertEqual(set(bits["UI_SET_ABSBIT"]), {a["code"] for a in register["abs_info"]})
self.assertEqual({"id": 1, "command": "delay", "duration": ctl.UINPUT_REGISTER_MS}, commands[1])
self.assertEqual([{"BTN_EAST": 1}, {"BTN_EAST": 0}, {"BTN_TR": 1}, {"BTN_TR": 0}], key_frames(commands))
self.assertEqual([50, 100, 50, 100], [c["duration"] for c in commands[2:-2] if c["command"] == "delay"])
self.assertEqual({"id": 1, "command": "sync", "syncToken": ctl.GAMEPAD_SYNC}, commands[-1])
def test_a_zero_gap_sends_no_empty_delay_which_android_rejects(self):
code, _ = self.gamepad("a", "b", "--hold", "40", "--gap", "0")
self.assertEqual(0, code)
commands = self.script()
self.assertEqual([{"BTN_SOUTH": 1}, {"BTN_SOUTH": 0}, {"BTN_EAST": 1}, {"BTN_EAST": 0}], key_frames(commands))
self.assertEqual([], [c for c in commands if c["command"] == "delay" and c["duration"] <= 0])
self.assertEqual([40, 40], [c["duration"] for c in commands[2:-2] if c["command"] == "delay"])
def test_a_dpad_release_never_runs_into_the_next_press_even_at_zero_gap(self):
code, _ = self.gamepad("left", "left", "--hold", "40", "--gap", "0")
self.assertEqual(0, code)
commands = self.script()
self.assertEqual([{"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}, {"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}], key_frames(commands))
self.assertEqual([40, ctl.GAMEPAD_DPAD_MIN_GAP_MS, 40, ctl.GAMEPAD_DPAD_MIN_GAP_MS],
[c["duration"] for c in commands[2:-2] if c["command"] == "delay"])
def test_the_dpad_uses_the_hat_axes(self):
code, _ = self.gamepad("up", "right", "down", "left")
self.assertEqual(0, code)
self.assertEqual([{"ABS_HAT0Y": -1}, {"ABS_HAT0Y": 0}, {"ABS_HAT0X": 1}, {"ABS_HAT0X": 0},
{"ABS_HAT0Y": 1}, {"ABS_HAT0Y": 0}, {"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}],
key_frames(self.script()))
def test_an_unknown_button_or_bad_timing_is_refused_before_touching_the_device(self):
for argv, message in ((("nope",), "Unknown gamepad button 'nope'"), (("a", "--hold", "1"), "--hold must be"),
(("a", "--gap", "-5"), "--gap 0..5000")):
with self.subTest(argv=argv):
code, out = self.gamepad(*argv)
self.assertEqual((2, "INVALID_INPUT"), (code, out["error"]["code"]))
self.assertIn(message, out["error"]["message"])
self.assertFalse(self.calls())
def test_a_shell_without_uinput_is_unavailable(self):
self.configure({}, uinput_probe="no-dev-uinput")
code, out = self.gamepad("a")
self.assertEqual((3, "UINPUT_UNAVAILABLE"), (code, out["error"]["code"]))
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]])
def test_uinput_that_stops_early_fails(self):
self.configure({}, uinput_stdout="")
code, out = self.gamepad("a")
self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"]))
if __name__ == "__main__":
unittest.main()
+42 -7
View File
@@ -26,14 +26,16 @@ class EffectsSourceResolutionTest(unittest.TestCase):
header = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.h').read_text()
effects = (REPO / 'app/src/main/cpp/waylandcomp/src/effects_chain.c').read_text()
functions = '\n'.join(function(source, signature) for signature in (
'static void release_external_client_image(', 'static void release_external_client_draws(',
'static int foreign_image(', 'static void release_external_client_image(', 'static void release_external_client_draws(',
'static int map_draw(', 'static int draw_to_blit(',
'static int draw_to_scene_blit(', 'static int effects_source_draw(',
'static void effects_source_note(',
'static void effects_overlay_draws(',
'static int render_impl(', 'static int pass_begin_impl('))
functions = (re.search(r'static int spatial_mode\([^\n]+', effects).group() + '\n' +
re.search(r'static int cas_active\([^\n]+', effects).group() + '\n' +
function(effects, 'int vkp_effects_upscaling(') +
function(effects, 'int vkp_effects_sharpening(') +
function(effects, 'int vkp_effects_postprocessing(') + functions)
image = source[source.index('struct vkp_image {'):source.index('\n};', source.index('struct vkp_image {')) + 3]
draw = header[header.index('struct vkp_draw {'):header.index('\n};', header.index('struct vkp_draw {')) + 3]
@@ -101,6 +103,9 @@ class EffectsSourceResolutionTest(unittest.TestCase):
def test_postprocessing_keeps_foreground_inside_the_effect_chain(self):
self.check_case('postprocessing')
def test_frame_generation_keeps_upscaling_and_sharpening_at_panel_size(self):
self.check_case('framegen-sharpening')
TYPES = r'''
#include <assert.h>
@@ -108,7 +113,7 @@ TYPES = r'''
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter;
typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter, VkBuffer;
typedef int VkImageLayout, VkPipelineStageFlags, VkImageUsageFlags;
typedef uint64_t VkDeviceSize;
typedef struct { unsigned width, height; } VkExtent2D;
@@ -121,6 +126,13 @@ typedef struct {
VkImageSubresourceLayers dstSubresource;
VkOffset3D dstOffsets[2];
} VkImageBlit;
typedef struct {
VkDeviceSize bufferOffset;
unsigned bufferRowLength, bufferImageHeight;
VkImageSubresourceLayers imageSubresource;
VkOffset3D imageOffset;
struct { unsigned width, height, depth; } imageExtent;
} VkBufferImageCopy;
typedef struct { int sType, flags; } VkCommandBufferBeginInfo;
typedef struct {
int sType, oldLayout, newLayout, srcQueueFamilyIndex, dstQueueFamilyIndex;
@@ -156,6 +168,8 @@ typedef struct AHardwareBuffer AHardwareBuffer;
STUBS = r'''
static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { (void)cmd; (void)draws; (void)count; }
static int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { return dmabuf && !staged; }
static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; }
static int noop(int handle, ...) { return VK_SUCCESS; }
static VkImageMemoryBarrier recorded_barriers[64];
@@ -189,10 +203,11 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map;
static struct { VkImage img; int w, h; } g_scene;
struct vkp_img_slot { VkImage img; int w, h; };
static struct vkp_img_slot g_hdrscene, g_fgscene;
static struct { int active, rw, rh; VkImage result; } g_pass;
static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass;
static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf;
static int effects_active = 1, framegen, cardboard;
static struct { int scaling; } g_cur = {4};
struct fx_settings { int scaling, cas_on, cas_pct; };
static struct fx_settings g_cur = {4};
static int copy_count, effects_count, screen_count, hdr_count, fail_scene, fail_effects, postprocessing;
static int copied_w, copied_h, target_w, target_h;
static int effects_w, effects_h, output_w, output_h, logical_w, logical_h;
@@ -276,7 +291,7 @@ static struct vkp_draw fullscreen(void) {
}
static void reset(void) {
copy_count = effects_count = screen_count = hdr_count = barrier_count = 0;
effects_active = 1; g_cur.scaling = 4;
effects_active = 1; g_cur = (struct fx_settings){4};
framegen = cardboard = fail_scene = fail_effects = postprocessing = g_plain_frame = 0;
g_pass.active = 0; g_extent = (VkExtent2D){1920, 1080};
image.w = 1280; image.h = 720;
@@ -353,7 +368,7 @@ static void run_path(int offscreen, const struct vkp_draw *draw, int n, const st
assert(n > 0 && n <= 4);
memcpy(before, draw, n * sizeof(*draw));
int rw = 0, rh = 0;
assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, &rw, &rh)
assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, 0, &rw, &rh)
: render_impl(1920, 1080, draw, n, hdr, NULL)) == 0);
assert(memcmp(draw, before, n * sizeof(*draw)) == 0);
if (offscreen) assert(rw == (fail_effects ? effects_w : (int)g_extent.width) &&
@@ -378,7 +393,7 @@ static void check_path(int offscreen) {
run_path(offscreen, &draw, 1, NULL); check_input(1280, 720);
reset(); draw = fullscreen(); draw.dw = 1280; draw.dh = 720;
int rw, rh;
assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, &rw, &rh)
assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, 0, &rw, &rh)
: render_impl(1280, 720, &draw, 1, NULL, NULL)) == 0);
check_input(1280, 720);
}
@@ -552,6 +567,25 @@ static void check_allocation(void) {
assert(recorded_blits[1].dstOffsets[1].x == 1920 && recorded_blits[1].dstOffsets[1].y == 1080);
assert(target_w == 1920 && target_h == 1080);
}
static void check_framegen_output(int scaling, int cas, int grading, int panel) {
reset(); framegen = 1; postprocessing = grading;
g_cur = (struct fx_settings){scaling, cas, cas ? 60 : 0};
g_extent = (VkExtent2D){2880, 1620};
struct vkp_draw draw = fullscreen();
run_path(0, &draw, 1, NULL);
assert(effects_count == 1);
assert(output_w == (panel ? 2880 : 1920) && output_h == (panel ? 1620 : 1080));
}
static void check_framegen_sharpening(void) {
check_framegen_output(4, 0, 0, 1);
check_framegen_output(3, 0, 0, 1);
check_framegen_output(8, 0, 0, 1);
check_framegen_output(0, 1, 1, 1);
check_framegen_output(1, 1, 1, 1);
check_framegen_output(0, 0, 1, 0);
check_framegen_output(6, 0, 0, 0);
check_framegen_output(2, 0, 1, 0);
}
int main(int argc, char **argv) {
assert(argc == 2); reset();
if (!strcmp(argv[1], "helper")) check_helper();
@@ -567,6 +601,7 @@ int main(int argc, char **argv) {
else if (!strcmp(argv[1], "effect-failure")) check_effect_failure();
else if (!strcmp(argv[1], "overlay-barriers")) check_overlay_barriers();
else if (!strcmp(argv[1], "postprocessing")) check_postprocessing();
else if (!strcmp(argv[1], "framegen-sharpening")) check_framegen_sharpening();
else assert(0);
puts("PASS");
}
+29
View File
@@ -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()
+120
View File
@@ -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()
+148
View File
@@ -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()
+49
View File
@@ -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()
+211
View File
@@ -0,0 +1,211 @@
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0006-smc-alias-of-code-created-after-translation.patch"
HARNESS = r"""
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <map>
#include <string>
#include <sys/mman.h>
namespace FEXCore::Config {
enum { CONFIG_SMC_NONE, CONFIG_SMC_MTRACK, CONFIG_SMC_FULL };
}
namespace LogMan::Throw {
template<typename... Args> void AFmt(bool, const char*, Args...) {}
}
union VMAProt {
struct { bool Readable : 1; bool Writable : 1; bool Executable : 1; };
};
struct VMAFlags { bool Shared : 1; };
struct MappedResource;
struct VMAEntry {
MappedResource* Resource;
VMAEntry* ResourcePrevVMA;
VMAEntry* ResourceNextVMA;
uint64_t Base, Offset, Length;
VMAFlags Flags;
VMAProt Prot;
};
struct MappedResource { VMAEntry* FirstVMA; };
struct VMATrackingT {
std::map<uint64_t, VMAEntry> VMAs;
std::map<uint64_t, VMAEntry>::const_iterator FindVMAEntry(uint64_t Addr) const {
auto it = VMAs.upper_bound(Addr);
if (it == VMAs.begin()) return VMAs.end();
--it;
return Addr < it->first + it->second.Length ? it : VMAs.end();
}
};
struct Recorded { uint64_t Address, Length; int Prot; };
static Recorded calls[16];
static int count;
static int fake_mprotect(void* address, size_t length, int prot) {
calls[count++] = {(uint64_t)address, length, prot};
return 0;
}
#define mprotect fake_mprotect
struct SyscallHandler {
int SMCChecks = FEXCore::Config::CONFIG_SMC_MTRACK;
VMATrackingT VMATracking;
void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length);
};
#include "extracted.inc"
static MappedResource resource, other;
int main(int argc, char** argv) {
std::string scenario = argc > 1 ? argv[1] : "";
SyscallHandler handler;
VMAEntry code{}, alias{};
code.Resource = &resource;
code.Base = 0x100000;
code.Offset = 0x10000;
code.Length = 0x4000;
code.Flags.Shared = true;
code.Prot.Readable = true;
code.Prot.Executable = true;
alias.Resource = &resource;
alias.Base = 0x700000;
alias.Offset = 0x10000;
alias.Length = 0x4000;
alias.Flags.Shared = true;
alias.Prot.Readable = true;
alias.Prot.Writable = true;
uint64_t base = alias.Base, length = alias.Length;
if (scenario == "disjoint") {
code.Offset = 0x80000;
} else if (scenario == "partial") {
code.Offset = 0x12000;
code.Length = 0x1000;
} else if (scenario == "tail") {
base += 0x2000;
length = 0x10000;
} else if (scenario == "gap") {
base -= 0x2000;
length = 0x6000;
} else if (scenario == "two") {
length = 0x6000;
} else if (scenario == "no_code") {
code.Prot.Executable = false;
} else if (scenario == "private") {
alias.Flags.Shared = false;
} else if (scenario == "read_only") {
alias.Prot.Writable = false;
} else if (scenario == "full") {
handler.SMCChecks = FEXCore::Config::CONFIG_SMC_FULL;
} else if (scenario == "none") {
handler.SMCChecks = FEXCore::Config::CONFIG_SMC_NONE;
}
code.ResourceNextVMA = &alias;
alias.ResourcePrevVMA = &code;
resource.FirstVMA = &code;
handler.VMATracking.VMAs[code.Base] = code;
handler.VMATracking.VMAs[alias.Base] = alias;
handler.VMATracking.VMAs[code.Base].ResourceNextVMA = &handler.VMATracking.VMAs[alias.Base];
handler.VMATracking.VMAs[alias.Base].ResourcePrevVMA = &handler.VMATracking.VMAs[code.Base];
resource.FirstVMA = &handler.VMATracking.VMAs[code.Base];
handler.VMATracking.VMAs[code.Base].Resource = &resource;
handler.VMATracking.VMAs[alias.Base].Resource = &resource;
if (scenario == "two") {
VMAEntry& next_code = handler.VMATracking.VMAs[0x200000];
VMAEntry& next_alias = handler.VMATracking.VMAs[0x704000];
next_code = {};
next_code.Resource = &other;
next_code.Base = 0x200000;
next_code.Length = 0x2000;
next_code.Flags.Shared = true;
next_code.Prot.Readable = true;
next_code.Prot.Executable = true;
next_alias = {};
next_alias.Resource = &other;
next_alias.Base = 0x704000;
next_alias.Length = 0x2000;
next_alias.Flags.Shared = true;
next_alias.Prot.Readable = true;
next_alias.Prot.Writable = true;
next_code.ResourceNextVMA = &next_alias;
next_alias.ResourcePrevVMA = &next_code;
other.FirstVMA = &next_code;
}
handler.ProtectWritableAliasOfCode(base, length);
printf("%d", count);
for (int i = 0; i < count; i++) printf(" %llx+%llx:%d", (unsigned long long)calls[i].Address, (unsigned long long)calls[i].Length, calls[i].Prot);
printf("\n");
return 0;
}
"""
def extracted():
text = PATCH.read_text()
section = re.search(r"^diff --git a/\S*SyscallsSMCTracking\.cpp .*?(?=^diff --git |\Z)", text, re.S | re.M).group(0)
added = [line[1:] for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")]
body = "\n".join(added)
start = body.index("void SyscallHandler::ProtectWritableAliasOfCode")
end = body.index("\n}\n", start) + 3
return body[start:end]
class SmcAliasTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which("g++") or shutil.which("c++")
if not compiler:
raise unittest.SkipTest("no C++ compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-smc-alias-"))
(cls.tmp / "extracted.inc").write_text(extracted())
(cls.tmp / "harness.cpp").write_text(HARNESS)
subprocess.run([compiler, "-std=c++20", "-fno-strict-aliasing", "-I", str(cls.tmp), "-o", str(cls.tmp / "harness"), str(cls.tmp / "harness.cpp")],
check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def run_scenario(self, name=""):
return subprocess.run([str(self.tmp / "harness"), name], check=True, capture_output=True, text=True).stdout.strip()
def test_writable_alias_of_translated_code_is_read_only_until_it_faults(self):
self.assertEqual(self.run_scenario(), "1 700000+4000:1")
def test_only_the_overlapping_part_of_the_alias_is_protected(self):
self.assertEqual(self.run_scenario("partial"), "1 702000+1000:1")
def test_alias_beyond_the_mapping_end_is_clamped(self):
self.assertEqual(self.run_scenario("tail"), "1 702000+2000:1")
def test_range_starting_in_a_gap_reaches_the_alias_after_it(self):
self.assertEqual(self.run_scenario("gap"), "1 700000+4000:1")
def test_every_alias_in_one_range_is_protected(self):
self.assertEqual(self.run_scenario("two"), "2 700000+4000:1 704000+2000:1")
def test_alias_of_another_file_range_is_untouched(self):
self.assertEqual(self.run_scenario("disjoint"), "0")
def test_alias_without_an_executable_mirror_is_untouched(self):
self.assertEqual(self.run_scenario("no_code"), "0")
def test_private_and_read_only_mappings_are_untouched(self):
self.assertEqual(self.run_scenario("private"), "0")
self.assertEqual(self.run_scenario("read_only"), "0")
def test_explicit_smc_check_settings_are_respected(self):
self.assertEqual(self.run_scenario("full"), "0")
self.assertEqual(self.run_scenario("none"), "0")
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()
+124
View File
@@ -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()
+164 -17
View File
@@ -824,7 +824,6 @@ class GameEnvironmentTest(unittest.TestCase):
"offline_without_anticheat": lambda command, env: command,
"game_logs": lambda command, env, app_id: env,
"directaudio_settings": lambda env: env,
"vram_cap": lambda env: env,
"render_path_defaults": lambda *args: None,
"bridge_feature_level": lambda env: None,
"force_ssbs": lambda command, env: env,
@@ -1231,6 +1230,22 @@ class GameEnvironmentTest(unittest.TestCase):
env = gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""})
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
def applied(config, app_id="42", env=None):
return MODULE["apply_config"](env or {"TU_DEBUG": "sysmem"}, config, app_id)
prefixed = "DROIDDECK_GAME_TU_DEBUG"
config = {"version": 1, "games": {"42": {prefixed: "gmem"}, "43": {prefixed: ""}}}
self.assertEqual(applied(config)["TU_DEBUG"], "gmem")
self.assertNotIn("TU_DEBUG", applied(config, "43"))
self.assertNotIn(prefixed, applied(config))
shared = {"version": 1, "shared": {prefixed: "gmem"}, "games": {"42": {"TU_DEBUG": "nolrz"}, "43": {"TU_DEBUG": None}}}
self.assertEqual(applied(shared)["TU_DEBUG"], "nolrz")
self.assertNotIn("TU_DEBUG", applied(shared, "43"))
self.assertEqual(applied(shared, "44")["TU_DEBUG"], "gmem")
self.assertNotIn(prefixed, applied(shared, "44"))
both = {"version": 1, "games": {"42": {"TU_DEBUG": "sysmem", prefixed: ""}, "43": {"TU_DEBUG": None, prefixed: "gmem"}}}
self.assertEqual(applied(both)["TU_DEBUG"], "sysmem")
self.assertNotIn("TU_DEBUG", applied(both, "43", {"TU_DEBUG": "nolrz"}))
self.assertNotIn(prefixed, applied(both))
def test_games_run_with_gl_error_checks_unless_the_user_turns_them_off(self):
gpu = MODULE["game_gpu"]
@@ -1288,22 +1303,6 @@ class GameEnvironmentTest(unittest.TestCase):
link.symlink_to(other, target_is_directory=True)
self.assertTrue(chromium(str(link)))
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
cap = MODULE["vram_cap"]
self.assertEqual(cap({"DD_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096; dxgi.maxSharedMemory = 4096")
self.assertEqual(cap({"DD_VRAM_MB": "8192"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 8192; dxgi.maxSharedMemory = 8192")
self.assertEqual(cap({"DD_VRAM_MB": "4095"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4095; dxgi.maxSharedMemory = 4095; d3d9.maxAvailableMemory = 4095")
self.assertEqual(cap({"DD_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"],
"dxgi.maxDeviceMemory = 2048; dxgi.maxSharedMemory = 2048; d3d9.maxAvailableMemory = 2048; dxvk.maxFrameRate = 60")
for off in ({}, {"DD_VRAM_MB": "0"}, {"DD_VRAM_MB": "lots"}, {"DD_VRAM_MB": "²"}, {"DD_VRAM_MB": "-1"}):
self.assertNotIn("DXVK_CONFIG", cap(off))
self.assertNotIn("DROIDDECK_VRAM_CAP", cap(off))
self.assertNotIn("DROIDDECK_VRAM_CAP_MB", cap(off))
def test_the_vram_cap_also_turns_on_the_vulkan_layer_that_holds_the_game_to_it(self):
env = MODULE["vram_cap"]({"DD_VRAM_MB": "3072", "DXVK_CONFIG": "dxgi.maxDeviceMemory = 16384"})
self.assertEqual((env["DROIDDECK_VRAM_CAP"], env["DROIDDECK_VRAM_CAP_MB"]), ("1", "3072"))
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
env = {"DD_SYNC": "1", "DD_SYNC_FALLBACK": "1", "DD_FSYNC_FIRST": "0", "OTHER": "kept"}
config = {"version": 1, "games": {"42": {"DD_SYNC": "0", "DD_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
@@ -1537,6 +1536,18 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["engine_fixes"]("/game/FSD-Win64-Shipping.exe", []), ({}, [], []))
self.assertEqual(MODULE["engine_fixes"]("/game/Other-WinGDK-Shipping.exe", []), ({}, [], []))
def test_dragons_dogma_2_turns_its_wine_detection_off_unless_the_user_sets_it(self):
game = "/game/Dragons Dogma 2/DD2.exe"
env, extra, notes = MODULE["engine_fixes"](game, [], "2054970")
self.assertEqual(extra, ["/WineDetectionEnabled:False"])
self.assertEqual(env, {})
self.assertTrue(notes)
self.assertEqual(MODULE["engine_fixes"](game, ["-dx12"], "2054970")[1], ["/WineDetectionEnabled:False"])
for own in ("/WineDetectionEnabled:False", "/WineDetectionEnabled:True", "/winedetectionenabled:false"):
self.assertEqual(MODULE["engine_fixes"](game, [own], "2054970"), ({}, [], []))
self.assertEqual(MODULE["engine_fixes"](game, [], "42"), ({}, [], []))
self.assertEqual(MODULE["engine_fixes"](game, []), ({}, [], []))
def test_arkham_city_gets_full_x87_precision_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32"
@@ -1616,6 +1627,14 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertTrue(notes)
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
def test_black_ops_ii_starts_with_steam_exec_handling(self):
for exe in ("/game/Call of Duty Black Ops II/t6zm.exe", "/game/Call of Duty Black Ops II/t6mp.exe", "/game/Call of Duty Black Ops II/t6sp.exe"):
env, extra, notes = MODULE["engine_fixes"](exe, [])
self.assertEqual((env, extra), ({"WINESTEAMNOEXEC": "0"}, []))
self.assertTrue(notes)
self.assertEqual(MODULE["engine_fixes"]("/game/Game/Other.exe", [], "202990")[0], {"WINESTEAMNOEXEC": "0"})
self.assertEqual(MODULE["engine_fixes"]("/game/Game/Other.exe", []), ({}, [], []))
def test_little_nightmares_keeps_its_render_thread(self):
env, extra, notes = MODULE["engine_fixes"]("/game/Little Nightmares/Atlas/Binaries/Win64/LittleNightmares.exe", [])
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
@@ -1835,6 +1854,18 @@ class GameEnvironmentTest(unittest.TestCase):
config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}}
self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"})
def test_kcd2_runs_at_feature_level_12_2_by_app_id_unless_the_game_overrides_it(self):
with tempfile.TemporaryDirectory() as tmp:
exe = Path(tmp) / "Bin/Win64MasterMasterSteamPGO/KingdomCome.exe"
exe.parent.mkdir(parents=True)
exe.touch()
env, extra, notes = MODULE["engine_fixes"](str(exe), [], "1771300")
self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2", "VKD3D_SHADER_MODEL": "6_9"})
self.assertTrue(notes)
config = {"version": 1, "shared": {}, "games": {"1771300": {"VKD3D_FEATURE_LEVEL": "12_1"}}}
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_unity_players_keep_tso_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
def game(*names):
@@ -2243,6 +2274,87 @@ class ProtonDefaultTest(unittest.TestCase):
self.assertEqual(changes, {"0": "GE-Proton11-7", "10": "GE-Proton11-7", "11": "GE-Proton11-7", "14": "GE-Proton11-7"})
self.assertEqual(auto, {"10": "GE-Proton11-7", "11": "GE-Proton11-7", "14": "GE-Proton11-7"})
def test_games_on_a_removed_custom_proton_go_back_to_the_default(self):
changes, auto = COMPAT["plan_mapping"](
{"0": self.TOOL, "311210": "bo3fix-proton", "42": "GE-Proton11-7"}, ["311210", "42"], self.NAMES, self.TOOL, {},
removed={"bo3fix-proton"})
self.assertEqual(changes, {"311210": self.TOOL})
self.assertEqual(auto, {"311210": self.TOOL})
def test_removed_tools_are_custom_builds_missing_from_the_catalog(self):
state = {"tools": [
{"name": self.TOOL, "valve": True},
{"name": "bo3fix-proton", "valve": False},
{"name": "GE-Proton11-7", "valve": False},
]}
self.assertEqual(COMPAT["removed_tools"](state, self.CATALOG), {"bo3fix-proton"})
self.assertEqual(COMPAT["removed_tools"]({}, self.CATALOG), set())
def test_a_failed_extra_adoption_is_not_classified_as_removed(self):
with tempfile.TemporaryDirectory() as tmp:
tools = Path(tmp) / "compatibilitytools.d"
tools.mkdir()
state = {"tools": [{"name": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}]}
(tools / "GE-Proton11-7").mkdir()
catalog = [tool for tool in self.CATALOG if tool["name"] != "GE-Proton11-7"]
self.assertEqual(COMPAT["removed_tools"](state, catalog, str(tools)), set())
(tools / "GE-Proton11-7").rmdir()
self.assertEqual(COMPAT["removed_tools"](state, catalog, str(tools)), {"GE-Proton11-7"})
def test_a_build_being_replaced_is_not_classified_as_removed(self):
with tempfile.TemporaryDirectory() as tmp:
tools = Path(tmp) / "compatibilitytools.d"
state = {"tools": [{"name": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}]}
catalog = [tool for tool in self.CATALOG if tool["name"] != "GE-Proton11-7"]
aside = tools / COMPAT["REPLACING"] / "GE-Proton11-7"
aside.mkdir(parents=True)
self.assertEqual(COMPAT["removed_tools"](state, catalog, str(tools)), set())
aside.rmdir()
self.assertEqual(COMPAT["removed_tools"](state, catalog, str(tools)), {"GE-Proton11-7"})
def test_a_request_for_a_removed_tool_is_dropped_and_others_are_kept(self):
state = {"tools": self.CATALOG, "games_applied": {}}
requests = {"10": {"valve": False, "dir": "GE-Proton11-7"}, "11": {"valve": False, "dir": "Never-Installed"},
"12": {"valve": True, "dir": "GE-Proton11-7"}}
catalog = [tool for tool in self.CATALOG if tool["name"] != "GE-Proton11-7"]
settled, moved = COMPAT["settle_game_requests"](requests, state, {}, catalog, removed={"GE-Proton11-7"})
self.assertTrue(moved)
self.assertEqual(settled, {"11": requests["11"], "12": requests["12"]})
self.assertEqual(COMPAT["settle_game_requests"](requests, state, {}, catalog), (requests, False))
malformed = {"10": {"valve": False, "dir": []}}
self.assertEqual(COMPAT["settle_game_requests"](malformed, state, {}, catalog, removed={"GE-Proton11-7"}), (malformed, False))
def test_a_game_on_a_removed_tool_follows_the_default_across_registrations(self):
with tempfile.TemporaryDirectory() as tmp:
config = Path(tmp) / "config.vdf"
config.write_text(config_text([("0", self.TOOL), ("10", "GE-Proton11-7"), ("11", "GE-Proton11-7")]))
request = {"valve": False, "dir": "GE-Proton11-7"}
available = [tool for tool in self.CATALOG if tool["name"] != "GE-Proton11-7"]
(Path(tmp) / "games.json").write_text(json.dumps({"version": 1, "games": {"10": request}}))
(Path(tmp) / "state.json").write_text(json.dumps({
"default": self.TOOL,
"tools": self.CATALOG,
}))
for default in (self.TOOL, self.TOOL, COMPAT["TOOL_11"]):
COMPAT["register_default"](
str(config), ["10", "11"], default=default, catalog=available,
directory=tmp,
)
self.assertEqual(mapping_of(config.read_text()),
{"0": COMPAT["TOOL_11"], "10": COMPAT["TOOL_11"], "11": COMPAT["TOOL_11"]})
self.assertEqual(json.loads((Path(tmp) / "games.json").read_text())["games"], {})
def test_a_steam_pick_survives_the_removal_of_another_tool(self):
with tempfile.TemporaryDirectory() as tmp:
config = Path(tmp) / "config.vdf"
config.write_text(config_text([("0", self.TOOL), ("10", COMPAT["TOOL_11"])]))
available = [tool for tool in self.CATALOG if tool["name"] != "GE-Proton11-7"]
(Path(tmp) / "games.json").write_text(json.dumps(
{"version": 1, "games": {"10": {"valve": False, "dir": "GE-Proton11-7"}}}))
(Path(tmp) / "state.json").write_text(json.dumps({"default": self.TOOL, "tools": self.CATALOG, "auto": {}}))
COMPAT["register_default"](str(config), ["10"], default=self.TOOL, catalog=available, directory=tmp)
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "10": COMPAT["TOOL_11"]})
def test_windows_only_titles_still_follow_the_default(self):
changes, auto = COMPAT["plan_mapping"](
{"0": self.TOOL}, ["42"], self.NAMES, self.TOOL, {})
@@ -2586,6 +2698,41 @@ class ProtonDefaultTest(unittest.TestCase):
"11": COMPAT["TOOL_11"],
})
def test_per_game_proton_that_was_removed_goes_back_to_the_default(self):
with tempfile.TemporaryDirectory() as tmp:
config = Path(tmp) / "config.vdf"
config.write_text(config_text([
("0", self.TOOL),
("10", "Experimental-DroidDeck-Proton-11-12.8-pr34-build"),
("12", "GE-Proton9-1"),
]))
(Path(tmp) / "games.json").write_text(json.dumps({
"version": 1,
"games": {
"10": {"valve": False, "dir": "Experimental-DroidDeck-Proton-11-12.8-pr34-build"},
"12": {"valve": False, "dir": "GE-Proton9-1"},
},
}))
(Path(tmp) / "state.json").write_text(json.dumps({
"default": self.TOOL,
"tools": self.CATALOG + [{
"name": "Experimental-DroidDeck-Proton-11-12.8-pr34-build",
"display": "Experimental-DroidDeck-Proton-11-12.8-pr34-build",
"dir": "Experimental-DroidDeck-Proton-11-12.8-pr34-build", "valve": False,
}],
}))
COMPAT["register_default"](
str(config), ["10", "12"], default=self.TOOL,
catalog=self.CATALOG, directory=tmp,
)
self.assertEqual(mapping_of(config.read_text()), {
"0": self.TOOL,
"10": self.TOOL,
"12": "GE-Proton9-1",
})
def test_the_last_side_to_change_wins(self):
state = {"default": self.TOOL, "applied": 5}
default, state = COMPAT["choose_default"]("GE-Proton11-7", state, {"seq": 5, "dir": "Proton 11.0 (ARM64)", "valve": True}, self.CATALOG, now=100)
@@ -0,0 +1,70 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0140-focus-follows-window-opacity.patch"
def added_lines():
return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
def patched_rule():
text = "\n".join(added_lines())
start = text.index("static bool")
return text[start:text.index("\n}\n", start) + 3]
PREAMBLE = r'''
#include <cassert>
#include <cstdio>
#define TRANSLUCENT 0x00000000
#define OPAQUE 0xffffffff
'''
MAIN = r'''
int main() {
assert(opacity_changes_focus_candidacy(TRANSLUCENT, OPAQUE));
assert(opacity_changes_focus_candidacy(TRANSLUCENT, 0x01010101u));
assert(opacity_changes_focus_candidacy(OPAQUE, TRANSLUCENT));
assert(opacity_changes_focus_candidacy(0x80808080u, TRANSLUCENT));
assert(!opacity_changes_focus_candidacy(0x40404040u, 0xc0c0c0c0u));
assert(!opacity_changes_focus_candidacy(OPAQUE, 0x80808080u));
assert(!opacity_changes_focus_candidacy(TRANSLUCENT, TRANSLUCENT));
assert(!opacity_changes_focus_candidacy(OPAQUE, OPAQUE));
puts("ok");
return 0;
}
'''
@unittest.skipUnless(shutil.which("c++"), "needs a C++ compiler")
class FocusOpacityRuleTest(unittest.TestCase):
def test_only_crossing_fully_transparent_changes_focus_candidacy(self):
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "opacity.cpp"
binary = Path(tmp) / "opacity"
source.write_text(PREAMBLE + patched_rule() + MAIN)
subprocess.run(["c++", "-std=c++17", "-Wall", "-Werror", str(source), "-o", str(binary)], check=True)
self.assertEqual(subprocess.run([str(binary)], capture_output=True, text=True, check=True).stdout.strip(), "ok")
class FocusOpacityHandlerTest(unittest.TestCase):
def test_opacity_property_change_reevaluates_focus_when_candidacy_changes(self):
hunks = PATCH.read_text().split("\n@@ ")
handler = next(hunk for hunk in hunks if "handle_property_notify(" in hunk.split("\n", 1)[0])
added = [line[1:].strip() for line in handler.splitlines() if line.startswith("+")]
self.assertIn("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );", added)
self.assertIn("MakeFocusDirty();", added)
context = [line[1:].strip() for line in handler.splitlines() if line.startswith(" ")]
self.assertIn("w->opacity = newOpacity;", context)
self.assertLess(added.index("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );"), added.index("MakeFocusDirty();"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,118 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0138-limiter-even-cadence.patch"
def added_source():
return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
def block(text, start):
begin = text.index(start)
return text[begin:text.index("\n}", begin) + 3]
PREAMBLE = r'''
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <vector>
'''
MAIN = r'''
struct Run {
std::vector<int> gaps;
int frames = 0;
};
static Run run(int hz, int fps, int vblanks, uint64_t latency) {
const uint64_t cycle = 1000000000ull / hz;
const uint64_t limited = cycle * hz / fps;
uint64_t target = 0;
int last = -1;
Run r;
for (int i = 0; i < vblanks; i++) {
const uint64_t now = (1000ull + i) * cycle;
if (limiter_holds_vblank(target, now, limited, cycle)) continue;
target = limiter_latch_target(target, now + latency, limited, cycle);
if (last >= 0) r.gaps.push_back(i - last);
last = i;
r.frames++;
}
return r;
}
static void check(int hz, int fps, uint64_t latency) {
const int vblanks = hz * 20;
const Run r = run(hz, fps, vblanks, latency);
const int low = hz / fps;
const int high = (hz + fps - 1) / fps;
for (int gap : r.gaps) {
if (gap != low && gap != high) {
std::printf("%d Hz at %d fps: a frame was held for %d refreshes\n", hz, fps, gap);
assert(false);
}
}
const int expected = fps * 20;
if (r.frames < expected - 1 || r.frames > expected + 1) {
std::printf("%d Hz at %d fps: %d frames, expected %d\n", hz, fps, r.frames, expected);
assert(false);
}
}
int main() {
const int rates[] = {60, 90, 120, 144, 165};
const int limits[] = {24, 30, 36, 40, 45, 48, 50, 60, 72, 80, 90, 100, 120, 144};
for (int hz : rates) {
for (int fps : limits) {
if (fps > hz) continue;
check(hz, fps, 0);
check(hz, fps, 1000000000ull / hz / 4);
}
}
const Run even = run(60, 30, 600, 0);
for (int gap : even.gaps) assert(gap == 2);
const Run full = run(120, 120, 600, 0);
for (int gap : full.gaps) assert(gap == 1);
const Run two_of_three = run(60, 40, 600, 0);
for (size_t i = 1; i < two_of_three.gaps.size(); i++) assert(two_of_three.gaps[i] != two_of_three.gaps[i - 1]);
const uint64_t cycle = 16666666, limited = cycle * 60 / 45;
assert(limiter_latch_target(1000 * cycle, 1500 * cycle, limited, cycle) == 1500 * cycle);
assert(limiter_latch_target(1500 * cycle, 1000 * cycle, limited, cycle) == 1000 * cycle);
assert(limiter_latch_target(1000 * cycle, 1001 * cycle, limited, cycle) == 1000 * cycle + limited);
return 0;
}
'''
class GamescopeLimiterCadenceTest(unittest.TestCase):
def test_a_limit_the_refresh_rate_does_not_divide_is_spread_evenly(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
added = added_source()
source = PREAMBLE + block(added, "static uint64_t limiter_latch_target") + block(added, "static bool limiter_holds_vblank") + MAIN
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "limiter_cadence.cpp"
exe = Path(tmp) / "limiter_cadence"
src.write_text(source)
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
def test_the_limited_cycle_is_no_longer_a_whole_number_of_refreshes(self):
added = added_source()
self.assertIn("g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS", added)
removed = "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("-") and not line.startswith("---"))
self.assertIn("nVblankDivisor", removed)
if __name__ == "__main__":
unittest.main()
+87
View File
@@ -0,0 +1,87 @@
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0139-hdr-switch-live.patch"
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
RES = ROOT / "app/src/main/res"
def lines(prefix):
return [line[1:] for line in PATCH.read_text().splitlines()
if line.startswith(prefix) and not line.startswith(prefix * 3)]
class HdrLiveSwitchTest(unittest.TestCase):
def test_display_capability_does_not_depend_on_the_setting(self):
added = [line for line in lines("+") if "bExposeHDRSupport =" in line]
self.assertEqual(len(added), 1)
self.assertNotIn("cv_hdr_enabled", added[0])
self.assertIn("m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance", added[0])
def test_sdr_keeps_the_8_bit_output(self):
added = [line for line in lines("+") if "*pPrimaryPlaneFormat" in line]
self.assertEqual(len(added), 1)
self.assertRegex(added[0], r"cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID \) \? u10BitFormat : u8BitFormat")
def test_remade_output_images_pick_the_format_again(self):
text = PATCH.read_text()
hunk = text[text.index("src/rendervulkan.cpp"):]
added = [line[1:] for line in hunk.splitlines() if line.startswith("+") and not line.startswith("+++")]
self.assertEqual([line.strip() for line in added],
["GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay );"])
self.assertIn("if ( vulkan_defer_output_images() )", hunk[:hunk.index(added[0])])
def test_capable_display_does_not_force_dxvk_hdr_off(self):
added = "\n".join(lines("+"))
self.assertIn('unsetenv( "DXVK_HDR" )', added)
off = added.index('setenv( "DXVK_HDR", "0", true )')
self.assertIn("!GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport", added[:off])
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("DriverSetupLog.write", start)]
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")])
self.assertIn("capable, false", request)
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()
self.assertIn('setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0)', helper)
self.assertIn("nativeSetHdrOutput(on)", helper)
self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))", helper)
self.assertIn("SessionPrefs.prefMode(SessionState.mode) != mode", helper)
for name in ("SessionActivity.kt", "FrontEndActivity.kt"):
text = (APP / name).read_text()
self.assertEqual(len(re.findall(r"onHdr = \{ on -> com\.droiddeck\.launcher\.session\.SessionHdr\.set\(", text)), 1, name)
self.assertNotIn("SessionPrefs.setHdr(", text, name)
def test_a_saved_opt_out_applies_before_the_gate_opens(self):
native = (ROOT / "app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c").read_text()
switch = native[native.index("void droiddeck_color_set_output(int on)"):]
switch = switch[:switch.index("if (gate != 1)")]
self.assertLess(switch.index("pthread_mutex_lock(&g_output_mu)"), switch.index("atomic_store(&g_output_wanted, on)"))
self.assertLess(switch.index("atomic_exchange(&g_output_on, on)"), switch.index("pthread_mutex_unlock(&g_output_mu)"))
opened = native[native.index("atomic_store(&g_gate, 1);") - 40:]
opened = opened[:opened.index("pthread_mutex_unlock(&g_output_mu)")]
self.assertIn("pthread_mutex_lock(&g_output_mu)", opened)
self.assertIn("if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0);", opened)
text = (APP / "SessionActivity.kt").read_text()
self.assertNotIn("if (attached) WaylandCompositor.nativeSetHdrOutput", text)
def test_retries_stay_with_the_session_that_asked(self):
helper = (APP / "session/SessionHdr.kt").read_text()
self.assertIn("val session = SessionState.sessionId", helper)
self.assertIn("SessionState.sessionId == session", helper)
def test_no_restart_hint_is_left(self):
for path in list(RES.glob("values*/strings.xml")) + list(APP.rglob("*.kt")):
self.assertNotIn("mode_hdr_restart", path.read_text(), str(path))
if __name__ == "__main__":
unittest.main()
+185
View File
@@ -0,0 +1,185 @@
import json
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
BIN = ROOT / "tools/linuxfs/overlay/usr/local/bin"
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
HARNESS = r"""
const assert = require('assert');
globalThis.window = globalThis;
globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64');
let now = 0, tick = null;
Object.defineProperty(globalThis, 'performance', { value: { now: () => now }, configurable: true });
globalThis.setInterval = callback => { tick = callback; return 1; };
const varints = bytes => { const out = []; let value = 0, shift = 0;
for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } }
return out; };
const writes = [], told = [];
let apply = true;
globalThis.settingsStore = { clientSettings: { gamescope_hdr_enabled: false } };
globalThis.SteamClient = { Settings: { SetSetting(encoded) {
const [key, value] = varints([...Buffer.from(encoded, 'base64')]);
assert.strictEqual(key, 21015 * 8);
writes.push(value);
if (apply) settingsStore.clientSettings.gamescope_hdr_enabled = value === 1;
} } };
window.droiddeckHdrChanged = value => told.push(value);
const script = require('fs').readFileSync(process.argv[2], 'utf8');
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
const bridge = window.__droiddeckHdr;
tick();
assert.deepStrictEqual(told, [], 'an unchanged client setting is not reported');
assert.strictEqual(bridge.set(true), true);
assert.deepStrictEqual(writes, [1]);
tick();
assert.deepStrictEqual(told, [], 'a value the app set is not reported back to it');
assert.strictEqual(bridge.set(true), true);
assert.deepStrictEqual(writes, [1], 'an equal value is not written again');
settingsStore.clientSettings.gamescope_hdr_enabled = false;
tick();
assert.deepStrictEqual(told, ['0'], 'a change made in the client reaches the app');
tick();
assert.deepStrictEqual(told, ['0']);
settingsStore.clientSettings.gamescope_hdr_enabled = true;
tick();
assert.deepStrictEqual(told, ['0', '1']);
apply = false;
bridge.set(false);
assert.deepStrictEqual(writes, [1, 0]);
now += 500; tick();
assert.deepStrictEqual(told, ['0', '1'], 'the old value is not reported while a write is settling');
now += 3000; tick();
assert.deepStrictEqual(told, ['0', '1', '1'], 'a write the client did not take is reported as its real value');
assert.strictEqual(bridge.set('yes'), true);
assert.deepStrictEqual(writes, [1, 0]);
bridge.set(false);
bridge.set(true);
assert.deepStrictEqual(writes, [1, 0, 0, 1], 'a newer opposite value is written while the earlier write is settling');
settingsStore.clientSettings.gamescope_hdr_enabled = false;
now += 500; tick();
settingsStore.clientSettings.gamescope_hdr_enabled = true;
now += 500; tick();
assert.deepStrictEqual(told, ['0', '1', '1'], 'the earlier write landing late is not reported to the app');
delete globalThis.__droiddeckHdr;
delete settingsStore.clientSettings.gamescope_hdr_enabled;
assert.strictEqual(eval(script), 'unavailable');
"""
class HdrSteamSyncTest(unittest.TestCase):
def test_bridge_keeps_the_client_setting_and_the_app_equal(self):
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "bridge.js"
script.write_text(LIVE["HDR_JS"])
test = Path(directory) / "test.js"
test.write_text(HARNESS)
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_requests_accept_only_on_and_off(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "hdr.request"
for value in ["2", "true", "", None, 1]:
LIVE["hdr_request"](value, directory)
self.assertFalse(path.exists())
LIVE["hdr_request"]("1", directory)
self.assertEqual(path.read_text(), "1\n")
LIVE["hdr_request"]("0", directory)
self.assertEqual(path.read_text(), "0\n")
def helper(self, directory):
helper = LIVE["Helper"]("/steam", 0)
calls = []
class Page:
answer = True
def call(self, method, params=None):
calls.append((method, params))
def evaluate(self, expression):
calls.append(expression)
return "installed" if expression == LIVE["HDR_JS"] else self.answer
helper.page = Page()
return helper, calls
def test_the_app_state_is_applied_once_per_change(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_hdr.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
helper, calls = self.helper(directory)
path = Path(directory) / "state.json"
helper.sync_hdr()
path.write_text(json.dumps({"brightness": 0.5}))
helper.sync_hdr()
self.assertEqual(calls, [], "a session that cannot show HDR leaves the client setting alone")
path.write_text(json.dumps({"brightness": 0.5, "hdr": True}))
helper.sync_hdr()
helper.sync_hdr()
self.assertEqual(calls[0], ("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]}))
self.assertEqual(calls[1], LIVE["HDR_JS"])
self.assertEqual(calls[2:], ["window.__droiddeckHdr ? window.__droiddeckHdr.set(true) : false"])
path.write_text(json.dumps({"brightness": 0.7, "hdr": True}))
helper.sync_hdr()
self.assertEqual(len(calls), 3)
path.write_text(json.dumps({"hdr": False}))
helper.sync_hdr()
self.assertEqual(calls[3], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false")
helper.page.answer = False
path.write_text(json.dumps({"hdr": True}))
helper.sync_hdr()
self.assertFalse(helper.hdr_installed)
self.assertIsNone(helper.hdr_state)
helper.page.answer = True
path.write_text(json.dumps({"hdr": False}))
helper.sync_hdr()
self.assertEqual(calls[-1], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false")
finally:
globals_["CONTROLS_DIR"] = previous
def test_a_client_without_the_setting_is_left_alone(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_hdr.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
helper, calls = self.helper(directory)
helper.page.evaluate = lambda expression: calls.append(expression) or "unavailable"
(Path(directory) / "state.json").write_text(json.dumps({"hdr": True}))
helper.sync_hdr()
self.assertEqual(calls, [("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]}), LIVE["HDR_JS"]])
self.assertFalse(helper.hdr_installed)
self.assertIsNone(helper.hdr_state)
helper.sync_hdr()
self.assertEqual(len(calls), 2, "a client without the setting is not asked again straight away")
finally:
globals_["CONTROLS_DIR"] = previous
def test_the_app_publishes_and_takes_the_shared_value(self):
controls = (APP / "runtime/DeviceControlsComponent.kt").read_text()
self.assertIn('if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr)', controls)
self.assertIn('"hdr.request" -> if (text == "0" || text == "1")', controls)
self.assertIn('SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1")', controls)
self.assertIn('"hdr.request")', controls[controls.index("REQUESTS = setOf"):])
session = (APP / "SessionActivity.kt").read_text()
self.assertIn("if (key == SessionPrefs.hdrKey(hdrPrefMode()))", session)
self.assertIn("registerOnSharedPreferenceChangeListener(hdrPrefListener)", session)
self.assertIn("unregisterOnSharedPreferenceChangeListener(hdrPrefListener)", session)
def test_frame_limit_writes_share_the_setting_writer(self):
self.assertIn("(21002, value)", LIVE["FRAME_LIMIT_JS"])
self.assertNotIn("__SET_SETTING__", LIVE["FRAME_LIMIT_JS"] + LIVE["HDR_JS"])
if __name__ == "__main__":
unittest.main()
+664
View File
@@ -0,0 +1,664 @@
from pathlib import Path
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
ONCE = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
static pthread_once_t once = PTHREAD_ONCE_INIT;
static long (*next_syscall)(long, ...);
static void init(void) { next_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall"); }
ssize_t readlink(const char *path, char *buf, size_t size) {
pthread_once(&once, init);
return next_syscall(SYS_readlinkat, -100, path, buf, size);
}
__attribute__((constructor)) static void start(void) {
char link[4096];
readlink("/proc/self/exe", link, sizeof(link));
}
"""
FIRST = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stddef.h>
int marker(void) { return 1; }
int next_marker(void) {
int (*next)(void) = (int (*)(void))dlsym(RTLD_NEXT, "marker");
return next != NULL ? next() : 0;
}
"""
SECOND = "int marker(void) { return 2; }\n"
CHAIN = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stddef.h>
static int calls;
int chained(void) { return calls > 1; }
void *dlsym(void *handle, const char *name) {
static void *(*real)(void *, const char *);
if (real == NULL) real = (void *(*)(void *, const char *))dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.2.5");
if (real == NULL) real = (void *(*)(void *, const char *))dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.17");
if (real == NULL) real = (void *(*)(void *, const char *))dlvsym(RTLD_NEXT, "dlsym", "GLIBC_2.34");
calls++;
return real(handle, name);
}
"""
MARK = r"""
#include <stdlib.h>
#include <string.h>
char *realpath(const char *path, char *resolved) {
(void)path;
if (resolved == NULL) return strdup("marked");
strcpy(resolved, "marked");
return resolved;
}
"""
LOCKED = r"""
#include <sys/syscall.h>
#include <unistd.h>
extern int busy;
__attribute__((constructor)) static void start(void) {
busy = 1;
syscall(SYS_getpid);
busy = 0;
}
"""
ARENA = r"""
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static _Alignas(64) unsigned char arena[1 << 23];
static size_t used;
int busy;
static int busy_allocations;
void *memalign(size_t align, size_t size) {
uintptr_t start;
if (busy) busy_allocations++;
if (align < 16) align = 16;
start = ((uintptr_t)(arena + used) + 16 + align - 1) & ~(uintptr_t)(align - 1);
if (start + size > (uintptr_t)(arena + sizeof(arena))) return NULL;
((size_t *)start)[-1] = size;
used = start + size - (uintptr_t)arena;
return (void *)start;
}
void *malloc(size_t size) { return memalign(16, size); }
void *aligned_alloc(size_t align, size_t size) { return memalign(align, size); }
int posix_memalign(void **out, size_t align, size_t size) { return (*out = memalign(align, size)) ? 0 : 12; }
void free(void *p) { (void)p; }
void *calloc(size_t n, size_t size) {
void *p = malloc(n * size);
if (p) memset(p, 0, n * size);
return p;
}
void *realloc(void *p, size_t size) {
void *q = malloc(size);
if (p && q) {
size_t old = ((size_t *)p)[-1];
memcpy(q, p, old < size ? old : size);
}
return q;
}
int main(void) {
printf("allocations %d\n", busy_allocations);
return 0;
}
"""
UDEV = r"""
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list { const char *name; struct list *next; };
struct enumerate { struct list head; struct list added; char name[16]; int fail; };
void *udev_enumerate_new(void *udev) {
static int count;
struct enumerate *enumerate = calloc(1, sizeof(*enumerate));
(void)udev;
snprintf(enumerate->name, sizeof(enumerate->name), "real%d", count++);
enumerate->head.name = enumerate->name;
enumerate->added.name = "added";
return enumerate;
}
void *udev_enumerate_unref(void *enumerate) { free(enumerate); return NULL; }
int udev_enumerate_add_match_subsystem(void *enumerate, const char *subsystem) {
if (strcmp(subsystem, "fail") == 0) ((struct enumerate *)enumerate)->fail = 1;
return 0;
}
int udev_enumerate_add_match_parent(void *enumerate, void *parent) {
if (parent == NULL) return -1;
((struct enumerate *)enumerate)->head.name = "parented";
return 0;
}
int udev_enumerate_add_syspath(void *enumerate, const char *syspath) {
(void)syspath;
((struct enumerate *)enumerate)->head.next = &((struct enumerate *)enumerate)->added;
return 0;
}
int udev_enumerate_scan_devices(void *enumerate) { return ((struct enumerate *)enumerate)->fail ? -1 : 0; }
void *udev_enumerate_get_list_entry(void *enumerate) { return &((struct enumerate *)enumerate)->head; }
void *udev_list_entry_get_next(void *entry) { return ((struct list *)entry)->next; }
void *udev_list_entry_get_by_name(void *entry, const char *name) {
return strcmp(((struct list *)entry)->name, name) == 0 ? entry : NULL;
}
const char *udev_list_entry_get_name(void *entry) { return ((struct list *)entry)->name; }
void *udev_device_new_from_syspath(void *udev, const char *syspath) { (void)udev; (void)syspath; return NULL; }
void *udev_device_new_from_subsystem_sysname(void *udev, const char *subsystem, const char *sysname) {
(void)udev; (void)subsystem; (void)sysname;
return NULL;
}
int real_device_calls;
void *udev_device_unref(void *device) { (void)device; real_device_calls++; return NULL; }
void *udev_device_ref(void *device) { (void)device; real_device_calls++; return NULL; }
void *udev_device_get_parent(void *device) { (void)device; real_device_calls++; return NULL; }
void *udev_device_get_udev(void *device) { (void)device; real_device_calls++; return NULL; }
const char *udev_device_get_syspath(void *device) { (void)device; real_device_calls++; return "real"; }
const char *udev_device_get_sysnum(void *device) { (void)device; real_device_calls++; return "real"; }
void *udev_device_new_from_devnum(void *udev, char type, unsigned long devnum) {
(void)udev; (void)type; (void)devnum;
return NULL;
}
"""
DEVICE_FUNCTIONS = (
"p:udev_device_ref", "p:udev_device_get_udev", "p:udev_device_get_parent",
"P:udev_device_get_parent_with_subsystem_devtype", "s:udev_device_get_devpath", "s:udev_device_get_subsystem",
"s:udev_device_get_devtype", "s:udev_device_get_syspath", "s:udev_device_get_sysname",
"s:udev_device_get_sysnum", "s:udev_device_get_devnode", "i:udev_device_get_is_initialized",
"p:udev_device_get_devlinks_list_entry", "p:udev_device_get_properties_list_entry",
"p:udev_device_get_tags_list_entry", "p:udev_device_get_current_tags_list_entry",
"p:udev_device_get_sysattr_list_entry", "S:udev_device_get_property_value", "s:udev_device_get_driver",
"d:udev_device_get_devnum", "s:udev_device_get_action", "u:udev_device_get_seqnum",
"u:udev_device_get_usec_since_initialized", "S:udev_device_get_sysattr_value",
"W:udev_device_set_sysattr_value", "I:udev_device_has_tag", "I:udev_device_has_current_tag",
"p:udev_device_unref",
)
SIGNATURES = {
"p": ("void *", ""), "s": ("const char *", ""), "i": ("int", ""), "d": ("dev_t", ""),
"u": ("unsigned long long", ""), "S": ("const char *", ", const char *a"), "I": ("int", ", const char *a"),
"P": ("void *", ", const char *a, const char *b"), "W": ("int", ", const char *a, const char *b"),
}
UDEV += "#include <sys/types.h>\n" + "".join(
f"{SIGNATURES[kind][0]} {name}(void *device{SIGNATURES[kind][1]}) {{ (void)device; real_device_calls++; return 0; }}\n"
for kind, _, name in (entry.partition(":") for entry in DEVICE_FUNCTIONS) if not re.search(rf"\b{name}\(", UDEV))
PROGRAM = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#define PAD "/sys/devices/virtual/input/droiddeck0"
#define PARENT0 "/sys/devices/droiddeck0/droiddeck-input0"
#define EVENT0 PARENT0 "/event0"
#define EVENT1 "/sys/devices/droiddeck1/droiddeck-input1/event1"
#define HANDLES 256
int next_marker(void);
static void *lib;
static void *(*new_device)(void *, const char *);
static void *(*new_sysname)(void *, const char *, const char *);
static void *(*ref)(void *);
static void *(*unref)(void *);
static void *(*get_parent)(void *);
static void *(*get_udev)(void *);
static const char *(*syspath)(void *);
static const char *(*sysname)(void *);
static const char *(*sysnum)(void *);
static const char *(*devnode)(void *);
static const char *(*property)(void *, const char *);
static void *(*properties)(void *);
static void *(*enumerate_new)(void *);
static int (*match)(void *, const char *);
static int (*match_parent)(void *, void *);
static int (*add_syspath)(void *, const char *);
static int (*scan)(void *);
static void *(*list)(void *);
static void *(*next)(void *);
static void *(*by_name)(void *, const char *);
static const char *(*name)(void *);
static const char *(*value)(void *);
static void *sym(const char *symbol) { return dlsym(lib, symbol); }
static const char *entry_name(void *entry) { return entry != NULL ? name(entry) : "none"; }
static void print_list(const char *label, void *entry) {
printf("%s", label);
for (; entry != NULL; entry = next(entry)) printf(" %s", name(entry));
printf("\n");
}
static void print_properties(const char *label, void *device) {
void *entry;
printf("%s", label);
for (entry = properties(device); entry != NULL; entry = next(entry)) printf(" %s=%s", name(entry), value(entry));
printf("\n");
}
static void *matched(void *udev, const char *subsystem) {
void *enumerate = enumerate_new(udev);
match(enumerate, subsystem);
return enumerate;
}
static void pad_file(const char *node, int present) {
char path[4096];
FILE *file;
snprintf(path, sizeof(path), "%s/%s", getenv("FAKE_EVDEV_DIR"), node);
if (!present) {
unlink(path);
} else if ((file = fopen(path, "w")) != NULL) {
fclose(file);
}
}
static void run_udev(void) {
int udev_a, udev_b, i, failures = 0;
void *device, *parent, *other, *entry, *held[HANDLES] = {0};
char resolved[4096];
const char *path;
printf("missing %d\n", sym("udev_no_such_symbol") == NULL);
printf("plain %d\n", dlsym(RTLD_DEFAULT, "printf") != NULL);
device = new_device(&udev_a, PAD);
printf("syspath %s sysnum %s devnode %s\n", syspath(device), sysnum(device), devnode(device));
parent = get_parent(device);
printf("nested %d\n", strncmp(syspath(device), syspath(parent), strlen(syspath(parent))) == 0 &&
syspath(device)[strlen(syspath(parent))] == '/');
other = new_device(&udev_a, EVENT0);
printf("canonical %s\n", other != NULL ? syspath(other) : "none");
if (other != NULL) unref(other);
printf("parent %s sysname %s stable %d\n", syspath(parent), sysname(parent), parent == get_parent(device));
print_properties("device properties", device);
print_properties("parent properties", parent);
entry = properties(device);
printf("joystick %s unknown %d\n", value(by_name(entry, "ID_INPUT_JOYSTICK")), by_name(entry, "NO_SUCH_KEY") == NULL);
ref(device);
unref(device);
printf("held %s\n", syspath(device));
ref(parent);
unref(device);
printf("retained %s\n", syspath(parent));
unref(parent);
for (i = 0; i < 1000; i++) {
device = new_device(&udev_a, PAD);
if (device == NULL || get_parent(device) == NULL || get_parent(device) != get_parent(device) ||
strcmp(syspath(device), EVENT0) != 0)
failures++;
if (device != NULL) unref(device);
}
printf("reuse failures %d\n", failures);
for (i = 0; i < HANDLES && (held[i] = new_device(&udev_a, PAD)) != NULL; i++) {
}
printf("full %d extra %d parent %d\n", i, new_device(&udev_a, PAD) == NULL, get_parent(held[0]) == NULL);
unref(held[1]);
parent = get_parent(held[0]);
printf("freed parent %s stable %d\n", parent != NULL ? syspath(parent) : "none", parent == get_parent(held[0]));
for (i = 0; i < HANDLES; i++)
if (i != 1 && held[i] != NULL) unref(held[i]);
path = realpath("/sys/class/input/droiddeck-input0", resolved);
printf("parent link %s\n", path != NULL ? path : "none");
path = realpath("/sys/class/input/input0", resolved);
printf("kernel link shadowed %d\n", path != NULL && strncmp(path, "/sys/devices/droiddeck", 22) == 0);
printf("kernel sysname shadowed %d\n", new_sysname(&udev_a, "input", "input0") != NULL);
other = new_sysname(&udev_a, "input", "droiddeck-input0");
printf("parent sysname %s\n", other != NULL ? syspath(other) : "none");
if (other != NULL) unref(other);
device = new_device(&udev_a, PAD);
other = new_device(&udev_b, PAD);
printf("contexts %d %d\n", get_udev(device) == (void *)&udev_a, get_udev(other) == (void *)&udev_b);
}
static void run_stable(void) {
int udev;
char copy[64];
void *device = new_device(&udev, PAD);
const char *before = devnode(device);
snprintf(copy, sizeof(copy), "%s", before);
pad_file("event0", 0);
printf("gone %d\n", new_device(&udev, PAD) == NULL);
printf("devnode %s same %d property %s\n", devnode(device), devnode(device) == before && strcmp(before, copy) == 0,
property(device, "DEVNAME"));
}
static void run_enumerate(void) {
int udev, i;
void *first, *entry, *found, *missing, *failed, *parented, *real_parent, *device, *parent, *other;
first = matched(&udev, "input");
scan(first);
entry = list(first);
print_list("scan", entry);
pad_file("event1", 1);
print_list("same scan", list(first));
entry = list(first);
found = by_name(entry, EVENT0);
missing = by_name(entry, EVENT1);
printf("by name %s missing %d\n", entry_name(found), missing == NULL);
for (i = 0; i < 20; i++) {
void *other = matched(&udev, "input");
scan(other);
list(other);
}
printf("kept tail %s\n", entry_name(next(entry)));
scan(first);
print_list("rescan", list(first));
printf("rescan by name %s\n", entry_name(by_name(list(first), EVENT1)));
add_syspath(first, "/sys/devices/added");
print_list("added", list(first));
failed = matched(&udev, "input");
match(failed, "fail");
printf("failed scan %d\n", scan(failed));
print_list("failed", list(failed));
device = new_device(&udev, PAD);
parent = get_parent(device);
parented = enumerate_new(&udev);
printf("synthetic parent %d\n", match_parent(parented, parent));
scan(parented);
print_list("parented", list(parented));
real_parent = enumerate_new(&udev);
printf("real parent %d\n", match_parent(real_parent, &udev));
scan(real_parent);
print_list("real parent list", list(real_parent));
other = matched(&udev, "input");
match_parent(other, &udev);
scan(other);
print_list("real parent suppressed", list(other));
other = matched(&udev, "input");
match_parent(other, parent);
match_parent(other, &udev);
scan(other);
print_list("real replaces synthetic", list(other));
other = matched(&udev, "input");
match_parent(other, &udev);
match_parent(other, parent);
scan(other);
print_list("synthetic replaces real", list(other));
other = matched(&udev, "input");
match_parent(other, parent);
printf("bad parent %d\n", match_parent(other, NULL));
scan(other);
print_list("bad parent kept", list(other));
other = enumerate_new(&udev);
match(other, "fail");
match_parent(other, parent);
printf("nothing added scan %d\n", scan(other));
}
static void run_every(int count, char **entries) {
void *(*from_devnum)(void *, char, dev_t) = sym("udev_device_new_from_devnum");
int *real_calls = dlsym(lib, "real_device_calls");
int udev;
void *pad = from_devnum(&udev, 'c', makedev(13, 64));
int i;
for (i = 0; pad != NULL && i < count; i++) {
const char *name = entries[i] + 2;
void *call = sym(name);
if (call == NULL) {
printf("missing %s\n", name);
continue;
}
switch (entries[i][0]) {
case 'p': ((void *(*)(void *))call)(pad); break;
case 's': ((const char *(*)(void *))call)(pad); break;
case 'i': ((int (*)(void *))call)(pad); break;
case 'd': ((dev_t (*)(void *))call)(pad); break;
case 'u': ((unsigned long long (*)(void *))call)(pad); break;
case 'S': ((const char *(*)(void *, const char *))call)(pad, "attr"); break;
case 'I': ((int (*)(void *, const char *))call)(pad, "attr"); break;
case 'P': ((void *(*)(void *, const char *, const char *))call)(pad, "input", NULL); break;
case 'W': ((int (*)(void *, const char *, const char *))call)(pad, "attr", "value"); break;
default: printf("unknown signature %s\n", entries[i]);
}
}
printf("pad %d real calls %d\n", pad != NULL, real_calls != NULL ? *real_calls : -1);
}
static void run_probe(void) {
int udev;
printf("pad %d\n", new_device(&udev, PAD) != NULL);
}
int main(int argc, char **argv) {
char link[4096];
if (strcmp(argv[1], "once") == 0) {
printf("readlink %d\n", readlink("/proc/self/exe", link, sizeof(link)) > 0);
return 0;
}
if (strcmp(argv[1], "next") == 0) {
int (*chained)(void) = (int (*)(void))dlsym(RTLD_DEFAULT, "chained");
printf("next %d\n", next_marker());
if (chained != NULL) printf("chained %d\n", chained());
return 0;
}
lib = dlopen(argv[2], RTLD_NOW | RTLD_LOCAL);
if (strcmp(argv[1], "realpath") == 0) {
printf("realpath %s\n", realpath("/no/such/inputudev/path", link));
return 0;
}
new_device = sym("udev_device_new_from_syspath");
new_sysname = sym("udev_device_new_from_subsystem_sysname");
ref = sym("udev_device_ref");
unref = sym("udev_device_unref");
get_parent = sym("udev_device_get_parent");
get_udev = sym("udev_device_get_udev");
syspath = sym("udev_device_get_syspath");
sysname = sym("udev_device_get_sysname");
sysnum = sym("udev_device_get_sysnum");
devnode = sym("udev_device_get_devnode");
property = sym("udev_device_get_property_value");
properties = sym("udev_device_get_properties_list_entry");
enumerate_new = sym("udev_enumerate_new");
match = sym("udev_enumerate_add_match_subsystem");
match_parent = sym("udev_enumerate_add_match_parent");
add_syspath = sym("udev_enumerate_add_syspath");
scan = sym("udev_enumerate_scan_devices");
list = sym("udev_enumerate_get_list_entry");
next = sym("udev_list_entry_get_next");
by_name = sym("udev_list_entry_get_by_name");
name = sym("udev_list_entry_get_name");
value = sym("udev_list_entry_get_value");
if (strcmp(argv[1], "probe") == 0) run_probe();
else if (strcmp(argv[1], "every") == 0) run_every(argc - 3, argv + 3);
else if (strcmp(argv[1], "stable") == 0) run_stable();
else if (strcmp(argv[1], "enumerate") == 0) run_enumerate();
else run_udev();
fflush(stdout);
return 0;
}
"""
def compile_c(*args):
result = subprocess.run(["cc", *args], capture_output=True, text=True)
if result.returncode != 0:
raise AssertionError(f"cc {' '.join(args)} failed:\n{result.stderr}")
return result.stdout
@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc")
class InputUdevPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
cls.addClassCleanup(shutil.rmtree, cls.dir, ignore_errors=True)
build = cls.dir / "build"
build.mkdir()
if "__GLIBC__" not in compile_c("-dM", "-E", "-x", "c", "-include", "limits.h", "/dev/null"):
raise unittest.SkipTest("needs a glibc toolchain")
sources = (("once.c", ONCE), ("first.c", FIRST), ("second.c", SECOND), ("chain.c", CHAIN), ("mark.c", MARK),
("udev.c", UDEV), ("program.c", PROGRAM), ("locked.c", LOCKED), ("arena.c", ARENA))
for name, text in sources:
(build / name).write_text(text)
cls.lib = cls.dir / "libddsession.so"
compile_c("-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl")
for name in ("once", "first", "second", "chain", "mark"):
compile_c("-shared", "-fPIC", "-O0", "-pthread", "-o", str(cls.dir / f"lib{name}.so"),
str(build / f"{name}.c"), "-ldl")
cls.udev = cls.dir / "libudev.so.1"
compile_c("-shared", "-fPIC", "-O2", "-o", str(cls.udev), str(build / "udev.c"))
cls.program = cls.dir / "program"
compile_c("-O0", "-o", str(cls.program), str(build / "program.c"), str(cls.dir / "libfirst.so"), "-ldl")
compile_c("-shared", "-fPIC", "-O0", "-o", str(cls.dir / "liblocked.so"), str(build / "locked.c"))
cls.arena = cls.dir / "arena"
compile_c("-O0", "-rdynamic", "-o", str(cls.arena), str(build / "arena.c"), "-Wl,--no-as-needed",
str(cls.dir / "liblocked.so"),
f"-Wl,-rpath,{cls.dir}")
cls.pads = cls.pad_dir("pads", "event0")
@classmethod
def pad_dir(cls, name, *nodes):
pads = cls.dir / name
pads.mkdir()
for node in nodes:
(pads / node).write_text("")
return pads
def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None, args=()):
env = dict(os.environ, LD_PRELOAD=":".join(str(self.dir / name) for name in ("libddsession.so", *preloads)),
FAKE_EVDEV_MEMFD_PATHS=slots, FAKE_EVDEV_DIR=str(pads or self.pads))
env.pop("FAKE_EVDEV_UINPUT", None)
result = subprocess.run([str(program or self.program), mode, str(self.udev), *args], env=env, capture_output=True, text=True,
timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout.splitlines()
def test_a_lookup_from_another_preloads_initialiser_does_not_reenter_it(self):
self.assertEqual(self.run_program("once", "libonce.so"), ["readlink 1"])
def test_a_first_wrapped_call_inside_the_programs_allocator_does_not_allocate(self):
result = subprocess.run([str(self.arena)], env=dict(os.environ, LD_PRELOAD=str(self.lib)), capture_output=True,
text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines(), ["allocations 0"])
def test_the_real_lookup_still_sees_the_original_caller(self):
self.assertEqual(self.run_program("next", "libfirst.so", "libsecond.so"), ["next 2"])
def test_another_preloads_dlsym_stays_in_the_chain(self):
self.assertEqual(self.run_program("next", "libfirst.so", "libchain.so", "libsecond.so"), ["next 2", "chained 1"])
def test_non_udev_lookups_skip_the_opened_libudev(self):
self.assertEqual(self.run_program("realpath", "libmark.so"), ["realpath marked"])
def test_a_program_resolving_udev_through_dlsym_gets_the_pads(self):
parent = "/sys/devices/droiddeck0/droiddeck-input0"
pad = f"{parent}/event0"
self.assertEqual(self.run_program("udev"), [
"missing 1",
"plain 1",
f"syspath {pad} sysnum 0 devnode /dev/input/event0",
"nested 1",
f"canonical {pad}",
f"parent {parent} sysname droiddeck-input0 stable 1",
f"device properties DEVNAME=/dev/input/event0 DEVPATH={pad[4:]} ID_INPUT=1 ID_INPUT_JOYSTICK=1",
f"parent properties DEVPATH={parent[4:]} ID_INPUT=1 ID_INPUT_JOYSTICK=1",
"joystick 1 unknown 1",
f"held {pad}",
f"retained {parent}",
"reuse failures 0",
"full 256 extra 1 parent 1",
f"freed parent {parent} stable 1",
f"parent link {parent}",
"kernel link shadowed 0",
"kernel sysname shadowed 0",
f"parent sysname {parent}",
"contexts 1 1",
])
def test_no_device_call_on_a_pad_reaches_the_real_libudev(self):
self.assertEqual(self.run_program("every", args=DEVICE_FUNCTIONS), ["pad 1 real calls 0"])
def test_a_handle_keeps_its_strings_after_the_pad_goes_away(self):
self.assertEqual(self.run_program("stable", pads=self.pad_dir("stable", "event0")), [
"gone 1",
"devnode /dev/input/event0 same 1 property /dev/input/event0",
])
def test_enumerations_keep_their_scan_and_their_state(self):
parent = "/sys/devices/droiddeck0/droiddeck-input0"
pad = f"{parent}/event0"
pad1 = "/sys/devices/droiddeck1/droiddeck-input1/event1"
self.assertEqual(self.run_program("enumerate", pads=self.pad_dir("enumerate", "event0"), slots="0=/pad;1=/pad"), [
f"scan {pad} real0",
f"same scan {pad} real0",
f"by name {pad} missing 1",
"kept tail real0",
f"rescan {pad} {pad1} real0",
f"rescan by name {pad1}",
f"added {pad} {pad1} real0 added",
"failed scan 0",
f"failed {pad} {pad1}",
"synthetic parent 0",
f"parented {parent} {pad}",
"real parent 0",
"real parent list parented",
"real parent suppressed parented",
"real replaces synthetic parented",
f"synthetic replaces real {parent} {pad}",
"bad parent -1",
f"bad parent kept {parent} {pad}",
"nothing added scan -1",
])
def test_only_the_steam_client_runtime_path_gets_the_real_libudev(self):
for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/steam-probe", 1),
("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), ("steamrt/steam", 1)):
with self.subTest(path=path):
client = self.dir / "clients" / path
client.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(self.program, client)
self.assertEqual(self.run_program("probe", program=client), [f"pad {pad}"])
if __name__ == "__main__":
unittest.main()
+90
View File
@@ -0,0 +1,90 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
LAYER = ROOT / "tools/venus/layer"
DEPS = ROOT / "build/layer-deps"
HARNESS = Path(__file__).with_name("mali_compat_spirv_test.c")
def include(variable, default):
return Path(os.environ.get(variable, str(default)))
class MaliCompatSpirvTest(unittest.TestCase):
def test_the_layer_lowers_a_module_to_the_version_the_driver_knows(self):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
self.fail("A C compiler is required for the Mali compatibility layer test")
vulkan = include("MALI_COMPAT_VULKAN_INCLUDE", DEPS / "vulkan/include")
spirv = include("MALI_COMPAT_SPIRV_INCLUDE", DEPS / "spirv/include")
missing = [str(path) for path in (vulkan / "vulkan/vk_layer.h", spirv / "spirv/unified1/spirv.h")
if not path.is_file()]
if missing:
message = "Vulkan 1.4 and SPIR-V headers are required: " + ", ".join(missing)
if os.environ.get("CI"):
self.fail(message)
self.skipTest(message)
with tempfile.TemporaryDirectory(prefix="droiddeck-mali-spirv-") as tmp:
program = Path(tmp) / "mali-compat-spirv"
module = Path(tmp) / "capped.spv"
guest = Path(tmp) / "guest.spv"
extension = Path(tmp) / "extension.spv"
scalar = Path(tmp) / "scalar.spv"
debug = Path(tmp) / "debug.spv"
private_readonly = Path(tmp) / "private-readonly.spv"
parameter = Path(tmp) / "parameter.spv"
converted = Path(tmp) / "converted.spv"
built = subprocess.run(
[compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-UNDEBUG",
"-pthread", "-Dcalloc=test_calloc", "-I", str(LAYER), "-I", str(vulkan), "-I", str(spirv),
str(HARNESS), str(LAYER / "spirv.c"), str(LAYER / "pipeline.c"), "-o", str(program)],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program), str(module), str(guest), str(extension), str(scalar), str(debug),
str(private_readonly), str(converted), str(parameter)],
capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
self.assertIn("mali compat spirv ok", ran.stdout)
self.assertTrue(module.is_file())
self.assertTrue(guest.is_file())
self.assertTrue(extension.is_file())
self.assertTrue(scalar.is_file())
self.assertTrue(debug.is_file())
validator = shutil.which("spirv-val")
if not validator:
return
for original in (private_readonly, converted):
checked = subprocess.run([validator, "--target-env", "vulkan1.3", str(original)],
capture_output=True, text=True)
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
downgraded = bytearray(original.read_bytes())
downgraded[4:8] = (0x00010300).to_bytes(4, "little")
offset = 20
while True:
instruction = int.from_bytes(downgraded[offset:offset + 4], "little")
length, opcode = instruction >> 16, instruction & 0xffff
if opcode == 15:
downgraded[offset:offset + 4] = (((length - 1) << 16) | opcode).to_bytes(4, "little")
del downgraded[offset + (length - 1) * 4:offset + length * 4]
break
offset += length * 4
original.write_bytes(downgraded)
checked = subprocess.run([validator, "--target-env", "vulkan1.1", str(original)],
capture_output=True, text=True)
self.assertNotEqual(checked.returncode, 0, "the 1.3 form must be rejected")
expected = "NonWritable" if original == private_readonly else "UConvert"
self.assertIn(expected, checked.stdout + checked.stderr)
for lowered in (module, guest, extension, scalar, debug, parameter):
checked = subprocess.run([validator, "--target-env", "vulkan1.1", str(lowered)],
capture_output=True, text=True)
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
if __name__ == "__main__":
unittest.main()
+134
View File
@@ -0,0 +1,134 @@
from pathlib import Path
import sys
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import memory_guard_ab as ab
ACTIVITIES = """\
Display #2 (activities from top to bottom):
* Task{b24f3e8 #1421 type=standard A=10120:com.droiddeck.launcher.keeptop U=0 visible=true visibleRequested=true mode=fullscreen translucent=true sz=1}
* Hist #0: ActivityRecord{10082571 u0 com.droiddeck.launcher/.session.KeepTopActivity t1421}
* Task{3002b72 #6 type=home U=0 visible=true visibleRequested=true mode=fullscreen translucent=false sz=2}
* Task{b347c40 #7 type=home A=10082:com.android.launcher3 nonResizable U=0 rootTaskId=6 visible=false visibleRequested=false mode=fullscreen translucent=true sz=1}
* Task{1ea585a #1448 type=home A=10130:rip.moth.cocoonshell nonResizable U=0 rootTaskId=6 visible=true visibleRequested=true mode=fullscreen translucent=false sz=1}
Display #0 (activities from top to bottom):
* Task{972c91 #1434 type=standard A=10120:com.droiddeck.launcher U=0 visible=true visibleRequested=true mode=fullscreen translucent=false sz=2}
* Hist #1: ActivityRecord{240807202 u0 com.droiddeck.launcher/.session.KeepTopActivity t1633}
* Hist #0: ActivityRecord{126627493 u0 com.droiddeck.launcher/.SessionActivity t1434}
* Task{93ad796 #1 type=home U=0 visible=false visibleRequested=false mode=fullscreen translucent=true sz=1}
* Task{ae41383 #1408 type=home I=com.android.launcher3/.uioverrides.QuickstepLauncher U=0 rootTaskId=1 visible=true visibleRequested=true mode=fullscreen translucent=true sz=1}
"""
WINDOWS = """\
Window #19 Window{6dc6ad8 u0 NavigationBar2}:
mDisplayId=2 rootTaskId=1 mSession=Session{1 2:u0a1} mClient=android.os.BinderProxy@1
Window #20 Window{cde10e4 u0 com.droiddeck.launcher}:
mDisplayId=2 rootTaskId=1 mSession=Session{2 3:u0a120} mClient=android.os.BinderProxy@2
Window #21 Window{d8e62b4 u0 com.droiddeck.launcher/com.droiddeck.launcher.session.KeepTopActivity}:
mDisplayId=2 taskId=1425 mSession=Session{2 3:u0a120} mClient=android.os.BinderProxy@3
Window #22 Window{aeb9be7 u0 com.droiddeck.launcher}:
mDisplayId=0 rootTaskId=1 mSession=Session{2 3:u0a120} mClient=android.os.BinderProxy@4
"""
DISPLAYS = """\
Display: mDisplayId=2 (organized)
init=1280x960 320dpi mMinSizeOfResizeableTaskDp=220 cur=1280x960 app=1280x960 rng=960x960-1280x1280
Display: mDisplayId=0 (organized)
init=1080x1920 369dpi mMinSizeOfResizeableTaskDp=220 cur=1920x1080 app=1920x1080 rng=1080x1080-1920x1920
"""
EVENTS = """\
11-19 22:50:25.389 514 514 I killinfo: [28834,10129,995,50,95820,1,28492]
11-19 22:50:26.239 514 514 I killinfo: [29132,1000,102,50,84792,1,43120]
11-19 22:50:33.400 514 514 I killinfo: [25557,10120,0,0,94252,1,79084]
11-19 22:50:29.811 2034 3827 I am_proc_died: [0,31749,rip.moth.cocoonshell,102,2]
11-19 22:50:30.199 2034 3827 I am_proc_died: [0,2286,rip.moth.cocoonshell,102,2]
11-19 22:50:33.535 2034 10103 I am_proc_died: [0,25557,com.droiddeck.launcher,0,2]
11-19 22:50:34.551 2034 11587 I wm_task_to_front: [0,1408,0]
11-19 22:42:44.766 2034 2707 I wm_create_activity: [0,1239004,1628,com.droiddeck.launcher/.session.KeepTopActivity,NULL,NULL,NULL,411107328]
11-19 22:42:44.816 16856 16856 I wm_on_top_resumed_lost_called: [24689759,com.droiddeck.launcher.SessionActivity,topStateChangedWhenResumed]
11-19 22:42:44.817 16856 16856 I wm_on_top_resumed_lost_called: [24689760,com.droiddeck.launcher.MainActivity,pausing]
"""
class DumpParsingTest(unittest.TestCase):
def test_focused_display(self):
self.assertEqual(2, ab.focused_display(" FocusedDisplayId: 2\n FocusedApplications:\n"))
self.assertIsNone(ab.focused_display(""))
def test_guards_and_sessions_are_counted_on_every_display(self):
self.assertEqual(2, ab.guard_count(ACTIVITIES))
self.assertEqual(1, ab.session_count(ACTIVITIES))
def test_the_bottom_home_is_the_visible_home_on_another_display(self):
self.assertEqual((2, "rip.moth.cocoonshell"), ab.bottom_home(ACTIVITIES, 0))
def test_android_13_activity_records_are_counted(self):
self.assertEqual(1, ab.session_count(
" * Hist #1: ActivityRecord{e1ec207 u0 com.droiddeck.launcher/.SessionActivity} t14519}\n"))
def test_the_visible_app_stands_in_when_no_home_is_on_the_other_display(self):
dump = ("Display #4 (activities from top to bottom):\n"
" * Task{21f60d6 #14493 type=standard A=10113:com.discord U=0 visible=true visibleRequested=true mode=fullscreen}\n")
self.assertEqual((4, "com.discord"), ab.bottom_home(dump, 0))
def test_no_bottom_home_without_another_display(self):
self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0))
def test_panel_windows_are_the_apps_bare_windows_on_that_display(self):
self.assertEqual(1, ab.panel_windows(WINDOWS, 2))
self.assertEqual(1, ab.panel_windows(WINDOWS, 0))
self.assertEqual(0, ab.panel_windows(WINDOWS, 3))
def test_logical_size_follows_rotation(self):
self.assertEqual((1920, 1080), ab.logical_size(DISPLAYS, 0))
self.assertEqual((1280, 960), ab.logical_size(DISPLAYS, 2))
self.assertIsNone(ab.logical_size(DISPLAYS, 5))
class HogScriptTest(unittest.TestCase):
def test_both_modes_start_the_fill_counter(self):
script = ab.HOG.splitlines()
counter = next(n for n, line in enumerate(script) if line.startswith("i=0"))
self.assertLess(counter, script.index('if [ "$mode" = burst ]; then'))
self.assertLess(counter, next(n for n, line in enumerate(script) if line.startswith("while [ $i -lt 512 ]")))
def test_a_failed_write_never_reports_released(self):
script = ab.HOG.splitlines()
check = script.index('[ "$failed" = 0 ] || { echo "write failed"; cleanup; exit 1; }')
self.assertLess(check, script.index("echo released"))
self.assertIn("failed=1", ab.HOG.split("echo released")[0])
def test_a_burst_takes_the_remainder_below_one_chunk(self):
self.assertIn("rest=$((take % 256))", ab.HOG)
self.assertIn('echo "nothing to take"', ab.HOG)
class SummaryTest(unittest.TestCase):
def test_max_adj_skips_samples_after_death(self):
self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""]))
self.assertIsNone(ab.max_adj(["DEAD"]))
def test_events_summary(self):
summary = ab.summarize_events(EVENTS)
self.assertEqual(3, summary["lmkd_kills"])
self.assertEqual(1, summary["lmkd_kills_down_to_adj0"])
self.assertEqual({"com.droiddeck.launcher": 1, "rip.moth.cocoonshell": 2}, summary["processes_died"])
self.assertEqual(0, summary["droiddeck_died_at_adj"])
self.assertEqual(1, summary["session_top_lost"])
self.assertEqual(1, summary["task_to_front"])
self.assertEqual(1, summary["guard_creates"])
def test_a_quiet_log_summarizes_to_nothing(self):
summary = ab.summarize_events("")
self.assertEqual(0, summary["lmkd_kills"])
self.assertIsNone(summary["droiddeck_died_at_adj"])
self.assertEqual({}, summary["processes_died"])
if __name__ == "__main__":
unittest.main()
+316 -607
View File
@@ -2,7 +2,9 @@ from pathlib import Path
import tempfile
import unittest
from tools.tests.test_client_zram_focus import SCRIPT, function_source, run_bash
from tools.tests.test_client_zram_focus import STATE, function_source, run_bash
MB = 1024
class MemoryPressureTest(unittest.TestCase):
@@ -10,629 +12,336 @@ class MemoryPressureTest(unittest.TestCase):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.memory()
def memory(self, available=1024, swap_free=4096, total=7168, swap_total=6144, psi='0.00'):
(self.root / 'meminfo').write_text(
f'MemTotal: {total * 1024} kB\nMemAvailable: {available * 1024} kB\n'
f'SwapTotal: {swap_total * 1024} kB\nSwapFree: {swap_free * 1024} kB\n')
(self.root / 'pressure').write_text(f'some avg10={psi} avg60=0.00 avg300=0.00 total=1234\n')
def sample(self, available=3000, total=7168, stall=0, zram=(6144, 0), other=(4096, 0), stored=None, swapped_in=None):
lines = [f'MemTotal: {total * MB} kB', f'MemAvailable: {available * MB} kB',
f'SwapTotal: {(zram[0] + other[0]) * MB} kB',
f'SwapFree: {(zram[0] - zram[1] + other[0] - other[1]) * MB} kB']
swaps = ['Filename Type Size Used Priority']
if zram[0]:
swaps.append(f'/dev/block/zram0 partition {zram[0] * MB} {zram[1] * MB} 100')
if other[0]:
swaps.append(f'/data/swap/swapfile file {other[0] * MB} {other[1] * MB} 50')
text = "printf '%s\\n' " + ' '.join(f"'{line}'" for line in lines) + f" > {self.root}/meminfo\n"
text += "printf '%s\\n' " + ' '.join(f"'{line}'" for line in swaps) + f" > {self.root}/swaps\n"
text += f"echo 'some avg10=0.00 avg60=0.00 avg300=0.00 total={stall}' > {self.root}/pressure\n"
if swapped_in is None:
text += f'rm -f {self.root}/vmstat\n'
else:
text += f"printf '%s\\n' 'pgfault 9' 'pswpin {swapped_in * MB // 4}' 'pswpout 7' > {self.root}/vmstat\n"
if stored is None:
text += f'rm -f {self.root}/mm_stat\n'
else:
text += f'echo "{stored[0] << 20} {stored[1] << 20} {stored[1] << 20} 0 0 0 0 0 0" > {self.root}/mm_stat\n'
return text
def run_policy(self, body):
functions = '\n'.join(function_source(name) for name in (
'dd_memory_read', 'dd_memory_tight', 'dd_memory_critical', 'dd_client_can_pageout',
'dd_client_can_readback', 'dd_client_pressure', 'dd_client_pressure_result', 'dd_zram_has_room'))
functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo'))
functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure'))
harness = '''
set -u
_dd_pids=(123) _dd_game=1 _dd_packed=-1 _dd_pressure_at=-1 _dd_pressure_backoff=30
rss=$((384 * 1024)) client_swap=$((512 * 1024)) reclaimed=$((128 * 1024))
step() { :; }
dd_zram_usage() { _dd_rss=$rss _dd_anon=${anon:-$rss} _dd_swap=$client_swap; }
dd_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _dd_pageout_complete=${pageout_complete:-1}; }
''' + functions + '\ndd_memory_read\n' + body
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
def run_policy(self, body, *names):
functions = '\n'.join(function_source(name) for name in ('dd_memory_read', 'dd_memory_need') + names)
for name in ('meminfo', 'swaps', 'pressure/memory', 'vmstat'):
functions = functions.replace('/proc/' + name, str(self.root / name.split('/')[0]))
functions = functions.replace('/sys/block/zram0/mm_stat', str(self.root / 'mm_stat'))
functions = functions.replace('/tmp/.dd-zram', str(self.root / 'ctl'))
result = run_bash(('NOW=0\nset -u\n' + STATE + functions + '\n' + body).replace('SECONDS', 'NOW'))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
return result.stdout.splitlines()
def test_pressure_reclaims_before_the_focus_delay_and_respects_cooldown(self):
self.assertEqual(['send:1:client', 'send:1:client'], self.run_policy('''
SECONDS=0; dd_client_pressure
SECONDS=5; dd_client_pressure
SECONDS=29; dd_client_pressure
SECONDS=30; dd_client_pressure
'''))
def test_no_game_or_disabled_client_compression_does_not_reclaim(self):
self.assertEqual([], self.run_policy('''
_dd_game=0; dd_client_pressure
_dd_game=1 DD_ZRAM_CLIENT=0; dd_client_pressure
'''))
def test_high_available_memory_does_not_reclaim_even_with_stalls(self):
self.memory(available=4096, psi='12.34')
self.assertEqual([], self.run_policy('dd_client_pressure'))
def test_psi_reclaims_with_moderate_headroom(self):
self.memory(available=2048, psi='01.23')
self.assertEqual(['send:1:client'], self.run_policy('dd_client_pressure'))
def test_missing_psi_still_uses_memory_headroom(self):
(self.root / 'pressure').unlink()
self.assertEqual(['send:1:client'], self.run_policy('dd_client_pressure'))
def test_missing_meminfo_never_reclaims_or_prefetches(self):
(self.root / 'meminfo').write_text('SwapTotal: 6291456 kB\nSwapFree: 4194304 kB\n')
self.assertEqual(['no'], self.run_policy('''
dd_client_pressure
if dd_client_can_readback; then echo yes; else echo no; fi
'''))
def test_missing_available_memory_does_not_trigger_pressure(self):
p = self.root / 'meminfo'
p.write_text('\n'.join(line for line in p.read_text().splitlines() if not line.startswith('MemAvailable:')))
self.assertEqual([], self.run_policy('dd_client_pressure'))
def test_swap_reserve_includes_the_clients_resident_memory(self):
self.memory(swap_free=1536)
self.assertEqual(['no'], self.run_policy('''
dd_client_pressure
if dd_client_can_pageout; then echo yes; else echo no; fi
'''))
def test_client_swap_budget_excludes_file_backed_memory(self):
self.memory(swap_free=1536)
self.assertEqual(['send:1:client'], self.run_policy('''
rss=$((2048 * 1024)) anon=$((256 * 1024))
dd_client_pressure
'''))
def test_without_swap_automatic_pageout_is_disabled(self):
self.memory(swap_total=0, swap_free=0)
self.assertEqual([], self.run_policy('dd_client_pressure'))
def test_recent_periodic_pageout_prevents_an_immediate_pressure_repeat(self):
self.assertEqual([], self.run_policy('_dd_packed=$SECONDS; dd_client_pressure'))
def test_ineffective_reclaim_backs_off_and_success_resets_it(self):
self.assertEqual(['send:1:client', 'backoff:60', 'send:1:client', 'backoff:30'], self.run_policy('''
reclaimed=0
SECONDS=0; dd_client_pressure
echo "backoff:$_dd_pressure_backoff"
SECONDS=30; dd_client_pressure
reclaimed=$((128 * 1024))
SECONDS=60; dd_client_pressure
echo "backoff:$_dd_pressure_backoff"
'''))
def test_readback_requires_room_for_the_swapped_client_plus_headroom(self):
self.memory(available=2048)
self.assertEqual(['yes', 'no'], self.run_policy('''
if dd_client_can_readback; then echo yes; else echo no; fi
client_swap=$((1024 * 1024))
if dd_client_can_readback; then echo yes; else echo no; fi
'''))
def test_unfinished_pageout_does_not_increase_the_ineffective_reclaim_backoff(self):
self.assertEqual(['send:1:client', 'backoff:30'], self.run_policy('''
reclaimed=0 pageout_complete=0
SECONDS=0; dd_client_pressure
echo "backoff:$_dd_pressure_backoff"
'''))
def test_pageout_completion_requires_a_finished_ack_from_every_live_target(self):
proc = self.root / 'proc'
proc.mkdir()
for pid in (123, 456):
(proc / str(pid)).mkdir()
source = function_source('dd_zram_wait').replace('/proc/', str(proc) + '/')
source = source.replace('/tmp/.dd-zram.ack.', str(self.root / 'ack.'))
for pending in ('done', 'running', 'not_started'):
with self.subTest(pending=pending):
(self.root / 'ack.123').write_text('1')
if pending != 'not_started':
(self.root / 'ack.456').write_text('1' if pending == 'done' else '')
result = run_bash('nap() { SECONDS=$((SECONDS + 1)); }\n' + source +
'\nSECONDS=0; dd_zram_wait 123 456; echo "$_dd_pageout_complete"')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('1' if pending == 'done' else '0', result.stdout.strip())
def test_pressure_prevents_prefetch_even_if_the_client_would_fit(self):
self.memory(available=2048, psi='2.00')
self.assertEqual(['no'], self.run_policy('if dd_client_can_readback; then echo yes; else echo no; fi'))
class SessionPressureTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.memory()
def memory(self, available=1024, swap_free=6144, total=7168, swap_total=8192, psi='0.00'):
(self.root / 'meminfo').write_text(
f'MemTotal: {total * 1024} kB\nMemAvailable: {available * 1024} kB\n'
f'SwapTotal: {swap_total * 1024} kB\nSwapFree: {swap_free * 1024} kB\n')
(self.root / 'pressure').write_text(f'some avg10={psi} avg60=0.00 avg300=0.00 total=1234\n')
def run_policy(self, body):
functions = '\n'.join(function_source(name) for name in (
'dd_memory_read', 'dd_memory_tight', 'dd_memory_critical',
'dd_client_can_pageout', 'dd_client_pressure', 'dd_client_pressure_result',
'dd_session_pressure', 'dd_zram_has_room', 'dd_watch_nap', 'dd_zram_pick', 'dd_tier_note', 'dd_tier_readback'))
functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo'))
functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure'))
harness = '''
set -u
_dd_game=1 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_pushed=0 _dd_tier_back=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=() _dd_pids=(999)
_dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_packed=-1
rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive="999 321 654" started=100 complete=1
step() { :; }
meminfo=''' + repr(str(self.root / 'meminfo')) + '''
dd_game_focused() { [ "${focused:-1}" = 1 ]; }
dd_proc_start() { _dd_start=; case " $alive " in *" $1 "*) _dd_start=$started; return 0 ;; esac; return 1; }
nap() { echo "nap:$1"; }
dd_session_others() { _dd_session=(321 654); }
dd_zram_usage() { _dd_rss=$rss _dd_anon=${anon:-$rss} _dd_swap=$swap; }
dd_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed)); next_available=${available_after:-$(( $(awk '/^MemAvailable:/ { print $2 }' "$meminfo") / 1024 + 128 ))}; sed -i "s/^MemAvailable:.*/MemAvailable: $((next_available * 1024)) kB/" "$meminfo"; _dd_pageout_complete=$complete; }
''' + functions + '\ndd_memory_read\n' + body
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
return result.stdout.splitlines()
def test_low_headroom_compresses_the_game_session_at_most_every_30_seconds(self):
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
SECONDS=0; dd_session_pressure
SECONDS=10; dd_session_pressure
SECONDS=29; dd_session_pressure
SECONDS=30; dd_session_pressure
'''))
def test_pressure_policy_is_independent_of_ram_size(self):
for total, expected in ((11264, ['send:1:session']), (12288, ['send:1:session']), (16384, ['send:1:session'])):
with self.subTest(total=total):
self.memory(total=total)
self.assertEqual(expected, self.run_policy('dd_session_pressure'))
def test_large_device_with_real_headroom_does_not_reclaim(self):
self.memory(total=16384, available=5120, psi='12.34')
self.assertEqual([], self.run_policy('dd_session_pressure'))
def test_large_device_with_psi_and_moderate_headroom_reclaims(self):
self.memory(total=16384, available=3072, psi='1.23')
self.assertEqual(['send:1:session'], self.run_policy('dd_session_pressure'))
def test_a_fast_fall_on_a_large_device_reclaims_above_the_fixed_headroom(self):
self.memory(total=15255, available=6176)
falling = self.root / 'falling'
falling.write_text(
f'MemTotal: {15255 * 1024} kB\nMemAvailable: {5367 * 1024} kB\n'
f'SwapTotal: {8192 * 1024} kB\nSwapFree: {6144 * 1024} kB\n')
meminfo = self.root / 'meminfo'
self.assertEqual(['send:1:session'], self.run_policy(
f'cp {falling} {meminfo}\nSECONDS=5; dd_session_pressure'))
def test_a_fall_split_across_one_second_polls_still_reclaims(self):
self.memory(total=15255, available=6300)
steps = []
for second, available in ((5, 6100), (6, 6020), (7, 5940), (8, 5860), (9, 5780)):
sample = self.root / f'meminfo-{second}'
sample.write_text(
f'MemTotal: {15255 * 1024} kB\nMemAvailable: {available * 1024} kB\n'
f'SwapTotal: {8192 * 1024} kB\nSwapFree: {6144 * 1024} kB\n')
steps.append(f'cp {sample} {self.root / "meminfo"}; SECONDS={second}; dd_session_pressure')
self.assertEqual(['send:1:session'], self.run_policy('\n'.join(steps)))
def test_no_game_does_not_compress_the_session(self):
self.assertEqual([], self.run_policy('_dd_game=0; dd_session_pressure'))
def test_disabled_idle_compression_does_not_compress_the_session(self):
self.assertEqual(['send:1:client'], self.run_policy('DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure'))
def test_disabled_idle_compression_signals_only_launcher_processes(self):
sender = (function_source('dd_zram_send') + '\n' + function_source('dd_zram_finish')).replace('/tmp/.dd-zram', str(self.root / 'control'))
self.assertEqual(['kill:-URG 999 998', 'mode:1'], self.run_policy('''
_dd_pids=(999 998)
kill() { echo "kill:$*"; }
dd_zram_wait() { _dd_pageout_complete=1; }
dd_zram_scan() { :; }
''' + sender + '''
DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure
echo "mode:$(cat ''' + str(self.root / 'control') + ''')"
'''))
def test_disabled_idle_compression_reclaims_only_the_launcher_before_focus(self):
self.memory(available=1700)
self.assertEqual(['send:1:client'], self.run_policy('''
DD_ZRAM_IDLE=0 focused=0
dd_client_pressure
dd_session_pressure
'''))
def test_disabled_idle_compression_respects_launcher_setting_and_threshold(self):
self.memory(available=1700)
self.assertEqual([], self.run_policy('DD_ZRAM_IDLE=0 DD_ZRAM_CLIENT=0; dd_client_pressure; dd_session_pressure'))
self.memory(available=1900)
self.assertEqual([], self.run_policy('DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure'))
def test_game_reclaim_requires_focus(self):
self.assertEqual([], self.run_policy('focused=0; dd_session_pressure'))
def test_game_reclaim_runs_when_focus_is_unknown(self):
launch = self.root / 'launch'
(launch / 'agent').mkdir(parents=True)
body = function_source('dd_game_focused') + f'\nDD_LAUNCH_DIR={launch} _dd_apps=7\n'
self.assertEqual(['send:1:session'], self.run_policy(body + 'dd_session_pressure'))
(launch / 'agent' / 'focus.json').write_text('{"focusedApp": 9}')
self.assertEqual([], self.run_policy(body + 'dd_session_pressure'))
self.assertEqual(['unfocused'], self.run_policy(body + 'dd_game_focused || echo unfocused'))
(launch / 'agent' / 'focus.json').unlink()
self.assertEqual(['unfocused'], self.run_policy(body + 'dd_game_focused || echo unfocused'))
def test_launcher_pressure_remains_available_on_larger_devices(self):
self.memory(total=15360, available=1400)
self.assertEqual(['send:1:client'], self.run_policy('DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure'))
def test_enough_available_memory_does_not_compress_even_with_stalls(self):
self.memory(available=3072, psi='5.00')
self.assertEqual([], self.run_policy('dd_session_pressure'))
def test_stalls_with_moderate_headroom_compress_before_the_hard_limit(self):
self.memory(available=2048, psi='1.50')
self.assertEqual(['send:1:session'], self.run_policy('dd_session_pressure'))
def test_moderate_headroom_without_stalls_waits(self):
self.memory(available=2048)
self.assertEqual([], self.run_policy('dd_session_pressure'))
def test_same_second_memory_read_preserves_the_pressure_baseline(self):
self.memory(available=2048)
meminfo = self.root / 'meminfo'
self.assertEqual(['1048576:524288:2097152'], self.run_policy(f'''
SECONDS=100
_dd_sample_at=100 _dd_sample_available=2097152 _dd_growth=0 _dd_fall=524288
sed -i 's/MemAvailable: 2097152 kB/MemAvailable: 1048576 kB/' {meminfo}
dd_memory_read
echo "$_dd_available:$_dd_fall:$_dd_sample_available"
'''))
def test_game_reading_back_most_of_a_pageout_skips_and_doubles_the_wait(self):
self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session', 'backoff:60',
'send:1:session', 'backoff:30'], self.run_policy('''
pushed=$((512 * 1024))
SECONDS=0; dd_session_pressure
swap=$((swap / 4))
SECONDS=30; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
SECONDS=60; dd_session_pressure
SECONDS=90; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
SECONDS=150; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
'''))
def test_repeated_read_back_keeps_doubling_up_to_five_minutes(self):
self.assertEqual(['backoff:300'], self.run_policy('''
_dd_tier_backoff=240 _dd_tier_at=0 _dd_tier_targets=(999) _dd_tier_swaps=($((1024 * 1024))) _dd_tier_starts=(100) _dd_tier_pushed=$((1024 * 1024)) swap=0
SECONDS=240; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
'''))
def test_no_gain_pageout_doubles_the_tier_wait(self):
self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session', 'backoff:120'], self.run_policy('''
available_after=1024
SECONDS=0; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
SECONDS=30; dd_session_pressure
SECONDS=60; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
'''))
def test_meaningful_available_gain_keeps_the_tier_wait(self):
self.assertEqual(['send:1:session', 'backoff:30', 'send:1:session', 'backoff:30'], self.run_policy('''
available_after=1300
SECONDS=0; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
available_after=1600
SECONDS=30; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
'''))
def test_recovered_available_memory_resets_the_tier_wait(self):
self.assertEqual(['send:1:session', 'backoff:60', 'backoff:30', 'send:1:session'], self.run_policy('''
available_after=1024
SECONDS=0; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
available_after=2000
sed -i "s/^MemAvailable:.*/MemAvailable: 2048000 kB/" "$meminfo"
SECONDS=30; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
available_after=1024
sed -i "s/^MemAvailable:.*/MemAvailable: 1048576 kB/" "$meminfo"
SECONDS=60; dd_session_pressure
'''))
def test_critical_memory_still_compresses_after_a_no_gain_pass(self):
self.memory(available=512)
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
available_after=512
SECONDS=0; dd_session_pressure
SECONDS=30; dd_session_pressure
'''))
def test_a_no_gain_pass_still_skips_memory_the_game_read_back(self):
self.memory(available=512)
self.assertEqual(['send:1:session'], self.run_policy('''
available_after=512
SECONDS=0; dd_session_pressure
swap=0
SECONDS=30; dd_session_pressure
'''))
def test_nearly_out_of_memory_ignores_the_backoff_but_keeps_30_seconds(self):
self.memory(available=512)
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
_dd_tier_backoff=300
SECONDS=0; dd_session_pressure
SECONDS=20; dd_session_pressure
SECONDS=30; dd_session_pressure
'''))
def test_nearly_out_of_memory_still_backs_off_when_the_game_reads_its_pageout_back(self):
self.memory(available=512)
self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session'], self.run_policy('''
SECONDS=0; dd_session_pressure
swap=0
SECONDS=30; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
SECONDS=59; dd_session_pressure
SECONDS=60; dd_session_pressure
SECONDS=90; dd_session_pressure
'''))
def test_nearly_out_of_memory_retries_a_skipped_pageout_after_30_seconds(self):
self.memory(available=512)
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
SECONDS=0; dd_session_pressure
swap=0
SECONDS=30; dd_session_pressure
_dd_tier_backoff=300
saved=$rss; rss=$((128 * 1024))
SECONDS=330; dd_session_pressure
rss=$saved
SECONDS=359; dd_session_pressure
SECONDS=360; dd_session_pressure
'''))
def test_small_swap_headroom_skips_the_pageout(self):
self.memory(swap_free=1536, swap_total=2048)
self.assertEqual([], self.run_policy('dd_session_pressure'))
def test_file_backed_resident_memory_does_not_consume_the_swap_budget(self):
self.memory(swap_free=3088, swap_total=6144)
self.assertEqual(['send:1:session'], self.run_policy('''
rss=$((4096 * 1024)) anon=$((1024 * 1024))
dd_session_pressure
'''))
def test_anonymous_memory_and_pending_client_still_need_the_full_swap_reserve(self):
self.memory(swap_free=3088, swap_total=6144)
self.assertEqual([], self.run_policy('''
rss=$((4096 * 1024)) anon=$((2048 * 1024))
dd_session_pressure
'''))
self.assertEqual([], self.run_policy('''
rss=$((4096 * 1024)) anon=$((1536 * 1024)) _dd_client_reserve=$((512 * 1024))
dd_session_pressure
'''))
def test_small_session_is_left_alone(self):
self.assertEqual([], self.run_policy('rss=$((128 * 1024)); dd_session_pressure'))
def test_watch_polls_every_second_near_the_limit_and_stops_when_critical(self):
self.memory(available=2560)
self.assertEqual(['nap:1', 'nap:1', 'nap:1', 'nap:1', 'nap:1'], self.run_policy('dd_watch_nap'))
self.memory(available=1024)
self.assertEqual(['nap:1'], self.run_policy('_dd_available=$((2560 * 1024)); dd_watch_nap'))
self.memory(available=4096)
self.assertEqual(['nap:5'], self.run_policy('dd_watch_nap'))
self.assertEqual(['nap:5'], self.run_policy('_dd_game=0; dd_watch_nap'))
def test_session_push_preserves_client_timestamps(self):
self.assertEqual(['send:1:session', 'pids:321 654', 'client:-1:-1'], self.run_policy('''
SECONDS=0; dd_session_pressure
dd_zram_pick session; echo "pids:${_pids[*]}"
echo "client:$_dd_pressure_at:$_dd_packed"
'''))
def test_launcher_compression_turned_off_keeps_the_launcher_out(self):
self.assertEqual(['pids:321 654', 'client:-1:-1'], self.run_policy('''
DD_ZRAM_CLIENT=0
SECONDS=0; dd_session_pressure
dd_zram_pick session; echo "pids:${_pids[*]}"
echo "client:$_dd_pressure_at:$_dd_packed"
''')[1:])
def test_low_ram_devices_compress_with_a_quarter_of_memory_left(self):
self.memory(available=1700)
self.assertEqual(['send:1:session'], self.run_policy('dd_session_pressure'))
self.memory(available=1900)
self.assertEqual([], self.run_policy('dd_session_pressure'))
def test_a_compressed_process_that_exits_is_not_counted_as_read_back(self):
self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy('''
SECONDS=0; dd_session_pressure
alive=""; swap=0
SECONDS=30; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
'''))
def test_a_process_that_starts_after_a_pageout_is_not_in_its_read_back(self):
self.assertEqual(['send:1:session', 'targets:321 654', 'send:1:session', 'backoff:30'], self.run_policy('''
SECONDS=0; dd_session_pressure
echo "targets:${_dd_tier_targets[*]}"
alive="999 1234"
SECONDS=30; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
'''))
def test_read_back_wait_holds_above_the_critical_level(self):
self.assertEqual(['send:1:session', 't:60', 'send:1:session'], self.run_policy('''
SECONDS=0; dd_session_pressure
swap=0
SECONDS=30; dd_session_pressure
SECONDS=60; dd_session_pressure; echo t:60
SECONDS=90; dd_session_pressure
'''))
def test_a_no_gain_pageout_preserves_client_timestamps(self):
self.assertEqual(['send:1:session', 'backoff:60', 'client:-1:-1'], self.run_policy('''
available_after=1024
SECONDS=0; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
echo "client:$_dd_pressure_at:$_dd_packed"
'''))
def test_an_incomplete_pageout_does_not_restart_the_launcher_wait(self):
self.assertEqual(['send:1:session', 'client:-1:-1'], self.run_policy('''
complete=0
SECONDS=0; dd_session_pressure
echo "client:$_dd_pressure_at:$_dd_packed"
'''))
def test_a_reused_process_id_is_not_counted_as_read_back(self):
self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy('''
SECONDS=0; dd_session_pressure
started=200; swap=0
SECONDS=30; dd_session_pressure
echo "backoff:$_dd_tier_backoff"
'''))
def test_process_start_comes_from_stat_and_zombies_have_none(self):
stat = self.root / 'stat'
source = function_source('dd_proc_start').replace('/proc/$1/stat', str(stat))
fields = ' '.join(['0'] * 17)
for state, expected in (('S', ['ok:4242']), ('Z', ['gone:'])):
with self.subTest(state=state):
stat.write_text(f'77 (Wow (arm64).exe) {state} 1 {fields} 4242 99 0\n')
result = run_bash(source + '\nif dd_proc_start 77; then echo "ok:$_dd_start"; else echo "gone:$_dd_start"; fi')
self.assertEqual(expected, result.stdout.split())
stat.unlink()
result = run_bash(source + '\ndd_proc_start 77 || echo gone')
self.assertEqual(['gone'], result.stdout.split())
class ReclaimDispatchTest(unittest.TestCase):
def run_cycle(self, client=1, game=1, anonymous=384, complete=1, reclaimed=128, body=None, available=1024, fall=0, tick=0):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'meminfo').write_text(
f'MemTotal: 7340032 kB\nMemAvailable: {available * 1024} kB\n'
'SwapTotal: 6291456 kB\nSwapFree: 4194304 kB\n')
(root / 'pressure').write_text('some avg10=0.00 avg60=0.00 avg300=0.00 total=0\n')
names = ('dd_memory_read', 'dd_memory_tight', 'dd_memory_critical',
'dd_zram_has_room', 'dd_client_can_pageout', 'dd_client_pressure',
'dd_client_pressure_result', 'dd_client_pressure_finish',
'dd_session_pressure', 'dd_zram_send', 'dd_zram_finish', 'dd_zram_pick')
source = '\n'.join(function_source(name) for name in names)
source = source.replace('/proc/meminfo', str(root / 'meminfo'))
source = source.replace('/proc/pressure/memory', str(root / 'pressure'))
source = source.replace('/tmp/.dd-zram', str(root / 'ctl'))
monitor = SCRIPT.read_text()
start = monitor.index(' _dd_preserved_growth=$_dd_growth', monitor.index('while kill -0 $$'))
stop = monitor.index(' _dd_focus=1\n', start)
cycle = monitor[start:stop] if body is None else body
script = f'''
set -u
DD_ZRAM_CLIENT={client} _dd_game={game} _dd_pids=(123) _dd_others=(321)
_dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_packed=-1
_dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_pushed=0
_dd_client_reserve=0 client_rss=393216 client_anon={anonymous * 1024}
step() {{ :; }}
dd_session_others() {{ _dd_session=(321); }}
dd_zram_scan() {{ _dd_pids=(456); }}
nap() {{ echo "nap:$*:at:$NOW"; }}
dd_zram_usage() {{
if [ "$1" = 123 ]; then
_dd_rss=$client_rss _dd_anon=$client_anon _dd_swap=0
else
_dd_rss=3145728 _dd_anon=1572864 _dd_swap=0
fi
}}
kill() {{ echo "signal:$*:at:$NOW"; NOW=$((NOW + {tick})); }}
dd_zram_wait() {{
echo "wait:$*:at:$NOW"
NOW=$((NOW + 12))
_dd_pageout_complete={complete}
[ "$1" != 123 ] || client_rss=$((client_rss - {reclaimed * 1024}))
}}
dd_tier_note() {{ :; }}
dd_game_focused() {{ :; }}
''' + source + f'''
dd_memory_read
_dd_fall={fall * 1024}
''' + cycle + '''
echo "client:$_dd_pressure_backoff:${_dd_client_reserve:-0}:${_dd_client_pending:-0}"
def test_the_floor_follows_device_memory_within_limits(self):
body = ''.join(self.sample(total=total) + 'dd_memory_read; echo $((_dd_floor / 1024))\n'
for total in (3584, 7168, 15360))
self.assertEqual(['640', '896', '1280'], self.run_policy(body))
def test_the_target_grows_with_how_fast_memory_is_falling(self):
body = (self.sample(available=3000) + 'dd_memory_read; echo $_dd_rate $((_dd_target / 1024))\n' +
self.sample(available=2800) + 'NOW=1; dd_memory_read; echo $((_dd_rate / 1024)) $((_dd_target / 1024))\n' +
'NOW=2; dd_memory_read; echo $((_dd_rate / 1024)) $((_dd_target / 1024))\n' +
self.sample(available=3400) + 'NOW=3; dd_memory_read; echo $((_dd_rate / 1024))\n')
self.assertEqual(['0 896', '200 2896', '150 2396', '112'], self.run_policy(body))
def test_memory_the_monitor_freed_itself_does_not_hide_a_fall(self):
body = (self.sample(available=2000) + 'dd_memory_read\n_dd_freed=$((300 * 1024))\n' +
'NOW=2; dd_memory_read; echo $((_dd_rate / 1024)) $_dd_freed\n')
self.assertEqual(['150 0'], self.run_policy(body))
def test_two_reads_in_the_same_second_keep_the_sample(self):
body = (self.sample(available=2000) + 'dd_memory_read\n_dd_freed=4096\n' +
self.sample(available=1000) + 'dd_memory_read; echo $_dd_rate $_dd_freed $_dd_sample_available\n')
self.assertEqual([f'0 4096 {2000 * MB}'], self.run_policy(body))
def test_stall_time_becomes_a_share_of_the_interval(self):
body = (self.sample(stall=1000) + 'dd_memory_read; echo $_dd_psi\n' +
self.sample(stall=41000) + 'NOW=2; dd_memory_read; echo $_dd_psi\n' +
'NOW=3; dd_memory_read; echo $_dd_psi\n')
self.assertEqual(['0', '200', '0'], self.run_policy(body))
def test_room_counts_zram_only_and_keeps_a_reserve(self):
body = (self.sample(zram=(6144, 1024)) + 'dd_memory_read; echo $((_dd_swap_room / 1024))\n' +
self.sample(zram=(6144, 5632)) + 'dd_memory_read; echo $((_dd_swap_room / 1024))\n' +
self.sample(zram=(0, 0), other=(4096, 1024)) + 'dd_memory_read; echo $((_dd_swap_room / 1024))\n' +
self.sample(zram=(512, 0), other=(0, 0)) + 'dd_memory_read; echo $((_dd_swap_room / 1024))\n' +
self.sample(zram=(0, 0), other=(4096, 1024)) + f'rm {self.root}/swaps\n' +
'dd_memory_read; echo $((_dd_swap_room / 1024))\n')
self.assertEqual(['4352', '-256', '-128', '384', '2560'], self.run_policy(body))
def test_memory_read_back_from_swap_is_remembered_for_half_a_minute(self):
body = '_dd_page_kb=4\n' + ''.join(
f'NOW={now}\n' + self.sample(swapped_in=total) + 'dd_memory_read; echo $((_dd_returned / 1024))\n'
for now, total in ((0, 500), (1, 800), (2, 800), (16, 800), (17, None), (18, 900), (19, 1000), (60, 1000)))
self.assertEqual(['0', '300', '290', '154', '149', '144', '239', '0'], self.run_policy(body))
def test_saving_comes_from_what_zram_really_stores(self):
body = ''.join(self.sample(stored=stored) + 'dd_memory_read; echo $_dd_saving\n'
for stored in (None, (32, 30), (1000, 250), (1000, 950), (1000, 20)))
self.assertEqual(['600', '600', '750', '167', '833'], self.run_policy(body))
def need(self, available, rate=0, psi=0):
return (self.sample(available=available) +
f'dd_memory_read; _dd_rate=$(({rate} * 1024)) _dd_psi={psi}\n'
'_dd_target=$((_dd_floor + _dd_rate * 10))\n'
'dd_memory_need; echo $((_dd_need / 1024)) $((_dd_hard / 1024)) $_dd_force\n')
def test_steady_memory_above_the_floor_needs_nothing(self):
self.assertEqual(['0 0 0'], self.run_policy(self.need(2000)))
def test_memory_under_the_floor_must_be_freed(self):
self.assertEqual(['96 96 0'], self.run_policy(self.need(800)))
def test_a_slow_fall_is_met_ten_seconds_ahead(self):
self.assertEqual(['196 0 0'], self.run_policy(self.need(1000, rate=30)))
def test_a_fast_fall_is_matched_once_memory_is_under_two_fifths(self):
self.assertEqual(['0 0 0', '200 0 0', '0 0 0'],
self.run_policy(self.need(2500, rate=20) + self.need(2500, rate=100) + self.need(4000, rate=100)))
def test_stalls_make_a_fall_urgent(self):
self.assertEqual(['200 0 0', '200 200 0', '0 0 0'],
self.run_policy(self.need(2500, rate=100) + self.need(2500, rate=100, psi=100) +
self.need(2000, psi=900)))
def test_half_the_floor_forces(self):
self.assertEqual(['446 446 0', '456 456 1'], self.run_policy(self.need(450) + self.need(440)))
RELIEVE = '''
step() { echo "step:$*"; }
dd_session_others() { echo others; _dd_session=(70 80); }
dd_zram_trim() { echo "trim:$1:$(($2 / 1024)):${*:3}"; _dd_trimmed=${paged:-$2}; }
relieve() { dd_memory_read; _dd_returned=${returned:-0}; _dd_rate=$((${2:-0} * 1024)) _dd_target=$((_dd_floor + ${2:-0} * 10240)); dd_memory_relieve; }
_dd_pids=(10 20) _dd_game=1 _dd_focus=0 _dd_saving=500
'''
result = run_bash('NOW=0\n' + script.replace('SECONDS', 'NOW'))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
return result.stdout.splitlines()
def test_both_requests_are_sent_before_either_wait(self):
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0',
'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'], self.run_cycle())
def relieve(self, body):
return self.run_policy(self.RELIEVE + body, 'dd_memory_relieve', 'dd_memory_note')
def test_disabled_client_is_never_signalled_or_waited_for(self):
self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'],
self.run_cycle(client=0))
def test_a_fall_trims_the_client_behind_a_game_by_what_zram_gives_back(self):
self.assertEqual(['trim:2:326:10 20', f'{196 * MB} {334506 * 600 // 1000} 334506'], self.relieve(
self.sample(available=1000) + 'relieve 1000 30; echo $_dd_need $_dd_freed $_dd_client_out\n'))
def test_no_game_requests_nothing(self):
self.assertEqual(['client:30:0:0'], self.run_cycle(game=0))
def test_the_client_in_front_is_left_alone_until_memory_is_under_the_floor(self):
self.assertEqual(['trim:2:160:10 20'], self.relieve(
self.sample(available=1000) + '_dd_focus=1; relieve 1000 30\n' +
self.sample(available=800) + 'relieve 800\n'))
def test_a_client_with_no_anonymous_pages_still_finishes_its_request(self):
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0',
'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'],
self.run_cycle(anonymous=0))
def test_unknown_focus_still_trims_the_client(self):
self.assertEqual(['trim:2:326:10 20'], self.relieve(self.sample(available=1000) + '_dd_focus=2; relieve 1000 30\n'))
def test_falling_headroom_survives_a_tick_between_requests(self):
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:1',
'wait:321:at:2', 'wait:123:at:14', 'client:30:0:0'],
self.run_cycle(available=2304, fall=512, tick=1))
def test_the_client_is_not_trimmed_right_after_it_was_read_back(self):
self.assertEqual(['trim:2:326:10 20'], self.relieve(
self.sample(available=1000) + 'NOW=100 _dd_back_at=80; relieve 1000 30\nNOW=110; relieve 1000 30\n'))
def test_deferred_ineffective_reclaim_still_doubles_the_backoff(self):
self.assertEqual('client:60:0:0', self.run_cycle(reclaimed=0)[-1])
def test_without_a_game_only_the_floor_trims(self):
self.assertEqual(['trim:2:160:10 20'], self.relieve(
self.sample(available=1000) + '_dd_game=0 _dd_focus=1; relieve 1000 30\n' +
self.sample(available=800) + 'relieve 800\n'))
def test_deferred_incomplete_reclaim_does_not_double_the_backoff(self):
self.assertEqual('client:30:0:0', self.run_cycle(reclaimed=0, complete=0)[-1])
def test_the_session_gives_what_the_client_could_not(self):
self.assertEqual(['trim:2:660:10 20', 'others', 'trim:2:256:70 80', 'trim:2:660:10 20', 'trim:2:256:70 80'],
self.relieve(self.sample(available=500) + f'paged={128 * MB}; relieve 500\nNOW=1; relieve 500\n'))
def test_explicit_combined_send_keeps_its_synchronous_wait(self):
self.assertEqual(['signal:-URG 321 123:at:0', 'wait:321 123:at:0', 'client:30:0:0'],
self.run_cycle(body='dd_zram_send 1 cap game\n'))
self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'],
self.run_cycle(client=0, body='dd_zram_send 1 cap game\n'))
def test_the_session_gets_what_the_client_left_of_the_pass(self):
self.assertEqual(['trim:3:1024:10 20', 'others', 'trim:3:24:70 80'], self.relieve(
self.sample(available=100) + f'paged={1000 * MB}; relieve 100\n'))
def test_readback_keeps_its_synchronous_delay(self):
self.assertEqual(['signal:-URG 123:at:0', 'nap:5:at:0', 'client:30:0:0'],
self.run_cycle(body='dd_zram_send 0 readback client\n'))
def test_memory_that_keeps_coming_back_is_taken_off_what_a_pass_may_move(self):
self.assertEqual(['trim:2:660:10 20', 'others', 'trim:2:156:70 80', 'trim:2:660:10 20', 'trim:2:24:10 20'], self.relieve(
self.sample(available=500) + f'paged={256 * MB}\nreturned={100 * MB}; relieve 500\n' +
f'NOW=1 returned={300 * MB}; relieve 500\nNOW=2 returned={1000 * MB}; relieve 500\n'))
def test_usage_sums_anonymous_rss_and_falls_back_per_process(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for pid, contents in ((123, 'VmRSS: 2000 kB\nRssAnon: 300 kB\nVmSwap: 100 kB\n'),
(321, 'VmRSS: 4000 kB\nVmSwap: 200 kB\n'),
(654, 'VmRSS: 1000 kB\nRssAnon: 0 kB\n')):
(root / str(pid)).mkdir()
(root / str(pid) / 'status').write_text(contents)
source = function_source('dd_zram_usage').replace('/proc/', str(root) + '/')
result = run_bash(source + '\ndd_zram_usage 123 321 654 > /dev/null; echo "$_dd_rss:$_dd_anon:$_dd_swap"')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('7000:4300:300', result.stdout.strip())
def test_forcing_moves_memory_whatever_came_back(self):
self.assertEqual(['trim:3:993:10 20', 'others', 'trim:3:993:70 80'], self.relieve(
self.sample(available=300) + f'paged=0 returned={2048 * MB}; relieve 300\n'))
def test_the_session_is_scanned_again_after_a_new_process_scan(self):
self.assertEqual(['others', 'others'], [line for line in self.relieve(
self.sample(available=500) + f'paged={256 * MB}; relieve 500\n_dd_scan_at=5; relieve 500\n') if line == 'others'])
def test_forcing_ignores_heat_once_in_ten_seconds(self):
lines = self.relieve(self.sample(available=300) + 'paged=0\nrelieve 300\nNOW=5; relieve 300\nNOW=10; relieve 300\n')
self.assertEqual(['3', '3', '2', '2', '3', '3'], [line.split(':')[1] for line in lines if line.startswith('trim')])
self.assertIn('trim:3:993:70 80', lines)
def trims(self, body):
return [line.split(':')[2] for line in self.relieve(body) if line.startswith('trim') and line.endswith('10 20')]
def test_passes_that_free_little_come_further_and_further_apart(self):
passes = ''.join(f'NOW={now}; relieve 500; echo at:{now}\n' for now in (0, 4, 5, 14, 15, 34, 35))
lines = self.relieve(self.sample(available=500) + f'paged={8 * MB}\n' + passes)
self.assertEqual(['0', '5', '15', '35'],
[after.split(':')[1] for line, after in zip(lines, lines[1:] + ['']) if line == 'trim:2:256:70 80'])
def test_the_wait_between_passes_stops_at_a_minute(self):
self.assertEqual(['60 195'], self.relieve(
self.sample(available=500) + f'paged={8 * MB}\nfor NOW in 0 5 15 35 75 135; do relieve 500; done > /dev/null\n'
'echo $_dd_rest $_dd_rest_until\n'))
def test_a_pass_that_frees_enough_is_followed_at_once(self):
self.assertEqual(['660', '660'], self.trims(
self.sample(available=500) + f'paged={128 * MB}; relieve 500\nNOW=1; relieve 500\n'))
def test_memory_that_keeps_falling_ends_the_wait(self):
self.assertEqual(['326', '526'], self.trims(
self.sample(available=700) + f'paged={8 * MB}; relieve 700\nNOW=1; relieve 700\n' +
self.sample(available=600) + 'NOW=2; relieve 600\n' + self.sample(available=580) + 'NOW=3; relieve 580\n'))
def test_forcing_does_not_wait(self):
self.assertEqual(['993', '993'], self.trims(
self.sample(available=300) + 'paged=0\nrelieve 300\nNOW=1; relieve 300\n'))
def test_the_wait_is_forgotten_once_memory_is_back(self):
self.assertEqual(['660', '660'], self.trims(
self.sample(available=500) + f'paged={8 * MB}; relieve 500\n' +
self.sample(available=3000) + 'NOW=1; relieve 3000\n' + self.sample(available=500) + 'NOW=2; relieve 500\n'))
def test_trims_stop_at_the_room_zram_has(self):
self.assertEqual(['trim:2:100:10 20', 'step:memory: available 800 MB and zRAM has no room left'], self.relieve(
self.sample(available=800, zram=(6144, 5276)) + 'relieve 800\n' +
self.sample(available=800, zram=(6144, 5400)) + 'relieve 800\nNOW=30; relieve 800\n'))
def test_small_trims_are_not_logged(self):
self.assertEqual(['step:memory: available 1000 MB, falling 30 MB/s, compressed 20 MB of the client and 0 MB of the session'],
[line for line in self.relieve(
self.sample(available=1000) + f'paged={10 * MB}\nrelieve 1000 30; dd_memory_note\n'
'NOW=1; relieve 1000 30; dd_memory_note\nNOW=2; dd_memory_note\n')
if line.startswith('step')])
TRIM = '''
declare -A anon=() reply=() born=()
nap() { :; }
dd_pid_key() { _dd_key=$1.${born[$1]:-0}; }
dd_zram_usage() { _dd_anon=${anon[$1]}; }
kill() {
echo "signal:$2:$(< "$ROOT/ctl")"
case ${reply[$2]} in
deaf) ;;
gone) return 1 ;;
*) printf %s "${reply[$2]}" > "$ROOT/ctl.trim.$2" ;;
esac
}
'''
def trim(self, body):
return self.run_policy(f'ROOT={self.root}\n' + self.TRIM + body + '\nls "$ROOT"; cat "$ROOT/ctl"', 'dd_memory_relieved', 'dd_zram_trim')
def test_a_trim_spends_its_budget_across_processes_in_order(self):
self.assertEqual(['signal:10:2 100000', 'signal:20:2 60000', '100000', 'ctl', '2 0'], self.trim('''
anon=([10]=500000 [20]=500000 [30]=500000) reply=([10]=40000 [20]=60000 [30]=1)
dd_zram_trim 2 100000 10 20 30
echo $_dd_trimmed'''))
def test_a_trim_skips_small_and_gone_processes_and_stops_when_little_is_left(self):
self.assertEqual(['signal:20:3 50000', 'signal:30:3 50000', 'signal:40:3 50000', '47000', 'ctl', '2 0'], self.trim('''
anon=([10]=4096 [20]=500000 [30]=500000 [40]=500000 [50]=500000) reply=([20]=gone [30]=0 [40]=47000 [50]=1)
dd_zram_trim 3 50000 10 20 30 40 50
echo $_dd_trimmed'''))
def test_a_process_that_never_answers_is_left_alone_for_a_minute(self):
self.assertEqual(['signal:10:2 9000', 'signal:20:2 9000', '500', 'signal:20:2 9000', 'signal:10:2 9000',
'signal:20:2 9000', 'ctl', '2 0'], self.trim('''
anon=([10]=500000 [20]=500000) reply=([10]=deaf [20]=500)
dd_zram_trim 2 9000 10 20
echo $_dd_trimmed
NOW=59 _dd_pass_at=59; dd_zram_trim 2 9000 10 20
NOW=60 _dd_pass_at=60; dd_zram_trim 2 9000 10 20'''))
def test_a_new_process_with_a_silent_ones_number_is_asked(self):
self.assertEqual(['signal:10:2 9000', 'signal:10:2 9000', '1', 'ctl', '2 0'], self.trim('''
anon=([10]=500000) reply=([10]=deaf)
dd_zram_trim 2 9000 10
NOW=5 _dd_pass_at=5; dd_zram_trim 2 9000 10
born[10]=7
dd_zram_trim 2 9000 10
NOW=62 _dd_pass_at=62 anon=(); dd_zram_trim 2 9000
echo ${#_dd_deaf[@]}'''))
def test_one_pass_waits_five_seconds_in_all(self):
self.assertEqual(['signal:10:2 9000', 'signal:20:2 9000', 'ctl', '2 0'], self.trim('''
anon=([10]=500000 [20]=500000 [30]=500000) reply=([10]=- [20]=deaf [30]=deaf)
_dd_polls=215
dd_zram_trim 2 9000 10
dd_zram_trim 2 9000 20 30'''))
def test_one_pass_ends_six_seconds_after_it_began_however_slow_the_polls(self):
self.assertEqual(['signal:10:2 9000', '6', 'ctl', '2 0'], self.trim('''
anon=([10]=500000 [20]=500000) reply=([10]=deaf [20]=500)
nap() { NOW=$((NOW + 1)); }
dd_zram_trim 2 9000 10 20
echo $_dd_polls'''))
def test_a_trim_stops_once_memory_is_back_where_it_should_be(self):
self.assertEqual(['signal:10:2 9000', '500', 'signal:10:2 9000', 'signal:20:2 8500', '1000', 'ctl', 'meminfo', '2 0'],
self.trim('''
anon=([10]=500000 [20]=500000) reply=([10]=500 [20]=500)
available() { echo "MemAvailable: $1 kB" > "$ROOT/meminfo"; }
signal=$(declare -f kill)
eval "raw_${signal}"
kill() { raw_kill "$@"; available $((after)); }
available 800000
_dd_goal=900000 after=900000
dd_zram_trim 2 9000 10 20
echo $_dd_trimmed
available 800000
after=899999
dd_zram_trim 2 9000 10 20
echo $_dd_trimmed'''))
def test_a_held_control_file_keeps_its_acknowledgements(self):
self.assertEqual(['signal:10:2 9000', 'ctl', 'ctl.hold', 'ctl.trim.10', '2 9000'], self.trim('''
anon=([10]=500000)
kill() { echo "signal:$2:$(< "$ROOT/ctl")"; : > "$ROOT/ctl.hold"; printf 1 > "$ROOT/ctl.trim.$2"; }
dd_zram_trim 2 9000 10'''))
def test_a_trim_leaves_the_acknowledgement_of_a_suspend_page_out_alone(self):
self.assertEqual(['signal:10:2 9000', 'ctl', 'ctl.ack.10', '2 0'], self.trim('''
anon=([10]=500000) reply=([10]=9000)
: > "$ROOT/ctl.ack.10"
dd_zram_trim 2 9000 10'''))
READBACK = '''
step() { echo "step:$*"; }
kill() { echo "signal:$*:$(< "$ROOT/ctl")"; }
dd_zram_usage() { _dd_swap=$((swap * 1024)); }
back() { dd_memory_read; _dd_rate=0 _dd_target=$_dd_floor; dd_client_readback; }
_dd_pids=(10 20) _dd_game=0 _dd_client_out=4096 _dd_trim_at=0 swap=400 NOW=30
'''
def readback(self, body):
return self.run_policy(f'ROOT={self.root}\n' + self.READBACK + body, 'dd_client_readback')
def test_the_client_is_read_back_once_memory_can_hold_it_with_a_floor_to_spare(self):
self.assertEqual(['step:memory: available 2192 MB, reading 400 MB of the client back', 'signal:-URG 10 20:0',
f'0 {-400 * MB * 600 // 1000} 30'], self.readback(
self.sample(available=2191) + 'back\n' + self.sample(available=2192) + 'back\n' +
'echo $_dd_client_out $_dd_freed $_dd_back_at\nback\n'))
def test_nothing_is_read_back_right_after_a_trim(self):
self.assertEqual([], self.readback(self.sample(available=4000) + 'NOW=29; back\n'))
def test_a_running_game_keeps_the_client_compressed_until_the_client_is_in_front(self):
self.assertEqual(['signal:-URG 10 20:0'], [line for line in self.readback(
self.sample(available=4000) + '_dd_game=1\nback\n_dd_away=27; back\n_dd_away=25; back\n')
if line.startswith('signal')])
def test_a_client_the_kernel_already_brought_back_needs_no_request(self):
self.assertEqual(['0'], self.readback(self.sample(available=4000) + 'swap=8; back; echo $_dd_client_out\n'))
if __name__ == '__main__':
+202
View File
@@ -0,0 +1,202 @@
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);
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):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
if binds:
hook_env["DDNATV_BINDS"] = binds
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.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_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_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()
+94 -3
View File
@@ -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()
+144
View File
@@ -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()
+146 -4
View File
@@ -12,7 +12,10 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
SHIM = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -92,6 +95,46 @@ FILE *fopen(const char *path, const char *mode) {
return real(path, mode);
}
static int denied(const char *path) {
const char *prefixes = getenv("NETLINK_TEST_DENIED");
if (!prefixes || !path) return 0;
for (const char *prefix = prefixes; *prefix;) {
size_t length = strcspn(prefix, ":");
if (length && !strncmp(path, prefix, length)) {
errno = EACCES;
return 1;
}
prefix += length + (prefix[length] == ':');
}
return 0;
}
int open(const char *path, int flags, ...) {
static int (*real)(const char *, int, ...);
if (!real) real = dlsym(RTLD_NEXT, "open");
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(path, flags, mode);
}
int __open_2(const char *path, int flags) {
static int (*real)(const char *, int);
if (!real) real = dlsym(RTLD_NEXT, "__open_2");
return denied(path) ? -1 : real(path, flags);
}
int openat(int dirfd, const char *path, int flags, ...) {
static int (*real)(int, const char *, int, ...);
if (!real) real = dlsym(RTLD_NEXT, "openat");
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, mode_t);
va_end(ap);
return denied(path) ? -1 : real(dirfd, path, flags, mode);
}
int close_range(unsigned int first, unsigned int last, int flags) {
return syscall(SYS_close_range, (long)first, (long)last, (long)flags, 0L, 0L, 0L);
}
@@ -137,6 +180,40 @@ static int route_socket(void) {
return descriptor;
}
static void proc_net_test(int denied, int sealed) {
static const char *const tables[] = {"/proc/net/tcp", "/proc/net/tcp6", "/proc/net/udp", "/proc/net/udp6"};
char text[512], target[128], link[64];
for (unsigned i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) {
int descriptor = i % 2 ? openat(AT_FDCWD, tables[i], O_RDONLY | O_CLOEXEC) : open(tables[i], O_RDONLY | O_CLOEXEC);
require(descriptor >= 0, "socket table opens");
require(fcntl(descriptor, F_GETFD) & FD_CLOEXEC, "socket table keeps close-on-exec");
snprintf(link, sizeof(link), "/proc/self/fd/%d", descriptor);
ssize_t length = readlink(link, target, sizeof(target) - 1);
require(length > 0, "socket table target");
target[length] = 0;
require((strncmp(target, "/memfd:droiddeck-net", 20) == 0) == denied, "synthesized only when denied");
if (denied) {
if (sealed) {
require(fcntl(descriptor, F_GET_SEALS) & F_SEAL_WRITE, "socket table is sealed");
require(write(descriptor, "x", 1) < 0 && errno == EPERM, "sealed socket table rejects writes");
} else {
require((fcntl(descriptor, F_GETFL) & O_ACCMODE) == O_RDONLY, "socket table is read-only");
require(write(descriptor, "x", 1) < 0 && errno == EBADF, "socket table rejects writes");
}
ssize_t total = read(descriptor, text, sizeof(text) - 1);
require(total > 0, "socket table read");
text[total] = 0;
require(strstr(text, "local_address") && strchr(text, '\n') == text + total - 1, "header without sockets");
}
close(descriptor);
}
if (denied) {
require(open("/proc/net/tcp", O_WRONLY) < 0 && errno == EACCES, "socket table writes stay denied");
require(open("/proc/net/netstat", O_RDONLY) < 0 && errno == EACCES, "other tables stay denied");
require(open("/proc/net/tcp", O_RDONLY | O_DIRECTORY) < 0 && errno == EACCES, "directory opens stay denied");
}
}
static unsigned port_of(int descriptor) {
struct sockaddr_nl address;
socklen_t length = sizeof(address);
@@ -609,6 +686,13 @@ static void batch_test(int oversized) {
close(descriptor);
}
static unsigned groups_of(int descriptor) {
struct sockaddr_nl address;
socklen_t length = sizeof(address);
require(getsockname(descriptor, (struct sockaddr *)&address, &length) == 0, "getsockname");
return address.nl_groups;
}
static void inherited_test(int argc, char **argv) {
require(argc == 6, "inherited arguments");
int descriptor = atoi(argv[2]), closed = atoi(argv[4]), datagram = atoi(argv[5]);
@@ -616,6 +700,7 @@ static void inherited_test(int argc, char **argv) {
require(fcntl(closed, F_GETFD) == -1 && errno == EBADF, "cloexec descriptor closed");
require(port_of(descriptor) == port && !(fcntl(descriptor, F_GETFD) & FD_CLOEXEC),
"inherited bound port");
require(groups_of(descriptor) == RTMGRP_LINK, "membership survives exec");
socket_info(descriptor, SOCK_RAW);
socket_info(datagram, SOCK_DGRAM);
require(fcntl(datagram, F_GETFL) & O_NONBLOCK, "inherited nonblocking flag");
@@ -640,6 +725,9 @@ static void exec_test(const char *program, int forked) {
int enabled = 1;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_CAP_ACK, &enabled, sizeof(enabled)) == 0,
"inherited cap ack");
int group = RTNLGRP_LINK;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0,
"inherited membership");
unsigned port = port_of(descriptor);
int alias = fcntl(descriptor, F_DUPFD, 100);
int closed = fcntl(descriptor, F_DUPFD_CLOEXEC, 200);
@@ -718,8 +806,8 @@ static void ack_test(const char *mode) {
static void options_test(void) {
int descriptor = route_socket();
int group = RTNLGRP_LINK;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1
&& errno == EACCES, "membership denied");
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0,
"membership accepted");
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_PKTINFO, &group, sizeof(group)) == -1
&& errno == ENOPROTOOPT, "unsupported option");
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_EXT_ACK, &group, sizeof(group)) == 0, "ext ack");
@@ -735,6 +823,44 @@ static void options_test(void) {
close(descriptor);
}
static void subscribe_test(void) {
unsigned wanted = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
int descriptor = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = wanted};
require(descriptor >= 0, "socket");
require(bind(descriptor, (struct sockaddr *)&address, sizeof(address)) == 0, "bind with groups");
require(groups_of(descriptor) == wanted, "bound groups");
int group = RTNLGRP_IPV4_ROUTE;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0,
"add membership");
require(groups_of(descriptor) == (wanted | RTMGRP_IPV4_ROUTE), "added group");
group = RTNLGRP_LINK;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0,
"drop membership");
require(groups_of(descriptor) == ((wanted & ~RTMGRP_LINK) | RTMGRP_IPV4_ROUTE), "dropped group");
pid_t child = fork();
require(child >= 0, "membership fork");
if (child == 0) {
group = RTNLGRP_IPV4_ROUTE;
_exit(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0
&& groups_of(descriptor) == (wanted & ~RTMGRP_LINK) ? 0 : 1);
}
int status;
require(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0,
"membership child");
require(groups_of(descriptor) == (wanted & ~RTMGRP_LINK), "membership shared after fork");
group = 0;
require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1
&& errno == EINVAL, "group zero refused");
struct timeval timeout = {.tv_usec = 30000};
require(setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0, "receive timeout");
unsigned char buffer[4096];
require(recv(descriptor, buffer, sizeof(buffer), 0) == -1
&& (errno == EAGAIN || errno == EWOULDBLOCK), "no unsolicited events");
usable(descriptor);
close(descriptor);
}
static void dump_test(void) {
int descriptor = route_socket();
send_link(descriptor, 0, NLM_F_DUMP | NLM_F_ACK);
@@ -1040,6 +1166,7 @@ int main(int argc, char **argv) {
if (!strcmp(argv[1], "ack") || !strcmp(argv[1], "error") || !strcmp(argv[1], "capped"))
ack_test(argv[1]);
else if (!strcmp(argv[1], "options")) options_test();
else if (!strcmp(argv[1], "subscribe")) subscribe_test();
else if (!strcmp(argv[1], "dump")) dump_test();
else if (!strcmp(argv[1], "send_timeout")) send_timeout_test(0);
else if (!strcmp(argv[1], "nonblocking")) send_timeout_test(1);
@@ -1082,6 +1209,7 @@ int main(int argc, char **argv) {
}
else if (!strcmp(argv[1], "range") || !strcmp(argv[1], "cloexec") || !strcmp(argv[1], "closefrom"))
close_range_test(argv[1]);
else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && strcmp(argv[2], "allowed"), argc > 2 && !strcmp(argv[2], "sealed"));
else if (!strcmp(argv[1], "route")) {
require(argc >= 3, "route destination");
route_test(argv[2]);
@@ -1129,10 +1257,12 @@ class NetlinkPreloadTest(unittest.TestCase):
def tearDownClass(cls):
cls.temp.cleanup()
def run_program(self, mode, *arguments, snapshot=None):
def run_program(self, mode, *arguments, snapshot=None, denied=None):
env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}",
NETLINK_TEST_SNAPSHOT=str(snapshot or self.snapshot),
DD_SYSV_DIR=str(self.directory / "sysv"))
if denied:
env["NETLINK_TEST_DENIED"] = denied
result = subprocess.run([str(self.program), mode, *arguments], env=env,
capture_output=True, text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
@@ -1207,9 +1337,12 @@ class NetlinkPreloadTest(unittest.TestCase):
def test_cloexec_sockets_release_their_ports_after_exec(self):
self.run_program("all_cloexec")
def test_subscription_is_denied_and_receive_timeout_is_applied(self):
def test_membership_is_accepted_and_receive_timeout_is_applied(self):
self.run_program("options")
def test_change_listeners_subscribe_and_still_query(self):
self.run_program("subscribe")
def test_dump_keeps_multipart_completion(self):
self.run_program("dump")
@@ -1249,6 +1382,15 @@ class NetlinkPreloadTest(unittest.TestCase):
with self.subTest(mode=mode):
self.run_program(mode)
def test_denied_socket_tables_open_as_empty_tables(self):
self.run_program("proc_net", "denied", denied="/proc/net/")
def test_denied_socket_tables_open_when_fd_reopen_is_denied(self):
self.run_program("proc_net", "sealed", denied="/proc/net/:/proc/self/fd/")
def test_readable_socket_tables_stay_real(self):
self.run_program("proc_net")
def test_loopback_and_own_addresses_are_local_routes(self):
for destination, source in (("127.0.0.2", "127.0.0.1"), ("::1", "::1"),
("192.168.1.10", "192.168.1.10"), ("2001:db8::10", "2001:db8::10")):
+8 -1
View File
@@ -44,10 +44,11 @@ static struct surface surface = { .xdg_toplevel = 1, .toplevel_committed = 1 };
static int g_input_pipe[2] = {-1, -1};
static atomic_int g_output_refresh_mhz = 60000;
static atomic_int g_output_refresh_pending;
static atomic_int g_panel_rates_pending;
static int g_output_announced_refresh_mhz = 60000;
static int g_output_w = 1920, g_output_h = 1080;
static int flushes, resizes, pointers, ticks;
static int scale_changes, scale_mode, scale_alignment, renders;
static int scale_changes, scale_mode, scale_alignment, renders, rate_notifies;
static void *g_display;
#define WL_OUTPUT_MODE_CURRENT 1
#define WL_OUTPUT_MODE_PREFERRED 2
@@ -77,6 +78,7 @@ static void vk_present_set_scale_mode(int mode, int alignment) {
scale_changes++; scale_mode = mode; scale_alignment = alignment;
}
static void schedule_render(void) { renders++; }
static void refresh_notify_rates(void) { rate_notifies++; }
'''
CHECKS = r'''
@@ -138,6 +140,11 @@ int main(void) {
droiddeck_wayland_set_output_refresh_rate(90000);
drain(); expect(6, 90000, 1);
assert(scale_changes == 2 && scale_mode == 1 && scale_alignment == 3 && renders == 2);
atomic_store(&g_panel_rates_pending, 1);
drain();
assert(rate_notifies == 1 && !atomic_load(&g_panel_rates_pending));
drain();
assert(rate_notifies == 1);
close(g_input_pipe[0]); close(g_input_pipe[1]);
puts("PASS");
}
+11 -2
View File
@@ -26,7 +26,7 @@ static struct wl_event_source *g_render_idle, *g_fallback_timer;
static int g_fallback_armed, g_dirty, g_hud_fresh, framegen;
static void *g_hud_surface;
static int64_t g_dirty_since_ns, g_last_vsync_ns, g_tick_vsync_ns, g_hud_last_ns, g_rendered_tick_ns;
static int g_tick_held;
static int g_tick_held, g_tick_spare, g_scene_queues;
static int64_t g_hold_missed_ns;
#define HOLD_RETRY_NS 1000000000LL
static int64_t g_refresh_ns = 16666667;
@@ -254,6 +254,15 @@ int main(void) {
clock_ns += 200000000LL;
schedule_render();
assert(idles_added == idles && g_fallback_armed == 1 && timers_armed == 1);
g_rendered_tick_ns = g_tick_vsync_ns;
g_tick_spare = 0; g_scene_queues = 1;
assert(!tick_takes_scene());
g_tick_spare = 1;
assert(tick_takes_scene());
g_scene_queues = 0;
assert(!tick_takes_scene());
g_rendered_tick_ns = g_tick_vsync_ns - 1;
assert(tick_takes_scene());
puts("PASS");
return 0;
}
@@ -270,7 +279,7 @@ class RenderOnCommitTest(unittest.TestCase):
render = extract_function(source, 'render_scene')
self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render)
self.assertIn('g_tick_held = 0;', render)
functions = ('scene_held_for_limit', 'commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle',
functions = ('scene_held_for_limit', 'commit_renders_on', 'tick_takes_scene', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle',
'bfi_blocked', 'bfi_update', 'bfi_tick', 'on_vsync')
harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS
with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder:
+63
View File
@@ -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')
@@ -137,6 +172,19 @@ class RuntimeInputsTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_cargo_output_beside_a_windows_helper_is_not_a_source(self):
crate = self.root / 'tools/epic-launcher'
(crate / 'src').mkdir(parents=True)
(crate / 'Cargo.toml').write_text('[package]\n')
(crate / 'src/lib.rs').write_text('old')
runtime.record(self.root)
(crate / 'target/debug').mkdir(parents=True)
(crate / 'target/debug/build.log').write_text('local cargo test')
runtime.verify(self.root)
(crate / 'src/lib.rs').write_text('new')
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_missing_quest_driver_cannot_be_attested(self):
(self.root / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst').unlink()
with self.assertRaisesRegex(ValueError, 'quest1.tzst'):
@@ -248,6 +296,21 @@ class RuntimeInputsTest(unittest.TestCase):
runtime.check_apk(apk, self.root)
runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root)
def test_an_apk_still_carrying_the_epic_parent_stand_in_is_rejected(self):
epic = self.root / 'app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic'
epic.mkdir(parents=True)
(epic / 'EpicGamesLauncher.exe').write_bytes(b'MZ parent')
self.packs()
name = 'assets/linuxfs/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe'
self.assertIn(name, runtime.outputs(self.root))
apk = self.current_apk(self.root / 'bundled.apk', {name: b'MZ parent'})
with self.assertRaisesRegex(ValueError, 'epic pack provides'):
runtime.check_apk(apk, self.root)
runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root)
self.pack('epic', {'EpicGamesLauncher.exe': b'MZ older parent'})
with self.assertRaisesRegex(ValueError, 'epic is missing or has a stale'):
runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root)
def test_an_apk_still_carrying_the_powervr_runtime_is_rejected(self):
apk = self.current_apk(self.root / 'bundled.apk', {'assets/hybris/runtime.tzst': b'runtime'})
with self.assertRaisesRegex(ValueError, 'powervr pack provides'):
+7
View File
@@ -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())
+40
View File
@@ -314,6 +314,46 @@ 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())
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()
+2 -2
View File
@@ -12,7 +12,7 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d
class SteamPresentationTest(unittest.TestCase):
def launch(self, enabled=None, inherited=None):
source = SESSION.read_text()
begin = source.index(" dd_steam_path=$PATH")
begin = source.index(" dd_steam_path=")
end = source.index("\n decky_loader=", begin)
command = source.index(' PATH="$dd_steam_path"')
command_end = source.index("\n rc=$?", command)
@@ -41,7 +41,7 @@ class SteamPresentationTest(unittest.TestCase):
env=env, capture_output=True, text=True, timeout=5)
self.assertEqual(result.returncode, 0, result.stderr)
launch = json.loads(result.stdout.splitlines()[-1])
self.assertEqual(enabled == "1", launch["path"].startswith("/usr/local/libexec/droiddeck-steam:"))
self.assertEqual(launch["path"], "/usr/local/libexec/droiddeck-steam:" + env["PATH"])
self.assertEqual(launch["helper"], str(Path(tmp) / "steamrtarm64/steamwebhelper"))
return launch
+12
View File
@@ -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))
@@ -0,0 +1,89 @@
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64'
SOURCE = SCRIPT.read_text()
FUNCTION = re.search(r'^x64_thunk_appconfigs\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group()
CFG = '{"ThunksDB": {"GL": 1, "Vulkan": 1}}'
class SteamX64ThunkAppConfigsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
self.src = root / 'global'
self.dst = root / 'local'
self.src.mkdir()
def write_global(self, name, data):
(self.src / name).write_text(json.dumps(data))
def run_fn(self, on):
shell = FUNCTION + 'x64_thunk_appconfigs "$SRC" "$DST" "$CFG" "$ON"\n'
env = dict(os.environ, SRC=str(self.src), DST=str(self.dst), CFG=CFG, ON=on)
result = subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True, timeout=20)
self.assertEqual(0, result.returncode, result.stderr)
def test_program_with_a_disabled_thunk_gets_the_session_thunks(self):
self.write_global('anyprogram.json', {'Comment': 'x', 'ThunksDB': {'GL': 0}})
self.run_fn('1')
self.assertEqual(json.loads(CFG), json.loads((self.dst / 'anyprogram.json').read_text()))
def test_disabled_vulkan_counts_too(self):
self.write_global('other.json', {'ThunksDB': {'Vulkan': 0}})
self.run_fn('1')
self.assertTrue((self.dst / 'other.json').exists())
def test_programs_without_a_thunk_opt_out_are_untouched(self):
self.write_global('client.json', {'Config': {'HideHypervisorBit': '1'}})
self.write_global('enabled.json', {'ThunksDB': {'GL': 1}})
self.write_global('unrelated.json', {'ThunksDB': {'asound': 0}})
self.run_fn('1')
self.assertFalse(self.dst.exists())
def test_user_override_is_kept(self):
self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}})
self.dst.mkdir()
user = {'ThunksDB': {'GL': 0}, 'Config': {'Multiblock': '0'}}
(self.dst / 'anyprogram.json').write_text(json.dumps(user))
self.run_fn('1')
self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text()))
self.run_fn('0')
self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text()))
def test_software_mode_removes_only_the_written_file(self):
self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}})
self.run_fn('1')
self.run_fn('0')
self.assertFalse((self.dst / 'anyprogram.json').exists())
def test_software_mode_writes_nothing(self):
self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}})
self.run_fn('0')
self.assertFalse(self.dst.exists())
def test_broken_global_configs_do_not_fail(self):
(self.src / 'broken.json').write_text('{')
self.write_global('list.json', [1, 2])
self.run_fn('1')
self.assertFalse(self.dst.exists())
def test_missing_global_dir_does_not_fail(self):
self.src = self.src / 'missing'
self.run_fn('1')
self.assertFalse(self.dst.exists())
def test_launcher_applies_it_to_the_fex_app_config_dirs(self):
self.assertIn('x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"', SOURCE)
self.assertIn('''printf '%s\\n' "$thunk_cfg" > "$X64_HOME/thunks.json"''', SOURCE)
if __name__ == '__main__':
unittest.main()
+107 -2
View File
@@ -106,6 +106,62 @@ class Asking(unittest.TestCase):
self.assertIsNone(store.ask(channel, {'op': 'epic-code'}, timeout=0.2))
self.assertEqual([], list((channel / 'req').iterdir()))
def test_a_cloud_download_the_launcher_stops_waiting_for_loses_its_claim(self):
with tempfile.TemporaryDirectory() as root:
channel = Path(root) / 'stores'
taken = []
handed = threading.Event()
def app():
deadline = time.monotonic() + 5
while not taken and time.monotonic() < deadline:
for request in (channel / 'req').glob('*.json') if (channel / 'req').is_dir() else []:
target = channel / 'resp' / (request.stem + '.taken')
os.rename(request, target)
taken.append(target)
handed.set()
time.sleep(0.02)
t = threading.Thread(target=app, daemon=True)
t.start()
try:
self.assertIsNone(store.ask(channel, {'op': 'cloud-down'}, timeout=2.0, claim=True))
finally:
t.join(5)
self.assertTrue(handed.is_set(), 'the app never took the request')
with self.assertRaises(OSError):
os.rename(taken[0], taken[0].with_suffix('.writing'))
def test_a_claimed_cloud_download_is_waited_for(self):
with tempfile.TemporaryDirectory() as root:
channel = Path(root) / 'stores'
handed = threading.Event()
def app():
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
names = list((channel / 'req').glob('*.json')) if (channel / 'req').is_dir() else []
if names:
handed.set()
writing = channel / 'resp' / (names[0].stem + '.writing')
os.rename(names[0], writing)
time.sleep(0.6)
tmp = channel / 'resp' / (names[0].name + '.tmp')
tmp.write_text(json.dumps({'ok': True, 'result': 'ok'}))
os.rename(tmp, channel / 'resp' / names[0].name)
writing.unlink()
return
time.sleep(0.02)
t = threading.Thread(target=app, daemon=True)
t.start()
try:
answer = store.ask(channel, {'op': 'cloud-down'}, timeout=0.2, claim=True)
finally:
t.join(5)
self.assertTrue(handed.is_set(), 'the app never took the request')
self.assertEqual({'ok': True, 'result': 'ok'}, answer)
def test_a_stale_code_is_dropped_before_asking(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root)
@@ -214,7 +270,7 @@ class CloudHooks(unittest.TestCase):
try:
original = store.ask
asked = []
store.ask = lambda channel, request, timeout=5.0: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'}
store.ask = lambda channel, request, timeout=5.0, claim=False: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'}
self.assertEqual(store.STORE_GAME, store.main([bat]))
self.assertEqual(0, store.main(['--exited', bat]))
finally:
@@ -225,6 +281,55 @@ class CloudHooks(unittest.TestCase):
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
self.assertEqual('cloud-up', asked[2][0]['op'])
def test_a_cloud_request_that_cannot_be_written_still_starts_the_game_and_uploads_on_exit(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='ubisoft', ident='space-1')
sc = json.loads((folder / '.droiddeck-store.json').read_text()); sc['extra'] = {'productId': '109'}
(folder / '.droiddeck-store.json').write_text(json.dumps(sc))
bat = str(folder / '.droiddeck-launch.bat')
asked = []
def ask(channel, request, timeout=5.0, claim=False):
asked.append(request['op'])
if request['op'] in ('cloud-down', 'cloud-up'):
raise PermissionError(13, 'read-only')
return {'ok': True}
lines = []
with patch.dict(os.environ, {'DD_LAUNCH_DIR': str(Path(root) / 'session')}), patch.object(store, 'ask', side_effect=ask), patch.object(store, 'prepare_ubisoft', return_value='ready'), patch.object(store, 'create_prefix', return_value='present'), patch.object(store, 'log', side_effect=lines.append):
self.assertEqual(store.STORE_GAME, store.main([bat]))
self.assertEqual(0, store.main(['--exited', bat]))
self.assertEqual(['cloud-down', 'cloud-up'], [op for op in asked if op.startswith('cloud-')])
self.assertIn('cloud ubisoft space-1 down result=failed reason=PermissionError', lines)
self.assertIn('cloud ubisoft space-1 up not requested (PermissionError)', lines)
def test_an_ea_game_with_cloud_saves_asks_after_its_preparation_and_exit(self):
ident = 'Origin.OFR.50.0002694'
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='ea', ident=ident)
bat = str(folder / '.droiddeck-launch.bat')
asked = []
env = {'DD_LAUNCH_DIR': str(Path(root) / 'session')}
record = lambda channel, request, timeout=5.0, claim=False: asked.append(request) or {'result': 'ok'}
with patch.dict(os.environ, env), \
patch.object(store, 'prepare_ea', side_effect=lambda *a: asked.append({'op': 'prepared'})), \
patch.object(store, 'create_prefix', side_effect=AssertionError('EA prepares its own prefix')), \
patch.object(store, 'ask', side_effect=record):
self.assertEqual(store.STORE_GAME, store.main([bat]))
self.assertEqual(['prepared', 'cloud-down'], [r['op'] for r in asked])
self.assertEqual({'op': 'cloud-down', 'store': 'ea', 'id': ident}, asked[1])
self.assertEqual(0, store.main(['--exited', bat]))
self.assertEqual(['ea-exited', 'cloud-up'], [r['op'] for r in asked[2:]])
self.assertEqual({'op': 'cloud-up', 'store': 'ea', 'id': ident}, asked[3])
sidecar = json.loads((folder / store.SIDECAR).read_text())
sidecar['cloud'] = False
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
asked.clear()
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea'), patch.object(store, 'ask', side_effect=record):
self.assertEqual(store.STORE_GAME, store.main([bat]))
self.assertEqual([], asked)
self.assertEqual(0, store.main(['--exited', bat]))
self.assertEqual(['ea-exited'], [r['op'] for r in asked])
def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='epic', ident='fa4240e5')
@@ -244,7 +349,7 @@ class CloudHooks(unittest.TestCase):
env = {'DD_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': str(compat), 'DD_STORE_PROTON': str(proton)}
with patch.dict(os.environ, env), patch.object(store.subprocess, 'run', side_effect=run), \
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0: order.append(request) or {'result': 'ok'}):
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0, claim=False: order.append(request) or {'result': 'ok'}):
self.assertEqual(store.STORE_GAME, store.main([str(folder / store.LAUNCHER)]))
self.assertEqual([str(proton), 'run', 'cmd.exe', '/d', '/c', 'exit'], order[0])
self.assertEqual({'op': 'cloud-down', 'store': 'epic', 'id': 'fa4240e5'}, order[-1])
+1 -1
View File
@@ -147,7 +147,7 @@ class EaHook(unittest.TestCase):
folder.mkdir()
asked = {}
def fake_ask(channel, request, timeout=5.0):
def fake_ask(channel, request, timeout=5.0, claim=False):
asked.update(request)
return {'ok': True, 'lsx': True, 'license': 'ok v4', 'licenses': [{'path': 'ProgramData/L/x.dlf', 'data': base64.b64encode(b'z').decode()}]}
+145
View File
@@ -292,5 +292,150 @@ class RockstarLaunch(unittest.TestCase):
self.assertIn('Grand Theft Auto: Vice City', text)
SDK_FILES = {'socialclub.dll': b'sdk dll', 'socialclub.pak': b'sdk pak', 'SocialClubHelper.exe': b'sdk helper'}
class EpicRockstarLaunch(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.folder = self.root / 'Grand Theft Auto V'
self.folder.mkdir()
(self.folder / 'PlayGTAV.exe').write_bytes(b'MZ')
self.sidecar = {'store': 'epic', 'id': '9d2d0eb64d5c44529cece33fe2a46482', 'title': 'Grand Theft Auto V', 'exe': 'PlayGTAV.exe'}
(self.folder / '.droiddeck-store.json').write_text(json.dumps(self.sidecar))
self.prefix = self.root / 'prefix'
(self.prefix / 'pfx').mkdir(parents=True)
(self.prefix / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n')
(self.prefix / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n')
self.sdk = self.prefix / 'pfx/drive_c/Program Files/Rockstar Games/Social Club'
self.unpacked = []
def unpacker(self, command, **kwargs):
if command[1] == 'l':
listing = ''.join('Path = x64/%s\nSize = %d\n\n' % (name, len(data)) for name, data in SDK_FILES.items())
return type('Listing', (), {'returncode': 0, 'stdout': listing.encode()})()
self.unpacked.append(Path(command[-2]))
out = Path(next(arg[2:] for arg in command if arg.startswith('-o'))) / 'x64'
out.mkdir(parents=True)
for name, data in SDK_FILES.items():
(out / name).write_bytes(data + b' from ' + Path(command[-2]).read_bytes())
return type('Done', (), {'returncode': 0})()
def stage(self):
with patch.object(store.shutil, 'which', return_value='/bin/7z'), patch.object(store.subprocess, 'run', side_effect=self.unpacker), \
patch.object(store, 'wait_for_server', return_value=True), \
patch.object(store, 'create_prefix', side_effect=AssertionError('the prefix already exists')):
return store.epic_rockstar_sdk(self.folder, self.sidecar, str(self.prefix), '')
def test_the_launchers_own_sdk_installer_is_staged_so_it_never_runs_it(self):
setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP
setup.parent.mkdir(parents=True)
setup.write_bytes(b'launcher setup')
(self.folder / 'Installers').mkdir()
(self.folder / 'Installers/Social-Club-Setup.exe').write_bytes(b'older game setup')
self.assertEqual('installed', self.stage())
self.assertEqual([setup], self.unpacked)
self.assertEqual(b'sdk dll from launcher setup', (self.sdk / 'socialclub.dll').read_bytes())
text = (self.prefix / 'pfx/system.reg').read_text()
self.assertIn(r'[Software\\Wow6432Node\\Rockstar Games\\Rockstar Games Social Club]', text)
self.assertIn(r'"InstallFolder"="C:\\Program Files\\Rockstar Games\\Social Club"', text)
self.assertNotIn(r'Rockstar Games\\Launcher]', text)
self.assertEqual('present', self.stage())
self.assertEqual([setup], self.unpacked)
def test_an_updated_launcher_installer_is_staged_again(self):
setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP
setup.parent.mkdir(parents=True)
setup.write_bytes(b'launcher setup')
self.assertEqual('installed', self.stage())
setup.write_bytes(b'newer launcher setup')
self.assertEqual('installed', self.stage())
self.assertEqual(b'sdk dll from newer launcher setup', (self.sdk / 'socialclub.dll').read_bytes())
def test_before_the_launcher_is_installed_the_games_installer_is_used(self):
(self.folder / 'Redistributables').mkdir()
(self.folder / 'Redistributables/Social-Club-Setup.exe').write_bytes(b'game setup')
self.assertEqual('installed', self.stage())
self.assertEqual(b'sdk dll from game setup', (self.sdk / 'socialclub.dll').read_bytes())
self.assertNotIn(r'Rockstar Games\\Launcher]', (self.prefix / 'pfx/system.reg').read_text())
def test_other_epic_games_are_left_alone(self):
self.assertIsNone(self.stage())
self.assertEqual([], self.unpacked)
self.assertFalse(self.sdk.exists())
self.assertEqual('WINE REGISTRY Version 2\n', (self.prefix / 'pfx/system.reg').read_text())
def test_an_installer_linked_from_outside_the_game_is_ignored(self):
outside = self.root / 'outside.exe'
outside.write_bytes(b'not the game')
(self.folder / 'Installers').mkdir()
(self.folder / 'Installers/Social-Club-Setup.exe').symlink_to(outside)
self.assertIsNone(self.stage())
self.assertEqual([], self.unpacked)
def game_environment(self, shared=None, games=None):
config = self.root / 'home/.config/droiddeck/game-environment.json'
config.parent.mkdir(parents=True, exist_ok=True)
config.write_text(json.dumps({'version': 1, 'shared': shared or {}, 'games': games or {}}))
def launch(self, bat, parent, compat_data=''):
(self.folder / '.droiddeck-launch.bat').write_text(bat)
calls = []
env = {'DD_LAUNCH_DIR': str(self.root / 'launch'), 'STEAM_COMPAT_DATA_PATH': compat_data, 'HOME': str(self.root / 'home'),
'DD_EPIC_PARENT': ''}
with patch.dict(os.environ, env), patch.object(store, 'EPIC_PARENT', parent), \
patch.object(store, 'client_wanted', return_value=False), \
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=0, claim=False: calls.append((request['op'], timeout)) or {'ok': False}):
store.main([str(self.folder / '.droiddeck-launch.bat')])
return calls
def test_a_title_that_needs_the_parent_fetches_the_stand_in_before_its_code(self):
bat = '@echo off\r\nsetlocal\r\nset "DD_P=1"\r\n'
calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe')
self.assertEqual([('store-service', store.EPIC_SERVICE_WAIT), 'epic-code', 'cloud-down'],
[calls[0]] + [op for op, _ in calls[1:]])
staged = self.root / 'EpicGamesLauncher.exe'
staged.write_bytes(b'MZ')
self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch(bat, staged)])
def test_other_epic_games_do_not_fetch_the_stand_in(self):
bat = '@echo off\r\nsetlocal\r\nset "DD_P="\r\nif "%DD_EPIC_PARENT%"=="1" set "DD_P=1"\r\n'
calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe')
self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in calls])
def test_the_games_own_switch_decides_whether_the_stand_in_is_fetched(self):
compat_data = str(self.root / 'compatdata/4089453117')
missing = self.root / 'missing/EpicGamesLauncher.exe'
self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}})
self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0])
self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '0'}})
self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)])
self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': None}}, shared={'DD_EPIC_PARENT': '0'})
self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)[0][0])
def test_the_sidecars_own_environment_wins_like_it_does_in_the_batch(self):
compat_data = str(self.root / 'compatdata/4089453117')
missing = self.root / 'missing/EpicGamesLauncher.exe'
sidecar = self.folder / '.droiddeck-store.json'
sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '1'})))
self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0])
self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}})
sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '"0"'})))
self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)])
def test_the_switch_is_read_the_way_the_game_will_see_it(self):
env = {'HOME': str(self.root / 'home'), 'STEAM_COMPAT_DATA_PATH': str(self.root / 'compatdata/4089453117')}
self.assertEqual('', store.epic_parent_switch({}, env))
self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1')))
self.game_environment(shared={'DD_EPIC_PARENT': '1'}, games={'4089453117': {'DD_EPIC_PARENT': '0'}, '7': {'DD_EPIC_PARENT': '1'}})
self.assertEqual('0', store.epic_parent_switch({}, env))
self.assertEqual('1', store.epic_parent_switch({'env': {'DD_EPIC_PARENT': '1'}}, env))
self.assertEqual('1', store.epic_parent_switch({}, dict(env, STEAM_COMPAT_DATA_PATH=str(self.root / 'compatdata/12'))))
(self.root / 'home/.config/droiddeck/game-environment.json').write_text('{"version": 9}')
self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1')))
if __name__ == '__main__':
unittest.main()
+96
View File
@@ -0,0 +1,96 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
REPO = Path(__file__).resolve().parents[2]
SOURCE = REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c'
FUNCTIONS = (
'pending_release_free', 'pending_releases_forget_surface', 'pending_releases_cancel',
'pending_releases_apply', 'sync_holder', 'pending_releases_rehold', 'on_pending_release_buffer_destroyed',
'arm_release_timer', 'release_due_buffers', 'release_buffer', 'buffer_shown_elsewhere',
'drop_dmabuf',
)
def extract_function(source, name):
match = re.search(r'^static [^\n;]*?\b' + re.escape(name) + r'\([^;{]*\) \{$', source, re.MULTILINE)
if match is None:
raise AssertionError(f'Missing compositor function: {name}')
cursor, depth = match.end(), 1
while depth:
depth += (source[cursor] == '{') - (source[cursor] == '}')
cursor += 1
return match.group(0)[:-2] + ';', source[match.start():cursor]
def function_body(source, name):
return extract_function(source, name)[1]
class SubsurfaceReleaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if compiler is None:
raise unittest.SkipTest('A host C compiler is required')
cls.source = SOURCE.read_text()
start = cls.source.index('struct pending_release {')
end = cls.source.index('\n};\n', start) + 4
parts = [extract_function(cls.source, name) for name in FUNCTIONS]
code = cls.source[start:end] + '\n'.join(p[0] for p in parts) + '\n' + '\n'.join(p[1] for p in parts) + '\n'
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-subsurface-release-')
cls.addClassCleanup(cls.temp.cleanup)
folder = Path(cls.temp.name)
(folder / 'release.inc').write_text(code)
cls.binary = folder / 'release-test'
subprocess.run([compiler, '-std=c11', '-Wall', '-Werror', '-Wno-unused-function',
'-I', str(folder), '-I', str(REPO / 'app/src/main/cpp/waylandcomp/prebuilt/include'),
str(REPO / 'tools/tests/subsurface_release_harness.c'), '-o', str(cls.binary)],
check=True, capture_output=True, text=True)
def check_case(self, case):
result = subprocess.run([str(self.binary), case], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_buffer_moved_to_another_plane_is_released_once_after_the_parent_commit(self):
self.check_case('moved')
def test_buffer_attached_again_before_its_paced_release_is_released_once(self):
self.check_case('reattached')
def test_buffers_cycled_faster_than_their_paced_releases_are_released_once_each(self):
self.check_case('cycled')
def test_unpaced_sync_child_waits_for_the_parent_commit(self):
self.check_case('unpaced')
def test_desynchronized_child_is_released_without_a_parent_commit(self):
self.check_case('desync')
def test_toplevel_release_pacing_is_unchanged(self):
self.check_case('toplevel')
def test_held_release_is_sent_when_the_parent_is_destroyed(self):
self.check_case('destroyed')
def test_desynchronized_parent_releases_its_synchronized_child(self):
self.check_case('nested')
def test_set_desync_releases_what_the_old_parent_held(self):
self.check_case('set-desync')
def test_compositor_attach_and_commit_use_the_release_hold(self):
self.assertIn('pending_releases_cancel(buffer);', function_body(self.source, 'take_dmabuf'))
commit = function_body(self.source, 'surface_commit')
self.assertIn('pending_releases_apply(s);', commit)
self.assertLess(commit.index('take_dmabuf(s, db, buffer);'), commit.index('pending_releases_apply(s);'))
self.assertLess(commit.index('buf_trace_attach(buffer);'), commit.index('if (s->role == ROLE_CURSOR)'))
self.assertIn('pending_releases_rehold(s);', function_body(self.source, 'subsurface_set_desync'))
if __name__ == '__main__':
unittest.main()
+112
View File
@@ -0,0 +1,112 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <linux/netlink.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main(int argc, char **argv) {
unsigned groups = argc > 1 ? (unsigned)atoi(argv[1]) : 2;
const char *mode = argc > 2 ? argv[2] : "";
if (!strcmp(mode, "churn")) {
for (int i = 0; i < 16; i++) {
int closed = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
struct sockaddr_nl unsubscribed = {.nl_family = AF_NETLINK};
if (closed < 0 || bind(closed, (struct sockaddr *)&unsubscribed, sizeof(unsubscribed)) != 0) return 3;
close(closed);
if (open("/dev/null", O_RDONLY) != closed) return 4;
}
}
int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
if (fd < 0) { printf("socket failed\n"); return 2; }
struct sockaddr_nl nl = {.nl_family = AF_NETLINK, .nl_groups = groups};
printf("bind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl)));
if (!strcmp(mode, "rebind")) {
nl.nl_pid = (unsigned)getpid() + 1;
printf("rebind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl)));
}
printf("cloexec %d nonblock %d\n", (fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (fcntl(fd, F_GETFL) & O_NONBLOCK) != 0);
int (*inject)(const char *, const char *, const char *, const char *, unsigned, unsigned) =
(int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned))dlsym(RTLD_DEFAULT, "dd_udevmon_inject");
int sent = inject("add", "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20", "hidraw",
"/dev/hidraw20", 245, 20);
printf("sent %d\n", sent);
struct pollfd p = {.fd = fd, .events = POLLIN};
if (sent > 0 && poll(&p, 1, 1000) == 1) {
char buf[2048];
struct sockaddr_nl from;
struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)};
struct msghdr msg = {.msg_name = &from, .msg_namelen = sizeof(from), .msg_iov = &iov, .msg_iovlen = 1};
ssize_t n = recvmsg(fd, &msg, 0);
int found = 0;
for (ssize_t i = 0; n > 0 && i < n; i += (ssize_t)strlen(buf + i) + 1)
if (!strcmp(buf + i, "ACTION=add") || !strcmp(buf + i, "DEVNAME=/dev/hidraw20")) found++;
printf("received %s fields %d\n", n > 0 && !memcmp(buf, "libudev", 8) ? "libudev" : "nothing", found);
}
return 0;
}
"""
@unittest.skipUnless(shutil.which("gcc") and os.uname().machine == "x86_64", "needs gcc on an x86-64 host")
class UdevMonitorPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = Path(tempfile.mkdtemp())
cls.library = cls.tmp / "libudevmon.so"
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DUDEVMON_TEST", "-DBINFMT_TEST",
'-DBINFMT_HANDLER="/bin/false"', "-o", str(cls.library), "-pthread"]
+ [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")]
+ [str(Path(__file__).with_name("netlink_stubs.c")), "-ldl"], check=True)
source = cls.tmp / "program.c"
source.write_text(PROGRAM)
cls.program = cls.tmp / "program"
subprocess.run(["gcc", "-O2", "-o", str(cls.program), str(source), "-ldl"], check=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, True)
def run_program(self, *args, refuse=False):
env = dict(os.environ, LD_PRELOAD=str(self.library))
env.pop("DD_UDEVMON_REFUSE", None)
if refuse:
env["DD_UDEVMON_REFUSE"] = "1"
return subprocess.run([str(self.program), *args], env=env, capture_output=True, text=True, check=True).stdout.splitlines()
def test_a_monitor_the_system_will_not_subscribe_hears_the_sessions_events(self):
out = self.run_program(refuse=True)
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out)
def test_a_monitor_the_system_subscribes_stays_on_the_real_socket(self):
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 0"], self.run_program())
def test_a_monitor_bound_without_groups_hears_the_sessions_events(self):
out = self.run_program("0")
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out)
def test_failed_rebind_leaves_the_original_subscription_in_place(self):
out = self.run_program("2", "rebind")
self.assertEqual(["bind 0", "rebind -1", "cloexec 1 nonblock 1", "sent 0"], out)
def test_closed_monitors_do_not_exhaust_stand_in_slots(self):
out = self.run_program("0", "churn")
self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out)
if __name__ == "__main__":
unittest.main()
+6 -6
View File
@@ -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)])
+140
View File
@@ -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()
+4
View File
@@ -51,6 +51,10 @@ class VkDmabufQuarantineTest(unittest.TestCase):
# One surface per buffer in these scenarios: never shown elsewhere.
helpers += ['static int buffer_shown_elsewhere(struct wl_resource *b, const struct surface *e) '
'{ (void)b; (void)e; return 0; }']
if re.search(r'^static void release_due_buffers\(void\) \{', comp, re.M):
helpers += ['static void release_due_buffers(void);', 'static void arm_release_timer(void);',
function(comp, 'sync_holder')]
names.insert(names.index('on_release_timer'), 'release_due_buffers')
if re.search(r'\bvolatile int g_release_unpaced;', comp):
# Releases stay paced in these scenarios (fps limit -1 sends them at once).
helpers.insert(0, 'static int g_release_unpaced;')
+156
View File
@@ -0,0 +1,156 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_vk_external_image_sync import vulkan_include_args
from tools.tests.test_vk_pending_completion import function
TESTS = Path(__file__).resolve().parent
SRC = TESTS.parents[1] / "app/src/main/cpp/waylandcomp/src"
LAYER_HARNESS = r'''
#include <assert.h>
#include <stdint.h>
#include <vulkan/vulkan.h>
#include "vk_external_image_sync.h"
#include "vk_linear_dmabuf.h"
typedef struct AHardwareBuffer AHardwareBuffer;
%(image)s
struct vkp_draw {
struct vkp_image *img;
float sx, sy, sw, sh;
int dx, dy, dw, dh;
int blend;
};
struct draw_list { struct vkp_draw *d; int n, cap; };
static const uint32_t g_qfam = 2;
%(foreign)s
%(is_dmabuf)s
%(width)s
%(height)s
static int black_fill_below(const struct draw_list *dl, int n) { (void)dl; (void)n; return 0; }
%(candidate)s
static int candidate(struct vkp_image *img) {
struct vkp_draw d = {.img = img, .sw = 1560, .sh = 720, .dw = 1560, .dh = 720};
struct draw_list dl = {.d = &d, .n = 1, .cap = 1};
return layer_candidate(&dl, 1560, 720);
}
static int foreign_pair(struct vkp_image *img) {
struct vkp_external_client_barrier_pair pair;
return vkp_external_client_barrier_pair(img->image, g_qfam, foreign_image(img), img->blit_dst, &pair);
}
int main(void) {
struct vkp_image staged = {.w = 1560, .h = 720, .dmabuf = 1, .staged = 1};
assert(candidate(&staged) == 0);
assert(!foreign_pair(&staged));
struct vkp_image client = {.w = 1560, .h = 720, .dmabuf = 1};
assert(candidate(&client) == 0);
assert(foreign_pair(&client));
struct vkp_image shm = {.w = 1560, .h = 720};
assert(candidate(&shm) == -1);
assert(!foreign_pair(&shm));
struct vkp_image layer = {.w = 1560, .h = 720, .dmabuf = 1, .blit_dst = 1};
assert(candidate(&layer) == -1);
assert(!foreign_pair(&layer));
return 0;
}
'''
def compile_and_run(test, source, tmp, name):
compiler = shutil.which(os.environ.get("CC", "cc"))
if not compiler:
test.fail("A C compiler is required for the linear dma-buf regression tests")
program = Path(tmp) / name
command = [
compiler,
"-std=c11",
"-Wall",
"-Wextra",
"-Werror",
"-UNDEBUG",
"-I",
str(SRC),
*vulkan_include_args(),
str(source),
"-o",
str(program),
]
built = subprocess.run(command, capture_output=True, text=True)
test.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
test.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
class VkLinearDmabufTest(unittest.TestCase):
def test_linear_dmabuf_copy(self):
with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-") as tmp:
compile_and_run(self, TESTS / "vk_linear_dmabuf_test.c", tmp, "vk-linear-dmabuf")
def test_readback_orders_general_transition_after_staging_copy(self):
body = function((SRC / "vk_present.c").read_text(), "vkp_image_readback")
stage = body.index("stage_linear_dmabuf(cmd, src);")
barrier = body.index("vkp_linear_dmabuf_readback_stage(src->in_general)")
self.assertLess(stage, barrier)
self.assertIn(".srcAccessMask = vkp_linear_dmabuf_readback_access(src->in_general)", body[stage:barrier])
self.assertNotIn("CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT", body)
def test_modifier_query_needs_drm_modifier_extension(self):
body = function((SRC / "vk_present.c").read_text(), "vkp_image_import_dmabuf")
query = re.search(r"const int modifier_sampled = (.*?);", body, re.S)
self.assertIsNotNone(query, "modifier_sampled not found in vkp_image_import_dmabuf")
terms = [t.strip() for t in query.group(1).split("&&")]
self.assertIn("g_drm_modifiers", terms)
self.assertLess(terms.index("g_drm_modifiers"), terms.index("modifier_importable(img->fmt, modifier, sampled_usage)"))
self.assertIn("!as_blit_dst", terms)
self.assertIn("g_vk.GetPhysicalDeviceImageFormatProperties2", terms)
def test_staged_client_image_stays_layer_candidate(self):
vk = (SRC / "vk_present.c").read_text()
comp = (SRC / "compositor.c").read_text()
image = re.search(r"^struct vkp_image \{.*?^\};", vk, re.M | re.S)
self.assertIsNotNone(image, "struct vkp_image not found in vk_present.c")
harness = LAYER_HARNESS % {
"image": image.group(0),
"foreign": function(vk, "foreign_image"),
"is_dmabuf": function(vk, "vkp_image_is_dmabuf"),
"width": function(vk, "vkp_image_width"),
"height": function(vk, "vkp_image_height"),
"candidate": function(comp, "layer_candidate"),
}
with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-layer-") as tmp:
source = Path(tmp) / "layer_candidate_test.c"
source.write_text(harness)
compile_and_run(self, source, tmp, "vk-linear-layer")
def test_layer_import_failure_requests_compositor_fallback(self):
source = (SRC / "sc_layer.c").read_text()
for name in ("sc_layer_present", "sc_layer_present_overlay"):
with self.subTest(layer=name):
body = function(source, name)
self.assertRegex(body, r"if \(idx < 0\) \{ log_drop\(l\); return g_alloc_failed \? -1 : 0; \}")
def test_layer_blits_use_the_imported_output_row_pitch(self):
source = (SRC / "vk_present.c").read_text()
blit = function(source, "blit_to_layer")
copy = blit.index("CmdCopyImageToBuffer")
self.assertLess(blit.index("VkBufferImageCopy copy = dst->linear_copy"), copy)
self.assertLess(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 1"), copy)
self.assertGreater(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 0"), copy)
for name in ("vkp_blit_image", "pass_finish"):
self.assertIn("blit_to_layer(", function(source, name))
if __name__ == "__main__":
unittest.main()
+7 -3
View File
@@ -56,16 +56,20 @@ static VkResult wait_fn(uintptr_t dev, unsigned n, const VkFence *f, int all, ui
static void unmap_fn(uintptr_t dev, uintptr_t mem) { (void)dev; (void)mem; ++unmapped; }
static void destroy_fn(uintptr_t dev, uintptr_t img, void *allocator) { (void)dev; (void)img; (void)allocator; ++destroyed; }
static void free_fn(uintptr_t dev, uintptr_t mem, void *allocator) { (void)dev; (void)mem; (void)allocator; ++freed_memory; }
static unsigned destroyed_buffers;
static void destroy_buffer_fn(uintptr_t dev, uintptr_t buf, void *allocator) { (void)dev; (void)buf; (void)allocator; ++destroyed_buffers; }
#define VK_NULL_HANDLE 0
static struct {
VkResult (*WaitForFences)(uintptr_t, unsigned, const VkFence *, int, uint64_t);
void (*UnmapMemory)(uintptr_t, uintptr_t);
void (*DestroyImage)(uintptr_t, uintptr_t, void *);
void (*FreeMemory)(uintptr_t, uintptr_t, void *);
} g_vk = {wait_fn, unmap_fn, destroy_fn, free_fn};
void (*DestroyBuffer)(uintptr_t, uintptr_t, void *);
} g_vk = {wait_fn, unmap_fn, destroy_fn, free_fn, destroy_buffer_fn};
typedef struct AHardwareBuffer AHardwareBuffer;
static int released_buffers;
static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; ++released_buffers; }
struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; };
struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; uintptr_t linear_buf, linear_mem; int staged, in_general; };
static void blendp_forget_image(uintptr_t image) { (void)image; ++forgotten; }
/* PRODUCTION_FUNCTIONS */
static struct vkp_image *image(void) {
@@ -173,7 +177,7 @@ class VkPendingCompletionTest(unittest.TestCase):
self.assertEqual(ran.returncode,0,ran.stdout+ran.stderr)
def test_unknown_completion_retains_gpu_resources(self):
self.compile_and_run(HARNESS, ['quarantine_pending_work', 'timed_wait', 'vkp_image_destroy'])
self.compile_and_run(HARNESS, ['quarantine_pending_work', 'timed_wait', 'destroy_image_objects', 'vkp_image_destroy'])
def test_failed_device_idle_does_not_destroy_swapchain(self):
# LOGE's arguments must be evaluated as real production logging does.
+3 -3
View File
@@ -58,7 +58,7 @@ class WaylandClockDomainTest(unittest.TestCase):
#include <unistd.h>
#include "clock_domain.h"
struct pending_release { void *buffer; int64_t at_ns; struct pending_release *next; };
struct pending_release { void *buffer; int64_t at_ns; struct pending_release *next; void *held_by; };
static struct pending_release *g_pending_releases;
static int g_release_timer_fd;
#define wl_list_for_each(pr, list, link) for (pr = *(list); pr; pr = pr->next)
@@ -79,8 +79,8 @@ int main(int argc, char **argv) {
struct timespec started, ended;
clock_gettime(CLOCK_MONOTONIC, &started);
int64_t start = now_ns();
struct pending_release blocked = {(void *)1, start + 1000000LL, NULL};
struct pending_release release = {NULL, start + 60000000LL, &blocked};
struct pending_release blocked = {(void *)1, start + 1000000LL, NULL, NULL};
struct pending_release release = {NULL, start + 60000000LL, &blocked, NULL};
g_pending_releases = &release;
arm_release_timer();
int64_t next_offset = offsets[i] + 10000000000LL;
+53 -4
View File
@@ -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)
+95
View File
@@ -178,6 +178,101 @@ class XboxLaunchTest(unittest.TestCase):
self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:'])
self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None))
def test_package_install_actions_run_once_and_stay_inside_the_game(self):
with tempfile.TemporaryDirectory() as root:
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
(game / 'Installers').mkdir(parents=True)
(game / 'Installers' / 'GameInputRedist.msi').write_bytes(b'msi')
(game / 'Emu.exe').write_bytes(b'exe')
(Path(root) / 'outside.msi').write_bytes(b'msi')
(game / 'MicrosoftGame.config').write_text(
'<Game><DesktopRegistration><CustomInstallActions><Folder>Installers</Folder><InstallActionList>'
'<InstallAction File="GameInputRedist.msi" Name="InstallGameInput" Arguments="/quiet"/>'
'<InstallAction File="..\\..\\outside.msi" Name="Escape"/>'
'</InstallActionList></CustomInstallActions></DesktopRegistration></Game>')
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
xbox['run_install_actions']('/selected/proton', prefix, str(game / 'Emu.exe'), {'A': '1'})
xbox['run_install_actions']('/selected/proton', prefix, str(game / 'Emu.exe'), {'A': '1'})
self.assertEqual(child.call_count, 1)
command = child.call_args.args[0]
self.assertEqual(command[:4], ['/selected/proton', 'run', 'msiexec', '/i'])
self.assertTrue(command[4].startswith('Z:') and command[4].endswith('GameInputRedist.msi'))
self.assertEqual(command[5:], ['/quiet'])
def test_a_failed_install_action_is_retried_on_the_next_launch(self):
with tempfile.TemporaryDirectory() as root:
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
game.mkdir()
(game / 'setup.exe').write_bytes(b'exe')
(game / 'MicrosoftGame.config').write_text(
'<Game><CustomInstallActions><InstallActionList><InstallAction File="setup.exe" Name="Setup"/>'
'</InstallActionList></CustomInstallActions></Game>')
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 1)) as child:
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
self.assertEqual(child.call_count, 2)
self.assertEqual(child.call_args.args[0][:2], ['/p', 'run'])
def test_install_action_arguments_follow_windows_command_line_rules(self):
parse = xbox['windows_arguments']
self.assertEqual(parse('/quiet /log "C:\\ProgramData\\Game Setup\\install.log"'),
['/quiet', '/log', 'C:\\ProgramData\\Game Setup\\install.log'])
self.assertEqual(parse('a\\\\b "x\\"y" "\\\\" "" c""d "e""f"'), ['a\\\\b', 'x"y', '\\', '', 'cd', 'e"f'])
self.assertEqual(parse(' '), [])
with tempfile.TemporaryDirectory() as root:
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
game.mkdir()
(game / 'setup.msi').write_bytes(b'msi')
(game / 'MicrosoftGame.config').write_text(
'<Game><CustomInstallActions><InstallActionList><InstallAction File="setup.msi" Name="Setup" '
'Arguments="/quiet /log &quot;C:\\ProgramData\\Game Setup\\install.log&quot;"/>'
'</InstallActionList></CustomInstallActions></Game>')
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
xbox['run_install_actions']('/p', prefix, str(game / 'setup.msi'), {})
self.assertEqual(child.call_args.args[0][5:], ['/quiet', '/log', 'C:\\ProgramData\\Game Setup\\install.log'])
def test_actions_whose_names_differ_only_in_punctuation_each_run(self):
with tempfile.TemporaryDirectory() as root:
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
game.mkdir()
(game / 'setup.exe').write_bytes(b'exe')
(game / 'MicrosoftGame.config').write_text(
'<Game><CustomInstallActions><InstallActionList>'
'<InstallAction File="setup.exe" Name="Setup A" Arguments="/a"/>'
'<InstallAction File="setup.exe" Name="SetupA" Arguments="/b"/>'
'</InstallActionList></CustomInstallActions></Game>')
with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {})
self.assertEqual([call.args[0][-1] for call in child.call_args_list], ['/a', '/b'])
def test_an_install_action_error_never_stops_the_launch(self):
with tempfile.TemporaryDirectory() as root:
game, prefix = Path(root) / 'game', Path(root) / 'pfx'
game.mkdir()
(game / 'first.exe').write_bytes(b'exe')
(game / 'second.exe').write_bytes(b'exe')
(game / 'MicrosoftGame.config').write_text(
'<Game><CustomInstallActions><InstallActionList>'
'<InstallAction File="first.exe" Name="First"/><InstallAction File="second.exe" Name="Second"/>'
'</InstallActionList></CustomInstallActions></Game>')
real_open = Path.open
def unreadable(path, *args, **kwargs):
if path.name == 'first.exe':
raise PermissionError('denied')
return real_open(path, *args, **kwargs)
with patch.object(Path, 'open', unreadable), \
patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
xbox['run_install_actions']('/p', prefix, str(game / 'first.exe'), {})
self.assertEqual(child.call_count, 1)
self.assertTrue(child.call_args.args[0][2].endswith('second.exe'))
with patch('subprocess.run', side_effect=OSError('no proton')):
xbox['run_install_actions']('/p', prefix, str(game / 'first.exe'), {})
with patch.object(Path, 'touch', side_effect=OSError('read-only')), \
patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child:
xbox['run_install_actions']('/p', prefix / 'other', str(game / 'first.exe'), {})
self.assertEqual(child.call_count, 2)
def test_missing_runtime_classes_are_registered_once(self):
with tempfile.TemporaryDirectory() as root:
prefix = Path(root)
+318 -30
View File
@@ -18,7 +18,14 @@ PROGRAM = r"""
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <sched.h>
#include <stddef.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
@@ -31,14 +38,15 @@ static unsigned char *shared;
static volatile sig_atomic_t urg_tid;
static volatile sig_atomic_t usr_tid;
static int urg_count, usr_count;
static int worker_tid;
static int worker_delivery;
_Static_assert(__atomic_always_lock_free(sizeof(int), 0), "signal state must be lock-free");
static void signal_tid(int sig) {
sig_atomic_t tid = (sig_atomic_t)syscall(SYS_gettid);
if (tid == __atomic_load_n(&worker_tid, __ATOMIC_RELAXED))
char name[16] = {0};
prctl(PR_GET_NAME, name, 0, 0, 0);
if (!strcmp(name, "zr-worker"))
__atomic_store_n(&worker_delivery, 1, __ATOMIC_RELAXED);
if (sig == SIGURG) {
__atomic_store_n(&urg_tid, tid, __ATOMIC_RELAXED);
@@ -60,6 +68,19 @@ static long status(const char *key) {
return v;
}
static long resident(char *start, size_t size) {
long page = sysconf(_SC_PAGESIZE), kb = 0;
int fd = open("/proc/self/pagemap", O_RDONLY);
if (fd < 0) exit(8);
for (size_t i = 0; i < size; i += page) {
uint64_t entry;
if (pread(fd, &entry, sizeof(entry), ((uintptr_t)start + i) / page * sizeof(entry)) != sizeof(entry)) exit(8);
if (entry >> 63) kb += page / 1024;
}
close(fd);
return kb;
}
static void send_request(char mode) {
int fd = open(ctl, O_WRONLY | O_TRUNC);
if (fd < 0 || write(fd, &mode, 1) != 1) exit(3);
@@ -91,6 +112,94 @@ static void request(char mode) {
usleep(1000000);
}
static long trim(char mode, long kb) {
char ack[256], text[32];
snprintf(ack, sizeof(ack), "%s.trim.%d", ctl, getpid());
unlink(ack);
FILE *f = fopen(ctl, "w");
if (!f) exit(3);
fprintf(f, "%c %ld\n", mode, kb);
fclose(f);
kill(getpid(), SIGURG);
for (int i = 0; i < 1200; i++) {
f = fopen(ack, "r");
char *line = f ? fgets(text, sizeof(text), f) : NULL;
if (f) fclose(f);
if (line) return atol(text);
usleep(10000);
}
exit(5);
}
static int workers(void) {
DIR *dir = opendir("/proc/self/task");
struct dirent *entry;
int count = 0;
while (dir && (entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') continue;
char path[64], name[32] = {0};
snprintf(path, sizeof(path), "/proc/self/task/%s/comm", entry->d_name);
FILE *comm = fopen(path, "r");
if (comm && fgets(name, sizeof(name), comm) && !strcmp(name, "zr-worker\n")) count++;
if (comm) fclose(comm);
}
if (dir) closedir(dir);
return count;
}
static void without_threads(void) {
struct rlimit limit;
if (getrlimit(RLIMIT_NPROC, &limit)) _exit(15);
limit.rlim_cur = 0;
if (setrlimit(RLIMIT_NPROC, &limit)) _exit(15);
}
static void *park(void *arg) {
(void)arg;
for (;;) pause();
return NULL;
}
static void parked(void) {
pthread_t thread;
sigset_t urg, previous;
sigemptyset(&urg);
sigaddset(&urg, SIGURG);
pthread_sigmask(SIG_BLOCK, &urg, &previous);
if (pthread_create(&thread, NULL, park, NULL)) _exit(16);
pthread_sigmask(SIG_SETMASK, &previous, NULL);
}
static void filter_clone(unsigned long allowed) {
struct sock_filter rules[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_clone, 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, allowed, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog program = {sizeof(rules) / sizeof(rules[0]), rules};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program)) _exit(17);
}
static volatile int sandbox_ready;
static void *sandbox(void *arg) {
(void)arg;
sigset_t urg;
sigemptyset(&urg);
sigaddset(&urg, SIGURG);
filter_clone(0);
pthread_sigmask(SIG_UNBLOCK, &urg, NULL);
sandbox_ready = 1;
for (;;) pause();
return NULL;
}
static const unsigned long thread_clone = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD |
CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
static uint64_t sum(const unsigned char *p, size_t n) {
uint64_t s = 0;
for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i];
@@ -123,6 +232,7 @@ int main(int argc, char **argv) {
memset(shared, 0, size);
pthread_t t[2];
for (uintptr_t i = 0; i < 2; i++) pthread_create(&t[i], NULL, writer, (void *)i);
parked();
struct sigaction sa;
sigaction(SIGURG, NULL, &sa);
printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0);
@@ -132,27 +242,21 @@ int main(int argc, char **argv) {
memset(&signal_action, 0, sizeof(signal_action));
signal_action.sa_handler = signal_tid;
sigemptyset(&signal_action.sa_mask);
sigaction(SIGURG, &signal_action, NULL);
sigaction(SIGUSR1, &signal_action, NULL);
int fd = open(ctl, O_WRONLY | O_TRUNC);
if (fd < 0 || write(fd, "1", 1) != 1) return 10;
close(fd);
printf("ready %d\n", getpid());
fflush(stdout);
int id;
if (scanf("%d", &id) != 1) return 10;
__atomic_store_n(&worker_tid, id, __ATOMIC_RELAXED);
printf("armed 1\n");
fflush(stdout);
for (int round = 1; round <= 100; round++) {
int i;
for (i = 0; i < 5000 &&
(__atomic_load_n(&urg_count, __ATOMIC_ACQUIRE) < round ||
__atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round); i++) usleep(1000);
for (i = 0; i < 5000 && __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round; i++) usleep(1000);
if (i == 5000) return 11;
printf("received %d\n", round);
fflush(stdout);
}
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("urg %d\n", __atomic_load_n(&urg_tid, __ATOMIC_RELAXED));
printf("usr %d\n", __atomic_load_n(&usr_tid, __ATOMIC_RELAXED));
printf("worker %d\n", __atomic_load_n(&worker_delivery, __ATOMIC_RELAXED));
return 0;
@@ -167,6 +271,126 @@ int main(int argc, char **argv) {
int status_code;
waitpid(child, &status_code, 0);
printf("childack %d\n", WIFEXITED(status_code) && WEXITSTATUS(status_code) == 0);
} else if (!strcmp(argv[4], "threads")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("idle %d\n", workers());
request('1');
printf("after %d\n", workers());
return 0;
} else if (!strcmp(argv[4], "trim")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("first %ld\n", trim('2', 8192));
printf("second %ld\n", trim('2', 8192));
printf("swapped %ld\n", status("VmSwap:"));
printf("rest %ld\n", trim('2', 1L << 30));
printf("touched %d\n", sum(shared, size) != 0);
printf("hot %ld\n", trim('2', 1L << 30));
printf("forced %ld\n", trim('3', 1L << 30));
request('0');
printf("again %ld\n", trim('2', 1L << 30));
printf("intact %d\n", sum(data, size) == before);
return 0;
} else if (!strcmp(argv[4], "trim-small")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
long total = 0, largest = 0;
for (int i = 0; i < 112; i++) {
long step = trim('2', 512);
total += step;
if (step > largest) largest = step;
}
printf("small %ld\n", total);
printf("largest %ld\n", largest);
return 0;
} else if (!strcmp(argv[4], "trim-sparse")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
size_t wide = 32UL << 20;
char *thin = mmap(NULL, wide, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (thin == MAP_FAILED) exit(7);
for (size_t i = 0; i < wide; i += 2 * page) thin[i] = 1;
printf("sparse %ld\n", resident(thin, wide));
for (int i = 0; i < 240; i++) trim('2', 512);
printf("kept %ld\n", resident(thin, wide));
return 0;
} else if (!strcmp(argv[4], "hold")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
char hold[256];
snprintf(hold, sizeof(hold), "%s.hold", ctl);
FILE *f = fopen(hold, "w");
if (!f) exit(3);
fclose(f);
printf("empty %ld\n", trim('2', 512));
f = fopen(hold, "w");
if (!f) exit(3);
fputs("1", f);
fclose(f);
f = fopen(ctl, "w");
if (!f) exit(3);
fputs("2 512\n", f);
fclose(f);
kill(getpid(), SIGURG);
wait_ack();
printf("held %ld\n", status("VmSwap:"));
unlink(hold);
return 0;
} else if (!strcmp(argv[4], "trim-fork")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
fflush(stdout);
pid_t child = fork();
if (child < 0) exit(6);
if (child == 0) {
for (size_t i = 0; i < size; i += page) data[i]++;
printf("inline_trim %ld\n", trim('2', 1L << 30));
fflush(stdout);
_exit(0);
}
waitpid(child, NULL, 0);
child = fork();
if (child < 0) exit(6);
if (child == 0) {
parked();
without_threads();
for (size_t i = 0; i < size; i += page) data[i]++;
printf("nothread_trim %ld\n", trim('2', 1L << 30));
fflush(stdout);
_exit(0);
}
waitpid(child, NULL, 0);
printf("worker_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "sandboxed")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
filter_clone(thread_clone);
printf("sandboxed_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "thread-sandboxed")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
sigset_t urg;
sigemptyset(&urg);
sigaddset(&urg, SIGURG);
pthread_sigmask(SIG_BLOCK, &urg, NULL);
pthread_t thread;
if (pthread_create(&thread, NULL, sandbox, NULL)) exit(16);
while (!sandbox_ready) usleep(1000);
printf("thread_sandboxed_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "filtered")) {
fflush(stdout);
filter_clone(thread_clone);
execl("/proc/self/exe", argv[0], argv[1], argv[2], "0", "filtered-trim", (char *)NULL);
return 18;
} else if (!strcmp(argv[4], "filtered-trim")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("filtered_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "burst")) {
send_request('0');
usleep(10000);
@@ -177,6 +401,7 @@ int main(int argc, char **argv) {
pid_t child = fork();
if (child < 0) exit(8);
if (child == 0) {
without_threads();
if (!strcmp(argv[4], "timed-inline-single")) {
if (munmap(data, size) || munmap(shared, size)) _exit(12);
data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
@@ -280,8 +505,9 @@ class ZramPreloadTest(unittest.TestCase):
def setUp(self):
self.ctl.write_text("0")
for ack in self.dir.glob("ctl.ack.*"):
for ack in [*self.dir.glob("ctl.ack.*"), *self.dir.glob("ctl.trim.*")]:
ack.unlink()
(self.dir / "ctl.hold").unlink(missing_ok=True)
def run_program(self, program=None, mb=48, cycles=1, *extra):
environment = dict(os.environ, LD_PRELOAD=str(self.lib))
@@ -324,6 +550,11 @@ class ZramPreloadTest(unittest.TestCase):
self.assertEqual([1], out["intact"])
self.assertEqual(6, len(out["out"]))
def test_a_process_keeps_no_extra_thread_while_nothing_is_paged_out(self):
out = self.run_program(None, 8, 0, "threads")
self.assertEqual([0], out["idle"])
self.assertEqual([0], out["after"])
def test_process_signals_do_not_reach_zram_worker(self):
environment = dict(os.environ, LD_PRELOAD=str(self.lib))
process = subprocess.Popen([str(self.steam), str(self.ctl), "1", "0", "signals"],
@@ -332,28 +563,16 @@ class ZramPreloadTest(unittest.TestCase):
process.stdout.readline()
ready = process.stdout.readline().split()
self.assertEqual("ready", ready[0])
worker = None
task_dir = Path("/proc") / ready[1] / "task"
for task in task_dir.iterdir():
if (task / "comm").read_text().strip() == "zr-worker":
worker = int(task.name)
break
self.assertIsNotNone(worker)
self.assertEqual(os.sched_getscheduler(process.pid), os.sched_getscheduler(worker))
process.stdin.write(f"{worker}\n")
process.stdin.flush()
self.assertEqual("armed 1", process.stdout.readline().strip())
for _ in range(100):
for round in range(100):
os.kill(process.pid, signal.SIGURG)
os.kill(process.pid, signal.SIGUSR1)
self.assertEqual(f"received {_ + 1}", process.stdout.readline().strip())
output, _ = process.communicate(timeout=10)
self.assertEqual(f"received {round + 1}", process.stdout.readline().strip())
process.stdin.close()
process.wait(timeout=10)
output = process.stdout.read()
values = dict(line.split() for line in output.splitlines())
self.assertNotEqual(0, int(values["urg"]))
self.assertNotEqual(0, int(values["usr"]))
self.assertEqual(0, int(values["worker"]))
self.assertNotEqual(worker, int(values["urg"]))
self.assertNotEqual(worker, int(values["usr"]))
finally:
if process.poll() is None:
process.kill()
@@ -368,6 +587,8 @@ class ZramPreloadTest(unittest.TestCase):
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_inline_pageout_exceeds_async_timing_tolerance(self):
out = self.run_program(None, 256, 0, "timed-inline")
if out["inline"][0] <= 250:
self.skipTest("inline page-out finished under the 250 ms timing threshold on this machine")
self.assertGreater(out["inline"][0], 250)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
@@ -386,6 +607,73 @@ class ZramPreloadTest(unittest.TestCase):
out = self.run_program(None, 48, 0, "fork")
self.assertEqual([1], out["childack"])
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_trim_stops_at_its_budget_and_continues_where_it_stopped(self):
out = self.run_program(None, 32, 0, "trim")
self.assertTrue(7168 < out["first"][0] <= 8192, out)
self.assertTrue(7168 < out["second"][0] <= 8192, out)
self.assertGreater(out["swapped"][0], 15 * 1024)
self.assertGreater(out["rest"][0], 40 * 1024)
self.assertEqual([1], out["intact"])
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_trim_leaves_memory_that_came_straight_back(self):
out = self.run_program(None, 32, 0, "trim")
self.assertLess(out["hot"][0], 4 * 1024, out)
self.assertGreater(out["forced"][0], 28 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_requested_read_back_does_not_count_as_heat(self):
out = self.run_program(None, 32, 0, "trim")
self.assertTrue(28 * 1024 < out["again"][0] < 40 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_budgets_smaller_than_a_chunk_still_reach_all_of_it(self):
out = self.run_program(None, 32, 0, "trim-small")
self.assertLessEqual(out["largest"][0], 512)
self.assertGreater(out["small"][0], 52 * 1024)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_small_budgets_reach_the_end_of_a_thinly_used_chunk(self):
out = self.run_program(None, 8, 0, "trim-sparse")
self.assertEqual([16 * 1024], out["sparse"])
self.assertLess(out["kept"][0], 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_request_in_the_hold_file_wins_over_the_control_file(self):
out = self.run_program(None, 32, 0, "hold")
self.assertTrue(0 < out["empty"][0] <= 512, out)
self.assertGreater(out["held"][0], 40 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_process_without_a_worker_trims_in_small_steps(self):
if os.geteuid() == 0:
self.skipTest("the thread limit does not apply to root")
out = self.run_program(None, 48, 0, "trim-fork")
self.assertTrue(16 * 1024 < out["nothread_trim"][0] <= 32 * 1024, out)
self.assertGreater(out["worker_trim"][0], 64 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_single_threaded_process_trims_without_starting_a_thread(self):
out = self.run_program(None, 48, 0, "trim-fork")
self.assertTrue(16 * 1024 < out["inline_trim"][0] <= 32 * 1024, out)
self.assertGreater(out["worker_trim"][0], 64 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_process_that_sandboxed_itself_trims_without_starting_a_thread(self):
out = self.run_program(None, 48, 0, "sandboxed")
self.assertTrue(16 * 1024 < out["sandboxed_trim"][0] <= 32 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_a_thread_that_sandboxed_itself_trims_without_starting_a_thread(self):
out = self.run_program(None, 48, 0, "thread-sandboxed")
self.assertTrue(16 * 1024 < out["thread_sandboxed_trim"][0] <= 32 * 1024, out)
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
def test_the_worker_passes_a_filter_that_only_allows_thread_clones(self):
out = self.run_program(None, 48, 0, "filtered")
self.assertGreater(out["filtered_trim"][0], 40 * 1024, out)
def test_worker_acknowledges_back_to_back_requests(self):
out = self.run_program(None, 48, 0, "burst")
self.assertEqual([1], out["burstack"])
+5 -1
View File
@@ -25,7 +25,11 @@ struct dmabuf_buffer {
struct vkp_image *img;
void *ahb_state;
};
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE };
struct surface {
enum surface_role role;
struct surface *parent;
int sub_desync;
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
@@ -113,7 +117,7 @@ static void test_queue(int mixed, int client_gone) {
g_release_timer_fd = 123; g_refresh_ns = 100000;
drop_dmabuf(&s, 1); assert(s.releases_pending == 1 && !r.releases);
assert(last_timer.it_value.tv_sec || last_timer.it_value.tv_nsec);
if (mixed) { init_resource(&shm, NULL); release_buffer(&s, &shm, now_ns()); }
if (mixed) { init_resource(&shm, NULL); droiddeck_release_buffer(&s, &shm, 1, now_ns()); }
pending_releases_forget_surface(&s);
g_dev_state = -3;
fire_timer();
+124
View File
@@ -0,0 +1,124 @@
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include "vk_linear_dmabuf.h"
static void check_padded_rows(void) {
VkBufferImageCopy copy;
memset(&copy, 0xa5, sizeof(copy));
const VkDeviceSize need = vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 0, &copy);
assert(copy.bufferRowLength == 1600);
assert(copy.bufferRowLength != 1560);
assert(copy.bufferOffset == 0);
assert(copy.bufferImageHeight == 720);
assert(copy.imageSubresource.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT);
assert(copy.imageSubresource.mipLevel == 0);
assert(copy.imageSubresource.baseArrayLayer == 0);
assert(copy.imageSubresource.layerCount == 1);
assert(copy.imageOffset.x == 0 && copy.imageOffset.y == 0 && copy.imageOffset.z == 0);
assert(copy.imageExtent.width == 1560);
assert(copy.imageExtent.height == 720);
assert(copy.imageExtent.depth == 1);
assert(need == (VkDeviceSize)6400 * 719 + 1560 * 4);
}
static void check_offset_and_wide_texels(void) {
VkBufferImageCopy copy;
const VkDeviceSize need = vkp_linear_dmabuf_copy(VK_FORMAT_R16G16B16A16_SFLOAT, 1920, 1080, 15360, 4096, &copy);
assert(copy.bufferRowLength == 1920);
assert(copy.bufferOffset == 4096);
assert(need == 4096 + (VkDeviceSize)15360 * 1079 + 1920 * 8);
assert(vkp_linear_dmabuf_copy(VK_FORMAT_B8G8R8A8_UNORM, 1, 1, 64, 0, &copy) == 4);
assert(copy.bufferRowLength == 16);
}
static void check_rejected_layouts(void) {
VkBufferImageCopy copy;
assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6236, 0, &copy) == 0);
assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6402, 0, &copy) == 0);
assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 2, &copy) == 0);
assert(vkp_linear_dmabuf_copy(VK_FORMAT_R16G16B16A16_SFLOAT, 1560, 720, 6240, 0, &copy) == 0);
assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 0, 720, 6400, 0, &copy) == 0);
assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 0, 6400, 0, &copy) == 0);
assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 0, NULL) == 0);
}
static void check_path_choice(void) {
const uint64_t linear = 0;
const uint64_t qcom_compressed = 0x0500000000000001ULL;
assert(vkp_linear_dmabuf_through_buffer(0, linear, 0));
assert(!vkp_linear_dmabuf_through_buffer(1, linear, 0));
assert(!vkp_linear_dmabuf_through_buffer(1, qcom_compressed, 0));
assert(!vkp_linear_dmabuf_through_buffer(0, qcom_compressed, 0));
assert(!vkp_linear_dmabuf_through_buffer(0, linear, 1));
assert(!vkp_linear_dmabuf_through_buffer(1, linear, 1));
}
static void check_foreign_image(void) {
assert(vkp_linear_dmabuf_foreign_image(1, 0));
assert(!vkp_linear_dmabuf_foreign_image(1, 1));
assert(!vkp_linear_dmabuf_foreign_image(0, 0));
assert(!vkp_linear_dmabuf_foreign_image(0, 1));
}
static void check_padded_layer_targets(void) {
const VkFormat rgba = VK_FORMAT_R8G8B8A8_UNORM;
const uint64_t qcom_compressed = 0x0500000000000001ULL;
assert(vkp_padded_linear_target_needs_layout(0, 0, rgba, 720, 3072, 0));
assert(vkp_padded_linear_target_needs_layout(0, 0, rgba, 720, 2880, 64));
assert(!vkp_padded_linear_target_needs_layout(0, 0, rgba, 1280, 5120, 0));
assert(!vkp_padded_linear_target_needs_layout(1, 0, rgba, 720, 3072, 0));
assert(!vkp_padded_linear_target_needs_layout(0, qcom_compressed, rgba, 720, 3072, 0));
}
static void check_readback_order(void) {
assert(vkp_linear_dmabuf_readback_stage(1) & VK_PIPELINE_STAGE_TRANSFER_BIT);
assert(vkp_linear_dmabuf_readback_access(1) & VK_ACCESS_TRANSFER_WRITE_BIT);
assert(vkp_linear_dmabuf_readback_stage(0) == VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
assert(vkp_linear_dmabuf_readback_access(0) == 0);
}
static void check_ownership(void) {
const VkBuffer buffer = (VkBuffer)(uintptr_t)0x4321;
const uint32_t queue_family = 3;
const VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_READ_BIT, 1);
assert(acquire.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER);
assert(acquire.pNext == NULL);
assert(acquire.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
assert(acquire.dstQueueFamilyIndex == queue_family);
assert(acquire.srcAccessMask == 0);
assert(acquire.dstAccessMask == VK_ACCESS_TRANSFER_READ_BIT);
assert(acquire.buffer == buffer);
assert(acquire.offset == 0);
assert(acquire.size == VK_WHOLE_SIZE);
const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_READ_BIT, 0);
assert(release.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER);
assert(release.srcQueueFamilyIndex == queue_family);
assert(release.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
assert(release.srcAccessMask == VK_ACCESS_TRANSFER_READ_BIT);
assert(release.dstAccessMask == 0);
assert(release.buffer == buffer);
assert(release.size == VK_WHOLE_SIZE);
const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_WRITE_BIT, 1);
const VkBufferMemoryBarrier written = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_WRITE_BIT, 0);
assert(write.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
assert(write.dstAccessMask == VK_ACCESS_TRANSFER_WRITE_BIT);
assert(written.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT);
assert(written.srcAccessMask == VK_ACCESS_TRANSFER_WRITE_BIT);
}
int main(void) {
check_padded_rows();
check_offset_and_wide_texels();
check_rejected_layouts();
check_path_choice();
check_padded_layer_targets();
check_foreign_image();
check_readback_order();
check_ownership();
return 0;
}
+2 -1
View File
@@ -72,6 +72,7 @@ PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return NULL; }
void vkp_effects_bind_device(VkDevice d, VkPhysicalDevice p, const VkPhysicalDeviceMemoryProperties *m) {}
int vkp_effects_active(void) { return 0; }
int vkp_effects_upscaling(void) { return 0; }
int vkp_effects_sharpening(void) { return 0; }
int vkp_effects_postprocessing(void) { return 0; }
VkFilter vkp_effects_blit_filter(void) { return VK_FILTER_NEAREST; }
void vkp_effects_set_formats(VkFormat a, VkFormat b) {}
@@ -109,7 +110,7 @@ struct damage_list { int n; };
struct surface {
struct vkp_image *shm_img;
struct wl_resource *resource;
int buf_w, buf_h, buf_alpha, has_content;
int buf_w, buf_h, buf_alpha, has_content, black_fill;
/* Read by take_shm's game-frame detection; with no damage it stays off here. */
int src_set; float src[4];
struct damage_list damage_buf, damage_local;