aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorPaul Eggert2013-07-07 11:00:14 -0700
committerPaul Eggert2013-07-07 11:00:14 -0700
commit067428c1717acd28f205c2cff93f0583eb347f4c (patch)
tree5937b119187f9900840e2c1174b408e86bb8d12b /lib
parent9aff9b3864085addb02b699f9648e547a8c00e54 (diff)
downloademacs-067428c1717acd28f205c2cff93f0583eb347f4c.tar.gz
emacs-067428c1717acd28f205c2cff93f0583eb347f4c.zip
Make file descriptors close-on-exec when possible.
This simplifies Emacs a bit, since it no longer needs to worry about closing file descriptors by hand in some cases. It also fixes some unlikely races. Not all such races, as libraries often open files internally without setting close-on-exec, but it's an improvement. * admin/merge-gnulib (GNULIB_MODULES): Add fcntl, pipe2. (GNULIB_TOOL_FLAGS): Avoid binary-io, close. Do not avoid fcntl. * configure.ac (mkostemp): New function to check for. (PTY_OPEN): Pass O_CLOEXEC to posix_openpt. * lib/fcntl.c, lib/getdtablesize.c, lib/pipe2.c, m4/fcntl.m4: * m4/getdtablesize.m4, m4/pipe2.m4: New files, taken from gnulib. * lib/gnulib.mk, m4/gnulib-comp.m4: Regenerate. * nt/gnulib.mk: Remove empty gl_GNULIB_ENABLED_verify section; otherwise, gnulib-tool complains given close-on-exec changes. * nt/inc/ms-w32.h (pipe): Remove. * nt/mingw-cfg.site (ac_cv_func_fcntl, gl_cv_func_fcntl_f_dupfd_cloexec) (gl_cv_func_fcntl_f_dupfd_works, ac_cv_func_pipe2): New vars. * src/alloc.c (valid_pointer_p) [!WINDOWSNT]: * src/callproc.c (Fcall_process) [!MSDOS]: * src/emacs.c (main) [!DOS_NT]: * src/nsterm.m (ns_term_init): * src/process.c (create_process): Use 'pipe2' with O_CLOEXEC instead of 'pipe'. * src/emacs.c (Fcall_process_region) [HAVE_MKOSTEMP]: * src/filelock.c (create_lock_file) [HAVE_MKOSTEMP]: Prefer mkostemp with O_CLOEXEC to mkstemp. * src/callproc.c (relocate_fd) [!WINDOWSNT]: * src/emacs.c (main): Use F_DUPFD_CLOEXEC, not plain F_DUPFD. No need to use fcntl (..., F_SETFD, FD_CLOEXEC), since we're now using pipe2. * src/filelock.c (create_lock_file) [! HAVE_MKOSTEMP]: Make the resulting file descriptor close-on-exec. * src/lisp.h, src/lread.c, src/process.c (close_load_descs, close_process_descs): * src/lread.c (load_descriptor_list, load_descriptor_unwind): Remove; no longer needed. All uses removed. * src/process.c (SOCK_CLOEXEC): Define to 0 if not supplied by system. (close_on_exec, accept4, process_socket) [!SOCK_CLOEXEC]: New functions. (socket) [!SOCK_CLOEXEC]: Supply a substitute. (Fmake_network_process, Fnetwork_interface_list): (Fnetwork_interface_info, server_accept_connection): Make newly-created socket close-on-exec. * src/sysdep.c (emacs_open, emacs_fopen): Make new-created descriptor close-on-exec. * src/w32.c (fcntl): Support F_DUPFD_CLOEXEC well enough for Emacs. * src/w32.c, src/w32.h (pipe2): Rename from 'pipe', with new flags arg. Fixes: debbugs:14803
Diffstat (limited to 'lib')
-rw-r--r--lib/fcntl.c311
-rw-r--r--lib/getdtablesize.c86
-rw-r--r--lib/gnulib.mk30
-rw-r--r--lib/pipe2.c171
4 files changed, 595 insertions, 3 deletions
diff --git a/lib/fcntl.c b/lib/fcntl.c
new file mode 100644
index 00000000000..735fa66f4d7
--- /dev/null
+++ b/lib/fcntl.c
@@ -0,0 +1,311 @@
1/* Provide file descriptor control.
2
3 Copyright (C) 2009-2013 Free Software Foundation, Inc.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17
18/* Written by Eric Blake <ebb9@byu.net>. */
19
20#include <config.h>
21
22/* Specification. */
23#include <fcntl.h>
24
25#include <errno.h>
26#include <limits.h>
27#include <stdarg.h>
28#include <unistd.h>
29
30#if !HAVE_FCNTL
31# define rpl_fcntl fcntl
32#endif
33#undef fcntl
34
35#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
36/* Get declarations of the native Windows API functions. */
37# define WIN32_LEAN_AND_MEAN
38# include <windows.h>
39
40/* Get _get_osfhandle. */
41# include "msvc-nothrow.h"
42
43/* Upper bound on getdtablesize(). See lib/getdtablesize.c. */
44# define OPEN_MAX_MAX 0x10000
45
46/* Duplicate OLDFD into the first available slot of at least NEWFD,
47 which must be positive, with FLAGS determining whether the duplicate
48 will be inheritable. */
49static int
50dupfd (int oldfd, int newfd, int flags)
51{
52 /* Mingw has no way to create an arbitrary fd. Iterate until all
53 file descriptors less than newfd are filled up. */
54 HANDLE curr_process = GetCurrentProcess ();
55 HANDLE old_handle = (HANDLE) _get_osfhandle (oldfd);
56 unsigned char fds_to_close[OPEN_MAX_MAX / CHAR_BIT];
57 unsigned int fds_to_close_bound = 0;
58 int result;
59 BOOL inherit = flags & O_CLOEXEC ? FALSE : TRUE;
60 int mode;
61
62 if (newfd < 0 || getdtablesize () <= newfd)
63 {
64 errno = EINVAL;
65 return -1;
66 }
67 if (old_handle == INVALID_HANDLE_VALUE
68 || (mode = setmode (oldfd, O_BINARY)) == -1)
69 {
70 /* oldfd is not open, or is an unassigned standard file
71 descriptor. */
72 errno = EBADF;
73 return -1;
74 }
75 setmode (oldfd, mode);
76 flags |= mode;
77
78 for (;;)
79 {
80 HANDLE new_handle;
81 int duplicated_fd;
82 unsigned int index;
83
84 if (!DuplicateHandle (curr_process, /* SourceProcessHandle */
85 old_handle, /* SourceHandle */
86 curr_process, /* TargetProcessHandle */
87 (PHANDLE) &new_handle, /* TargetHandle */
88 (DWORD) 0, /* DesiredAccess */
89 inherit, /* InheritHandle */
90 DUPLICATE_SAME_ACCESS)) /* Options */
91 {
92 /* TODO: Translate GetLastError () into errno. */
93 errno = EMFILE;
94 result = -1;
95 break;
96 }
97 duplicated_fd = _open_osfhandle ((intptr_t) new_handle, flags);
98 if (duplicated_fd < 0)
99 {
100 CloseHandle (new_handle);
101 errno = EMFILE;
102 result = -1;
103 break;
104 }
105 if (newfd <= duplicated_fd)
106 {
107 result = duplicated_fd;
108 break;
109 }
110
111 /* Set the bit duplicated_fd in fds_to_close[]. */
112 index = (unsigned int) duplicated_fd / CHAR_BIT;
113 if (fds_to_close_bound <= index)
114 {
115 if (sizeof fds_to_close <= index)
116 /* Need to increase OPEN_MAX_MAX. */
117 abort ();
118 memset (fds_to_close + fds_to_close_bound, '\0',
119 index + 1 - fds_to_close_bound);
120 fds_to_close_bound = index + 1;
121 }
122 fds_to_close[index] |= 1 << ((unsigned int) duplicated_fd % CHAR_BIT);
123 }
124
125 /* Close the previous fds that turned out to be too small. */
126 {
127 int saved_errno = errno;
128 unsigned int duplicated_fd;
129
130 for (duplicated_fd = 0;
131 duplicated_fd < fds_to_close_bound * CHAR_BIT;
132 duplicated_fd++)
133 if ((fds_to_close[duplicated_fd / CHAR_BIT]
134 >> (duplicated_fd % CHAR_BIT))
135 & 1)
136 close (duplicated_fd);
137
138 errno = saved_errno;
139 }
140
141# if REPLACE_FCHDIR
142 if (0 <= result)
143 result = _gl_register_dup (oldfd, result);
144# endif
145 return result;
146}
147#endif /* W32 */
148
149/* Perform the specified ACTION on the file descriptor FD, possibly
150 using the argument ARG further described below. This replacement
151 handles the following actions, and forwards all others on to the
152 native fcntl. An unrecognized ACTION returns -1 with errno set to
153 EINVAL.
154
155 F_DUPFD - duplicate FD, with int ARG being the minimum target fd.
156 If successful, return the duplicate, which will be inheritable;
157 otherwise return -1 and set errno.
158
159 F_DUPFD_CLOEXEC - duplicate FD, with int ARG being the minimum
160 target fd. If successful, return the duplicate, which will not be
161 inheritable; otherwise return -1 and set errno.
162
163 F_GETFD - ARG need not be present. If successful, return a
164 non-negative value containing the descriptor flags of FD (only
165 FD_CLOEXEC is portable, but other flags may be present); otherwise
166 return -1 and set errno. */
167
168int
169rpl_fcntl (int fd, int action, /* arg */...)
170{
171 va_list arg;
172 int result = -1;
173 va_start (arg, action);
174 switch (action)
175 {
176
177#if !HAVE_FCNTL
178 case F_DUPFD:
179 {
180 int target = va_arg (arg, int);
181 result = dupfd (fd, target, 0);
182 break;
183 }
184#elif FCNTL_DUPFD_BUGGY || REPLACE_FCHDIR
185 case F_DUPFD:
186 {
187 int target = va_arg (arg, int);
188 /* Detect invalid target; needed for cygwin 1.5.x. */
189 if (target < 0 || getdtablesize () <= target)
190 errno = EINVAL;
191 else
192 {
193 /* Haiku alpha 2 loses fd flags on original. */
194 int flags = fcntl (fd, F_GETFD);
195 if (flags < 0)
196 {
197 result = -1;
198 break;
199 }
200 result = fcntl (fd, action, target);
201 if (0 <= result && fcntl (fd, F_SETFD, flags) == -1)
202 {
203 int saved_errno = errno;
204 close (result);
205 result = -1;
206 errno = saved_errno;
207 }
208# if REPLACE_FCHDIR
209 if (0 <= result)
210 result = _gl_register_dup (fd, result);
211# endif
212 }
213 break;
214 } /* F_DUPFD */
215#endif /* FCNTL_DUPFD_BUGGY || REPLACE_FCHDIR */
216
217 case F_DUPFD_CLOEXEC:
218 {
219 int target = va_arg (arg, int);
220
221#if !HAVE_FCNTL
222 result = dupfd (fd, target, O_CLOEXEC);
223 break;
224#else /* HAVE_FCNTL */
225 /* Try the system call first, if the headers claim it exists
226 (that is, if GNULIB_defined_F_DUPFD_CLOEXEC is 0), since we
227 may be running with a glibc that has the macro but with an
228 older kernel that does not support it. Cache the
229 information on whether the system call really works, but
230 avoid caching failure if the corresponding F_DUPFD fails
231 for any reason. 0 = unknown, 1 = yes, -1 = no. */
232 static int have_dupfd_cloexec = GNULIB_defined_F_DUPFD_CLOEXEC ? -1 : 0;
233 if (0 <= have_dupfd_cloexec)
234 {
235 result = fcntl (fd, action, target);
236 if (0 <= result || errno != EINVAL)
237 {
238 have_dupfd_cloexec = 1;
239# if REPLACE_FCHDIR
240 if (0 <= result)
241 result = _gl_register_dup (fd, result);
242# endif
243 }
244 else
245 {
246 result = rpl_fcntl (fd, F_DUPFD, target);
247 if (result < 0)
248 break;
249 have_dupfd_cloexec = -1;
250 }
251 }
252 else
253 result = rpl_fcntl (fd, F_DUPFD, target);
254 if (0 <= result && have_dupfd_cloexec == -1)
255 {
256 int flags = fcntl (result, F_GETFD);
257 if (flags < 0 || fcntl (result, F_SETFD, flags | FD_CLOEXEC) == -1)
258 {
259 int saved_errno = errno;
260 close (result);
261 errno = saved_errno;
262 result = -1;
263 }
264 }
265 break;
266#endif /* HAVE_FCNTL */
267 } /* F_DUPFD_CLOEXEC */
268
269#if !HAVE_FCNTL
270 case F_GETFD:
271 {
272# if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
273 HANDLE handle = (HANDLE) _get_osfhandle (fd);
274 DWORD flags;
275 if (handle == INVALID_HANDLE_VALUE
276 || GetHandleInformation (handle, &flags) == 0)
277 errno = EBADF;
278 else
279 result = (flags & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
280# else /* !W32 */
281 /* Use dup2 to reject invalid file descriptors. No way to
282 access this information, so punt. */
283 if (0 <= dup2 (fd, fd))
284 result = 0;
285# endif /* !W32 */
286 break;
287 } /* F_GETFD */
288#endif /* !HAVE_FCNTL */
289
290 /* Implementing F_SETFD on mingw is not trivial - there is no
291 API for changing the O_NOINHERIT bit on an fd, and merely
292 changing the HANDLE_FLAG_INHERIT bit on the underlying handle
293 can lead to odd state. It may be possible by duplicating the
294 handle, using _open_osfhandle with the right flags, then
295 using dup2 to move the duplicate onto the original, but that
296 is not supported for now. */
297
298 default:
299 {
300#if HAVE_FCNTL
301 void *p = va_arg (arg, void *);
302 result = fcntl (fd, action, p);
303#else
304 errno = EINVAL;
305#endif
306 break;
307 }
308 }
309 va_end (arg);
310 return result;
311}
diff --git a/lib/getdtablesize.c b/lib/getdtablesize.c
new file mode 100644
index 00000000000..9947405af61
--- /dev/null
+++ b/lib/getdtablesize.c
@@ -0,0 +1,86 @@
1/* getdtablesize() function for platforms that don't have it.
2 Copyright (C) 2008-2013 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2008.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17
18#include <config.h>
19
20/* Specification. */
21#include <unistd.h>
22
23#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
24
25#include <stdio.h>
26
27#include "msvc-inval.h"
28
29#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
30static int
31_setmaxstdio_nothrow (int newmax)
32{
33 int result;
34
35 TRY_MSVC_INVAL
36 {
37 result = _setmaxstdio (newmax);
38 }
39 CATCH_MSVC_INVAL
40 {
41 result = -1;
42 }
43 DONE_MSVC_INVAL;
44
45 return result;
46}
47# define _setmaxstdio _setmaxstdio_nothrow
48#endif
49
50/* Cache for the previous getdtablesize () result. */
51static int dtablesize;
52
53int
54getdtablesize (void)
55{
56 if (dtablesize == 0)
57 {
58 /* We are looking for the number N such that the valid file descriptors
59 are 0..N-1. It can be obtained through a loop as follows:
60 {
61 int fd;
62 for (fd = 3; fd < 65536; fd++)
63 if (dup2 (0, fd) == -1)
64 break;
65 return fd;
66 }
67 On Windows XP, the result is 2048.
68 The drawback of this loop is that it allocates memory for a libc
69 internal array that is never freed.
70
71 The number N can also be obtained as the upper bound for
72 _getmaxstdio (). _getmaxstdio () returns the maximum number of open
73 FILE objects. The sanity check in _setmaxstdio reveals the maximum
74 number of file descriptors. This too allocates memory, but it is
75 freed when we call _setmaxstdio with the original value. */
76 int orig_max_stdio = _getmaxstdio ();
77 unsigned int bound;
78 for (bound = 0x10000; _setmaxstdio (bound) < 0; bound = bound / 2)
79 ;
80 _setmaxstdio (orig_max_stdio);
81 dtablesize = bound;
82 }
83 return dtablesize;
84}
85
86#endif
diff --git a/lib/gnulib.mk b/lib/gnulib.mk
index 4a84b1db261..9f9ac6c0583 100644
--- a/lib/gnulib.mk
+++ b/lib/gnulib.mk
@@ -21,7 +21,7 @@
21# the same distribution terms as the rest of that program. 21# the same distribution terms as the rest of that program.
22# 22#
23# Generated by gnulib-tool. 23# Generated by gnulib-tool.
24# Reproduce by: gnulib-tool --import --dir=. --lib=libgnu --source-base=lib --m4-base=m4 --doc-base=doc --tests-base=tests --aux-dir=build-aux --avoid=dup --avoid=fchdir --avoid=fcntl --avoid=fstat --avoid=malloc-posix --avoid=msvc-inval --avoid=msvc-nothrow --avoid=open --avoid=openat-die --avoid=opendir --avoid=raise --avoid=save-cwd --avoid=select --avoid=sigprocmask --avoid=sys_types --avoid=threadlib --makefile-name=gnulib.mk --conditional-dependencies --no-libtool --macro-prefix=gl --no-vc-files alloca-opt c-ctype c-strcase careadlinkat close-stream crypto/md5 crypto/sha1 crypto/sha256 crypto/sha512 dtoastr dtotimespec dup2 environ execinfo faccessat fcntl-h fdatasync fdopendir filemode fstatat fsync getloadavg getopt-gnu gettime gettimeofday ignore-value intprops largefile lstat manywarnings memrchr mktime pselect pthread_sigmask putenv qacl readlink readlinkat sig2str socklen stat-time stdalign stdarg stdbool stdio strftime strtoimax strtoumax symlink sys_stat sys_time time timer-time timespec-add timespec-sub unsetenv utimens warnings 24# Reproduce by: gnulib-tool --import --dir=. --lib=libgnu --source-base=lib --m4-base=m4 --doc-base=doc --tests-base=tests --aux-dir=build-aux --avoid=binary-io --avoid=close --avoid=dup --avoid=fchdir --avoid=fstat --avoid=malloc-posix --avoid=msvc-inval --avoid=msvc-nothrow --avoid=open --avoid=openat-die --avoid=opendir --avoid=raise --avoid=save-cwd --avoid=select --avoid=sigprocmask --avoid=sys_types --avoid=threadlib --makefile-name=gnulib.mk --conditional-dependencies --no-libtool --macro-prefix=gl --no-vc-files alloca-opt c-ctype c-strcase careadlinkat close-stream crypto/md5 crypto/sha1 crypto/sha256 crypto/sha512 dtoastr dtotimespec dup2 environ execinfo faccessat fcntl fcntl-h fdatasync fdopendir filemode fstatat fsync getloadavg getopt-gnu gettime gettimeofday ignore-value intprops largefile lstat manywarnings memrchr mktime pipe2 pselect pthread_sigmask putenv qacl readlink readlinkat sig2str socklen stat-time stdalign stdarg stdbool stdio strftime strtoimax strtoumax symlink sys_stat sys_time time timer-time timespec-add timespec-sub unsetenv utimens warnings
25 25
26 26
27MOSTLYCLEANFILES += core *.stackdump 27MOSTLYCLEANFILES += core *.stackdump
@@ -296,6 +296,15 @@ EXTRA_libgnu_a_SOURCES += at-func.c faccessat.c
296 296
297## end gnulib module faccessat 297## end gnulib module faccessat
298 298
299## begin gnulib module fcntl
300
301
302EXTRA_DIST += fcntl.c
303
304EXTRA_libgnu_a_SOURCES += fcntl.c
305
306## end gnulib module fcntl
307
299## begin gnulib module fcntl-h 308## begin gnulib module fcntl-h
300 309
301BUILT_SOURCES += fcntl.h 310BUILT_SOURCES += fcntl.h
@@ -384,6 +393,17 @@ EXTRA_libgnu_a_SOURCES += fsync.c
384 393
385## end gnulib module fsync 394## end gnulib module fsync
386 395
396## begin gnulib module getdtablesize
397
398if gl_GNULIB_ENABLED_getdtablesize
399
400endif
401EXTRA_DIST += getdtablesize.c
402
403EXTRA_libgnu_a_SOURCES += getdtablesize.c
404
405## end gnulib module getdtablesize
406
387## begin gnulib module getgroups 407## begin gnulib module getgroups
388 408
389if gl_GNULIB_ENABLED_getgroups 409if gl_GNULIB_ENABLED_getgroups
@@ -568,6 +588,12 @@ EXTRA_DIST += pathmax.h
568 588
569## end gnulib module pathmax 589## end gnulib module pathmax
570 590
591## begin gnulib module pipe2
592
593libgnu_a_SOURCES += pipe2.c
594
595## end gnulib module pipe2
596
571## begin gnulib module pselect 597## begin gnulib module pselect
572 598
573 599
@@ -1704,9 +1730,7 @@ EXTRA_DIST += utimens.h
1704 1730
1705## begin gnulib module verify 1731## begin gnulib module verify
1706 1732
1707if gl_GNULIB_ENABLED_verify
1708 1733
1709endif
1710EXTRA_DIST += verify.h 1734EXTRA_DIST += verify.h
1711 1735
1712## end gnulib module verify 1736## end gnulib module verify
diff --git a/lib/pipe2.c b/lib/pipe2.c
new file mode 100644
index 00000000000..3858c328f76
--- /dev/null
+++ b/lib/pipe2.c
@@ -0,0 +1,171 @@
1/* Create a pipe, with specific opening flags.
2 Copyright (C) 2009-2013 Free Software Foundation, Inc.
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
7 any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, see <http://www.gnu.org/licenses/>. */
16
17#include <config.h>
18
19/* Specification. */
20#include <unistd.h>
21
22#include <errno.h>
23#include <fcntl.h>
24
25#if GNULIB_BINARY_IO
26# include "binary-io.h"
27#endif
28
29#include "verify.h"
30
31#if GNULIB_defined_O_NONBLOCK
32# include "nonblocking.h"
33#endif
34
35#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
36/* Native Windows API. */
37
38# include <io.h>
39
40#endif
41
42int
43pipe2 (int fd[2], int flags)
44{
45 /* Mingw _pipe() corrupts fd on failure; also, if we succeed at
46 creating the pipe but later fail at changing fcntl, we want
47 to leave fd unchanged: http://austingroupbugs.net/view.php?id=467 */
48 int tmp[2];
49 tmp[0] = fd[0];
50 tmp[1] = fd[1];
51
52#if HAVE_PIPE2
53# undef pipe2
54 /* Try the system call first, if it exists. (We may be running with a glibc
55 that has the function but with an older kernel that lacks it.) */
56 {
57 /* Cache the information whether the system call really exists. */
58 static int have_pipe2_really; /* 0 = unknown, 1 = yes, -1 = no */
59 if (have_pipe2_really >= 0)
60 {
61 int result = pipe2 (fd, flags);
62 if (!(result < 0 && errno == ENOSYS))
63 {
64 have_pipe2_really = 1;
65 return result;
66 }
67 have_pipe2_really = -1;
68 }
69 }
70#endif
71
72 /* Check the supported flags. */
73 if ((flags & ~(O_CLOEXEC | O_NONBLOCK | O_BINARY | O_TEXT)) != 0)
74 {
75 errno = EINVAL;
76 return -1;
77 }
78
79#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
80/* Native Windows API. */
81
82 if (_pipe (fd, 4096, flags & ~O_NONBLOCK) < 0)
83 {
84 fd[0] = tmp[0];
85 fd[1] = tmp[1];
86 return -1;
87 }
88
89 /* O_NONBLOCK handling.
90 On native Windows platforms, O_NONBLOCK is defined by gnulib. Use the
91 functions defined by the gnulib module 'nonblocking'. */
92# if GNULIB_defined_O_NONBLOCK
93 if (flags & O_NONBLOCK)
94 {
95 if (set_nonblocking_flag (fd[0], true) != 0
96 || set_nonblocking_flag (fd[1], true) != 0)
97 goto fail;
98 }
99# else
100 {
101 verify (O_NONBLOCK == 0);
102 }
103# endif
104
105 return 0;
106
107#else
108/* Unix API. */
109
110 if (pipe (fd) < 0)
111 return -1;
112
113 /* POSIX <http://www.opengroup.org/onlinepubs/9699919799/functions/pipe.html>
114 says that initially, the O_NONBLOCK and FD_CLOEXEC flags are cleared on
115 both fd[0] and fd[1]. */
116
117 /* O_NONBLOCK handling.
118 On Unix platforms, O_NONBLOCK is defined by the system. Use fcntl(). */
119 if (flags & O_NONBLOCK)
120 {
121 int fcntl_flags;
122
123 if ((fcntl_flags = fcntl (fd[1], F_GETFL, 0)) < 0
124 || fcntl (fd[1], F_SETFL, fcntl_flags | O_NONBLOCK) == -1
125 || (fcntl_flags = fcntl (fd[0], F_GETFL, 0)) < 0
126 || fcntl (fd[0], F_SETFL, fcntl_flags | O_NONBLOCK) == -1)
127 goto fail;
128 }
129
130 if (flags & O_CLOEXEC)
131 {
132 int fcntl_flags;
133
134 if ((fcntl_flags = fcntl (fd[1], F_GETFD, 0)) < 0
135 || fcntl (fd[1], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1
136 || (fcntl_flags = fcntl (fd[0], F_GETFD, 0)) < 0
137 || fcntl (fd[0], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
138 goto fail;
139 }
140
141# if O_BINARY
142 if (flags & O_BINARY)
143 {
144 setmode (fd[1], O_BINARY);
145 setmode (fd[0], O_BINARY);
146 }
147 else if (flags & O_TEXT)
148 {
149 setmode (fd[1], O_TEXT);
150 setmode (fd[0], O_TEXT);
151 }
152# endif
153
154 return 0;
155
156#endif
157
158#if GNULIB_defined_O_NONBLOCK || \
159 !((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__)
160 fail:
161 {
162 int saved_errno = errno;
163 close (fd[0]);
164 close (fd[1]);
165 fd[0] = tmp[0];
166 fd[1] = tmp[1];
167 errno = saved_errno;
168 return -1;
169 }
170#endif
171}