Debian Codegraph @

libs/indicore/shm_open_anon.c

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2019 Lassi Kortela
2 // SPDX-License-Identifier: ISC
3
4 #ifdef __linux__
5 #ifndef _GNU_SOURCE
6 #define _GNU_SOURCE
7 #endif
8 #include <linux/memfd.h>
9 #include <linux/unistd.h>
10 #endif
11
12 #include <sys/types.h>
13
14 #include <sys/mman.h>
15
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <string.h>
19 #include <time.h>
20 #include <unistd.h>
21
22 #undef IMPL_MEMFD
23 #undef IMPL_POSIX
24 #undef IMPL_SHM_ANON
25 #undef IMPL_SHM_MKSTEMP
26 #undef IMPL_UNLINK_OR_CLOSE
27
28 #ifdef __linux__
29 #ifdef __NR_memfd_create
30 #define IMPL_MEMFD
31 #endif
32 #endif
33
34 #ifdef __FreeBSD__
35 #define IMPL_SHM_ANON
36 #endif
37
38 #ifdef __HAIKU__
39 #define IMPL_POSIX
40 #endif
41
42 #ifdef __NetBSD__
43 #define IMPL_POSIX
44 #endif
45
46 #ifdef __APPLE__
47 #ifdef __MACH__
48 #define IMPL_POSIX
49 #endif
50 #endif
51
52 #ifdef __sun
53 #define IMPL_POSIX
54 #endif
55
56 #ifdef __DragonFly__
57 #define IMPL_POSIX
58 #endif
59
60 #ifdef __OpenBSD__
61 #define IMPL_SHM_MKSTEMP
62 #endif
63
64 #ifdef IMPL_POSIX
65 #define IMPL_UNLINK_OR_CLOSE
66 #endif
67
68 #ifdef IMPL_SHM_MKSTEMP
69 #define IMPL_UNLINK_OR_CLOSE
70 #endif
71
72 #ifdef IMPL_UNLINK_OR_CLOSE
73 static int
74 shm_unlink_or_close(const char *name, int fd)
75 {
76 int save;
77
78 if (shm_unlink(name) == -1) {
79 save = errno;
80 close(fd);
81 errno = save;
82 return -1;
83 }
84 return fd;
85 }
86 #endif
87
88 #ifdef IMPL_POSIX
89 int
90 shm_open_anon(void)
91 {
92 char name[16] = "/shm-";
93 struct timespec tv;
94 unsigned long r;
95 char *const limit = name + sizeof(name) - 1;
96 char *start;
97 char *fill;
98 int fd, tries;
99
100 *limit = 0;
101 start = name + strlen(name);
102 for (tries = 0; tries < 4; tries++) {
103 clock_gettime(CLOCK_REALTIME, &tv);
104 r = (unsigned long)tv.tv_sec + (unsigned long)tv.tv_nsec;
105 for (fill = start; fill < limit; r /= 8)
106 *fill++ = '0' + (r % 8);
107 fd = shm_open(
108 name, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
109 if (fd != -1)
110 return shm_unlink_or_close(name, fd);
111 if (errno != EEXIST)
112 break;
113 }
114 return -1;
115 }
116 #endif
117
118 #ifdef IMPL_SHM_MKSTEMP
119 int
120 shm_open_anon(void)
121 {
122 char name[16] = "/shm-XXXXXXXXXX";
123 int fd;
124
125 if ((fd = shm_mkstemp(name)) == -1)
126 return -1;
127 return shm_unlink_or_close(name, fd);
128 }
129 #endif
130
131 #ifdef IMPL_SHM_ANON
132 int
133 shm_open_anon(void)
134 {
135 return shm_open(SHM_ANON, O_RDWR, 0);
136 }
137 #endif
138
139 #ifdef IMPL_MEMFD
140 int
141 shm_open_anon(void)
142 {
143 return syscall(
144 __NR_memfd_create, "shm_anon", (unsigned int)(MFD_CLOEXEC));
145 }
146 #endif