blob: 6fddebbb8d590f28e882c0c067f7a97a4bdb071a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
#define _POSIX_C_SOURCE 200112L
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <wlr/config.h>
#include "util/shm.h"
#define RANDNAME_PATTERN "/wlroots-XXXXXX"
static void randname(char *buf) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
long r = ts.tv_nsec;
for (int i = 0; i < 6; ++i) {
buf[i] = 'A'+(r&15)+(r&16)*2;
r >>= 5;
}
}
static int excl_shm_open(char *name) {
int retries = 100;
do {
randname(name + strlen(RANDNAME_PATTERN) - 6);
--retries;
// CLOEXEC is guaranteed to be set by shm_open
int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
if (fd >= 0) {
return fd;
}
} while (retries > 0 && errno == EEXIST);
return -1;
}
int allocate_shm_file(size_t size) {
char name[] = RANDNAME_PATTERN;
int fd = excl_shm_open(name);
if (fd < 0) {
return -1;
}
shm_unlink(name);
int ret;
do {
ret = ftruncate(fd, size);
} while (ret < 0 && errno == EINTR);
if (ret < 0) {
close(fd);
return -1;
}
return fd;
}
bool allocate_shm_file_pair(size_t size, int *rw_fd_ptr, int *ro_fd_ptr) {
char name[] = RANDNAME_PATTERN;
int rw_fd = excl_shm_open(name);
if (rw_fd < 0) {
return false;
}
// CLOEXEC is guaranteed to be set by shm_open
int ro_fd = shm_open(name, O_RDONLY, 0);
if (ro_fd < 0) {
shm_unlink(name);
close(rw_fd);
return false;
}
shm_unlink(name);
// Make sure the file cannot be re-opened in read-write mode (e.g. via
// "/proc/self/fd/" on Linux)
if (fchmod(rw_fd, 0) != 0) {
close(rw_fd);
close(ro_fd);
return false;
}
int ret;
do {
ret = ftruncate(rw_fd, size);
} while (ret < 0 && errno == EINTR);
if (ret < 0) {
close(rw_fd);
close(ro_fd);
return false;
}
*rw_fd_ptr = rw_fd;
*ro_fd_ptr = ro_fd;
return true;
}
|