Compare commits

..
Author SHA1 Message Date
The412Banner 93dd562e14 chore(xbox): merge main into the in-place unpack fix
Resolves the legacy-install patch conflict with #3229: its XML manifest
parsing, framework copy rollback and hoist backups are kept alongside the
in-place bundle unpack. The extract-failed message keeps telling apart a
kept download from a container that already gave space back.
2026-11-28 07:50:26 +00:00
The412Banner 47ae756748 fix(xbox): keep the download when the install folder cannot give space back 2026-11-25 19:43:44 +00:00
The412Banner d34ef11bf4 fix(xbox): unpack legacy bundles in place so an install no longer needs twice its size free 2026-11-25 19:29:12 +00:00
41 changed files with 923 additions and 1657 deletions

No files matched your search

@@ -133,24 +133,6 @@ static void objects_destroy(void) {
g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE;
}
void blendp_destroy(void) {
if (g_dev) {
for (int i = 0; i < NSRC; i++) src_release(i);
for (int i = 0; i < NDST; i++) dst_release(i);
for (int i = 0; i < NFMT; i++) {
if (g_out[i].pipe) g_vk.DestroyPipeline(g_dev, g_out[i].pipe, NULL);
if (g_out[i].rp) g_vk.DestroyRenderPass(g_dev, g_out[i].rp, NULL);
}
objects_destroy();
}
memset(g_src, 0, sizeof(g_src));
memset(g_dst, 0, sizeof(g_dst));
memset(g_out, 0, sizeof(g_out));
g_ready = 0;
g_frame = 1;
g_dev = VK_NULL_HANDLE;
}
static int objects_ensure(void) {
if (g_ready) return g_ready == 1 ? 0 : -1;
g_ready = -1;
@@ -4,7 +4,6 @@
#include <vulkan/vulkan.h>
void blendp_bind_device(VkDevice dev);
void blendp_destroy(void);
void blendp_forget_image(VkImage img);
void blendp_begin_frame(void);
@@ -311,16 +311,6 @@ static void objects_destroy(void) {
g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE;
}
void vkp_cardboard_destroy(void) {
if (g_dev) objects_destroy();
g_dev = VK_NULL_HANDLE;
g_ready = 0;
memset(&g_t, 0, sizeof(g_t));
memset(g_src, 0, sizeof(g_src));
g_nsrc = 0;
memset(&g_mp, 0, sizeof(g_mp));
}
static int objects_ensure(void) {
if (g_ready) return g_ready == 1 ? 0 : -1;
if (!g_dev || !g_vk.CreateGraphicsPipelines) goto fail;
@@ -26,7 +26,6 @@ void vkp_cardboard_set_pose_file(const char *path);
void vkp_cardboard_set_render_height(int height);
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
void vkp_cardboard_destroy(void);
int vkp_cardboard_active(void);
int vkp_cardboard_source(void);
int vkp_cardboard_pose_changed(void);
@@ -194,31 +194,7 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable");
}
void vkp_framegen_device_lost(void) {
atomic_store(&g_dev_lost, 1);
atomic_store(&g_dev_ready, 0);
fge_device_lost();
if (g_dev) {
for (uint32_t i = 0; i < g_ring_n; i++) {
if (g_ring[i].view && vk.DestroyImageView) vk.DestroyImageView(g_dev, g_ring[i].view, NULL);
if (g_ring[i].img && vk.DestroyImage) vk.DestroyImage(g_dev, g_ring[i].img, NULL);
if (g_ring[i].mem && vk.FreeMemory) vk.FreeMemory(g_dev, g_ring[i].mem, NULL);
}
}
memset(g_ring, 0, sizeof(g_ring));
g_ring_n = g_ring_w = g_ring_h = 0;
g_ring_fmt = VK_FORMAT_UNDEFINED;
g_engine_ok = 0;
g_engine_kind = -1;
g_engine_cache_gen = -1;
g_built_w = g_built_h = 0;
g_built_fmt = VK_FORMAT_UNDEFINED;
g_planned = 0;
memset(&vk, 0, sizeof(vk));
g_dev = VK_NULL_HANDLE;
g_queue = VK_NULL_HANDLE;
g_qfam = 0;
}
void vkp_framegen_device_lost(void) { atomic_store(&g_dev_lost, 1); }
static void destroy_ring(void) {
@@ -126,23 +126,6 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
(int)g_caps.storageOnSwapchainFormat);
}
void fge_device_lost(void) {
g_lsfg.reset();
g_ddfg.reset();
g_kind = -1;
g_dev = VK_NULL_HANDLE;
g_queue = VK_NULL_HANDLE;
g_pd = VK_NULL_HANDLE;
g_qfam = 0;
g_ready = false;
g_probed = false;
g_table = {};
g_caps = {};
g_v12 = {};
g_f2 = {};
g_build[0] = 0;
}
int fge_caps_ok(int kind) {
if (!g_ready) return 0;
if (kind == 1) return g_caps.storageOnSwapchainFormat ? 1 : 0;
@@ -12,7 +12,6 @@ extern "C" {
const void *fge_probe(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd,
VkFormat ring_fmt);
void fge_device_lost(void);
void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd,
VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled);
int fge_caps_ok(int kind);
@@ -9,7 +9,6 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled) {
(void)gipa; (void)inst; (void)pd; (void)dev; (void)queue; (void)qfam; (void)features_enabled;
}
void fge_device_lost(void) {}
int fge_caps_ok(int kind) { (void)kind; return 0; }
const char *fge_caps_reason(void) { return "frame-generation engines not built into this compositor"; }
int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; }
@@ -73,19 +73,8 @@ void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family) {
}
void vkp_gpu_busy_device_lost(void) {
pthread_mutex_lock(&g_lock);
atomic_store(&g_lost, 1);
atomic_store(&g_timing, 0);
if (g_v.device) {
gpuload_ring_release(&g_ring, &g_v);
g_ring.state = 0;
}
if (g_vk.QueueSubmit == timed_submit && g_submit) g_vk.QueueSubmit = g_submit;
g_submit = NULL;
memset(&g_v, 0, sizeof(g_v));
g_family = g_bits = 0;
g_was_on = 0;
pthread_mutex_unlock(&g_lock);
}
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeGpuBusyNs(JNIEnv *env, jclass cls) {
+3 -3
View File
@@ -15,9 +15,9 @@
X(GetPhysicalDeviceImageFormatProperties2) X(GetPhysicalDeviceProperties2)
#define VK_DEVICE_FUNCS(X) \
X(DestroyDevice) X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
X(CreateCommandPool) X(DestroyCommandPool) X(AllocateCommandBuffers) X(CreateSemaphore) X(CreateFence) \
X(DeviceWaitIdle) X(DestroyFence) X(CreateImage) X(GetImageMemoryRequirements) X(AllocateMemory) \
X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
X(CreateCommandPool) X(AllocateCommandBuffers) X(CreateSemaphore) X(CreateFence) \
X(DeviceWaitIdle) X(CreateImage) X(GetImageMemoryRequirements) X(AllocateMemory) \
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
+15 -290
View File
@@ -31,15 +31,6 @@
#define LOGE(...) droiddeck_log("error", __VA_ARGS__)
#define MOD_INVALID VKP_MOD_INVALID
enum vkp_image_source {
VKP_IMAGE_SOURCE_NONE = 0,
VKP_IMAGE_SOURCE_DMABUF,
VKP_IMAGE_SOURCE_AHB_WLEGL,
VKP_IMAGE_SOURCE_AHB_SOURCE,
VKP_IMAGE_SOURCE_AHB_TARGET,
VKP_IMAGE_SOURCE_SHM
};
struct vkp_image {
VkImage image;
VkDeviceMemory mem;
@@ -56,61 +47,14 @@ struct vkp_image {
VkBuffer linear_buf;
VkDeviceMemory linear_mem;
VkBufferImageCopy linear_copy;
enum vkp_image_source source_type;
int source_fd;
uint32_t source_drm_format, source_stride, source_offset;
uint64_t source_modifier;
uint8_t *recovery_pixels;
struct vkp_image *next;
};
static struct vkp_image *g_client_images;
static struct vkp_image *g_rb;
static int g_recovery_attempted;
static void image_register(struct vkp_image *img) {
if (!img) return;
img->next = g_client_images;
g_client_images = img;
}
static void image_unregister(struct vkp_image *img) {
struct vkp_image **p = &g_client_images;
while (*p && *p != img) p = &(*p)->next;
if (*p) *p = img->next;
if (img) img->next = NULL;
}
static void image_track_dmabuf(struct vkp_image *img, int fd, uint32_t drm_format,
uint64_t modifier, uint32_t stride, uint32_t offset) {
img->source_fd = dup(fd);
img->source_type = img->source_fd >= 0 ? VKP_IMAGE_SOURCE_DMABUF : VKP_IMAGE_SOURCE_NONE;
img->source_drm_format = drm_format;
img->source_modifier = modifier;
img->source_stride = stride;
img->source_offset = offset;
image_register(img);
if (img->source_type == VKP_IMAGE_SOURCE_NONE)
droiddeck_log("gpu", "device recovery unavailable for one DMA-BUF: source FD could not be retained");
}
static void image_track_ahb(struct vkp_image *img, AHardwareBuffer *buffer,
enum vkp_image_source source_type) {
AHardwareBuffer_acquire(buffer);
img->android_buffer = buffer;
img->source_type = source_type;
image_register(img);
}
static void destroy_image_objects(struct vkp_image *img);
static ANativeWindow *g_window;
static int g_ahb_import;
static int g_drm_modifiers;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_allow_driver_fallback;
static int g_dev_state;
static int dev_init(void);
static void device_lost(const char *where);
static const char *vk_result_name(VkResult r);
@@ -574,7 +518,7 @@ static void log_display_driver(void) {
g_library_name);
}
static int dev_init_once(void) {
static int dev_init(void) {
if (g_dev_state != 0) return g_dev_state == 1 ? 0 : -1;
if (vk_loader_open(g_driver_path, g_library_name, g_native_lib_dir) != 0) {
@@ -776,189 +720,6 @@ static int dev_init_once(void) {
return 0;
}
static void suspend_client_images(void) {
for (struct vkp_image *img = g_client_images; img; img = img->next) {
if (img->source_type == VKP_IMAGE_SOURCE_SHM && !img->recovery_pixels)
img->source_type = VKP_IMAGE_SOURCE_NONE;
if (img->map && g_vk.UnmapMemory && g_dev) g_vk.UnmapMemory(g_dev, img->mem);
img->map = NULL;
destroy_image_objects(img);
}
}
static int restore_client_image(struct vkp_image *img) {
if (!img || img->source_type == VKP_IMAGE_SOURCE_NONE) return -1;
struct vkp_image *replacement = NULL;
switch (img->source_type) {
case VKP_IMAGE_SOURCE_DMABUF:
if (img->source_fd >= 0)
replacement = vkp_image_import_dmabuf(img->source_fd, img->source_drm_format, img->source_modifier,
img->w, img->h, img->source_stride, img->source_offset,
img->blit_dst);
break;
case VKP_IMAGE_SOURCE_AHB_WLEGL:
replacement = vkp_image_from_android_buffer(img->android_buffer);
break;
case VKP_IMAGE_SOURCE_AHB_SOURCE:
replacement = vkp_image_from_ahb(img->android_buffer);
break;
case VKP_IMAGE_SOURCE_AHB_TARGET:
replacement = vkp_image_import_ahb(img->android_buffer, NULL, 0);
break;
case VKP_IMAGE_SOURCE_SHM:
replacement = vkp_image_create_shm(img->w, img->h);
break;
default:
break;
}
if (!replacement) return -1;
struct vkp_image *next = img->next;
const enum vkp_image_source old_type = img->source_type;
const int old_fd = img->source_fd;
AHardwareBuffer *old_ahb = img->android_buffer;
uint8_t *pixels = img->recovery_pixels;
image_unregister(replacement);
*img = *replacement;
img->next = next;
free(replacement);
if (old_type == VKP_IMAGE_SOURCE_DMABUF && old_fd >= 0) close(old_fd);
if (old_ahb) AHardwareBuffer_release(old_ahb);
if (old_type == VKP_IMAGE_SOURCE_SHM && pixels && img->map) {
const size_t row_bytes = (size_t)img->w * 4;
for (int y = 0; y < img->h; y++)
memcpy((uint8_t *)img->map + img->offset + (size_t)y * img->row_pitch,
pixels + (size_t)y * row_bytes, row_bytes);
img->recovery_pixels = pixels;
pixels = NULL;
}
free(pixels);
return 0;
}
static int restore_client_images(void) {
int failed = 0;
for (struct vkp_image *img = g_client_images; img; ) {
struct vkp_image *next = img->next;
if (restore_client_image(img) != 0) {
failed++;
droiddeck_log("error", "GPU recovery: could not re-import a retained %dx%d client buffer",
img->w, img->h);
}
img = next;
}
return failed ? -1 : 0;
}
static void release_lost_device(void) {
vkp_pass_abort();
blendp_destroy();
vkp_effects_destroy();
hdrc_destroy();
vkp_cardboard_destroy();
vkp_framegen_device_lost();
vkp_gpu_busy_device_lost();
suspend_client_images();
if (g_rb) {
vkp_image_destroy(g_rb);
g_rb = NULL;
}
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
if (g_scene.mem) g_vk.FreeMemory(g_dev, g_scene.mem, NULL);
memset(&g_scene, 0, sizeof(g_scene));
struct vkp_img_slot *slots[] = {&g_mixed, &g_hdrscene, &g_fgscene};
for (size_t i = 0; i < sizeof(slots) / sizeof(slots[0]); i++) {
if (slots[i]->img) g_vk.DestroyImage(g_dev, slots[i]->img, NULL);
if (slots[i]->mem) g_vk.FreeMemory(g_dev, slots[i]->mem, NULL);
memset(slots[i], 0, sizeof(*slots[i]));
}
if (g_black_img) g_vk.DestroyImage(g_dev, g_black_img, NULL);
if (g_black_mem) g_vk.FreeMemory(g_dev, g_black_mem, NULL);
g_black_img = VK_NULL_HANDLE;
g_black_mem = VK_NULL_HANDLE;
g_black_state = 0;
for (int i = 0; i < MAX_PRESENTS; i++) {
if (g_acqs[i]) g_vk.DestroySemaphore(g_dev, g_acqs[i], NULL);
if (g_rnds[i]) g_vk.DestroySemaphore(g_dev, g_rnds[i], NULL);
g_acqs[i] = g_rnds[i] = VK_NULL_HANDLE;
}
if (g_wait_sem) g_vk.DestroySemaphore(g_dev, g_wait_sem, NULL);
g_wait_sem = VK_NULL_HANDLE;
if (g_fence) g_vk.DestroyFence(g_dev, g_fence, NULL);
g_fence = VK_NULL_HANDLE;
if (g_pool) g_vk.DestroyCommandPool(g_dev, g_pool, NULL);
g_pool = VK_NULL_HANDLE;
memset(g_cmds, 0, sizeof(g_cmds));
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
g_swapchain = VK_NULL_HANDLE;
free(g_images);
g_images = NULL;
g_nimg = 0;
if (g_surface) g_vk.DestroySurfaceKHR(g_inst, g_surface, NULL);
g_surface = VK_NULL_HANDLE;
if (g_dev) g_vk.DestroyDevice(g_dev, NULL);
g_dev = VK_NULL_HANDLE;
if (g_inst) g_vk.DestroyInstance(g_inst, NULL);
g_inst = VK_NULL_HANDLE;
vk_loader_close();
g_pd = VK_NULL_HANDLE;
g_queue = VK_NULL_HANDLE;
g_qfam = 0;
memset(&g_memprops, 0, sizeof(g_memprops));
memset(&g_map, 0, sizeof(g_map));
memset(&g_extent, 0, sizeof(g_extent));
memset(&g_caps_extent, 0, sizeof(g_caps_extent));
g_surface_transform_known = 0;
g_surface_checked_ns = 0;
g_ahb_import = 0;
g_drm_modifiers = 0;
g_colorspace_ext = 0;
g_import_sem_fd = NULL;
g_ahb_properties = NULL;
g_set_hdr_metadata = NULL;
g_swap_extra = 0;
g_swap_is_hdr = 0;
g_swap_fmt = VK_FORMAT_UNDEFINED;
g_swap_md_identity = 0;
g_swap_retry_at_ns = 0;
g_swap_fail_logged = 0;
g_base_black = 0;
g_dev_state = 0;
}
static int dev_init(void) {
if (g_dev_state != -2) return dev_init_once();
if (g_recovery_attempted) return -1;
g_recovery_attempted = 1;
droiddeck_log("gpu", "VK_ERROR_DEVICE_LOST: attempting one in-process compositor recovery");
release_lost_device();
if (dev_init_once() != 0) {
if (g_dev_state == -3) {
droiddeck_log("error", "GPU recovery initialization left completion unknown; retaining resources");
return -1;
}
release_lost_device();
g_dev_state = -2;
droiddeck_log("error", "GPU recovery failed while recreating the Vulkan device; restart the session");
set_fault("the display GPU was lost and in-process recovery failed");
return -1;
}
if (restore_client_images() != 0) {
release_lost_device();
g_dev_state = -2;
droiddeck_log("error", "GPU recovery could not restore every client buffer; restart the session");
set_fault("the display GPU was lost and some client buffers could not be restored");
return -1;
}
g_recovery_attempted = 0;
droiddeck_log("gpu", "Vulkan device and retained client buffers recovered");
return 0;
}
int vkp_ready(void) { return dev_init(); }
static int swap_init_locked(void);
@@ -1455,8 +1216,6 @@ struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
if (result != VK_SUCCESS) goto fail;
AHardwareBuffer_acquire(buffer);
img->android_buffer = buffer;
img->source_type = VKP_IMAGE_SOURCE_AHB_WLEGL;
image_register(img);
return img;
fail:
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
@@ -1608,7 +1367,6 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) {
if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF",
w, h, stride);
image_track_dmabuf(img, fd, drm_format, modifier, stride, offset);
return img;
}
if (padded_target) { free(img); return NULL; }
@@ -1678,12 +1436,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
g_vk.FreeMemory(g_dev, img->mem, NULL); g_vk.DestroyImage(g_dev, img->image, NULL);
free(img); return NULL;
}
image_track_dmabuf(img, fd, drm_format, modifier, stride, offset);
return img;
}
void vkp_wait_idle(void) {
if (g_dev_state == 1 && g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
}
struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
@@ -1733,7 +1490,6 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
}
image_track_ahb(img, ahb, VKP_IMAGE_SOURCE_AHB_SOURCE);
return img;
}
@@ -1829,7 +1585,6 @@ struct vkp_image *vkp_image_import_ahb(struct AHardwareBuffer *ahb, char *info,
if (info && info_n)
snprintf(info, info_n, "VkFormat %d, %llu bytes, memory type %d of memoryTypeBits %#x", (int)fp.format,
(unsigned long long)hp.allocationSize, idx, hp.memoryTypeBits);
image_track_ahb(img, ahb, VKP_IMAGE_SOURCE_AHB_TARGET);
return img;
}
@@ -1883,34 +1638,13 @@ struct vkp_image *vkp_image_create_shm(int w, int h) {
if (g_vk.MapMemory(g_dev, img->mem, 0, req.size, 0, &img->map) != VK_SUCCESS) {
vkp_image_destroy(img); return NULL;
}
img->source_type = VKP_IMAGE_SOURCE_SHM;
image_register(img);
return img;
}
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride) {
if (!img || !data || img->w <= 0 || img->h <= 0 || stride <= 0 ||
(size_t)img->w > SIZE_MAX / 4)
return;
const size_t full_rowbytes = (size_t)img->w * 4;
size_t rowbytes = full_rowbytes;
if (g_dev_state != 1 || !img || !img->map || !data) return;
size_t rowbytes = (size_t)img->w * 4;
if ((size_t)stride < rowbytes) rowbytes = (size_t)stride;
if (img->source_type == VKP_IMAGE_SOURCE_SHM && !img->recovery_pixels) {
if ((size_t)img->h <= SIZE_MAX / full_rowbytes) {
const size_t bytes = full_rowbytes * (size_t)img->h;
img->recovery_pixels = calloc(1, bytes);
}
if (!img->recovery_pixels) img->source_type = VKP_IMAGE_SOURCE_NONE;
}
if (img->source_type == VKP_IMAGE_SOURCE_SHM && img->recovery_pixels) {
for (int y = 0; y < img->h; y++)
memcpy(img->recovery_pixels + (size_t)y * full_rowbytes,
(const uint8_t *)data + (size_t)y * stride, rowbytes);
}
if (g_dev_state != 1 || !img->map) return;
for (int y = 0; y < img->h; y++)
memcpy((uint8_t *)img->map + img->offset + (size_t)y * img->row_pitch,
(const uint8_t *)data + (size_t)y * stride, rowbytes);
@@ -1927,10 +1661,7 @@ void vkp_image_destroy(struct vkp_image *img) {
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
destroy_image_objects(img);
}
image_unregister(img);
if (img->source_type == VKP_IMAGE_SOURCE_DMABUF && img->source_fd >= 0) close(img->source_fd);
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
free(img->recovery_pixels);
free(img);
}
@@ -2194,23 +1925,14 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
}
static void device_lost(const char *where) {
if (g_dev_state == -2 || g_dev_state == -3) return;
if (g_dev_state == 1) {
VkResult idle = g_vk.DeviceWaitIdle ? g_vk.DeviceWaitIdle(g_dev) : VK_ERROR_UNKNOWN;
if (idle != VK_SUCCESS && idle != VK_ERROR_DEVICE_LOST) {
quarantine_pending_work(idle, "device-loss idle");
return;
}
}
if (g_dev_state == -2) return;
g_dev_state = -2;
g_base_black = 0;
vkp_framegen_device_lost();
vkp_gpu_busy_device_lost();
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor will try one in-process recovery",
where);
set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s); recovery pending", where);
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
"restart the session", where);
set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s)", where);
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
g_swapchain = VK_NULL_HANDLE;
@@ -2435,10 +2157,11 @@ static void send_hdr_metadata(const struct droiddeck_color *c) {
static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *how) {
if (how) *how = 0;
if (g_dev_state == -1 || g_dev_state == -3) return -1;
if (g_dev_state < 0) return -1;
vkp_apply_window_request();
sc_layer_hide_base();
check_surface_changed();
if (g_dev_state == -2) return -1;
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
if (g_swapchain && vkp_framegen_extra_images() != g_swap_extra) {
@@ -2783,7 +2506,7 @@ void vkp_signal_first_frame(void) {
}
int vkp_update_map(int scene_w, int scene_h) {
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
if (vkp_quest_layer_presentation()) {
int w = ANativeWindow_getWidth(g_window), h = ANativeWindow_getHeight(g_window);
if (w <= 0 || h <= 0) return -1;
@@ -2857,7 +2580,7 @@ static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_la
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || dev_init() != 0) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -2920,9 +2643,11 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
static struct vkp_image *g_rb;
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
dev_init() != 0)
g_dev_state == -2 || dev_init() != 0)
return -1;
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
if (!g_rb) {
@@ -16,7 +16,7 @@ object DeviceInfo {
val vk = VulkanInfo.query()
val gpu = GpuInfo.detect()
return listOf(
chip(), gpu(context, gpu), npu(context), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
chip(), gpu(context, gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
).filter { it.rows.isNotEmpty() }
}
@@ -51,10 +51,6 @@ object DeviceInfo {
add("Family", read("/sys/devices/soc0/family"))
})
private fun npu(context: Context) = Section("NPU", NpuInfo.rows(
NpuInfo.detect(context.applicationInfo.nativeLibraryDir?.let(::File)),
))
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
add("GPU", gpu.name)
add("Family", gpu.family.label(gpu.name))
@@ -1,71 +0,0 @@
package com.droiddeck.launcher.gpu
import java.io.File
/** What this device's Qualcomm Hexagon NPU would offer a neural upscaler, and whether the app can reach it. */
object NpuInfo {
enum class Hexagon(val arch: String, val vtcmMb: Int) {
V68("v68", 4), V69("v69", 4), V73("v73", 4), V75("v75", 8), V79("v79", 8), V81("v81", 8),
}
enum class Access { OPEN, BROKERED, NO_NODE, DENIED }
data class Status(
val hexagon: Hexagon?,
val node: String?,
val access: Access,
val qnnRuntime: Boolean,
) {
val usable: Boolean get() = hexagon != null && (access == Access.OPEN || access == Access.BROKERED) && qnnRuntime
}
private val BY_MODEL = mapOf(
"SM8350" to Hexagon.V68, "SM8450" to Hexagon.V69, "SM8475" to Hexagon.V69,
"SM8550" to Hexagon.V73, "QCS8550" to Hexagon.V73, "SM8650" to Hexagon.V75,
"SM8750" to Hexagon.V79, "SM8850" to Hexagon.V81,
)
private val BY_PLATFORM = mapOf(
"lahaina" to Hexagon.V68, "taro" to Hexagon.V69, "cape" to Hexagon.V69, "kalama" to Hexagon.V73,
"pineapple" to Hexagon.V75, "sun" to Hexagon.V79, "canoe" to Hexagon.V81,
)
// The compute DSP is the one that runs HTP graphs; /dev/adsprpc-smd is the pre-5.x name of the same service.
internal val NODES = listOf("/dev/fastrpc-cdsp", "/dev/adsprpc-smd", "/dev/cdsprpc-smd")
// Qualcomm's dspservice hands an app a FastRPC fd over binder when the node itself is closed to apps.
internal const val DSP_SERVICE_MANIFEST = "/vendor/etc/vintf/manifest/vendor.qti.hardware.dsp-service.xml"
internal val QNN_LIBS = listOf("libQnnHtp.so", "libQnnSystem.so")
fun hexagon(
model: String = SocNames.model(),
platform: String = GpuInfo.systemProperty("ro.board.platform"),
): Hexagon? = BY_MODEL[SocNames.normalizedModel(model)] ?: BY_PLATFORM[platform.trim().lowercase()]
/** `canWrite` is access(2) for the app's own uid, so it answers for DAC but not SELinux. */
internal fun access(nodes: List<File>, broker: File = File(DSP_SERVICE_MANIFEST)): Pair<File?, Access> {
val present = nodes.firstOrNull { it.exists() } ?: return null to Access.NO_NODE
val access = when {
present.canRead() && present.canWrite() -> Access.OPEN
broker.exists() -> Access.BROKERED
else -> Access.DENIED
}
return present to access
}
fun detect(nativeLibDir: File?, hexagon: Hexagon? = hexagon()): Status {
val (node, access) = access(NODES.map(::File))
val qnn = nativeLibDir != null && QNN_LIBS.all { File(nativeLibDir, it).exists() }
return Status(hexagon, node?.path, access, qnn)
}
fun rows(status: Status): List<Pair<String, String>> = buildList {
add("Hexagon" to (status.hexagon?.let { "${it.arch} (${it.vtcmMb} MB VTCM)" } ?: "not recognised"))
add("FastRPC node" to when (status.access) {
Access.NO_NODE -> "none found"
Access.OPEN -> "${status.node} (app can open it)"
Access.BROKERED -> "${status.node} (closed to apps; the DSP service can hand over a descriptor)"
Access.DENIED -> "${status.node} (app cannot open it)"
})
add("QNN runtime" to if (status.qnnRuntime) "bundled" else "not bundled")
add("Neural upscaling" to if (status.usable) "possible" else "not available")
}
}
@@ -1,54 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
/** Finds the processes a session left running, also once proot is gone and they belong to init. */
object GuestLeftovers {
private const val MARKER = "DD_DEBUG_DIR="
fun find(rootfs: String, ended: File?, skip: Set<Int>): Set<Int> {
val marker = ended?.let { MARKER + it.path }
val parents = HashMap<Int, Int>()
val matched = HashSet<Int>()
File("/proc").listFiles { f -> f.name.all { it.isDigit() } }?.forEach { proc ->
val pid = proc.name.toIntOrNull() ?: return@forEach
parentOf(proc)?.let { parents[pid] = it }
if (pid in skip) return@forEach
val exe = runCatching { File(proc, "exe").canonicalPath }.getOrNull()
// proot runs a guest through its loader, which is then the process's executable
if (exe?.startsWith(rootfs) == true ||
marker != null && carries(runCatching { File(proc, "environ").readBytes() }.getOrNull(), marker)) {
matched.add(pid)
}
}
return withDescendants(matched, parents) - skip
}
internal fun carries(environ: ByteArray?, marker: String): Boolean {
if (environ == null) return false
val wanted = marker.toByteArray()
var start = 0
while (start < environ.size) {
var end = start
while (end < environ.size && environ[end] != 0.toByte()) end++
if (end - start == wanted.size && (0 until wanted.size).all { environ[start + it] == wanted[it] }) return true
start = end + 1
}
return false
}
internal fun withDescendants(roots: Set<Int>, parents: Map<Int, Int>): Set<Int> {
val out = HashSet(roots)
var grew = true
while (grew) {
grew = false
for ((pid, ppid) in parents) if (pid > 1 && ppid in out && out.add(pid)) grew = true
}
return out
}
private fun parentOf(proc: File): Int? {
val stat = runCatching { File(proc, "stat").readText() }.getOrNull() ?: return null
return stat.substringAfterLast(") ").split(' ').getOrNull(1)?.toIntOrNull()
}
}
@@ -1888,11 +1888,21 @@ class SessionService : Service() {
File(directory, STEAM_GAME_REQUEST + ".tmp").delete()
}
private fun killGuestLeftovers(ended: File?) {
private fun killGuestLeftovers() {
val me = android.os.Process.myPid()
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
val leftovers = GuestLeftovers.find(rootfs, ended, OrphanReaper.spared() + android.os.Process.myPid())
leftovers.forEach { android.os.Process.killProcess(it) }
if (leftovers.isNotEmpty()) Log.w(TAG, "killed ${leftovers.size} guest process(es) proot no longer tracked")
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
val spared = OrphanReaper.spared()
var killed = 0
for (proc in procs) {
val pid = proc.name.toIntOrNull() ?: continue
if (pid == me || pid in spared) continue
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
if (!exe.startsWith(rootfs)) continue
android.os.Process.killProcess(pid)
killed++
}
if (killed > 0) Log.w(TAG, "killed $killed guest process(es) proot no longer tracked")
}
private fun killStragglers() {
@@ -2378,7 +2388,7 @@ class SessionService : Service() {
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers(ended)
killGuestLeftovers()
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
@@ -1,49 +0,0 @@
package com.droiddeck.launcher.gpu
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class NpuInfoTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun modelPicksTheHexagonGenerationAndFallsBackToThePlatform() {
assertEquals(NpuInfo.Hexagon.V79, NpuInfo.hexagon("SM8750", "sun"))
assertEquals(NpuInfo.Hexagon.V81, NpuInfo.hexagon("QTI SM8850", ""))
assertEquals(NpuInfo.Hexagon.V73, NpuInfo.hexagon("", "Kalama"))
assertNull(NpuInfo.hexagon("MT6989", "mt6989"))
}
@Test fun nodeAccessSeparatesMissingFromDenied() {
assertEquals(NpuInfo.Access.NO_NODE, NpuInfo.access(listOf(File(tmp.root, "nope"))).second)
val node = tmp.newFile("fastrpc-cdsp")
assertEquals(NpuInfo.Access.OPEN, NpuInfo.access(listOf(File(tmp.root, "nope"), node)).second)
node.setWritable(false)
val absent = File(tmp.root, "no-broker")
if (!node.canWrite()) {
assertEquals(NpuInfo.Access.DENIED, NpuInfo.access(listOf(node), absent).second)
assertEquals(NpuInfo.Access.BROKERED, NpuInfo.access(listOf(node), tmp.newFile("dsp-service.xml")).second)
}
}
@Test fun usableNeedsChipNodeAndRuntime() {
val ok = NpuInfo.Status(NpuInfo.Hexagon.V79, "/dev/fastrpc-cdsp", NpuInfo.Access.OPEN, true)
assertTrue(ok.usable)
assertTrue(ok.copy(access = NpuInfo.Access.BROKERED).usable)
assertFalse(ok.copy(access = NpuInfo.Access.DENIED).usable)
assertFalse(ok.copy(qnnRuntime = false).usable)
assertFalse(ok.copy(hexagon = null).usable)
}
@Test fun runtimeIsBundledOnlyWhenEveryLibraryIsPresent() {
NpuInfo.QNN_LIBS.dropLast(1).forEach { File(tmp.root, it).createNewFile() }
assertFalse(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
File(tmp.root, NpuInfo.QNN_LIBS.last()).createNewFile()
assertTrue(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
}
}
@@ -1,35 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class GuestLeftoversTest {
private fun environ(vararg entries: String) = entries.joinToString("\u0000", postfix = "\u0000").toByteArray()
@Test
fun aProcessOfTheEndedSessionCarriesItsFolder() {
val marker = "DD_DEBUG_DIR=/data/logs/2026-11-28-85-steam"
assertTrue(GuestLeftovers.carries(environ("HOME=/home/deck", marker, "TERM=xterm"), marker))
assertTrue(GuestLeftovers.carries(environ(marker), marker))
}
@Test
fun anotherSessionsFolderOrALongerPathIsNotTheEndedSession() {
val marker = "DD_DEBUG_DIR=/data/logs/2026-11-28-85-steam"
assertFalse(GuestLeftovers.carries(environ("DD_DEBUG_DIR=/data/logs/2026-11-28-86-steam"), marker))
assertFalse(GuestLeftovers.carries(environ("$marker-2"), marker))
assertFalse(GuestLeftovers.carries(environ("X$marker"), marker))
assertFalse(GuestLeftovers.carries(null, marker))
assertFalse(GuestLeftovers.carries(ByteArray(0), marker))
}
@Test
fun whatAMatchedProcessStartedGoesWithIt() {
// 10 was proot's child and now belongs to init; 12 cleared its environment; 20 is unrelated
val parents = mapOf(10 to 1, 11 to 10, 12 to 11, 13 to 12, 20 to 1, 21 to 20)
assertEquals(setOf(10, 11, 12, 13), GuestLeftovers.withDescendants(setOf(10), parents))
assertEquals(emptySet<Int>(), GuestLeftovers.withDescendants(emptySet(), parents))
}
}
-129
View File
@@ -1,129 +0,0 @@
# Neural upscaling on the Hexagon NPU
Reference: [Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale), a Winlator fork that
runs AMD FSR 4 on the Qualcomm Hexagon HTP through QNN, with GPU (DP4a) FSR 4 / XeSS / FSR 3.1 fallbacks. This note
records what carries over to DroidDeck, what does not, and what has been built so far.
## How the reference works
A Vulkan layer in the game's process intercepts the game's own upscaler calls (FSR 2/3/4, DLSS through an NGX
bridge, XeSS) via replacement DLLs. Those calls hand over colour, depth, motion vectors, exposure and jitter. The
layer runs the FSR 4 network (INT8, compiled on the device by `libQnnHtpPrepare.so`) on the NPU, with Vulkan passes
before and after it and `AHardwareBuffer` for the hand-off.
## What carries over, what does not
| Piece | In DroidDeck |
|---|---|
| Game-side hook (DLL replacement, NGX/FFX bridges) | The guest runs Steam under FEX and Proton, so the same Windows-side bridge DLLs could apply, but nothing in the repo loads them yet. |
| Temporal inputs (depth, motion vectors, jitter) | Only exist inside the guest. The Wayland compositor (`waylandcomp`, where FSR 1 / SGSR / frame generation run) sees a finished colour frame, so FSR 4 cannot run there. A compositor-side network would have to be a spatial-only super-resolution model, a different thing from FSR 4. |
| QNN runtime and skel libraries | Qualcomm's, not redistributable here. They would come from the user's own QAIRT SDK or a runtime download. |
| FSR 4 weights | AMD's. The reference ships them in its APK; DroidDeck should not copy them without a licence check. |
| DP4a GPU path | Independent of the NPU and the most portable part. Needs the same guest-side hook. |
## Findings: the NPU is reachable from an unprivileged app
Tested on the Retroid Pocket Duo (SM8750, Hexagon v79) and the AYANEO Pocket FIT Elite (SM8750P, stock, no root).
**The node is closed, but there is a supported way around it.**
- `/dev/fastrpc-cdsp` is `0664 system:system` and the two `-secure` nodes are `0644`. A real app uid (checked with
`run-as` as uid 10185) fails `access(W_OK)`. This is Qualcomm's own `ueventd` setting, not an OEM quirk.
- Qualcomm's `libcdsprpc.so` is not loadable by an app on this firmware: `libcdsprpc.so` and even `libOpenCL.so` fail
with "not found" from an app namespace, with or without `<uses-native-library>`, and a copy would need private
system libraries (`libutils`, `libhidlbase`, `libcutils`). So QNN stubs that `dlopen("libcdsprpc.so")` fail today.
- The vendor AIDL service `vendor.qti.hardware.dsp.IDspService/default` (process `dspservice`, uid `system`) opens
the node on behalf of callers. From the app, `AServiceManager_checkService` returns it,
`getNewDSPSession(int)` returns an `IDspManager`, and `openSession(DSPDomain)` returns a `FastrpcDev` whose
`NativeHandle` carries an open descriptor for `/dev/fastrpc-cdsp`. `readlink` on it gives `/dev/fastrpc-cdsp`.
- On that descriptor, from the app: `FASTRPC_IOCTL_GET_DSP_INFO` (`_IOWR('R', 13, ...)`) succeeds and reports
unsigned-PD support (attribute 1 = 1). `FASTRPC_IOCTL_INIT_ATTACH` returns `EACCES`, and the kernel logs "untrusted
app trying to attach to privileged DSP PD". That is the expected outcome: an app must create an unsigned PD
(`INIT_CREATE`) instead of attaching to the root PD.
Wire format that worked (transaction codes are the AIDL order): `IDspService` 1 = `getNewDSPSession(int)`;
`IDspManager` 2 = `openSession`. The `in DSPDomain` argument is written as `[1 (non-null)][size][domain]`; domain 3 is
the compute DSP. The reply is `[status][1][size][int][int][NativeHandle: size, fd count, fds, int count]`.
`tools/experiments/npu-fastrpc-probe` reproduces all of it; results go to logcat tag `NPUPROBE`.
### AYN Thor (QCS8550, Hexagon v73, Android 13, release-keys): closed
- `/dev/adsprpc-smd` is `0664 system:system` and `open(O_RDWR)` from an app gives `EACCES`. There is no
`/dev/fastrpc-cdsp`.
- There is no `IDspService` here. `checkService` returns null, and SELinux logs a `find` denial for
`untrusted_app` on `default_android_service`.
- `dlopen("libcdsprpc.so")` fails with "not found" even with `<uses-native-library>` declared.
- So no route was found on this device without root. SELinux is enforcing here, which is the case the 8 Elite tests
could not cover.
### How BananaNative's PR (moceure/BananaNative #703) gets in
It declares `<uses-native-library android:name="libcdsprpc.so" android:required="false"/>`, then
`dlopen("libcdsprpc.so")`, `remote_handle_control(4, {domain 3, enable 1})` to request an unsigned PD, and an
`ADSP_LIBRARY_PATH` that puts the app's own `adsp` directory first so the DSP can load the HTP skel from the app.
That only works on firmware that exposes the vendor library to apps; its logs are from a Xiaomi phone on a v81 SoC.
It does not work on the three Qualcomm-reference style builds tried here (Duo, FIT Elite, Thor), where the library is
invisible to app namespaces. Useful from it, if the NPU path goes ahead: a process-wide ref-counted QNN HTP runtime
shared by two users, zero-copy `AHardwareBuffer` DMA-BUF registration, a thermal power tier (turbo, balanced, low)
with hysteresis, and clamping the ADPF target duration to the frame-generated output period so the PowerHAL does not
halve a 2x frame-generated game. Its MIT-licensed GLSL for flow, splat and blend is a possible reference for DD-FG.
Its QNN graph binaries come from a companion repo; where they derive from is a licence question.
Caveats:
- SELinux is permissive on both devices (dev-keys builds). On an enforcing production build, `untrusted_app` may not
be allowed to find `IDspService`, and that has not been tried.
- Nothing has run on the NPU yet. A descriptor and a capability query are not a graph execution.
- The reference fork does not need any of this on devices where the node is world-writable.
## vk-fsr4 (han39835/vk-fsr4, GPL-3.0): FSR 4 INT8 on the GPU, no NPU
An implicit Vulkan layer plus a drop-in replacement for AMD's `amd_fidelityfx_upscaler_vk` provider. It runs FSR 4.1.2
as INT8 compute shaders on any Vulkan GPU with `shaderInt8` and `shaderIntegerDotProduct` (DP4a), and keeps the
cooperative-matrix FP8 path for RDNA 3/4. Aimed at AMD and Linux, but nothing in the INT8 path is vendor specific.
- **Assets:** 31 MB of precompiled SPIR-V for INT8 (1080, 2160 and 4320 tiers, each in `native` and `ultraperf`) plus
quantised weights. The DXIL from AMD's DLL was converted to SPIR-V at build time with `dxil-spirv`, which is not
linked into the provider. The tools to repeat that are in the repo (`tools/extract`, `tools/convert`).
- **Two entry points.** As an FFX provider, games that already call FSR 3/4 through the FFX API get FSR 4 with the
game's own motion vectors, depth and jitter: the exact inputs, and the most robust option. As a layer without the
API (`F4_MV=1`), it guesses which descriptor holds the motion vectors by fingerprinting Unreal TSR layouts. The
author says other engines "may or may not match", so only the provider mode is worth building on.
- **Licence, checked:** the author's claim that the 4.1.2 DLL is MIT licensed holds up. AMD's FidelityFX SDK 2.4.0
`license.md` starts with a restrictive default (binary-only redistribution, no reverse engineering) "except as noted
below". It then lists the files "subject to" an MIT licence, and that list includes
`signedbin/amd_fidelityfx_upscaler_dx12.dll` and `amd_fidelityfx_upscaler_vk.dll`. So the 4.1.x shaders and weights
are redistributable with the MIT notice, which removes the AMD half of the earlier licence concern for that version.
Which SDK version a given weights file came from still has to be pinned (the repo pins 4.1.2.4555 by SHA-256).
Qualcomm's QNN libraries are a separate matter. This is a reading of the licence file, not legal advice.
- **Frame generation:** FSR 4.0.2 ML frame generation is bundled but needs RDNA 4 WMMA, so it is not usable here.
- **Fit with DroidDeck:** GPL-3.0, same as DroidDeck. The provider route would sit in the guest, in front of
vkd3d-proton, where the game's FFX calls arrive. It needs no NPU access, so it works on the Thor.
- **Risk to check first:** the INT8 plan marks most passes `require_wave32`. Adreno runs 64 or 128 wide waves, so
either the passes can run at those widths or they need the variants the Winlator fork's Adreno path uses
(`dvj5411/fsr4vk`). Also unmeasured: INT8 FSR 4 on a handheld GPU may cost more than it saves at 1080p to 4K.
## Built so far
- `gpu/NpuInfo.kt`: maps the SoC model or board platform to a Hexagon generation (v68 to v81, with the VTCM size the
reference caps `vtcmSizeInMB` to), checks whether the app's uid can open the FastRPC node (or the DSP service that
can hand it over), and whether the QNN libraries are bundled. Shown as an "NPU" section in Device info.
- `NpuInfoTest`.
## Next steps, in order
1. Create an unsigned PD on the brokered descriptor (`INIT_CREATE`, with the DSP-side `fastrpc_shell_unsigned_3`) and
invoke one remote call. Qualcomm's open-source userspace library (`quic/fastrpc`, BSD-3) implements this; it would
be built as the app's own `libcdsprpc.so`, with the device open replaced by the binder call above. QNN stubs
resolve `libcdsprpc.so` from the app's library directory, so they would pick it up unchanged.
2. Run a QNN HTP graph with the user's own QAIRT libraries (v79 skel for the 8 Elite) to prove an end-to-end NPU run.
3. Check the binder route on an enforcing 8 Elite build and on an 8 Elite Gen 5 device. Thor (v73) has no route at all.
4. Decide the hook point. Guest-side (Winlator's approach) is the only one that can run FSR 4; compositor-side
limits it to spatial super-resolution.
5. GPU-only FSR 4.1.2 INT8 (DP4a) as an FFX provider in the guest (see vk-fsr4), since it needs no NPU access and
exercises the same plumbing. First measure: wave size on Adreno, and cost per frame on the Thor.
6. Per-architecture QNN cache directories (`v73/`, `v75/`, `v79/`, `v81/`) and a fallback to the GPU path whenever
`NpuInfo.usable` is false.
7. Pin the exact AMD SDK version for any weights that ship (4.1.2.4555 is MIT per the SDK 2.4.0 licence file), keep
the MIT notice with them, and review Qualcomm's QNN licence separately before anything of theirs is bundled or
downloaded.
@@ -1,10 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.probe.npu">
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="34"/>
<application android:label="npuprobe" android:hasCode="false" android:debuggable="true">
<uses-native-library android:name="libcdsprpc.so" android:required="false"/>
<activity android:name="android.app.NativeActivity" android:exported="true">
<meta-data android:name="android.app.lib_name" android:value="npuprobe"/>
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
</activity>
</application>
</manifest>
@@ -1,18 +0,0 @@
#!/usr/bin/env bash
# Builds a Java-less NativeActivity APK that asks the vendor dspservice for a FastRPC fd and probes it.
# Usage: build.sh <out.apk>; then: adb install -r out.apk; adb shell am start -n dev.probe.npu/android.app.NativeActivity
# Results go to logcat, tag NPUPROBE.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
out=${1:?out.apk}
bt=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)
work=$(mktemp -d "$HOME/.cache/npu-probe-build.XXXXXX")
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/lib/arm64-v8a"
clang=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android34-clang
"$clang" -shared -fPIC "$here/probe.c" -o "$work/lib/arm64-v8a/libnpuprobe.so" -llog -landroid -lbinder_ndk -ldl
"$bt/aapt2" link -o "$work/base.apk" --manifest "$here/AndroidManifest.xml" -I "$ANDROID_HOME/platforms/android-34/android.jar"
(cd "$work" && zip -q -u base.apk lib/arm64-v8a/libnpuprobe.so)
"$bt/zipalign" -f 4 "$work/base.apk" "$work/aligned.apk"
"$bt/apksigner" sign --ks "$HOME/.android/debug.keystore" --ks-pass pass:android --key-pass pass:android \
--ks-key-alias androiddebugkey --out "$out" "$work/aligned.apk"
-100
View File
@@ -1,100 +0,0 @@
#include <android/native_activity.h>
#include <android/log.h>
#include <android/binder_ibinder.h>
#include <android/binder_parcel.h>
#include <android/binder_status.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <sys/stat.h>
#define L(...) do { char b[600]; snprintf(b, sizeof b, __VA_ARGS__); __android_log_write(ANDROID_LOG_INFO, "NPUPROBE", b); } while (0)
static void *oc(void *a){return a;} static void od(void *a){} static binder_status_t ot(AIBinder *b, transaction_code_t c, const AParcel *i, AParcel *o){return STATUS_UNKNOWN_TRANSACTION;}
typedef uint32_t remote_handle;
/* Route A: what BananaNative does: dlopen the vendor libcdsprpc from the app namespace. */
static void route_dlopen(void) {
void *h = dlopen("libcdsprpc.so", RTLD_NOW | RTLD_LOCAL);
L("A dlopen(libcdsprpc.so) = %s", h ? "ok" : dlerror());
if (!h) return;
int (*ctl)(int, void *, uint32_t) = dlsym(h, "remote_handle_control");
int (*cap)(int, uint32_t, uint32_t *) = dlsym(h, "fastrpc_get_cap");
int (*opn)(int, const char *, remote_handle *) = dlsym(h, "remote_handle_open_domain");
L("A syms control=%p get_cap=%p open_domain=%p", ctl, cap, opn);
if (ctl) { struct { uint32_t domain, enable; } req = {3, 1}; L("A unsigned-pd control r=%d", ctl(4, &req, sizeof req)); }
if (cap) for (uint32_t i = 0; i < 3; i++) { uint32_t v = 0xdead; int r = cap(3, i, &v); L("A get_cap(cdsp,%u) r=0x%x v=%u", i, r, v); }
if (opn) { remote_handle rh = 0; errno = 0; int r = opn(3, "file:///libhalide_hexagon_remote_skel.so?halide_hexagon_initialize_kernels&_modver=1.0", &rh); L("A open_domain r=0x%x errno=%d", r, errno); }
}
static void dump_dev(AParcel *r) {
int32_t v[16]; int n = 0;
int32_t pos = AParcel_getDataPosition(r), size = AParcel_getDataSize(r);
L("reply pos=%d size=%d", pos, size);
for (int i = 0; i < 12 && AParcel_getDataPosition(r) < size; i++) { int32_t x; if (AParcel_readInt32(r, &x) != STATUS_OK) break; v[n++] = x; L(" int[%d]=%d (0x%x)", i, x, x); }
}
void ANativeActivity_onCreate(ANativeActivity *a, void *s, size_t n) {
L("uid=%d", getuid());
route_dlopen();
{ const char *nodes[] = {"/dev/fastrpc-cdsp", "/dev/adsprpc-smd"};
for (int i = 0; i < 2; i++) { int f = open(nodes[i], O_RDWR | O_CLOEXEC); L("direct open(%s) fd=%d errno=%d", nodes[i], f, errno); if (f >= 0) close(f); } }
const char *name = "vendor.qti.hardware.dsp.IDspService/default";
AIBinder *(*chk)(const char *) = dlsym(RTLD_DEFAULT, "AServiceManager_checkService");
L("dlsym checkService=%p", chk);
if (!chk) return;
AIBinder *svc = chk(name);
L("checkService(%s)=%p", name, svc);
if (!svc) { L("no service (denied or absent)"); return; }
AIBinder_Class *cs = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspService", oc, od, ot);
AIBinder_associateClass(svc, cs);
AIBinder_Class *cm = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspManager", oc, od, ot);
AParcel *in = NULL, *out = NULL;
AIBinder_prepareTransaction(svc, &in);
AParcel_writeInt32(in, 3);
binder_status_t st = AIBinder_transact(svc, 1, &in, &out, 0);
AStatus *as = NULL; AIBinder *mgr = NULL;
if (st == STATUS_OK) { AParcel_readStatusHeader(out, &as); AParcel_readStrongBinder(out, &mgr); }
L("getNewDSPSession: st=%d mgr=%p", st, mgr);
if (!mgr) return;
AIBinder_associateClass(mgr, cm);
int doms[] = {3, 0};
for (int di = 0; di < 2; di++) {
AParcel *i2 = NULL, *o2 = NULL;
AIBinder_prepareTransaction(mgr, &i2);
AParcel_writeInt32(i2, 1); /* non-null */
int32_t start = AParcel_getDataPosition(i2);
AParcel_writeInt32(i2, 0); AParcel_writeInt32(i2, doms[di]);
int32_t end = AParcel_getDataPosition(i2);
AParcel_setDataPosition(i2, start); AParcel_writeInt32(i2, end - start); AParcel_setDataPosition(i2, end);
st = AIBinder_transact(mgr, 2, &i2, &o2, 0);
L("openSession(domain %d): st=%d", doms[di], st);
if (st != STATUS_OK) continue;
AStatus *s2 = NULL; AParcel_readStatusHeader(o2, &s2);
L(" ex=%d", s2 ? AStatus_getExceptionCode(s2) : -1);
int32_t nn, sz, a1, b1, hsz, nf, ni;
AParcel_readInt32(o2, &nn); AParcel_readInt32(o2, &sz); AParcel_readInt32(o2, &a1); AParcel_readInt32(o2, &b1);
AParcel_readInt32(o2, &hsz); AParcel_readInt32(o2, &nf);
L(" nonnull=%d size=%d a=%d b=%d handleSize=%d nfds=%d", nn, sz, a1, b1, hsz, nf);
for (int k = 0; k < nf && k < 4; k++) {
int fd = -1; binder_status_t rs = AParcel_readParcelFileDescriptor(o2, &fd);
char path[256] = "?"; char lp[64]; snprintf(lp, sizeof lp, "/proc/self/fd/%d", fd); ssize_t r = readlink(lp, path, sizeof path - 1); if (r > 0) path[r] = 0;
L(" fd[%d]=%d (rs=%d) -> %s", k, fd, rs, path);
if (fd >= 0) {
struct { uint32_t domain, attr, cap, rsv[4]; } cap;
for (uint32_t at = 0; at < 4; at++) { cap.domain = 3; cap.attr = at; cap.cap = 0xdead; memset(cap.rsv, 0, sizeof cap.rsv); errno = 0;
int ir = ioctl(fd, _IOWR('R', 13, cap), &cap); L(" GET_DSP_INFO attr=%u r=%d errno=%d cap=%u", at, ir, errno, cap.cap); }
errno = 0; int ar = ioctl(fd, _IO('R', 4)); L(" INIT_ATTACH r=%d errno=%d", ar, errno);
uint32_t info = 3; errno = 0; int gr = ioctl(fd, _IOWR('R', 8, uint32_t), &info); L(" GETINFO(R,8) r=%d errno=%d info=%u", gr, errno, info);
}
}
AParcel_readInt32(o2, &ni);
L(" nints=%d", ni);
}
L("done");
}
-30
View File
@@ -444,33 +444,3 @@ starts there as before, but no motion is sent for it. The fake pointer position
With the patch, the Duo starts with only the bottom bar under the parked pointer hovered and controller focus on the
first tile (4 of 4 starts), and returns from a game the same way (3 of 3). Making 0100 ignore the X server's initial
pointer instead was tried and rejected: the centre motion still arrived, and the header or search bar ended up hovered.
## 0143 wlserver: only the first finger drives the emulated mouse
In the Hover, Left, Right, Middle and Trackpad touch click modes every finger warped the X pointer and any finger lifting
released the click. With a second finger down the pointer jumped between both fingers on every frame while the button
stayed held, so a dragged item followed whichever finger moved last, and lifting the second finger dropped it under the
first. The first finger of a gesture now owns the emulated mouse: only it moves the pointer and only its lift releases the
click. Fingers that land while it is down are ignored, and so are the others once it lifts, until every finger is up.
Touches the click modes never claimed (Passthrough, Disabled, no focused surface) still release a held click when they
lift, and the nested pointer (`bAlwaysWarpCursor`) moves the pointer as before. `tools/tests/test_gamescope_touch_click_owner.py`
compiles the rule from this patch.
## 0144 steamcompmgr: motion into the screen edge does not decide the pointer hold
0133 compares the motion gamescope sends with how the X pointer moves. At the edge of the X screen the pointer cannot move
further, so a drawn-cursor game whose pointer sat at an edge while touch or mouse motion pushed outward counted as
holding the pointer: the hold stayed on, every such frame restarted the 30 frames needed to release it, and touch drags
kept turning into relative motion with no button held. The sent motion is now clamped to what the pointer can reach
inside the X screen before it is compared, so motion into an edge counts as no motion. A recentring game is detected as
before, since its pointer stays away from the edges. `tools/tests/test_gamescope_pointer_hold_edge.py` compiles the rule
from this patch with the 0133 rule.
## 0145 steamcompmgr: touch-down warps do not decide the pointer hold
In click mode every touch-down warps the X pointer to the finger. 0133 read that jump as the pointer not following the
sent motion, so each new stroke on a drawn-cursor game restarted the 30 following frames needed to release the hold.
Short strokes never released it, and taps kept landing at the relative pointer instead of under the finger. wlserver now
counts its touch-down warps, and a frame that contains one is left out of the hold decision. Touch drags, mouse motion
and mouse warps still count, so a drag on a game that follows the pointer releases the hold and a recentring game is
still held. `tools/tests/test_gamescope_pointer_hold_touch_down.py` compiles the rule with the 0133 rule.
@@ -1,75 +0,0 @@
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index 9740875..cb72051 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -3283,6 +3283,38 @@ static void apply_touchscreen_orientation(GamescopePanelOrientation orientation,
*y = ty;
}
+struct TouchClickState
+{
+ std::set<int> ids;
+ int nOwner = -1;
+};
+
+static TouchClickState s_TouchClick;
+
+static bool touch_click_claim( TouchClickState &state, int nTouchId )
+{
+ if ( state.ids.empty() )
+ state.nOwner = nTouchId;
+ state.ids.insert( nTouchId );
+ return state.nOwner == nTouchId;
+}
+
+static bool touch_click_drives( const TouchClickState &state, int nTouchId )
+{
+ return state.nOwner == nTouchId;
+}
+
+static bool touch_click_lift( TouchClickState &state, int nTouchId )
+{
+ const bool bTracked = state.ids.erase( nTouchId ) > 0;
+ if ( state.nOwner == nTouchId )
+ {
+ state.nOwner = -1;
+ return true;
+ }
+ return !bTracked && state.nOwner < 0;
+}
+
void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool bAlwaysWarpCursor, gamescope::IBackendConnector* connector )
{
assert( wlserver_is_lock_held() );
@@ -3333,9 +3365,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
}
else if ( eMode == gamescope::TouchClickModes::Trackpad )
{
- wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
+ if ( touch_click_drives( s_TouchClick, touch_id ) )
+ wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
}
- else
+ else if ( bAlwaysWarpCursor || touch_click_drives( s_TouchClick, touch_id ) )
{
g_bPendingTouchMovement = true;
@@ -3389,7 +3422,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
{
return;
}
- else
+ else if ( touch_click_claim( s_TouchClick, touch_id ) )
{
g_bPendingTouchMovement = true;
@@ -3417,7 +3450,8 @@ void wlserver_touchup( int touch_id, uint32_t time )
// Release whatever the touch pressed even if its surface is gone, or the seat keeps the button down.
bool bReleasedAny = false;
- for ( int i = 0; i < WLSERVER_BUTTON_COUNT; i++ )
+ const bool bClickTouch = touch_click_lift( s_TouchClick, touch_id );
+ for ( int i = 0; bClickTouch && i < WLSERVER_BUTTON_COUNT; i++ )
{
if ( wlserver.button_held[ i ] == true )
{
@@ -1,28 +0,0 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index e98d320..85af598 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -3245,6 +3245,11 @@ static bool pointer_hold_step( PointerHold &state, bool bConstrained, double flS
return state.bHeld;
}
+static double pointer_reach( int nFrom, double flDelta, int nSize )
+{
+ return std::clamp( nFrom + flDelta, 0.0, double( std::max( nSize - 1, 0 ) ) ) - nFrom;
+}
+
static bool s_bPointerHeld = false;
static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool bHinted )
@@ -3311,7 +3316,10 @@ static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool
if ( s_bTracking )
{
- s_bPointerHeld = pointer_hold_step( s_Hold, true, flDX, flDY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
+ const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
+ const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
+ const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
+ s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
}
else
{
@@ -1,73 +0,0 @@
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
--- a/src/wlserver.hpp
+++ b/src/wlserver.hpp
@@ -173,6 +173,7 @@
double flFollowDY = 0.0;
double flSentDX = 0.0;
double flSentDY = 0.0;
+ uint64_t ulTouchDownWarps = 0;
bool button_held[ WLSERVER_BUTTON_COUNT ];
std::set <uint32_t> touch_down_ids;
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -3429,6 +3429,7 @@
if ( eMode != gamescope::TouchClickModes::Trackpad )
{
wlserver_mousewarp( tx, ty, time, false, true );
+ wlserver.ulTouchDownWarps++;
}
uint32_t button = TouchClickModeToLinuxButton( eMode );
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -3263,6 +3263,7 @@
static bool s_bHinted = false;
static const steamcompmgr_win_t *s_pWindow = nullptr;
static const struct wlr_pointer_constraint_v1 *s_pConstraint = nullptr;
+ static uint64_t s_ulTouchDownWarps = 0;
wlserver_lock();
const double flX = wlserver.mouse_surface_cursorx;
@@ -3272,8 +3273,12 @@
const struct wlr_pointer_constraint_v1 *pConstraint = wlserver.GetCursorConstraint();
wlserver.flSentDX = 0.0;
wlserver.flSentDY = 0.0;
+ const uint64_t ulTouchDownWarps = wlserver.ulTouchDownWarps;
wlserver_unlock();
+ const bool bTouchDown = ulTouchDownWarps != s_ulTouchDownWarps;
+ s_ulTouchDownWarps = ulTouchDownWarps;
+
if ( !bConstrained || !pFocus->cursor )
{
s_bTracking = false;
@@ -3314,19 +3319,19 @@
int nRootY = 0;
pFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
- if ( s_bTracking )
+ if ( !s_bTracking )
+ {
+ s_Hold = PointerHold{};
+ s_Hold.bHeld = bHinted;
+ s_bPointerHeld = bHinted;
+ }
+ else if ( !bTouchDown )
{
const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
}
- else
- {
- s_Hold = PointerHold{};
- s_Hold.bHeld = bHinted;
- s_bPointerHeld = bHinted;
- }
s_bTracking = true;
s_flSeatX = flX;
-1
View File
@@ -10,7 +10,6 @@ export SHELL=/bin/bash
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export QTWEBENGINE_DISABLE_SANDBOX=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
export KWIN_USE_OVERLAYS=0
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
@@ -12,7 +12,6 @@ fi
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export QTWEBENGINE_DISABLE_SANDBOX=1
if [ -s /etc/ld.so.preload ]; then
preload=$(tr -s '\n' ':' < /etc/ld.so.preload)
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
+1 -6
View File
@@ -6,7 +6,7 @@ import unittest
from pathlib import Path
RUN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-appimage-run"
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI", "QTWEBENGINE_DISABLE_SANDBOX")
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI")
QUICK = ("usr/lib/libQt6Quick.so.6", "usr/lib/libvulkan.so.1", "usr/plugins/platforms/libqwayland-generic.so")
RUN_MODE = {"GAMESCOPE_WAYLAND_DISPLAY": "gamescope-0", "WAYLAND_DISPLAY": "gamescope-0", "DISPLAY": ":0",
"QT_QPA_PLATFORM": "xcb", "SDL_VIDEODRIVER": "x11", "XDG_SESSION_TYPE": "x11"}
@@ -128,11 +128,6 @@ class AppImageRunTest(unittest.TestCase):
self.assertEqual("wayland;xcb", env["QT_QPA_PLATFORM"])
def test_a_web_engine_app_starts_as_root_in_either_session(self):
for session in (RUN_MODE, DESKTOP):
env, _ = self.launch(session)
self.assertEqual("1", env["QTWEBENGINE_DISABLE_SANDBOX"])
def test_a_program_drops_the_sessions_sysmem_like_a_steam_game(self):
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem", DROIDDECK_GAME_TU_DEBUG=""))
self.assertEqual("unset", env["TU_DEBUG"])
-36
View File
@@ -1,36 +0,0 @@
import os
from pathlib import Path
import subprocess
import unittest
TOOLS = Path(__file__).resolve().parents[1]
DESKTOP = (TOOLS / "linuxfs/desktop/droiddeck-desktop").read_text()
PACKAGES = (TOOLS / "ubuntu/packages-desktop.txt").read_text().split()
SANDBOXES = ("MOZ_DISABLE_CONTENT_SANDBOX", "MOZ_SHM_NO_SEALS", "QTWEBENGINE_DISABLE_SANDBOX")
class DesktopRootAppsTest(unittest.TestCase):
def desktop_environment(self):
head = DESKTOP[:DESKTOP.index("\nexport KWIN_COMPOSE=")]
env = {k: v for k, v in os.environ.items() if k not in SANDBOXES}
probe = "".join('echo %s=${%s-unset}\n' % (name, name) for name in SANDBOXES)
result = subprocess.run(["bash", "-c", head + "\nsh -c '" + probe + "'"], env=env,
capture_output=True, text=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
return dict(line.split("=", 1) for line in result.stdout.splitlines())
def test_web_engine_apps_start_as_root_like_firefox(self):
self.assertEqual({name: "1" for name in SANDBOXES}, self.desktop_environment())
def test_the_sandbox_switches_are_set_before_plasma(self):
self.assertLess(DESKTOP.index("export QTWEBENGINE_DISABLE_SANDBOX=1"),
DESKTOP.index("dbus-run-session -- startplasma-wayland"))
def test_software_sources_gets_the_modules_it_imports(self):
self.assertIn("software-properties-qt", PACKAGES)
for module in ("pyqt6-dev-tools", "ubuntu-drivers-common"):
self.assertIn(module, PACKAGES)
if __name__ == "__main__":
unittest.main()
@@ -163,14 +163,6 @@ typedef struct {
#define droiddeck_log(...) ((void)0)
#define LOGE(...) ((void)0)
struct droiddeck_color { uint32_t identity; };
enum vkp_image_source {
VKP_IMAGE_SOURCE_NONE = 0,
VKP_IMAGE_SOURCE_DMABUF,
VKP_IMAGE_SOURCE_AHB_WLEGL,
VKP_IMAGE_SOURCE_AHB_SOURCE,
VKP_IMAGE_SOURCE_AHB_TARGET,
VKP_IMAGE_SOURCE_SHM
};
typedef struct AHardwareBuffer AHardwareBuffer;
'''
@@ -1,102 +0,0 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
HOLD = ROOT / "tools/gamescope/patches/0133-constraint-relative-when-held.patch"
EDGE = ROOT / "tools/gamescope/patches/0144-pointer-hold-ignores-motion-into-the-edge.patch"
def added_source(patch):
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 <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
'''
MAIN = r'''
static const uint64_t FRAME = 16'666'667ul;
struct Pointer {
PointerHold hold;
int x;
int width;
uint64_t now = 1'000'000'000ul;
bool step(double seatDX, int pointerDX) {
now += FRAME;
const double reach = pointer_reach(x, seatDX, width);
x += pointerDX;
return pointer_hold_step(hold, true, reach, 0.0, pointerDX, 0.0, now);
}
};
int main() {
assert(pointer_reach(1279, 26.0, 1280) == 0.0);
assert(pointer_reach(1270, 26.0, 1280) == 9.0);
assert(pointer_reach(0, -13.0, 1280) == 0.0);
assert(pointer_reach(640, -13.0, 1280) == -13.0);
assert(pointer_reach(5, 3.0, 0) == -5.0);
Pointer pinned{{}, 1279, 1280};
for (int i = 0; i < 20; i++) assert(!pinned.step(26.0, 0));
Pointer release{{}, 1279, 1280};
release.hold.bHeld = true;
for (int i = 0; i < 20; i++) assert(release.step(26.0, 0));
for (int i = 0; i < 10; i++) assert(release.step(-13.0, -13));
for (int i = 0; i < 10; i++) assert(release.step(13.0, 13));
assert(release.x == 1279);
for (int i = 0; i < 20; i++) assert(release.step(26.0, 0));
for (int i = 0; i < 9; i++) assert(release.step(-13.0, -13));
assert(!release.step(-13.0, -13));
bool held = false;
Pointer recentre{{}, 640, 1280};
held = false;
for (int i = 0; i < 3; i++) held = recentre.step(26.0, 0);
assert(held);
return 0;
}
'''
class GamescopePointerHoldEdgeTest(unittest.TestCase):
def test_motion_into_the_screen_edge_neither_holds_nor_resets_the_release(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
hold = added_source(HOLD)
edge = added_source(EDGE)
source = PREAMBLE + "\n".join([
block(hold, "struct PointerHold"),
block(hold, "static bool pointer_hold_step"),
block(edge, "static double pointer_reach"),
]) + MAIN
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "pointer_hold_edge.cpp"
exe = Path(tmp) / "pointer_hold_edge"
src.write_text(source)
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
def test_the_hold_rule_compares_against_the_reachable_motion(self):
edge = added_source(EDGE)
self.assertIn("pointer_reach( s_nRootX, flDX, pCtx->root_width )", edge)
self.assertIn("pointer_reach( s_nRootY, flDY, pCtx->root_height )", edge)
self.assertIn("pointer_hold_step( s_Hold, true, flReachX, flReachY,", edge)
if __name__ == "__main__":
unittest.main()
@@ -1,109 +0,0 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
HOLD = ROOT / "tools/gamescope/patches/0133-constraint-relative-when-held.patch"
DOWN = ROOT / "tools/gamescope/patches/0145-pointer-hold-skips-touch-down-warps.patch"
def added_source(patch):
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 <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
'''
MAIN = r'''
static const uint64_t FRAME = 16'666'667ul;
struct Session {
PointerHold hold;
uint64_t now = 1'000'000'000ul;
bool skipTouchDown;
bool frame(double seatDX, double pointerDX, bool touchDown) {
now += FRAME;
if (touchDown && skipTouchDown) return hold.bHeld;
return pointer_hold_step(hold, true, seatDX, 0.0, pointerDX, 0.0, now);
}
void held() {
hold = PointerHold{};
hold.bHeld = true;
}
bool strokes() {
held();
bool result = true;
for (int i = 0; i < 17; i++) result = frame(80.0, 80.0, false);
result = frame(41.0, -1106.0, true);
for (int i = 0; i < 15; i++) result = frame(73.3, 73.0, false);
return result;
}
};
int main() {
Session counted{{}, 1'000'000'000ul, false};
assert(counted.strokes());
Session skipped{{}, 1'000'000'000ul, true};
assert(!skipped.strokes());
Session drag{{}, 1'000'000'000ul, true};
drag.held();
bool result = drag.frame(41.0, -1106.0, true);
assert(result);
for (int i = 0; i < 29; i++) result = drag.frame(12.0, 12.0, false);
assert(result);
result = drag.frame(12.0, 12.0, false);
assert(!result);
Session recentre{{}, 1'000'000'000ul, true};
for (int i = 0; i < 3; i++) result = recentre.frame(26.0, 0.0, false);
assert(result);
result = recentre.frame(-400.0, 300.0, true);
assert(result);
for (int i = 0; i < 40; i++) result = recentre.frame(12.0, 0.0, false);
assert(result);
return 0;
}
'''
class GamescopePointerHoldTouchDownTest(unittest.TestCase):
def test_touch_down_is_skipped_and_touch_drags_release_the_hold(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
hold = added_source(HOLD)
source = PREAMBLE + "\n".join([
block(hold, "struct PointerHold"),
block(hold, "static bool pointer_hold_step"),
]) + MAIN
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "pointer_hold_touch_down.cpp"
exe = Path(tmp) / "pointer_hold_touch_down"
src.write_text(source)
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
def test_only_touch_down_warps_are_skipped(self):
added = added_source(DOWN)
self.assertIn(" \t\t\t\twlserver_mousewarp( tx, ty, time, false, true );\n+\t\t\t\twlserver.ulTouchDownWarps++;", DOWN.read_text())
self.assertEqual(1, added.count("wlserver.ulTouchDownWarps++"))
self.assertIn("const bool bTouchDown = ulTouchDownWarps != s_ulTouchDownWarps;", added)
self.assertIn("else if ( !bTouchDown )", added)
self.assertNotIn("bFromTouch )\n\t\twlserver.ulTouchDownWarps++", added)
if __name__ == "__main__":
unittest.main()
@@ -1,121 +0,0 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCH = ROOT / "tools/gamescope/patches/0143-touch-click-first-finger-drives.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 <set>
'''
MAIN = r'''
struct Pointer {
TouchClickState state;
int warps = 0;
int presses = 0;
int releases = 0;
void down(int id) { if (touch_click_claim(state, id)) { warps++; presses++; } }
void move(int id, bool nested = false) { if (nested || touch_click_drives(state, id)) warps++; }
void up(int id) { if (touch_click_lift(state, id)) releases++; }
};
int main() {
Pointer tap;
tap.down(1);
tap.move(1);
tap.up(1);
assert(tap.presses == 1 && tap.releases == 1 && tap.warps == 2);
Pointer drag;
drag.down(1);
drag.move(1);
drag.down(2);
drag.move(2);
drag.move(1);
drag.up(2);
assert(drag.presses == 1 && drag.releases == 0 && drag.warps == 3);
drag.move(1);
drag.up(1);
assert(drag.releases == 1 && drag.warps == 4);
Pointer handover;
handover.down(1);
handover.down(2);
handover.up(1);
assert(handover.releases == 1);
handover.move(2);
handover.down(3);
handover.move(3);
assert(handover.warps == 1 && handover.presses == 1);
handover.up(3);
handover.up(2);
assert(handover.releases == 1);
handover.down(4);
handover.move(4);
handover.up(4);
assert(handover.presses == 2 && handover.releases == 2 && handover.warps == 3);
Pointer nested;
nested.move(0, true);
nested.down(1);
nested.move(0, true);
assert(nested.warps == 3);
Pointer stray;
stray.up(7);
assert(stray.releases == 1);
stray.down(1);
stray.up(7);
assert(stray.releases == 1);
stray.up(1);
assert(stray.releases == 2);
return 0;
}
'''
class GamescopeTouchClickOwnerTest(unittest.TestCase):
def test_only_the_first_finger_drives_the_emulated_mouse(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
self.skipTest("no C++ compiler")
added = added_source()
helpers = "\n".join(block(added, start) for start in (
"struct TouchClickState",
"static bool touch_click_claim",
"static bool touch_click_drives",
"static bool touch_click_lift",
))
source = PREAMBLE + helpers + MAIN
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "touch_click_owner.cpp"
exe = Path(tmp) / "touch_click_owner"
src.write_text(source)
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
def test_the_patch_gates_every_finger_path(self):
added = added_source()
self.assertIn("else if ( bAlwaysWarpCursor || touch_click_drives( s_TouchClick, touch_id ) )", added)
self.assertIn("if ( touch_click_drives( s_TouchClick, touch_id ) )", added)
self.assertIn("else if ( touch_click_claim( s_TouchClick, touch_id ) )", added)
self.assertIn("bClickTouch && i < WLSERVER_BUTTON_COUNT", added)
if __name__ == "__main__":
unittest.main()
+10 -106
View File
@@ -1,6 +1,5 @@
from pathlib import Path
import os
import signal
import subprocess
import tempfile
import unittest
@@ -55,70 +54,12 @@ FORKER = r"""
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
static const char *name;
static _Atomic int done;
static _Atomic int parked_word;
static _Atomic pid_t parked_tid;
// the host's futex call: 202 on x86-64, where qemu-user runs, 98 on aarch64
static int blocked_futex(const char *path, unsigned long *addr) {
unsigned long nr = 0;
FILE *f = fopen(path, "r");
int got = f && fscanf(f, "%lu %lx", &nr, addr) == 2;
if (f) fclose(f);
return got && (nr == 202 || nr == 98);
}
static void *park(void *arg) {
parked_tid = (pid_t)syscall(SYS_gettid);
while (!parked_word) syscall(SYS_futex, &parked_word, 0 /* FUTEX_WAIT */, 0, NULL, NULL, 0);
return arg;
}
// How far qemu-user moved the guest in the host's address space (its guest_base; 0 natively): a
// thread parked on a futex this program knows shows that futex's host address in its syscall file,
// which qemu-user passes through unlike /proc/self/maps.
static long guest_base(void) {
char path[96];
unsigned long addr = 0;
while (!parked_tid) usleep(1000);
snprintf(path, sizeof(path), "/proc/%d/task/%d/syscall", (int)getpid(), (int)parked_tid);
for (int i = 0; i < 5000; i++) {
if (blocked_futex(path, &addr) && addr) return (long)(addr - (unsigned long)&parked_word);
usleep(1000);
}
return -1;
}
// A child that hangs in qemu-user itself: a fork while another thread is inside the emulator's
// own locks (its mmap() handling) can leave the child waiting on a futex in qemu's memory, which no
// guest lock is. The child's blocking call shows the host's address; under qemu-user this
// program's /proc/self/maps lists the guest's mappings only, and a futex outside all of them, once
// moved back by the guest base, is the emulator's. Natively every futex is in the process's own
// mappings: never counted. Seen on x86 runners; there is no emulator on a device.
static int stuck_in_emulator(pid_t pid, long base) {
char path[64], line[512];
unsigned long addr = 0;
snprintf(path, sizeof(path), "/proc/%d/syscall", (int)pid);
if (base < 0 || !blocked_futex(path, &addr)) return 0;
addr -= (unsigned long)base;
FILE *f = fopen("/proc/self/maps", "r");
if (!f) return 0;
int guest = 0;
while (!guest && fgets(line, sizeof(line), f)) {
unsigned long start, end;
if (sscanf(line, "%lx-%lx", &start, &end) == 2 && addr >= start && addr < end) guest = 1;
}
fclose(f);
return !guest;
}
static void *churn(void *arg) {
while (!done) {
@@ -130,40 +71,24 @@ static void *churn(void *arg) {
int main(int argc, char **argv) {
name = argv[1];
pthread_t parked, thread;
if (pthread_create(&parked, NULL, park, NULL) != 0) return 1;
long base = guest_base();
printf("base\t%ld\n", base);
pthread_t thread;
if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1;
int finished = 0, emulator = 0;
int finished = 0;
for (int i = 0; i < 200; i++) {
pid_t pid = fork();
if (pid < 0) break;
if (pid == 0) {
alarm(10);
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
_exit(sem == SEM_FAILED || sem_close(sem) != 0);
}
int status = 0, stalled = 0;
pid_t r;
for (int waited = 0; (r = waitpid(pid, &status, WNOHANG)) == 0; waited++) {
if (waited == 1000) { // 10 s
stalled = stuck_in_emulator(pid, base);
kill(pid, SIGKILL);
}
usleep(10000);
}
if (r != pid) continue;
if (stalled) emulator++;
else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
int status;
if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
}
done = 1;
pthread_join(thread, NULL);
parked_word = 1;
syscall(SYS_futex, &parked_word, 1 /* FUTEX_WAKE */, 1, NULL, NULL, 0);
pthread_join(parked, NULL);
sem_unlink(name);
printf("finished\t%d\n", finished);
printf("emulator\t%d\n", emulator);
return 0;
}
"""
@@ -191,7 +116,7 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
def tearDownClass(cls):
cls.tmp.cleanup()
def run_hooked(self, program, *args, timeout=120):
def run_hooked(self, program, *args):
hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
@@ -199,17 +124,9 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
else:
cmd = []
env.update(hook_env)
# its own process group, so a timeout also ends a child still blocked once the program is gone
proc = subprocess.Popen(cmd + [str(program), *args], env=env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, start_new_session=True)
try:
stdout, stderr = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
proc.communicate()
raise
self.assertEqual(proc.returncode, 0, stderr)
return dict(line.split("\t") for line in stdout.splitlines())
out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
return dict(line.split("\t") for line in out.stdout.splitlines())
def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self):
name = f"/ddsem-{os.getpid()}"
@@ -222,20 +139,7 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
source.write_text(FORKER)
forker = self.probe.with_name("forker")
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True)
name = f"/ddsem-fork-{os.getpid()}"
# left by a run that did not get to sem_unlink(), it would fail the other tests' empty /dev/shm
self.addCleanup(lambda: (self.shm / f"sem.{name[1:]}").unlink(missing_ok=True))
# 200 forks under a loaded qemu-user, and 10 s for each child that hangs in the emulator
result = self.run_hooked(forker, name, timeout=300)
# every child opened one, but for one now and then that hung in qemu-user itself (a fork during
# the emulator's own locking), which a native run never has
if self.prefix:
self.assertNotEqual("-1", result.get("base"), result)
else:
self.assertEqual("0", result.get("base"), result)
emulator = int(result.get("emulator", "0"))
self.assertEqual(200, int(result.get("finished", "0")) + emulator, result)
self.assertLessEqual(emulator, 0 if not self.prefix else 3, result)
self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}"))
def test_a_created_semaphore_keeps_its_name_and_mode(self):
name = f"ddsem-kept-{os.getpid()}"
-8
View File
@@ -20,14 +20,6 @@ LAYER_HARNESS = r'''
#include "vk_linear_dmabuf.h"
typedef struct AHardwareBuffer AHardwareBuffer;
enum vkp_image_source {
VKP_IMAGE_SOURCE_NONE = 0,
VKP_IMAGE_SOURCE_DMABUF,
VKP_IMAGE_SOURCE_AHB_WLEGL,
VKP_IMAGE_SOURCE_AHB_SOURCE,
VKP_IMAGE_SOURCE_AHB_TARGET,
VKP_IMAGE_SOURCE_SHM
};
%(image)s
struct vkp_draw {
struct vkp_image *img;
+2 -23
View File
@@ -31,10 +31,8 @@ def function(text, name):
HARNESS = r'''
#include <assert.h>
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
typedef int VkResult;
typedef uintptr_t VkFence;
#define VK_TRUE 1
@@ -71,31 +69,12 @@ static struct {
typedef struct AHardwareBuffer AHardwareBuffer;
static int released_buffers;
static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; ++released_buffers; }
enum vkp_image_source {
VKP_IMAGE_SOURCE_NONE = 0,
VKP_IMAGE_SOURCE_DMABUF,
VKP_IMAGE_SOURCE_AHB_WLEGL,
VKP_IMAGE_SOURCE_AHB_SOURCE,
VKP_IMAGE_SOURCE_AHB_TARGET,
VKP_IMAGE_SOURCE_SHM
};
struct vkp_image {
uintptr_t image, mem;
void *map;
AHardwareBuffer *android_buffer;
uintptr_t linear_buf, linear_mem;
int staged, in_general;
enum vkp_image_source source_type;
int source_fd;
uint8_t *recovery_pixels;
struct vkp_image *next;
};
static void image_unregister(struct vkp_image *img) { (void)img; }
struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; uintptr_t linear_buf, linear_mem; int staged, in_general; };
static void blendp_forget_image(uintptr_t image) { (void)image; ++forgotten; }
/* PRODUCTION_FUNCTIONS */
static struct vkp_image *image(void) {
struct vkp_image *p = calloc(1, sizeof(*p)); assert(p);
p->image=1; p->mem=2; p->map=p; p->source_fd=-1; return p;
p->image=1; p->mem=2; p->map=p; return p;
}
int main(void) {
g_dev_state=1; answer=VK_SUCCESS;
-6
View File
@@ -117,9 +117,6 @@ int __android_log_print(int, const char *, const char *, ...);
def test_finite_blit_timeout_same_size_pixel_upload(self):
self.run_scenario('pixel-timeout')
def test_lost_device_shm_upload_keeps_cpu_snapshot(self):
self.run_scenario('lost-shm-upload')
def test_normal_present(self):
self.run_scenario('normal')
@@ -129,9 +126,6 @@ int __android_log_print(int, const char *, const char *, ...);
def test_healthy_later_acquire_timeout_drains_work(self):
self.run_scenario('later-timeout')
def test_device_loss_with_unconfirmed_idle_retains_resources(self):
self.run_scenario('acquire-device-lost-unconfirmed')
def test_real_device_lost_on_acquire(self):
self.run_scenario('acquire-device-lost')
+6 -44
View File
@@ -38,11 +38,7 @@ static void blit(VkCommandBuffer c, VkImage s, VkImageLayout sl, VkImage d, VkIm
uint32_t n, const VkImageBlit *b, VkFilter f) { live(); }
static void destroy_swap(VkDevice d, VkSwapchainKHR s, const VkAllocationCallbacks *a) { ++destroys; }
static void destroy_surface(VkInstance i, VkSurfaceKHR s, const VkAllocationCallbacks *a) { ++destroys; }
static void destroy_fence(VkDevice d, VkFence f, const VkAllocationCallbacks *a) { ++destroys; }
static void destroy_pool(VkDevice d, VkCommandPool p, const VkAllocationCallbacks *a) { ++destroys; }
static void destroy_device(VkDevice d, const VkAllocationCallbacks *a) { ++destroys; }
static void destroy_instance(VkInstance i, const VkAllocationCallbacks *a) { ++destroys; }
static void destroy_sem(VkDevice d, VkSemaphore s, const VkAllocationCallbacks *a) { ++destroys; }
static void destroy_sem(VkDevice d, VkSemaphore s, const VkAllocationCallbacks *a) { live(); ++destroys; }
static VkResult create_sem(VkDevice d, const VkSemaphoreCreateInfo *c, const VkAllocationCallbacks *a, VkSemaphore *s) {
live(); *s = (VkSemaphore)(uintptr_t)1; return VK_SUCCESS;
}
@@ -65,17 +61,15 @@ int sc_layer_base_black(int w, int h) { return 0; }
void sc_layer_hide_base(void) {}
void sc_layer_hide_overlay(void) {}
void vkp_cardboard_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {}
void vkp_cardboard_destroy(void) {}
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) { return -1; }
void vk_loader_close(void) {}
void vk_loader_load_instance(VkInstance i) {}
void vk_loader_load_device(VkDevice d) {}
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; }
void vkp_effects_bind_device(VkDevice d, VkPhysicalDevice p, const VkPhysicalDeviceMemoryProperties *m) {}
void vkp_effects_destroy(void) {}
int vkp_effects_active(void) { return 0; }
int vkp_effects_upscaling(void) { return 0; }
int vkp_effects_sharpening(void) { return 0; }
@@ -100,11 +94,9 @@ void vkp_framegen_presented(int n) { ++presented_notifications; }
void vkp_gpu_busy_device(VkPhysicalDevice p, VkDevice d, uint32_t f) {}
void vkp_gpu_busy_device_lost(void) {}
void hdrc_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {}
void hdrc_destroy(void) {}
void hdrc_forget_image(VkImage i) {}
int hdrc_encode(VkCommandBuffer c, VkImage a, VkImage b, VkFormat f, int w, int h, const struct hdrc_params *p) { return -1; }
void blendp_bind_device(VkDevice d) {}
void blendp_destroy(void) {}
void blendp_forget_image(VkImage i) {}
void vkp_effects_forget_image(VkImage i) {}
void blendp_begin_frame(void) {}
@@ -163,8 +155,6 @@ static void setup(int extra) {
.ResetCommandBuffer = reset_cmd, .ResetFences = reset_fence, .BeginCommandBuffer = begin_cmd,
.EndCommandBuffer = end_cmd, .CmdPipelineBarrier = barrier, .CmdClearColorImage = clear,
.CmdBlitImage = blit, .DestroySwapchainKHR = destroy_swap, .DestroySurfaceKHR = destroy_surface,
.DestroyFence = destroy_fence, .DestroyCommandPool = destroy_pool,
.DestroyDevice = destroy_device, .DestroyInstance = destroy_instance,
.DestroySemaphore = destroy_sem, .CreateSemaphore = create_sem,
.DestroyImage = destroy_image, .FreeMemory = free_memory, .UnmapMemory = unmap};
idle_answer = fence_answer = acquire_answer = present_answer = VK_SUCCESS;
@@ -190,7 +180,6 @@ static void setup(int extra) {
/* Probe the public GPU entry points after a terminal result. This includes an
* active off-screen pass and consumed release fds, not just the render guard. */
static void assert_stopped(void) {
assert(g_dev_state == -3 || (g_dev_state == -2 && g_recovery_attempted));
unsigned before = operations, before_destroys = destroys;
struct vkp_image src = {.image = (VkImage)(uintptr_t)7, .w = 1, .h = 1};
struct vkp_image dst = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1, .blit_dst = 1};
@@ -279,20 +268,7 @@ int main(int argc, char **argv) {
else if (!strcmp(name, "later-surface-lost")) acquire_failure(1, VK_ERROR_SURFACE_LOST_KHR);
else if (!strcmp(name, "shm-timeout")) upload_timeout(0);
else if (!strcmp(name, "pixel-timeout")) upload_timeout(1);
else if (!strcmp(name, "lost-shm-upload")) {
setup(0);
uint8_t bytes[64], data[16];
memset(bytes, 0xa5, sizeof(bytes));
for (unsigned i = 0; i < sizeof(data); i++) data[i] = (uint8_t)(i + 1);
struct vkp_image img = {.map = bytes, .offset = 3, .row_pitch = 16, .w = 2, .h = 2,
.source_type = VKP_IMAGE_SOURCE_SHM};
g_dev_state = -2;
vkp_image_upload_shm(&img, data, 8);
assert(img.recovery_pixels && !memcmp(img.recovery_pixels, data, sizeof(data)));
assert(bytes[3] == 0xa5 && bytes[19] == 0xa5);
free(img.recovery_pixels);
free(g_images);
} else if (!strcmp(name, "pass-terminal")) { setup(0); g_dev_state = -3; assert_stopped(); free(g_images); }
else if (!strcmp(name, "pass-terminal")) { setup(0); g_dev_state = -3; assert_stopped(); free(g_images); }
else if (!strcmp(name, "normal") || !strcmp(name, "framegen")) {
int extra = !strcmp(name, "framegen"); setup(extra);
assert(vkp_render(64, 64, NULL, 0) == 0 && g_dev_state == 1);
@@ -303,18 +279,6 @@ int main(int argc, char **argv) {
setup(1); fail_acquire_at = 2; acquire_answer = VK_TIMEOUT;
assert(vkp_render(64, 64, NULL, 0) == -1 && g_dev_state == 1);
assert(acquires == 2 && submits == 2 && markers == 1 && waits == 1); free(g_images);
} else if (!strcmp(name, "acquire-device-lost-unconfirmed")) {
setup(1);
fail_acquire_at = 2;
acquire_answer = VK_ERROR_DEVICE_LOST;
idle_answer = VK_ERROR_OUT_OF_HOST_MEMORY;
VkImage *retained = g_images;
assert(vkp_render(64, 64, NULL, 0) == -1);
assert(g_dev_state == -3 && vkp_completion_unknown() && !vkp_device_lost());
assert(idle_calls == 1 && lost_notifications == 0 && waits == 0);
assert(g_images == retained && g_nimg == 1 && g_swapchain && g_surface && destroys == 0);
assert_stopped();
free(g_images); /* test-owned fake resources only */
} else if (!strcmp(name, "acquire-device-lost") || !strcmp(name, "present-device-lost")) {
setup(1);
if (!strcmp(name, "acquire-device-lost")) { fail_acquire_at = 2; acquire_answer = VK_ERROR_DEVICE_LOST; }
@@ -323,8 +287,6 @@ int main(int argc, char **argv) {
assert(!vkp_completion_unknown());
assert(g_dev_state == -2 && lost_notifications == 1 && markers == 0 && waits == 0);
assert(!g_images && !g_swapchain && !g_surface && destroys == 2);
assert(vkp_ready() == -1);
assert(g_dev_state == -2 && g_recovery_attempted);
assert_stopped();
} else assert(0 && "unknown scenario");
return 0;
-2
View File
@@ -215,7 +215,6 @@ power-profiles-daemon
powerdevil
ppa-purge
print-manager
pyqt6-dev-tools
python3-dbus
python3-launchpadlib
python3-setuptools
@@ -242,7 +241,6 @@ software-properties-qt
squashfs-tools
synaptic
systemsettings
ubuntu-drivers-common
udisks2
unrar-free
upower
+10 -2
View File
@@ -120,8 +120,16 @@ from the content service. The WU endpoint needs no Xbox credential but chains to
Product Root CA 2018, which Android's CA bundle does not carry, so that one public root is
pinned in `wu-root.pem` for these requests. Only `.eappx`/`.eappxbundle` files from a WU result
are kept; the `.appx` framework packages and `.cab` metadata beside them are dropped. Licensing
runs before the first byte and must return content keys. Free space is checked against the
download plus two copies of the largest container, and each container is deleted once unpacked.
runs before the first byte and must return content keys. Bundle members are read in place, and
where the filesystem can punch holes the container blocks already decrypted are freed as the
unpack runs, so an install needs about the size of the download free before it starts. After the
download, the packages' blockmaps give an exact check before anything is unpacked: growth from
inflation, two blocks per file and the data in flight; a failed check keeps the download. Storage
that cannot punch holes needs the download plus the largest container and a tenth of it before the
download, and the container plus its full unpacked size after it; a package that cannot be measured
(a bundle with compressed members) counts its own size and a tenth. A container is renamed to
`.unpacking` before its first block is freed, so an interrupted unpack downloads it again, and it is
renamed back when the filesystem refuses the first punch. Each container is deleted once unpacked.
The download has no control channel: cancelling kills it and the next attempt starts that
container from zero.
+859 -22
View File
@@ -57,10 +57,15 @@ index 088a6d0..825c24e 100644
pub mod social;
pub mod game_activity;
diff --git a/crates/xodus-cli/src/commands/extract_eappx.rs b/crates/xodus-cli/src/commands/extract_eappx.rs
index 5ea43da..0bad98e 100644
index 5ea43da..e236002 100644
--- a/crates/xodus-cli/src/commands/extract_eappx.rs
+++ b/crates/xodus-cli/src/commands/extract_eappx.rs
@@ -51,6 +51,8 @@ pub struct Meter {
@@ -1,3 +1,4 @@
+use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
@@ -51,6 +52,8 @@ pub struct Meter {
pub banked: std::sync::atomic::AtomicU64,
/// Bytes the package being unpacked now will write in total.
pub total: std::sync::atomic::AtomicU64,
@@ -69,7 +74,7 @@ index 5ea43da..0bad98e 100644
turn: std::sync::Mutex<()>,
}
@@ -61,7 +63,14 @@ impl Meter {
@@ -61,7 +64,14 @@ impl Meter {
let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let banked = self.banked.load(Relaxed);
let total = self.total.load(Relaxed);
@@ -85,7 +90,7 @@ index 5ea43da..0bad98e 100644
}
pub fn done(&self) -> u64 {
@@ -79,6 +88,8 @@ impl Meter {
@@ -79,6 +89,8 @@ impl Meter {
self.banked.fetch_add(self.total.load(Relaxed), Relaxed);
self.written.store(0, Relaxed);
self.total.store(total, Relaxed);
@@ -94,40 +99,636 @@ index 5ea43da..0bad98e 100644
}
}
@@ -260,6 +271,9 @@ fn derive(
@@ -129,16 +141,30 @@ pub fn run_blocking(
}
}
- match derive(
- Path::new(&path),
- Path::new(&destination),
- &key_collection,
- 0,
- meter,
- release,
- ) {
- Ok(()) => ExitCode::SUCCESS,
- Err(failure) => report_failure(&failure, ExitCode::FAILURE),
+ let origin = Path::new(&path);
+ let container = match std::fs::File::open(origin) {
+ Ok(file) => file,
+ Err(e) => return report_failure(&Failure::at("open", origin, &e.to_string()), ExitCode::FAILURE),
+ };
+ let len = match container.metadata() {
+ Ok(meta) => meta.len(),
+ Err(e) => return report_failure(&Failure::at("open", origin, &e.to_string()), ExitCode::FAILURE),
+ };
+ let release = release.then(|| Release::open(origin, &container));
+ let source = Source { file: &container, origin, name: origin.to_path_buf(), start: 0, len };
+ match derive(&source, Path::new(&destination), &key_collection, 0, meter, release.as_ref()) {
+ Ok(()) => {
+ if let Some(release) = &release {
+ release.finish();
+ }
+ ExitCode::SUCCESS
+ }
+ Err(failure) => {
+ if let Some(release) = &release {
+ release.abandon();
+ }
+ report_failure(&failure, ExitCode::FAILURE)
+ }
}
}
@@ -197,17 +223,285 @@ fn is_eappx(path: &Path) -> bool {
matches!(&magic, b"EXPH" | b"EXSH" | b"EXBH")
}
+struct Source<'a> {
+ file: &'a std::fs::File,
+ origin: &'a Path,
+ name: PathBuf,
+ start: u64,
+ len: u64,
+}
+
+impl<'a> Source<'a> {
+ fn inner(&self, member: &Member) -> Option<Source<'a>> {
+ let info = &member.info;
+ if info.compression_type == 1 || info.offset_to_file.checked_add(info.uncompressed_length)? > self.len {
+ return None;
+ }
+ let start = self.start.checked_add(info.offset_to_file)?;
+ let mut magic = [0u8; 4];
+ self.file.read_exact_at(&mut magic, start).ok()?;
+ matches!(&magic, b"EXPH" | b"EXSH" | b"EXBH").then(|| Source {
+ file: self.file,
+ origin: self.origin,
+ name: PathBuf::from(member.name.replace('\\', "/")),
+ start,
+ len: info.uncompressed_length,
+ })
+ }
+}
+
+struct Window<'r> {
+ file: std::fs::File,
+ start: u64,
+ len: u64,
+ pos: u64,
+ release: Option<&'r Release>,
+ spend: Option<(u64, u64)>,
+}
+
+impl<'r> Window<'r> {
+ fn open(source: &Source, release: Option<&'r Release>) -> std::io::Result<Self> {
+ Ok(Self { file: source.file.try_clone()?, start: source.start, len: source.len, pos: 0, release, spend: None })
+ }
+
+ fn spend(&mut self, offset: u64, length: u64) {
+ let Some(release) = self.release else { return };
+ let from = self.start.saturating_add(offset);
+ let to = from.saturating_add(length).min(self.start.saturating_add(self.len));
+ self.spend = Some((release.align_up(from), to));
+ }
+
+ fn settle(&mut self) {
+ if let (Some(release), Some((from, to))) = (self.release, self.spend.take()) {
+ release.give_back(from, release.align_down(to));
+ }
+ }
+
+ fn advance(&mut self) {
+ let (Some(release), Some((from, to))) = (self.release, self.spend) else { return };
+ let reached = release.align_down(self.start.saturating_add(self.pos).min(to));
+ if reached >= from.saturating_add(SPEND_STEP) {
+ release.give_back(from, reached);
+ self.spend = Some((reached, to));
+ }
+ }
+}
+
+impl std::io::Read for Window<'_> {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+ let left = self.len.saturating_sub(self.pos);
+ let wanted = buf.len().min(usize::try_from(left).unwrap_or(usize::MAX));
+ if wanted == 0 {
+ return Ok(0);
+ }
+ let read = self.file.read_at(&mut buf[..wanted], self.start + self.pos)?;
+ self.pos += read as u64;
+ self.advance();
+ Ok(read)
+ }
+}
+
+impl std::io::Seek for Window<'_> {
+ fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
+ let next = match to {
+ std::io::SeekFrom::Start(offset) => Some(offset),
+ std::io::SeekFrom::End(delta) => self.len.checked_add_signed(delta),
+ std::io::SeekFrom::Current(delta) => self.pos.checked_add_signed(delta),
+ };
+ self.pos = next.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek outside the package"))?;
+ Ok(self.pos)
+ }
+}
+
+const SPEND_STEP: u64 = 64 << 20;
+const SPENT_SUFFIX: &str = ".unpacking";
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Spent {
+ Intact,
+ Moved,
+ Punched,
+ Kept,
+ Spoiled,
+}
+
+struct Release {
+ origin: PathBuf,
+ spent: PathBuf,
+ file: Option<std::fs::File>,
+ block: u64,
+ state: std::sync::Mutex<Spent>,
+}
+
+impl Release {
+ fn open(origin: &Path, container: &std::fs::File) -> Self {
+ let mut spent = origin.as_os_str().to_owned();
+ spent.push(SPENT_SUFFIX);
+ let file = std::fs::OpenOptions::new().write(true).open(origin).ok();
+ let state = if file.is_some() { Spent::Intact } else { Spent::Kept };
+ Self {
+ origin: origin.to_path_buf(),
+ spent: PathBuf::from(spent),
+ file,
+ block: block_size(container),
+ state: std::sync::Mutex::new(state),
+ }
+ }
+
+ fn align_up(&self, at: u64) -> u64 {
+ at.div_ceil(self.block).saturating_mul(self.block)
+ }
+
+ fn align_down(&self, at: u64) -> u64 {
+ at - at % self.block
+ }
+
+ fn give_back(&self, from: u64, to: u64) {
+ if to <= from {
+ return;
+ }
+ let Some(file) = &self.file else { return };
+ let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ if *state == Spent::Intact {
+ *state = if std::fs::rename(&self.origin, &self.spent).is_ok() { Spent::Moved } else { Spent::Kept };
+ }
+ if !matches!(*state, Spent::Moved | Spent::Punched) {
+ return;
+ }
+ let mode = rustix::fs::FallocateFlags::PUNCH_HOLE | rustix::fs::FallocateFlags::KEEP_SIZE;
+ *state = match (rustix::fs::fallocate(file, mode, from, to - from).is_ok(), *state) {
+ (true, _) => Spent::Punched,
+ (false, Spent::Moved) => self.restore(),
+ (false, _) => Spent::Spoiled,
+ };
+ }
+
+ fn restore(&self) -> Spent {
+ if std::fs::rename(&self.spent, &self.origin).is_ok() { Spent::Kept } else { Spent::Spoiled }
+ }
+
+ fn finish(&self) {
+ std::fs::remove_file(&self.origin).ok();
+ std::fs::remove_file(&self.spent).ok();
+ }
+
+ fn abandon(&self) {
+ let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ if *state == Spent::Moved {
+ *state = self.restore();
+ }
+ if matches!(*state, Spent::Punched | Spent::Spoiled) {
+ std::fs::remove_file(&self.spent).ok();
+ }
+ }
+}
+
+fn block_size(file: &std::fs::File) -> u64 {
+ use std::os::unix::fs::MetadataExt;
+ file.metadata().map(|meta| meta.blksize()).ok().filter(|size| size.is_power_of_two()).unwrap_or(4096)
+}
+
+pub fn releases_space(dir: &Path) -> bool {
+ use std::io::Write;
+ let Ok(mut probe) = tempfile::tempfile_in(dir) else { return false };
+ if probe.write_all(&[1u8; 1 << 16]).and_then(|()| probe.sync_data()).is_err() {
+ return false;
+ }
+ let mode = rustix::fs::FallocateFlags::PUNCH_HOLE | rustix::fs::FallocateFlags::KEEP_SIZE;
+ rustix::fs::fallocate(&probe, mode, 0, 1 << 16).is_ok()
+}
+
+struct Layout {
+ bounds: Vec<u64>,
+ len: u64,
+}
+
+impl Layout {
+ fn of(eappx: &EAppxFile, len: u64) -> Self {
+ let header = &eappx.header;
+ let mut bounds: Vec<u64> = eappx
+ .footers
+ .iter()
+ .map(|footer| footer.offset_to_file)
+ .chain([header.footer_offset, header.signature_offset, header.code_integrity_offset])
+ .collect();
+ bounds.sort_unstable();
+ bounds.dedup();
+ Self { bounds, len }
+ }
+
+ fn stored(&self, info: &eappx::FileInfo) -> u64 {
+ let size = if info.compression_type == 1 { info.compressed_length } else { info.uncompressed_length };
+ let next = self
+ .bounds
+ .get(self.bounds.partition_point(|&bound| bound <= info.offset_to_file))
+ .copied()
+ .unwrap_or(self.len);
+ info.offset_to_file.saturating_add(size).min(next).min(self.len).saturating_sub(info.offset_to_file)
+ }
+}
+
+struct Member {
+ name: String,
+ info: eappx::FileInfo,
+}
+
+fn bundle_members<R: std::io::BufRead + std::io::Seek>(eappx: &EAppxFile, reader: &mut R) -> Result<Vec<Member>, String> {
+ let eappx::Manifest::BundleManifest(manifest) = eappx.read_manifest(reader).map_err(|e| e.to_string())? else {
+ return Err("the bundle carries no bundle manifest".into());
+ };
+ manifest
+ .packages
+ .package
+ .into_iter()
+ .enumerate()
+ .map(|(index, package)| {
+ let footer = eappx
+ .find_footer_for_file(index as u64)
+ .ok_or_else(|| format!("bundle file {} is not in the footers", package.filename))?;
+ if footer.offset_to_file != package.offset {
+ return Err(format!("bundle file {} disagrees with its footer about its offset", package.filename));
+ }
+ Ok(Member { name: package.filename, info: eappx::FileInfo::from(footer) })
+ })
+ .collect()
+}
+
+fn save(
+ eappx: &EAppxFile,
+ layout: &Layout,
+ stream: &mut std::io::BufReader<Window<'_>>,
+ info: eappx::FileInfo,
+ outdir: &Path,
+ name: &str,
+) -> Result<(), eappx::error::Error> {
+ stream.get_mut().spend(info.offset_to_file, layout.stored(&info));
+ let saved = eappx.save_file_to_fs(stream, info, outdir, name);
+ if saved.is_ok() {
+ stream.get_mut().settle();
+ } else {
+ stream.get_mut().spend = None;
+ }
+ saved
+}
+
+fn stem(name: &Path) -> Result<String, Failure> {
+ name.file_stem()
+ .map(|stem| stem.to_string_lossy().into_owned())
+ .ok_or_else(|| Failure::at("no-name", name, "package without a usable name"))
+}
+
fn derive(
- infile: &Path,
+ source: &Source,
outdir: &Path,
keys: &KeyCollection,
depth: usize,
meter: Option<&Meter>,
- release: bool,
+ release: Option<&Release>,
) -> Result<(), Failure> {
- let file = std::fs::File::open(infile)
- .map_err(|e| Failure::at("open", infile, &e.to_string()))?;
- let mut reader = std::io::BufReader::new(file);
+ let infile = source.name.as_path();
+ let window = Window::open(source, release).map_err(|e| Failure::at("open", infile, &e.to_string()))?;
+ let mut reader = std::io::BufReader::new(window);
let mut eappx = EAppxFile::from_stream(&mut reader)
.map_err(|e| Failure::at("header", infile, &e.to_string()))?;
@@ -236,8 +530,16 @@ fn derive(
std::fs::create_dir_all(outdir)
.map_err(|e| Failure::at("create-dir", outdir, &e.to_string()))?;
- unpack(infile, &eappx, &mut reader, outdir, meter, release)?;
- // The handle must close before a released container gives its space back.
+ eappx
+ .extract_footprint_files(&mut reader, outdir)
+ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
+
+ let inner = if eappx.header.is_bundle() {
+ unbundle(source, &eappx, &mut reader, outdir, meter)?
+ } else {
+ unpack(source, &eappx, outdir, meter, release)?;
+ Vec::new()
+ };
drop(reader);
println!("Extracted {}", infile.file_name().unwrap_or_default().to_string_lossy());
@@ -248,33 +550,189 @@ fn derive(
// The container being unpacked may itself sit in the destination, which is
// what `extract-eappx ./title.eappx .` asks for. Re-entering it would
// recurse into the same bytes and then delete the caller's file.
- .filter(|path| std::fs::canonicalize(path).ok() != std::fs::canonicalize(infile).ok())
+ .filter(|path| std::fs::canonicalize(path).ok() != std::fs::canonicalize(source.origin).ok())
.filter(|path| path.is_file() && is_eappx(path))
.collect();
nested.sort();
- if nested.is_empty() {
+ if inner.is_empty() && nested.is_empty() {
return Ok(());
}
if depth >= MAX_BUNDLE_DEPTH {
return Err(Failure::at("nesting", infile, "bundle nesting exceeds the limit"));
}
- for child in nested {
- let name = child
- .file_stem()
- .map(|name| name.to_string_lossy().into_owned())
- .ok_or_else(|| Failure::at("no-name", &child, "package without a usable name"))?;
- derive(&child, &outdir.join(&name), keys, depth + 1, meter, release)?;
+ let opened = nested
+ .into_iter()
+ .map(|path| {
+ let file = std::fs::File::open(&path).map_err(|e| Failure::at("open", &path, &e.to_string()))?;
+ let len = file.metadata().map_err(|e| Failure::at("open", &path, &e.to_string()))?.len();
+ Ok((path, file, len))
+ })
+ .collect::<Result<Vec<_>, Failure>>()?;
+ let children: Vec<Source> = opened
+ .iter()
+ .map(|(path, file, len)| Source { file, origin: source.origin, name: path.clone(), start: 0, len: *len })
+ .collect();
+
+ if let Some(meter) = meter {
+ meter.expect(nested.iter().map(|child| package_size(child)).sum());
+ meter.expect(inner.iter().map(package_size).sum::<u64>() + children.iter().map(package_size).sum::<u64>());
+ }
for child in nested {
let name = child
.file_stem()
@@ -275,6 +289,14 @@ fn derive(
+ for member in &inner {
+ derive(member, &outdir.join(stem(&member.name)?), keys, depth + 1, meter, release)?;
+ }
+ for child in &children {
+ derive(child, &outdir.join(stem(&child.name)?), keys, depth + 1, meter, None)?;
// The member's bytes are no longer needed once its contents are on disk.
// A bundle of a full title holds tens of gigabytes, and keeping every
// member beside the decrypted copy doubles what the install occupies.
- std::fs::remove_file(&child).ok();
+ std::fs::remove_file(&child.name).ok();
}
Ok(())
}
+fn unbundle<'a>(
+ source: &Source<'a>,
+ eappx: &EAppxFile,
+ reader: &mut std::io::BufReader<Window<'_>>,
+ outdir: &Path,
+ meter: Option<&Meter>,
+) -> Result<Vec<Source<'a>>, Failure> {
+ let infile = source.name.as_path();
+ let members = bundle_members(eappx, reader).map_err(|e| Failure::at("extract", infile, &e))?;
+ let shared: Vec<u64> = members.iter().map(|member| member.info.offset_to_file).collect();
+
+ let mut written = Vec::new();
+ for file in &eappx.blockmap.files {
+ let footer = eappx
+ .find_footer_for_file(file.id())
+ .ok_or_else(|| Failure::at("extract", infile, "the blockmap names a file the package does not hold"))?;
+ if shared.contains(&footer.offset_to_file) {
+ continue;
+ }
+ if footer.uncompressed_length != file.size {
+ return Err(Failure::at("extract", infile, "a package entry disagrees with its blockmap about its size"));
+ }
+ let mut info = eappx::FileInfo::from(footer);
+ info.filehash = file.filehash_bytes();
+ info.block_hashes = Some(file.block_hashes());
+ written.push((info, file.name.clone()));
+ }
+
+ let mut inner = Vec::new();
+ for member in members {
+ match source.inner(&member) {
+ Some(package) => inner.push(package),
+ None => written.push((member.info, member.name)),
+ }
+ }
+ inner.sort_by(|a, b| a.name.cmp(&b.name));
+
+ if let Some(meter) = meter {
+ meter.roll(written.iter().map(|(info, _)| info.uncompressed_length).sum());
+ }
+ let layout = Layout::of(eappx, source.len);
+ for (info, name) in written {
+ save(eappx, &layout, reader, info, outdir, &name).map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
+ }
+ Ok(inner)
+}
+
+/// What a package's blockmap says it will write, or nothing when its header is unreadable.
+fn package_size(path: &Path) -> u64 {
+ let Ok(file) = std::fs::File::open(path) else { return 0 };
+ EAppxFile::from_stream(&mut std::io::BufReader::new(file))
+fn package_size(source: &Source) -> u64 {
+ let Ok(window) = Window::open(source, None) else { return 0 };
+ EAppxFile::from_stream(&mut std::io::BufReader::new(window))
+ .map(|package| package.blockmap.files.iter().map(|entry| entry.size).sum())
+ .unwrap_or(0)
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct Footprint {
+ pub unpacked: u64,
+ pub growth: u64,
+ pub files: u64,
+ pub block: u64,
+}
+
+impl Footprint {
+ fn add(&mut self, other: Footprint) {
+ self.unpacked = self.unpacked.saturating_add(other.unpacked);
+ self.growth = self.growth.saturating_add(other.growth);
+ self.files = self.files.saturating_add(other.files);
+ }
+
+ pub fn extra(&self, releases: bool) -> u64 {
+ if !releases {
+ return self.unpacked;
+ }
+ self.growth
+ .saturating_add(self.files.saturating_mul(2).saturating_mul(self.block))
+ .saturating_add(in_flight())
+ }
+}
+
+pub fn in_flight() -> u64 {
+ (workers() as u64).saturating_mul(SPEND_STEP + READ_BUFFER as u64)
+}
+
+pub fn footprint(path: &Path) -> Option<Footprint> {
+ if !is_eappx(path) {
+ return None;
+ }
+ let file = std::fs::File::open(path).ok()?;
+ let len = file.metadata().ok()?.len();
+ let source = Source { file: &file, origin: path, name: path.to_path_buf(), start: 0, len };
+ let mut total = measure(&source, 0)?;
+ total.block = block_size(&file);
+ Some(total)
+}
+
+fn measure(source: &Source, depth: usize) -> Option<Footprint> {
+ let mut reader = std::io::BufReader::new(Window::open(source, None).ok()?);
+ let eappx = EAppxFile::from_stream(&mut reader).ok()?;
+ let layout = Layout::of(&eappx, source.len);
+ let header = &eappx.header;
+ let packaging = eappx
+ .find_footer_for_file(header.block_map_file_id)
+ .map_or(0, |footer| footer.uncompressed_length)
+ .saturating_add(u64::from(header.signature_uncompressed_length))
+ .saturating_add(u64::from(header.code_integrity_uncompressed_length));
+ let mut total = Footprint { unpacked: packaging, growth: packaging, files: 3, block: 0 };
+ let mut written = Vec::new();
+ if header.is_bundle() {
+ let members = bundle_members(&eappx, &mut reader).ok()?;
+ let shared: Vec<u64> = members.iter().map(|member| member.info.offset_to_file).collect();
+ for file in &eappx.blockmap.files {
+ let footer = eappx.find_footer_for_file(file.id())?;
+ if !shared.contains(&footer.offset_to_file) {
+ written.push(eappx::FileInfo::from(footer));
+ }
+ }
+ for member in members {
+ match source.inner(&member) {
+ Some(_) if depth >= MAX_BUNDLE_DEPTH => return None,
+ Some(package) => total.add(measure(&package, depth + 1)?),
+ None if member.info.compression_type == 1 => return None,
+ None => written.push(member.info),
+ }
+ }
+ } else {
+ for file in &eappx.blockmap.files {
+ written.push(eappx::FileInfo::from(eappx.find_footer_for_file(file.id())?));
+ }
+ }
+ for info in &written {
+ total.add(Footprint {
+ unpacked: info.uncompressed_length,
+ growth: info.uncompressed_length.saturating_sub(layout.stored(info)),
+ files: 1,
+ block: 0,
+ });
+ }
+ Some(total)
+}
+
/// Bytes currently on disk under `dir`.
///
/// A bundle member is written as one file, so a per-file counter says nothing
@@ -414,3 +436,29 @@ fn unpack(
@@ -319,48 +777,33 @@ fn workers() -> usize {
/// goes. The blockmap already totals every file's uncompressed length, so the
/// end point is known before the first byte is written.
fn unpack(
- infile: &Path,
+ source: &Source,
eappx: &EAppxFile,
- reader: &mut std::io::BufReader<std::fs::File>,
outdir: &Path,
meter: Option<&Meter>,
- release: bool,
+ release: Option<&Release>,
) -> Result<(), Failure> {
+ let infile = source.name.as_path();
let total: u64 = eappx.blockmap.files.iter().map(|package| package.size).sum();
if let Some(meter) = meter {
meter.roll(total);
}
Ok(())
}
- eappx
- .extract_footprint_files(reader, outdir)
- .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
-
- if eappx.header.is_bundle() {
- eappx
- .extract_blockmap_files(reader, outdir)
- .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
- eappx
- .extract_bundle_files(reader, outdir)
- .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
- if release {
- std::fs::remove_file(infile).ok();
- }
- return Ok(());
- }
-
+ let layout = Layout::of(eappx, source.len);
let count = workers().min(eappx.blockmap.files.len().max(1));
let failure = std::sync::Mutex::new(None::<String>);
std::thread::scope(|scope| {
for shard in 0..count {
let failure = &failure;
+ let layout = &layout;
scope.spawn(move || {
- let Ok(handle) = std::fs::File::open(infile) else {
+ let Ok(window) = Window::open(source, release) else {
if let Ok(mut slot) = failure.lock() {
*slot = Some("a worker could not reopen the package".to_string());
}
return;
};
- let mut stream = std::io::BufReader::with_capacity(READ_BUFFER, handle);
+ let mut stream = std::io::BufReader::with_capacity(READ_BUFFER, window);
for (index, package) in eappx.blockmap.files.iter().enumerate() {
if index % count != shard {
continue;
@@ -387,7 +830,7 @@ fn unpack(
}
return;
}
- if let Err(error) = eappx.save_file_to_fs(&mut stream, info, outdir, &package.name) {
+ if let Err(error) = save(eappx, layout, &mut stream, info, outdir, &package.name) {
if let Ok(mut slot) = failure.lock() {
*slot = Some(error.to_string());
}
@@ -406,11 +849,190 @@ fn unpack(
if let Some(reason) = failure.into_inner().unwrap_or(None) {
return Err(Failure::at("extract", infile, &reason));
}
+ Ok(())
+}
+
+#[cfg(test)]
+mod meter_tests {
+ use super::Meter;
+
- if release {
- // The files are on disk; the container is not read again unless the
- // install is retried from scratch.
- std::fs::remove_file(infile).ok();
+ #[test]
+ fn announced_packages_keep_the_total_from_growing() {
+ let meter = Meter::default();
@@ -149,12 +750,172 @@ index 5ea43da..0bad98e 100644
+ assert_eq!(meter.snapshot(), (10, 10));
+ }
+}
+
+#[cfg(test)]
+mod release_tests {
+ use super::{Footprint, Layout, Release, Source, Window, in_flight, releases_space};
+ use std::io::{Read, Seek, SeekFrom};
+ use std::path::{Path, PathBuf};
+
+ fn scratch(name: &str) -> PathBuf {
+ let path = std::env::temp_dir().join(format!("xodus-release-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&path);
+ std::fs::create_dir_all(&path).unwrap();
+ path
+ }
+
+ fn pattern(len: usize) -> Vec<u8> {
+ (0..len).map(|index| (index % 251) as u8 + 1).collect()
+ }
+
+ fn info(offset: u64, uncompressed: u64, compressed: u64, compression: u16) -> eappx::FileInfo {
+ eappx::FileInfo {
+ key_id_index: 0,
+ compression_type: compression,
+ offset_to_file: offset,
+ uncompressed_length: uncompressed,
+ compressed_length: compressed,
+ filehash: None,
+ block_hashes: None,
+ }
+ }
+
+ #[test]
+ fn a_window_reads_only_the_package_it_covers() {
+ let root = scratch("window");
+ let path = root.join("bundle.eappxbundle");
+ let bytes = pattern(4096);
+ std::fs::write(&path, &bytes).unwrap();
+ let file = std::fs::File::open(&path).unwrap();
+ let source = Source { file: &file, origin: &path, name: PathBuf::from("member.eappx"), start: 100, len: 50 };
+ let mut window = Window::open(&source, None).unwrap();
+
+ let mut all = Vec::new();
+ window.read_to_end(&mut all).unwrap();
+ assert_eq!(all, bytes[100..150]);
+
+ assert_eq!(window.seek(SeekFrom::End(-10)).unwrap(), 40);
+ let mut tail = Vec::new();
+ window.read_to_end(&mut tail).unwrap();
+ assert_eq!(tail, bytes[140..150]);
+
+ window.seek(SeekFrom::Start(5)).unwrap();
+ let mut two = [0u8; 2];
+ window.read_exact(&mut two).unwrap();
+ assert_eq!(two, bytes[105..107]);
+ assert!(window.seek(SeekFrom::Current(-10)).is_err());
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ #[test]
+ fn a_file_never_claims_bytes_past_the_next_entry() {
+ let layout = Layout { bounds: vec![0, 100, 300, 1000], len: 1200 };
+ assert_eq!(layout.stored(&info(100, 150, 0, 0)), 150);
+ assert_eq!(layout.stored(&info(100, 900, 0, 0)), 200);
+ assert_eq!(layout.stored(&info(100, 900, 120, 1)), 120);
+ assert_eq!(layout.stored(&info(1000, 900, 0, 0)), 200);
+ }
+
+ #[test]
+ fn released_bytes_stay_inside_the_written_file() {
+ let root = scratch("punch");
+ if !releases_space(&root) {
+ std::fs::remove_dir_all(&root).ok();
+ return;
+ }
+ let path = root.join("game.eappx");
+ std::fs::write(&path, pattern(1 << 20)).unwrap();
+ let file = std::fs::File::open(&path).unwrap();
+ let release = Release::open(&path, &file);
+ let block = release.block;
+ let source = Source { file: &file, origin: &path, name: path.clone(), start: 0, len: 1 << 20 };
+ let mut window = Window::open(&source, Some(&release)).unwrap();
+ window.spend(100, 3 * block);
+ window.seek(SeekFrom::Start(100)).unwrap();
+ let mut consumed = vec![0u8; usize::try_from(3 * block).unwrap()];
+ window.read_exact(&mut consumed).unwrap();
+ window.settle();
+
+ assert!(!path.exists(), "a container that lost bytes no longer looks like a finished download");
+ let spent = std::fs::read(&release.spent).unwrap();
+ let original = pattern(1 << 20);
+ let block = usize::try_from(block).unwrap();
+ assert_eq!(spent.len(), original.len());
+ assert_eq!(spent[..block], original[..block]);
+ assert!(spent[block..3 * block].iter().all(|&byte| byte == 0));
+ assert_eq!(spent[3 * block..], original[3 * block..]);
+
+ release.abandon();
+ assert!(!release.spent.exists());
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ #[test]
+ fn a_failure_before_any_release_keeps_the_download() {
+ let root = scratch("kept");
+ let path = root.join("game.eappx");
+ std::fs::write(&path, pattern(1 << 16)).unwrap();
+ let file = std::fs::File::open(&path).unwrap();
+ let release = Release::open(&path, &file);
+ release.abandon();
+ assert_eq!(std::fs::read(&path).unwrap(), pattern(1 << 16));
+ release.finish();
+ assert!(!path.exists());
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ #[test]
+ fn a_container_that_cannot_give_bytes_back_is_kept_for_a_retry() {
+ let root = scratch("unpunchable");
+ let path = root.join("game.eappx");
+ std::fs::write(&path, pattern(1 << 20)).unwrap();
+ let file = std::fs::File::open(&path).unwrap();
+ let mut release = Release::open(&path, &file);
+ release.file = Some(std::fs::File::open(&path).unwrap());
+ let block = release.block;
+ let source = Source { file: &file, origin: &path, name: path.clone(), start: 0, len: 1 << 20 };
+ let mut window = Window::open(&source, Some(&release)).unwrap();
+ window.spend(0, 3 * block);
+ let mut consumed = vec![0u8; usize::try_from(3 * block).unwrap()];
+ window.read_exact(&mut consumed).unwrap();
+ window.settle();
+
+ assert!(!release.spent.exists());
+ release.abandon();
+ assert_eq!(std::fs::read(&path).unwrap(), pattern(1 << 20));
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ #[test]
+ fn reading_without_a_release_leaves_the_container_alone() {
+ let root = scratch("plain");
+ let path = root.join("game.eappx");
+ std::fs::write(&path, pattern(1 << 16)).unwrap();
+ let file = std::fs::File::open(&path).unwrap();
+ let source = Source { file: &file, origin: Path::new(&path), name: path.clone(), start: 0, len: 1 << 16 };
+ let mut window = Window::open(&source, None).unwrap();
+ window.spend(0, 1 << 16);
+ let mut all = Vec::new();
+ window.read_to_end(&mut all).unwrap();
+ window.settle();
+ assert_eq!(std::fs::read(&path).unwrap(), pattern(1 << 16));
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ #[test]
+ fn the_extra_space_depends_on_whether_bytes_are_given_back() {
+ let footprint = Footprint { unpacked: 80_000_000_000, growth: 1_000, files: 10, block: 4096 };
+ assert_eq!(footprint.extra(false), 80_000_000_000);
+ assert_eq!(footprint.extra(true), 1_000 + 10 * 2 * 4096 + in_flight());
}
- Ok(())
}
diff --git a/crates/xodus-cli/src/commands/legacy_install.rs b/crates/xodus-cli/src/commands/legacy_install.rs
new file mode 100755
index 0000000..d43c5fc
index 0000000..a98d0fd
--- /dev/null
+++ b/crates/xodus-cli/src/commands/legacy_install.rs
@@ -0,0 +1,1527 @@
@@ -0,0 +1,1603 @@
+//! Installs a legacy Store title: resolve, license, download, extract.
+//!
+//! `streaming` only understands MSIXVC, where the container *is* the game and
@@ -215,6 +976,22 @@ index 0000000..d43c5fc
+ available.parse::<u64>().ok().map(|kib| kib.saturating_mul(1024))
+}
+
+struct Step {
+ container: u64,
+ during: u64,
+ after: u64,
+}
+
+fn space_to_unpack(steps: &[Step]) -> u64 {
+ let mut settled: i128 = 0;
+ let mut peak: i128 = 0;
+ for step in steps {
+ peak = peak.max(settled + i128::from(step.during));
+ settled += i128::from(step.after) - i128::from(step.container);
+ }
+ u64::try_from(peak).unwrap_or(u64::MAX)
+}
+
+/// Reports why the install stopped without disclosing anything sensitive.
+///
+/// The app only forwards stderr lines that are on a known allowlist, so a bare
@@ -621,8 +1398,13 @@ index 0000000..d43c5fc
+ return fail("staging-failed", "Could not clear an unfinished download from the staging folder");
+ }
+ }
+ let releases = crate::commands::extract_eappx::releases_space(&destination);
+ if let Some(free) = free_bytes(&destination) {
+ let needed = total.saturating_add(largest).saturating_add(largest / 10);
+ let needed = if releases {
+ total.saturating_add(crate::commands::extract_eappx::in_flight())
+ } else {
+ total.saturating_add(largest).saturating_add(largest / 10)
+ };
+ if free.saturating_add(held) < needed {
+ return fail(
+ "insufficient-space",
@@ -691,6 +1473,30 @@ index 0000000..d43c5fc
+ downloaded.push(target);
+ }
+
+ if let Some(free) = free_bytes(&destination) {
+ let steps: Vec<Step> = downloaded
+ .iter()
+ .map(|container| {
+ let size = std::fs::metadata(container).map_or(0, |meta| meta.len());
+ match crate::commands::extract_eappx::footprint(container) {
+ Some(footprint) => Step { container: size, during: footprint.extra(releases), after: footprint.unpacked },
+ None => Step { container: size, during: size.saturating_add(size / 10), after: size },
+ }
+ })
+ .collect();
+ let needed = space_to_unpack(&steps);
+ if free < needed {
+ return fail(
+ "insufficient-space",
+ &format!(
+ "Unpacking needs about {} GB free, and {} GB is available; the download is kept for a retry",
+ needed.div_ceil(1_000_000_000),
+ free / 1_000_000_000
+ ),
+ );
+ }
+ }
+
+ progress.phase("installing");
+ let key_file_text = key_file.display().to_string();
+ let meter = std::sync::Arc::new(crate::commands::extract_eappx::Meter::default());
@@ -715,7 +1521,7 @@ index 0000000..d43c5fc
+ Some(&meter),
+ // A full title is tens of gigabytes. Holding the container
+ // while its members are decrypted can fill the device.
+ true,
+ releases,
+ )
+ }
+ });
@@ -739,7 +1545,10 @@ index 0000000..d43c5fc
+ progress.bytes(high, total);
+ };
+ if extracted != ExitCode::SUCCESS {
+ return fail("extract-failed", "Could not unpack the package; retrying may require downloading the bundle again because containers are removed to save disk space");
+ if container.is_file() {
+ return fail("extract-failed", "Could not unpack the package; the download is kept for a retry");
+ }
+ return fail("extract-failed", "Could not unpack the package; resume to download it again");
+ }
+ // Drop each container as soon as it is unpacked: a full title is tens of
+ // gigabytes, and holding the archive and its contents at once can fill
@@ -1358,6 +2167,34 @@ index 0000000..d43c5fc
+ }
+
+ #[test]
+ fn a_container_unpacked_in_place_needs_only_its_growth() {
+ let size = 85_000_000_000;
+ let steps = [Step { container: size, during: 300_000_000, after: size }];
+ assert_eq!(space_to_unpack(&steps), 300_000_000);
+ }
+
+ #[test]
+ fn a_container_held_while_unpacking_needs_its_full_contents() {
+ let size = 85_000_000_000;
+ let steps = [Step { container: size, during: size, after: size }];
+ assert_eq!(space_to_unpack(&steps), size);
+ }
+
+ #[test]
+ fn later_containers_count_what_earlier_ones_left_behind() {
+ let steps = [
+ Step { container: 10, during: 12, after: 15 },
+ Step { container: 5, during: 9, after: 6 },
+ ];
+ assert_eq!(space_to_unpack(&steps), 14);
+ let shrinking = [
+ Step { container: 10, during: 12, after: 4 },
+ Step { container: 5, during: 9, after: 6 },
+ ];
+ assert_eq!(space_to_unpack(&shrinking), 12);
+ }
+
+ #[test]
+ fn free_bytes_reads_the_available_column() {
+ let root = scratch("free");
+ let free = free_bytes(&root).expect("df should answer for an existing folder");