New module 'dup3'.
[gnulib.git] / lib / dup3.c
1 /* Copy a file descriptor, applying specific flags.
2    Copyright (C) 2009 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 2, 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, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 #include <config.h>
19
20 /* Specification.  */
21 #include <unistd.h>
22
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <limits.h>
26
27 #include "binary-io.h"
28
29 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
30 /* Native Woe32 API.  */
31
32 /* Get declarations of the Win32 API functions.  */
33 # define WIN32_LEAN_AND_MEAN
34 # include <windows.h>
35
36 /* Upper bound on getdtablesize().  See lib/getdtablesize.c.  */
37 # define OPEN_MAX_MAX 0x10000
38
39 #else
40 /* Unix API.  */
41
42 # ifndef O_CLOEXEC
43 #  define O_CLOEXEC 0
44 # endif
45
46 #endif
47
48 int
49 dup3 (int oldfd, int newfd, int flags)
50 {
51   if (oldfd < 0 || newfd < 0 || newfd >= getdtablesize ())
52     {
53       errno = EBADF;
54       return -1;
55     }
56
57   if (newfd == oldfd)
58     {
59       errno = EINVAL;
60       return -1;
61     }
62
63   /* Check the supported flags.
64      Note that O_NONBLOCK is not supported, because setting it on newfd
65      would implicitly also set it on oldfd.  */
66   if ((flags & ~(O_CLOEXEC | O_BINARY | O_TEXT)) != 0)
67     {
68       errno = EINVAL;
69       return -1;
70     }
71
72 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
73 /* Native Woe32 API.  */
74
75   if (flags & O_CLOEXEC)
76     {
77       /* Neither dup() nor dup2() can create a file descriptor with
78          O_CLOEXEC = O_NOINHERIT set.  We need to use the low-level function
79          _open_osfhandle for this.  Iterate until all file descriptors less
80          than newfd are filled up.  */
81       HANDLE curr_process = GetCurrentProcess ();
82       HANDLE old_handle = (HANDLE) _get_osfhandle (oldfd);
83       unsigned char fds_to_close[OPEN_MAX_MAX / CHAR_BIT];
84       unsigned int fds_to_close_bound = 0;
85       int result;
86
87       if (old_handle == INVALID_HANDLE_VALUE)
88         {
89           /* oldfd is not open, or is an unassigned standard file
90              descriptor.  */
91           errno = EBADF;
92           return -1;
93         }
94
95       close (newfd);
96
97       for (;;)
98         {
99           HANDLE new_handle;
100           int duplicated_fd;
101           unsigned int index;
102
103           if (!DuplicateHandle (curr_process,         /* SourceProcessHandle */
104                                 old_handle,           /* SourceHandle */
105                                 curr_process,         /* TargetProcessHandle */
106                                 (PHANDLE) &new_handle, /* TargetHandle */
107                                 (DWORD) 0,            /* DesiredAccess */
108                                 FALSE,                /* InheritHandle */
109                                 DUPLICATE_SAME_ACCESS)) /* Options */
110             {
111               errno = EBADF; /* arbitrary */
112               result = -1;
113               break;
114             }
115           duplicated_fd = _open_osfhandle ((long) new_handle, flags);
116           if (duplicated_fd < 0)
117             {
118               CloseHandle (new_handle);
119               result = -1;
120               break;
121             }
122           if (duplicated_fd > newfd)
123             /* Shouldn't happen, since newfd is still closed.  */
124             abort ();
125           if (duplicated_fd == newfd)
126             {
127               result = newfd;
128               break;
129             }
130
131           /* Set the bit duplicated_fd in fds_to_close[].  */
132           index = (unsigned int) duplicated_fd / CHAR_BIT;
133           if (index >= fds_to_close_bound)
134             {
135               if (index >= sizeof (fds_to_close))
136                 /* Need to increase OPEN_MAX_MAX.  */
137                 abort ();
138               memset (fds_to_close + fds_to_close_bound, '\0',
139                       index + 1 - fds_to_close_bound);
140               fds_to_close_bound = index + 1;
141             }
142           fds_to_close[index] |= 1 << ((unsigned int) duplicated_fd % CHAR_BIT);
143         }
144
145       /* Close the previous fds that turned out to be too small.  */
146       {
147         int saved_errno = errno;
148         unsigned int duplicated_fd;
149
150         for (duplicated_fd = 0;
151              duplicated_fd < fds_to_close_bound * CHAR_BIT;
152              duplicated_fd++)
153           if ((fds_to_close[duplicated_fd / CHAR_BIT]
154                >> (duplicated_fd % CHAR_BIT))
155               & 1)
156             close (duplicated_fd);
157
158         errno = saved_errno;
159       }
160
161       return result;
162     }
163
164   if (dup2 (oldfd, newfd) < 0)
165     return -1;
166
167 #else
168 /* Unix API.  */
169
170   if (dup2 (oldfd, newfd) < 0)
171     return -1;
172
173   /* POSIX <http://www.opengroup.org/onlinepubs/9699919799/functions/dup.html>
174      says that initially, the FD_CLOEXEC flag is cleared on newfd.  */
175
176   if (flags & O_CLOEXEC)
177     {
178       int fcntl_flags;
179
180       if ((fcntl_flags = fcntl (newfd, F_GETFD, 0)) < 0
181           || fcntl (newfd, F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
182         {
183           int saved_errno = errno;
184           close (newfd);
185           errno = saved_errno;
186           return -1;
187         }
188     }
189
190 #endif
191
192 #if O_BINARY
193   if (flags & O_BINARY)
194     setmode (newfd, O_BINARY);
195   else if (flags & O_TEXT)
196     setmode (newfd, O_TEXT);
197 #endif
198
199   return newfd;
200 }