-
Notifications
You must be signed in to change notification settings - Fork 1
/
shm_open_anon.c
144 lines (121 loc) · 2.18 KB
/
shm_open_anon.c
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// Copyright 2019 Lassi Kortela
// SPDX-License-Identifier: ISC
#ifdef __linux__
#define _GNU_SOURCE
#include <linux/memfd.h>
#include <linux/unistd.h>
#endif
#include <sys/types.h>
#include <sys/mman.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#undef IMPL_MEMFD
#undef IMPL_POSIX
#undef IMPL_SHM_ANON
#undef IMPL_SHM_MKSTEMP
#undef IMPL_UNLINK_OR_CLOSE
#ifdef __linux__
#ifdef __NR_memfd_create
#define IMPL_MEMFD
#endif
#endif
#ifdef __FreeBSD__
#define IMPL_SHM_ANON
#endif
#ifdef __HAIKU__
#define IMPL_POSIX
#endif
#ifdef __NetBSD__
#define IMPL_POSIX
#endif
#ifdef __APPLE__
#ifdef __MACH__
#define IMPL_POSIX
#endif
#endif
#ifdef __sun
#define IMPL_POSIX
#endif
#ifdef __DragonFly__
#define IMPL_POSIX
#endif
#ifdef __OpenBSD__
#define IMPL_SHM_MKSTEMP
#endif
#ifdef IMPL_POSIX
#define IMPL_UNLINK_OR_CLOSE
#endif
#ifdef IMPL_SHM_MKSTEMP
#define IMPL_UNLINK_OR_CLOSE
#endif
#ifdef IMPL_UNLINK_OR_CLOSE
static int
shm_unlink_or_close(const char *name, int fd)
{
int save;
if (shm_unlink(name) == -1) {
save = errno;
close(fd);
errno = save;
return -1;
}
return fd;
}
#endif
#ifdef IMPL_POSIX
int
shm_open_anon(void)
{
char name[16] = "/shm-";
struct timespec tv;
unsigned long r;
char *const limit = name + sizeof(name) - 1;
char *start;
char *fill;
int fd, tries;
*limit = 0;
start = name + strlen(name);
for (tries = 0; tries < 4; tries++) {
clock_gettime(CLOCK_REALTIME, &tv);
r = (unsigned long)tv.tv_sec + (unsigned long)tv.tv_nsec;
for (fill = start; fill < limit; r /= 8)
*fill++ = '0' + (r % 8);
fd = shm_open(
name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
if (fd != -1)
return shm_unlink_or_close(name, fd);
if (errno != EEXIST)
break;
}
return -1;
}
#endif
#ifdef IMPL_SHM_MKSTEMP
int
shm_open_anon(void)
{
char name[16] = "/shm-XXXXXXXXXX";
int fd;
if ((fd = shm_mkstemp(name)) == -1)
return -1;
return shm_unlink_or_close(name, fd);
}
#endif
#ifdef IMPL_SHM_ANON
int
shm_open_anon(void)
{
return shm_open(SHM_ANON, O_RDWR, 0);
}
#endif
#ifdef IMPL_MEMFD
int
shm_open_anon(void)
{
return syscall(
__NR_memfd_create, "shm_anon", (unsigned int)(MFD_CLOEXEC));
}
#endif