From 848ff54d37359a636078d6b6c6c815bf49bdbce4 Mon Sep 17 00:00:00 2001 From: Manuel Stoeckl Date: Thu, 24 Nov 2022 12:27:47 -0500 Subject: Use shm_open instead of mkstemp for anon files --- pool-buffer.c | 74 ++++++++++++++++++++++------------------------------------- 1 file changed, 28 insertions(+), 46 deletions(-) (limited to 'pool-buffer.c') diff --git a/pool-buffer.c b/pool-buffer.c index 0016c1f..ec3927b 100644 --- a/pool-buffer.c +++ b/pool-buffer.c @@ -1,60 +1,40 @@ #define _POSIX_C_SOURCE 200809 #include #include +#include #include #include #include #include #include +#include #include #include #include "pool-buffer.h" -static bool set_cloexec(int fd) { - long flags = fcntl(fd, F_GETFD); - if (flags == -1) { - return false; - } - - if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) { - return false; - } - - return true; -} - -static int create_pool_file(size_t size, char **name) { - static const char template[] = "sway-client-XXXXXX"; - const char *path = getenv("XDG_RUNTIME_DIR"); - if (path == NULL) { - fprintf(stderr, "XDG_RUNTIME_DIR is not set\n"); - return -1; - } - - size_t name_size = strlen(template) + 1 + strlen(path) + 1; - *name = malloc(name_size); - if (*name == NULL) { - fprintf(stderr, "allocation failed\n"); - return -1; - } - snprintf(*name, name_size, "%s/%s", path, template); +static int anonymous_shm_open(void) { + int retries = 100; - int fd = mkstemp(*name); - if (fd < 0) { - return -1; - } + do { + // try a probably-unique name + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + pid_t pid = getpid(); + char name[50]; + snprintf(name, sizeof(name), "/swaybg-%x-%x", + (unsigned int)pid, (unsigned int)ts.tv_nsec); - if (!set_cloexec(fd)) { - close(fd); - return -1; - } + // shm_open guarantees that O_CLOEXEC is set + int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd >= 0) { + shm_unlink(name); + return fd; + } - if (ftruncate(fd, size) < 0) { - close(fd); - return -1; - } + --retries; + } while (retries > 0 && errno == EEXIST); - return fd; + return -1; } bool create_buffer(struct pool_buffer *buf, struct wl_shm *shm, @@ -62,18 +42,20 @@ bool create_buffer(struct pool_buffer *buf, struct wl_shm *shm, uint32_t stride = width * 4; size_t size = stride * height; - char *name; - int fd = create_pool_file(size, &name); + int fd = anonymous_shm_open(); assert(fd != -1); + + if (ftruncate(fd, size) < 0) { + close(fd); + return false; + } + void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size); buf->buffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, format); wl_shm_pool_destroy(pool); close(fd); - unlink(name); - free(name); - fd = -1; buf->size = size; buf->data = data; -- cgit v1.2.3