2 * Copyright © 2012 Collabora, Ltd.
4 * Permission to use, copy, modify, distribute, and sell this software and its
5 * documentation for any purpose is hereby granted without fee, provided that
6 * the above copyright notice appear in all copies and that both that copyright
7 * notice and this permission notice appear in supporting documentation, and
8 * that the name of the copyright holders not be used in advertising or
9 * publicity pertaining to distribution of the software without specific,
10 * written prior permission. The copyright holders make no representations
11 * about the suitability of this software for any purpose. It is provided "as
12 * is" without express or implied warranty.
14 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
15 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
16 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
17 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
18 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
19 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
25 #include <sys/types.h>
26 #include <sys/socket.h>
30 #include <sys/epoll.h>
34 #include "os-compatibility.h"
37 set_cloexec_or_close(int fd)
44 flags = fcntl(fd, F_GETFD);
48 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
59 os_socketpair_cloexec(int domain, int type, int protocol, int *sv)
64 ret = socketpair(domain, type | SOCK_CLOEXEC, protocol, sv);
65 if (ret == 0 || errno != EINVAL)
69 ret = socketpair(domain, type, protocol, sv);
73 sv[0] = set_cloexec_or_close(sv[0]);
74 sv[1] = set_cloexec_or_close(sv[1]);
76 if (sv[0] != -1 && sv[1] != -1)
85 os_epoll_create_cloexec(void)
90 fd = epoll_create1(EPOLL_CLOEXEC);
98 return set_cloexec_or_close(fd);
102 create_tmpfile_cloexec(char *tmpname)
107 fd = mkostemp(tmpname, O_CLOEXEC);
111 fd = mkstemp(tmpname);
113 fd = set_cloexec_or_close(fd);
122 * Create a new, unique, anonymous file of the given size, and
123 * return the file descriptor for it. The file descriptor is set
124 * CLOEXEC. The file is immediately suitable for mmap()'ing
125 * the given size at offset zero.
127 * The file should not have a permanent backing store like a disk,
128 * but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
130 * The file name is deleted from the file system.
132 * The file is suitable for buffer sharing between processes by
133 * transmitting the file descriptor over Unix sockets using the
134 * SCM_RIGHTS methods.
137 os_create_anonymous_file(off_t size)
139 static const char template[] = "/weston-shared-XXXXXX";
144 path = getenv("XDG_RUNTIME_DIR");
150 name = malloc(strlen(path) + sizeof(template));
155 strcat(name, template);
157 fd = create_tmpfile_cloexec(name);
164 if (ftruncate(fd, size) < 0) {
172 #ifndef HAVE_STRCHRNUL
174 strchrnul(const char *s, int c)
176 while (*s && *s != c)