Merge remote-tracking branch 'droiddeck/main' into HEAD

# Conflicts:
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-fex
#	tools/tests/test_droiddeck_fex.py
This commit is contained in:
maxjivi05 committed 2026-11-15 10:38:06 -05:00
commit b36e5425d7
227 files changed
+12088 -1987

No files matched your search

+490
View File
@@ -0,0 +1,490 @@
#include "mali_compat.h"
#include <assert.h>
#include <spirv/unified1/spirv.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *interface);
struct object { void *dispatch; };
static int instance_table, device_table;
static struct object mock_instance = {&instance_table};
static struct object mock_lacking = {&instance_table}, mock_capable = {&instance_table};
static struct object mock_device = {&device_table}, mock_command_buffer = {&device_table};
static VkBool32 driver_saw_dual_source;
static uint32_t *driver_code;
static size_t driver_code_count;
static VkPipelineColorBlendAttachmentState driver_attachments[4];
static uint32_t driver_attachment_count;
static VkColorBlendEquationEXT driver_equations[4];
static uint32_t driver_equation_count;
#define MAIN 1
#define VOID 2
#define FUNCTION 3
#define FLOAT 4
#define VEC4 5
#define OUTPUT_VEC4 6
#define COLOR 7
#define SECOND 8
#define ONE 9
#define ONES 10
#define OUTPUT_FLOAT 11
#define UINT 12
#define ZERO 13
#define LABEL 14
#define CHANNEL 15
#define BOUND 16
struct spirv { uint32_t w[256]; size_t n; };
static void op(struct spirv *s, SpvOp code, uint32_t count, const uint32_t *operands)
{
s->w[s->n++] = (count + 1) << 16 | code;
for (uint32_t i = 0; i < count; i++)
s->w[s->n++] = operands[i];
}
#define OP(s, code, ...) \
do { \
const uint32_t operands_[] = {__VA_ARGS__}; \
op(s, code, sizeof(operands_) / sizeof(operands_[0]), operands_); \
} while (0)
static void fragment_shader(struct spirv *s, uint32_t version, bool dual_source)
{
s->n = 0;
const uint32_t header[5] = {SpvMagicNumber, version, 0, BOUND, 0};
memcpy(s->w, header, sizeof(header));
s->n = 5;
OP(s, SpvOpCapability, SpvCapabilityShader);
OP(s, SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450);
OP(s, SpvOpEntryPoint, SpvExecutionModelFragment, MAIN, 0x6e69616d, 0, COLOR, SECOND);
OP(s, SpvOpExecutionMode, MAIN, SpvExecutionModeOriginUpperLeft);
OP(s, SpvOpDecorate, COLOR, SpvDecorationLocation, 0);
if (dual_source) {
OP(s, SpvOpDecorate, COLOR, SpvDecorationIndex, 0);
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 0);
OP(s, SpvOpDecorate, SECOND, SpvDecorationIndex, 1);
} else {
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 1);
}
OP(s, SpvOpTypeVoid, VOID);
OP(s, SpvOpTypeFunction, FUNCTION, VOID);
OP(s, SpvOpTypeFloat, FLOAT, 32);
OP(s, SpvOpTypeVector, VEC4, FLOAT, 4);
OP(s, SpvOpTypePointer, OUTPUT_VEC4, SpvStorageClassOutput, VEC4);
OP(s, SpvOpTypePointer, OUTPUT_FLOAT, SpvStorageClassOutput, FLOAT);
OP(s, SpvOpTypeInt, UINT, 32, 0);
OP(s, SpvOpConstant, FLOAT, ONE, 0x3f800000);
OP(s, SpvOpConstantComposite, VEC4, ONES, ONE, ONE, ONE, ONE);
OP(s, SpvOpConstant, UINT, ZERO, 0);
OP(s, SpvOpVariable, OUTPUT_VEC4, COLOR, SpvStorageClassOutput);
OP(s, SpvOpVariable, OUTPUT_VEC4, SECOND, SpvStorageClassOutput);
OP(s, SpvOpFunction, VOID, MAIN, SpvFunctionControlMaskNone, FUNCTION);
OP(s, SpvOpLabel, LABEL);
OP(s, SpvOpStore, COLOR, ONES);
OP(s, SpvOpStore, SECOND, ONES);
OP(s, SpvOpAccessChain, OUTPUT_FLOAT, CHANNEL, SECOND, ZERO);
OP(s, SpvOpStore, CHANNEL, ONE);
s->w[s->n++] = 1u << 16 | SpvOpReturn;
s->w[s->n++] = 1u << 16 | SpvOpFunctionEnd;
}
static const uint32_t *find(const uint32_t *w, size_t count, SpvOp code, uint32_t position, uint32_t value)
{
for (size_t i = 5; i < count; i += w[i] >> 16) {
if ((w[i] & 0xffff) == code && (w[i] >> 16) > position && w[i + position] == value)
return &w[i];
}
return NULL;
}
static uint32_t storage_of(const uint32_t *w, size_t count, uint32_t pointer_type)
{
const uint32_t *type = find(w, count, SpvOpTypePointer, 1, pointer_type);
assert(type);
return type[2];
}
static bool in_interface(const uint32_t *w, size_t count, uint32_t id)
{
const uint32_t *entry = find(w, count, SpvOpEntryPoint, 2, MAIN);
assert(entry);
for (uint32_t i = 5; i < entry[0] >> 16; i++) {
if (entry[i] == id)
return true;
}
return false;
}
static void save(const char *directory, const char *name, const uint32_t *words, size_t count)
{
if (!directory)
return;
char path[512];
snprintf(path, sizeof(path), "%s/%s", directory, name);
FILE *file = fopen(path, "wb");
assert(file);
assert(fwrite(words, sizeof(uint32_t), count, file) == count);
fclose(file);
}
static void check_stripped(const uint32_t *w, size_t count, bool second_listed)
{
assert(!spirv_uses_dual_source(w, count));
const uint32_t *second = find(w, count, SpvOpVariable, 2, SECOND);
const uint32_t *color = find(w, count, SpvOpVariable, 2, COLOR);
assert(second && second[3] == SpvStorageClassPrivate);
assert(storage_of(w, count, second[1]) == SpvStorageClassPrivate);
assert(color && color[3] == SpvStorageClassOutput && color[1] == OUTPUT_VEC4);
assert(!find(w, count, SpvOpDecorate, 1, SECOND));
const uint32_t *location = find(w, count, SpvOpDecorate, 1, COLOR);
assert(location && location[2] == SpvDecorationLocation && location[3] == 0);
const uint32_t *channel = find(w, count, SpvOpAccessChain, 2, CHANNEL);
assert(channel && storage_of(w, count, channel[1]) == SpvStorageClassPrivate);
assert(storage_of(w, count, OUTPUT_FLOAT) == SpvStorageClassOutput);
assert(in_interface(w, count, COLOR));
assert(in_interface(w, count, SECOND) == second_listed);
}
static void test_spirv(const char *directory)
{
struct spirv dual, plain;
struct spirv_code out;
fragment_shader(&dual, 0x00010000, true);
save(directory, "dual-1.0.spv", dual.w, dual.n);
assert(spirv_uses_dual_source(dual.w, dual.n));
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
check_stripped(out.words, out.count, false);
save(directory, "stripped-1.0.spv", out.words, out.count);
free(out.words);
fragment_shader(&dual, 0x00010400, true);
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
check_stripped(out.words, out.count, true);
save(directory, "stripped-1.4.spv", out.words, out.count);
free(out.words);
fragment_shader(&plain, 0x00010000, false);
save(directory, "plain-1.0.spv", plain.w, plain.n);
assert(!spirv_uses_dual_source(plain.w, plain.n));
assert(spirv_strip_dual_source(plain.w, plain.n, &out));
assert(out.count == plain.n && !memcmp(out.words, plain.w, plain.n * sizeof(uint32_t)));
free(out.words);
uint32_t truncated[5] = {SpvMagicNumber, 0x00010000, 0, BOUND, 0};
assert(!spirv_uses_dual_source(truncated, 5));
assert(!spirv_strip_dual_source(truncated, 5, &out));
}
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance)
{
*instance = (VkInstance)&mock_instance;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_instance(VkInstance instance, const VkAllocationCallbacks *allocator) {}
static VkResult VKAPI_CALL mock_extensions(VkPhysicalDevice physical, const char *layer, uint32_t *count,
VkExtensionProperties *properties)
{
*count = 0;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features)
{
memset(features, 0, sizeof(*features));
features->dualSrcBlend = physical == (VkPhysicalDevice)&mock_capable;
}
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features)
{
mock_features(physical, &features->features);
}
static void VKAPI_CALL mock_properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *properties)
{
memset(properties, 0, sizeof(*properties));
strcpy(properties->deviceName, "mock");
properties->limits.maxFragmentDualSrcAttachments = physical == (VkPhysicalDevice)&mock_capable;
}
static void VKAPI_CALL mock_properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *properties)
{
mock_properties(physical, &properties->properties);
}
static void VKAPI_CALL mock_memory_properties(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties *properties)
{
memset(properties, 0, sizeof(*properties));
}
static void VKAPI_CALL mock_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out)
{
memset(&out->formatProperties, 0, sizeof(out->formatProperties));
}
static VkResult VKAPI_CALL mock_image_format_properties2(VkPhysicalDevice physical,
const VkPhysicalDeviceImageFormatInfo2 *info,
VkImageFormatProperties2 *properties)
{
return VK_ERROR_FORMAT_NOT_SUPPORTED;
}
static VkResult VKAPI_CALL mock_create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
const VkAllocationCallbacks *allocator, VkDevice *device)
{
driver_saw_dual_source = info->pEnabledFeatures && info->pEnabledFeatures->dualSrcBlend;
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext) {
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
((const VkPhysicalDeviceFeatures2 *)p)->features.dualSrcBlend)
driver_saw_dual_source = VK_TRUE;
}
VkPhysicalDeviceFeatures supported;
mock_features(physical, &supported);
if (driver_saw_dual_source && !supported.dualSrcBlend)
return VK_ERROR_FEATURE_NOT_PRESENT;
*device = (VkDevice)&mock_device;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {}
static void capture_code(const uint32_t *words, size_t size)
{
free(driver_code);
driver_code_count = size / sizeof(uint32_t);
driver_code = malloc(size);
memcpy(driver_code, words, size);
}
static VkResult VKAPI_CALL mock_create_shader_module(VkDevice device, const VkShaderModuleCreateInfo *info,
const VkAllocationCallbacks *allocator, VkShaderModule *module)
{
capture_code(info->pCode, info->codeSize);
*module = (VkShaderModule)0x1000;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_destroy_shader_module(VkDevice device, VkShaderModule module,
const VkAllocationCallbacks *allocator) {}
static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPipelineCache cache, uint32_t count,
const VkGraphicsPipelineCreateInfo *infos,
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
{
const VkPipelineColorBlendStateCreateInfo *blend = infos[0].pColorBlendState;
driver_attachment_count = blend->attachmentCount;
memcpy(driver_attachments, blend->pAttachments, blend->attachmentCount * sizeof(*driver_attachments));
const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext;
assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
capture_code(module->pCode, module->codeSize);
pipelines[0] = (VkPipeline)0x2000;
return VK_SUCCESS;
}
static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count,
const VkColorBlendEquationEXT *equations)
{
for (uint32_t i = 0; i < count; i++)
driver_equations[first + i] = equations[i];
if (first + count > driver_equation_count)
driver_equation_count = first + count;
}
#define MOCK(name, function) if (!strcmp(requested, name)) return (PFN_vkVoidFunction)function
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gipa(VkInstance instance, const char *requested)
{
MOCK("vkCreateInstance", mock_create_instance);
MOCK("vkDestroyInstance", mock_destroy_instance);
MOCK("vkCreateDevice", mock_create_device);
MOCK("vkEnumerateDeviceExtensionProperties", mock_extensions);
MOCK("vkGetPhysicalDeviceFeatures", mock_features);
MOCK("vkGetPhysicalDeviceFeatures2", mock_features2);
MOCK("vkGetPhysicalDeviceProperties", mock_properties);
MOCK("vkGetPhysicalDeviceProperties2", mock_properties2);
MOCK("vkGetPhysicalDeviceMemoryProperties", mock_memory_properties);
MOCK("vkGetPhysicalDeviceFormatProperties2", mock_format_properties2);
MOCK("vkGetPhysicalDeviceImageFormatProperties2", mock_image_format_properties2);
return NULL;
}
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const char *requested)
{
MOCK("vkDestroyDevice", mock_destroy_device);
MOCK("vkCreateShaderModule", mock_create_shader_module);
MOCK("vkDestroyShaderModule", mock_destroy_shader_module);
MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines);
MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation);
return NULL;
}
static PFN_vkGetInstanceProcAddr layer_gipa;
static PFN_vkGetDeviceProcAddr layer_gdpa;
static VkResult create_device(VkPhysicalDevice physical, const void *chain, const VkPhysicalDeviceFeatures *enabled,
VkDevice *device)
{
VkLayerDeviceLink link = {NULL, mock_gipa, mock_gdpa};
VkLayerDeviceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, chain, VK_LAYER_LINK_INFO, {&link}};
VkDeviceCreateInfo info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &loader, 0, 0, NULL, 0, NULL, 0, NULL, enabled};
PFN_vkCreateDevice create = (PFN_vkCreateDevice)layer_gipa((VkInstance)&mock_instance, "vkCreateDevice");
return create(physical, &info, NULL, device);
}
static void destroy_device(VkDevice device)
{
((PFN_vkDestroyDevice)layer_gdpa(device, "vkDestroyDevice"))(device, NULL);
}
static const VkPipelineColorBlendAttachmentState dual_attachment = {
VK_TRUE, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_OP_ADD, 0xf,
};
static const VkPipelineColorBlendAttachmentState plain_attachment = {
VK_TRUE, VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_OP_ADD, 0xf,
};
static void create_pipeline(VkDevice device, VkPipelineColorBlendAttachmentState *attachments,
VkShaderModuleCreateInfo *module)
{
VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, module, 0,
VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL};
VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, VK_LOGIC_OP_COPY, 2, attachments, {0}};
VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1,
.pStages = &stage, .pColorBlendState = &blend};
VkPipeline pipeline;
PFN_vkCreateGraphicsPipelines create =
(PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines");
assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS);
assert(stage.pNext == module && blend.pAttachments == attachments);
}
static bool same_attachment(const VkPipelineColorBlendAttachmentState *a, const VkPipelineColorBlendAttachmentState *b)
{
return !memcmp(a, b, sizeof(*a));
}
static void test_lacking_device(void)
{
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_lacking;
VkPhysicalDeviceFeatures features;
((PFN_vkGetPhysicalDeviceFeatures)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures"))(physical,
&features);
assert(features.dualSrcBlend);
VkPhysicalDeviceFeatures2 queried = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
((PFN_vkGetPhysicalDeviceFeatures2)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures2"))(physical,
&queried);
assert(queried.features.dualSrcBlend);
VkPhysicalDeviceProperties properties;
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
physical, &properties);
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
VkDevice device;
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS);
assert(!driver_saw_dual_source && enabled.dualSrcBlend);
destroy_device(device);
VkPhysicalDeviceFeatures2 chained = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, NULL, {.dualSrcBlend = VK_TRUE}};
assert(create_device(physical, &chained, NULL, &device) == VK_SUCCESS);
assert(!driver_saw_dual_source && chained.features.dualSrcBlend);
struct spirv dual;
fragment_shader(&dual, 0x00010300, true);
VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, dual.n * sizeof(uint32_t),
dual.w};
VkShaderModule handle;
assert(((PFN_vkCreateShaderModule)layer_gdpa(device, "vkCreateShaderModule"))(device, &module, NULL, &handle) ==
VK_SUCCESS);
check_stripped(driver_code, driver_code_count, false);
((PFN_vkDestroyShaderModule)layer_gdpa(device, "vkDestroyShaderModule"))(device, handle, NULL);
VkPipelineColorBlendAttachmentState attachments[2] = {dual_attachment, plain_attachment};
create_pipeline(device, attachments, &module);
check_stripped(driver_code, driver_code_count, false);
assert(module.pCode == dual.w && spirv_uses_dual_source(module.pCode, module.codeSize / sizeof(uint32_t)));
assert(driver_attachment_count == 2);
assert(driver_attachments[0].srcColorBlendFactor == VK_BLEND_FACTOR_ONE);
assert(driver_attachments[0].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_attachments[0].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
assert(driver_attachments[0].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_attachments[0].colorWriteMask == 0xf && driver_attachments[0].blendEnable);
assert(same_attachment(&driver_attachments[1], &plain_attachment));
assert(same_attachment(&attachments[0], &dual_attachment));
VkColorBlendEquationEXT equations[2] = {
{VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD},
{VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_SRC_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_FACTOR_CONSTANT_COLOR, VK_BLEND_OP_ADD},
};
VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer;
PFN_vkCmdSetColorBlendEquationEXT set_equation =
(PFN_vkCmdSetColorBlendEquationEXT)layer_gdpa(device, "vkCmdSetColorBlendEquationEXT");
assert(set_equation != (PFN_vkCmdSetColorBlendEquationEXT)mock_set_blend_equation);
set_equation(cmd, 1, 2, equations);
assert(driver_equation_count == 3);
assert(driver_equations[1].srcColorBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
assert(driver_equations[1].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
assert(driver_equations[1].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE);
assert(!memcmp(&driver_equations[2], &equations[1], sizeof(equations[1])));
assert(equations[0].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR);
destroy_device(device);
}
static void test_capable_device(void)
{
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_capable;
VkPhysicalDeviceProperties properties;
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
physical, &properties);
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
VkDevice device;
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS && driver_saw_dual_source);
assert(layer_gdpa(device, "vkCreateGraphicsPipelines") == (PFN_vkVoidFunction)mock_create_graphics_pipelines);
assert(layer_gdpa(device, "vkCreateShaderModule") == (PFN_vkVoidFunction)mock_create_shader_module);
assert(layer_gdpa(device, "vkCmdSetColorBlendEquationEXT") == (PFN_vkVoidFunction)mock_set_blend_equation);
destroy_device(device);
}
int main(int argc, char **argv)
{
test_spirv(argc > 1 ? argv[1] : NULL);
setenv("WINEPREFIX", "/nonexistent", 1);
unsetenv("DROIDDECK_MALI_COMPAT");
unsetenv("DROIDDECK_MALI_COMPAT_TRACE");
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
layer_gipa = negotiate.pfnGetInstanceProcAddr;
layer_gdpa = negotiate.pfnGetDeviceProcAddr;
VkLayerInstanceLink link = {NULL, mock_gipa, NULL};
VkLayerInstanceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, NULL, VK_LAYER_LINK_INFO, {&link}};
VkInstanceCreateInfo info = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &loader};
VkInstance instance;
PFN_vkCreateInstance create_instance = (PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance");
assert(create_instance(&info, NULL, &instance) == VK_SUCCESS);
test_lacking_device();
test_capable_device();
((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL);
free(driver_code);
printf("mali compat layer ok\n");
return 0;
}
+158
View File
@@ -0,0 +1,158 @@
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define BTN_LEFT 0x110
#define BTN_RIGHT 0x111
#define BTN_MIDDLE 0x112
#define INPUT_SPACE_W 1920
#define INPUT_SPACE_H 1080
#include "input_msg.inc"
#include "pen_state.inc"
enum { MOTION, PRESS, RELEASE };
struct event { int kind; uint32_t button; double x, y; int raw_valid; };
struct constraint { int is_lock; };
static struct constraint *g_active_constraint;
static struct surface *g_grab;
static int g_raw_valid;
static struct event events[16];
static int nevents, logs;
static uint32_t held;
static void scene_size(int *w, int *h) { *w = 3840; *h = 2160; }
static void vkp_output_size(int *w, int *h) { *w = 0; *h = 0; }
static int vkp_output_to_scene(double ox, double oy, double *x, double *y) {
(void)ox; (void)oy; (void)x; (void)y;
return 0;
}
static void pointer_event(double x, double y, uint32_t button, int pressed) {
assert(!button && !pressed && nevents < 16);
events[nevents++] = (struct event){MOTION, 0, x, y, g_raw_valid};
g_raw_valid = 1;
}
static void pointer_button(uint32_t button, int pressed) {
assert(button >= BTN_LEFT && button <= BTN_MIDDLE && nevents < 16);
uint32_t bit = 1u << (button - BTN_LEFT);
if (pressed) assert(!(held & bit));
else assert(held & bit);
held = pressed ? held | bit : held & ~bit;
events[nevents++] = (struct event){pressed ? PRESS : RELEASE, button, 0, 0, g_raw_valid};
}
static void pen_log_target(void) { logs++; }
#include "pen.inc"
static void pen(int flags, double x, double y) {
struct input_msg m = {13, flags, (int)(x * 256), (int)(y * 256), 0};
nevents = 0;
deliver_pen(&m);
}
static void motion(int i, double x, double y) {
assert(events[i].kind == MOTION && events[i].x == x && events[i].y == y);
}
static void button(int i, int kind, uint32_t code) {
assert(events[i].kind == kind && events[i].button == code);
}
static void expect(int count, uint32_t buttons) {
assert(nevents == count && held == buttons);
assert(g_pen.buttons == (int)buttons);
}
#define L (1u << 0)
#define R (1u << 1)
#define M (1u << 2)
int main(int argc, char **argv) {
assert(argc == 2);
const char *c = argv[1];
if (!strcmp(c, "hover")) {
pen(PEN_IN, 100.5, 50.25);
expect(1, 0); motion(0, 201, 100.5);
pen(PEN_IN, 2000, -4);
expect(1, 0); motion(0, 3839, 0);
assert(g_pen.in && logs == 2);
pen(0, 2000, -4);
expect(0, 0);
assert(!g_pen.in && logs == 2);
} else if (!strcmp(c, "tip")) {
pen(PEN_IN, 10, 10);
expect(1, 0);
pen(PEN_IN | PEN_TIP, 10, 10);
expect(2, L); motion(0, 20, 20); button(1, PRESS, BTN_LEFT);
pen(PEN_IN | PEN_TIP, 11, 10);
expect(1, L); motion(0, 22, 20);
pen(PEN_IN, 12, 10);
expect(2, 0); motion(0, 24, 20); button(1, RELEASE, BTN_LEFT);
pen(PEN_IN | PEN_TIP, 12, 10);
pen(PEN_IN, 12, 10);
pen(0, 12, 10);
expect(0, 0);
} else if (!strcmp(c, "buttons")) {
pen(PEN_IN | PEN_RIGHT, 10, 10);
expect(2, R); motion(0, 20, 20); button(1, PRESS, BTN_RIGHT);
pen(PEN_IN | PEN_RIGHT | PEN_MIDDLE, 10, 10);
expect(2, R | M); button(1, PRESS, BTN_MIDDLE);
pen(PEN_IN | PEN_MIDDLE | PEN_TIP, 11, 10);
expect(3, L | M); motion(0, 22, 20); button(1, PRESS, BTN_LEFT); button(2, RELEASE, BTN_RIGHT);
pen(PEN_IN | PEN_RIGHT, 12, 10);
expect(4, R); motion(0, 24, 20); button(1, PRESS, BTN_RIGHT);
button(2, RELEASE, BTN_LEFT); button(3, RELEASE, BTN_MIDDLE);
pen(PEN_IN, 12, 10);
expect(2, 0); button(1, RELEASE, BTN_RIGHT);
} else if (!strcmp(c, "out")) {
pen(PEN_IN | PEN_TIP | PEN_RIGHT | PEN_MIDDLE, 10, 10);
expect(4, L | R | M); motion(0, 20, 20);
button(1, PRESS, BTN_LEFT); button(2, PRESS, BTN_RIGHT); button(3, PRESS, BTN_MIDDLE);
pen(PEN_TIP | PEN_RIGHT | PEN_MIDDLE, 30, 30);
expect(3, 0);
button(0, RELEASE, BTN_LEFT); button(1, RELEASE, BTN_RIGHT); button(2, RELEASE, BTN_MIDDLE);
assert(!g_pen.in && !g_pen.buttons);
pen(0, 30, 30);
expect(0, 0);
} else if (!strcmp(c, "lock")) {
struct constraint lock = {1}, confine = {0};
g_active_constraint = &lock;
pen(PEN_IN, 10, 10);
expect(0, 0);
assert(g_pen.in && logs == 1);
pen(PEN_IN | PEN_TIP, 11, 10);
expect(1, L); button(0, PRESS, BTN_LEFT);
pen(PEN_IN | PEN_TIP, 40, 10);
expect(0, L);
pen(PEN_IN | PEN_RIGHT, 40, 10);
expect(2, R); button(0, PRESS, BTN_RIGHT); button(1, RELEASE, BTN_LEFT);
pen(0, 40, 10);
expect(1, 0); button(0, RELEASE, BTN_RIGHT);
g_active_constraint = &confine;
pen(PEN_IN, 10, 10);
expect(1, 0); motion(0, 20, 20);
} else if (!strcmp(c, "lost")) {
pen(PEN_IN | PEN_TIP, 10, 10);
expect(2, L); motion(0, 20, 20); button(1, PRESS, BTN_LEFT);
pen(0, 10, 10);
expect(1, 0); button(0, RELEASE, BTN_LEFT);
pen(PEN_IN | PEN_TIP | PEN_MIDDLE, 10, 10);
expect(3, L | M);
pen(PEN_IN, 50, 10);
expect(3, 0); motion(0, 100, 20); button(1, RELEASE, BTN_LEFT); button(2, RELEASE, BTN_MIDDLE);
} else {
assert(!strcmp(c, "raw"));
g_raw_valid = 1;
pen(PEN_IN, 10, 10);
assert(!events[0].raw_valid && g_raw_valid);
pen(PEN_IN, 11, 10);
assert(events[0].raw_valid);
pen(PEN_IN | PEN_TIP, 12, 10);
assert(events[0].raw_valid && events[1].raw_valid);
pen(0, 12, 10);
assert(!g_raw_valid);
g_raw_valid = 1;
pen(0, 12, 10);
assert(g_raw_valid);
}
puts("PASS");
}
+182
View File
@@ -0,0 +1,182 @@
#include <assert.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define BTN_LEFT 0x110
#define BTN_RIGHT 0x111
#define BTN_MIDDLE 0x112
#define INPUT_SPACE_W 1920
#define INPUT_SPACE_H 1080
#define WL_POINTER_FRAME_SINCE_VERSION 5
#define WL_POINTER_BUTTON_STATE_RELEASED 0
#define WL_POINTER_BUTTON_STATE_PRESSED 1
#include "input_msg.inc"
#include "pen_state.inc"
typedef int32_t wl_fixed_t;
struct wl_client { int id; };
struct wl_resource { struct wl_client *client; };
struct wl_display { int unused; };
struct surface { struct wl_resource *resource; int placed, x, y; };
struct seat_pointer { struct wl_resource *ptr, *focus; };
struct constraint { int is_lock; struct surface *surface; };
static struct wl_client client_a, client_b;
static struct wl_resource surface_a = {&client_a}, surface_b = {&client_b};
static struct wl_resource pointer_a = {&client_a}, pointer_b = {&client_b};
static struct surface a = {&surface_a, 1, 0, 0}, b = {&surface_b, 1, 1000, 0};
static struct seat_pointer g_ptrs[2] = {{&pointer_a, NULL}, {&pointer_b, NULL}};
static int g_nptrs = 2;
static struct wl_display *g_display;
static struct constraint *g_active_constraint;
static struct surface *g_desktop, *g_grab, *g_key_target, *g_ime_click;
static double g_ptr_x, g_ptr_y, g_raw_x, g_raw_y;
static int g_ptr_known, g_raw_valid;
static atomic_int g_cursor_composite;
enum { ENTER, LEAVE, PRESS, RELEASE };
struct event { int kind; struct wl_resource *pointer, *surface; uint32_t button; };
static struct event events[32];
static int nevents;
static void record(int kind, struct wl_resource *pointer, struct wl_resource *surface, uint32_t button) {
assert(nevents < 32);
events[nevents++] = (struct event){kind, pointer, surface, button};
}
static void scene_size(int *w, int *h) { *w = 2000; *h = 1000; }
static void vkp_output_size(int *w, int *h) { *w = 0; *h = 0; }
static int vkp_output_to_scene(double ox, double oy, double *x, double *y) {
(void)ox; (void)oy; (void)x; (void)y;
return 0;
}
static struct surface *toplevel_at(double x, double y) {
(void)y;
return x < 1000 ? &a : &b;
}
static void confine_clamp(struct constraint *k, double *x, double *y) { (void)k; (void)x; (void)y; }
static void schedule_render(void) {}
static void publish_query_state(void) {}
static void constraints_focus_entered(struct wl_resource *target, struct wl_client *client) {
(void)target; (void)client;
}
static void droiddeck_text_input_refocus(void) {}
static void pen_log_target(void) {}
static struct surface *dying;
static void wl_display_flush_clients(struct wl_display *display) {
(void)display;
if (!dying || !nevents || events[nevents - 1].kind != RELEASE) return;
if (g_grab == dying) g_grab = NULL;
if (g_pen.grab == dying) g_pen.grab = NULL;
dying = NULL;
}
static uint32_t now_ms(void) { return 0; }
static uint32_t wl_display_next_serial(struct wl_display *display) { (void)display; return 0; }
static int wl_resource_get_version(struct wl_resource *r) { (void)r; return 7; }
static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->client; }
static wl_fixed_t wl_fixed_from_double(double d) { return (wl_fixed_t)(d * 256); }
static int send_relative_motion(struct wl_client *client, double dx, double dy) {
(void)client; (void)dx; (void)dy;
return 0;
}
static void wl_pointer_send_enter(struct wl_resource *p, uint32_t serial, struct wl_resource *s,
wl_fixed_t x, wl_fixed_t y) {
(void)serial; (void)x; (void)y;
record(ENTER, p, s, 0);
}
static void wl_pointer_send_leave(struct wl_resource *p, uint32_t serial, struct wl_resource *s) {
(void)serial;
record(LEAVE, p, s, 0);
}
static void wl_pointer_send_motion(struct wl_resource *p, uint32_t t, wl_fixed_t x, wl_fixed_t y) {
(void)p; (void)t; (void)x; (void)y;
}
static void wl_pointer_send_frame(struct wl_resource *p) { (void)p; }
static void wl_pointer_send_button(struct wl_resource *p, uint32_t serial, uint32_t t, uint32_t button,
uint32_t state) {
(void)serial; (void)t;
record(state == WL_POINTER_BUTTON_STATE_PRESSED ? PRESS : RELEASE, p, NULL, button);
}
#include "pointer.inc"
#include "pen.inc"
static void pen(int flags, double x) {
struct input_msg m = {13, flags, (int)(x * INPUT_SPACE_W / 2000 * 256), 100 * 256, 0};
nevents = 0;
deliver_pen(&m);
}
static void focus(int i, struct wl_resource *pointer, struct wl_resource *surface) {
assert(i < nevents && events[i].kind == ENTER && events[i].pointer == pointer && events[i].surface == surface);
}
static void left(int i, struct wl_resource *pointer, struct wl_resource *surface) {
assert(i < nevents && events[i].kind == LEAVE && events[i].pointer == pointer && events[i].surface == surface);
}
static void button(int i, int kind, uint32_t code) {
assert(i < nevents && events[i].kind == kind && events[i].pointer == &pointer_a && events[i].button == code);
}
static void hover_away(void) {
assert(!g_grab);
pen(PEN_IN, 1500);
assert(nevents == 2);
left(0, &pointer_a, &surface_a); focus(1, &pointer_b, &surface_b);
}
int main(int argc, char **argv) {
assert(argc == 2);
const char *c = argv[1];
pen(PEN_IN, 500);
assert(nevents == 1);
focus(0, &pointer_a, &surface_a);
pen(PEN_IN | PEN_TIP, 500);
assert(nevents == 1 && g_grab == &a);
button(0, PRESS, BTN_LEFT);
if (!strcmp(c, "side")) {
pen(PEN_IN | PEN_TIP | PEN_RIGHT, 600);
assert(nevents == 1 && g_grab == &a);
button(0, PRESS, BTN_RIGHT);
pen(PEN_IN | PEN_TIP, 700);
assert(nevents == 1 && g_grab == &a);
button(0, RELEASE, BTN_RIGHT);
pen(PEN_IN | PEN_TIP, 1500);
assert(nevents == 0 && g_grab == &a);
pen(PEN_IN, 1500);
assert(nevents == 1);
button(0, RELEASE, BTN_LEFT);
} else if (!strcmp(c, "swap")) {
pen(PEN_IN | PEN_RIGHT, 600);
assert(nevents == 2 && g_grab == &a);
button(0, PRESS, BTN_RIGHT); button(1, RELEASE, BTN_LEFT);
pen(PEN_IN | PEN_RIGHT, 1500);
assert(nevents == 0 && g_grab == &a);
pen(PEN_IN, 1500);
assert(nevents == 1);
button(0, RELEASE, BTN_RIGHT);
} else if (!strcmp(c, "mouse")) {
pointer_button(BTN_RIGHT, 1);
pointer_button(BTN_RIGHT, 0);
pen(PEN_IN | PEN_TIP, 1500);
assert(nevents == 0 && g_grab == &a);
pen(PEN_IN, 1500);
assert(nevents == 1);
button(0, RELEASE, BTN_LEFT);
} else {
assert(!strcmp(c, "gone"));
pen(PEN_IN | PEN_TIP | PEN_RIGHT, 600);
assert(nevents == 1 && g_grab == &a);
dying = &a;
pen(PEN_IN | PEN_TIP, 700);
assert(nevents == 1 && !dying && !g_grab && !g_pen.grab);
button(0, RELEASE, BTN_RIGHT);
pen(PEN_IN, 700);
assert(nevents == 1);
button(0, RELEASE, BTN_LEFT);
}
hover_away();
puts("PASS");
}
+41
View File
@@ -47,6 +47,47 @@ class LogTest(Temp):
self.assertRegex(log.read_text(), r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d \[\d+\] second\n$")
class StoreDebugEnvironmentTest(Temp):
def config(self, enabled):
config = self.tmp / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True, exist_ok=True)
config.write_text(json.dumps({"version": 1, "gameDebugLogs": enabled}))
def env(self, values=None):
debug_dir = self.tmp / "session"
debug_dir.mkdir(exist_ok=True)
base = {"HOME": str(self.tmp), "BL_DEBUG_DIR": str(debug_dir)}
base.update(values or {})
return base
def test_store_proton_command_gets_debug_defaults_when_enabled(self):
self.config(True)
with mock.patch.dict(os.environ, self.env(), clear=True):
result = BNET["proton_env"]()
self.assertEqual(result["PROTON_LOG"], "1")
self.assertEqual(result["DXVK_LOG_LEVEL"], "debug")
self.assertEqual(result["PROTON_LOG_DIR"], str(self.tmp / "session"))
self.assertIn("+seh", result["WINEDEBUG"])
def test_store_proton_command_keeps_debug_off_when_disabled(self):
self.config(False)
with mock.patch.dict(os.environ, self.env(), clear=True):
result = BNET["proton_env"]()
self.assertNotIn("PROTON_LOG", result)
self.assertNotIn("DXVK_LOG_LEVEL", result)
def test_store_proton_command_keeps_user_debug_values(self):
self.config(True)
values = {"PROTON_LOG": "0", "DXVK_LOG_LEVEL": "none", "WINEDEBUG": "-all", "PROTON_LOG_DIR": "/custom"}
with mock.patch.dict(os.environ, self.env(values), clear=True):
result = BNET["proton_env"]()
self.assertEqual(result["PROTON_LOG"], "1")
self.assertEqual(result["DXVK_LOG_LEVEL"], "debug")
self.assertEqual(result["PROTON_LOG_DIR"], str(self.tmp / "session"))
self.assertIn("+seh", result["WINEDEBUG"])
self.assertIn("-all", result["WINEDEBUG"])
class IdTest(unittest.TestCase):
def test_the_prefix_id_is_the_shortcut_id_the_app_names(self):
self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000)
+97
View File
@@ -0,0 +1,97 @@
import pathlib
import subprocess
import tempfile
import unittest
class DirectAudioWatchdogTest(unittest.TestCase):
def test_recovery_threshold_callback_race_and_forced_exit(self):
source = pathlib.Path('tools/directaudio/sink/module-directaudio-native-sink.c').read_text()
watchdog = source[source.index('static void watchdog('):source.index('static void close_output(')]
callback = source[source.index('static void record_callback('):
source.index('static aaudio_data_callback_result_t out_cb(')]
constants = '\n'.join(line for line in source.splitlines()
if line.startswith(('#define DA_FREEZE_GAP_NS ', '#define DA_CB_STALL_NS ',
'#define DA_HOST_RESTART_STALLS ')))
harness = r'''
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
typedef void AAudioStream;
struct userdata {
bool watchdog_on;
AAudioStream *aq;
uint64_t wd_last_tick_ns, last_cb_ns;
unsigned int cb_count, wd_last_cb;
uint64_t stall_state;
};
static uint64_t clock_ns = 10000000000ull;
static unsigned int reopens;
static bool callback_race;
static struct userdata *current;
static uint64_t now_ns(void) { return clock_ns; }
static void request_reopen(struct userdata *u, const char *why) { reopens++; }
#define pa_log(...) ((void)0)
CALLBACK
static bool exchange(uint64_t *value, uint64_t *expected, uint64_t next,
int weak, int success, int failure) {
if (callback_race) {
struct userdata *u = current;
record_callback(u);
__atomic_add_fetch(&u->cb_count, 1, __ATOMIC_SEQ_CST);
}
return __atomic_compare_exchange_n(value, expected, next, weak, success, failure);
}
#define __atomic_compare_exchange_n exchange
WATCHDOG
static void cleanup(void) { _exit(99); }
static void tick(struct userdata *u) {
clock_ns += 1000000000ull;
watchdog(u);
}
int main(int argc, char **argv) {
struct userdata state = {.watchdog_on = true, .aq = (void *)1};
struct userdata *u = &state;
current = u;
watchdog(u);
if (argc > 1 && strcmp(argv[1], "zero") == 0) {
callback_race = true;
tick(u);
assert(reopens == 0 && (uint32_t) u->stall_state == 0);
return 0;
}
tick(u);
assert(reopens == 1 && (uint32_t) u->stall_state == 1);
tick(u);
assert(reopens == 2 && (uint32_t) u->stall_state == 2);
if (argc > 1 && strcmp(argv[1], "exit") == 0) {
atexit(cleanup);
tick(u);
return 42;
}
callback_race = true;
tick(u);
assert(reopens == 2 && (uint32_t) u->stall_state == 0);
callback_race = false;
tick(u);
assert(reopens == 2 && (uint32_t) u->stall_state == 0);
tick(u);
assert(reopens == 3 && (uint32_t) u->stall_state == 1);
u->watchdog_on = false;
tick(u);
assert(reopens == 3 && (uint32_t) u->stall_state == 1);
return 0;
}
'''.replace('CALLBACK', callback).replace('WATCHDOG', watchdog)
with tempfile.TemporaryDirectory() as folder:
path = pathlib.Path(folder)
(path / 'watchdog.c').write_text(constants + '\n' + harness)
subprocess.run(['cc', '-std=c11', '-Werror', str(path / 'watchdog.c'),
'-o', str(path / 'watchdog')], check=True, capture_output=True)
subprocess.run([str(path / 'watchdog')], check=True, timeout=5)
subprocess.run([str(path / 'watchdog'), 'zero'], check=True, timeout=5)
result = subprocess.run([str(path / 'watchdog'), 'exit'], timeout=5)
self.assertEqual(1, result.returncode)
+15 -4
View File
@@ -887,17 +887,28 @@ class BrokerTest(EpicTestCase):
folder.mkdir()
(folder / ".droiddeck-store.json").write_text(json.dumps({"store": "epic", "id": "Fig", "args": ["-x"]}))
(folder / ".droiddeck-launch.bat").write_text('if exist "%~dp0.droiddeck-epic-args" goto client\r\n')
debug_dir = self.tmp / "session"
debug_dir.mkdir()
config = self.home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"version": 1, "gameDebugLogs": True}))
calls = []
def popen(command, env=None, cwd=None, start_new_session=False):
calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), start_new_session))
calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), env.get("BL_DEBUG_DIR"),
env.get("PROTON_LOG"), env.get("WINEDEBUG"), start_new_session))
return mock.Mock(wait=mock.Mock(return_value=7))
running = []
with mock.patch.object(subprocess, "Popen", popen):
code = G["run_game"]({"exe": str(folder / "Fig.exe"), "args": ["-epicapp=Fig"]}, {"PATH": "/usr/bin"}, running)
with mock.patch.dict(os.environ, {"HOME": str(self.home), "BL_DEBUG_DIR": str(debug_dir),
"PROTON_LOG": "0", "WINEDEBUG": "-all"}), \
mock.patch.object(subprocess, "Popen", popen):
code = G["run_game"]({"exe": str(folder / "Fig.exe"), "args": ["-epicapp=Fig"]},
{"PATH": "/usr/bin", "BL_DEBUG_DIR": str(debug_dir)}, running)
self.assertEqual(7, code)
self.assertEqual(([G["PROTON_RUN"], str(folder / ".droiddeck-launch.bat")], "1", True), calls[0])
self.assertEqual(([G["PROTON_RUN"], str(folder / ".droiddeck-launch.bat")], "1", str(debug_dir), "1",
mock.ANY, True), calls[0])
self.assertIn("+seh", calls[0][4])
self.assertEqual([], running)
self.assertEqual(b"-epicapp=Fig -x\r\n", (folder / ".droiddeck-epic-args").read_bytes())
+69 -4
View File
@@ -5,6 +5,7 @@ import json
import os
import runpy
import shutil
import stat
import struct
import subprocess
import sys
@@ -473,7 +474,6 @@ class PrepareTest(FexTestCase):
for name in names:
library = root / "lib" / arch / name
expected = sniper if name == "libwayland-cursor.so.0" else provider
self.assertEqual(library.resolve(), (expected / "files/lib" / arch / name).resolve())
self.assertEqual(library.read_bytes(), b"old ABI" if expected == sniper else b"new ABI " + name.encode())
self.assertEqual((root / "lib" / arch / "libffi.so.7").read_bytes(), b"old ffi")
self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"old ABI")
@@ -591,8 +591,7 @@ class PrepareTest(FexTestCase):
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
for name in names:
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).resolve(),
provider / "files/lib" / arch / name)
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new")
self.assertEqual((sniper / "files/lib" / arch / name).read_bytes(), b"base")
@unittest.skipUnless(shutil.which("cc"), "C compiler unavailable")
@@ -644,7 +643,7 @@ class PrepareTest(FexTestCase):
self.graphics(sniper)
base = self.write(sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0", b"base wayland")
fex, _ = self.quiet(FEX["prepare"])
self.assertEqual((Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-client.so.0").resolve(), base)
self.assertEqual((Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"base wayland")
def test_provider_symlinks_require_existing_targets_on_both_architectures(self):
self.fex_tool()
@@ -778,6 +777,72 @@ class PrepareTest(FexTestCase):
self.assertIn("built the x86 runtime", said)
self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
def test_the_built_x86_runtime_holds_nothing_that_leaves_it(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
os.chmod(sniper / "files/share/ca", 0o750)
self.quiet(FEX["prepare"])
root = (self.home / ".local/share/droiddeck-fex/rootfs").resolve()
self.assertEqual(stat.S_IMODE(os.stat(root / "share/ca").st_mode), 0o750)
entries = 0
for directory, dirs, files in os.walk(root):
for name in dirs + files:
path = Path(directory) / name
entries += 1
if path.is_symlink():
self.assertFalse(os.path.isabs(os.readlink(path)), path)
self.assertTrue(path.resolve().is_relative_to(root), path)
self.assertGreater(entries, 10)
self.assertEqual((root / "bin/[").read_bytes(), b"blob")
self.assertEqual((root / "share/ca/real.crt").read_bytes(), b"cert")
self.assertFalse(os.path.lexists(root / "ab"))
def test_guest_writes_do_not_mutate_runtime_blob_files(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
self.quiet(FEX["prepare"])
root = self.home / ".local/share/droiddeck-fex/rootfs"
marker = root / ".droiddeck-fex"
stamp = marker.read_text()
marker.write_text("3\n" + stamp.partition("\n")[2])
source = sniper / "files/ab/cdef-1.bin"
guest = root / "bin/["
guest.unlink()
os.link(source, guest)
self.assertEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
self.assertNotEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
guest.write_bytes(b"guest mutation")
self.assertEqual(source.read_bytes(), b"blob")
self.assertEqual(guest.read_bytes(), b"guest mutation")
def test_a_rebuilt_x86_runtime_refreshes_the_steam_client_links_and_drops_read_only_trees(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
self.graphics(sniper)
base = sniper / "files"
(base / str(self.home).lstrip("/") / ".steam").mkdir(parents=True)
os.symlink(self.steam / "linuxarm64", base / str(self.home).lstrip("/") / ".steam/sdk64")
self.write(self.steam / "linuxarm64/steamclient.so", elf(183))
os.chmod(base / "share/ca", 0o500)
self.addCleanup(os.chmod, base / "share/ca", 0o700)
self.quiet(FEX["prepare"])
rootfs = self.home / ".local/share/droiddeck-fex/rootfs"
os.chmod(rootfs / "share/ca", 0o000)
self.write(self.steam / "linux64/steamclient.so", elf(62))
self.write(self.steam / "linux32/steamclient.so", elf(3))
os.utime(self.steam / "steamapps/common/SteamLinuxRuntime_4/steamrt4_platform_4.0.20260928.262390/usr-mtree.txt.gz", ns=(1, 1))
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
guest = rootfs / str(self.home).lstrip("/") / ".steam"
self.assertEqual(os.readlink(guest / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(guest / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(sorted(os.listdir(rootfs.parent)), ["config", "lock", "rootfs", "status.json"])
def test_a_runtime_that_is_not_newer_is_left_out(self):
self.fex_tool()
sniper = self.runtime()
+28
View File
@@ -55,6 +55,19 @@ FAKE_ADB = textwrap.dedent('''\
print("Result: Bundle[{json=" + json.dumps(answers) + "}]")
elif args[:3] == ["shell", "dumpsys", "display"]:
print(config.get("dumpsys_display", ""))
elif args[:3] == ["shell", "dumpsys", "input"]:
print(config.get("dumpsys_input", ""))
elif args[:3] == ["shell", "uinput", "-"]:
entry["stdin"] = sys.stdin.read()
if "uinput_stdout" in config:
print(config["uinput_stdout"])
else:
for line in entry["stdin"].splitlines():
command = json.loads(line)
if command["command"] == "sync":
print(json.dumps({"reason": "sync", "id": command["id"], "syncToken": command["syncToken"]}))
elif args[:1] == ["shell"] and len(args) == 2 and "command -v uinput" in args[1]:
print(config.get("uinput_probe", ""))
elif args[:3] == ["shell", "dumpsys", "power"]:
print(" mWakefulness=Awake")
elif args[:3] == ["shell", "dumpsys", "SurfaceFlinger"] and "-dump" in args:
@@ -332,6 +345,21 @@ class DroiddeckctlTest(FakeAdbTest):
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p", "-d", "222"], shot["args"])
def test_screenshot_with_two_screens_takes_the_main_display(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
code, out = self.run_ctl("screenshot", str(self.dir / "shot.png"))
self.assertEqual(0, code)
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p", "-d", "111"], shot["args"])
def test_screenshot_with_one_screen_names_no_display(self):
one = DUMPSYS_DISPLAY.split(" Display 4:")[0]
self.configure({}, dumpsys_display=one)
code, out = self.run_ctl("screenshot", str(self.dir / "shot.png"))
self.assertEqual(0, code)
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
self.assertEqual(["exec-out", "screencap", "-p"], shot["args"])
def test_displays(self):
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
code, out = self.run_ctl("displays")
+255
View File
@@ -0,0 +1,255 @@
import json
import unittest
import unittest.mock
from test_droiddeckctl import FakeAdbTest, ctl
def samples(*argv):
return ctl.pen_samples(ctl.build_parser().parse_args(["input", "pen", *argv]))
def phases(gesture):
return [s["phase"] for s in gesture]
def dumpsys_input(rotation=0, size=(1140, 2616), active=1, frame=None):
other = ("Viewport INTERNAL: displayId=2, uniqueId=local:147, port=147, orientation=0, "
"logicalFrame=[0, 0, 2248, 2480], physicalFrame=[0, 0, 2248, 2480], deviceSize=[2248, 2480], isActive=[0]")
shown = (f"Viewport INTERNAL: displayId=0, uniqueId=local:148, port=148, orientation={rotation}, "
f"logicalFrame=[0, 0, {size[0]}, {size[1]}], physicalFrame=[{', '.join(map(str, frame or (0, 0, *size)))}], "
f"deviceSize=[{size[0]}, {size[1]}], isActive=[{active}]")
reader = (f"Input Reader State (Nums of device: 11):\n Device 6: touchpanel_pen\n {other}\n"
f" Configuration:\n Viewports:\n {other}\n {shown}\n OplusInputReader mMergeEnable = 0\n")
return reader + "\nINPUT MANAGER (dumpsys input)\n\n" + reader
def frames(commands):
found, frame = [], {}
for command in commands:
if command["command"] == "inject":
events = command["events"]
for code, value in zip(events[1::3], events[2::3]):
if code == "SYN_REPORT":
found.append(frame)
frame = {}
else:
frame[code] = value
return found
class PenSamplesTest(unittest.TestCase):
def test_a_tap_hovers_lands_lifts_and_leaves(self):
gesture = samples("tap", "0.5", "0.5", "--hold", "20")
self.assertEqual(["hover"] * 10 + ["down", "move", "up"] + ["hover"] * 10 + ["out"], phases(gesture))
times = [s["t"] for s in gesture]
self.assertEqual(sorted(times), times)
self.assertEqual([0, 8, 80, 100, 180, 180], [times[0], times[1], times[10], times[12], times[-2], times[-1]])
self.assertEqual({0.5}, {s["pressure"] for s in gesture[10:13]})
self.assertEqual({0}, {s["pressure"] for s in gesture[:10] + gesture[13:]})
self.assertEqual({(0.5, 0.5, None)}, {(s["x"], s["y"], s["button"]) for s in gesture})
def test_without_hover_the_pen_lands_and_leaves_at_once(self):
gesture = samples("tap", "0.5", "0.5", "--hover-ms", "0", "--hold", "0")
self.assertEqual([("down", 0), ("up", 0), ("out", 0)], [(s["phase"], s["t"]) for s in gesture])
def test_a_stroke_ramps_pressure_and_tilt(self):
gesture = samples("stroke", "0.25", "0.5", "0.75", "1", "--duration", "100", "--hover-ms", "20", "--rate", "100",
"--pressure", "0.25:0.75", "--tilt-x=-30:30", "--tilt-y", "10")
self.assertEqual(["hover", "hover", "down"] + ["move"] * 9 + ["up", "hover", "hover", "out"], phases(gesture))
contact = gesture[2:13]
self.assertEqual([(20, 0.25, 0.5, 0.25), (70, 0.5, 0.75, 0.5), (120, 0.75, 1, 0.75)],
[(s["t"], s["x"], s["y"], s["pressure"]) for s in (contact[0], contact[5], contact[-1])])
self.assertEqual((-30, 30), (gesture[0]["tilt_x"], gesture[-1]["tilt_x"]))
self.assertAlmostEqual(-30 + 60 * 20 / 140, contact[0]["tilt_x"])
self.assertEqual({10}, {s["tilt_y"] for s in gesture})
def test_hover_glides_to_the_target(self):
gesture = samples("hover", "0.25", "0.25", "--to", "0.75", "0.5", "--duration", "300", "--distance", "5")
self.assertEqual(["hover"] * 37 + ["out"], phases(gesture))
self.assertEqual([(0.25, 0.25), (0.75, 0.5), (0.75, 0.5)],
[(s["x"], s["y"]) for s in (gesture[0], gesture[-2], gesture[-1])])
self.assertEqual((300, {5}), (gesture[-1]["t"], {s["distance"] for s in gesture}))
def test_a_side_button_is_held_while_hovering(self):
gesture = samples("button", "secondary", "0.5", "0.5", "--hold", "40")
self.assertEqual([80, 88, 96, 104, 112], [s["t"] for s in gesture if s["button"] == "secondary"])
self.assertEqual(["hover"] * (len(gesture) - 1) + ["out"], phases(gesture))
self.assertEqual((200, None), (gesture[-1]["t"], gesture[-2]["button"]))
class PenUinputTest(FakeAdbTest):
def setUp(self):
super().setUp()
self.configure({}, dumpsys_input=dumpsys_input())
def pen(self, *argv):
return self.run_ctl("input", "pen", *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_a_stroke_draws_with_a_virtual_direct_pen(self):
code, out = self.pen("stroke", "0.25", "0.5", "0.75", "0.5", "--duration", "100", "--rate", "100",
"--hover-ms", "20", "--pressure", "0.2:1")
self.assertEqual(0, code)
self.assertEqual({"ok": True, "command": "input", "type": "pen", "samples": 16, "deviceSerial": "fake-1",
"viewport": {"display": 0, "rotation": 0, "size": [1140, 2616]}},
{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", "virtual", ["EV_KEY", "EV_ABS"], ["INPUT_PROP_DIRECT"]),
(register["command"], register["bus"], bits["UI_SET_EVBIT"], bits["UI_SET_PROPBIT"]))
self.assertEqual({"BTN_TOOL_PEN", "BTN_TOOL_RUBBER", "BTN_TOUCH", "BTN_STYLUS", "BTN_STYLUS2"},
set(bits["UI_SET_KEYBIT"]))
ranges = {a["code"]: (a["info"]["minimum"], a["info"]["maximum"]) for a in register["abs_info"]}
self.assertEqual({"ABS_X": (0, 1140 * 16 - 1), "ABS_Y": (0, 2616 * 16 - 1), "ABS_PRESSURE": (0, 4095),
"ABS_DISTANCE": (0, 255), "ABS_TILT_X": (-90, 90), "ABS_TILT_Y": (-90, 90)}, ranges)
self.assertEqual(set(bits["UI_SET_ABSBIT"]), set(ranges))
self.assertEqual({"id": 1, "command": "delay", "duration": 1000}, commands[1])
self.assertNotIn("updateTimeBase", [c["command"] for c in commands])
self.assertEqual(140, sum(c["duration"] for c in commands[2:-2] if c["command"] == "delay"))
self.assertEqual([{"id": 1, "command": "delay", "duration": 300},
{"id": 1, "command": "sync", "syncToken": ctl.UINPUT_SYNC}], commands[-2:])
drawn = frames(commands)
self.assertEqual({"BTN_TOOL_PEN": 1, "ABS_X": 4560, "ABS_Y": 20928, "ABS_PRESSURE": 0, "ABS_DISTANCE": 0,
"ABS_TILT_X": 0, "ABS_TILT_Y": 0}, drawn[0])
self.assertEqual([{"ABS_X": 4561}, {"BTN_TOUCH": 1, "ABS_X": 4560, "ABS_PRESSURE": 819}], drawn[1:3])
self.assertEqual([{"ABS_X": 13680, "ABS_PRESSURE": 4095}, {"BTN_TOUCH": 0, "ABS_PRESSURE": 0}, {"ABS_X": 13681},
{"ABS_X": 13680}, {"BTN_TOOL_PEN": 0}], drawn[-5:])
pressures = [f["ABS_PRESSURE"] for f in drawn[2:-4]]
self.assertEqual(sorted(pressures), pressures)
def test_positions_and_tilt_follow_the_rotation(self):
cases = {0: ([1000, 2000], 4000, 24000, 30, -10), 1: ([2000, 1000], 3999, 8000, 10, 30),
2: ([1000, 2000], 11999, 7999, -30, 10), 3: ([2000, 1000], 12000, 23999, -10, -30)}
for rotation, (size, x, y, tilt_x, tilt_y) in cases.items():
with self.subTest(rotation=rotation):
self.configure({}, dumpsys_input=dumpsys_input(rotation, size))
self.log.unlink(missing_ok=True)
code, out = self.pen("tap", "0.25", "0.75", "--tilt-x", "30", "--tilt-y=-10")
self.assertEqual((0, rotation), (code, out["viewport"]["rotation"]))
commands = self.script()
self.assertEqual([15999, 31999], [a["info"]["maximum"] for a in commands[0]["abs_info"][:2]])
first = frames(commands)[0]
self.assertEqual((x, y, tilt_x, tilt_y),
tuple(first[key] for key in ("ABS_X", "ABS_Y", "ABS_TILT_X", "ABS_TILT_Y")))
def test_the_mapping_inverts_aosps_input_coordinates_example(self):
self.assertEqual((0, 2, 0, 0), ctl.uinput_point(2 / 4, 2 / 3, 0, 0, 1, 3, 4, [0, 0, 4, 3]))
self.assertEqual((2, 3, 0, 0), ctl.uinput_point(1, 1, 0, 0, 0, 3, 4, [0, 0, 3, 4]))
self.assertEqual((0, 0, 0, 0), ctl.uinput_point(1, 1, 0, 0, 2, 3, 4, [0, 0, 3, 4]))
def test_positions_map_onto_the_physical_frame(self):
cases = {0: ((1000, 2000), (100, 250, 900, 1750), ("1", "0.05"), (14399, 5200)),
1: ((2000, 1000), (250, 100, 1750, 900), ("0.05", "1"), (1600, 5200))}
for rotation, (size, frame, position, first) in cases.items():
with self.subTest(rotation=rotation):
self.configure({}, dumpsys_input=dumpsys_input(rotation, size, frame=frame))
self.log.unlink(missing_ok=True)
self.assertEqual(0, self.pen("tap", *position)[0])
drawn = frames(self.script())
self.assertEqual(first, (drawn[0]["ABS_X"], drawn[0]["ABS_Y"]))
self.assertTrue(all(1600 <= f.get("ABS_X", 1600) < 14400 for f in drawn))
def test_eraser_and_buttons_use_the_stylus_keys(self):
for button, side in (("primary", "BTN_STYLUS"), ("secondary", "BTN_STYLUS2")):
with self.subTest(button=button):
self.log.unlink(missing_ok=True)
code, _ = self.pen("button", button, "0.5", "0.5", "--hold", "40", "--tool", "eraser", "--distance", "12")
self.assertEqual(0, code)
drawn = frames(self.script())
keys = [(key, value) for frame in drawn for key, value in frame.items() if key.startswith("BTN_")]
self.assertEqual([("BTN_TOOL_RUBBER", 1), (side, 1), (side, 0), ("BTN_TOOL_RUBBER", 0)], keys)
self.assertEqual(12, drawn[0]["ABS_DISTANCE"])
def test_a_still_pen_keeps_reporting_at_the_rate(self):
code, out = self.pen("hover", "1", "0.5", "--duration", "100", "--rate", "50")
self.assertEqual(0, code)
commands = self.script()
drawn = frames(commands)
self.assertEqual(out["samples"], len(drawn))
self.assertEqual([18239, 18238, 18239, 18238, 18239, 18238], [f["ABS_X"] for f in drawn[:-1]])
self.assertEqual([20, 20, 20, 20, 20, 300], [c["duration"] for c in commands[2:] if c["command"] == "delay"])
def test_a_contact_without_pressure_still_touches(self):
code, _ = self.pen("tap", "0.5", "0.5", "--pressure", "0", "--hover-ms", "0", "--hold", "0", "--distance", "5")
self.assertEqual(0, code)
drawn = frames(self.script())
self.assertEqual((1, 1, 1, 0),
tuple(drawn[0][key] for key in ("BTN_TOOL_PEN", "BTN_TOUCH", "ABS_PRESSURE", "ABS_DISTANCE")))
self.assertEqual([{"BTN_TOUCH": 0, "ABS_PRESSURE": 0, "ABS_DISTANCE": 5}, {"BTN_TOOL_PEN": 0}], drawn[1:])
def test_bad_values_are_refused(self):
cases = [
(("tap", "1.5", "0.5"), "Positions are fractions of the screen"),
(("hover", "0.5", "0.5", "--to", "nan", "0.5"), "Positions are fractions of the screen"),
(("stroke", "0", "0", "1", "1", "--pressure", "0.5:1.5"), "--pressure must be 0..1"),
(("tap", "0.5", "0.5", "--tilt-x=-91"), "--tilt-x and --tilt-y must be -90..90"),
(("tap", "0.5", "0.5", "--tilt-y", "120"), "--tilt-x and --tilt-y must be -90..90"),
(("hover", "0.5", "0.5", "--distance", "256"), "--distance must be 0..255"),
(("tap", "0.5", "0.5", "--rate", "1e9"), "--rate must be 1..1000 Hz"),
(("button", "primary", "0.5", "0.5", "--hold", "-5"), "--hold must not be negative"),
(("tap", "0.5", "0.5", "--hover-ms", "-1"), "--hover-ms must not be negative"),
(("stroke", "0", "0", "1", "1", "--duration", "40000"), "lasts 40160 ms, more than 30000"),
(("hover", "0.5", "0.5", "--duration", "1000000000"), "more than 30000"),
]
with unittest.mock.patch.object(ctl, "pen_times", side_effect=AssertionError):
for argv, message in cases:
with self.subTest(message=message):
code, out = self.pen(*argv)
self.assertEqual((2, "INVALID_INPUT"), (code, out["error"]["code"]))
self.assertIn(message, out["error"]["message"])
self.assertFalse(self.calls())
self.assertEqual(30_000, samples("tap", "1", "1", "--hover-ms", "14970")[-1]["t"])
def test_a_shell_without_uinput_is_unavailable(self):
for probe, message in (("no-uinput", "no `uinput` command"), ("no-dev-uinput", "cannot write /dev/uinput")):
with self.subTest(probe=probe):
self.configure({}, dumpsys_input=dumpsys_input(), uinput_probe=probe)
code, out = self.pen("tap", "0.5", "0.5")
self.assertEqual((3, "UINPUT_UNAVAILABLE"), (code, out["error"]["code"]))
self.assertIn(message, out["error"]["message"])
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]])
def test_a_missing_or_dark_display_is_refused(self):
for dump, message in (("Input Reader State (Nums of device: 0):\n", "no internal display viewport"),
(dumpsys_input(active=0), "Display 0 is off")):
with self.subTest(message=message):
self.configure({}, dumpsys_input=dump)
code, out = self.pen("tap", "0.5", "0.5")
self.assertEqual((3, "NO_VIEWPORT"), (code, out["error"]["code"]))
self.assertIn(message, out["error"]["message"])
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]])
def test_uinput_that_stops_early_fails(self):
self.configure({}, dumpsys_input=dumpsys_input(), uinput_stdout="")
code, out = self.pen("tap", "0.5", "0.5")
self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"]))
self.assertIn("adb logcat -s UINPUT", out["error"]["message"])
def test_the_viewport_android_maps_touchscreens_to(self):
self.assertEqual({"display": 0, "rotation": 0, "size": [1140, 2616], "frame": [0, 0, 1140, 2616], "active": True},
ctl.input_viewport(dumpsys_input()))
device = " Device 7: touchpanel\n Viewport INTERNAL: displayId=0, orientation=0, deviceSize=[1140, 2616]\n"
self.assertEqual(1, ctl.input_viewport(device + dumpsys_input(1, (2480, 2248)))["rotation"])
newest = (" Viewports:\n Viewport INTERNAL: displayId=3, uniqueId=local:1, port=<none>, orientation=3, "
"densityDpi=420 xDpi=409.432007, yDpi=411.891998, logicalFrame=[0, 0, 2400, 1080], "
"physicalFrame=[0, 0, 2400, 1080], deviceSize=[2400, 1080], isActive=[1]\n"
" Viewport INTERNAL: displayId=5, uniqueId=local:3, port=2, orientation=0, "
"deviceSize=[1080, 2400], isActive=[1]\n"
" Viewport EXTERNAL: displayId=0, uniqueId=local:2, port=1, orientation=0, "
"deviceSize=[1920, 1080], isActive=[1]\n")
self.assertEqual({"display": 3, "rotation": 3, "size": [2400, 1080], "frame": [0, 0, 2400, 1080], "active": True},
ctl.input_viewport(newest))
older = ("Viewport INTERNAL: displayId=0, orientation=2, logicalFrame=[0, 0, 720, 1280], "
"physicalFrame=[-3, 0, 717, 1280], deviceSize=[720, 1280]")
self.assertEqual({"display": 0, "rotation": 2, "size": [720, 1280], "frame": [-3, 0, 717, 1280], "active": True},
ctl.input_viewport(older))
if __name__ == "__main__":
unittest.main()
+28 -18
View File
@@ -1069,26 +1069,36 @@ class LauncherTest(SyncTestCase):
dist = self.dist_of(pack["id"], tool)
game_env = runpy.run_path(str(BIN / "droiddeck-game-env"))
command = [str(tool / "proton"), "waitforexitandrun", "game.exe"]
env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="1", WINEESYNC="1")
calls = []
cases = (
({}, {"WINEDLLOVERRIDES": "tabtip.exe=d"}),
({"WINEDLLOVERRIDES": "dxgi=n"}, {"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=d"}),
({"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=b"}, {"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=b"}),
({"SteamDeck": "1"}, {"SteamDeck": "1"}),
)
for inherited, expected in cases:
with self.subTest(inherited=inherited):
env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="1", WINEESYNC="1", **inherited)
calls = []
def execvpe(path, args, environment):
calls.append((path, list(args), dict(environment)))
if len(calls) == 1:
raise PermissionError("denied")
raise SystemExit(0)
def execvpe(path, args, environment):
calls.append((path, list(args), dict(environment)))
if len(calls) == 1:
raise PermissionError("denied")
raise SystemExit(0)
with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(sys, "argv", ["droiddeck-game-env"] + command), \
mock.patch("os.execvpe", execvpe), contextlib.redirect_stderr(io.StringIO()) as said:
with self.assertRaises(SystemExit):
game_env["main"]()
self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]),
(str(tool / "proton"), command)])
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"]))
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1",
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1"))
self.assertIn("could not start (", said.getvalue())
with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(sys, "argv", ["droiddeck-game-env"] + command), \
mock.patch("os.execvpe", execvpe), contextlib.redirect_stderr(io.StringIO()) as said:
with self.assertRaises(SystemExit):
game_env["main"]()
self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]),
(str(tool / "proton"), command)])
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"]))
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1",
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1", **expected))
self.assertEqual(calls[0][2].get("WINEDLLOVERRIDES"), expected.get("WINEDLLOVERRIDES"))
self.assertEqual(calls[0][2].get("SteamDeck"), expected.get("SteamDeck"))
self.assertIn("could not start (", said.getvalue())
def test_generated_launchers_run_the_dist_proton(self):
root = self.store()
+189
View File
@@ -1,3 +1,5 @@
import fcntl
import mmap
import os
from pathlib import Path
import shutil
@@ -5,6 +7,8 @@ import struct
import subprocess
import sys
import tempfile
import threading
import time
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
@@ -14,6 +18,14 @@ HEADER = 64
EVENT = 24
CAPACITY = 4096
DESCRIPTION = 1824
RING_SIZE = HEADER + CAPACITY * EVENT
DECK_IMU = 64
TRITON_BLOCK = 256
TRITON_MAGIC = 0x4E525454
TOUCH_MAGIC = 0x31484354
TOUCH_RING_SIZE = 256
PAD_TYPE_DECK = 0
PAD_TYPE_STEAM = 1
READER = r"""
#include <fcntl.h>
#include <linux/input.h>
@@ -215,6 +227,72 @@ int main(int argc, char **argv)
return 0;
}
"""
HIDRAW_PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <linux/hidraw.h>
#include <poll.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd = open(argv[1], O_RDONLY | O_NONBLOCK);
if (fd < 0) {
puts(errno == ENOENT ? "refused" : "failed");
return 0;
}
struct hidraw_devinfo info;
if (ioctl(fd, HIDIOCGRAWINFO, &info) < 0)
return 1;
struct pollfd ready = {fd, POLLIN, 0};
unsigned char report[64];
if (poll(&ready, 1, 2000) != 1 || read(fd, report, sizeof(report)) <= 0)
return 2;
printf("%04hx:%04hx report %02x\n", info.vendor, info.product, report[0]);
return 0;
}
"""
FEATURE_PROBE = r"""
#include <fcntl.h>
#include <linux/hidraw.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int main(int argc, char **argv)
{
unsigned char id = (unsigned char)strtoul(argv[1], NULL, 0);
int fd = open("/dev/hidraw18", O_RDWR);
if (fd < 0)
return 1;
int count = argc > 2 ? atoi(argv[2]) : 200, wrong = 0;
for (int i = 0; i < count; i++) {
unsigned char report[64] = {id};
if (ioctl(fd, HIDIOCGFEATURE(sizeof(report)), report) < 0 || report[0] != id || report[1] != id)
wrong++;
}
printf("%d wrong\n", wrong);
return 0;
}
"""
IMU_MODE_PROBE = r"""
#include <fcntl.h>
#include <linux/hidraw.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int main(int argc, char **argv)
{
unsigned mode = (unsigned)strtoul(argv[1], NULL, 0);
int fd = open("/dev/hidraw16", O_RDWR);
if (fd < 0)
return 1;
unsigned char report[65] = {0x00, 0x87, 3, 48, mode & 0xff, mode >> 8};
return ioctl(fd, HIDIOCSFEATURE(sizeof(report)), report) < 0;
}
"""
OVERLAY_READ = r"""
#include <sys/uio.h>
#include <unistd.h>
@@ -348,6 +426,117 @@ class FakeinputRingTest(unittest.TestCase):
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, "JSIOCGNAME -1 EINVAL\n28de:11ff Microsoft X-Box 360 pad 0\n")
def pad_ring(self, pad_type, triton_connected=False):
hooks, ring = self.ring(virtual=False)
data = bytearray(ring.read_bytes()) + bytearray(DECK_IMU + TRITON_BLOCK)
struct.pack_into("<I", data, RING_SIZE + 44, 0x80000000 | pad_type)
struct.pack_into("<II", data, RING_SIZE + DECK_IMU, TRITON_MAGIC, 1 if triton_connected else 0)
ring.write_bytes(bytes(data))
env = dict(os.environ, FAKE_EVDEV_DIR=str(hooks), FAKE_EVDEV_DECK="1", FAKE_EVDEV_TRITON="1",
FAKE_EVDEV_MEMFD_PATHS="0=" + str(ring))
return ring, env
def as_process(self, binary, name):
named = self.tmp / name
shutil.copy(binary, named)
return str(named)
def assert_opened_by_steam_and_remote_play_only(self, device, expected, env):
library, probe = self.build("-m64", HIDRAW_PROBE, "hidraw-probe")
env = dict(env, LD_PRELOAD=str(library))
for name, want in (("steam", expected), ("streaming_client", expected), ("game", "refused\n")):
with self.subTest(name=name):
run = subprocess.run([self.as_process(probe, name), device], capture_output=True, text=True,
timeout=10, env=env)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, want)
def test_the_deck_pad_opens_in_steam_and_its_remote_play_client_only(self):
_, env = self.pad_ring(PAD_TYPE_DECK)
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw16", "28de:1205 report 01\n", env)
def test_the_steam_controller_pad_opens_in_steam_and_its_remote_play_client_only(self):
_, env = self.pad_ring(PAD_TYPE_STEAM)
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw19", "28de:1302 report 42\n", env)
def test_the_touch_controller_opens_in_steam_and_its_remote_play_client_only(self):
_, env = self.pad_ring(PAD_TYPE_DECK)
touch = self.tmp / "touchctl"
data = bytearray(TOUCH_RING_SIZE)
struct.pack_into("<I", data, 0, TOUCH_MAGIC)
struct.pack_into("<I", data, 56, 1)
touch.write_bytes(bytes(data))
env["FAKE_TOUCHCTL_RING"] = str(touch)
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw17", "0000:11fb report 00\n", env)
def ask_paired_controller(self, probes, locks_unavailable=False, held=False, count=200):
library, probe = self.build("-m64", FEATURE_PROBE, "feature-probe")
ring, env = self.pad_ring(PAD_TYPE_DECK, triton_connected=True)
env["LD_PRELOAD"] = str(library)
lock = Path(env["FAKE_EVDEV_DIR"]) / ".triton-feature.lock"
if locks_unavailable:
lock.mkdir()
holder = open(lock, "w") if held else None
if holder:
self.addCleanup(holder.close)
fcntl.flock(holder, fcntl.LOCK_EX)
block = RING_SIZE + DECK_IMU
stop = threading.Event()
def controller():
with open(ring, "r+b") as f, mmap.mmap(f.fileno(), 0) as shared:
served = 0
while not stop.is_set():
request = struct.unpack_from("<Q", shared, block + 168)[0]
if request == served:
time.sleep(0.0001)
continue
report_id = struct.unpack_from("<I", shared, block + 184)[0]
struct.pack_into("<i", shared, block + 188, 2)
struct.pack_into("<BB", shared, block + 192, report_id, report_id)
struct.pack_into("<Q", shared, block + 176, request)
served = request
thread = threading.Thread(target=controller)
thread.start()
try:
runs = [subprocess.Popen([self.as_process(probe, name), report_id, str(count)], stdout=subprocess.PIPE,
text=True, env=env)
for name, report_id in probes]
outputs = [run.communicate(timeout=60)[0] for run in runs]
finally:
stop.set()
thread.join()
self.assertEqual([run.returncode for run in runs], [0] * len(probes))
return outputs
def test_steam_and_its_remote_play_client_take_turns_with_the_paired_controllers_features(self):
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")))
self.assertEqual(outputs, ["0 wrong\n", "0 wrong\n"])
def test_without_the_lock_only_steam_asks_the_paired_controller(self):
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")), locks_unavailable=True)
self.assertEqual(outputs, ["0 wrong\n", "200 wrong\n"])
def test_a_stopped_lock_holder_does_not_stall_steam_or_its_remote_play_client(self):
started = time.monotonic()
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")), held=True, count=3)
self.assertEqual(outputs, ["3 wrong\n", "3 wrong\n"])
self.assertLess(time.monotonic() - started, 20)
def test_steam_turning_motion_off_leaves_it_on_for_its_remote_play_client(self):
library, probe = self.build("-m64", IMU_MODE_PROBE, "imu-mode-probe")
ring, env = self.pad_ring(PAD_TYPE_DECK)
env["LD_PRELOAD"] = str(library)
pids = {}
for name, mode in (("steam", "0x18"), ("streaming_client", "0x18"), ("steam", "0x00")):
run = subprocess.Popen([self.as_process(probe, name), mode], env=env)
self.assertEqual(run.wait(timeout=10), 0)
pids[name] = run.pid
data = ring.read_bytes()
self.assertEqual(struct.unpack_from("<I", data, RING_SIZE + 4)[0], 0x80000000)
self.assertEqual(struct.unpack_from("<II", data, RING_SIZE + 52), (0x80000018, pids["streaming_client"]))
if __name__ == "__main__":
unittest.main()
+145
View File
@@ -0,0 +1,145 @@
import os
from pathlib import Path
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
RING_MAGIC = 0x46494252
DESCRIPTION_MAGIC = 0x46495544
HEADER = 64
EVENT = 24
CAPACITY = 4096
DESCRIPTION = 1824
GAME = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <unistd.h>
static int rumble(int fd, unsigned short strong) {
struct ff_effect effect;
memset(&effect, 0, sizeof(effect));
effect.id = -1;
effect.type = FF_RUMBLE;
effect.u.rumble.strong_magnitude = strong;
effect.u.rumble.weak_magnitude = 20000;
if (ioctl(fd, EVIOCSFF, &effect) < 0) return -1;
struct input_event play;
memset(&play, 0, sizeof(play));
play.type = EV_FF;
play.code = effect.id;
play.value = 1;
if (write(fd, &play, sizeof(play)) != sizeof(play)) return -1;
return effect.id;
}
int main(int argc, char **argv) {
int fd = open("/dev/input/event16", O_RDWR | O_NONBLOCK);
if (fd < 0) return 1;
if (argv[1][0] == 'p') {
int other = open("/dev/input/event16", O_RDWR | O_NONBLOCK);
if (other < 0 || rumble(fd, 40000) < 0 || rumble(other, 30000) < 0) return 2;
close(fd);
return 0;
}
if (argv[1][0] == 'k') {
pid_t child = fork();
if (child == 0) {
if (rumble(fd, 40000) < 0) _exit(2);
close(fd);
_exit(0);
}
int status = 0;
waitpid(child, &status, 0);
return WEXITSTATUS(status);
}
struct ff_effect effect;
effect.id = rumble(fd, 40000);
if (effect.id < 0) return 2;
if (argv[1][0] == 'e') ioctl(fd, EVIOCRMFF, effect.id);
else if (argv[1][0] == 'c') close(fd);
else if (argv[1][0] == 'f') {
pid_t child = fork();
if (child == 0) {
close(fd);
_exit(0);
}
waitpid(child, NULL, 0);
}
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("g++") and shutil.which("gcc"), "needs Linux, gcc and g++")
class FakeinputRumbleStopTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = Path(tempfile.mkdtemp())
cls.addClassCleanup(shutil.rmtree, cls.tmp, True)
cls.library = cls.tmp / "libfakeinput.so"
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread", "-std=c++17",
"-static-libstdc++", "-static-libgcc", "-Wl,--exclude-libs,ALL", "-o", str(cls.library),
str(SOURCE), "-ldl"], check=True)
cls.game = cls.tmp / "game"
(cls.tmp / "game.c").write_text(GAME)
subprocess.run(["gcc", "-o", str(cls.game), str(cls.tmp / "game.c")], check=True)
cls.hooks = cls.tmp / "hooks"
cls.hooks.mkdir()
(cls.hooks / "event16").touch()
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 0, 0, 0)
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
(cls.hooks / ".uinput-event16").write_bytes(bytes(ring))
def packets(self, ending):
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.addCleanup(server.close)
try:
server.bind("\0droiddeck-rumble")
except OSError:
self.skipTest("the rumble socket name is taken on this machine")
server.listen(16)
server.settimeout(0.5)
env = dict(os.environ, LD_PRELOAD=str(self.library), FAKE_EVDEV_DIR=str(self.hooks), FAKE_EVDEV_VIBRATION="1")
run = subprocess.run([str(self.game), ending], env=env, capture_output=True, timeout=10)
self.assertEqual(run.returncode, 0, run.stderr)
got = []
while True:
try:
client, _ = server.accept()
except socket.timeout:
return got
with client:
got.append(struct.unpack("<4H", client.recv(8))[:3])
def test_closing_the_controller_stops_its_held_rumble(self):
self.assertEqual(self.packets("close")[-1], (0, 0, 0))
def test_erasing_the_playing_effect_stops_it(self):
self.assertEqual(self.packets("erase")[-1], (0, 0, 0))
def test_a_forked_child_closing_its_copy_leaves_the_parents_rumble(self):
self.assertEqual(self.packets("fork")[-1], (40000, 20000, 0xffff))
def test_a_child_that_plays_on_an_inherited_controller_stops_it_on_close(self):
self.assertEqual(self.packets("kid")[-1], (0, 0, 0))
def test_closing_an_older_handle_leaves_the_newer_rumble_on_the_slot(self):
self.assertEqual(self.packets("pair")[-1], (30000, 20000, 0xffff))
def test_a_held_effect_still_plays_until_then(self):
self.assertIn((40000, 20000, 0xffff), self.packets("keep"))
if __name__ == "__main__":
unittest.main()
+347 -6
View File
@@ -33,6 +33,94 @@ class SupergiantDotnetReporterTest(unittest.TestCase):
self.assertIsNone(MODULE["supergiant_dotnet_reporter"](game))
class DeathStrandingAllocatorTest(unittest.TestCase):
def make_exe(self, name="ds.exe", size=None, window=None, tail=None):
folder = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, folder, True)
path = os.path.join(folder, name)
with open(path, "wb") as game:
game.truncate(MODULE["DS_SIZE"] if size is None else size)
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
game.write(b"<" + (MODULE["DS_WINDOW"] if window is None else window) + (MODULE["DS_ORIGINAL"] if tail is None else tail) + b">")
return path
def read_tail(self, path):
with open(path, "rb") as game:
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
return game.read(len(MODULE["DS_WINDOW"]) + len(MODULE["DS_ORIGINAL"]) + 2)
def run_fix(self, path, app_id="1850570"):
errors = io.StringIO()
with mock.patch("sys.stderr", errors):
return MODULE["death_stranding_allocator"](app_id, path), errors.getvalue()
def test_window_and_patch_have_the_measured_shape(self):
self.assertEqual(41, len(MODULE["DS_WINDOW"]))
self.assertEqual(6, len(MODULE["DS_ORIGINAL"]))
self.assertEqual(6, len(MODULE["DS_FIXED"]))
self.assertEqual(0x38FE1B9, MODULE["DS_WINDOW_OFFSET"] + len(MODULE["DS_WINDOW"]))
def test_replaces_only_the_jump_in_the_original_build(self):
path = self.make_exe()
patched, message = self.run_fix(path)
self.assertTrue(patched)
self.assertIn("Death Stranding", message)
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
self.assertEqual(MODULE["DS_SIZE"], os.path.getsize(path))
def test_an_already_patched_game_is_left_alone(self):
path = self.make_exe(tail=MODULE["DS_FIXED"])
before = os.stat(path).st_mtime_ns
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, os.stat(path).st_mtime_ns)
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
def test_a_second_run_changes_nothing(self):
path = self.make_exe()
self.assertTrue(self.run_fix(path)[0])
after_first = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(after_first, self.read_tail(path))
def test_other_builds_of_the_game_are_not_touched(self):
for size, window in ((MODULE["DS_SIZE"] + 1, None), (None, bytes(len(MODULE["DS_WINDOW"])))):
path = self.make_exe(size=size, window=window)
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_an_unknown_instruction_at_the_patch_site_is_not_touched(self):
path = self.make_exe(tail=bytes.fromhex("0f85a6000000"))
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_other_executables_are_ignored(self):
path = self.make_exe(name="game.exe")
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path))
self.assertEqual(before, self.read_tail(path))
def test_other_games_are_not_touched_even_with_a_matching_file(self):
for app_id in ("440", "", None):
path = self.make_exe()
before = self.read_tail(path)
self.assertEqual((False, ""), self.run_fix(path, app_id))
self.assertEqual(before, self.read_tail(path))
def test_both_death_stranding_app_ids_are_patched(self):
for app_id in ("1850570", "1190460"):
self.assertTrue(self.run_fix(self.make_exe(), app_id)[0])
def test_the_file_name_check_ignores_case(self):
self.assertTrue(self.run_fix(self.make_exe(name="DS.EXE"))[0])
def test_a_missing_game_file_is_reported_without_raising(self):
patched, message = self.run_fix(os.path.join(tempfile.gettempdir(), "droiddeck-no-such-folder", "ds.exe"))
self.assertFalse(patched)
self.assertIn("not applied", message)
def mapping_of(text):
tokens = COMPAT["tokenize"](text)
return COMPAT["read_mapping"](tokens, COMPAT["mapping_block"](tokens))
@@ -723,6 +811,7 @@ class GameEnvironmentTest(unittest.TestCase):
"install_scripts_done": lambda scripts, env: False,
"scripts_digest": lambda scripts: None,
"win_components": lambda *args: seen_components.append(args[3]) or "",
"restore_compatible_system_dlls": lambda *args: [],
"repair_foreign_system_dlls": lambda *args: seen_repair.append(args[2]) or [],
"gl_vsync": lambda env: False,
"game_images": lambda env: None,
@@ -756,6 +845,61 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_repair])
self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_start])
def test_keyboard_helper_is_off_unless_steam_keyboard_or_the_user_wants_it(self):
cases = (
({}, "tabtip.exe=d"),
({"WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "tabtipx=d"}, "tabtipx=d;tabtip.exe=d"),
({"SteamDeck": "0"}, "tabtip.exe=d"),
({"SteamDeck": "1"}, None),
({"SteamDeck": "1", "WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n"),
({"WINEDLLOVERRIDES": "tabtip.exe=b"}, "tabtip.exe=b"),
({"WINEDLLOVERRIDES": "dxgi=n; TabTip.EXE=n,b"}, "dxgi=n; TabTip.EXE=n,b"),
({"WINEDLLOVERRIDES": "dxgi=n; TabTip=n,b"}, "dxgi=n; TabTip=n,b;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "d3d11 tabtip.exe"}, "d3d11 tabtip.exe;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "tabtip.exe;dxgi=n"}, "tabtip.exe;dxgi=n;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "d3d11,tabtip.exe=b"}, "d3d11,tabtip.exe=b"),
({"WINEDLLOVERRIDES": "d3d11 tabtip.exe=b"}, "d3d11 tabtip.exe=b"),
({"WINEDLLOVERRIDES": "d3d11\ttabtip.exe=b"}, "d3d11\ttabtip.exe=b"),
({"WINEDLLOVERRIDES": "d3d11\ttabtip=b"}, "d3d11\ttabtip=b;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "d3d11 dxgi=n"}, "d3d11 dxgi=n;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "*tabtip.exe=b"}, "*tabtip.exe=b"),
({"WINEDLLOVERRIDES": "TabTip.exe.DLL=b"}, "TabTip.exe.DLL=b"),
({"WINEDLLOVERRIDES": "d3d11,*tabtip.exe.dll=n"}, "d3d11,*tabtip.exe.dll=n"),
({"WINEDLLOVERRIDES": "*tabtip=b"}, "*tabtip=b;tabtip.exe=d"),
({"WINEDLLOVERRIDES": "tabtip.dll=b"}, "tabtip.dll=b;tabtip.exe=d"),
)
for before, overrides in cases:
with self.subTest(env=before):
env = dict(before)
note = MODULE["keyboard_helper_off"](env)
self.assertEqual(env.get("WINEDLLOVERRIDES"), overrides)
self.assertEqual(note is not None, overrides != before.get("WINEDLLOVERRIDES"))
def test_game_launch_turns_the_keyboard_helper_off_and_keeps_user_choices(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
probe = home / "probe"
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('WINEDLLOVERRIDES', 'unset'))\n")
probe.chmod(0o755)
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
cases = (
("waitforexitandrun", {}, "tabtip.exe=d"),
("waitforexitandrun", {"WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n;tabtip.exe=d"),
("waitforexitandrun", {"SteamDeck": "1"}, "unset"),
("waitforexitandrun", {"WINEDLLOVERRIDES": "tabtip.exe=b"}, "tabtip.exe=b"),
("run", {}, "unset"),
)
for verb, profile, expected in cases:
with self.subTest(verb=verb, profile=profile):
config.write_text(json.dumps({"version": 1, "games": {"42": profile}}))
env = {k: v for k, v in os.environ.items() if k not in ("SteamDeck", "WINEDLLOVERRIDES")}
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42")
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), verb],
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip().splitlines()[-1], expected)
def test_optional_xbox_loader_failure_keeps_stock_launch(self):
from unittest.mock import patch
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
@@ -1172,6 +1316,8 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d")
self.assertEqual(extra, ["--rendering-driver", "vulkan"])
self.assertEqual(MODULE["engine_fixes"](str(game / "Game.exe"), ["--rendering-driver", "opengl3"])[1], [])
(game / "data_game_windows_x86_64/Sentry.Godot.dll").touch()
self.assertNotIn("WINEDLLOVERRIDES", MODULE["engine_fixes"](str(game / "Game.exe"), [])[0])
script = Path(tmp) / "GDScript Game"
script.mkdir()
for name in ("Game.exe", "Game.pck", "libsentry.windows.release.x86_64.dll"):
@@ -1592,6 +1738,35 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(result["FEX_TSOENABLED"], "0")
self.assertEqual(result["WINEDLLOVERRIDES"], "dxgi=n;libsentry=d")
def test_game_dll_overrides_follow_droiddecks_own(self):
fixes = {"WINEDLLOVERRIDES": "msvcp100=n,b"}
config = {"version": 1, "shared": {}, "games": {"42": {"WINEDLLOVERRIDES": "windowscodecs,windowscodecsext=n"}}}
result = MODULE["apply_config"]({}, config, "42", fixes)
self.assertEqual(result["WINEDLLOVERRIDES"], "msvcp100=n,b;windowscodecs,windowscodecsext=n")
def test_game_dll_overrides_edge_cases(self):
fixes = {"WINEDLLOVERRIDES": "msvcp100=n,b"}
env = {"WINEDLLOVERRIDES": "dxgi=n"}
for game, shared, expected in (
({"WINEDLLOVERRIDES": "msvcp100=b"}, {}, "msvcp100=n,b;msvcp100=b"),
({"WINEDLLOVERRIDES": ""}, {}, "msvcp100=n,b"),
({"WINEDLLOVERRIDES": None}, {}, None),
({"WINEDLLOVERRIDES": "d3d9=n"}, {"WINEDLLOVERRIDES": "xinput1_3=n"}, "msvcp100=n,b;d3d9=n"),
({}, {}, "dxgi=n;msvcp100=n,b"),
({"WINEDLLOVERRIDES": "x" * 8179}, {}, "msvcp100=n,b;" + "x" * 8179),
):
with self.subTest(game=game, shared=shared):
config = {"version": 1, "shared": shared, "games": {"42": game, "43": {"WINEDLLOVERRIDES": "d3d11=n"}}}
result = MODULE["apply_config"](env, config, "42", fixes)
self.assertEqual(result.get("WINEDLLOVERRIDES"), expected)
self.assertEqual(MODULE["apply_config"](env, config, "43")["WINEDLLOVERRIDES"], "d3d11=n")
stderr = io.StringIO()
config = {"version": 1, "shared": {}, "games": {"42": {"WINEDLLOVERRIDES": "x" * 8192}}}
with mock.patch("sys.stderr", stderr):
result = MODULE["apply_config"](env, config, "42", fixes)
self.assertEqual(result["WINEDLLOVERRIDES"], "x" * 8192)
self.assertIn("too long", stderr.getvalue())
def test_invalid_configuration_is_atomic(self):
env = {"ORIGINAL": "unchanged"}
for entries in ({"A": "ok", "BAD=KEY": "x"}, {"A": "bad\0value"}, {"A": 1}):
@@ -2718,6 +2893,39 @@ def arm64ec_pe_image():
return bytes(image)
def program_image(machine, imports):
image = bytearray(0x400)
image[:2] = b"MZ"
image[60:64] = (64).to_bytes(4, "little")
image[64:68] = b"PE\0\0"
coff = 68
image[coff:coff + 2] = machine.to_bytes(2, "little")
image[coff + 2:coff + 4] = (1).to_bytes(2, "little")
image[coff + 16:coff + 18] = (240).to_bytes(2, "little")
optional = coff + 20
image[optional:optional + 2] = (0x20B).to_bytes(2, "little")
image[optional + 108:optional + 112] = (16).to_bytes(4, "little")
image[optional + 120:optional + 124] = (0x1000).to_bytes(4, "little")
image[optional + 124:optional + 128] = (20 * (len(imports) + 1)).to_bytes(4, "little")
section = optional + 240
image[section + 8:section + 12] = (0x200).to_bytes(4, "little")
image[section + 12:section + 16] = (0x1000).to_bytes(4, "little")
image[section + 16:section + 20] = (0x200).to_bytes(4, "little")
image[section + 20:section + 24] = (0x200).to_bytes(4, "little")
name = 20 * (len(imports) + 1)
for index, dll in enumerate(imports):
image[0x200 + index * 20 + 12:0x200 + index * 20 + 16] = (0x1000 + name).to_bytes(4, "little")
image[0x200 + name:0x200 + name + len(dll)] = dll.encode()
name += len(dll) + 1
return bytes(image)
def bytes_path(folder, data):
path = folder / "image.exe"
path.write_bytes(data)
return path
class ForeignSystemDllTest(unittest.TestCase):
def prefix(self, tmp, arm=True):
proton = Path(tmp) / "Proton"
@@ -2729,7 +2937,8 @@ class ForeignSystemDllTest(unittest.TestCase):
for libdir, machine in (("aarch64-windows", 0xAA64), ("i386-windows", 0x14C)):
(dist / libdir).mkdir(parents=True)
for name in ("ucrtbase.dll", "rpcrt4.dll"):
(dist / libdir / name).write_bytes(pe_image(machine))
(dist / libdir / name).write_bytes(program_image(machine, []))
(dist / "aarch64-windows/wineboot.exe").write_bytes(program_image(0xAA64, ["UCRTBASE.dll", "rpcrt4.dll"]))
windows = Path(tmp) / "compat/pfx/drive_c/windows"
for folder in ("system32", "syswow64"):
(windows / folder).mkdir(parents=True)
@@ -2769,16 +2978,148 @@ class ForeignSystemDllTest(unittest.TestCase):
self.assertFalse((system32 / "ucrtbase.dll").is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](system32 / "userlib.dll"))
def test_x64_visual_cpp_runtime_in_arm64_system32_is_kept(self):
def test_x64_dlls_proton_programs_do_not_import_are_kept_in_arm64_system32(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
for name in ("msvcp140.dll", "VCRUNTIME140.dll", "msvcp_win.dll"):
(builtins / name.lower()).write_bytes(pe_image(0xAA64))
(builtins / "explorer.exe").write_bytes(program_image(0xAA64, ["shell32.dll"]))
(builtins / "shell32.dll").write_bytes(program_image(0xAA64, ["msvcp_win.dll"]))
names = ("vulkan-1.dll", "msvcp140.dll", "VCRUNTIME140.dll", "concrt140.dll", "d3dcompiler_43.dll",
"winhttp.dll", "msvcp_win.dll")
for name in names:
(builtins / name.lower()).write_bytes(program_image(0xAA64, []))
(windows / "system32" / name).write_bytes(pe_image(0x8664))
self.assertEqual(["system32/msvcp_win.dll (machine 0x8664)"], self.run_repair(compat, proton))
self.assertFalse((windows / "system32/msvcp140.dll").is_symlink())
self.assertFalse((windows / "system32/VCRUNTIME140.dll").is_symlink())
for name in names[:-1]:
self.assertFalse((windows / "system32" / name).is_symlink())
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
def test_repaired_dll_proton_programs_do_not_import_gets_its_native_copy_back(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
for name in ("vulkan-1.dll", "ucrtbase.dll"):
(system32 / name).symlink_to(os.path.relpath(builtins / name, system32))
(system32 / (name + ".foreign-arch")).write_bytes(pe_image(0x8664))
(system32 / "vulkan-1.dll.foreign-arch.1").write_bytes(pe_image(0x8664) + b"newest")
restore = MODULE["restore_compatible_system_dlls"]
self.assertEqual(["system32/vulkan-1.dll (machine 0x8664)"], restore(str(compat), str(proton)))
self.assertFalse((system32 / "vulkan-1.dll").is_symlink())
self.assertTrue((system32 / "vulkan-1.dll").read_bytes().endswith(b"newest"))
self.assertFalse((system32 / "vulkan-1.dll.foreign-arch.1").exists())
self.assertTrue((system32 / "ucrtbase.dll").is_symlink())
self.assertEqual([], restore(str(compat), str(proton)))
self.assertEqual([], self.run_repair(compat, proton))
def test_prefix_backup_directory_is_listed_once_per_pass(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
system32 = windows / "system32"
for index in range(12):
name = "native_%02d.dll" % index
(builtins / name).write_bytes(pe_image(0xAA64))
(system32 / name).symlink_to(os.path.relpath(builtins / name, system32))
(system32 / (name + ".foreign-arch")).write_bytes(pe_image(0x8664))
(system32 / "ucrtbase.dll").write_bytes(pe_image(0x8664))
original_listdir = os.listdir
visited = []
def counted_listdir(folder):
if Path(folder) == system32:
visited.append(folder)
return original_listdir(folder)
with mock.patch("os.listdir", side_effect=counted_listdir):
restored = MODULE["restore_compatible_system_dlls"](str(compat), str(proton))
fixed = self.run_repair(compat, proton)
self.assertEqual(12, len(restored))
self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], fixed)
# One system32 listing for restore and one for repair, regardless
# of the number of DLLs and backup files in the prefix.
self.assertEqual(2, len(visited))
def test_restore_takes_the_highest_backup_serial_across_gaps(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(builtins / "vulkan-1.dll", system32))
(system32 / "vulkan-1.dll.foreign-arch.2").write_bytes(pe_image(0x8664) + b"two")
(system32 / "vulkan-1.dll.foreign-arch.10").write_bytes(pe_image(0x8664) + b"ten")
self.assertEqual(["system32/vulkan-1.dll (machine 0x8664)"],
MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").read_bytes().endswith(b"ten"))
def test_unreadable_proton_program_keeps_the_conservative_rule(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "broken.exe").mkdir()
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
(system32 / "concrt140.dll").write_bytes(pe_image(0x8664))
(builtins / "concrt140.dll").write_bytes(pe_image(0xAA64))
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(builtins / "vulkan-1.dll", system32))
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0x8664))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
self.assertEqual(["system32/concrt140.dll (machine 0x8664)"], self.run_repair(compat, proton))
def test_new_backup_goes_above_the_highest_existing_serial(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
system32 = windows / "system32"
(system32 / "ucrtbase.dll").write_bytes(pe_image(0x8664) + b"newest")
(system32 / "ucrtbase.dll.foreign-arch").write_bytes(pe_image(0x8664))
(system32 / "ucrtbase.dll.foreign-arch.2").write_bytes(pe_image(0x8664))
self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], self.run_repair(compat, proton))
self.assertTrue((system32 / "ucrtbase.dll.foreign-arch.3").read_bytes().endswith(b"newest"))
self.assertFalse((system32 / "ucrtbase.dll.foreign-arch.1").exists())
def test_truncated_import_table_keeps_the_conservative_rule(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "cut.exe").write_bytes(program_image(0xAA64, ["concrt140.dll"])[:0x20A])
self.assertIsNone(MODULE["PE"]["pe_imports"](builtins / "cut.exe"))
self.assertIsNone(MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), program_image(0xAA64, ["a.dll"])[:200])))
self.assertEqual(set(), MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), program_image(0xAA64, []))))
moved = bytearray(program_image(0xAA64, ["concrt140.dll"]))
moved[208:212] = (0x3000).to_bytes(4, "little")
self.assertIsNone(MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), moved)))
(builtins / "concrt140.dll").write_bytes(pe_image(0xAA64))
(windows / "system32/concrt140.dll").write_bytes(pe_image(0x8664))
self.assertEqual(["system32/concrt140.dll (machine 0x8664)"], self.run_repair(compat, proton))
def test_restore_leaves_other_links_and_x64_proton_alone(self):
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp)
builtins = proton.parent / "files/lib/wine/aarch64-windows"
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
other = Path(tmp) / "other-vulkan-1.dll"
other.write_bytes(pe_image(0xAA64))
system32 = windows / "system32"
(system32 / "vulkan-1.dll").symlink_to(other)
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0x8664))
(system32 / "rpcrt4.dll").symlink_to(os.path.relpath(builtins / "rpcrt4.dll", system32))
(system32 / "rpcrt4.dll.foreign-arch").write_bytes(pe_image(0x14C))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
self.assertTrue((system32 / "rpcrt4.dll").is_symlink())
with tempfile.TemporaryDirectory() as tmp:
proton, compat, windows = self.prefix(tmp, arm=False)
dist = proton.parent / "files/lib/wine/x86_64-windows"
dist.mkdir(parents=True)
(dist / "vulkan-1.dll").write_bytes(pe_image(0x8664))
system32 = windows / "system32"
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(dist / "vulkan-1.dll", system32))
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0xAA64))
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
def test_final_arm64ec_image_is_not_repaired_as_a_foreign_x64_dll(self):
with tempfile.TemporaryDirectory() as tmp:
+112
View File
@@ -0,0 +1,112 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0134-touch-click-press-once.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>
#define WLSERVER_BUTTON_COUNT 7
enum { HOVER = 0, LEFT = 1, RIGHT = 2, PASSTHROUGH = 4 };
static const uint32_t BTN_L = 0x110, BTN_R = 0x111;
'''
MAIN = r'''
struct Seat {
int pressed[2] = {0, 0};
int sent[2] = {0, 0};
int slot(uint32_t b) { return b == BTN_L ? 0 : 1; }
void press(uint32_t b) { if (pressed[slot(b)]++ == 0) sent[slot(b)]++; }
void release(uint32_t b) { if (pressed[slot(b)] > 0 && --pressed[slot(b)] == 0) sent[slot(b)]--; }
};
static uint32_t button_of(int mode) { return mode == LEFT ? BTN_L : mode == RIGHT ? BTN_R : 0; }
struct Server {
bool held[WLSERVER_BUTTON_COUNT] = {};
Seat seat;
void down(int mode) {
uint32_t b = button_of(mode);
if (touch_click_press(held, mode, b)) seat.press(b);
}
void up() {
for (int i = 0; i < WLSERVER_BUTTON_COUNT; i++) {
if (held[i] && button_of(i)) seat.release(button_of(i));
held[i] = false;
}
}
};
int main() {
Server tap;
tap.down(LEFT);
assert(tap.seat.sent[0] == 1);
tap.up();
assert(tap.seat.sent[0] == 0 && tap.seat.pressed[0] == 0);
Server overlap;
overlap.down(LEFT);
overlap.down(LEFT);
overlap.up();
overlap.up();
assert(overlap.seat.pressed[0] == 0 && overlap.seat.sent[0] == 0);
overlap.down(LEFT);
assert(overlap.seat.sent[0] == 1);
overlap.up();
assert(overlap.seat.sent[0] == 0);
Server three;
for (int i = 0; i < 3; i++) three.down(LEFT);
for (int i = 0; i < 3; i++) three.up();
assert(three.seat.pressed[0] == 0);
Server modes;
modes.down(LEFT);
modes.down(RIGHT);
modes.up();
modes.up();
assert(modes.seat.pressed[0] == 0 && modes.seat.pressed[1] == 0);
Server hover;
hover.down(HOVER);
hover.down(PASSTHROUGH);
assert(hover.seat.pressed[0] == 0 && hover.seat.pressed[1] == 0);
bool held[WLSERVER_BUTTON_COUNT] = {};
assert(!touch_click_press(held, -1, BTN_L));
assert(!touch_click_press(held, WLSERVER_BUTTON_COUNT, BTN_L));
return 0;
}
'''
class GamescopeTouchClickTest(unittest.TestCase):
def test_overlapping_touches_release_the_emulated_button(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
source = PREAMBLE + block(added_source(), "static bool touch_click_press") + MAIN
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "touch_click.cpp"
exe = Path(tmp) / "touch_click"
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)
if __name__ == "__main__":
unittest.main()
+56
View File
@@ -0,0 +1,56 @@
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"
def include(variable, default):
return Path(os.environ.get(variable, str(default)))
class MaliCompatLayerTest(unittest.TestCase):
def test_dual_source_blending_against_a_mock_loader_and_driver(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")
bcdec = include("MALI_COMPAT_BCDEC_INCLUDE", DEPS / "bcdec")
missing = [str(path) for path in (vulkan / "vulkan/vk_layer.h", spirv / "spirv/unified1/spirv.h",
bcdec / "bcdec.h") if not path.is_file()]
if missing:
message = "Vulkan 1.4, SPIR-V and bcdec headers are required: " + ", ".join(missing)
if os.environ.get("CI"):
self.fail(message)
self.skipTest(message)
with tempfile.TemporaryDirectory(prefix="droiddeck-mali-compat-") as tmp:
program = Path(tmp) / "mali-compat-layer"
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
"-UNDEBUG", "-pthread", "-I", str(LAYER), "-I", str(vulkan), "-I", str(spirv),
"-I", str(bcdec), str(Path(__file__).with_name("mali_compat_layer_test.c")),
*sorted(str(source) for source in LAYER.glob("*.c")), "-o", str(program)],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
ran = subprocess.run([str(program), tmp], capture_output=True, text=True, timeout=30)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
self.assertIn("mali compat layer ok", ran.stdout)
self.assertIn("emulating dualSrcBlend for mock", ran.stderr)
validator = shutil.which("spirv-val")
if not validator:
return
for name, environment in (("dual-1.0.spv", "vulkan1.0"), ("plain-1.0.spv", "vulkan1.0"),
("stripped-1.0.spv", "vulkan1.0"), ("stripped-1.4.spv", "vulkan1.2")):
checked = subprocess.run([validator, "--target-env", environment, str(Path(tmp) / name)],
capture_output=True, text=True)
self.assertEqual(checked.returncode, 0, name + ": " + checked.stdout + checked.stderr)
if __name__ == "__main__":
unittest.main()
+51 -1
View File
@@ -160,15 +160,17 @@ class SessionPressureTest(unittest.TestCase):
def run_policy(self, body):
functions = '\n'.join(function_source(name) for name in (
'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical',
'bl_client_can_pageout', 'bl_client_pressure', 'bl_client_pressure_result',
'bl_session_pressure', 'bl_zram_has_room', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback'))
functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo'))
functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure'))
harness = '''
set -u
_bl_game=1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() _bl_pids=(999)
_bl_pressure_at=-1 _bl_packed=-1
_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1
rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive="999 321 654" started=100 complete=1
step() { :; }
bl_game_focused() { [ "${focused:-1}" = 1 ]; }
bl_proc_start() { _bl_start=; case " $alive " in *" $1 "*) _bl_start=$started; return 0 ;; esac; return 1; }
nap() { echo "nap:$1"; }
bl_session_others() { _bl_session=(321 654); }
@@ -205,6 +207,53 @@ SECONDS=30; bl_session_pressure
def test_no_game_does_not_compress_the_session(self):
self.assertEqual([], self.run_policy('_bl_game=0; bl_session_pressure'))
def test_disabled_idle_compression_does_not_compress_the_session(self):
self.assertEqual(['send:1:client'], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
def test_disabled_idle_compression_signals_only_launcher_processes(self):
sender = (function_source('bl_zram_send') + '\n' + function_source('bl_zram_finish')).replace('/tmp/.bl-zram', str(self.root / 'control'))
self.assertEqual(['kill:-URG 999 998', 'mode:1'], self.run_policy('''
_bl_pids=(999 998)
kill() { echo "kill:$*"; }
bl_zram_wait() { _bl_pageout_complete=1; }
bl_zram_scan() { :; }
''' + sender + '''
BL_ZRAM_IDLE=0; bl_client_pressure; bl_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('''
BL_ZRAM_IDLE=0 focused=0
bl_client_pressure
bl_session_pressure
'''))
def test_disabled_idle_compression_respects_launcher_setting_and_threshold(self):
self.memory(available=1700)
self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0 BL_ZRAM_CLIENT=0; bl_client_pressure; bl_session_pressure'))
self.memory(available=1900)
self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
def test_game_reclaim_requires_focus(self):
self.assertEqual([], self.run_policy('focused=0; bl_session_pressure'))
def test_game_reclaim_runs_when_focus_is_unknown(self):
launch = self.root / 'launch'
(launch / 'agent').mkdir(parents=True)
body = function_source('bl_game_focused') + f'\nBL_LAUNCH_DIR={launch} _bl_apps=7\n'
self.assertEqual(['send:1:session'], self.run_policy(body + 'bl_session_pressure'))
(launch / 'agent' / 'focus.json').write_text('{"focusedApp": 9}')
self.assertEqual([], self.run_policy(body + 'bl_session_pressure'))
self.assertEqual(['unfocused'], self.run_policy(body + 'bl_game_focused || echo unfocused'))
(launch / 'agent' / 'focus.json').unlink()
self.assertEqual(['unfocused'], self.run_policy(body + 'bl_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('BL_ZRAM_IDLE=0; bl_client_pressure; bl_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('bl_session_pressure'))
@@ -433,6 +482,7 @@ bl_zram_wait() {{
[ "$1" != 123 ] || client_rss=$((client_rss - {reclaimed * 1024}))
}}
bl_tier_note() {{ :; }}
bl_game_focused() {{ :; }}
''' + source + f'''
bl_memory_read
_bl_fall={fall * 1024}
+1
View File
@@ -70,6 +70,7 @@ static void send_toplevel_configure(struct surface *s) { (void)s; resizes++; }
#define stream_forget_all(...) ((void)0)
#define pointer_delta(...) ((void)0)
#define deliver_touch(m) ((void)0)
#define deliver_pen(m) ((void)0)
#define deliver_pointer(m) (pointers++)
static void on_vsync(int64_t ns) { assert(ns > 0); ticks++; }
static void vk_present_set_scale_mode(int mode, int alignment) {
+102
View File
@@ -0,0 +1,102 @@
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'
PEN_STREAM = REPO / 'app/src/main/java/com/droiddeck/launcher/input/PenStream.kt'
def function(source, signature):
start = source.index(signature)
return source[start:source.index('\n}\n', start) + 3]
class PenEmulationTest(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')
source = SOURCE.read_text()
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-pen-emulation-')
cls.addClassCleanup(cls.temp.cleanup)
folder = Path(cls.temp.name)
start = source.index('struct input_msg {')
(folder / 'input_msg.inc').write_text(source[start:source.index('\n', start) + 1])
start = source.index('#define PEN_IN ')
end = source.index('static struct pen_state g_pen;\n', start)
(folder / 'pen_state.inc').write_text(source[start:source.index('\n', end) + 1])
(folder / 'pen.inc').write_text(''.join(function(source, signature) for signature in (
'static int pointer_locked_for_cursor(void) {',
'static void input_output_to_scene(double px, double py, double *x, double *y) {',
'static int pen_buttons(int flags) {',
'static void pen_release(int buttons) {',
'static void deliver_pen(const struct input_msg *m) {')))
start = source.index('#define for_each_pointer_of(client, sp)')
(folder / 'pointer.inc').write_text(
function(source, 'static struct seat_pointer *pointer_for(struct wl_client *client) {')
+ source[start:source.index('#define for_each_keyboard_of', start)]
+ ''.join(function(source, signature) for signature in (
'static void pointer_focus(struct wl_resource *target, wl_fixed_t fx, wl_fixed_t fy) {',
'static void pointer_input(double x, double y, int relative, uint32_t button, int pressed) {',
'static void pointer_event(double x, double y, uint32_t button, int pressed) {',
'static void pointer_button(uint32_t button, int pressed) {')))
cls.binary = folder / 'pen-test'
cls.pointer_binary = folder / 'pen-pointer-test'
for harness, binary in (('pen_emulation_harness.c', cls.binary),
('pen_pointer_harness.c', cls.pointer_binary)):
subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror', '-I', str(folder),
str(REPO / 'tools/tests' / harness),
'-o', str(binary)], check=True, capture_output=True, text=True)
def check_case(self, case, binary=None):
result = subprocess.run([str(binary or self.binary), case], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_flags_match_the_kotlin_pen_stream(self):
native = dict(re.findall(r'^#define (PEN_[A-Z]+) \(1 << (\d+)\)$', SOURCE.read_text(), re.MULTILINE))
kotlin = dict(re.findall(r'^\s*const val (PEN_[A-Z]+) = 1 shl (\d+)$', PEN_STREAM.read_text(), re.MULTILINE))
self.assertEqual({'PEN_IN', 'PEN_TIP', 'PEN_RIGHT', 'PEN_MIDDLE'}, set(native))
self.assertEqual(native, kotlin)
def test_hover_moves_the_pointer_in_scene_coordinates(self):
self.check_case('hover')
def test_tip_presses_and_releases_the_left_button_once(self):
self.check_case('tip')
def test_buttons_press_after_motion_and_before_releases(self):
self.check_case('buttons')
def test_leaving_proximity_releases_every_button_without_motion(self):
self.check_case('out')
def test_pointer_lock_blocks_motion_but_passes_buttons(self):
self.check_case('lock')
def test_lost_records_still_release_held_buttons(self):
self.check_case('lost')
def test_relative_origin_resets_when_proximity_starts_and_ends(self):
self.check_case('raw')
def test_side_button_release_keeps_the_grab(self):
self.check_case('side', self.pointer_binary)
def test_swapping_buttons_in_one_record_keeps_the_grab(self):
self.check_case('swap', self.pointer_binary)
def test_a_button_release_from_another_pointer_keeps_the_grab(self):
self.check_case('mouse', self.pointer_binary)
def test_a_window_closed_by_a_button_release_is_not_grabbed_again(self):
self.check_case('gone', self.pointer_binary)
if __name__ == '__main__':
unittest.main()
+39
View File
@@ -0,0 +1,39 @@
from pathlib import Path
import re
import unittest
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[2]
RES = ROOT / "app/src/main/res"
def strings(path):
return {
element.attrib["name"]: "".join(element.itertext())
for element in ET.parse(path).getroot()
if element.tag == "string" and element.get("translatable") != "false"
}
class PenLocalizationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.required = [key for key in strings(RES / "values/strings.xml") if key.startswith("mode_pen")]
language_source = (ROOT / "app/src/main/java/com/droiddeck/launcher/core/AppLanguage.kt").read_text(encoding="utf-8")
tags = re.findall(r'"([a-zA-Z0-9-]+)"', re.search(r"val supported:.*?listOf\((.*?)\)", language_source, re.S).group(1))
special = {"id": "in", "es-419": "b+es+419", "pt-BR": "pt"}
cls.locales = {
tag: strings(RES / f"values-{special.get(tag, tag.replace('-', '-r'))}/strings.xml")
for tag in tags if tag != "en"
}
def test_every_supported_language_translates_the_pen_settings(self):
for locale, translated in self.locales.items():
for key in self.required:
with self.subTest(locale=locale, key=key):
self.assertTrue(translated.get(key, "").strip(), "Missing translation would fall back to English")
if __name__ == "__main__":
unittest.main()
+52
View File
@@ -0,0 +1,52 @@
import unittest
from tools.release.update_catalog import ApiError, in_preview, iso_millis, keeps_test_build
from tools.release.retire_test_builds import retired
MERGED = "2026-11-14T20:00:00Z"
NOW = iso_millis(MERGED) + 3600_000
class FakeSource:
def __init__(self, status=None):
self.status = status
self.asked = []
def get(self, path):
self.asked.append(path)
if self.status is None:
raise ApiError(404, "no")
return {"status": self.status}
def pull(state="closed", merged_at=MERGED, draft=False, base="main"):
return {"state": state, "merged_at": merged_at, "merge_commit_sha": "a" * 40, "draft": draft, "base": {"ref": base}}
class RetireTestBuildsTest(unittest.TestCase):
def test_an_open_pr_keeps_its_build(self):
self.assertFalse(retired(pull(state="open", merged_at=None), FakeSource("ahead"), "o/r", "b" * 40))
def test_a_closed_unmerged_pr_loses_it_at_once(self):
self.assertTrue(retired(pull(merged_at=None), FakeSource(), "o/r", None))
def test_a_merged_pr_keeps_it_until_a_preview_carries_the_merge(self):
self.assertFalse(in_preview(FakeSource("behind"), "o/r", pull(), "b" * 40, NOW))
self.assertFalse(in_preview(FakeSource(), "o/r", pull(), "b" * 40, NOW))
self.assertFalse(in_preview(FakeSource("ahead"), "o/r", pull(), None, NOW))
self.assertTrue(in_preview(FakeSource("ahead"), "o/r", pull(), "b" * 40, NOW))
self.assertTrue(in_preview(FakeSource("identical"), "o/r", pull(), "a" * 40, NOW))
def test_a_merge_no_preview_ever_carries_is_let_go_after_the_grace(self):
self.assertTrue(in_preview(FakeSource(), "o/r", pull(), None, NOW + 4 * 86_400_000))
def test_the_catalog_lists_open_and_merged_main_prs(self):
self.assertTrue(keeps_test_build(pull(state="open", merged_at=None)))
self.assertTrue(keeps_test_build(pull()))
self.assertFalse(keeps_test_build(pull(merged_at=None)))
self.assertFalse(keeps_test_build(pull(draft=True)))
self.assertFalse(keeps_test_build(pull(base="release")))
if __name__ == "__main__":
unittest.main()
+62
View File
@@ -1,8 +1,12 @@
import base64
import unittest
from tools.release.update_catalog import (
Cache,
asset_for_suffix,
build_catalog,
complete_apks,
newest_complete,
merged_pr,
ci_description,
parse_gradle,
@@ -59,6 +63,64 @@ pubg com.tencent.ig -pubg
self.assertEqual("DroidDeck-main-deadbee.apk", standard["name"])
self.assertEqual("DroidDeck-main-deadbee-pubg.apk", pubg["name"])
def test_the_apk_named_for_the_build_commit_wins_over_a_previous_push(self):
def apk(name, digit):
return {"name": name, "size": 1, "digest": "sha256:" + digit * 64, "browser_download_url": "https://example/" + name}
assets = [apk("DroidDeck-PR.7-1111111.apk", "a"), apk("DroidDeck-PR.7-2222222.apk", "b"),
apk("DroidDeck-PR.7-1111111-pubg.apk", "c"), apk("DroidDeck-PR.7-2222222-pubg.apk", "d")]
suffixes = ["", "-pubg"]
self.assertEqual("DroidDeck-PR.7-2222222.apk", asset_for_suffix(assets, "", suffixes, "2222222abc")["name"])
self.assertEqual("DroidDeck-PR.7-2222222-pubg.apk", asset_for_suffix(assets, "-pubg", suffixes, "2222222abc")["name"])
self.assertEqual("DroidDeck-PR.7-1111111.apk", asset_for_suffix(assets, "", suffixes)["name"])
def test_a_preview_counts_only_with_every_package_and_digest(self):
variants = [("com.droiddeck.launcher", ""), ("com.tencent.ig", "-pubg")]
good = {"sha256": "a" * 64, "signerSha256": "b" * 64}
self.assertTrue(complete_apks({"apks": {"com.droiddeck.launcher": good, "com.tencent.ig": good}}, variants))
self.assertFalse(complete_apks({"apks": {"com.droiddeck.launcher": good}}, variants))
self.assertFalse(complete_apks({"apks": {}}, variants))
self.assertFalse(complete_apks({"apks": {"com.droiddeck.launcher": good, "com.tencent.ig": {"sha256": "x"}}}, variants))
def test_no_preview_is_offered_until_one_has_every_apk(self):
variants = [("com.droiddeck.launcher", "")]
good = {"com.droiddeck.launcher": {"sha256": "a" * 64, "signerSha256": "b" * 64}}
uploading = {"commit": "2" * 40, "apks": {}}
done = {"commit": "1" * 40, "apks": good}
self.assertIsNone(newest_complete([uploading], variants))
self.assertIsNone(newest_complete([], variants))
self.assertIs(done, newest_complete([uploading, done], variants))
def test_the_catalog_publishes_no_preview_while_its_apks_are_uploading(self):
commit = "c" * 40
files = {
"app/build.gradle": " versionCode 19\n versionName \"0.7.1\"\n",
"tools/release/variants.txt": "standard com.droiddeck.launcher -\n",
"keystore/release-signer.sha256": "b" * 64 + "\n",
}
class FakeGitHub:
def get_all(self, path, limit=1000):
if "DroidDeck-CI/releases" in path:
return [{
"tag_name": f"main-{commit[:7]}", "prerelease": True, "assets": [],
"published_at": "2026-11-14T10:00:00Z",
"body": f"**Merged to main** - [PR #5](u): fix: x\n\nCommit: {commit}\nVersionCode: 19\n",
}]
return []
def get(self, path):
for name, text in files.items():
if f"/contents/{name.replace('/', '%2F')}?" in path:
return {"encoding": "base64", "content": base64.b64encode(text.encode()).decode()}
if "/commits/" in path:
return {"author": {"login": "dev"}, "commit": {"committer": {"date": "2026-11-14T09:59:00Z"}}}
raise AssertionError(path)
gh = FakeGitHub()
catalog = build_catalog(gh, gh, "Droid-Deck/DroidDeck", "Droid-Deck/DroidDeck-CI")
self.assertIsNone(catalog["preview"])
self.assertEqual([commit], [p["commit"] for p in catalog["previews"]])
def test_ci_description(self):
title, summary = ci_description(
{
+85 -8
View File
@@ -41,8 +41,37 @@ class WinComponentsTest(unittest.TestCase):
def proton(self, arm=True):
root = Path(self.tmp.name) / ("arm-proton" if arm else "x64-proton")
(root / "files/lib/wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True)
builtins = root / "files/lib/wine/aarch64-windows"
builtins.mkdir(parents=True)
(builtins / "wineboot.exe").write_bytes(self.program_image(0xAA64, ["ucrtbase.dll"]))
(builtins / "steam.exe").write_bytes(self.program_image(0x8664, ["vulkan-1.dll"]))
(builtins / "d3dx9_43.dll").write_bytes(self.program_image(0xAA64, ["d3dcompiler_43.dll"]))
return root / "proton"
def program_image(self, machine, imports):
image = bytearray(0x400)
image[:2] = b"MZ"
image[60:64] = (64).to_bytes(4, "little")
image[64:68] = b"PE\0\0"
image[68:70] = machine.to_bytes(2, "little")
image[70:72] = (1).to_bytes(2, "little")
image[84:86] = (240).to_bytes(2, "little")
image[88:90] = (0x20B).to_bytes(2, "little")
image[196:200] = (16).to_bytes(4, "little")
image[208:212] = (0x1000).to_bytes(4, "little")
image[212:216] = (20 * (len(imports) + 1)).to_bytes(4, "little")
section = 88 + 240
image[section + 8:section + 12] = (0x200).to_bytes(4, "little")
image[section + 12:section + 16] = (0x1000).to_bytes(4, "little")
image[section + 16:section + 20] = (0x200).to_bytes(4, "little")
image[section + 20:section + 24] = (0x200).to_bytes(4, "little")
name = 20 * (len(imports) + 1)
for index, dll in enumerate(imports):
image[0x200 + index * 20 + 12:0x200 + index * 20 + 16] = (0x1000 + name).to_bytes(4, "little")
image[0x200 + name:0x200 + name + len(dll)] = dll.encode()
name += len(dll) + 1
return bytes(image)
def pe_image(self, machine):
head = bytearray(64)
head[:2] = b"MZ"
@@ -92,17 +121,65 @@ class WinComponentsTest(unittest.TestCase):
self.assertEqual(names, ["ucrtbase"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/ucrtbase.dll"), 0x8664)
def test_x64_visual_cpp_runtime_is_placed_in_arm64_system32(self):
def test_x64_dlls_proton_programs_do_not_import_are_placed_in_arm64_system32(self):
proton = self.proton()
self.component("vc", ["msvcp140", "vcruntime140_1"], {
"system32/msvcp140.dll": self.pe_image(0x8664),
"system32/vcruntime140_1.dll": self.pe_image(0x8664),
})
names = ["concrt140", "d3dcompiler_43", "msvcp140", "vcruntime140_1", "vulkan-1"]
self.component("vc", names, {"system32/%s.dll" % name: self.pe_image(0x8664) for name in names})
self.pick("vc")
names, _ = self.apply(proton)
self.assertEqual(names, ["msvcp140", "vcruntime140_1"])
placed, _ = self.apply(proton)
self.assertEqual(placed, names)
for name in names:
self.assertEqual(MODULE["pe_machine"](self.pfx / ("system32/%s.dll" % name)), 0x8664)
def test_x64_d3dx9_and_its_compiler_stay_placed_on_every_launch(self):
proton = self.proton()
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.pe_image(0x8664)})
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dx9", "d3dcompiler")
for _ in range(2):
placed, _ = self.apply(proton)
self.assertEqual(placed, ["d3dx9_43", "d3dcompiler_43"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
def test_x64_compiler_alone_is_placed_although_a_builtin_dll_imports_it(self):
proton = self.proton()
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
self.pick("d3dcompiler")
placed, _ = self.apply(proton)
self.assertEqual(placed, ["d3dcompiler_43"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
def test_x64_proton_program_imports_do_not_make_a_dll_foreign(self):
proton = self.proton()
self.component("vk", ["vulkan-1"], {"system32/vulkan-1.dll": self.pe_image(0x8664)})
self.pick("vk")
placed, _ = self.apply(proton)
self.assertEqual(placed, ["vulkan-1"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vulkan-1.dll"), 0x8664)
def test_partly_installed_x64_visual_cpp_runtime_stays_x64(self):
proton = self.proton()
self.pfx.joinpath("system32").mkdir(parents=True)
self.pfx.joinpath("system32/vcruntime140.dll").write_bytes(self.pe_image(0x8664))
self.component("vc", ["msvcp140"], {"system32/msvcp140.dll": self.pe_image(0x8664)})
self.pick("vc")
placed, _ = self.apply(proton)
self.assertEqual(placed, ["msvcp140"])
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/msvcp140.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140_1.dll"), 0x8664)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140.dll"), 0x8664)
def test_deselected_component_restores_the_saved_x64_dll(self):
proton = self.proton()
self.pfx.joinpath("system32").mkdir(parents=True)
self.pfx.joinpath("system32/d3dx9_43.dll").write_bytes(self.pe_image(0x8664))
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.program_image(0xAA64, [])})
self.pick("d3dx9")
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0xAA64)
self.pick()
self.apply(proton)
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
def test_compatible_copy_keeps_override_when_other_architecture_copy_is_skipped(self):
proton = self.proton()
+181
View File
@@ -211,3 +211,184 @@ class XboxLaunchTest(unittest.TestCase):
with patch('subprocess.run', **outcome), patch('sys.stderr', new_callable=io.StringIO) as err:
self.assertIsNone(xbox['register_classes']('/selected/proton', prefix, {}))
self.assertIn('registration failed', err.getvalue())
def pe_with_exports(names, forward=None, machine=0x8664, unnamed=0):
"""A minimal x64 PE image whose export table names `names`; with `forward`, every export is forwarded there.
`unnamed` adds that many ordinal-only exports after the named ones."""
rva, raw = 0x1000, 0x200
functions = rva + 40
name_pointers = functions + 4 * (len(names) + unnamed)
ordinals = name_pointers + 4 * len(names)
strings = ordinals + 2 * len(names)
blob = bytearray()
name_rvas, forward_rvas = [], []
for name in names:
name_rvas.append(strings + len(blob))
blob += name.encode() + b'\0'
for name in names:
forward_rvas.append(strings + len(blob))
if forward:
blob += ('%s.%s' % (forward, name)).encode() + b'\0'
size = strings + len(blob) - rva
directory = bytearray(40)
directory[16:20] = (1).to_bytes(4, 'little')
directory[20:24] = (len(names) + unnamed).to_bytes(4, 'little')
directory[24:28] = len(names).to_bytes(4, 'little')
directory[28:32] = functions.to_bytes(4, 'little')
directory[32:36] = name_pointers.to_bytes(4, 'little')
directory[36:40] = ordinals.to_bytes(4, 'little')
section = bytearray(directory)
for index in range(len(names)):
section += (forward_rvas[index] if forward else 0x3000 + index).to_bytes(4, 'little')
for index in range(unnamed):
section += (0x4000 + index).to_bytes(4, 'little')
for value in name_rvas:
section += value.to_bytes(4, 'little')
for index in range(len(names)):
section += index.to_bytes(2, 'little')
section += blob
image = bytearray(raw)
image[:2] = b'MZ'
image[60:64] = (0x40).to_bytes(4, 'little')
image[0x40:0x44] = b'PE\0\0'
image[0x44:0x46] = machine.to_bytes(2, 'little')
image[0x46:0x48] = (1).to_bytes(2, 'little')
image[0x54:0x56] = (240).to_bytes(2, 'little')
optional = 0x58
image[optional:optional + 2] = (0x20B).to_bytes(2, 'little')
image[optional + 108:optional + 112] = (16).to_bytes(4, 'little')
image[optional + 112:optional + 116] = rva.to_bytes(4, 'little')
image[optional + 116:optional + 120] = size.to_bytes(4, 'little')
header = optional + 240
image[header + 8:header + 12] = len(section).to_bytes(4, 'little')
image[header + 12:header + 16] = rva.to_bytes(4, 'little')
image[header + 16:header + 20] = len(section).to_bytes(4, 'little')
image[header + 20:header + 24] = raw.to_bytes(4, 'little')
return bytes(image + section)
class PlayFabProxyTest(unittest.TestCase):
SDK = pe_with_exports(xbox['PGS_EXPORTS'])
NEWER_SDK = SDK + b'\0update'
PROXY = pe_with_exports(xbox['PGS_EXPORTS'], forward='nexus_pgs_native')
def stage(self, root, proxy=PROXY):
runtime = Path(root) / 'runtime'
if proxy is not None:
(runtime / 'compat').mkdir(parents=True, exist_ok=True)
(runtime / 'compat/PlayFabGameSave.dll').write_bytes(proxy)
with patch.dict(xbox['stage_playfab_proxy'].__globals__, PGS_PROXY=runtime / 'compat/PlayFabGameSave.dll'), \
patch('sys.stderr', new_callable=io.StringIO):
return xbox['stage_playfab_proxy'](Path(root) / 'game')
def game(self, root, data, sub='Bin'):
folder = Path(root) / 'game' / sub
folder.mkdir(parents=True)
(folder / 'PlayFabGameSave.dll').write_bytes(data)
return folder
def test_sdk_and_proxy_are_told_apart_by_their_exports(self):
self.assertTrue(xbox['playfab_sdk'](self.SDK))
self.assertFalse(xbox['playfab_proxy'](self.SDK))
self.assertTrue(xbox['playfab_proxy'](self.PROXY))
self.assertFalse(xbox['playfab_sdk'](self.PROXY))
other = pe_with_exports(list(xbox['PGS_EXPORTS'][:-1]) + ['PFGameSaveFilesSomethingNew'])
self.assertFalse(xbox['playfab_sdk'](other))
self.assertFalse(xbox['playfab_sdk'](pe_with_exports(xbox['PGS_EXPORTS'], machine=0xAA64)))
self.assertIsNone(xbox['pe_exports'](b'not a pe image'))
self.assertEqual(xbox['pe_exports'](pe_with_exports(['A', 'B'], unnamed=1))[0], 3)
self.assertFalse(xbox['playfab_sdk'](pe_with_exports(xbox['PGS_EXPORTS'], unnamed=1)))
self.assertFalse(xbox['playfab_proxy'](pe_with_exports(xbox['PGS_EXPORTS'], forward='nexus_pgs_native', unnamed=1)))
def test_first_launch_keeps_the_sdk_and_puts_the_proxy_in_front(self):
with tempfile.TemporaryDirectory() as root:
folder = self.game(root, self.SDK)
self.assertEqual(self.stage(root), 1)
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), self.SDK)
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.PROXY)
self.assertEqual(self.stage(root), 1)
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), self.SDK)
self.assertEqual(sorted(path.name for path in folder.iterdir()), ['PlayFabGameSave.dll', 'nexus_pgs_native.dll'])
def test_a_game_update_replaces_the_kept_sdk(self):
with tempfile.TemporaryDirectory() as root:
folder = self.game(root, self.SDK)
self.stage(root)
(folder / 'PlayFabGameSave.dll').write_bytes(self.NEWER_SDK)
self.assertEqual(self.stage(root), 1)
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), self.NEWER_SDK)
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.PROXY)
def test_an_older_proxy_is_refreshed_only_while_its_sdk_is_there(self):
older = self.PROXY + b'\0older'
with tempfile.TemporaryDirectory() as root:
folder = self.game(root, older)
(folder / 'nexus_pgs_native.dll').write_bytes(self.SDK)
self.assertEqual(self.stage(root), 1)
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.PROXY)
with tempfile.TemporaryDirectory() as root:
folder = self.game(root, older)
self.assertEqual(self.stage(root), 0)
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), older)
def test_an_unknown_file_or_link_in_place_of_the_kept_sdk_is_never_overwritten(self):
with tempfile.TemporaryDirectory() as root:
folder = self.game(root, self.SDK)
(folder / 'nexus_pgs_native.dll').write_bytes(b'MZ someone else')
self.assertEqual(self.stage(root), 0)
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), b'MZ someone else')
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.SDK)
with tempfile.TemporaryDirectory() as root:
folder = self.game(root, self.SDK)
target = Path(root) / 'elsewhere.dll'
target.write_bytes(self.SDK)
(folder / 'nexus_pgs_native.dll').symlink_to(target)
self.assertEqual(self.stage(root), 0)
self.assertTrue((folder / 'nexus_pgs_native.dll').is_symlink())
self.assertEqual(target.read_bytes(), self.SDK)
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.SDK)
def test_unknown_sdk_symlinks_and_a_runtime_without_the_proxy_are_left_alone(self):
with tempfile.TemporaryDirectory() as root:
unknown = pe_with_exports(['PFGameSaveFilesInitialize'])
folder = self.game(root, unknown)
self.assertEqual(self.stage(root), 0)
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), unknown)
self.assertFalse((folder / 'nexus_pgs_native.dll').exists())
with tempfile.TemporaryDirectory() as root:
folder = self.game(root, self.SDK)
self.assertEqual(self.stage(root, proxy=None), 0)
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.SDK)
with tempfile.TemporaryDirectory() as root:
target = Path(root) / 'elsewhere.dll'
target.write_bytes(self.SDK)
folder = Path(root) / 'game'
folder.mkdir()
(folder / 'PlayFabGameSave.dll').symlink_to(target)
self.assertEqual(self.stage(root), 0)
self.assertEqual(target.read_bytes(), self.SDK)
def test_launch_stages_the_proxy_without_dll_overrides_and_survives_a_failure(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
runtime = root / 'windows'
runtime.mkdir()
for name in xbox['DLLS']:
(runtime / name).touch()
store = {'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}),
'ask': unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1',
'exe': '/Game.exe'})}
wine = unittest.mock.Mock(return_value=0)
staged = []
def failing(folder):
raise RuntimeError('unreadable game folder')
for stage in (lambda folder: staged.append(folder) or 1, failing):
wine.reset_mock()
with patch('runpy.run_path', return_value=store), patch('sys.stderr', new_callable=io.StringIO), \
patch.dict(xbox['launch'].__globals__, RUNTIME=root, bridge=lambda path: (1, 'key', lambda: None),
wine=wine, stage_playfab_proxy=stage):
self.assertEqual(xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'],
{'BL_LAUNCH_DIR': '/launch', 'WINEDLLOVERRIDES': 'd3d11=n'}), 0)
self.assertEqual(wine.call_args.args[1]['WINEDLLOVERRIDES'], 'd3d11=n')
self.assertEqual(staged, [root])
+1
View File
@@ -65,6 +65,7 @@ int vkp_cardboard_active(void) { return 0; }
void vkp_cardboard_begin_frame(void) {}
VkImage vkp_cardboard_run(VkCommandBuffer c, VkImage s, int sw, int sh, int ow, int oh) { return s; }
int vk_loader_open(const char *a, const char *b, const char *c) { assert(0); return -1; }
void vk_loader_close(void) { assert(0); }
void vk_loader_load_instance(VkInstance i) { assert(0); }
void vk_loader_load_device(VkDevice d) { assert(0); }
PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return NULL; }