mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-25 15:56:01 +00:00
chore: merge main into feat/lse-emu
This commit is contained in:
commit
73104aff03
667 files changed
+75245
-4143
No files matched your search
@@ -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;
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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)
|
||||
@@ -198,6 +239,155 @@ class ConfigAndMenuTest(Temp):
|
||||
self.assertEqual(path.stat().st_mtime_ns, mtime)
|
||||
|
||||
|
||||
class DriveTest(Temp):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.root = str(self.tmp / "Steam")
|
||||
self.devices = Path(BNET["dosdevices"](self.root))
|
||||
self.card = self.tmp / "card"
|
||||
self.library = self.card / "Games/Battle.net"
|
||||
self.library.mkdir(parents=True)
|
||||
self.running = []
|
||||
patcher = mock.patch.dict(BNET, {"say": lambda message: None, "wine_processes": lambda pfx, proc="/proc": list(self.running),
|
||||
"volume_root": lambda path: str(self.card) if BNET["inside"](path, str(self.card)) else "/"})
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def test_a_volume_ends_where_the_device_changes(self):
|
||||
devices = {"/": 1, "/mnt": 1, "/mnt/card": 7, "/mnt/card/Games": 7, "/mnt/card/Games/Battle.net": 7, "/root": 1, "/root/Games": 1}
|
||||
with mock.patch.object(os, "stat", lambda path: mock.Mock(st_dev=devices[path])):
|
||||
volume_root = runpy.run_path(str(BIN / "droiddeck-battlenet"))["volume_root"]
|
||||
self.assertEqual(volume_root("/mnt/card/Games/Battle.net"), "/mnt/card")
|
||||
self.assertEqual(volume_root("/mnt/card"), "/mnt/card")
|
||||
self.assertEqual(volume_root("/root/Games"), "/")
|
||||
self.assertEqual(volume_root("/"), "/")
|
||||
|
||||
def test_a_library_on_the_root_volume_keeps_its_path_and_gets_no_drive(self):
|
||||
library = self.tmp / "root/Games/Battle.net"
|
||||
library.mkdir(parents=True)
|
||||
self.assertEqual(BNET["install_path"](self.root, str(library) + "/"), "Z:" + str(library))
|
||||
self.assertFalse(self.devices.exists())
|
||||
|
||||
def test_a_library_on_another_volume_gets_a_drive_at_the_volume_root(self):
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
|
||||
self.assertEqual(os.readlink(self.devices / "d:"), str(self.card))
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library / "World of Warcraft")), "D:\\Games\\Battle.net\\World of Warcraft")
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.card)), "D:\\")
|
||||
self.assertEqual(sorted(os.listdir(self.devices)), ["d:"])
|
||||
|
||||
def test_drives_in_use_and_the_ones_proton_owns_are_left_alone(self):
|
||||
self.devices.mkdir(parents=True)
|
||||
os.symlink("/somewhere/else", self.devices / "d:")
|
||||
os.symlink(str(self.card), self.devices / "s:")
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "E:\\Games\\Battle.net")
|
||||
self.assertEqual(os.readlink(self.devices / "d:"), "/somewhere/else")
|
||||
for letter in BNET["DRIVES"]:
|
||||
if not os.path.lexists(self.devices / (letter + ":")):
|
||||
os.symlink("/somewhere/else", self.devices / (letter + ":"))
|
||||
os.unlink(self.devices / "e:")
|
||||
os.symlink("/somewhere/else", self.devices / "e:")
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library))
|
||||
self.assertNotIn("s", BNET["DRIVES"])
|
||||
self.assertNotIn("t", BNET["DRIVES"])
|
||||
|
||||
def test_a_running_prefix_gets_no_new_drive_but_uses_the_ones_it_started_with(self):
|
||||
self.running = [(5, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])]
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library))
|
||||
self.assertFalse(self.devices.exists())
|
||||
self.running = []
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
|
||||
self.running = [(5, ["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"])]
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
|
||||
|
||||
def test_a_drive_mapped_inside_the_volume_is_reused(self):
|
||||
self.devices.mkdir(parents=True)
|
||||
os.symlink(str(self.card / "Games"), self.devices / "g:")
|
||||
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "G:\\Battle.net")
|
||||
self.assertEqual(sorted(os.listdir(self.devices)), ["g:"])
|
||||
|
||||
def test_the_config_stores_the_drive_path_once(self):
|
||||
path = self.tmp / ("Steam/steamapps/compatdata/%s/pfx/drive_c/users/steamuser/AppData/Roaming/Battle.net/Battle.net.config"
|
||||
% BNET["APP_ID"])
|
||||
BNET["write_config"](self.root)
|
||||
self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library")
|
||||
self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Games\\Battle.net")
|
||||
self.assertIsNone(BNET["write_config"](self.root, str(self.library)))
|
||||
|
||||
def test_registered_paths_resolve_through_their_drive(self):
|
||||
BNET["install_path"](self.root, str(self.library))
|
||||
self.assertEqual(BNET["windows_path"](self.root, "D:/Games/Battle.net/World of Warcraft"),
|
||||
str(self.library / "World of Warcraft"))
|
||||
self.assertEqual(BNET["windows_path"](self.root, "Z:\\mnt\\card\\World of Warcraft"), "/mnt/card/World of Warcraft")
|
||||
self.assertEqual(BNET["windows_path"](self.root, "C:/Program Files (x86)/World of Warcraft"),
|
||||
os.path.join(BNET["drive_c"](self.root), "Program Files (x86)/World of Warcraft"))
|
||||
self.assertIsNone(BNET["windows_path"](self.root, "E:/Games/X"))
|
||||
self.assertIsNone(BNET["windows_path"](self.root, "D:/../etc"))
|
||||
self.assertEqual(BNET["windows_path"](self.root, "D:\\"), str(self.library.parent.parent))
|
||||
|
||||
def field(self, number, value):
|
||||
varint = BNET["encode_varint"]
|
||||
return varint(number << 3 | 2) + varint(len(value)) + value
|
||||
|
||||
def product(self, uid, folder, filler=b""):
|
||||
settings = self.field(1, folder.encode()) + self.field(2, b"us") + b"\x18\x02" + filler
|
||||
return self.field(1, self.field(1, uid.encode()) + self.field(2, uid.encode()) + self.field(3, settings)
|
||||
+ b"\x21" + bytes(8) + b"\x2d" + bytes(4))
|
||||
|
||||
def database(self, *products):
|
||||
path = Path(BNET["drive_c"](self.root)) / "ProgramData/Battle.net/Agent/product.db"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"".join(products) + self.field(7, b"tail"))
|
||||
path.chmod(0o600)
|
||||
return path
|
||||
|
||||
def test_games_registered_through_the_root_drive_move_to_their_volume_drive(self):
|
||||
game = self.library / "World of Warcraft"
|
||||
game.mkdir()
|
||||
other = self.tmp / "root/Games/Other"
|
||||
other.mkdir(parents=True)
|
||||
client = self.product("battle.net", "C:/Program Files (x86)/Battle.net")
|
||||
local = self.product("other", "Z:" + str(other))
|
||||
gone = self.product("gone", "Z:" + str(self.card / "Missing"))
|
||||
path = self.database(client, self.product("wow", "Z:" + str(game), bytes(200)), local, gone)
|
||||
self.assertTrue(BNET["move_installs"](self.root))
|
||||
self.assertEqual(path.read_bytes(), client + self.product("wow", "D:/Games/Battle.net/World of Warcraft", bytes(200))
|
||||
+ local + gone + self.field(7, b"tail"))
|
||||
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual(os.readlink(self.devices / "d:"), str(self.card))
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
|
||||
def test_registrations_stay_while_the_prefix_runs_or_the_database_is_unreadable(self):
|
||||
game = self.library / "World of Warcraft"
|
||||
game.mkdir()
|
||||
path = self.database(self.product("wow", "Z:" + str(game)))
|
||||
before = path.read_bytes()
|
||||
self.running = [(5, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.exe"])]
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
self.assertEqual(path.read_bytes(), before)
|
||||
self.running = []
|
||||
for broken in (before[:-3], b"\x0a\xff", b"\x0b\x01"):
|
||||
path.write_bytes(broken)
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
self.assertEqual(path.read_bytes(), broken)
|
||||
os.unlink(path)
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
|
||||
def test_a_database_written_while_it_was_being_read_is_left_as_written(self):
|
||||
game = self.library / "World of Warcraft"
|
||||
game.mkdir()
|
||||
path = self.database(self.product("wow", "Z:" + str(game)))
|
||||
newer = path.read_bytes() + self.field(7, b"newer")
|
||||
|
||||
def processes(pfx, proc="/proc"):
|
||||
path.write_bytes(newer)
|
||||
return []
|
||||
|
||||
with mock.patch.dict(BNET, {"wine_processes": processes}):
|
||||
self.assertFalse(BNET["move_installs"](self.root))
|
||||
self.assertEqual(path.read_bytes(), newer)
|
||||
self.assertTrue(BNET["move_installs"](self.root))
|
||||
|
||||
|
||||
class GamepadTest(Temp):
|
||||
def registry(self, *entries):
|
||||
rows = ["WINE REGISTRY Version 2"]
|
||||
@@ -772,7 +962,7 @@ class Harness(Temp):
|
||||
"stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))),
|
||||
"start": lambda exe, verb=None: self.calls.append(("start", os.path.basename(exe), verb)) or self.Proton(),
|
||||
"spawn": lambda program, verb, args=(): self.calls.append(("spawn", os.path.basename(program), verb, list(args))),
|
||||
"acquire": lambda folder=None: self.lock,
|
||||
"acquire": lambda folder=None: self.lock, "volume_root": lambda path: "/",
|
||||
"POLL": 0, "READY_SETTLE": 0, "GAME_GRACE": 0, "CLIENT_WAIT": 0,
|
||||
})
|
||||
patcher.start()
|
||||
@@ -1170,6 +1360,7 @@ class AgentTest(Temp):
|
||||
script = BNET["AGENT_SCRIPT"]
|
||||
self.assertIn("port = a(0), action = a(1), uid = a(2), product = a(3), dir = a(4)", script)
|
||||
self.assertIn("lang = a(5), country = a(6), region = a(7), out = a(8)", script)
|
||||
self.assertIn(r'''"game_dir":"' + dir.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '","geo''', script)
|
||||
self.assertIn('"--internalclienttools"', (BIN / "droiddeck-battlenet").read_text())
|
||||
|
||||
def test_the_driver_asks_blizzards_chinese_repository_for_chinese_installs(self):
|
||||
@@ -1230,6 +1421,40 @@ class AgentJobTest(Harness):
|
||||
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
|
||||
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
|
||||
|
||||
def test_an_install_on_another_volume_is_handed_over_by_its_drive_once_the_prefix_is_stopped(self):
|
||||
self.install()
|
||||
card = self.tmp / "card"
|
||||
folder = str(card / "Games/Battle.net/Warcraft Rumble")
|
||||
self.files = {".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004}),
|
||||
".game": json.dumps({"installed": True, "install_dir": "D:/Games/Battle.net/Warcraft Rumble", "local_version": "1",
|
||||
"binaries": {"game": {"relative_path": "WarcraftRumble.exe"}}})}
|
||||
self.states = [[(7, self.AGENT)]]
|
||||
events = []
|
||||
real_map = BNET["map_drive"]
|
||||
|
||||
def acquire(folder=None):
|
||||
events.append("lock")
|
||||
return self.lock
|
||||
|
||||
def stop(pfx):
|
||||
events.append(("stop", not self.lock.closed))
|
||||
self.states = [[]]
|
||||
return True
|
||||
|
||||
def map_drive(root, volume):
|
||||
events.append(("map", not self.lock.closed))
|
||||
return real_map(root, volume)
|
||||
|
||||
with mock.patch.dict(BNET, {"volume_root": lambda path: str(card), "stop_leftovers": stop, "map_drive": map_drive,
|
||||
"acquire": acquire}):
|
||||
code = BNET["agent_job"](self.root, "install", "gryphon", "gryphon", folder, "enUS", "USA", "US", poll=0)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(events, ["lock", ("stop", True), ("map", True)])
|
||||
self.assertTrue(self.lock.closed)
|
||||
cmd = self.started[0]
|
||||
self.assertEqual(cmd[cmd.index("--") + 6], "D:\\Games\\Battle.net\\Warcraft Rumble")
|
||||
self.assertEqual(os.readlink(os.path.join(BNET["dosdevices"](self.root), "d:")), str(card))
|
||||
|
||||
def test_an_agent_error_is_reported_with_its_code(self):
|
||||
self.install()
|
||||
self.files = {".json": json.dumps({"error": 2421, "progress": 0.0})}
|
||||
@@ -1257,6 +1482,138 @@ class AgentJobTest(Harness):
|
||||
self.assertEqual(BNET["agent_job"](self.root, "update", "gryphon", poll=0), 1)
|
||||
self.assertEqual(self.lines[-1][0], "ERROR")
|
||||
|
||||
def test_a_job_that_stops_moving_is_ended_as_stalled_and_its_agent_stopped(self):
|
||||
self.install()
|
||||
self.files = {".json": json.dumps({"state": 1003, "paused": True, "download_current": [10, 0, 0], "download_total": [99, 0, 0]})}
|
||||
killed = []
|
||||
stopped = []
|
||||
|
||||
class Hung:
|
||||
returncode = None
|
||||
|
||||
def __init__(self, cmd, **kwargs):
|
||||
base = cmd[-1][2:].replace("\\", "/")
|
||||
with open(base + ".json", "wb") as f:
|
||||
f.write(self_files[".json"].encode("utf-16"))
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
def kill(self):
|
||||
killed.append(True)
|
||||
|
||||
def wait(self):
|
||||
return -9
|
||||
|
||||
self_files = self.files
|
||||
with mock.patch.object(BNET["subprocess"], "Popen", Hung), \
|
||||
mock.patch.dict(BNET, {"wine_processes": lambda pfx: [(5, ["agent.exe"])], "stop": lambda p: stopped.append(p)}):
|
||||
code = BNET["agent_job"](self.root, "install", "s1", "s1", str(self.tmp / "S1"), "enUS", "USA", "US", poll=0, stall=0.05)
|
||||
self.assertEqual(code, 6)
|
||||
self.assertEqual(killed, [True])
|
||||
self.assertEqual(stopped, [[(5, ["agent.exe"])]])
|
||||
self.assertEqual(self.lines[-1], ("ERROR", "stalled"))
|
||||
|
||||
def test_a_stalled_job_leaves_a_game_or_client_in_the_prefix_running(self):
|
||||
self.install()
|
||||
self.files = {".json": json.dumps({"state": 1003, "download_current": [10, 0, 0], "download_total": [99, 0, 0]})}
|
||||
stopped = []
|
||||
calls = []
|
||||
|
||||
class Hung:
|
||||
returncode = None
|
||||
|
||||
def __init__(self, cmd, **kwargs):
|
||||
calls.append(True)
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
def wait(self):
|
||||
return -9
|
||||
|
||||
def processes(pfx):
|
||||
if not calls:
|
||||
return [(3, ["agent.exe"])]
|
||||
return [(3, ["agent.exe"]), (5, ["Agent.exe"]), (6, ["wineserver"]), (7, ["Wow.exe"])]
|
||||
|
||||
with mock.patch.object(BNET["subprocess"], "Popen", Hung), \
|
||||
mock.patch.dict(BNET, {"wine_processes": processes, "stop": lambda p: stopped.append(p)}):
|
||||
code = BNET["agent_job"](self.root, "install", "s1", "s1", str(self.tmp / "S1"), "enUS", "USA", "US", poll=0, stall=0.05)
|
||||
self.assertEqual(code, 6)
|
||||
self.assertEqual(stopped, [[(5, ["Agent.exe"])]])
|
||||
|
||||
def test_only_a_changing_rate_or_estimate_does_not_hold_off_the_stall(self):
|
||||
self.install()
|
||||
clock = [0.0]
|
||||
|
||||
class Spinning:
|
||||
returncode = None
|
||||
|
||||
def __init__(self, cmd, **kwargs):
|
||||
self.base = cmd[-1][2:].replace("\\", "/")
|
||||
self.polls = 0
|
||||
|
||||
def poll(self):
|
||||
self.polls += 1
|
||||
if self.polls > 10:
|
||||
raise AssertionError("the stall timeout never ended the job")
|
||||
clock[0] += 10
|
||||
with open(self.base + ".json", "wb") as f:
|
||||
f.write(json.dumps({"state": 1003, "download_current": [4, 0, 0], "download_total": [9, 0, 0],
|
||||
"download_rate": self.polls, "estimated_time_in_sec": self.polls}).encode("utf-16"))
|
||||
return None
|
||||
|
||||
def kill(self):
|
||||
pass
|
||||
|
||||
def wait(self):
|
||||
return -9
|
||||
|
||||
fake = mock.Mock(monotonic=lambda: clock[0], sleep=lambda s: None)
|
||||
with mock.patch.object(BNET["subprocess"], "Popen", Spinning), mock.patch.dict(BNET, {"time": fake, "stop": lambda p: None}):
|
||||
code = BNET["agent_job"](self.root, "update", "gryphon", poll=0, stall=25)
|
||||
self.assertEqual(code, 6)
|
||||
self.assertEqual(self.lines[-1], ("ERROR", "stalled"))
|
||||
|
||||
def test_a_moving_job_is_not_ended_as_stalled(self):
|
||||
self.install()
|
||||
done = json.dumps({"installed": True, "playable": True, "install_dir": "Z:/g", "local_version": "2"})
|
||||
clock = [0.0]
|
||||
|
||||
class Moving:
|
||||
returncode = 0
|
||||
|
||||
def __init__(self, cmd, **kwargs):
|
||||
self.base = cmd[-1][2:].replace("\\", "/")
|
||||
self.polls = 0
|
||||
|
||||
def poll(self):
|
||||
self.polls += 1
|
||||
clock[0] += 10
|
||||
with open(self.base + ".json", "wb") as f:
|
||||
f.write(json.dumps({"state": 1003, "download_current": [self.polls, 0, 0], "download_total": [9, 0, 0]}).encode("utf-16"))
|
||||
if self.polls < 6:
|
||||
return None
|
||||
with open(self.base + ".game", "wb") as f:
|
||||
f.write(done.encode("utf-16"))
|
||||
return 0
|
||||
|
||||
fake = mock.Mock(monotonic=lambda: clock[0], sleep=lambda s: None)
|
||||
with mock.patch.object(BNET["subprocess"], "Popen", Moving), mock.patch.dict(BNET, {"time": fake}):
|
||||
code = BNET["agent_job"](self.root, "update", "gryphon", poll=0, stall=15)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertNotIn(("ERROR", "stalled"), self.lines)
|
||||
|
||||
def test_only_a_real_job_reply_counts_as_started(self):
|
||||
script = BNET["AGENT_SCRIPT"]
|
||||
self.assertIn("if (state == 1000 || state == 1003 || job(s) && !complete) started = true;", script)
|
||||
self.assertIn('return /"state"\\s*:\\s*\\d+/.test(bare) || /"download_current"\\s*:/.test(bare);', script)
|
||||
self.assertIn('if (/"error"\\s*:\\s*[1-9]/.test(text)) return false;', script)
|
||||
|
||||
def test_the_driver_only_stops_once_the_agent_has_really_run(self):
|
||||
script = BNET["AGENT_SCRIPT"]
|
||||
self.assertIn("if (started && (state == 1004 || complete && /\"playable\"\\s*:\\s*true/.test(s))) break;", script)
|
||||
@@ -1352,5 +1709,12 @@ class AgentJobTest(Harness):
|
||||
self.assertEqual(calls, [("install", "gryphon", "gryphon", "/g/Rumble", "enUS", "USA", "US"), ("update", "wow_classic")])
|
||||
|
||||
|
||||
class BattleNetFormTest(Temp):
|
||||
def test_the_driver_waits_on_the_install_form_and_names_a_folder_that_is_taken(self):
|
||||
script = BNET["AGENT_SCRIPT"]
|
||||
self.assertIn(r'if (/"form"\s*:\s*\{/.test(s)) {', script)
|
||||
self.assertIn("the game folder already holds a game", script)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -58,11 +58,17 @@ class CiChecksTest(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
sudo = root / 'sudo'
|
||||
sudo.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$APT_LOG"\nexit "${APT_RESULT:-0}"\n')
|
||||
sudo.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$APT_LOG"\n'
|
||||
'for arg; do case "$arg" in Dir::Etc::sourcelist=*) '
|
||||
'grep -h "^URIs:" "${arg#*=}" >> "$APT_LOG.mirrors";; esac; done\n'
|
||||
'exit "${APT_RESULT:-0}"\n')
|
||||
sudo.chmod(0o755)
|
||||
query = root / 'dpkg-query'
|
||||
query.write_text('#!/bin/sh\nexit 1\n')
|
||||
query.chmod(0o755)
|
||||
dpkg = root / 'dpkg'
|
||||
dpkg.write_text('#!/bin/sh\necho "${DPKG_ARCH:-amd64}"\n')
|
||||
dpkg.chmod(0o755)
|
||||
log = root / 'apt.log'
|
||||
sources = root / 'ubuntu.sources'
|
||||
sources.write_text('URIs: http://mirror.invalid/ubuntu\n')
|
||||
@@ -71,8 +77,23 @@ class CiChecksTest(unittest.TestCase):
|
||||
installer = ROOT / 'tools/ci/install-ubuntu-packages.sh'
|
||||
result = subprocess.run(['bash', str(installer), 'qemu-user'], env=dict(env, APT_RESULT='17'))
|
||||
self.assertEqual(result.returncode, 17)
|
||||
self.assertEqual(len(log.read_text().splitlines()), 2)
|
||||
self.assertEqual(len(log.read_text().splitlines()), 3)
|
||||
mirrors = Path(str(log) + '.mirrors')
|
||||
self.assertEqual(mirrors.read_text().splitlines(), [
|
||||
'URIs: http://mirror.invalid/ubuntu',
|
||||
'URIs: https://archive.ubuntu.com/ubuntu',
|
||||
'URIs: https://mirrors.edge.kernel.org/ubuntu',
|
||||
])
|
||||
log.unlink()
|
||||
mirrors.unlink()
|
||||
result = subprocess.run(['bash', str(installer), 'qemu-user'], env=dict(env, APT_RESULT='17', DPKG_ARCH='arm64'))
|
||||
self.assertEqual(result.returncode, 17)
|
||||
self.assertEqual(mirrors.read_text().splitlines()[1:], [
|
||||
'URIs: https://ports.ubuntu.com/ubuntu-ports',
|
||||
'URIs: https://mirrors.ocf.berkeley.edu/ubuntu-ports',
|
||||
])
|
||||
log.unlink()
|
||||
mirrors.unlink()
|
||||
subprocess.run(['bash', str(installer), 'qemu-user'], env=env, check=True)
|
||||
update, install = log.read_text().splitlines()
|
||||
for command in (update, install):
|
||||
|
||||
@@ -121,6 +121,7 @@ step() { :; }
|
||||
bl_zram_scan() { :; }
|
||||
bl_memory_read() { :; }
|
||||
bl_client_pressure() { :; }
|
||||
bl_client_pressure_finish() { :; }
|
||||
bl_session_pressure() { :; }
|
||||
bl_client_can_pageout() { return 0; }
|
||||
bl_client_can_readback() { [ "${readback:-1}" = 1 ]; }
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import queue
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
|
||||
def clock_reset_command(control):
|
||||
script = (PRELOAD.parent / "overlay/usr/local/bin/droiddeck-session").read_text()
|
||||
start = script.index('if [ -z "${BL_INSIDE:-}" ]; then\n if [ "${BL_ZRAM:-0}"')
|
||||
end = script.index("\nfi", start) + len("\nfi")
|
||||
paths = {"/tmp/.bl-clock": shlex.quote(str(control)),
|
||||
"/tmp/.bl-zram": shlex.quote(str(control.parent / "zram"))}
|
||||
pattern = "|".join(re.escape(token) for token in paths)
|
||||
return 'BL_INSIDE=; BL_ZRAM=0; ' + re.sub(pattern, lambda match: paths[match.group(0)], script[start:end])
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <linux/futex.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/timerfd.h>
|
||||
@@ -36,12 +51,26 @@ static int64_t start;
|
||||
static void begin(void) { start = ns(CLOCK_BOOTTIME); }
|
||||
static void end(const char *name) { printf("%s %lld\n", name, (long long)((ns(CLOCK_BOOTTIME) - start) / 1000000LL)); }
|
||||
|
||||
static unsigned long long memory_probe(void) {
|
||||
static volatile unsigned char memory[4 * 1024 * 1024];
|
||||
unsigned long long checksum = 0;
|
||||
for (size_t i = 0; i < sizeof(memory); i += 4096) memory[i] = (unsigned char)(i / 4096 + 1);
|
||||
for (size_t i = 0; i < sizeof(memory); i += 4096) checksum += memory[i];
|
||||
return checksum;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
const int64_t wait = 60000000LL;
|
||||
printf("gap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL));
|
||||
struct timespec raw;
|
||||
syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &raw);
|
||||
printf("rawgap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ((int64_t)raw.tv_sec * 1000000000LL + raw.tv_nsec)) / 1000000LL));
|
||||
printf("memory %llu\n", memory_probe());
|
||||
if (getenv("CLOCK_PAUSE_WAIT")) { puts("ready"); fflush(stdout); getchar(); }
|
||||
if (getenv("CLOCK_PAUSE_WAIT")) {
|
||||
printf("livegap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL));
|
||||
printf("livememory %llu\n", memory_probe());
|
||||
}
|
||||
|
||||
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
pthread_condattr_t attr;
|
||||
@@ -124,14 +153,124 @@ class ClockPausePreloadTest(unittest.TestCase):
|
||||
self.assertGreaterEqual(paused[name], 50, name)
|
||||
self.assertLess(paused[name], 1000, name)
|
||||
|
||||
def test_other_programs_keep_the_real_clock(self):
|
||||
def test_program_without_preload_keeps_the_real_clock(self):
|
||||
plain = self.run_program(self.other, 0, preload=False)
|
||||
paused = self.run_program(self.other, SHIFT_MS)
|
||||
paused = self.run_program(self.other, SHIFT_MS, preload=False)
|
||||
self.assertAlmostEqual(paused["gap"], plain["gap"], delta=50)
|
||||
for name in ("cond_mono", "clockwait", "sem", "nanosleep", "timerfd", "futex"):
|
||||
self.assertGreaterEqual(paused[name], 50, name)
|
||||
self.assertLess(paused[name], 1000, name)
|
||||
|
||||
def test_every_session_program_stops_monotonic_clock_and_keeps_memory_access(self):
|
||||
plain = self.run_program(self.other, 0)
|
||||
paused = self.run_program(self.other, SHIFT_MS)
|
||||
self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50)
|
||||
self.assertAlmostEqual(paused["rawgap"] - plain["rawgap"], SHIFT_MS, delta=50)
|
||||
self.assertEqual(plain["memory"], 130560)
|
||||
self.assertEqual(paused["memory"], 130560)
|
||||
|
||||
def test_running_session_program_observes_pause_offset_update(self):
|
||||
self.check_running_offset_update(False)
|
||||
|
||||
def test_session_reset_preserves_live_guest_mapping(self):
|
||||
self.check_running_offset_update(True)
|
||||
|
||||
def check_running_offset_update(self, reset):
|
||||
self.control.write_bytes(struct.pack("<q", 0))
|
||||
env = dict(os.environ)
|
||||
env["LD_PRELOAD"] = str(self.preload)
|
||||
env["CLOCK_PAUSE_WAIT"] = "1"
|
||||
with tempfile.TemporaryFile(mode="w+") as errors:
|
||||
process = subprocess.Popen([str(self.other)], env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=errors, text=True)
|
||||
lines = queue.Queue()
|
||||
|
||||
def read_handshake():
|
||||
for _ in range(4):
|
||||
line = process.stdout.readline()
|
||||
lines.put(line)
|
||||
if not line:
|
||||
break
|
||||
|
||||
threading.Thread(target=read_handshake, daemon=True).start()
|
||||
try:
|
||||
handshake = []
|
||||
for _ in range(4):
|
||||
try:
|
||||
line = lines.get(timeout=5)
|
||||
except queue.Empty:
|
||||
line = ""
|
||||
if not line:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
errors.seek(0)
|
||||
self.fail(f"child handshake timed out or ended early (exit {process.returncode}): {errors.read()}")
|
||||
handshake.append(line.strip())
|
||||
self.assertEqual(handshake[3], "ready")
|
||||
self.assertTrue(handshake[0].startswith("gap "))
|
||||
initial_gap = int(handshake[0].split()[1])
|
||||
rawgap = handshake[1]
|
||||
memory = handshake[2]
|
||||
self.assertTrue(rawgap.startswith("rawgap "))
|
||||
self.assertEqual(memory, "memory 130560")
|
||||
if reset:
|
||||
inode = self.control.stat().st_ino
|
||||
subprocess.run(["bash", "-c", clock_reset_command(self.control)],
|
||||
check=True, timeout=5)
|
||||
self.assertEqual(self.control.stat().st_ino, inode)
|
||||
self.assertEqual(self.control.read_bytes(), struct.pack("<q", 0))
|
||||
with self.control.open("r+b") as control:
|
||||
control.write(struct.pack("<q", SHIFT_MS * 1000000))
|
||||
control.flush()
|
||||
process.stdin.write("\n")
|
||||
process.stdin.flush()
|
||||
output, _ = process.communicate(timeout=5)
|
||||
errors.seek(0)
|
||||
self.assertEqual(process.returncode, 0, errors.read())
|
||||
values = dict(line.split() for line in output.splitlines())
|
||||
self.assertAlmostEqual(int(values["livegap"]) - initial_gap, SHIFT_MS, delta=50)
|
||||
self.assertEqual(int(values["livememory"]), 130560)
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.communicate()
|
||||
|
||||
|
||||
class ClockResetCommandTest(unittest.TestCase):
|
||||
def test_reset_keeps_paths_with_spaces_and_shell_syntax_as_single_arguments(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
folder = root / "session dir; touch injected $(touch substituted) 'quoted'"
|
||||
folder.mkdir()
|
||||
control = folder / "clock"
|
||||
control.write_bytes(struct.pack("<q", 10_000_000_000) + b"tail")
|
||||
(folder / "zram").write_text("1")
|
||||
bystander = root / "session"
|
||||
bystander.write_text("keep")
|
||||
inode = control.stat().st_ino
|
||||
subprocess.run(["bash", "-c", clock_reset_command(control)], cwd=root, check=True, timeout=5)
|
||||
self.assertEqual(control.stat().st_ino, inode)
|
||||
self.assertEqual(control.read_bytes(), struct.pack("<q", 0) + b"tail")
|
||||
self.assertFalse((folder / "zram").exists())
|
||||
self.assertEqual(bystander.read_text(), "keep")
|
||||
self.assertEqual(sorted(path.name for path in root.iterdir()), sorted([folder.name, bystander.name]))
|
||||
|
||||
def test_reset_does_not_rewrite_placeholders_inside_substituted_paths(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
folder = root / "tmp/.bl-zram/$(touch injected)"
|
||||
folder.mkdir(parents=True)
|
||||
control = folder / "clock"
|
||||
control.write_bytes(struct.pack("<q", 10_000_000_000))
|
||||
(folder / "zram").write_text("1")
|
||||
inode = control.stat().st_ino
|
||||
subprocess.run(["bash", "-c", clock_reset_command(control)], cwd=root, check=True, timeout=5)
|
||||
self.assertEqual(control.stat().st_ino, inode)
|
||||
self.assertEqual(control.read_bytes(), struct.pack("<q", 0))
|
||||
self.assertFalse((folder / "zram").exists())
|
||||
self.assertEqual([path.name for path in root.iterdir()], ["tmp"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,69 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / 'agent/dd-lab-build'
|
||||
|
||||
|
||||
class LabBuildPackageTest(unittest.TestCase):
|
||||
def test_package_override_survives_app_handoff_without_its_environment(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
inbox = root / 'agent'
|
||||
inbox.mkdir()
|
||||
cache = root / '.cache'
|
||||
env = {**os.environ, 'HOME': tmp, 'DD_AGENT': '1',
|
||||
'DD_AGENT_INBOX': str(inbox), 'DROIDDECK_PACKAGE': 'com.example.target'}
|
||||
env.pop('DD_LAB_DETACHED', None)
|
||||
child = subprocess.Popen(['bash', str(SCRIPT), '--prepare'], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
request = inbox / 'lab-request'
|
||||
deadline = time.monotonic() + 10
|
||||
while not request.exists() and child.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
self.assertTrue(request.exists())
|
||||
payload = json.loads(request.read_text())
|
||||
self.assertEqual(['--prepare', '--package=com.example.target'], payload['args'])
|
||||
progress = cache / 'dd-lab-build.json'
|
||||
progress.write_text('{"stage":"prepared"}')
|
||||
stdout, stderr = child.communicate(timeout=10)
|
||||
self.assertEqual(0, child.returncode, stdout + stderr)
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.kill()
|
||||
child.communicate()
|
||||
|
||||
bin_dir = root / 'bin'
|
||||
bin_dir.mkdir()
|
||||
(bin_dir / 'adb').write_text('#!/bin/sh\nexit 0\n')
|
||||
(bin_dir / 'python3').write_text(
|
||||
'#!/bin/sh\nprintf "%s" "$DROIDDECK_PACKAGE" > "$HOME/selected-package"\nexit 1\n')
|
||||
for tool in bin_dir.iterdir():
|
||||
tool.chmod(0o755)
|
||||
env.pop('DROIDDECK_PACKAGE')
|
||||
env['DD_LAB_DETACHED'] = '1'
|
||||
env['PATH'] = str(bin_dir) + os.pathsep + env['PATH']
|
||||
result = subprocess.run(['bash', str(SCRIPT), *payload['args']], env=env,
|
||||
capture_output=True, text=True, timeout=10, cwd=SCRIPT.parents[2])
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertIn('could not read DroidDeck', result.stderr)
|
||||
self.assertEqual('com.example.target', (root / 'selected-package').read_text())
|
||||
|
||||
def test_invalid_packages_are_rejected_before_handoff(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
inbox = Path(tmp) / 'agent'
|
||||
inbox.mkdir()
|
||||
for package in ('bad;touch injected', '../other', '', 'com.example/other'):
|
||||
with self.subTest(package=package):
|
||||
env = {**os.environ, 'HOME': tmp, 'DD_AGENT': '1', 'DD_AGENT_INBOX': str(inbox)}
|
||||
result = subprocess.run(['bash', str(SCRIPT), '--package=' + package], env=env,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertNotEqual(0, result.returncode)
|
||||
self.assertIn('invalid Android package', result.stderr)
|
||||
self.assertFalse((inbox / 'lab-request').exists())
|
||||
@@ -0,0 +1,245 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
FAKE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int answer(int fd) {
|
||||
char link[32], path[4096];
|
||||
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
|
||||
long n = syscall(SYS_readlinkat, AT_FDCWD, link, path, sizeof(path) - 1);
|
||||
path[n > 0 ? n : 0] = '\0';
|
||||
if (strstr(path, "/card/")) return ENOTSUP;
|
||||
if (strstr(path, "/denied/")) return EACCES;
|
||||
return ENODATA;
|
||||
}
|
||||
|
||||
ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) {
|
||||
(void)name; (void)value; (void)size;
|
||||
errno = answer(fd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) {
|
||||
(void)name; (void)value; (void)size; (void)flags;
|
||||
int error = answer(fd);
|
||||
if (error == ENODATA) return 0;
|
||||
errno = error;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int fremovexattr(int fd, const char *name) {
|
||||
(void)name;
|
||||
errno = answer(fd);
|
||||
return -1;
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/xattr.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *error(void) {
|
||||
return errno == ENOTSUP ? "unsupported" : errno == ENODATA ? "none" : errno == ERANGE ? "range" :
|
||||
errno == EACCES ? "denied" : "other";
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
for (int i = 1; i < argc; i++) {
|
||||
const char *op = argv[i];
|
||||
if (!strcmp(op, "unlink") || !strcmp(op, "rmdir")) {
|
||||
const char *path = argv[++i];
|
||||
printf("%s\n", (op[0] == 'u' ? unlink(path) : rmdir(path)) == 0 ? "ok" : "failed");
|
||||
continue;
|
||||
}
|
||||
if (!strcmp(op, "remove-path")) {
|
||||
printf("%s\n", remove(argv[++i]) == 0 ? "ok" : "failed");
|
||||
continue;
|
||||
}
|
||||
if (!strcmp(op, "rename")) {
|
||||
const char *from = argv[++i], *to = argv[++i];
|
||||
printf("%s\n", rename(from, to) == 0 ? "ok" : "failed");
|
||||
continue;
|
||||
}
|
||||
int fd = open(argv[++i], O_RDONLY);
|
||||
char value[64];
|
||||
if (!strcmp(op, "set")) {
|
||||
const char *text = argv[++i];
|
||||
errno = 1234;
|
||||
int result = fsetxattr(fd, "user.wine.sd", text, strlen(text), 0);
|
||||
printf("%s\n", result == 0 ? errno == 1234 ? "ok" : "errno" : error());
|
||||
} else if (!strcmp(op, "get")) {
|
||||
ssize_t n = fgetxattr(fd, "user.wine.sd", value, sizeof(value));
|
||||
if (n < 0) printf("%s\n", error());
|
||||
else printf("=%.*s\n", (int)n, value);
|
||||
} else if (!strcmp(op, "size")) {
|
||||
ssize_t n = fgetxattr(fd, "user.wine.sd", NULL, 0);
|
||||
if (n < 0) printf("%s\n", error());
|
||||
else printf("%d\n", (int)n);
|
||||
} else if (!strcmp(op, "short")) {
|
||||
ssize_t n = fgetxattr(fd, "user.wine.sd", value, 2);
|
||||
printf("%s\n", n < 0 ? error() : "read");
|
||||
} else if (!strcmp(op, "remove")) {
|
||||
errno = 1234;
|
||||
int result = fremovexattr(fd, "user.wine.sd");
|
||||
printf("%s\n", result == 0 ? errno == 1234 ? "ok" : "errno" : error());
|
||||
} else if (!strcmp(op, "other")) {
|
||||
ssize_t n = fgetxattr(fd, "user.other", value, sizeof(value));
|
||||
printf("%s\n", n < 0 ? error() : "read");
|
||||
}
|
||||
close(fd);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class DescriptorPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.build_dir = tempfile.TemporaryDirectory()
|
||||
build = Path(cls.build_dir.name)
|
||||
(build / "fake.c").write_text(FAKE)
|
||||
(build / "program.c").write_text(PROGRAM)
|
||||
cls.preload = build / "libblsession.so"
|
||||
cls.fake = build / "fake.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload),
|
||||
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.fake), str(build / "fake.c")], check=True)
|
||||
cls.wineserver = build / "wineserver"
|
||||
subprocess.run(["cc", "-O2", "-o", str(cls.wineserver), str(build / "program.c")], check=True)
|
||||
cls.other = build / "wine64-preloader"
|
||||
shutil.copy(cls.wineserver, cls.other)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.build_dir.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.dir = Path(os.path.realpath(self.temp.name))
|
||||
self.prefix = self.dir / "prefix"
|
||||
self.prefix.mkdir()
|
||||
self.store = self.prefix / ".droiddeck-descriptors"
|
||||
for kind in ("card", "disk", "denied"):
|
||||
(self.dir / kind / "game").mkdir(parents=True)
|
||||
(self.dir / kind / "game" / "file").write_text("x")
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def path(self, *parts):
|
||||
return str(self.dir.joinpath(*parts))
|
||||
|
||||
def run_as(self, program, *args, prefix=True):
|
||||
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.preload, self.fake))
|
||||
env.pop("WINEPREFIX", None)
|
||||
if prefix:
|
||||
env["WINEPREFIX"] = str(self.prefix)
|
||||
result = subprocess.run([str(program), *args], env=env, capture_output=True, text=True, check=True)
|
||||
return result.stdout.split()
|
||||
|
||||
def server(self, *args, **kwargs):
|
||||
return self.run_as(self.wineserver, *args, **kwargs)
|
||||
|
||||
def test_a_descriptor_is_kept_where_the_volume_cannot_store_it(self):
|
||||
file, folder = self.path("card", "game", "file"), self.path("card", "game")
|
||||
self.assertEqual(["none", "ok", "ok"], self.server("get", file, "set", file, "one", "set", folder, "two"))
|
||||
self.assertEqual(["=one", "3", "=two"], self.server("get", file, "size", file, "get", folder))
|
||||
|
||||
def test_a_descriptor_is_replaced_and_removed(self):
|
||||
file = self.path("card", "game", "file")
|
||||
self.assertEqual(["ok", "ok", "=longer"], self.server("set", file, "one", "set", file, "longer", "get", file))
|
||||
self.assertEqual(["range", "ok", "none", "none"], self.server("short", file, "remove", file, "get", file, "remove", file))
|
||||
|
||||
def test_a_volume_that_stores_descriptors_is_left_alone(self):
|
||||
file = self.path("disk", "game", "file")
|
||||
self.assertEqual(["ok", "none", "none"], self.server("set", file, "one", "get", file, "remove", file))
|
||||
self.assertFalse(self.store.exists())
|
||||
|
||||
def test_other_failures_keep_their_error(self):
|
||||
file = self.path("denied", "game", "file")
|
||||
self.assertEqual(["denied", "denied", "denied"], self.server("set", file, "one", "get", file, "remove", file))
|
||||
self.assertFalse(self.store.exists())
|
||||
|
||||
def test_other_programs_and_other_attributes_are_unchanged(self):
|
||||
file = self.path("card", "game", "file")
|
||||
self.assertEqual(["unsupported", "unsupported", "unsupported"],
|
||||
self.run_as(self.other, "set", file, "one", "get", file, "remove", file))
|
||||
self.assertEqual(["ok", "unsupported"], self.server("set", file, "one", "other", file))
|
||||
self.assertEqual(["unsupported"], self.run_as(self.other, "get", file))
|
||||
|
||||
def test_nothing_is_kept_without_a_prefix(self):
|
||||
file = self.path("card", "game", "file")
|
||||
self.assertEqual(["unsupported", "unsupported", "unsupported"],
|
||||
self.server("set", file, "one", "get", file, "remove", file, prefix=False))
|
||||
|
||||
def test_a_deleted_file_loses_its_descriptor(self):
|
||||
file, folder = self.path("card", "game", "file"), self.path("card", "game")
|
||||
self.assertEqual(["ok", "ok", "ok"], self.server("set", file, "one", "set", folder, "two", "unlink", file))
|
||||
Path(file).write_text("x")
|
||||
self.assertEqual(["none", "ok", "ok"], self.server("get", file, "unlink", file, "rmdir", folder))
|
||||
Path(folder).mkdir()
|
||||
self.assertEqual(["none"], self.server("get", folder))
|
||||
|
||||
def test_a_removed_file_or_folder_loses_its_descriptor(self):
|
||||
file, folder = self.path("card", "game", "file"), self.path("card", "game")
|
||||
self.assertEqual(["ok", "ok", "ok", "ok"],
|
||||
self.server("set", file, "one", "set", folder, "two", "remove-path", file, "remove-path", folder))
|
||||
Path(folder).mkdir()
|
||||
Path(file).write_text("x")
|
||||
self.assertEqual(["none", "none"], self.server("get", folder, "get", file))
|
||||
|
||||
def test_a_file_deleted_through_a_link_loses_its_descriptor(self):
|
||||
file = self.path("card", "game", "file")
|
||||
os.symlink(self.path("card"), self.path("drive"))
|
||||
self.assertEqual(["ok", "ok"], self.server("set", file, "one", "unlink", self.path("drive", "game", "file")))
|
||||
Path(file).write_text("x")
|
||||
self.assertEqual(["none"], self.server("get", file))
|
||||
|
||||
def test_a_descriptor_follows_a_rename(self):
|
||||
file, moved = self.path("card", "game", "file"), self.path("card", "game", "moved")
|
||||
self.assertEqual(["ok", "ok", "=one"], self.server("set", file, "one", "rename", file, moved, "get", moved))
|
||||
Path(file).write_text("x")
|
||||
self.assertEqual(["none", "ok", "none"], self.server("get", file, "rename", file, moved, "get", moved))
|
||||
|
||||
def test_descriptors_follow_a_renamed_folder(self):
|
||||
file, folder, moved = self.path("card", "game", "file"), self.path("card", "game"), self.path("card", "moved")
|
||||
self.assertEqual(["ok", "ok", "ok"], self.server("set", file, "one", "set", folder, "two", "rename", folder, moved))
|
||||
self.assertEqual(["=two", "=one"], self.server("get", moved, "get", self.path("card", "moved", "file")))
|
||||
Path(folder).mkdir()
|
||||
(Path(folder) / "file").write_text("x")
|
||||
self.assertEqual(["none", "none"], self.server("get", folder, "get", file))
|
||||
|
||||
def test_deletes_outside_the_store_cost_nothing_before_it_exists(self):
|
||||
file = self.path("disk", "game", "file")
|
||||
self.assertEqual(["ok"], self.server("unlink", file))
|
||||
self.assertFalse(self.store.exists())
|
||||
|
||||
def test_a_name_too_long_to_keep_reports_no_support(self):
|
||||
long_file = self.path("card", "game", "n" * 254)
|
||||
Path(long_file).write_text("x")
|
||||
self.assertEqual(["unsupported", "unsupported"], self.server("set", long_file, "one", "get", long_file))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -136,6 +136,30 @@ class CommandTest(Temp):
|
||||
self.assertEqual(OPEN["command"](script, [], "x86 script")[0],
|
||||
[OPEN["FEX"], "run", "--mode", "on", "--for", str(self.tmp), "--", "/bin/sh", script])
|
||||
|
||||
def test_a_store_games_exe_runs_through_its_launcher(self):
|
||||
exe, launcher = str(self.tmp / "game.exe"), str(self.tmp / "launch.bat")
|
||||
with mock.patch.dict(OPEN, {"store_launcher": lambda path: launcher if path == exe else None,
|
||||
"exe_prefix": lambda path: ["--prefix", "4242", "--compatdata", "/c/4242"]}):
|
||||
keep = ["--prefix", "4242", "--compatdata", "/c/4242"]
|
||||
self.assertEqual(OPEN["command"](exe, [], "windows")[0], [OPEN["PROTON_RUN"]] + keep + [launcher])
|
||||
self.assertEqual(OPEN["command"](exe, [], "windows", True)[0],
|
||||
[OPEN["PROTON_RUN"], "--window"] + keep + [launcher])
|
||||
self.assertEqual(OPEN["command"](exe, ["-x"], "windows")[0], [OPEN["PROTON_RUN"], exe, "-x"])
|
||||
other = str(self.tmp / "other.exe")
|
||||
self.assertEqual(OPEN["command"](other, [], "windows")[0], [OPEN["PROTON_RUN"], other])
|
||||
|
||||
def test_a_store_games_launcher_keeps_the_exes_prefix(self):
|
||||
exe = self.tmp / "game.exe"
|
||||
exe.write_text("x")
|
||||
root = str(self.tmp / "steam")
|
||||
with mock.patch.dict(os.environ, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": root}), \
|
||||
mock.patch.dict(OPEN, {"PROTON_RUN": str(BIN / "droiddeck-proton-run"),
|
||||
"store_launcher": lambda path: str(self.tmp / "launch.bat")}):
|
||||
command = OPEN["command"](str(exe), [], "windows")[0]
|
||||
located = RUN["locate"](str(exe), root)
|
||||
self.assertEqual(command[1:5], ["--prefix", located.appid, "--compatdata", located.compatdata])
|
||||
self.assertEqual(str(RUN["own_id"](str(exe))), str(RUN["locate"](str(exe), root).appid))
|
||||
|
||||
def test_a_native_program_on_noexec_storage_runs_from_a_copy(self):
|
||||
program = self.write("storage/tool", elf(183))
|
||||
x86 = self.write("storage/game.x86_64", elf(62))
|
||||
@@ -737,6 +761,20 @@ class ProtonRunTest(Temp):
|
||||
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed))
|
||||
self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists())
|
||||
|
||||
def test_a_launcher_run_keeps_the_resolved_compatdata_folder(self):
|
||||
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
|
||||
signed = self.root / "steamapps/compatdata/-1561598272"
|
||||
signed.mkdir(parents=True)
|
||||
other = self.tmp / "Library2/steamapps/compatdata/555"
|
||||
other.mkdir(parents=True)
|
||||
for compatdata, appid in ((signed, "2733369024"), (other, "555")):
|
||||
with self.subTest(compatdata=str(compatdata)):
|
||||
code, calls, dirs = self.run_main(["--prefix", appid, "--compatdata", str(compatdata), str(bat)])
|
||||
self.assertIsNone(code)
|
||||
self.assertEqual(calls[0][2]["STEAM_COMPAT_DATA_PATH"], str(compatdata))
|
||||
code, calls, dirs = self.run_main(["--prefix", "555", str(bat)])
|
||||
self.assertEqual(calls[0][2]["STEAM_COMPAT_DATA_PATH"], str(self.root / "steamapps/compatdata/555"))
|
||||
|
||||
def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self):
|
||||
signed = self.root / "steamapps/compatdata/-1561598272"
|
||||
signed.mkdir(parents=True)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
|
||||
LINUXFS = Path(__file__).resolve().parents[1] / 'linuxfs'
|
||||
DESKTOP = (LINUXFS / 'desktop/droiddeck-desktop').read_text()
|
||||
SESSION = (LINUXFS / 'overlay/usr/local/bin/droiddeck-session').read_text()
|
||||
BOTTOM_DESKTOP = (LINUXFS / 'overlay/usr/local/bin/droiddeck-bottom-desktop').read_text()
|
||||
BOTTOM_SESSION = (
|
||||
Path(__file__).resolve().parents[2]
|
||||
/ 'app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt'
|
||||
).read_text()
|
||||
HELPER = '/usr/local/bin/droiddeck-pipewire'
|
||||
|
||||
|
||||
class DesktopPipeWireTest(unittest.TestCase):
|
||||
def run_lifecycle_block(self, start, end, bottom, start_status=0, probe_env=False):
|
||||
block = DESKTOP[DESKTOP.index(start):DESKTOP.index(end, DESKTOP.index(start))]
|
||||
block = block.replace(HELPER, 'pipewire')
|
||||
script = '''
|
||||
pipewire() {
|
||||
if [ "$1" = env ]; then
|
||||
printf 'export PW_ENV=set\\n'
|
||||
else
|
||||
printf 'call:%s\\n' "$1"
|
||||
[ "$1" != start ] || return "$PW_START_STATUS"
|
||||
fi
|
||||
}
|
||||
''' + block + ('echo "env:${PW_ENV:-unset}"\n' if probe_env else '')
|
||||
environment = dict(os.environ, BL_BOTTOM_DESKTOP='1' if bottom else '0',
|
||||
PW_START_STATUS=str(start_status))
|
||||
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True,
|
||||
text=True, timeout=5)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def test_desktop_serves_pipewire_before_plasma_and_stops_it_after(self):
|
||||
start = DESKTOP.index(HELPER + ' start')
|
||||
env = DESKTOP.index(HELPER + ' env')
|
||||
plasma = DESKTOP.index('dbus-run-session -- startplasma-wayland')
|
||||
stop = DESKTOP.index(HELPER + ' stop')
|
||||
self.assertLess(start, env)
|
||||
self.assertLess(env, plasma)
|
||||
self.assertLess(plasma, stop)
|
||||
self.assertLess(stop, DESKTOP.index('droiddeck-steam-launch bigpicture'))
|
||||
|
||||
def test_steam_session_keeps_its_pipewire_startup(self):
|
||||
self.assertEqual(1, SESSION.count(HELPER + ' start'))
|
||||
self.assertIn('if [ "$mode" = steam ]; then\n if ' + HELPER + ' start', SESSION)
|
||||
|
||||
def test_bottom_desktop_starts_and_stops_its_pipewire_service(self):
|
||||
self.assertIn('export BL_BOTTOM_DESKTOP=1', BOTTOM_DESKTOP)
|
||||
self.assertLess(BOTTOM_DESKTOP.index('export BL_BOTTOM_DESKTOP=1'),
|
||||
BOTTOM_DESKTOP.index('exec /usr/local/bin/droiddeck-desktop'))
|
||||
self.assertIn('File(context.filesDir, ".wayland-rt-bottom")', BOTTOM_SESSION)
|
||||
self.assertNotIn('if [ "${BL_BOTTOM_DESKTOP:-0}" != 1 ]; then', DESKTOP)
|
||||
for bottom in (False, True):
|
||||
self.assertEqual(['call:start'], self.run_lifecycle_block(
|
||||
'if ' + HELPER + ' start',
|
||||
'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom))
|
||||
self.assertEqual(['call:stop'], self.run_lifecycle_block(
|
||||
HELPER + ' stop',
|
||||
'echo "== droiddeck-desktop: Plasma ended ($rc)"', bottom))
|
||||
|
||||
def test_successful_start_exports_the_client_environment(self):
|
||||
for bottom in (False, True):
|
||||
self.assertEqual(['call:start', 'env:set'], self.run_lifecycle_block(
|
||||
'if ' + HELPER + ' start',
|
||||
'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom, probe_env=True))
|
||||
|
||||
def test_failed_start_reports_it_and_leaves_the_environment_alone(self):
|
||||
for bottom in (False, True):
|
||||
self.assertEqual(
|
||||
['call:start', '== pipewire: not running; screen capture has no picture', 'env:unset'],
|
||||
self.run_lifecycle_block(
|
||||
'if ' + HELPER + ' start',
|
||||
'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom,
|
||||
start_status=1, probe_env=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -83,9 +83,25 @@ int inotify_add_watch(int fd, const char *path, uint32_t mask) {
|
||||
errno = ENOSPC;
|
||||
return -1;
|
||||
}
|
||||
if (getenv("NESTED") && (mask & IN_ONLYDIR)) {
|
||||
static DIR *(*uncounted)(const char *);
|
||||
if (!uncounted) uncounted = dlsym(RTLD_NEXT, "opendir");
|
||||
mkdir(path, 0755);
|
||||
DIR *d = uncounted("/proc/self/fd");
|
||||
while (d && readdir(d)) {}
|
||||
if (d) closedir(d);
|
||||
}
|
||||
return next(fd, path, mask);
|
||||
}
|
||||
|
||||
int remove(const char *path) {
|
||||
static int (*next)(const char *);
|
||||
if (!next) next = dlsym(RTLD_NEXT, "remove");
|
||||
if (!getenv("NESTED")) return next(path);
|
||||
if (unlink(path) == 0) return 0;
|
||||
return errno == EISDIR ? rmdir(path) : -1;
|
||||
}
|
||||
|
||||
int statfs(const char *path, struct statfs *out) {
|
||||
static int (*next)(const char *, struct statfs *);
|
||||
if (!next) next = dlsym(RTLD_NEXT, "statfs");
|
||||
@@ -337,9 +353,9 @@ class DirCachePreloadTest(unittest.TestCase):
|
||||
environment.update(env or {})
|
||||
return environment
|
||||
|
||||
def run_program(self, *args, program=None, env=None):
|
||||
def run_program(self, *args, program=None, env=None, timeout=60):
|
||||
result = subprocess.run([str(program or self.steam), *map(str, args)], env=self.environment(env),
|
||||
capture_output=True, text=True, check=True, timeout=60)
|
||||
capture_output=True, text=True, check=True, timeout=timeout)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def run_paused(self, *args, between, env=None):
|
||||
@@ -675,6 +691,20 @@ class DirCachePreloadTest(unittest.TestCase):
|
||||
env={"BL_NO_DIR_CACHE": "1"})
|
||||
self.assertEqual(["-1 2", "-1 2", "2"], out[1:])
|
||||
|
||||
def test_a_preload_below_calling_back_while_a_folder_is_watched_does_not_hang(self):
|
||||
common = self.lib / "common/Game"
|
||||
common.mkdir(parents=True)
|
||||
(common / "game.exe").touch()
|
||||
out = self.run_program("list", self.staging, "list", common, "list", common, "opens",
|
||||
env={"NESTED": "1"}, timeout=20)
|
||||
self.assertEqual(["a.bundle,b.bundle", "game.exe", "game.exe", "2"], out)
|
||||
|
||||
def test_a_preload_below_removing_through_unlink_does_not_hang(self):
|
||||
s = self.staging
|
||||
out = self.run_program("list", s, "remove", s / "a.bundle", "list", s, "raw", s, "opens",
|
||||
env={"NESTED": "1"}, timeout=20)
|
||||
self.assertEqual(["a.bundle,b.bundle", "b.bundle", "b.bundle", "1"], out)
|
||||
|
||||
def test_can_be_turned_off(self):
|
||||
out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"BL_NO_DIR_CACHE": "1"})
|
||||
self.assertEqual("2", out[-1])
|
||||
|
||||
@@ -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)
|
||||
@@ -175,17 +175,27 @@ class RuntimeExtractTest(EpicTestCase):
|
||||
old = self.state / "app/0.1"
|
||||
old.mkdir(parents=True)
|
||||
|
||||
def extract_app(image, dest):
|
||||
os.makedirs(os.path.join(dest, "usr/bin"))
|
||||
Path(dest, "AppRun").write_text("run")
|
||||
Path(dest, "usr/bin/EpicGamesLauncher").write_text("bin")
|
||||
layers = []
|
||||
|
||||
def extract_app(image, dest, desktop=()):
|
||||
layers.append(list(desktop))
|
||||
os.makedirs(os.path.join(dest, "usr/bin"))
|
||||
os.makedirs(os.path.join(dest, "desktop/usr/lib/x86_64-linux-gnu"))
|
||||
Path(dest, "usr/bin/EpicGamesLauncher").write_text("bin")
|
||||
Path(dest, "desktop/usr/lib/x86_64-linux-gnu/libwebkit2gtk-4.1.so.0").write_text("webkit")
|
||||
|
||||
package = self.tmp / "libwebkit.deb"
|
||||
package.write_bytes(b"x")
|
||||
with mock.patch.dict(G, {"extract_app": extract_app, "fex_tool": lambda request=False: {"bin": "/fex", "server": "/s"}}), \
|
||||
mock.patch("sys.stdout", new_callable=io.StringIO) as out:
|
||||
image = self.tmp / "image"
|
||||
image.write_bytes(b"x")
|
||||
with self.assertRaises(G["Failure"]):
|
||||
G["install"]({"app": str(image), "app-version": "0.95.2+g1", "runtime": str(tarball),
|
||||
"runtime-version": "4.0.1", "gles": str(deb), "desktop": [str(self.tmp / "missing.deb")]})
|
||||
code = G["install"]({"app": str(image), "app-version": "0.95.2+g1", "runtime": str(tarball),
|
||||
"runtime-version": "4.0.1", "gles": str(deb)})
|
||||
"runtime-version": "4.0.1", "gles": str(deb), "desktop": [str(package)]})
|
||||
self.assertEqual([[str(package)]], layers)
|
||||
self.assertEqual(0, code)
|
||||
report = json.loads(out.getvalue())
|
||||
self.assertTrue(report["installed"])
|
||||
@@ -197,6 +207,147 @@ class RuntimeExtractTest(EpicTestCase):
|
||||
self.assertTrue((self.state / "app/0.95.2+g1/.droiddeck-ready").is_file())
|
||||
|
||||
|
||||
def deb(path, entries, compression="gz"):
|
||||
data = io.BytesIO()
|
||||
with tarfile.open(fileobj=data, mode="w:" + compression) as archive:
|
||||
for entry in entries:
|
||||
tar_add(archive, *entry[:1], **entry[1])
|
||||
path.write_bytes(ar([("debian-binary", b"2.0\n"), ("control.tar.xz", b"c"), ("data.tar." + compression, data.getvalue())]))
|
||||
return path
|
||||
|
||||
|
||||
class LauncherDebTest(EpicTestCase):
|
||||
def launcher(self, extra=()):
|
||||
return deb(self.tmp / "EpicGamesLauncher-x86_64.deb", [
|
||||
("./usr", {"kind": "dir"}),
|
||||
("./usr/bin/EpicGamesLauncher", {"data": b"egl", "mode": 0o755}),
|
||||
("./usr/lib/epic-games-launcher/libEOSSDK-Linux-Shipping.so", {"data": b"eos"}),
|
||||
("./usr/share/icons/hicolor/256x256@2/apps/EpicGamesLauncher.png", {"data": b"png"}),
|
||||
("./usr/share/applications/epic-games-launcher.desktop", {"data": b"[Desktop Entry]\n"}),
|
||||
("./usr/bin/egl", {"link": "/usr/bin/EpicGamesLauncher"}),
|
||||
("../escape", {"data": b"x"}),
|
||||
*extra,
|
||||
])
|
||||
|
||||
def webkit(self):
|
||||
return deb(self.tmp / "libwebkit2gtk-4.1-0_amd64.deb", [
|
||||
("./usr/lib/x86_64-linux-gnu/libwebkit2gtk-4.1.so.0.19.1", {"data": b"webkit"}),
|
||||
("./usr/lib/x86_64-linux-gnu/libwebkit2gtk-4.1.so.0", {"link": "libwebkit2gtk-4.1.so.0.19.1"}),
|
||||
("./usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/WebKitNetworkProcess", {"data": b"net", "mode": 0o755}),
|
||||
("./usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/injected-bundle/libwebkit2gtkinjectedbundle.so", {"data": b"bundle"}),
|
||||
("./usr/share/glib-2.0/schemas/org.gnome.GWeather4.gschema.xml", {"data": b"schema"}),
|
||||
("./usr/share/doc/libwebkit2gtk-4.1-0/copyright", {"data": b"c"}),
|
||||
("./usr/share/locale/fr/LC_MESSAGES/WebKitGTK-4.1.mo", {"data": b"fr"}),
|
||||
], "xz")
|
||||
|
||||
def test_the_launcher_and_its_desktop_layer_come_out_of_debs(self):
|
||||
dest = self.state / "app/0.113.0+g1"
|
||||
G["extract_app"](str(self.launcher()), str(dest), [str(self.webkit())])
|
||||
self.assertEqual(b"egl", (dest / "usr/bin/EpicGamesLauncher").read_bytes())
|
||||
self.assertTrue(os.access(dest / "usr/bin/EpicGamesLauncher", os.X_OK))
|
||||
self.assertEqual(b"eos", (dest / "usr/lib/epic-games-launcher/libEOSSDK-Linux-Shipping.so").read_bytes())
|
||||
self.assertEqual("EpicGamesLauncher", os.readlink(dest / "usr/bin/egl"))
|
||||
self.assertEqual(b"png", (dest / "epic-games-launcher.png").read_bytes())
|
||||
libs = dest / "desktop/usr/lib/x86_64-linux-gnu"
|
||||
self.assertEqual(b"webkit", (libs / "libwebkit2gtk-4.1.so.0").read_bytes())
|
||||
self.assertEqual(b"net", (libs / "webkit2gtk-4.1/WebKitNetworkProcess").read_bytes())
|
||||
self.assertEqual(b"schema", (dest / "desktop/usr/share/glib-2.0/schemas/org.gnome.GWeather4.gschema.xml").read_bytes())
|
||||
self.assertFalse((dest / "desktop/usr/share/doc").exists())
|
||||
self.assertFalse((self.state / "app/escape").exists())
|
||||
self.assertFalse((self.state / "app/0.113.0+g1.staging").exists())
|
||||
self.assertTrue(G["app_complete"](str(dest)))
|
||||
self.assertEqual(str(dest / "usr/bin/EpicGamesLauncher"), G["app_command"](str(dest)))
|
||||
self.assertEqual(str(libs), G["desktop_libs"](str(dest)))
|
||||
|
||||
def test_archive_symlinks_cannot_redirect_the_desktop_layer_or_icon(self):
|
||||
outside = self.tmp / "outside"
|
||||
outside.mkdir()
|
||||
dest = self.state / "app/0.113.0+g1"
|
||||
escape = os.path.relpath(outside, Path(str(dest) + ".staging"))
|
||||
launcher = self.launcher([("./desktop", {"link": escape}),
|
||||
("./epic-games-launcher.png", {"link": escape + "/target"})])
|
||||
with self.assertRaises(G["Failure"]) as caught:
|
||||
G["extract_app"](str(launcher), str(dest), [str(self.webkit())])
|
||||
self.assertEqual("app-extract", str(caught.exception))
|
||||
self.assertFalse((outside / "usr").exists())
|
||||
self.assertFalse((outside / "target").exists())
|
||||
|
||||
icon_dest = self.state / "app/0.113.0+g2"
|
||||
icon_escape = os.path.relpath(outside / "target", Path(str(icon_dest) + ".staging"))
|
||||
G["extract_app"](str(self.launcher([("./epic-games-launcher.png", {"link": icon_escape})])),
|
||||
str(icon_dest), [str(self.webkit())])
|
||||
self.assertEqual(b"png", (icon_dest / "epic-games-launcher.png").read_bytes())
|
||||
self.assertFalse((outside / "target").exists())
|
||||
|
||||
def test_a_launcher_without_its_desktop_layer_is_refused(self):
|
||||
dest = self.state / "app/0.113.0+g1"
|
||||
with self.assertRaises(G["Failure"]) as caught:
|
||||
G["extract_app"](str(self.launcher()), str(dest))
|
||||
self.assertEqual("app-extract", str(caught.exception))
|
||||
self.assertFalse(dest.exists())
|
||||
self.assertFalse(Path(str(dest) + ".staging").exists())
|
||||
|
||||
def test_anything_but_a_deb_is_refused_and_leaves_nothing_behind(self):
|
||||
image = self.tmp / "EpicGamesLauncher-x86_64.AppImage"
|
||||
image.write_bytes(b"\x7fELF\x02\x01\x01\x00AI\x02" + bytes(64))
|
||||
dest = self.state / "app/0.95.2+g1"
|
||||
with self.assertRaises(G["Failure"]) as caught:
|
||||
G["extract_app"](str(image), str(dest), [str(self.webkit())])
|
||||
self.assertEqual("app-format", str(caught.exception))
|
||||
plain = self.tmp / "plain.deb"
|
||||
plain.write_bytes(ar([("data.tar.gz", b"x")]))
|
||||
with self.assertRaises(G["Failure"]) as caught:
|
||||
G["extract_app"](str(self.launcher()), str(dest), [str(plain)])
|
||||
self.assertEqual("desktop-format", str(caught.exception))
|
||||
self.assertFalse(dest.exists())
|
||||
self.assertFalse(Path(str(dest) + ".staging").exists())
|
||||
|
||||
def test_an_installed_appimage_launcher_still_runs_through_apprun(self):
|
||||
app = self.state / "app/0.95.2+g1"
|
||||
(app / "usr/bin").mkdir(parents=True)
|
||||
(app / "AppRun").write_text("run")
|
||||
(app / "usr/bin/EpicGamesLauncher").write_text("bin")
|
||||
self.assertTrue(G["app_complete"](str(app)))
|
||||
self.assertEqual(str(app / "AppRun"), G["app_command"](str(app)))
|
||||
self.assertIsNone(G["desktop_libs"](str(app)))
|
||||
(app / "usr/bin/EpicGamesLauncher").unlink()
|
||||
self.assertFalse(G["app_complete"](str(app)))
|
||||
|
||||
def test_the_webkit_helpers_are_linked_into_the_runtime(self):
|
||||
dest = self.state / "app/0.113.0+g1"
|
||||
G["extract_app"](str(self.launcher()), str(dest), [str(self.webkit())])
|
||||
files = self.state / "runtime/4.0.1/files"
|
||||
(files / "lib/x86_64-linux-gnu").mkdir(parents=True)
|
||||
link = files / "lib/x86_64-linux-gnu/webkit2gtk-4.1"
|
||||
G["link_webkit"](str(files), G["desktop_libs"](str(dest)))
|
||||
self.assertFalse(os.path.isabs(os.readlink(link)))
|
||||
self.assertEqual(b"net", (link / "WebKitNetworkProcess").read_bytes())
|
||||
G["link_webkit"](str(files), G["desktop_libs"](str(dest)))
|
||||
self.assertEqual(b"net", (link / "WebKitNetworkProcess").read_bytes())
|
||||
G["link_webkit"](str(files), None)
|
||||
self.assertFalse(os.path.lexists(link))
|
||||
link.mkdir()
|
||||
(link / "own").write_text("x")
|
||||
G["link_webkit"](str(files), G["desktop_libs"](str(dest)))
|
||||
self.assertTrue((link / "own").is_file())
|
||||
self.assertTrue((dest / "desktop/usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/WebKitNetworkProcess").is_file())
|
||||
|
||||
def test_only_the_deb_launcher_gets_the_desktop_libraries(self):
|
||||
with mock.patch.dict(G, {"fex_environment": lambda fex, files, base: {}}):
|
||||
plain = G["client_environment"]({"LD_LIBRARY_PATH": "/host"}, None, None, ":0", "bus", "broker")
|
||||
layered = G["client_environment"]({}, None, None, ":0", "bus", "broker", libs="/app/desktop/usr/lib/x86_64-linux-gnu")
|
||||
self.assertNotIn("LD_LIBRARY_PATH", plain)
|
||||
self.assertEqual("/app/desktop/usr/lib/x86_64-linux-gnu", layered["LD_LIBRARY_PATH"])
|
||||
self.assertEqual("/app/desktop/usr/share:/usr/local/share:/usr/share", layered["XDG_DATA_DIRS"])
|
||||
self.assertEqual("/app/desktop/usr/share/glib-2.0/schemas", layered["GSETTINGS_SCHEMA_DIR"])
|
||||
|
||||
def test_every_desktop_package_reaches_the_install(self):
|
||||
options, rest = G["parse_options"](["--app", "a.deb", "--desktop", "one.deb", "--desktop", "two.deb", "x"], lists=("desktop",))
|
||||
self.assertEqual({"app": "a.deb", "desktop": ["one.deb", "two.deb"]}, options)
|
||||
self.assertEqual(["x"], rest)
|
||||
self.assertEqual({"desktop": "two.deb"}, G["parse_options"](["--desktop", "one.deb", "--desktop", "two.deb"])[0])
|
||||
|
||||
|
||||
class ArgumentsTest(EpicTestCase):
|
||||
def test_client_arguments_win_and_paths_become_windows_paths(self):
|
||||
ovt = self.tmp / "ovt"
|
||||
@@ -736,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())
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
@@ -450,6 +451,72 @@ class PrepareTest(FexTestCase):
|
||||
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
|
||||
self.assertEqual(sorted(os.listdir(root.parent)), ["config", "lock", "rootfs", "status.json"])
|
||||
|
||||
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()
|
||||
|
||||
@@ -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:
|
||||
@@ -213,6 +226,18 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
started = [e["args"] for e in self.calls() if e["args"][:3] == ["shell", "am", "start"]]
|
||||
self.assertIn("com.antutu.benchmark.full/com.droiddeck.launcher.agent.AgentStartActivity", started[0])
|
||||
|
||||
def test_a_start_delivered_to_an_existing_task_is_a_failure(self):
|
||||
output = (b"Starting: Intent { cmp=com.droiddeck.launcher/.agent.AgentStartActivity (has extras) }\n"
|
||||
b"Warning: Activity not started, intent has been delivered to currently running top-most instance.\n"
|
||||
b"Status: ok\nActivity: com.droiddeck.launcher/.FrontEndActivity\nComplete\n")
|
||||
|
||||
def adb(_adb, _serial, *args, timeout=30):
|
||||
return ctl.subprocess.CompletedProcess(args, 0, output, b"")
|
||||
|
||||
with unittest.mock.patch.object(ctl, "run_adb", adb), self.assertRaises(ctl.ControlError) as caught:
|
||||
ctl.start_agent_activity("adb", "fake-1", {"mode": "steam"})
|
||||
self.assertEqual("ACTIVITY_START_FAILED", caught.exception.code)
|
||||
|
||||
def test_a_malformed_package_is_refused_before_adb(self):
|
||||
with unittest.mock.patch.dict(os.environ, {"DROIDDECK_PACKAGE": "com.example;reboot"}):
|
||||
variant = load("droiddeckctl")
|
||||
@@ -291,7 +316,7 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true")
|
||||
self.assertEqual(7, code)
|
||||
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
|
||||
self.assertIn("Setup > Diagnostics > Debugging tools", out["error"]["message"])
|
||||
self.assertIn("Setup > Developer > Debugging tools", out["error"]["message"])
|
||||
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
|
||||
|
||||
def test_override_checks_names_before_pushing_any_file(self):
|
||||
@@ -320,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")
|
||||
@@ -417,12 +457,14 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
return ctl.subprocess.CompletedProcess(args, 127, b"", b"/system/bin/sh: content: inaccessible or not found")
|
||||
if args[:2] == ("shell", "am"):
|
||||
return ctl.subprocess.CompletedProcess(args, 0, b"Broadcast completed: result=0", b"")
|
||||
if args[:2] == ("shell", "pidof " + ctl.PACKAGE):
|
||||
return ctl.subprocess.CompletedProcess(args, 0, b"4940\n", b"")
|
||||
return ctl.subprocess.CompletedProcess(args, 0, next(answers), b"")
|
||||
|
||||
with unittest.mock.patch.object(ctl, "run_adb", adb), unittest.mock.patch.object(ctl.time, "sleep"):
|
||||
answer = ctl.provider_call("adb", "fake-1", "state", arg="a b", request={"x": 1})
|
||||
self.assertEqual({"ok": True, "command": "state"}, answer)
|
||||
broadcast = calls[1]
|
||||
broadcast = next(c for c in calls if c[:2] == ("shell", "am"))
|
||||
self.assertEqual(("shell", "am", "broadcast", "-a", ctl.PACKAGE + ".AGENT_CALL", "-p", ctl.PACKAGE), broadcast[:7])
|
||||
self.assertIn("'a b'", broadcast)
|
||||
self.assertEqual(ctl.encode_request({"x": 1}), broadcast[broadcast.index("request") + 1])
|
||||
@@ -823,5 +865,48 @@ class ScenarioTest(FakeAdbTest):
|
||||
self.assertEqual([{"appId": 7, "timeout": 15.0}] * 2, [c["request"] for c in self.calls("quit")])
|
||||
|
||||
|
||||
class ProviderFallbackTest(unittest.TestCase):
|
||||
MISSING = "/system/bin/sh: content: inaccessible or not found\n"
|
||||
|
||||
def adb(self, answers):
|
||||
calls = []
|
||||
|
||||
def run(adb, serial, *args, timeout=None):
|
||||
calls.append(args)
|
||||
for prefix, (code, out, err) in answers:
|
||||
if " ".join(args).startswith(" ".join(prefix)):
|
||||
return unittest.mock.Mock(returncode=code, stdout=out.encode(), stderr=err.encode())
|
||||
raise AssertionError(f"unexpected adb call {args}")
|
||||
return calls, unittest.mock.patch.object(ctl, "run_adb", run)
|
||||
|
||||
def test_a_command_that_prints_the_shell_error_is_not_run_again(self):
|
||||
result = 'Result: Bundle[{json={"ok":true,"stdout":{"text":"' + self.MISSING.strip() + '"}}}]'
|
||||
calls, patch = self.adb([(["shell", "content"], (0, result, ""))])
|
||||
with patch:
|
||||
self.assertTrue(ctl.provider_call("adb", "s", "native", request={"argv": ["x"]})["ok"])
|
||||
self.assertEqual(1, len(calls))
|
||||
|
||||
def test_a_shell_without_content_uses_the_broadcast(self):
|
||||
calls, patch = self.adb([
|
||||
(["shell", "content"], (127, "", self.MISSING)),
|
||||
(["shell", "pidof"], (0, "4940\n", "")),
|
||||
(["shell", "am", "broadcast"], (0, "Broadcast completed", "")),
|
||||
(["shell"], (0, '{"ok": true}', "")),
|
||||
])
|
||||
with patch:
|
||||
self.assertTrue(ctl.provider_call("adb", "s", "state")["ok"])
|
||||
self.assertEqual(["shell", "am", "broadcast"], list(calls[2][:3]))
|
||||
|
||||
def test_the_broadcast_needs_the_app_running(self):
|
||||
calls, patch = self.adb([
|
||||
(["shell", "content"], (127, "", self.MISSING)),
|
||||
(["shell", "pidof"], (1, "", "")),
|
||||
])
|
||||
with patch, self.assertRaises(ctl.ControlError) as raised:
|
||||
ctl.provider_call("adb", "s", "state")
|
||||
self.assertEqual("APP_NOT_RUNNING", raised.exception.code)
|
||||
self.assertFalse(any(c[:3] == ("shell", "am", "broadcast") for c in calls))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,314 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
USERNS = shutil.which("unshare") is not None and subprocess.run(["unshare", "-Urm", "true"], capture_output=True).returncode == 0
|
||||
|
||||
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include "FASTPATH"
|
||||
#include <sys/mount.h>
|
||||
|
||||
static const char *race_from, *race_to;
|
||||
static dev_t race_dev;
|
||||
static ino_t race_ino;
|
||||
|
||||
static long trapped_nr = -1, unsupported_nr = -1;
|
||||
|
||||
static long host_sys(long nr, long a, long b, long c, long d, long e, long f) {
|
||||
if (nr == trapped_nr || (nr == unsupported_nr && a != -1)) return -ENOSYS;
|
||||
long r = syscall(nr, a, b, c, d, e, f);
|
||||
struct stat fs;
|
||||
if (r >= 0 && nr == SYS_fcntl && b == F_DUPFD_CLOEXEC && c == DIR_FD_FLOOR && race_from
|
||||
&& syscall(SYS_fstat, a, &fs) == 0 && fs.st_dev == race_dev && fs.st_ino == race_ino) {
|
||||
syscall(SYS_renameat, AT_FDCWD, race_from, AT_FDCWD, race_to);
|
||||
race_from = NULL;
|
||||
}
|
||||
return r < 0 ? -errno : r;
|
||||
}
|
||||
|
||||
static void show(long r) {
|
||||
if (r == FP_SLOW) puts("SLOW");
|
||||
else if (r < 0) printf("E%ld\n", -r);
|
||||
else puts("ok");
|
||||
}
|
||||
|
||||
static int high_fds(void) {
|
||||
int n = 0;
|
||||
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + 4 * DIRS; fd++)
|
||||
if (fcntl(fd, F_GETFD) >= 0) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
static char hosts[MAX_BINDS][PATH_MAX], guests[MAX_BINDS][512];
|
||||
static int taken[DIRS];
|
||||
int ntaken = 0;
|
||||
fp_sys = host_sys;
|
||||
snprintf(root, sizeof root, "%s", argv[1]);
|
||||
rootlen = strlen(root);
|
||||
int i = 2;
|
||||
for (; i + 1 < argc && strcmp(argv[i], "--"); i += 2) {
|
||||
struct bind *bd = &binds[nbinds];
|
||||
bd->host = hosts[nbinds];
|
||||
bd->guest = guests[nbinds];
|
||||
snprintf(bd->host, PATH_MAX, "%s", argv[i]);
|
||||
snprintf(bd->guest, sizeof guests[0], "%s", argv[i + 1]);
|
||||
bd->hlen = strlen(bd->host);
|
||||
bd->glen = strlen(bd->guest);
|
||||
nbinds++;
|
||||
}
|
||||
pthread_once(&init_once, fp_init);
|
||||
fp_on = 1;
|
||||
for (i++; i < argc; i++) {
|
||||
const char *op = argv[i];
|
||||
if (!strcmp(op, "fuse")) {
|
||||
for (int b = 0; b < nbinds; b++) binds[b].fuse = 1;
|
||||
} else if (!strcmp(op, "touch")) {
|
||||
long fd = fp_open(AT_FDCWD, argv[++i], O_CREAT | O_WRONLY | O_CLOEXEC, 0644);
|
||||
if (fd >= 0) close((int)fd);
|
||||
show(fd);
|
||||
} else if (!strcmp(op, "stat")) {
|
||||
struct stat st;
|
||||
show(fp_stat(AT_FDCWD, argv[++i], AT_SYMLINK_NOFOLLOW, &st));
|
||||
} else if (!strcmp(op, "symlink")) {
|
||||
long r = fp_symlink("target", AT_FDCWD, argv[++i]);
|
||||
if (refused()) puts("REFUSED");
|
||||
else show(r);
|
||||
} else if (!strcmp(op, "trap-symlink")) {
|
||||
trapped_nr = SYS_symlinkat;
|
||||
} else if (!strcmp(op, "no-symlinks")) {
|
||||
unsupported_nr = SYS_symlinkat;
|
||||
} else if (!strcmp(op, "on")) {
|
||||
printf("%d\n", fp_ready());
|
||||
} else if (!strcmp(op, "no-folders")) {
|
||||
unsupported_nr = SYS_mkdirat;
|
||||
} else if (!strcmp(op, "busy-cache")) {
|
||||
pthread_mutex_lock(&dir_lock);
|
||||
} else if (!strcmp(op, "mkdir")) {
|
||||
long r = fp_mkdir(AT_FDCWD, argv[++i], 0755);
|
||||
if (refused()) puts("REFUSED");
|
||||
else show(r);
|
||||
} else if (!strcmp(op, "mv")) {
|
||||
show(fp_rename(AT_FDCWD, argv[i + 1], AT_FDCWD, argv[i + 2], 0));
|
||||
i += 2;
|
||||
} else if (!strcmp(op, "rm")) {
|
||||
show(fp_unlink(AT_FDCWD, argv[++i], 0));
|
||||
} else if (!strcmp(op, "host-mv")) {
|
||||
show(host_sys(SYS_renameat, AT_FDCWD, (long)argv[i + 1], AT_FDCWD, (long)argv[i + 2], 0, 0));
|
||||
i += 2;
|
||||
} else if (!strcmp(op, "race-mv")) {
|
||||
struct stat rs;
|
||||
race_from = argv[i + 1];
|
||||
race_to = argv[i + 2];
|
||||
i += 2;
|
||||
show(host_sys(SYS_newfstatat, AT_FDCWD, (long)race_from, (long)&rs, 0, 0, 0));
|
||||
race_dev = rs.st_dev;
|
||||
race_ino = rs.st_ino;
|
||||
} else if (!strcmp(op, "host-rmdir")) {
|
||||
show(host_sys(SYS_unlinkat, AT_FDCWD, (long)argv[++i], AT_REMOVEDIR, 0, 0, 0));
|
||||
} else if (!strcmp(op, "host-mkdir")) {
|
||||
show(host_sys(SYS_mkdirat, AT_FDCWD, (long)argv[++i], 0755, 0, 0, 0));
|
||||
} else if (!strcmp(op, "clobber")) {
|
||||
long null = host_sys(SYS_openat, AT_FDCWD, (long)"/dev/null", O_RDONLY, 0, 0, 0);
|
||||
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) host_sys(SYS_dup3, null, fd, 0, 0, 0, 0);
|
||||
host_sys(SYS_close, null, 0, 0, 0, 0, 0);
|
||||
puts("ok");
|
||||
} else if (!strcmp(op, "first-fd")) {
|
||||
char link[40], out[PATH_MAX];
|
||||
snprintf(link, sizeof link, "/proc/self/fd/%d", DIR_FD_FLOOR);
|
||||
long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0);
|
||||
out[n > 0 ? n : 0] = 0;
|
||||
puts(out);
|
||||
} else if (!strcmp(op, "fds")) {
|
||||
printf("%d\n", high_fds());
|
||||
} else if (!strcmp(op, "ttl")) {
|
||||
ttl_ns = atoll(argv[++i]) * 1000000LL;
|
||||
} else if (!strcmp(op, "sleep")) {
|
||||
usleep(atoi(argv[++i]) * 1000);
|
||||
} else if (!strcmp(op, "chmod")) {
|
||||
show(fp_chmod(AT_FDCWD, argv[i + 1], strtol(argv[i + 2], NULL, 8), 0));
|
||||
i += 2;
|
||||
} else if (!strcmp(op, "host-mount")) {
|
||||
show(mount("tmpfs", argv[++i], "tmpfs", 0, NULL) == 0 ? 0 : -errno);
|
||||
} else if (!strcmp(op, "take-over")) {
|
||||
for (int fd = DIR_FD_FLOOR; fd < DIR_FD_FLOOR + DIRS; fd++) {
|
||||
char link[40], out[PATH_MAX];
|
||||
snprintf(link, sizeof link, "/proc/self/fd/%d", fd);
|
||||
long n = host_sys(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, sizeof out - 1, 0, 0);
|
||||
if (n <= 0) continue;
|
||||
out[n] = 0;
|
||||
long mine = host_sys(SYS_openat, AT_FDCWD, (long)out, O_RDONLY | O_DIRECTORY, 0, 0, 0);
|
||||
host_sys(SYS_dup3, mine, fd, 0, 0, 0, 0);
|
||||
host_sys(SYS_close, mine, 0, 0, 0, 0, 0);
|
||||
taken[ntaken++] = fd;
|
||||
}
|
||||
puts("ok");
|
||||
} else if (!strcmp(op, "taken")) {
|
||||
int open_fds = 0;
|
||||
for (int t = 0; t < ntaken; t++)
|
||||
if (lseek(taken[t], 0, SEEK_CUR) == 0) open_fds++;
|
||||
printf("%d/%d\n", open_fds, ntaken);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class FastPathFuseDirsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if shutil.which("gcc") is None:
|
||||
raise unittest.SkipTest("gcc is not available")
|
||||
cls.build = tempfile.TemporaryDirectory()
|
||||
source = Path(cls.build.name) / "fuse_dirs.c"
|
||||
source.write_text(PROGRAM.replace("FASTPATH", str(FASTPATH)))
|
||||
cls.program = Path(cls.build.name) / "fuse_dirs"
|
||||
subprocess.run(["gcc", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-format-truncation", "-pthread", "-o", str(cls.program), str(source), "-ldl"], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.build.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
base = Path(self.temp.name)
|
||||
self.root = base / "root"
|
||||
(self.root / "mnt").mkdir(parents=True)
|
||||
self.card = base / "card"
|
||||
(self.card / "Games/steamapps/common/Game/Data").mkdir(parents=True)
|
||||
|
||||
def ask(self, *ops, wrap=()):
|
||||
argv = [*wrap, str(self.program), str(self.root), str(self.card), "/mnt/card", "--", *ops]
|
||||
return subprocess.run(argv, capture_output=True, text=True, timeout=20, check=True).stdout.split()
|
||||
|
||||
def test_files_deep_in_a_fuse_library_are_created_renamed_and_removed(self):
|
||||
data = "/mnt/card/Games/steamapps/common/Game/Data"
|
||||
out = self.ask("fuse", "touch", f"{data}/a.tmp", "mv", f"{data}/a.tmp", f"{data}/a.idx",
|
||||
"stat", f"{data}/a.idx", "stat", f"{data}/a.tmp", "rm", f"{data}/a.idx",
|
||||
"stat", f"{data}/a.idx", "fds")
|
||||
self.assertEqual(["ok", "ok", "ok", "E2", "ok", "E2"], out[:-1])
|
||||
self.assertGreater(int(out[-1]), 0)
|
||||
self.assertEqual([], list((self.card / "Games/steamapps/common/Game/Data").iterdir()))
|
||||
|
||||
def test_a_folder_renamed_behind_the_cache_is_not_reused(self):
|
||||
game = self.card / "Games/steamapps/common/Game"
|
||||
(game / "Data/keep").write_text("x")
|
||||
out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
|
||||
"host-mv", str(game), str(game.parent / "Moved"),
|
||||
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
|
||||
"stat", "/mnt/card/Games/steamapps/common/Moved/Data/keep")
|
||||
self.assertEqual(["ok", "ok", "E2", "ok"], out)
|
||||
|
||||
def test_a_folder_renamed_while_it_is_opened_is_not_used_under_its_old_name(self):
|
||||
game = self.card / "Games/steamapps/common/Game"
|
||||
(game / "Data/keep").write_text("x")
|
||||
out = self.ask("fuse", "race-mv", str(game / "Data"), str(game / "Moved"),
|
||||
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
|
||||
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new", "fds")
|
||||
self.assertEqual(["ok", "E2", "E2"], out[:3])
|
||||
self.assertEqual(["keep"], [p.name for p in (game / "Moved").iterdir()])
|
||||
self.assertLessEqual(int(out[-1]), 64)
|
||||
|
||||
def test_a_folder_deleted_and_made_again_is_looked_up_fresh(self):
|
||||
data = self.card / "Games/steamapps/common/Game/Data"
|
||||
out = self.ask("fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/old",
|
||||
"rm", "/mnt/card/Games/steamapps/common/Game/Data/old",
|
||||
"host-rmdir", str(data), "host-mkdir", str(data),
|
||||
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new")
|
||||
self.assertEqual(["ok"] * 5, out)
|
||||
self.assertEqual(["new"], [p.name for p in data.iterdir()])
|
||||
|
||||
def test_folders_deleted_and_made_again_many_times_keep_descriptors_bounded(self):
|
||||
data = self.card / "Games/steamapps/common/Game/Data"
|
||||
ops = ["fuse"]
|
||||
for _ in range(200):
|
||||
ops += ["touch", "/mnt/card/Games/steamapps/common/Game/Data/x",
|
||||
"rm", "/mnt/card/Games/steamapps/common/Game/Data/x",
|
||||
"host-rmdir", str(data), "host-mkdir", str(data)]
|
||||
out = self.ask(*ops, "fds")
|
||||
self.assertEqual(["ok"] * 800, out[:-1])
|
||||
self.assertLessEqual(int(out[-1]), 64)
|
||||
|
||||
def test_descriptors_the_program_takes_over_are_left_alone(self):
|
||||
data = "/mnt/card/Games/steamapps/common/Game/Data"
|
||||
out = self.ask("fuse", "touch", f"{data}/a", "clobber", "touch", f"{data}/b",
|
||||
"stat", f"{data}/a", "first-fd")
|
||||
self.assertEqual(["ok", "ok", "ok", "ok", "/dev/null"], out)
|
||||
self.assertEqual({"a", "b"}, {p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir()})
|
||||
|
||||
def test_a_folder_the_program_opened_itself_stays_open_when_the_cache_moves_on(self):
|
||||
data = self.card / "Games/steamapps/common/Game/Data"
|
||||
ops = ["fuse", "touch", "/mnt/card/Games/steamapps/common/Game/Data/a", "take-over"]
|
||||
for n in range(200):
|
||||
(data / f"d{n}").mkdir()
|
||||
ops += ["touch", f"/mnt/card/Games/steamapps/common/Game/Data/d{n}/x"]
|
||||
out = self.ask(*ops, "taken")
|
||||
self.assertEqual(["ok"] * 202, out[:-1])
|
||||
opened, total = map(int, out[-1].split("/"))
|
||||
self.assertGreater(total, 0)
|
||||
self.assertEqual(total, opened)
|
||||
self.assertEqual(200, len(list(data.glob("d*/x"))))
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root passes folder permissions")
|
||||
def test_a_parent_folder_closed_by_the_program_stops_cached_access_at_once(self):
|
||||
game = self.card / "Games/steamapps/common/Game"
|
||||
(game / "Data/keep").write_text("x")
|
||||
self.addCleanup(os.chmod, game, 0o755)
|
||||
out = self.ask("fuse", "stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
|
||||
"chmod", "/mnt/card/Games/steamapps/common/Game", "000",
|
||||
"stat", "/mnt/card/Games/steamapps/common/Game/Data/keep",
|
||||
"touch", "/mnt/card/Games/steamapps/common/Game/Data/new")
|
||||
self.assertEqual(["ok", "ok"], out[:2])
|
||||
self.assertNotIn("ok", out[2:])
|
||||
os.chmod(game, 0o755)
|
||||
self.assertEqual(["keep"], [p.name for p in (game / "Data").iterdir()])
|
||||
|
||||
@unittest.skipUnless(USERNS, "mount namespaces are not available")
|
||||
def test_a_mount_placed_over_a_cached_folder_receives_later_writes(self):
|
||||
data = self.card / "Games/steamapps/common/Game/Data"
|
||||
out = self.ask("fuse", "ttl", "1", "touch", "/mnt/card/Games/steamapps/common/Game/Data/under",
|
||||
"host-mount", str(data), "sleep", "20",
|
||||
"touch", "/mnt/card/Games/steamapps/common/Game/Data/over",
|
||||
"stat", "/mnt/card/Games/steamapps/common/Game/Data/under", wrap=("unshare", "-Urm"))
|
||||
self.assertEqual(["ok", "ok", "ok", "E2"], out)
|
||||
self.assertEqual(["under"], [p.name for p in data.iterdir()])
|
||||
|
||||
def test_a_call_the_filesystem_does_not_implement_leaves_the_fast_path_on(self):
|
||||
data = "/mnt/card/Games/steamapps/common/Game/Data"
|
||||
out = self.ask("fuse", "no-symlinks", "touch", f"{data}/a", "symlink", f"{data}/link", "on",
|
||||
"stat", f"{data}/a", "symlink", f"{data}/link", "on", "touch", f"{data}/b")
|
||||
self.assertEqual(["ok", "REFUSED", "1", "ok", "REFUSED", "1", "ok"], out)
|
||||
self.assertEqual(["a", "b"], sorted(p.name for p in (self.card / "Games/steamapps/common/Game/Data").iterdir()))
|
||||
|
||||
def test_repeated_unsupported_calls_close_the_folders_they_opened(self):
|
||||
data = "/mnt/card/Games/steamapps/common/Game/Data"
|
||||
ops = [op for n in range(40) for op in ("mkdir", f"{data}/new{n}")]
|
||||
out = self.ask("fuse", "no-folders", "busy-cache", *ops, "on", "fds")
|
||||
self.assertEqual(["REFUSED"] * 40 + ["1", "0"], out)
|
||||
|
||||
def test_a_trapped_call_still_stops_the_fast_path_for_the_process(self):
|
||||
data = "/mnt/card/Games/steamapps/common/Game/Data"
|
||||
out = self.ask("fuse", "trap-symlink", "symlink", f"{data}/link", "on")
|
||||
self.assertEqual(["REFUSED", "0"], out)
|
||||
|
||||
def test_a_symlink_is_made_where_the_filesystem_allows_it(self):
|
||||
data = "/mnt/card/Games/steamapps/common/Game/Data"
|
||||
out = self.ask("fuse", "symlink", f"{data}/link", "on")
|
||||
self.assertEqual(["ok", "1"], out)
|
||||
self.assertEqual("target", os.readlink(self.card / "Games/steamapps/common/Game/Data/link"))
|
||||
|
||||
def test_other_filesystems_keep_absolute_paths_and_open_no_folders(self):
|
||||
data = "/mnt/card/Games/steamapps/common/Game/Data"
|
||||
out = self.ask("touch", f"{data}/a", "mv", f"{data}/a", f"{data}/b", "rm", f"{data}/b", "fds")
|
||||
self.assertEqual(["ok", "ok", "ok", "0"], out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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')):
|
||||
@@ -950,6 +1094,22 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
|
||||
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
|
||||
|
||||
def test_games_run_with_gl_error_checks_unless_the_user_turns_them_off(self):
|
||||
gpu = MODULE["game_gpu"]
|
||||
session = {"MESA_NO_ERROR": "1", "DROIDDECK_GAME_MESA_NO_ERROR": "", "KEEP": "1"}
|
||||
self.assertEqual(gpu(session), {"KEEP": "1"})
|
||||
self.assertEqual(gpu(session, True), {"MESA_NO_ERROR": "1", "KEEP": "1"})
|
||||
self.assertEqual(gpu({"MESA_NO_ERROR": "1"}), {"MESA_NO_ERROR": "1"})
|
||||
self.assertEqual(gpu({"MESA_NO_ERROR": "1", "DROIDDECK_GAME_MESA_NO_ERROR": "1"}), {"MESA_NO_ERROR": "1"})
|
||||
both = gpu({"MESA_NO_ERROR": "1", "DROIDDECK_GAME_MESA_NO_ERROR": "", "TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "nolrz"})
|
||||
self.assertEqual(both, {"TU_DEBUG": "nolrz"})
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "MESA_NO_ERROR": "1"}),
|
||||
{"MESA_NO_ERROR": "1"})
|
||||
config = {"version": 1, "games": {"42": {"MESA_NO_ERROR": "1"}}}
|
||||
env = gpu(session)
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "42")["MESA_NO_ERROR"], "1")
|
||||
self.assertNotIn("MESA_NO_ERROR", MODULE["apply_config"](env, config, "43"))
|
||||
|
||||
def test_a_chromium_app_keeps_the_sessions_turnip_debug(self):
|
||||
gpu = MODULE["game_gpu"]
|
||||
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "KEEP": "1"}, True),
|
||||
@@ -992,9 +1152,11 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
|
||||
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
|
||||
cap = MODULE["vram_cap"]
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096")
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096; dxgi.maxSharedMemory = 4096")
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "8192"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 8192; dxgi.maxSharedMemory = 8192")
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "4095"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4095; dxgi.maxSharedMemory = 4095; d3d9.maxAvailableMemory = 4095")
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"],
|
||||
"dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60")
|
||||
"dxgi.maxDeviceMemory = 2048; dxgi.maxSharedMemory = 2048; d3d9.maxAvailableMemory = 2048; dxvk.maxFrameRate = 60")
|
||||
for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}):
|
||||
self.assertNotIn("DXVK_CONFIG", cap(off))
|
||||
self.assertNotIn("DROIDDECK_VRAM_CAP", cap(off))
|
||||
@@ -1154,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"):
|
||||
@@ -1520,6 +1684,19 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
config = {"version": 1, "shared": {}, "games": {"42": values}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "42", env), values, name)
|
||||
|
||||
def test_ff7_rebirth_runs_at_feature_level_12_2_unless_the_game_overrides_it(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "FINAL FANTASY VII REBIRTH"
|
||||
game = root / "End/Binaries/Win64/ff7rebirth_.exe"
|
||||
game.parent.mkdir(parents=True)
|
||||
for exe in (root / "ff7rebirth.exe", game):
|
||||
exe.touch()
|
||||
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
|
||||
self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2"}, exe.name)
|
||||
self.assertTrue(notes)
|
||||
config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"})
|
||||
|
||||
def test_unity_players_keep_tso_over_the_preset(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
def game(*names):
|
||||
@@ -1561,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}):
|
||||
@@ -2687,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"
|
||||
@@ -2698,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)
|
||||
@@ -2738,6 +2978,149 @@ class ForeignSystemDllTest(unittest.TestCase):
|
||||
self.assertFalse((system32 / "ucrtbase.dll").is_symlink())
|
||||
self.assertEqual(0x8664, MODULE["pe_machine"](system32 / "userlib.dll"))
|
||||
|
||||
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"
|
||||
(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))
|
||||
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:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
|
||||
@@ -9,7 +9,7 @@ from pathlib import Path
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "MESA_LOADER_DRIVER_OVERRIDE", "GALLIUM_DRIVER",
|
||||
"LIBGL_KOPPER_DRI2", "VK_ICD_FILENAMES", "VK_DRIVER_FILES")
|
||||
"LIBGL_KOPPER_DRI2", "VK_ICD_FILENAMES", "VK_DRIVER_FILES", "MESA_NO_ERROR", "DROIDDECK_GAME_MESA_NO_ERROR")
|
||||
SESSION = {"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""}
|
||||
GPU_SESSION = {"MESA_LOADER_DRIVER_OVERRIDE": "zink", "GALLIUM_DRIVER": "zink",
|
||||
"LIBGL_KOPPER_DRI2": "true", "VK_ICD_FILENAMES": "/runtime/turnip.json",
|
||||
@@ -68,6 +68,15 @@ class GameGpuLaunchersTest(unittest.TestCase):
|
||||
self.chromium()
|
||||
self.assertEqual("sysmem", self.wrapper("--for", str(self.app / "files"))["TU_DEBUG"])
|
||||
|
||||
def test_programs_get_gl_error_checks_back_while_chromium_keeps_the_client_setting(self):
|
||||
session = dict(GPU_SESSION, MESA_NO_ERROR="1", DROIDDECK_GAME_MESA_NO_ERROR="")
|
||||
values = self.wrapper(session=session)
|
||||
self.assertEqual(("unset", "unset"), (values["MESA_NO_ERROR"], values["DROIDDECK_GAME_MESA_NO_ERROR"]))
|
||||
self.assertEqual(GPU_SESSION, {key: values[key] for key in GPU_SESSION})
|
||||
self.assertEqual("1", self.wrapper("--chromium", session=session)["MESA_NO_ERROR"])
|
||||
self.assertEqual("unset", self.flatpak(session)["MESA_NO_ERROR"])
|
||||
self.assertEqual("1", self.wrapper(session={"MESA_NO_ERROR": "1"})["MESA_NO_ERROR"])
|
||||
|
||||
def test_without_the_game_setting_the_wrapper_changes_nothing(self):
|
||||
self.assertEqual("sysmem", self.wrapper(session={"TU_DEBUG": "sysmem"})["TU_DEBUG"])
|
||||
self.assertEqual("unset", self.wrapper(session={})["TU_DEBUG"])
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
|
||||
|
||||
class GameResolutionTest(unittest.TestCase):
|
||||
def launch(self, mode, **overrides):
|
||||
source = SESSION.read_text()
|
||||
start = source.index(' width=${BL_WIDTH:-1280}')
|
||||
end = source.index('\nfi\n\nbl_displays()', start)
|
||||
block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub')
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH='60', BL_MANGOAPP='0',
|
||||
BL_WIDTH='2560', BL_HEIGHT='1600')
|
||||
for name in ('BL_GAME_WIDTH', 'BL_GAME_HEIGHT', 'BL_FOLLOW_OUTPUT', 'BL_GAMESCOPE_STRETCH_16X9'):
|
||||
env.pop(name, None)
|
||||
env.update(overrides)
|
||||
fake = Path(directory) / 'gamescope'
|
||||
fake.write_text('#!/bin/bash\nprintf "ARG:%s\\n" "$@"\n')
|
||||
fake.chmod(0o755)
|
||||
env['PATH'] = directory + os.pathsep + env['PATH']
|
||||
script = f'''
|
||||
set -u
|
||||
mode={mode}
|
||||
pipewire_stub() {{ return 1; }}
|
||||
run_gamescope() {{ printf 'ARG:%s\n' "$@"; }}
|
||||
''' + block
|
||||
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=5)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return [line.removeprefix('ARG:') for line in result.stdout.splitlines() if line.startswith('ARG:')]
|
||||
|
||||
def test_a_game_started_without_steam_runs_at_its_resolution_with_proportions_kept(self):
|
||||
args = self.launch('run', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720')
|
||||
self.assertEqual(['2560', '1600'], [args[args.index('-W') + 1], args[args.index('-H') + 1]])
|
||||
self.assertEqual(['1280', '720'], [args[args.index('-w') + 1], args[args.index('-h') + 1]])
|
||||
self.assertNotIn('-S', args)
|
||||
|
||||
def test_without_a_game_resolution_the_game_matches_the_output(self):
|
||||
args = self.launch('run')
|
||||
self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]])
|
||||
|
||||
def test_steam_ignores_the_game_resolution(self):
|
||||
args = self.launch('steam', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720')
|
||||
self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -2,7 +2,7 @@ from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_client_zram_focus import function_source, run_bash
|
||||
from tools.tests.test_client_zram_focus import SCRIPT, function_source, run_bash
|
||||
|
||||
|
||||
class MemoryPressureTest(unittest.TestCase):
|
||||
@@ -20,8 +20,8 @@ class MemoryPressureTest(unittest.TestCase):
|
||||
|
||||
def run_policy(self, body):
|
||||
functions = '\n'.join(function_source(name) for name in (
|
||||
'bl_memory_read', 'bl_memory_tight', 'bl_client_can_pageout',
|
||||
'bl_client_can_readback', 'bl_client_pressure'))
|
||||
'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', 'bl_client_can_pageout',
|
||||
'bl_client_can_readback', 'bl_client_pressure', 'bl_client_pressure_result', 'bl_zram_has_room'))
|
||||
functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo'))
|
||||
functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure'))
|
||||
harness = '''
|
||||
@@ -29,7 +29,7 @@ set -u
|
||||
_bl_pids=(123) _bl_game=1 _bl_packed=-1 _bl_pressure_at=-1 _bl_pressure_backoff=30
|
||||
rss=$((384 * 1024)) client_swap=$((512 * 1024)) reclaimed=$((128 * 1024))
|
||||
step() { :; }
|
||||
bl_zram_usage() { _bl_rss=$rss _bl_swap=$client_swap; }
|
||||
bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$client_swap; }
|
||||
bl_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _bl_pageout_complete=${pageout_complete:-1}; }
|
||||
''' + functions + '\nbl_memory_read\n' + body
|
||||
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
|
||||
@@ -80,6 +80,13 @@ if bl_client_can_readback; then echo yes; else echo no; fi
|
||||
self.assertEqual(['no'], self.run_policy('''
|
||||
bl_client_pressure
|
||||
if bl_client_can_pageout; then echo yes; else echo no; fi
|
||||
'''))
|
||||
|
||||
def test_client_swap_budget_excludes_file_backed_memory(self):
|
||||
self.memory(swap_free=1536)
|
||||
self.assertEqual(['send:1:client'], self.run_policy('''
|
||||
rss=$((2048 * 1024)) anon=$((256 * 1024))
|
||||
bl_client_pressure
|
||||
'''))
|
||||
|
||||
def test_without_swap_automatic_pageout_is_disabled(self):
|
||||
@@ -152,20 +159,22 @@ 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_low_ram',
|
||||
'bl_session_pressure', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback'))
|
||||
'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
|
||||
rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive=999 started=100 complete=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); }
|
||||
bl_zram_usage() { _bl_rss=$rss _bl_swap=$swap; }
|
||||
bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$swap; }
|
||||
bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed)); _bl_pageout_complete=$complete; }
|
||||
''' + functions + '\nbl_memory_read\n' + body
|
||||
result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW'))
|
||||
@@ -174,37 +183,103 @@ bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def test_low_headroom_compresses_the_game_session_at_most_every_30_seconds(self):
|
||||
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
|
||||
SECONDS=0; bl_session_pressure
|
||||
SECONDS=10; bl_session_pressure
|
||||
SECONDS=29; bl_session_pressure
|
||||
SECONDS=30; bl_session_pressure
|
||||
'''))
|
||||
|
||||
def test_twelve_gigabyte_devices_are_included_and_larger_ones_are_not(self):
|
||||
for total, expected in ((11264, ['send:1:game']), (12288, ['send:1:game']), (15360, [])):
|
||||
def test_pressure_policy_is_independent_of_ram_size(self):
|
||||
for total, expected in ((11264, ['send:1:session']), (12288, ['send:1:session']), (16384, ['send:1:session'])):
|
||||
with self.subTest(total=total):
|
||||
self.memory(total=total)
|
||||
self.assertEqual(expected, self.run_policy('bl_session_pressure'))
|
||||
|
||||
def test_large_device_with_real_headroom_does_not_reclaim(self):
|
||||
self.memory(total=16384, available=5120, psi='12.34')
|
||||
self.assertEqual([], self.run_policy('bl_session_pressure'))
|
||||
|
||||
def test_large_device_with_psi_and_moderate_headroom_reclaims(self):
|
||||
self.memory(total=16384, available=3072, psi='1.23')
|
||||
self.assertEqual(['send:1:session'], self.run_policy('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'))
|
||||
|
||||
def test_stalls_with_moderate_headroom_compress_before_the_hard_limit(self):
|
||||
self.memory(available=2048, psi='1.50')
|
||||
self.assertEqual(['send:1:game'], self.run_policy('bl_session_pressure'))
|
||||
self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure'))
|
||||
|
||||
def test_moderate_headroom_without_stalls_waits(self):
|
||||
self.memory(available=2048)
|
||||
self.assertEqual([], self.run_policy('bl_session_pressure'))
|
||||
|
||||
def test_same_second_memory_read_preserves_the_pressure_baseline(self):
|
||||
self.memory(available=2048)
|
||||
meminfo = self.root / 'meminfo'
|
||||
self.assertEqual(['1048576:524288:2097152'], self.run_policy(f'''
|
||||
SECONDS=100
|
||||
_bl_sample_at=100 _bl_sample_available=2097152 _bl_growth=0 _bl_fall=524288
|
||||
sed -i 's/MemAvailable: 2097152 kB/MemAvailable: 1048576 kB/' {meminfo}
|
||||
bl_memory_read
|
||||
echo "$_bl_available:$_bl_fall:$_bl_sample_available"
|
||||
'''))
|
||||
|
||||
def test_game_reading_back_most_of_a_pageout_skips_and_doubles_the_wait(self):
|
||||
self.assertEqual(['send:1:game', 'backoff:60', 'send:1:game', 'backoff:60',
|
||||
'send:1:game', 'backoff:30'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session', 'backoff:60',
|
||||
'send:1:session', 'backoff:30'], self.run_policy('''
|
||||
pushed=$((512 * 1024))
|
||||
SECONDS=0; bl_session_pressure
|
||||
swap=$((swap / 4))
|
||||
@@ -226,7 +301,7 @@ echo "backoff:$_bl_tier_backoff"
|
||||
|
||||
def test_nearly_out_of_memory_ignores_the_backoff_but_keeps_30_seconds(self):
|
||||
self.memory(available=512)
|
||||
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
|
||||
_bl_tier_backoff=300
|
||||
SECONDS=0; bl_session_pressure
|
||||
SECONDS=20; bl_session_pressure
|
||||
@@ -235,7 +310,7 @@ SECONDS=30; bl_session_pressure
|
||||
|
||||
def test_nearly_out_of_memory_still_backs_off_when_the_game_reads_its_pageout_back(self):
|
||||
self.memory(available=512)
|
||||
self.assertEqual(['send:1:game', 'backoff:60', 'send:1:game'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session'], self.run_policy('''
|
||||
SECONDS=0; bl_session_pressure
|
||||
swap=0
|
||||
SECONDS=30; bl_session_pressure
|
||||
@@ -247,7 +322,7 @@ SECONDS=90; bl_session_pressure
|
||||
|
||||
def test_nearly_out_of_memory_retries_a_skipped_pageout_after_30_seconds(self):
|
||||
self.memory(available=512)
|
||||
self.assertEqual(['send:1:game', 'send:1:game'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy('''
|
||||
SECONDS=0; bl_session_pressure
|
||||
swap=0
|
||||
SECONDS=30; bl_session_pressure
|
||||
@@ -263,6 +338,24 @@ SECONDS=360; bl_session_pressure
|
||||
self.memory(swap_free=1536, swap_total=2048)
|
||||
self.assertEqual([], self.run_policy('bl_session_pressure'))
|
||||
|
||||
def test_file_backed_resident_memory_does_not_consume_the_swap_budget(self):
|
||||
self.memory(swap_free=3088, swap_total=6144)
|
||||
self.assertEqual(['send:1:session'], self.run_policy('''
|
||||
rss=$((4096 * 1024)) anon=$((1024 * 1024))
|
||||
bl_session_pressure
|
||||
'''))
|
||||
|
||||
def test_anonymous_memory_and_pending_client_still_need_the_full_swap_reserve(self):
|
||||
self.memory(swap_free=3088, swap_total=6144)
|
||||
self.assertEqual([], self.run_policy('''
|
||||
rss=$((4096 * 1024)) anon=$((2048 * 1024))
|
||||
bl_session_pressure
|
||||
'''))
|
||||
self.assertEqual([], self.run_policy('''
|
||||
rss=$((4096 * 1024)) anon=$((1536 * 1024)) _bl_client_reserve=$((512 * 1024))
|
||||
bl_session_pressure
|
||||
'''))
|
||||
|
||||
def test_small_session_is_left_alone(self):
|
||||
self.assertEqual([], self.run_policy('rss=$((128 * 1024)); bl_session_pressure'))
|
||||
|
||||
@@ -275,10 +368,10 @@ SECONDS=360; bl_session_pressure
|
||||
self.assertEqual(['nap:5'], self.run_policy('bl_watch_nap'))
|
||||
self.assertEqual(['nap:5'], self.run_policy('_bl_game=0; bl_watch_nap'))
|
||||
|
||||
def test_one_push_compresses_the_game_and_the_launcher_and_restarts_the_launcher_wait(self):
|
||||
self.assertEqual(['send:1:game', 'pids:321 654 999', 'client:0:0'], self.run_policy('''
|
||||
def test_session_push_preserves_client_timestamps(self):
|
||||
self.assertEqual(['send:1:session', 'pids:321 654', 'client:-1:-1'], self.run_policy('''
|
||||
SECONDS=0; bl_session_pressure
|
||||
bl_zram_pick game; echo "pids:${_pids[*]}"
|
||||
bl_zram_pick session; echo "pids:${_pids[*]}"
|
||||
echo "client:$_bl_pressure_at:$_bl_packed"
|
||||
'''))
|
||||
|
||||
@@ -286,19 +379,19 @@ echo "client:$_bl_pressure_at:$_bl_packed"
|
||||
self.assertEqual(['pids:321 654', 'client:-1:-1'], self.run_policy('''
|
||||
BL_ZRAM_CLIENT=0
|
||||
SECONDS=0; bl_session_pressure
|
||||
bl_zram_pick game; echo "pids:${_pids[*]}"
|
||||
bl_zram_pick session; echo "pids:${_pids[*]}"
|
||||
echo "client:$_bl_pressure_at:$_bl_packed"
|
||||
''')[1:])
|
||||
|
||||
def test_low_ram_devices_compress_with_a_quarter_of_memory_left(self):
|
||||
self.memory(available=1700)
|
||||
self.assertEqual(['send:1:game'], self.run_policy('bl_session_pressure'))
|
||||
self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure'))
|
||||
self.memory(available=1900)
|
||||
self.assertEqual([], self.run_policy('bl_session_pressure'))
|
||||
|
||||
|
||||
def test_a_compressed_process_that_exits_is_not_counted_as_read_back(self):
|
||||
self.assertEqual(['send:1:game', 'send:1:game', 'backoff:30'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy('''
|
||||
SECONDS=0; bl_session_pressure
|
||||
alive=""; swap=0
|
||||
SECONDS=30; bl_session_pressure
|
||||
@@ -306,7 +399,7 @@ echo "backoff:$_bl_tier_backoff"
|
||||
'''))
|
||||
|
||||
def test_a_process_that_starts_after_a_pageout_is_not_in_its_read_back(self):
|
||||
self.assertEqual(['send:1:game', 'targets:999', 'send:1:game', 'backoff:30'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'targets:321 654', 'send:1:session', 'backoff:30'], self.run_policy('''
|
||||
SECONDS=0; bl_session_pressure
|
||||
echo "targets:${_bl_tier_targets[*]}"
|
||||
alive="999 1234"
|
||||
@@ -315,7 +408,7 @@ echo "backoff:$_bl_tier_backoff"
|
||||
'''))
|
||||
|
||||
def test_an_incomplete_pageout_does_not_restart_the_launcher_wait(self):
|
||||
self.assertEqual(['send:1:game', 'client:-1:-1'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'client:-1:-1'], self.run_policy('''
|
||||
complete=0
|
||||
SECONDS=0; bl_session_pressure
|
||||
echo "client:$_bl_pressure_at:$_bl_packed"
|
||||
@@ -323,7 +416,7 @@ echo "client:$_bl_pressure_at:$_bl_packed"
|
||||
|
||||
|
||||
def test_a_reused_process_id_is_not_counted_as_read_back(self):
|
||||
self.assertEqual(['send:1:game', 'send:1:game', 'backoff:30'], self.run_policy('''
|
||||
self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy('''
|
||||
SECONDS=0; bl_session_pressure
|
||||
started=200; swap=0
|
||||
SECONDS=30; bl_session_pressure
|
||||
@@ -344,5 +437,113 @@ echo "backoff:$_bl_tier_backoff"
|
||||
self.assertEqual(['gone'], result.stdout.split())
|
||||
|
||||
|
||||
class ReclaimDispatchTest(unittest.TestCase):
|
||||
def run_cycle(self, client=1, game=1, anonymous=384, complete=1, reclaimed=128, body=None, available=1024, fall=0, tick=0):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / 'meminfo').write_text(
|
||||
f'MemTotal: 7340032 kB\nMemAvailable: {available * 1024} kB\n'
|
||||
'SwapTotal: 6291456 kB\nSwapFree: 4194304 kB\n')
|
||||
(root / 'pressure').write_text('some avg10=0.00 avg60=0.00 avg300=0.00 total=0\n')
|
||||
names = ('bl_memory_read', 'bl_memory_tight', 'bl_memory_critical',
|
||||
'bl_zram_has_room', 'bl_client_can_pageout', 'bl_client_pressure',
|
||||
'bl_client_pressure_result', 'bl_client_pressure_finish',
|
||||
'bl_session_pressure', 'bl_zram_send', 'bl_zram_finish', 'bl_zram_pick')
|
||||
source = '\n'.join(function_source(name) for name in names)
|
||||
source = source.replace('/proc/meminfo', str(root / 'meminfo'))
|
||||
source = source.replace('/proc/pressure/memory', str(root / 'pressure'))
|
||||
source = source.replace('/tmp/.bl-zram', str(root / 'ctl'))
|
||||
monitor = SCRIPT.read_text()
|
||||
start = monitor.index(' _bl_preserved_growth=$_bl_growth', monitor.index('while kill -0 $$'))
|
||||
stop = monitor.index(' if [ "$_bl_game" = 1 ] && bl_game_focused', start)
|
||||
cycle = monitor[start:stop] if body is None else body
|
||||
script = f'''
|
||||
set -u
|
||||
BL_ZRAM_CLIENT={client} _bl_game={game} _bl_pids=(123) _bl_others=(321)
|
||||
_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1
|
||||
_bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0
|
||||
_bl_client_reserve=0 client_rss=393216 client_anon={anonymous * 1024}
|
||||
step() {{ :; }}
|
||||
bl_session_others() {{ _bl_session=(321); }}
|
||||
bl_zram_scan() {{ _bl_pids=(456); }}
|
||||
nap() {{ echo "nap:$*:at:$NOW"; }}
|
||||
bl_zram_usage() {{
|
||||
if [ "$1" = 123 ]; then
|
||||
_bl_rss=$client_rss _bl_anon=$client_anon _bl_swap=0
|
||||
else
|
||||
_bl_rss=3145728 _bl_anon=1572864 _bl_swap=0
|
||||
fi
|
||||
}}
|
||||
kill() {{ echo "signal:$*:at:$NOW"; NOW=$((NOW + {tick})); }}
|
||||
bl_zram_wait() {{
|
||||
echo "wait:$*:at:$NOW"
|
||||
NOW=$((NOW + 12))
|
||||
_bl_pageout_complete={complete}
|
||||
[ "$1" != 123 ] || client_rss=$((client_rss - {reclaimed * 1024}))
|
||||
}}
|
||||
bl_tier_note() {{ :; }}
|
||||
bl_game_focused() {{ :; }}
|
||||
''' + source + f'''
|
||||
bl_memory_read
|
||||
_bl_fall={fall * 1024}
|
||||
''' + cycle + '''
|
||||
echo "client:$_bl_pressure_backoff:${_bl_client_reserve:-0}:${_bl_client_pending:-0}"
|
||||
'''
|
||||
result = run_bash('NOW=0\n' + script.replace('SECONDS', 'NOW'))
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('', result.stderr)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def test_both_requests_are_sent_before_either_wait(self):
|
||||
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0',
|
||||
'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'], self.run_cycle())
|
||||
|
||||
def test_disabled_client_is_never_signalled_or_waited_for(self):
|
||||
self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'],
|
||||
self.run_cycle(client=0))
|
||||
|
||||
def test_no_game_requests_nothing(self):
|
||||
self.assertEqual(['client:30:0:0'], self.run_cycle(game=0))
|
||||
|
||||
def test_a_client_with_no_anonymous_pages_still_finishes_its_request(self):
|
||||
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:0',
|
||||
'wait:321:at:0', 'wait:123:at:12', 'client:30:0:0'],
|
||||
self.run_cycle(anonymous=0))
|
||||
|
||||
def test_falling_headroom_survives_a_tick_between_requests(self):
|
||||
self.assertEqual(['signal:-URG 123:at:0', 'signal:-URG 321:at:1',
|
||||
'wait:321:at:2', 'wait:123:at:14', 'client:30:0:0'],
|
||||
self.run_cycle(available=2304, fall=512, tick=1))
|
||||
|
||||
def test_deferred_ineffective_reclaim_still_doubles_the_backoff(self):
|
||||
self.assertEqual('client:60:0:0', self.run_cycle(reclaimed=0)[-1])
|
||||
|
||||
def test_deferred_incomplete_reclaim_does_not_double_the_backoff(self):
|
||||
self.assertEqual('client:30:0:0', self.run_cycle(reclaimed=0, complete=0)[-1])
|
||||
|
||||
def test_explicit_combined_send_keeps_its_synchronous_wait(self):
|
||||
self.assertEqual(['signal:-URG 321 123:at:0', 'wait:321 123:at:0', 'client:30:0:0'],
|
||||
self.run_cycle(body='bl_zram_send 1 cap game\n'))
|
||||
self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'],
|
||||
self.run_cycle(client=0, body='bl_zram_send 1 cap game\n'))
|
||||
|
||||
def test_readback_keeps_its_synchronous_delay(self):
|
||||
self.assertEqual(['signal:-URG 123:at:0', 'nap:5:at:0', 'client:30:0:0'],
|
||||
self.run_cycle(body='bl_zram_send 0 readback client\n'))
|
||||
|
||||
def test_usage_sums_anonymous_rss_and_falls_back_per_process(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
for pid, contents in ((123, 'VmRSS: 2000 kB\nRssAnon: 300 kB\nVmSwap: 100 kB\n'),
|
||||
(321, 'VmRSS: 4000 kB\nVmSwap: 200 kB\n'),
|
||||
(654, 'VmRSS: 1000 kB\nRssAnon: 0 kB\n')):
|
||||
(root / str(pid)).mkdir()
|
||||
(root / str(pid) / 'status').write_text(contents)
|
||||
source = function_source('bl_zram_usage').replace('/proc/', str(root) + '/')
|
||||
result = run_bash(source + '\nbl_zram_usage 123 321 654 > /dev/null; echo "$_bl_rss:$_bl_anon:$_bl_swap"')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('7000:4300:300', result.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,224 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
PROBE = r"""
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char cwd[4096];
|
||||
for (int i = 1; i < argc; i++) {
|
||||
struct stat st;
|
||||
if (strncmp(argv[i], "cd:", 3) == 0) {
|
||||
int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL;
|
||||
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "at:", 3) == 0) {
|
||||
int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY);
|
||||
printf("%s\t%d\t%d\n", argv[i], fstatat(AT_FDCWD, argv[i] + 3, &st, 0) == 0, dfd >= 0);
|
||||
if (dfd >= 0) close(dfd);
|
||||
continue;
|
||||
}
|
||||
if (strncmp(argv[i], "ls:", 3) == 0) {
|
||||
DIR *dir = opendir(argv[i] + 3);
|
||||
char names[1024] = "";
|
||||
struct dirent *de;
|
||||
while (dir && (de = readdir(dir)) != NULL) {
|
||||
if (de->d_name[0] == '.') continue;
|
||||
if (names[0]) strncat(names, ",", sizeof(names) - strlen(names) - 1);
|
||||
strncat(names, de->d_name, sizeof(names) - strlen(names) - 1);
|
||||
}
|
||||
if (dir) closedir(dir);
|
||||
printf("%s\t%s\n", argv[i], dir ? names : "-");
|
||||
continue;
|
||||
}
|
||||
int fd = open(argv[i], O_RDONLY);
|
||||
char data[64] = "-";
|
||||
if (fd >= 0) {
|
||||
ssize_t n = read(fd, data, sizeof(data) - 1);
|
||||
data[n > 0 ? n : 0] = 0;
|
||||
close(fd);
|
||||
}
|
||||
printf("%s\t%d\t%s\n", argv[i], stat(argv[i], &st) == 0, data);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
GAME = "/mnt/library/Some Game"
|
||||
|
||||
|
||||
class NativeHookMountTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
(tmp / "probe.c").write_text(PROBE)
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
|
||||
cls.probe = tmp / "probe"
|
||||
cls.root = tmp / "root"
|
||||
cls.library = tmp / "storage/PC GAMES"
|
||||
(cls.root / "etc").mkdir(parents=True)
|
||||
(cls.root / "etc/hostname").write_text("rootfs")
|
||||
(cls.root / "mnt/library/Some Game").mkdir(parents=True)
|
||||
(cls.root / "mnt/library/Some Game/game.txt").write_text("mount point")
|
||||
(cls.library / "Some Game").mkdir(parents=True)
|
||||
(cls.library / "Some Game/game.txt").write_text("library")
|
||||
for name, target in (("native", str(cls.root)), ("guest", "/")):
|
||||
devices = cls.root / "pfx" / name / "dosdevices"
|
||||
devices.mkdir(parents=True)
|
||||
os.symlink(target, devices / "z:")
|
||||
relinked = cls.root / "pfx/relinked"
|
||||
(relinked / "dosdevices").mkdir(parents=True)
|
||||
(relinked / "drive_c").mkdir()
|
||||
(relinked / "drive_c/c.txt").write_text("drive c")
|
||||
os.symlink(os.path.relpath(cls.root, relinked / "dosdevices"), relinked / "dosdevices/z:")
|
||||
os.symlink("../drive_c", relinked / "dosdevices/c:")
|
||||
copied = cls.root / "pfx/copied/dosdevices"
|
||||
copied.mkdir(parents=True)
|
||||
os.symlink("../" * 12 + "..", copied / "z:")
|
||||
elsewhere = tmp / "elsewhere"
|
||||
(elsewhere / "outside/pfx/dosdevices").mkdir(parents=True)
|
||||
(elsewhere / "mnt/library/Some Game").mkdir(parents=True)
|
||||
(elsewhere / "mnt/library/Some Game/game.txt").write_text("elsewhere")
|
||||
os.symlink("../../..", elsewhere / "outside/pfx/dosdevices/z:")
|
||||
os.symlink(str(elsewhere / "outside/pfx"), cls.root / "pfx/outside")
|
||||
cls.private = tmp / "private"
|
||||
private_pfx = cls.private / "123/pfx/dosdevices"
|
||||
private_pfx.mkdir(parents=True)
|
||||
os.symlink(os.path.relpath("/", "/mnt/private/123/pfx/dosdevices"), private_pfx / "z:")
|
||||
private_copy = cls.private / "456/pfx/dosdevices"
|
||||
private_copy.mkdir(parents=True)
|
||||
os.symlink("../" * 12 + "..", private_copy / "z:")
|
||||
cls.eqlen_src = tmp / "eqsrcdir"
|
||||
cls.eqlen_dst = "/" + "d" * (len(str(cls.eqlen_src)) - 1)
|
||||
eqlen_pfx = cls.eqlen_src / "123/pfx/dosdevices"
|
||||
eqlen_pfx.mkdir(parents=True)
|
||||
os.symlink(os.path.relpath("/", f"{cls.eqlen_dst}/123/pfx/dosdevices"), eqlen_pfx / "z:")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_probe(self, *args):
|
||||
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.probe), *args], env=env, capture_output=True, text=True, timeout=120,
|
||||
cwd=self.tmp.name)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self):
|
||||
path = f"/pfx/native/dosdevices/z:{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
|
||||
|
||||
def test_working_directory_through_a_drive_link_is_the_mount(self):
|
||||
arg = f"cd:/pfx/native/dosdevices/z:{GAME}/"
|
||||
self.assertEqual(self.run_probe(arg)[arg], [GAME])
|
||||
|
||||
def test_rootfs_path_under_a_mount_point_reaches_the_mount(self):
|
||||
path = f"{self.root}{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
|
||||
|
||||
def test_guest_drive_link_is_unchanged(self):
|
||||
path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
|
||||
|
||||
def test_rootfs_paths_outside_mounts_are_unchanged(self):
|
||||
paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"]
|
||||
result = self.run_probe(*paths)
|
||||
for path in paths:
|
||||
self.assertEqual(result[path], ["1", "rootfs"], path)
|
||||
|
||||
def test_wine_lookup_steps_reach_the_mount(self):
|
||||
for pfx in ("/pfx/native", "/pfx/guest", "/pfx/relinked", f"{self.root}/pfx/native", f"{self.root}/pfx/guest",
|
||||
f"{self.root}/pfx/relinked"):
|
||||
drive = f"{pfx}/dosdevices/z:"
|
||||
args = [f"at:{drive}{GAME}/", f"at:{drive}{GAME}", f"ls:{drive}/mnt/library", f"ls:{drive}{GAME}"]
|
||||
result = self.run_probe(*args)
|
||||
self.assertEqual(result[args[0]], ["1", "1"], pfx)
|
||||
self.assertEqual(result[args[1]], ["1", "1"], pfx)
|
||||
self.assertEqual(result[args[2]], ["Some Game"], pfx)
|
||||
self.assertEqual(result[args[3]], ["game.txt"], pfx)
|
||||
|
||||
def test_relative_drive_link_reaches_the_mount(self):
|
||||
path = f"/pfx/relinked/dosdevices/z:{GAME}/game.txt"
|
||||
cd = f"cd:/pfx/relinked/dosdevices/z:{GAME}/"
|
||||
result = self.run_probe(path, cd)
|
||||
self.assertEqual(result[path], ["1", "library"])
|
||||
self.assertEqual(result[cd], [GAME])
|
||||
|
||||
def test_relative_links_outside_mounts_are_unchanged(self):
|
||||
paths = ["/pfx/relinked/dosdevices/z:/etc/hostname", "/pfx/relinked/dosdevices/c:/c.txt",
|
||||
f"{self.root}/pfx/relinked/dosdevices/c:/c.txt"]
|
||||
result = self.run_probe(*paths)
|
||||
self.assertEqual(result[paths[0]], ["1", "rootfs"])
|
||||
self.assertEqual(result[paths[1]], ["1", "drive c"])
|
||||
self.assertEqual(result[paths[2]], ["1", "drive c"])
|
||||
|
||||
def test_suffix_after_a_relative_link_is_not_collapsed(self):
|
||||
path = "/pfx/relinked/dosdevices/z:/mnt/library/missing/../Some Game/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["0", "-"])
|
||||
|
||||
def test_relative_drive_link_climbing_past_the_root_reaches_the_mount(self):
|
||||
path = f"/pfx/copied/dosdevices/z:{GAME}/game.txt"
|
||||
cd = f"cd:/pfx/copied/dosdevices/z:{GAME}/"
|
||||
result = self.run_probe(path, cd)
|
||||
self.assertEqual(result[path], ["1", "library"])
|
||||
self.assertEqual(result[cd], [GAME])
|
||||
|
||||
def test_relative_link_climbing_past_the_root_stays_in_the_rootfs(self):
|
||||
path = "/pfx/copied/dosdevices/z:/etc/hostname"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "rootfs"])
|
||||
|
||||
def test_relative_link_is_resolved_from_its_real_directory(self):
|
||||
path = f"/pfx/outside/dosdevices/z:{GAME}/game.txt"
|
||||
self.assertEqual(self.run_probe(path)[path], ["1", "elsewhere"])
|
||||
|
||||
def test_drive_link_in_a_bound_prefix_reaches_the_mount(self):
|
||||
path = f"/mnt/private/123/pfx/dosdevices/z:{GAME}/game.txt"
|
||||
cd = f"cd:/mnt/private/123/pfx/dosdevices/z:{GAME}/"
|
||||
result = self.run_probe(path, cd)
|
||||
self.assertEqual(result[path], ["1", "library"])
|
||||
self.assertEqual(result[cd], [GAME])
|
||||
|
||||
def test_drive_link_copied_into_a_bound_prefix_reaches_the_mount(self):
|
||||
path = f"/mnt/private/456/pfx/dosdevices/z:{GAME}/game.txt"
|
||||
cd = f"cd:/mnt/private/456/pfx/dosdevices/z:{GAME}/"
|
||||
result = self.run_probe(path, cd)
|
||||
self.assertEqual(result[path], ["1", "library"])
|
||||
self.assertEqual(result[cd], [GAME])
|
||||
|
||||
def test_drive_link_in_equal_length_bound_prefix_reaches_the_mount(self):
|
||||
path = f"{self.eqlen_dst}/123/pfx/dosdevices/z:{GAME}/game.txt"
|
||||
cd = f"cd:{self.eqlen_dst}/123/pfx/dosdevices/z:{GAME}/"
|
||||
result = self.run_probe(path, cd)
|
||||
self.assertEqual(result[path], ["1", "library"])
|
||||
self.assertEqual(result[cd], [GAME])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import struct
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
MODULE = runpy.run_path(str(BIN / 'droiddeck-pace-cores'))
|
||||
Frames = MODULE['Frames']
|
||||
Parker = MODULE['Parker']
|
||||
Governor = MODULE['Governor']
|
||||
efficient_cores = MODULE['efficient_cores']
|
||||
paced_interval = MODULE['paced_interval']
|
||||
|
||||
ALL = set(range(8))
|
||||
EFFICIENT = set(range(6))
|
||||
VBLANK = 1e9 / 60
|
||||
CAPACITY = 1024
|
||||
|
||||
|
||||
class FakeCores:
|
||||
|
||||
def __init__(self, tids):
|
||||
self.state = {tid: set(ALL) for tid in tids}
|
||||
|
||||
def get(self, tid):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
return set(self.state[tid])
|
||||
|
||||
def set(self, tid, cpus):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
self.state[tid] = set(cpus)
|
||||
|
||||
|
||||
class FeedWriter:
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self.count = 0
|
||||
self.data = bytearray(128 + CAPACITY * 16)
|
||||
struct.pack_into('<IIII', self.data, 0, 0x46484444, 1, CAPACITY, 0)
|
||||
|
||||
def focus(self, pid, steam=False):
|
||||
struct.pack_into('<I', self.data, 12, pid)
|
||||
struct.pack_into('<IIII', self.data, 28, 1920, 1080, 60000, 1 if steam else 0)
|
||||
self.flush()
|
||||
|
||||
def frames(self, *intervals):
|
||||
for value in intervals:
|
||||
struct.pack_into('<QQ', self.data, 128 + (self.count % CAPACITY) * 16, int(value), 0)
|
||||
self.count += 1
|
||||
struct.pack_into('<Q', self.data, 16, self.count)
|
||||
self.flush()
|
||||
|
||||
def flush(self):
|
||||
self.path.write_bytes(bytes(self.data))
|
||||
|
||||
|
||||
class PacedIntervalTest(unittest.TestCase):
|
||||
def test_a_steady_cap_at_30_fps_or_more_is_paced(self):
|
||||
self.assertAlmostEqual(paced_interval([VBLANK] * 60), VBLANK)
|
||||
self.assertAlmostEqual(paced_interval([1e9 / 30] * 30), 1e9 / 30)
|
||||
jitter = [1e9 / 60 * (1 + 0.03 * (-1) ** i) for i in range(60)]
|
||||
self.assertIsNotNone(paced_interval(jitter))
|
||||
|
||||
def test_under_30_fps_is_not(self):
|
||||
self.assertIsNone(paced_interval([1e9 / 24] * 24))
|
||||
self.assertIsNone(paced_interval([1e9 / 15] * 15))
|
||||
|
||||
def test_a_spread_or_missed_frames_are_not(self):
|
||||
self.assertIsNone(paced_interval([VBLANK] * 50 + [2 * VBLANK] * 10))
|
||||
self.assertIsNone(paced_interval([VBLANK * (0.8 + 0.4 * (i % 5) / 4) for i in range(60)]))
|
||||
self.assertIsNone(paced_interval([]))
|
||||
|
||||
|
||||
class EfficientCoresTest(unittest.TestCase):
|
||||
def test_everything_below_the_top_capacity(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
cpu = Path(temp)
|
||||
(cpu / 'online').write_text('0-7\n')
|
||||
for core in ALL:
|
||||
(cpu / f'cpu{core}').mkdir()
|
||||
(cpu / f'cpu{core}/cpu_capacity').write_text('1024\n' if core >= 6 else '792\n')
|
||||
self.assertEqual(efficient_cores(cpu, set(ALL)), EFFICIENT)
|
||||
self.assertEqual(efficient_cores(cpu, {6, 7}), set())
|
||||
|
||||
def test_one_tier_has_none(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
cpu = Path(temp)
|
||||
(cpu / 'online').write_text('0-3\n')
|
||||
for core in range(4):
|
||||
(cpu / f'cpu{core}').mkdir()
|
||||
(cpu / f'cpu{core}/cpu_capacity').write_text('1024\n')
|
||||
self.assertEqual(efficient_cores(cpu, set(range(4))), set())
|
||||
|
||||
|
||||
class GovernorTest(unittest.TestCase):
|
||||
PID = 400
|
||||
TIDS = (400, 401, 402)
|
||||
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
root = Path(temp.name)
|
||||
for tid in self.TIDS:
|
||||
(root / f'proc/{self.PID}/task/{tid}').mkdir(parents=True)
|
||||
self.cores = FakeCores(self.TIDS)
|
||||
self.feed = FeedWriter(root / 'frames')
|
||||
self.feed.focus(self.PID)
|
||||
self.now = 0.0
|
||||
self.governor = Governor(Frames(root / 'frames'), Parker(EFFICIENT, root / 'proc', self.cores),
|
||||
clock=lambda: self.now)
|
||||
self.governor.tick()
|
||||
|
||||
def run_for(self, seconds, interval):
|
||||
for _ in range(int(seconds / 0.5)):
|
||||
self.now += 0.5
|
||||
self.feed.frames(*([interval] * int(0.5e9 / interval)))
|
||||
self.governor.tick()
|
||||
|
||||
def test_parks_a_game_that_holds_its_pace(self):
|
||||
self.run_for(4, VBLANK)
|
||||
self.assertEqual(self.governor.parker.pid, self.PID)
|
||||
self.assertTrue(all(cpus == EFFICIENT for cpus in self.cores.state.values()))
|
||||
|
||||
def test_releases_when_frames_fall_behind_and_backs_off(self):
|
||||
self.run_for(4, VBLANK)
|
||||
self.run_for(2, 2 * VBLANK)
|
||||
self.assertIsNone(self.governor.parker.pid)
|
||||
self.assertTrue(all(cpus == ALL for cpus in self.cores.state.values()))
|
||||
self.run_for(10, VBLANK)
|
||||
self.assertIsNone(self.governor.parker.pid)
|
||||
self.run_for(30, VBLANK)
|
||||
self.assertEqual(self.governor.parker.pid, self.PID)
|
||||
|
||||
def test_struggling_game_stays_on_every_core(self):
|
||||
for step in range(20):
|
||||
self.now += 0.5
|
||||
self.feed.frames(*([VBLANK, 2 * VBLANK] * 10))
|
||||
self.governor.tick()
|
||||
self.assertIsNone(self.governor.parker.pid)
|
||||
self.assertTrue(all(cpus == ALL for cpus in self.cores.state.values()))
|
||||
|
||||
def test_steam_in_front_releases_without_backoff(self):
|
||||
self.run_for(4, VBLANK)
|
||||
self.feed.focus(self.PID, steam=True)
|
||||
self.now += 0.5
|
||||
self.governor.tick()
|
||||
self.assertTrue(all(cpus == ALL for cpus in self.cores.state.values()))
|
||||
self.feed.focus(self.PID)
|
||||
self.run_for(4, VBLANK)
|
||||
self.assertEqual(self.governor.parker.pid, self.PID)
|
||||
|
||||
def test_a_mask_the_game_set_itself_is_kept(self):
|
||||
self.run_for(4, VBLANK)
|
||||
self.cores.state[401] = {7}
|
||||
self.run_for(2, 2 * VBLANK)
|
||||
self.assertEqual(self.cores.state[401], {7})
|
||||
self.assertEqual(self.cores.state[400], ALL)
|
||||
|
||||
def idle_for(self, seconds):
|
||||
for _ in range(int(seconds / 0.5)):
|
||||
self.now += 0.5
|
||||
self.governor.tick()
|
||||
|
||||
def test_thread_born_parked_is_restored(self):
|
||||
self.run_for(4, VBLANK)
|
||||
(self.governor.parker.proc / f'{self.PID}/task/403').mkdir()
|
||||
self.cores.state[403] = set(EFFICIENT)
|
||||
self.run_for(1, VBLANK)
|
||||
self.run_for(2, 2 * VBLANK)
|
||||
self.assertEqual(self.cores.state[403], ALL)
|
||||
|
||||
def test_a_thread_already_on_efficient_cores_keeps_its_mask(self):
|
||||
self.cores.state[402] = set(EFFICIENT)
|
||||
self.run_for(4, VBLANK)
|
||||
self.run_for(1, VBLANK)
|
||||
self.run_for(2, 2 * VBLANK)
|
||||
self.assertEqual(self.cores.state[402], EFFICIENT)
|
||||
self.assertEqual(self.cores.state[400], ALL)
|
||||
|
||||
def test_a_child_of_a_game_pinned_thread_keeps_its_mask(self):
|
||||
self.cores.state[402] = set(EFFICIENT)
|
||||
self.run_for(4, VBLANK)
|
||||
(self.governor.parker.proc / f'{self.PID}/task/404').mkdir()
|
||||
self.cores.state[404] = set(EFFICIENT)
|
||||
self.run_for(1, VBLANK)
|
||||
self.run_for(2, 2 * VBLANK)
|
||||
self.assertEqual(self.cores.state[404], EFFICIENT)
|
||||
self.assertEqual(self.cores.state[400], ALL)
|
||||
|
||||
def test_a_child_of_a_game_pinned_thread_that_exited_keeps_its_mask(self):
|
||||
self.cores.state[402] = set(EFFICIENT)
|
||||
self.run_for(4, VBLANK)
|
||||
(self.governor.parker.proc / f'{self.PID}/task/402').rmdir()
|
||||
del self.cores.state[402]
|
||||
(self.governor.parker.proc / f'{self.PID}/task/404').mkdir()
|
||||
self.cores.state[404] = set(EFFICIENT)
|
||||
self.run_for(1, VBLANK)
|
||||
self.run_for(2, 2 * VBLANK)
|
||||
self.assertEqual(self.cores.state[404], EFFICIENT)
|
||||
self.assertEqual(self.cores.state[400], ALL)
|
||||
|
||||
def test_born_parked_thread_gets_every_original_it_could_have_had(self):
|
||||
for tid in self.TIDS:
|
||||
self.cores.state[tid] = EFFICIENT | {6}
|
||||
self.cores.state[402] = EFFICIENT | {7}
|
||||
self.run_for(4, VBLANK)
|
||||
(self.governor.parker.proc / f'{self.PID}/task/404').mkdir()
|
||||
self.cores.state[404] = set(EFFICIENT)
|
||||
self.run_for(1, VBLANK)
|
||||
self.run_for(2, 2 * VBLANK)
|
||||
self.assertEqual(self.cores.state[404], ALL)
|
||||
self.assertEqual(self.cores.state[402], EFFICIENT | {7})
|
||||
|
||||
def test_a_stalled_game_is_not_parked_on_old_frames(self):
|
||||
self.run_for(0.5, VBLANK)
|
||||
self.idle_for(3)
|
||||
self.assertIsNone(self.governor.parker.pid)
|
||||
self.run_for(2, VBLANK)
|
||||
self.assertIsNone(self.governor.parker.pid)
|
||||
|
||||
def test_a_parked_game_that_stops_presenting_is_released(self):
|
||||
self.run_for(4, VBLANK)
|
||||
self.run_for(1, 1e9)
|
||||
self.idle_for(1)
|
||||
self.assertIsNone(self.governor.parker.pid)
|
||||
self.assertTrue(all(cpus == ALL for cpus in self.cores.state.values()))
|
||||
|
||||
def test_threads_pinned_to_fast_cores_are_left_alone(self):
|
||||
self.cores.state[402] = {6, 7}
|
||||
self.run_for(4, VBLANK)
|
||||
self.assertEqual(self.cores.state[402], {6, 7})
|
||||
self.assertEqual(self.cores.state[400], EFFICIENT)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -23,6 +23,7 @@ class PipeWireHelperTest(unittest.TestCase):
|
||||
self.helper = self.root / 'droiddeck-pipewire'
|
||||
self.helper.write_text(text)
|
||||
self.environment = dict(os.environ, XDG_RUNTIME_DIR=str(self.runtime))
|
||||
self.started = []
|
||||
|
||||
def pack(self, daemon_body):
|
||||
tree = self.root / 'tree'
|
||||
@@ -36,9 +37,27 @@ class PipeWireHelperTest(unittest.TestCase):
|
||||
archive.add(tree, arcname='.')
|
||||
subprocess.run(['zstd', '-q', '-f', str(tar), '-o', str(self.bundle)], check=True)
|
||||
|
||||
def run_helper(self, *args):
|
||||
def pack_with_stub_zstd(self, delay=''):
|
||||
tree = self.root / 'tree'
|
||||
daemon = tree / 'bin/pipewire'
|
||||
daemon.parent.mkdir(parents=True)
|
||||
daemon.write_text('#!/bin/sh\npython3 -c "import socket,sys; s=socket.socket(socket.AF_UNIX); '
|
||||
's.bind(sys.argv[1]); import time; time.sleep(30)" "$XDG_RUNTIME_DIR/pipewire-0"\n')
|
||||
(tree / 'bin/wireplumber').write_text('#!/bin/sh\nexec sleep 30\n')
|
||||
for script in daemon.parent.iterdir():
|
||||
script.chmod(0o755)
|
||||
with tarfile.open(self.bundle, 'w') as archive:
|
||||
archive.add(tree, arcname='.')
|
||||
stubs = self.root / 'stubs'
|
||||
stubs.mkdir()
|
||||
slow = stubs / 'zstd'
|
||||
slow.write_text('#!/bin/sh\n' + delay + 'exec cat -- "$2"\n')
|
||||
slow.chmod(0o755)
|
||||
self.environment['PATH'] = '%s:%s' % (stubs, os.environ['PATH'])
|
||||
|
||||
def run_helper(self, *args, environment=None):
|
||||
with tempfile.TemporaryFile('w+') as out, tempfile.TemporaryFile('w+') as err:
|
||||
done = subprocess.run(['sh', str(self.helper), *args], env=self.environment, stdout=out, stderr=err,
|
||||
done = subprocess.run(['sh', str(self.helper), *args], env=environment or self.environment, stdout=out, stderr=err,
|
||||
text=True, timeout=15)
|
||||
out.seek(0)
|
||||
err.seek(0)
|
||||
@@ -46,6 +65,8 @@ class PipeWireHelperTest(unittest.TestCase):
|
||||
|
||||
def tearDown(self):
|
||||
self.run_helper('stop')
|
||||
for environment in self.started:
|
||||
self.run_helper('stop', environment=environment)
|
||||
|
||||
def test_env_points_clients_at_the_bundle(self):
|
||||
out = self.run_helper('env').stdout
|
||||
@@ -104,6 +125,39 @@ class PipeWireHelperTest(unittest.TestCase):
|
||||
self.assertIn('could not write the access settings', result.stderr)
|
||||
self.assertFalse((self.runtime / 'droiddeck-pipewire/pids').exists())
|
||||
|
||||
def test_access_settings_are_replaced_atomically_without_leftovers(self):
|
||||
self.pack_with_stub_zstd()
|
||||
self.assertEqual(self.run_helper('start').returncode, 0)
|
||||
fragments = [self.dir / 'share/pipewire/pipewire.conf.d/droiddeck-access.conf',
|
||||
self.dir / 'share/wireplumber/wireplumber.conf.d/droiddeck-access.conf']
|
||||
before = [(f.stat().st_ino, f.read_text()) for f in fragments]
|
||||
held = [f.open() for f in fragments]
|
||||
self.assertEqual(self.run_helper('start').returncode, 0)
|
||||
for handle, (_, text) in zip(held, before):
|
||||
self.assertEqual(handle.read(), text)
|
||||
handle.close()
|
||||
for fragment, (inode, text) in zip(fragments, before):
|
||||
self.assertNotEqual(fragment.stat().st_ino, inode)
|
||||
self.assertEqual(fragment.read_text(), text)
|
||||
self.assertEqual([c.name for c in fragment.parent.iterdir()], [fragment.name])
|
||||
|
||||
def test_concurrent_starts_share_one_unpack(self):
|
||||
self.pack_with_stub_zstd('sleep 1\n')
|
||||
errors = [tempfile.TemporaryFile('w+') for _ in range(3)]
|
||||
for index in range(len(errors)):
|
||||
runtime = self.root / ('run%d' % index)
|
||||
runtime.mkdir()
|
||||
self.started.append(dict(self.environment, XDG_RUNTIME_DIR=str(runtime)))
|
||||
runs = [subprocess.Popen(['sh', str(self.helper), 'start'], env=environment,
|
||||
stdout=subprocess.DEVNULL, stderr=err, text=True)
|
||||
for environment, err in zip(self.started, errors)]
|
||||
for run, err in zip(runs, errors):
|
||||
run.wait(timeout=30)
|
||||
err.seek(0)
|
||||
self.assertEqual(run.returncode, 0, err.read())
|
||||
self.assertTrue((self.dir / 'bin/pipewire').is_file())
|
||||
self.assertFalse((self.lib / 'droiddeck-pipewire.new').exists())
|
||||
|
||||
def test_unchanged_bundle_is_not_unpacked_again(self):
|
||||
self.pack('exec sleep 30')
|
||||
self.run_helper('start')
|
||||
|
||||
@@ -150,6 +150,30 @@ class PreloadSnapshotTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'successful main'):
|
||||
snapshots.artifact_bytes(self.data['origin'], self.root / 'cache')
|
||||
|
||||
def test_origin_apk_without_a_newer_output_reads_the_rest(self):
|
||||
from zipfile import ZipFile
|
||||
newest = 'libddnatv-hook.so'
|
||||
apk = io.BytesIO()
|
||||
with ZipFile(apk, 'w') as z:
|
||||
for name, value in self.binaries.items():
|
||||
if name != newest:
|
||||
z.writestr('assets/linuxfs/' + name, value)
|
||||
outer = io.BytesIO()
|
||||
with ZipFile(outer, 'w') as z:
|
||||
z.writestr('app-release.apk', apk.getvalue())
|
||||
digest = snapshots.sha(outer.getvalue())
|
||||
origin = dict(self.data['origin'], artifact_sha256=digest)
|
||||
build = dict(event='push', head_branch='main', conclusion='success', head_sha=origin['commit'],
|
||||
path='.github/workflows/build.yml', repository=dict(full_name=snapshots.REPO))
|
||||
artifact = dict(name='droiddeck-apk', workflow_run=dict(id=origin['run']), digest='sha256:' + digest)
|
||||
cache = self.root / 'cache'
|
||||
cache.mkdir()
|
||||
(cache / (digest + '.zip')).write_bytes(outer.getvalue())
|
||||
with patch.object(snapshots, 'api', side_effect=[build, artifact]):
|
||||
content = snapshots.artifact_bytes(origin, cache)
|
||||
self.assertNotIn(newest, content)
|
||||
self.assertEqual(set(content), snapshots.FILES - {newest})
|
||||
|
||||
def test_corrupt_archive_is_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'):
|
||||
snapshots.unpack(self.content + b'tampered', self.data)
|
||||
|
||||
@@ -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()
|
||||
@@ -36,6 +36,10 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
service = self.root / 'app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe'
|
||||
service.parent.mkdir(parents=True)
|
||||
service.write_bytes(b'MZ service')
|
||||
rockstar = self.root / 'app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar'
|
||||
rockstar.mkdir(parents=True)
|
||||
(rockstar / 'Launcher32.exe').write_bytes(b'MZ launcher 32')
|
||||
(rockstar / 'Launcher64.exe').write_bytes(b'MZ launcher 64')
|
||||
self.audio(['pactl', 'modules/arm64/module-aaudio-sink.so', 'modules/arm64/module-directaudio-native-sink.so'])
|
||||
self.packs()
|
||||
|
||||
@@ -189,6 +193,46 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'ubisoft pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_an_apk_still_carrying_the_rockstar_service_is_rejected(self):
|
||||
name = 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/Launcher32.exe'
|
||||
self.assertIn(name, runtime.outputs(self.root))
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {name: b'MZ launcher 32'})
|
||||
with self.assertRaisesRegex(ValueError, 'rockstar pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_a_packed_file_the_manifest_does_not_list_is_rejected(self):
|
||||
name = 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/Unlisted.bin'
|
||||
self.assertNotIn(name, runtime.outputs(self.root))
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {name: b'helper data'})
|
||||
with self.assertRaisesRegex(ValueError, 'Unlisted.bin, which the rockstar pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_a_stale_rockstar_pack_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'current.apk')
|
||||
self.pack('rockstar', {'Launcher32.exe': b'MZ older launcher', 'Launcher64.exe': b'MZ launcher 64'})
|
||||
with self.assertRaisesRegex(ValueError, 'rockstar is missing or has a stale'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_an_apk_carrying_any_windows_executable_is_rejected(self):
|
||||
for name in ('assets/linuxfs/usr/local/lib/new-helper/helper.exe', 'assets/anything/renamed.bin', 'res/raw/x.dll'):
|
||||
with self.subTest(name=name):
|
||||
apk = self.current_apk(self.root / 'windows.apk', {name: b'MZ helper'})
|
||||
with self.assertRaisesRegex(ValueError, 'Windows executables.*' + name):
|
||||
runtime.check_apk(apk, self.root)
|
||||
|
||||
def test_an_apk_still_carrying_the_dirt_stand_in_is_rejected(self):
|
||||
dirt = self.root / 'app/src/main/assets/linuxfs/usr/local/lib/droiddeck-dirt'
|
||||
dirt.mkdir(parents=True)
|
||||
(dirt / 'ws2_32.dll').write_bytes(b'MZ droiddeck-dirt-ws2_32')
|
||||
self.packs()
|
||||
name = 'assets/linuxfs/usr/local/lib/droiddeck-dirt/ws2_32.dll'
|
||||
self.assertIn(name, runtime.outputs(self.root))
|
||||
self.assertEqual('dirt', runtime.PACKED['assets/linuxfs/usr/local/lib/droiddeck-dirt/'])
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {name: b'MZ droiddeck-dirt-ws2_32'})
|
||||
with self.assertRaisesRegex(ValueError, 'dirt pack provides'):
|
||||
runtime.check_apk(apk, self.root)
|
||||
runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root)
|
||||
|
||||
def test_an_apk_still_carrying_the_powervr_runtime_is_rejected(self):
|
||||
apk = self.current_apk(self.root / 'bundled.apk', {'assets/hybris/runtime.tzst': b'runtime'})
|
||||
with self.assertRaisesRegex(ValueError, 'powervr pack provides'):
|
||||
|
||||
@@ -2,6 +2,7 @@ import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -128,6 +129,67 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.run_seed(str(sd))
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def manifest(self, name, build):
|
||||
path = self.steam / "steamapps/appmanifest_77.acf"
|
||||
path.write_text('"AppState"\n{\n\t"installdir"\t\t"%s"\n\t"buildid"\t\t"%s"\n}\n' % (name, build))
|
||||
return path
|
||||
|
||||
def test_a_game_is_searched_again_only_when_its_build_changes(self):
|
||||
late = self.steam / "steamapps/common/Late Game/installscript.vdf"
|
||||
late.parent.mkdir(parents=True)
|
||||
manifest = self.manifest("Late Game", "1")
|
||||
self.run_seed()
|
||||
late.write_text(GAME_SCRIPT)
|
||||
manifest.write_text(manifest.read_text() + "\n")
|
||||
self.run_seed()
|
||||
self.assertNotIn("VCRedist2022", self.reg.read_text())
|
||||
self.manifest("Late Game", "2")
|
||||
self.run_seed()
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_one_changed_game_leaves_the_other_games_unsearched(self):
|
||||
other = self.game("Other Game").parent / "installscript_extra.vdf"
|
||||
self.manifest("Late Game", "1")
|
||||
self.run_seed()
|
||||
other.write_text(GAME_SCRIPT.replace("VCRedist2022", "Unsearched"))
|
||||
self.manifest("Late Game", "2")
|
||||
self.run_seed()
|
||||
self.assertNotIn("Unsearched", self.reg.read_text())
|
||||
|
||||
def test_a_call_that_names_its_scripts_does_not_search_the_libraries(self):
|
||||
script = self.game()
|
||||
named = self.tmp / "legacycompat/evaluatorscript_1.vdf"
|
||||
named.parent.mkdir(parents=True)
|
||||
named.write_text(GAME_SCRIPT.replace("VCRedist2022", "Named"))
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_SCRIPTS=str(named))
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
reg = self.reg.read_text()
|
||||
self.assertIn('"Named"=dword:00000001', reg)
|
||||
self.assertNotIn("VCRedist2022", reg)
|
||||
self.run_seed()
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
self.assertIn(str(script), (self.steam / ".droiddeck-game-scripts").read_text())
|
||||
|
||||
def test_a_removed_game_leaves_the_list(self):
|
||||
script = self.game()
|
||||
self.run_seed()
|
||||
cache = self.steam / ".droiddeck-game-scripts"
|
||||
self.assertIn(str(script), cache.read_text())
|
||||
for manifest in (self.steam / "steamapps").glob("appmanifest_*.acf"):
|
||||
manifest.unlink()
|
||||
self.run_seed()
|
||||
self.assertEqual("", cache.read_text())
|
||||
|
||||
def test_a_list_from_an_earlier_version_is_taken_over_without_a_search(self):
|
||||
script = self.steam / "steamapps/common/Old Game/a/b/c/d/e/installscript.vdf"
|
||||
script.parent.mkdir(parents=True)
|
||||
script.write_text(GAME_SCRIPT)
|
||||
self.manifest("Old Game", "1")
|
||||
(self.steam / ".droiddeck-game-scripts").write_text("123 456\n%s\n" % script)
|
||||
self.run_seed()
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
self.assertIn("\t%s\n" % script, (self.steam / ".droiddeck-game-scripts").read_text())
|
||||
|
||||
def test_current_user_and_machine_markers_go_to_their_own_registries(self):
|
||||
self.game(script=GAME_SCRIPT + GAME_SCRIPT.replace("HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER").replace("VCRedist2022", "UserRedist"))
|
||||
with self.reg.open("a") as out:
|
||||
@@ -398,6 +460,62 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2)
|
||||
|
||||
|
||||
def test_a_session_start_leaves_the_library_search_to_a_later_run(self):
|
||||
self.game(script=GAME_SCRIPT.replace("Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022", "SOFTWARE\\\\AGEIA Technologies").replace("VCRedist2022", "PhysX Version"))
|
||||
shim = self.tmp / "bin"
|
||||
shim.mkdir()
|
||||
go = self.tmp / "go"
|
||||
(shim / "find").write_text('#!/bin/sh\ncase "$*" in *"installscript*"*) n=0; while [ ! -e "%s" ] && [ $n -lt 600 ]; do sleep 0.1; n=$((n + 1)); done;; esac\nexec %s "$@"\n' % (go, shutil.which("find")))
|
||||
(shim / "find").chmod(0o755)
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_LATER="1", PATH="%s:%s" % (shim, os.environ["PATH"]))
|
||||
marker = '"PhysX Version"=dword:00000001'
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||
self.assertNotIn(marker, self.reg.read_text())
|
||||
go.touch()
|
||||
deadline = time.monotonic() + 30
|
||||
while marker not in self.reg.read_text() and time.monotonic() < deadline:
|
||||
time.sleep(0.2)
|
||||
self.assertIn(marker, self.reg.read_text())
|
||||
before = self.reg.read_text()
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||
time.sleep(0.5)
|
||||
self.assertEqual(before, self.reg.read_text())
|
||||
|
||||
def test_a_game_whose_search_failed_is_searched_again(self):
|
||||
self.game()
|
||||
broken = self.tmp / "broken"
|
||||
broken.touch()
|
||||
shim = self.tmp / "bin"
|
||||
shim.mkdir()
|
||||
(shim / "find").write_text('#!/bin/sh\n%s "$@"\n[ ! -e "%s" ]\n' % (shutil.which("find"), broken))
|
||||
(shim / "find").chmod(0o755)
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"]))
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, check=True)
|
||||
self.assertNotIn("VCRedist2022", self.reg.read_text())
|
||||
broken.unlink()
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, check=True)
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_a_later_run_leaves_the_registry_alone_while_a_wine_server_runs(self):
|
||||
self.game(script=GAME_SCRIPT.replace("Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022", "SOFTWARE\\\\AGEIA Technologies").replace("VCRedist2022", "PhysX Version"))
|
||||
shim = self.tmp / "bin"
|
||||
shim.mkdir()
|
||||
(shim / "pgrep").write_text("#!/bin/sh\nexit 0\n")
|
||||
(shim / "pgrep").chmod(0o755)
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_LATER="1", PATH="%s:%s" % (shim, os.environ["PATH"]))
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||
cache = self.steam / ".droiddeck-game-scripts"
|
||||
deadline = time.monotonic() + 30
|
||||
while not (cache.exists() and "installscript" in cache.read_text().lower()) and time.monotonic() < deadline:
|
||||
time.sleep(0.2)
|
||||
self.assertIn("installscript", cache.read_text().lower())
|
||||
time.sleep(1)
|
||||
self.assertNotIn("PhysX Version", self.reg.read_text())
|
||||
env.pop("DROIDDECK_SEED_LATER")
|
||||
env["PATH"] = os.environ["PATH"]
|
||||
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
||||
self.assertIn('"PhysX Version"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def evaluator(self, appid, install_script):
|
||||
script = self.tmp / ("legacycompat/evaluatorscript_%s.vdf" % appid)
|
||||
script.parent.mkdir(parents=True)
|
||||
|
||||
@@ -43,6 +43,34 @@ class WebhelperLayoutTest(unittest.TestCase):
|
||||
def test_the_steam_block_uses_it(self):
|
||||
self.assertIn("BL_WEBHELPER_ARGS=$(bl_webhelper_layout)", SESSION.read_text())
|
||||
|
||||
def test_the_gpu_ui_on_the_bridge_defaults_to_angle_on_vulkan_without_vulkan_compositing(self):
|
||||
text = SESSION.read_text()
|
||||
gpu = text.index('elif [ "${_bl_cef[0]}" = -cef-force-gpu ]; then')
|
||||
software = text.rindex('_bl_cef=(-cef-disable-gpu -cef-disable-gpu-compositing)', 0, gpu)
|
||||
defaults = text.index(': "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}"', gpu)
|
||||
self.assertLess(software, gpu)
|
||||
self.assertLess(defaults, text.index("BL_WEBHELPER_ARGS=$(bl_webhelper_layout)", gpu))
|
||||
self.assertLess(defaults, text.index("\n fi\n", gpu))
|
||||
|
||||
def test_the_defaults_give_way_to_settings(self):
|
||||
script = ': "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "bl_webhelper_layout\n"
|
||||
env = {k: v for k, v in os.environ.items() if k not in KEYS}
|
||||
run = lambda **s: subprocess.run(["bash", "-c", "set -u\n" + script], env={**env, **s},
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
self.assertEqual(run(), "--use-gl=angle --use-angle=vulkan")
|
||||
self.assertEqual(run(BL_VKBRIDGE_CEF_VULKAN="1"),
|
||||
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
|
||||
self.assertEqual(run(BL_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl")
|
||||
|
||||
def test_empty_settings_are_kept_as_set(self):
|
||||
script = ': "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "bl_webhelper_layout\n"
|
||||
env = {k: v for k, v in os.environ.items() if k not in KEYS}
|
||||
run = lambda **s: subprocess.run(["bash", "-c", "set -u\n" + script], env={**env, **s},
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
self.assertEqual(run(BL_VKBRIDGE_CEF_ANGLE=""), "stock")
|
||||
self.assertEqual(run(BL_VKBRIDGE_CEF_VULKAN=""),
|
||||
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -99,6 +99,31 @@ class X64RepointTest(unittest.TestCase):
|
||||
self.assertEqual(COMPAT["x64_repoint"](str(self.root), None), [])
|
||||
self.assertEqual((self.root / "config" / "config.vdf").read_text(), before)
|
||||
|
||||
def test_new_owned_shortcut_gets_the_x64_default_and_explicit_choice_stays(self):
|
||||
app = "2350879490"
|
||||
chosen = "proton-cachyos-a64"
|
||||
config = self.root / "config" / "config.vdf"
|
||||
state = self.root / "droiddeck-compat"
|
||||
self.assertEqual(COMPAT["register_default"](
|
||||
str(config), apps=[app], protect={chosen: "proton-cachyos-a64"},
|
||||
default="GE-Proton11-7-a64", directory=str(state),
|
||||
linux_tool="droiddeck-direct", owned=[app]), "GE-Proton11-7-a64")
|
||||
self.assertEqual(self.mapping()[app], "GE-Proton11-7-a64")
|
||||
self.assertEqual(COMPAT["register_default"](
|
||||
str(config), apps=[app], protect={chosen: "proton-cachyos-a64"},
|
||||
default="GE-Proton11-7-a64", directory=str(state),
|
||||
linux_tool="droiddeck-direct", owned=[app]), "GE-Proton11-7-a64")
|
||||
self.assertEqual(self.mapping()[app], "GE-Proton11-7-a64")
|
||||
tokens = COMPAT["tokenize"](config.read_text())
|
||||
mapping = COMPAT["mapping_block"](tokens)
|
||||
COMPAT["set_mapping"](tokens, mapping, app, chosen)
|
||||
config.write_text(COMPAT["serialize"](tokens))
|
||||
COMPAT["register_default"](
|
||||
str(config), apps=[app], protect={chosen: "proton-cachyos-a64"},
|
||||
default="GE-Proton11-7-a64", directory=str(state),
|
||||
linux_tool="droiddeck-direct", owned=[app])
|
||||
self.assertEqual(self.mapping()[app], chosen)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3,6 +3,7 @@ import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -56,6 +57,171 @@ class ImportsTest(unittest.TestCase):
|
||||
self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve())
|
||||
self.assertEqual(b'game', self.exe.read_bytes())
|
||||
|
||||
def steam_install(self, appid=42):
|
||||
library = self.root / 'Library'
|
||||
folder = library / 'steamapps/common/Example'
|
||||
folder.mkdir(parents=True)
|
||||
(folder / 'Example.exe').write_bytes(b'game')
|
||||
(library / f'steamapps/appmanifest_{appid}.acf').write_text(f'"AppState"\n{{\n"appid" "{appid}"\n"installdir" "Example"\n}}\n')
|
||||
saves = library / f'steamapps/compatdata/{appid}/pfx/drive_c/users/steamuser'
|
||||
saves.mkdir(parents=True)
|
||||
(saves / 'save.dat').write_bytes(b'cloud')
|
||||
return dict(self.game, folder=str(folder), exe=str(folder / 'Example.exe'), dir=str(folder)), library
|
||||
|
||||
def shortcut_prefix(self):
|
||||
return self.steam / 'steamapps/compatdata' / str(self.game['appid'] & 0xFFFFFFFF)
|
||||
|
||||
def link_shortcut_prefix(self, target, owned=True):
|
||||
(self.steam / 'steamapps/compatdata').mkdir(parents=True, exist_ok=True)
|
||||
self.shortcut_prefix().symlink_to(target)
|
||||
if owned:
|
||||
imports.save_json(self.steam / 'steamapps' / imports.PREFIX_LINKS,
|
||||
{str(self.shortcut_prefix()): str(target)})
|
||||
|
||||
def test_shortcut_of_a_steam_install_shares_the_steam_apps_prefix(self):
|
||||
game, library = self.steam_install()
|
||||
(self.steam / 'steamapps').mkdir(parents=True)
|
||||
(self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n')
|
||||
games, routes = imports.route(self.steam, self.acct, [game])
|
||||
self.assertEqual(([game], {}), (games, routes))
|
||||
self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve())
|
||||
self.assertEqual(b'cloud', (self.shortcut_prefix() / 'pfx/drive_c/users/steamuser/save.dat').read_bytes())
|
||||
|
||||
def test_matching_install_prefix_precedes_an_older_prefix_in_another_library(self):
|
||||
game, library = self.steam_install()
|
||||
(self.steam / 'steamapps').mkdir(parents=True)
|
||||
(self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n')
|
||||
older = self.steam / 'steamapps/compatdata/42/pfx/drive_c/users/steamuser'
|
||||
older.mkdir(parents=True)
|
||||
(older / 'save.dat').write_bytes(b'old')
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve())
|
||||
self.assertEqual(b'cloud', (self.shortcut_prefix() / 'pfx/drive_c/users/steamuser/save.dat').read_bytes())
|
||||
self.assertEqual(b'old', (older / 'save.dat').read_bytes())
|
||||
|
||||
def test_an_existing_shortcut_prefix_is_never_replaced(self):
|
||||
game, library = self.steam_install()
|
||||
(self.steam / 'steamapps').mkdir(parents=True, exist_ok=True)
|
||||
(self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n')
|
||||
local = self.shortcut_prefix() / 'pfx/drive_c'
|
||||
local.mkdir(parents=True)
|
||||
(local / 'local.dat').write_bytes(b'local')
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertFalse(self.shortcut_prefix().is_symlink())
|
||||
self.assertEqual(b'local', (local / 'local.dat').read_bytes())
|
||||
self.assertEqual(b'cloud', (library / 'steamapps/compatdata/42/pfx/drive_c/users/steamuser/save.dat').read_bytes())
|
||||
|
||||
def test_shortcuts_without_a_manifest_identity_keep_their_own_prefix(self):
|
||||
game, library = self.steam_install()
|
||||
(self.steam / 'steamapps').mkdir(parents=True, exist_ok=True)
|
||||
(self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n')
|
||||
imports.route(self.steam, self.acct, [self.game, dict(game, folder=str(self.folder.parent / 'Other'))])
|
||||
self.assertFalse(os.path.lexists(self.shortcut_prefix()))
|
||||
|
||||
def test_a_manifest_without_a_steam_prefix_links_nothing(self):
|
||||
game, library = self.steam_install()
|
||||
shutil.rmtree(library / 'steamapps/compatdata/42')
|
||||
(self.steam / 'steamapps').mkdir(parents=True, exist_ok=True)
|
||||
(self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n')
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertFalse(os.path.lexists(self.shortcut_prefix()))
|
||||
|
||||
def test_an_older_prefix_in_another_library_is_not_linked_for_a_steam_install(self):
|
||||
game, library = self.steam_install()
|
||||
shutil.rmtree(library / 'steamapps/compatdata/42')
|
||||
(self.steam / 'steamapps').mkdir(parents=True, exist_ok=True)
|
||||
(self.steam / 'steamapps/libraryfolders.vdf').write_text(f'"libraryfolders"\n{{\n"1" {{ "path" "{library}" }}\n}}\n')
|
||||
(self.steam / 'steamapps/compatdata/42/pfx/drive_c').mkdir(parents=True)
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertFalse(os.path.lexists(self.shortcut_prefix()))
|
||||
|
||||
def test_a_dangling_shortcut_prefix_link_is_replaced(self):
|
||||
game, library = self.steam_install()
|
||||
self.link_shortcut_prefix(self.root / 'moved')
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve())
|
||||
|
||||
def test_a_dangling_shortcut_prefix_link_is_removed_without_a_replacement(self):
|
||||
game, library = self.steam_install()
|
||||
shutil.rmtree(library / 'steamapps/compatdata/42')
|
||||
self.link_shortcut_prefix(self.root / 'moved')
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertFalse(os.path.lexists(self.shortcut_prefix()))
|
||||
|
||||
def test_a_link_the_user_made_is_never_changed(self):
|
||||
game, library = self.steam_install()
|
||||
for target in (self.root / 'moved', library / 'steamapps/compatdata/42', self.folder):
|
||||
if os.path.lexists(self.shortcut_prefix()):
|
||||
self.shortcut_prefix().unlink()
|
||||
self.link_shortcut_prefix(target, owned=False)
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertEqual(str(target), os.readlink(self.shortcut_prefix()))
|
||||
|
||||
def test_a_user_link_to_the_matching_prefix_is_never_recorded_or_removed(self):
|
||||
game, library = self.steam_install()
|
||||
target = library / 'steamapps/compatdata/42'
|
||||
self.link_shortcut_prefix(target, owned=False)
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertEqual(str(target), os.readlink(self.shortcut_prefix()))
|
||||
self.assertNotIn(str(self.shortcut_prefix()), imports.read_json(self.steam / 'steamapps' / imports.PREFIX_LINKS, {}))
|
||||
shutil.rmtree(target)
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertTrue(os.path.islink(self.shortcut_prefix()))
|
||||
self.assertEqual(str(target), os.readlink(self.shortcut_prefix()))
|
||||
|
||||
def test_our_link_survives_a_library_that_is_temporarily_missing(self):
|
||||
game, library = self.steam_install()
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
hidden = self.root / 'Hidden'
|
||||
library.rename(hidden)
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertTrue(os.path.islink(self.shortcut_prefix()))
|
||||
hidden.rename(library)
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertEqual(library / 'steamapps/compatdata/42', self.shortcut_prefix().resolve())
|
||||
self.assertEqual(b'cloud', (self.shortcut_prefix() / 'pfx/drive_c/users/steamuser/save.dat').read_bytes())
|
||||
|
||||
def test_our_link_is_dropped_once_its_prefix_is_deleted(self):
|
||||
game, library = self.steam_install()
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
shutil.rmtree(library / 'steamapps/compatdata/42')
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertFalse(os.path.lexists(self.shortcut_prefix()))
|
||||
self.assertEqual({}, imports.read_json(self.steam / 'steamapps' / imports.PREFIX_LINKS, None))
|
||||
|
||||
def test_a_replaced_link_record_is_forgotten_when_the_user_makes_a_real_prefix(self):
|
||||
game, library = self.steam_install()
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.shortcut_prefix().unlink()
|
||||
(self.shortcut_prefix() / 'pfx/drive_c').mkdir(parents=True)
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertFalse(self.shortcut_prefix().is_symlink())
|
||||
self.assertEqual({}, imports.read_json(self.steam / 'steamapps' / imports.PREFIX_LINKS, None))
|
||||
|
||||
def test_a_shortcut_prefix_with_its_own_saves_is_reported_and_kept(self):
|
||||
game, library = self.steam_install()
|
||||
local = self.shortcut_prefix() / 'pfx/drive_c'
|
||||
local.mkdir(parents=True)
|
||||
with patch('builtins.print') as printed:
|
||||
imports.route(self.steam, self.acct, [game])
|
||||
self.assertTrue(local.is_dir())
|
||||
self.assertIn('keeps its own prefix', printed.call_args_list[-1][0][0])
|
||||
|
||||
def test_a_winnative_game_shares_the_prefix_the_steam_client_uses(self):
|
||||
self.winnative_manifest()
|
||||
(self.steam / 'steamapps/libraryfolders.vdf').parent.mkdir(parents=True, exist_ok=True)
|
||||
saves = self.steam / 'steamapps/compatdata/42/pfx/drive_c/users/steamuser'
|
||||
saves.mkdir(parents=True)
|
||||
(saves / 'save.dat').write_bytes(b'cloud')
|
||||
imports.share_prefix(self.steam, self.game)
|
||||
self.assertEqual(self.steam / 'steamapps/compatdata/42', self.shortcut_prefix().resolve())
|
||||
|
||||
def test_an_unreadable_library_does_not_stop_the_routing(self):
|
||||
with patch.object(Path, 'glob', side_effect=PermissionError):
|
||||
games, routes = imports.route(self.steam, self.acct, [self.game])
|
||||
self.assertEqual([self.game], games)
|
||||
self.assertFalse(os.path.lexists(self.shortcut_prefix()))
|
||||
|
||||
def test_store_installs_stay_shortcuts_even_when_owned_on_steam(self):
|
||||
self.snapshot()
|
||||
game = dict(self.game, store='amazon')
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64'
|
||||
SOURCE = SCRIPT.read_text()
|
||||
LIBRARY_LOOP = re.search(r'^for d in "\$STEAM_X64"/steamrt64/.*?^done\nFEX_ROOTFS=', SOURCE, re.M | re.S).group()
|
||||
LIBRARY_LOOP = LIBRARY_LOOP[:LIBRARY_LOOP.rfind('\nFEX_ROOTFS=')]
|
||||
|
||||
|
||||
class SteamX64RuntimeLibsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.steam = self.root / 'Steam'
|
||||
self.runtime = self.steam / 'steamrt64/pv-runtime/steam-runtime-steamrt'
|
||||
self.lib = self.runtime / 'steamrt3c_platform_a/files/lib/x86_64-linux-gnu'
|
||||
self.usr_lib = self.runtime / 'steamrt3c_platform_a/files/usr/lib/x86_64-linux-gnu'
|
||||
self.lib.mkdir(parents=True)
|
||||
self.usr_lib.mkdir(parents=True)
|
||||
self.dest = self.root / 'steamrt-libs'
|
||||
self.dest.mkdir()
|
||||
|
||||
def run_loop(self):
|
||||
shell = 'srt_libs="$DEST"\n' + LIBRARY_LOOP
|
||||
env = dict(os.environ, STEAM_X64=str(self.steam), DEST=str(self.dest))
|
||||
return subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True, timeout=10)
|
||||
|
||||
def test_empty_library_directory_is_skipped(self):
|
||||
(self.usr_lib / 'libexample.so.1').touch()
|
||||
result = self.run_loop()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertTrue((self.dest / 'libexample.so.1').is_symlink())
|
||||
|
||||
def test_two_platform_versions_with_empty_lib_dirs_use_usr_lib(self):
|
||||
platform_b = self.runtime / 'steamrt3c_platform_b'
|
||||
(platform_b / 'files/lib/x86_64-linux-gnu').mkdir(parents=True)
|
||||
usr_lib_b = platform_b / 'files/usr/lib/x86_64-linux-gnu'
|
||||
usr_lib_b.mkdir(parents=True)
|
||||
(self.usr_lib / 'libexample.so.1').touch()
|
||||
(usr_lib_b / 'libother.so.1').touch()
|
||||
result = self.run_loop()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertTrue((self.dest / 'libexample.so.1').is_symlink())
|
||||
self.assertTrue((self.dest / 'libother.so.1').is_symlink())
|
||||
|
||||
def test_stale_literal_glob_link_does_not_abort(self):
|
||||
(self.dest / '*.so*').symlink_to('/missing/*.so*')
|
||||
result = self.run_loop()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertTrue((self.dest / '*.so*').is_symlink())
|
||||
|
||||
def test_existing_dangling_library_link_is_not_recreated(self):
|
||||
(self.lib / 'libexample.so.1').touch()
|
||||
(self.dest / 'libexample.so.1').symlink_to('/missing/libexample.so.1')
|
||||
result = self.run_loop()
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('/missing/libexample.so.1', os.readlink(self.dest / 'libexample.so.1'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -35,6 +35,52 @@ class EaHook(unittest.TestCase):
|
||||
self.assertIn((r'HKEY_LOCAL_MACHINE\SOFTWARE\EA Games\Game', 'DisplayName', 'Mass Effect 3'), entries)
|
||||
self.assertIn((r'HKEY_LOCAL_MACHINE\SOFTWARE\Respawn\Titanfall2', 'DisplayName', 'Mass Effect 3'), entries)
|
||||
|
||||
def test_the_games_exe_maps_to_its_launcher_only(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
folder = Path(tmp) / 'Game'
|
||||
(folder / 'bin').mkdir(parents=True)
|
||||
for name in ('bin/Game.exe', 'bin/Other.exe', store.LAUNCHER):
|
||||
(folder / name).write_text('x')
|
||||
sidecar = {'store': 'ea', 'id': 'Origin.OFR.50.1', 'exe': 'bin/Game.exe', 'launcher': store.LAUNCHER}
|
||||
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
|
||||
self.assertEqual(store.store_launcher(str(folder / 'bin/Game.exe')), str(folder / store.LAUNCHER))
|
||||
self.assertEqual(store.store_launcher(str(folder / 'bin/game.exe')), str(folder / store.LAUNCHER))
|
||||
self.assertIsNone(store.store_launcher(str(folder / 'bin/Other.exe')))
|
||||
self.assertIsNone(store.store_launcher(str(Path(tmp) / 'Elsewhere.exe')))
|
||||
(folder / store.SIDECAR).write_text(json.dumps(dict(sidecar, launcher='')))
|
||||
self.assertIsNone(store.store_launcher(str(folder / 'bin/Game.exe')))
|
||||
|
||||
def test_a_symlinked_or_deep_exe_still_finds_its_launcher(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
folder = Path(tmp) / 'Game'
|
||||
deep = folder / 'a/b/c/d/e/f'
|
||||
deep.mkdir(parents=True)
|
||||
(deep / 'Game.exe').write_text('x')
|
||||
(folder / store.LAUNCHER).write_text('x')
|
||||
sidecar = {'store': 'ea', 'id': 'Origin.OFR.50.1', 'exe': 'a/b/c/d/e/f/Game.exe', 'launcher': store.LAUNCHER}
|
||||
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
|
||||
link = Path(tmp) / 'x/y/z/Link.exe'
|
||||
link.parent.mkdir(parents=True)
|
||||
link.symlink_to(deep / 'Game.exe')
|
||||
expected = str(folder.resolve() / store.LAUNCHER)
|
||||
self.assertEqual(store.store_launcher(str(deep / 'Game.exe')), expected)
|
||||
self.assertEqual(store.store_launcher(str(link)), expected)
|
||||
self.assertIsNone(store.find_store_game([str(deep / 'Game.exe')]))
|
||||
|
||||
def test_a_symlinked_exe_finds_the_sidecar_beside_the_link(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
outside = Path(tmp) / 'Real/Game.exe'
|
||||
outside.parent.mkdir()
|
||||
outside.write_text('x')
|
||||
folder = Path(tmp) / 'Game'
|
||||
folder.mkdir()
|
||||
(folder / store.LAUNCHER).write_text('x')
|
||||
(folder / 'Game.exe').symlink_to(outside)
|
||||
sidecar = {'store': 'ea', 'id': 'Origin.OFR.50.1', 'exe': 'Game.exe', 'launcher': store.LAUNCHER}
|
||||
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
|
||||
self.assertEqual(store.store_launcher(str(folder / 'Game.exe')), str(folder / store.LAUNCHER))
|
||||
self.assertIsNone(store.store_launcher(str(outside)))
|
||||
|
||||
def test_legacy_games_are_registered_by_content_id(self):
|
||||
sidecar = {'id': 'Origin.OFR.50.0005237', 'title': 'Mass Effect 3 (2012)',
|
||||
'extra': {'contentIds': '71073,71183, bad id', 'displayName': 'Mass Effect 3', 'locale': 'fr_FR'}}
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from test_store_launch import store
|
||||
|
||||
|
||||
class RockstarLaunch(unittest.TestCase):
|
||||
def test_service_directory_cannot_export_sessions_outside_the_prefix(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, sidecar, prefix, _, _ = self.setup_game(root)
|
||||
outside = Path(root) / 'outside'
|
||||
outside.mkdir()
|
||||
target = prefix / 'pfx' / store.ROCKSTAR_FOLDER
|
||||
target.parent.mkdir(parents=True)
|
||||
target.symlink_to(outside, target_is_directory=True)
|
||||
sentinel = outside / 'launch.json'
|
||||
sentinel.write_text('keep')
|
||||
with patch.object(store, 'ask') as ask:
|
||||
self.assertEqual('invalid-service-path', store.prepare_rockstar(folder, sidecar, prefix, 'channel'))
|
||||
ask.assert_not_called()
|
||||
self.assertEqual('keep', sentinel.read_text())
|
||||
|
||||
def test_sdk_registration_does_not_use_an_untrusted_display_name_as_a_key(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, _, prefix, _, _ = self.setup_game(root)
|
||||
with patch.object(store, 'wait_for_server', return_value=True):
|
||||
self.assertTrue(store.rockstar_registry(folder, None, prefix, '', sdk_arch='x64'))
|
||||
text = (prefix / 'pfx/system.reg').read_text()
|
||||
self.assertIn(r'[Software\\Rockstar Games\\Rockstar Games Social Club]', text)
|
||||
self.assertNotIn('Grand Theft Auto', text)
|
||||
|
||||
def test_root_metadata_is_found_after_many_assets(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = Path(root)
|
||||
for index in range(300):
|
||||
(folder / ('asset-%s.dat' % index)).write_bytes(b'asset')
|
||||
(folder / 'title.rgl').write_bytes(b'RGLM' + bytes(108))
|
||||
self.assertTrue(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'}))
|
||||
(folder / 'title.rgl').unlink()
|
||||
(folder / 'Title.RGL').write_bytes(b'RGLM' + bytes(108))
|
||||
self.assertTrue(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'}))
|
||||
|
||||
def test_sdk_titles_receive_only_their_short_lived_game_session(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
def change(values):
|
||||
folder, sidecar, _, _, answer = values
|
||||
sidecar['id'] = 'future_title'
|
||||
(folder / 'socialclub.dll').write_bytes(b'game-runtime')
|
||||
answer['session'] = {'accountId': '123', 'identity': 'player@example.invalid', 'ticket': 'game-session',
|
||||
'ScAuthToken': 'never-export-refresh-token'}
|
||||
result, path, _ = self.prepare(root, change)
|
||||
self.assertEqual('ready', result)
|
||||
data = json.loads(path.read_text())
|
||||
self.assertEqual({'accountId', 'identity', 'ticket'}, set(data['session']))
|
||||
self.assertNotIn('pipe', data)
|
||||
self.assertNotIn('material', data)
|
||||
self.assertNotIn('never-export-refresh-token', path.read_text())
|
||||
self.assertEqual(0o600, path.stat().st_mode & 0o777)
|
||||
|
||||
def test_invalid_sdk_sessions_cannot_reuse_an_old_handoff(self):
|
||||
for session in (None, {'accountId': '0', 'identity': 'player', 'ticket': 'session'},
|
||||
{'accountId': '123', 'identity': 'player', 'ticket': 'bad\0session'}):
|
||||
with self.subTest(session=session), tempfile.TemporaryDirectory() as root:
|
||||
def change(values):
|
||||
folder, sidecar, _, _, answer = values
|
||||
sidecar['id'] = 'future_title'
|
||||
(folder / 'socialclub.dll').write_bytes(b'game-runtime')
|
||||
answer['session'] = session
|
||||
result, path, _ = self.prepare(root, change)
|
||||
self.assertEqual('invalid-sdk-session', result)
|
||||
self.assertFalse(path.exists())
|
||||
|
||||
def test_sdk_detection_does_not_follow_external_metadata(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = Path(root) / 'game'
|
||||
folder.mkdir()
|
||||
metadata = Path(root) / 'outside.rgl'
|
||||
metadata.write_bytes(b'RGLM' + bytes(108))
|
||||
(folder / 'title.rgl').symlink_to(metadata)
|
||||
self.assertFalse(store.rockstar_sdk(folder, {'id': 'future_title', 'exe': 'Game.exe'}))
|
||||
|
||||
def test_sdk_installer_cannot_escape_its_architecture_folder(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = Path(root) / 'game'
|
||||
installer = folder / 'Installers/Social-Club-Setup.exe'
|
||||
installer.parent.mkdir(parents=True)
|
||||
installer.write_bytes(b'installer')
|
||||
listing = type('Listing', (), {'returncode': 0, 'stdout': b'Path = x64/../../outside.dll\nSize = 1\n'})()
|
||||
with patch.object(store.shutil, 'which', return_value='/bin/7z'), patch.object(store.subprocess, 'run', return_value=listing):
|
||||
with self.assertRaises(ValueError):
|
||||
store.rockstar_runtime(folder, folder / 'Game.exe', str(Path(root) / 'prefix'), 'x64')
|
||||
self.assertFalse((Path(root) / 'outside.dll').exists())
|
||||
|
||||
def test_other_titles_can_launch_without_the_classic_pipe_service(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = Path(root)
|
||||
sidecar = {'store': 'rockstar', 'id': 'rdr2', 'exe': 'RDR2.exe'}
|
||||
with patch.object(store, 'find_store_game', return_value=(folder, sidecar)), \
|
||||
patch.object(store, 'prepare_rockstar') as prepare, \
|
||||
patch.object(store, 'ask') as ask, patch.dict(os.environ, {}, clear=True):
|
||||
self.assertEqual(store.STORE_GAME, store.main([str(folder / 'RDR2.exe')]))
|
||||
prepare.assert_not_called()
|
||||
ask.assert_not_called()
|
||||
|
||||
def test_classic_authentication_failure_still_stops_launch(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = Path(root)
|
||||
sidecar = {'store': 'rockstar', 'id': 'gtavc', 'exe': 'gta-vc.exe'}
|
||||
with patch.object(store, 'find_store_game', return_value=(folder, sidecar)), \
|
||||
patch.object(store, 'prepare_rockstar', return_value='session-not-owned'), \
|
||||
patch.dict(os.environ, {}, clear=True):
|
||||
self.assertEqual(store.RAN_FAILED, store.main([str(folder / 'gta-vc.exe')]))
|
||||
|
||||
def setup_game(self, root):
|
||||
folder = Path(root) / 'game'
|
||||
folder.mkdir()
|
||||
exe = bytearray(128)
|
||||
exe[:2] = b'MZ'
|
||||
exe[0x3c:0x40] = (64).to_bytes(4, 'little')
|
||||
exe[64:70] = b'PE\0\0\x4c\x01'
|
||||
(folder / 'gta-vc.exe').write_bytes(exe)
|
||||
(folder / 'MTLX.dll').write_bytes(b'vendor')
|
||||
prefix = Path(root) / 'prefix'
|
||||
(prefix / 'pfx').mkdir(parents=True)
|
||||
(prefix / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n')
|
||||
(prefix / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n')
|
||||
service = Path(root) / 'service'
|
||||
service.mkdir()
|
||||
(service / 'Launcher32.exe').write_bytes(b'compiled-helper')
|
||||
sidecar = {'store': 'rockstar', 'id': 'gtavc', 'exe': 'gta-vc.exe', 'args': ['one argument', '&literal']}
|
||||
answer = {'ok': True, 'pipe': 'GTA-VC_Pipe', 'material': 'A' * 640,
|
||||
'expiresAt': int(time.time() * 1000) + 90000, 'ticket': 'must-not-be-exported'}
|
||||
return folder, sidecar, prefix, service, answer
|
||||
|
||||
def prepare(self, root, modify=lambda values: None):
|
||||
values = self.setup_game(root)
|
||||
modify(values)
|
||||
folder, sidecar, prefix, service, answer = values
|
||||
config = prefix / 'pfx' / store.ROCKSTAR_FOLDER / 'launch.json'
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text('stale')
|
||||
requests = []
|
||||
|
||||
def ask(channel, request, timeout):
|
||||
requests.append(request)
|
||||
return answer
|
||||
|
||||
with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True):
|
||||
result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask)
|
||||
return result, config, requests
|
||||
|
||||
def test_handoff_contains_only_launch_fields_and_preserves_argument_boundaries(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
result, path, requests = self.prepare(root)
|
||||
self.assertEqual('ready', result)
|
||||
data = json.loads(path.read_text())
|
||||
self.assertEqual({'folder', 'exe', 'workdir', 'args', 'pipe', 'material', 'expiresAt'}, set(data))
|
||||
self.assertEqual(['one argument', '&literal'], data['args'])
|
||||
self.assertNotIn('must-not-be-exported', path.read_text())
|
||||
self.assertEqual('rockstar-launch', requests[0]['op'])
|
||||
self.assertEqual(b'compiled-helper', path.with_name('Launcher.exe').read_bytes())
|
||||
|
||||
def test_a_missing_service_is_fetched_from_the_app_before_launch(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, sidecar, prefix, service, answer = self.setup_game(root)
|
||||
helper = (service / 'Launcher32.exe').read_bytes()
|
||||
(service / 'Launcher32.exe').unlink()
|
||||
requests = []
|
||||
|
||||
def ask(channel, request, timeout):
|
||||
requests.append(request)
|
||||
if request['op'] == 'store-service':
|
||||
(service / 'Launcher32.exe').write_bytes(helper)
|
||||
return {'ok': True}
|
||||
return answer
|
||||
|
||||
with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True):
|
||||
result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask)
|
||||
self.assertEqual('ready', result)
|
||||
self.assertEqual([{'op': 'store-service', 'store': 'rockstar'}], requests[:1])
|
||||
self.assertEqual('rockstar-launch', requests[1]['op'])
|
||||
|
||||
def test_an_unavailable_service_does_not_request_account_data(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, sidecar, prefix, service, _ = self.setup_game(root)
|
||||
(service / 'Launcher32.exe').unlink()
|
||||
requests = []
|
||||
|
||||
def ask(channel, request, timeout):
|
||||
requests.append(request)
|
||||
return {'ok': False, 'reason': 'service-unavailable'}
|
||||
|
||||
with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True):
|
||||
result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask)
|
||||
self.assertEqual('no-service', result)
|
||||
self.assertEqual(['store-service'], [request['op'] for request in requests])
|
||||
|
||||
def test_rejected_or_expired_sessions_cannot_reuse_stale_material(self):
|
||||
for update in ({'ok': False, 'reason': 'not-owned'}, {'material': 'A' * 641}, {'expiresAt': 1}):
|
||||
with self.subTest(update=update), tempfile.TemporaryDirectory() as root:
|
||||
result, config, _ = self.prepare(root, lambda values: values[4].update(update))
|
||||
self.assertNotEqual('ready', result)
|
||||
self.assertFalse(config.exists())
|
||||
|
||||
def test_path_escape_does_not_request_account_data(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
def change(values):
|
||||
(Path(root) / 'outside.exe').write_bytes(b'MZ')
|
||||
values[1]['exe'] = '../outside.exe'
|
||||
result, config, requests = self.prepare(root, change)
|
||||
self.assertEqual('invalid-game-path', result)
|
||||
self.assertEqual([], requests)
|
||||
self.assertFalse(config.exists())
|
||||
|
||||
def test_writes_both_registry_views_and_escapes_values(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, _, prefix, _, _ = self.setup_game(root)
|
||||
with patch.object(store, 'wait_for_server', return_value=True):
|
||||
self.assertTrue(store.rockstar_registry(folder, 'Grand Theft Auto: Vice City', prefix, ''))
|
||||
text = (prefix / 'pfx/system.reg').read_text()
|
||||
self.assertIn(r'[Software\\Rockstar Games\\Launcher]', text)
|
||||
self.assertIn(r'[Software\\Wow6432Node\\Rockstar Games\\Launcher]', text)
|
||||
self.assertIn('Grand Theft Auto: Vice City', text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,7 +1,13 @@
|
||||
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,
|
||||
parse_variants,
|
||||
@@ -10,6 +16,7 @@ from tools.release.update_catalog import (
|
||||
recent_previews,
|
||||
release_body_value,
|
||||
stable_app_release,
|
||||
unique_previews,
|
||||
)
|
||||
|
||||
|
||||
@@ -56,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(
|
||||
{
|
||||
@@ -149,6 +214,25 @@ pubg com.tencent.ig -pubg
|
||||
self.assertEqual("0.2.0", stable_app_release(releases)["tag_name"])
|
||||
self.assertIsNone(stable_app_release(releases[:1]))
|
||||
|
||||
def test_merged_pr_comes_from_the_first_paragraph(self):
|
||||
body = "**Merged to main** - [PR #2602](https://github.com/Droid-Deck/DroidDeck/pull/2602): fix: x\n\nSee [PR #9](u)."
|
||||
self.assertEqual(2602, merged_pr({"body": body}))
|
||||
self.assertEqual(0, merged_pr({"body": "**Pushed to main** without a PR - fix: x"}))
|
||||
|
||||
def test_previews_follow_commit_order_not_publish_order(self):
|
||||
older = {"commit": "a" * 40, "committedAt": 100, "publishedAt": 900}
|
||||
newer = {"commit": "b" * 40, "committedAt": 200, "publishedAt": 300}
|
||||
again = {**newer, "publishedAt": 50}
|
||||
self.assertEqual([newer, older], unique_previews([older, again, newer]))
|
||||
|
||||
def test_cache_reuses_commit_facts_from_the_last_catalog(self):
|
||||
class NoNetwork:
|
||||
def get(self, path):
|
||||
raise AssertionError(path)
|
||||
|
||||
cache = Cache({"previews": [{"commit": "A" * 40, "author": "dev", "committedAt": 5}]})
|
||||
self.assertEqual({"author": "dev", "committedAt": 5}, cache.commit(NoNetwork(), "o/r", "a" * 40))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,66 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
int unsetenv(const char *name) { return -1; }
|
||||
int setenv(const char *name, const char *value, int overwrite) { return -1; }
|
||||
int putenv(char *string) { return -1; }
|
||||
int main(void) {
|
||||
const char *names[] = {"LIBGL_KOPPER_DISABLE", "LIBGL_KOPPER_DISABLE_X", "ZINK_DEBUG", "VN_DEBUG"};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
const char *value = getenv(names[i]);
|
||||
printf("%s=%s\n", names[i], value ? value : "(unset)");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs cc")
|
||||
class VenusPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
cls.program = cls.tmp / "program"
|
||||
cls.library = cls.tmp / "libvenus.so"
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.program), str(source)], check=True)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-shared", "-fPIC", "-o", str(cls.library),
|
||||
str(PRELOAD / "venus.c")], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def values(self, **extra):
|
||||
env = {"PATH": os.environ.get("PATH", ""), "LD_PRELOAD": str(self.library), **extra}
|
||||
result = subprocess.run([str(self.program)], env=env, capture_output=True, text=True, check=True)
|
||||
return dict(line.split("=", 1) for line in result.stdout.splitlines())
|
||||
|
||||
def test_kopper_is_kept_when_environment_changes_are_refused(self):
|
||||
values = self.values(VN_DEBUG="vtest", LIBGL_KOPPER_DISABLE="true", LIBGL_KOPPER_DISABLE_X="1",
|
||||
ZINK_DEBUG="mem")
|
||||
self.assertEqual(values["LIBGL_KOPPER_DISABLE"], "(unset)")
|
||||
self.assertEqual(values["LIBGL_KOPPER_DISABLE_X"], "1")
|
||||
self.assertEqual(values["ZINK_DEBUG"], "mem")
|
||||
self.assertEqual(values["VN_DEBUG"], "vtest")
|
||||
|
||||
def test_other_sessions_keep_kopper_disabled(self):
|
||||
self.assertEqual(self.values(LIBGL_KOPPER_DISABLE="true")["LIBGL_KOPPER_DISABLE"], "true")
|
||||
self.assertEqual(self.values(VN_DEBUG="init", LIBGL_KOPPER_DISABLE="true")["LIBGL_KOPPER_DISABLE"], "true")
|
||||
|
||||
def test_absent_variable_is_harmless(self):
|
||||
self.assertEqual(self.values(VN_DEBUG="vtest")["LIBGL_KOPPER_DISABLE"], "(unset)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,267 @@
|
||||
import ctypes
|
||||
import mmap
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_clock_pause_preload import clock_reset_command
|
||||
from tools.tests.test_output_refresh import extract_function as extract_void_function
|
||||
from tools.tests.test_scene_limit_hold import extract_function
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/waylandcomp/src/clock_domain.c"
|
||||
HEADER = SOURCE.with_suffix(".h")
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class WaylandClockDomainTest(unittest.TestCase):
|
||||
def test_host_timestamp_uses_the_guest_domain(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
control = root / "clock"
|
||||
control.write_bytes(struct.pack("<q", 10_000_000_000))
|
||||
program = root / "program.c"
|
||||
program.write_text(
|
||||
'#include <stdio.h>\n'
|
||||
'#include "clock_domain.h"\n'
|
||||
'int main(int argc, char **argv) { (void)argc;\n'
|
||||
' droiddeck_clock_domain_set_control(argv[1]);\n'
|
||||
' printf("%lld %u %lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL), '
|
||||
' droiddeck_clock_domain_now_ms(), (long long)droiddeck_clock_domain_adjust_ns(5LL * 1000000000LL));\n'
|
||||
' return 0;\n'
|
||||
'}\n'
|
||||
)
|
||||
binary = root / "program"
|
||||
subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), "-o", str(binary), str(program), str(SOURCE)],
|
||||
check=True)
|
||||
result = subprocess.run([str(binary), str(control)], capture_output=True, text=True, check=True)
|
||||
adjusted, now_ms, clamped = map(int, result.stdout.split())
|
||||
self.assertEqual(adjusted, 20_000_000_000)
|
||||
self.assertGreaterEqual(now_ms, 0)
|
||||
self.assertLessEqual(now_ms, 0xFFFFFFFF)
|
||||
self.assertEqual(clamped, 0)
|
||||
|
||||
def test_paced_release_uses_kernel_time_across_pause_offsets(self):
|
||||
compositor = SOURCE.with_name("compositor.c").read_text()
|
||||
functions = extract_function(compositor, "now_ns") + "\n" + extract_void_function(compositor, "arm_release_timer")
|
||||
harness = r'''
|
||||
#define _GNU_SOURCE
|
||||
#include <assert.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include "clock_domain.h"
|
||||
|
||||
struct pending_release { void *buffer; int64_t at_ns; struct pending_release *next; };
|
||||
static struct pending_release *g_pending_releases;
|
||||
static int g_release_timer_fd;
|
||||
#define wl_list_for_each(pr, list, link) for (pr = *(list); pr; pr = pr->next)
|
||||
static int buffer_release_blocked(void *buffer) { return buffer != NULL; }
|
||||
|
||||
@FUNCTIONS@
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
(void)argc;
|
||||
droiddeck_clock_domain_set_control(argv[1]);
|
||||
int control = open(argv[1], O_WRONLY);
|
||||
assert(control >= 0);
|
||||
g_release_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
|
||||
assert(g_release_timer_fd >= 0);
|
||||
const int64_t offsets[] = {0, 10000000000LL, 300000000000LL};
|
||||
for (unsigned i = 0; i < sizeof(offsets) / sizeof(offsets[0]); i++) {
|
||||
assert(pwrite(control, &offsets[i], sizeof(offsets[i]), 0) == sizeof(offsets[i]));
|
||||
struct timespec started, ended;
|
||||
clock_gettime(CLOCK_MONOTONIC, &started);
|
||||
int64_t start = now_ns();
|
||||
struct pending_release blocked = {(void *)1, start + 1000000LL, NULL};
|
||||
struct pending_release release = {NULL, start + 60000000LL, &blocked};
|
||||
g_pending_releases = &release;
|
||||
arm_release_timer();
|
||||
int64_t next_offset = offsets[i] + 10000000000LL;
|
||||
assert(pwrite(control, &next_offset, sizeof(next_offset), 0) == sizeof(next_offset));
|
||||
struct pollfd pollfd = {g_release_timer_fd, POLLIN, 0};
|
||||
assert(poll(&pollfd, 1, 1000) == 1);
|
||||
clock_gettime(CLOCK_MONOTONIC, &ended);
|
||||
int64_t elapsed = (ended.tv_sec - started.tv_sec) * 1000000000LL + ended.tv_nsec - started.tv_nsec;
|
||||
assert(elapsed >= 50000000LL && elapsed < 1000000000LL);
|
||||
uint64_t expirations;
|
||||
assert(read(g_release_timer_fd, &expirations, sizeof(expirations)) == sizeof(expirations));
|
||||
assert(expirations == 1);
|
||||
g_pending_releases = &blocked;
|
||||
arm_release_timer();
|
||||
struct itimerspec remaining;
|
||||
assert(timerfd_gettime(g_release_timer_fd, &remaining) == 0);
|
||||
assert(remaining.it_value.tv_sec == 0 && remaining.it_value.tv_nsec == 0);
|
||||
}
|
||||
close(g_release_timer_fd);
|
||||
close(control);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
control = root / "clock"
|
||||
control.write_bytes(struct.pack("<q", 0))
|
||||
program = root / "program.c"
|
||||
program.write_text(harness.replace("@FUNCTIONS@", functions))
|
||||
binary = root / "program"
|
||||
subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent),
|
||||
"-o", str(binary), str(program), str(SOURCE)], check=True)
|
||||
subprocess.run([str(binary), str(control)], check=True, timeout=5)
|
||||
|
||||
def test_zero_and_missing_offsets_are_unchanged(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
control = root / "clock"
|
||||
control.write_bytes(struct.pack("<q", 0))
|
||||
program = root / "program.c"
|
||||
program.write_text(
|
||||
'#include <stdio.h>\n'
|
||||
'#include "clock_domain.h"\n'
|
||||
'int main(int argc, char **argv) { (void)argc;\n'
|
||||
' droiddeck_clock_domain_set_control(argv[1]);\n'
|
||||
' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n'
|
||||
' droiddeck_clock_domain_set_control(argv[2]);\n'
|
||||
' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n'
|
||||
' return 0;\n'
|
||||
'}\n'
|
||||
)
|
||||
binary = root / "program"
|
||||
subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), "-o", str(binary), str(program), str(SOURCE)],
|
||||
check=True)
|
||||
result = subprocess.run([str(binary), str(control), str(root / "missing")], capture_output=True, text=True, check=True)
|
||||
self.assertEqual(result.stdout.split(), ["30000000000", "30000000000"])
|
||||
|
||||
def test_replaced_control_file_updates_offset_without_invalidating_readers(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
control = root / "clock"
|
||||
replacement = root / "replacement"
|
||||
control.write_bytes(struct.pack("<q", 10_000_000_000))
|
||||
replacement.write_bytes(struct.pack("<q", 20_000_000_000))
|
||||
program = root / "program.c"
|
||||
program.write_text(
|
||||
'#include <stdio.h>\n'
|
||||
'#include "clock_domain.h"\n'
|
||||
'int main(int argc, char **argv) { (void)argc;\n'
|
||||
' droiddeck_clock_domain_set_control(argv[1]);\n'
|
||||
' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n'
|
||||
' if (rename(argv[2], argv[1]) != 0) return 1;\n'
|
||||
' droiddeck_clock_domain_set_control(argv[1]);\n'
|
||||
' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n'
|
||||
' return 0;\n'
|
||||
'}\n'
|
||||
)
|
||||
binary = root / "program"
|
||||
subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent), "-o", str(binary), str(program), str(SOURCE)],
|
||||
check=True)
|
||||
result = subprocess.run([str(binary), str(control), str(replacement)], capture_output=True, text=True, check=True)
|
||||
self.assertEqual(result.stdout.split(), ["20000000000", "10000000000"])
|
||||
|
||||
def test_session_transition_clears_stale_offset_but_live_failures_preserve_it(self):
|
||||
harness = r'''
|
||||
#include <assert.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <unistd.h>
|
||||
#include "clock_domain.h"
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
(void)argc;
|
||||
int64_t shift = 10000000000LL;
|
||||
int fd = open(argv[1], O_CREAT | O_RDWR, 0600);
|
||||
assert(fd >= 0);
|
||||
assert(write(fd, &shift, sizeof(shift)) == sizeof(shift));
|
||||
droiddeck_clock_domain_set_control(argv[1]);
|
||||
assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 20000000000LL);
|
||||
assert(unlink(argv[1]) == 0);
|
||||
droiddeck_clock_domain_set_control(argv[1]);
|
||||
assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 20000000000LL);
|
||||
int replacement = open(argv[1], O_CREAT | O_RDWR, 0600);
|
||||
assert(replacement >= 0);
|
||||
droiddeck_clock_domain_set_control(argv[1]);
|
||||
assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 20000000000LL);
|
||||
droiddeck_clock_domain_set_control(NULL);
|
||||
droiddeck_clock_domain_set_control(argv[1]);
|
||||
assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 30000000000LL);
|
||||
shift = 20000000000LL;
|
||||
assert(write(replacement, &shift, sizeof(shift)) == sizeof(shift));
|
||||
droiddeck_clock_domain_set_control(argv[1]);
|
||||
assert(droiddeck_clock_domain_adjust_ns(30000000000LL) == 10000000000LL);
|
||||
close(replacement);
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
program = root / "program.c"
|
||||
program.write_text(harness)
|
||||
binary = root / "program"
|
||||
subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent),
|
||||
"-o", str(binary), str(program), str(SOURCE)], check=True)
|
||||
subprocess.run([str(binary), str(root / "clock")], check=True, timeout=5)
|
||||
host = SOURCE.parents[3] / "java/com/droiddeck/launcher/wayland/CompositorHost.kt"
|
||||
self.assertIn("nativeSetClockControl(null)", host.read_text().split("fun newSession() {", 1)[1].split("}", 1)[0])
|
||||
|
||||
def test_startup_reset_keeps_host_and_guest_on_the_same_inode(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
control = root / "clock"
|
||||
control.write_bytes(struct.pack("<q", 10_000_000_000))
|
||||
library = root / "clock.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-pthread", "-Wall", "-Wextra", "-Werror",
|
||||
"-o", str(library), str(SOURCE)], check=True)
|
||||
host = ctypes.CDLL(str(library))
|
||||
host.droiddeck_clock_domain_set_control.argtypes = [ctypes.c_char_p]
|
||||
host.droiddeck_clock_domain_adjust_ns.argtypes = [ctypes.c_int64]
|
||||
host.droiddeck_clock_domain_adjust_ns.restype = ctypes.c_int64
|
||||
host.droiddeck_clock_domain_set_control(str(control).encode())
|
||||
with control.open("r+b") as file, mmap.mmap(file.fileno(), 8) as guest:
|
||||
inode = control.stat().st_ino
|
||||
subprocess.run(["bash", "-c", clock_reset_command(control)],
|
||||
check=True, timeout=5)
|
||||
self.assertEqual(control.stat().st_ino, inode)
|
||||
self.assertEqual(struct.unpack("<q", guest[:])[0], 0)
|
||||
self.assertEqual(host.droiddeck_clock_domain_adjust_ns(30_000_000_000), 30_000_000_000)
|
||||
file.seek(0)
|
||||
file.write(struct.pack("<q", 20_000_000_000))
|
||||
file.flush()
|
||||
self.assertEqual(struct.unpack("<q", guest[:])[0], 20_000_000_000)
|
||||
self.assertEqual(host.droiddeck_clock_domain_adjust_ns(30_000_000_000), 10_000_000_000)
|
||||
host.droiddeck_clock_domain_set_control(None)
|
||||
|
||||
def test_initially_missing_control_is_mapped_after_creation(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
control = root / "clock"
|
||||
replacement = root / "replacement"
|
||||
replacement.write_bytes(struct.pack("<q", 20_000_000_000))
|
||||
program = root / "program.c"
|
||||
program.write_text(
|
||||
'#include <stdio.h>\n'
|
||||
'#include "clock_domain.h"\n'
|
||||
'int main(int argc, char **argv) { (void)argc;\n'
|
||||
' droiddeck_clock_domain_set_control(argv[1]);\n'
|
||||
' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n'
|
||||
' if (rename(argv[2], argv[1]) != 0) return 1;\n'
|
||||
' droiddeck_clock_domain_set_control(argv[1]);\n'
|
||||
' printf("%lld\\n", (long long)droiddeck_clock_domain_adjust_ns(30LL * 1000000000LL));\n'
|
||||
' return 0;\n'
|
||||
'}\n'
|
||||
)
|
||||
binary = root / "program"
|
||||
subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", "-O2", "-I", str(SOURCE.parent),
|
||||
"-o", str(binary), str(program), str(SOURCE)], check=True)
|
||||
result = subprocess.run([str(binary), str(control), str(replacement)], capture_output=True, text=True, check=True)
|
||||
self.assertEqual(result.stdout.split(), ["30000000000", "10000000000"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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,6 +121,66 @@ class WinComponentsTest(unittest.TestCase):
|
||||
self.assertEqual(names, ["ucrtbase"])
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/ucrtbase.dll"), 0x8664)
|
||||
|
||||
def test_x64_dlls_proton_programs_do_not_import_are_placed_in_arm64_system32(self):
|
||||
proton = self.proton()
|
||||
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")
|
||||
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.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()
|
||||
self.component("vc", ["ucrtbase"], {
|
||||
|
||||
@@ -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])
|
||||
@@ -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; }
|
||||
|
||||
Reference in new issue
Block a user