Import upstream version 1.28
[debian/tar] / gnu / fcntl.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Provide file descriptor control.
4
5    Copyright (C) 2009-2014 Free Software Foundation, Inc.
6
7    This program is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* Written by Eric Blake <ebb9@byu.net>.  */
21
22 #include <config.h>
23
24 /* Specification.  */
25 #include <fcntl.h>
26
27 #include <errno.h>
28 #include <limits.h>
29 #include <stdarg.h>
30 #include <unistd.h>
31
32 #if !HAVE_FCNTL
33 # define rpl_fcntl fcntl
34 #endif
35 #undef fcntl
36
37 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
38 /* Get declarations of the native Windows API functions.  */
39 # define WIN32_LEAN_AND_MEAN
40 # include <windows.h>
41
42 /* Get _get_osfhandle.  */
43 # include "msvc-nothrow.h"
44
45 /* Upper bound on getdtablesize().  See lib/getdtablesize.c.  */
46 # define OPEN_MAX_MAX 0x10000
47
48 /* Duplicate OLDFD into the first available slot of at least NEWFD,
49    which must be positive, with FLAGS determining whether the duplicate
50    will be inheritable.  */
51 static int
52 dupfd (int oldfd, int newfd, int flags)
53 {
54   /* Mingw has no way to create an arbitrary fd.  Iterate until all
55      file descriptors less than newfd are filled up.  */
56   HANDLE curr_process = GetCurrentProcess ();
57   HANDLE old_handle = (HANDLE) _get_osfhandle (oldfd);
58   unsigned char fds_to_close[OPEN_MAX_MAX / CHAR_BIT];
59   unsigned int fds_to_close_bound = 0;
60   int result;
61   BOOL inherit = flags & O_CLOEXEC ? FALSE : TRUE;
62   int mode;
63
64   if (newfd < 0 || getdtablesize () <= newfd)
65     {
66       errno = EINVAL;
67       return -1;
68     }
69   if (old_handle == INVALID_HANDLE_VALUE
70       || (mode = setmode (oldfd, O_BINARY)) == -1)
71     {
72       /* oldfd is not open, or is an unassigned standard file
73          descriptor.  */
74       errno = EBADF;
75       return -1;
76     }
77   setmode (oldfd, mode);
78   flags |= mode;
79
80   for (;;)
81     {
82       HANDLE new_handle;
83       int duplicated_fd;
84       unsigned int index;
85
86       if (!DuplicateHandle (curr_process,           /* SourceProcessHandle */
87                             old_handle,             /* SourceHandle */
88                             curr_process,           /* TargetProcessHandle */
89                             (PHANDLE) &new_handle,  /* TargetHandle */
90                             (DWORD) 0,              /* DesiredAccess */
91                             inherit,                /* InheritHandle */
92                             DUPLICATE_SAME_ACCESS)) /* Options */
93         {
94           /* TODO: Translate GetLastError () into errno.  */
95           errno = EMFILE;
96           result = -1;
97           break;
98         }
99       duplicated_fd = _open_osfhandle ((intptr_t) new_handle, flags);
100       if (duplicated_fd < 0)
101         {
102           CloseHandle (new_handle);
103           errno = EMFILE;
104           result = -1;
105           break;
106         }
107       if (newfd <= duplicated_fd)
108         {
109           result = duplicated_fd;
110           break;
111         }
112
113       /* Set the bit duplicated_fd in fds_to_close[].  */
114       index = (unsigned int) duplicated_fd / CHAR_BIT;
115       if (fds_to_close_bound <= index)
116         {
117           if (sizeof fds_to_close <= index)
118             /* Need to increase OPEN_MAX_MAX.  */
119             abort ();
120           memset (fds_to_close + fds_to_close_bound, '\0',
121                   index + 1 - fds_to_close_bound);
122           fds_to_close_bound = index + 1;
123         }
124       fds_to_close[index] |= 1 << ((unsigned int) duplicated_fd % CHAR_BIT);
125     }
126
127   /* Close the previous fds that turned out to be too small.  */
128   {
129     int saved_errno = errno;
130     unsigned int duplicated_fd;
131
132     for (duplicated_fd = 0;
133          duplicated_fd < fds_to_close_bound * CHAR_BIT;
134          duplicated_fd++)
135       if ((fds_to_close[duplicated_fd / CHAR_BIT]
136            >> (duplicated_fd % CHAR_BIT))
137           & 1)
138         close (duplicated_fd);
139
140     errno = saved_errno;
141   }
142
143 # if REPLACE_FCHDIR
144   if (0 <= result)
145     result = _gl_register_dup (oldfd, result);
146 # endif
147   return result;
148 }
149 #endif /* W32 */
150
151 /* Perform the specified ACTION on the file descriptor FD, possibly
152    using the argument ARG further described below.  This replacement
153    handles the following actions, and forwards all others on to the
154    native fcntl.  An unrecognized ACTION returns -1 with errno set to
155    EINVAL.
156
157    F_DUPFD - duplicate FD, with int ARG being the minimum target fd.
158    If successful, return the duplicate, which will be inheritable;
159    otherwise return -1 and set errno.
160
161    F_DUPFD_CLOEXEC - duplicate FD, with int ARG being the minimum
162    target fd.  If successful, return the duplicate, which will not be
163    inheritable; otherwise return -1 and set errno.
164
165    F_GETFD - ARG need not be present.  If successful, return a
166    non-negative value containing the descriptor flags of FD (only
167    FD_CLOEXEC is portable, but other flags may be present); otherwise
168    return -1 and set errno.  */
169
170 int
171 rpl_fcntl (int fd, int action, /* arg */...)
172 {
173   va_list arg;
174   int result = -1;
175   va_start (arg, action);
176   switch (action)
177     {
178
179 #if !HAVE_FCNTL
180     case F_DUPFD:
181       {
182         int target = va_arg (arg, int);
183         result = dupfd (fd, target, 0);
184         break;
185       }
186 #elif FCNTL_DUPFD_BUGGY || REPLACE_FCHDIR
187     case F_DUPFD:
188       {
189         int target = va_arg (arg, int);
190         /* Detect invalid target; needed for cygwin 1.5.x.  */
191         if (target < 0 || getdtablesize () <= target)
192           errno = EINVAL;
193         else
194           {
195             /* Haiku alpha 2 loses fd flags on original.  */
196             int flags = fcntl (fd, F_GETFD);
197             if (flags < 0)
198               {
199                 result = -1;
200                 break;
201               }
202             result = fcntl (fd, action, target);
203             if (0 <= result && fcntl (fd, F_SETFD, flags) == -1)
204               {
205                 int saved_errno = errno;
206                 close (result);
207                 result = -1;
208                 errno = saved_errno;
209               }
210 # if REPLACE_FCHDIR
211             if (0 <= result)
212               result = _gl_register_dup (fd, result);
213 # endif
214           }
215         break;
216       } /* F_DUPFD */
217 #endif /* FCNTL_DUPFD_BUGGY || REPLACE_FCHDIR */
218
219     case F_DUPFD_CLOEXEC:
220       {
221         int target = va_arg (arg, int);
222
223 #if !HAVE_FCNTL
224         result = dupfd (fd, target, O_CLOEXEC);
225         break;
226 #else /* HAVE_FCNTL */
227         /* Try the system call first, if the headers claim it exists
228            (that is, if GNULIB_defined_F_DUPFD_CLOEXEC is 0), since we
229            may be running with a glibc that has the macro but with an
230            older kernel that does not support it.  Cache the
231            information on whether the system call really works, but
232            avoid caching failure if the corresponding F_DUPFD fails
233            for any reason.  0 = unknown, 1 = yes, -1 = no.  */
234         static int have_dupfd_cloexec = GNULIB_defined_F_DUPFD_CLOEXEC ? -1 : 0;
235         if (0 <= have_dupfd_cloexec)
236           {
237             result = fcntl (fd, action, target);
238             if (0 <= result || errno != EINVAL)
239               {
240                 have_dupfd_cloexec = 1;
241 # if REPLACE_FCHDIR
242                 if (0 <= result)
243                   result = _gl_register_dup (fd, result);
244 # endif
245               }
246             else
247               {
248                 result = rpl_fcntl (fd, F_DUPFD, target);
249                 if (result < 0)
250                   break;
251                 have_dupfd_cloexec = -1;
252               }
253           }
254         else
255           result = rpl_fcntl (fd, F_DUPFD, target);
256         if (0 <= result && have_dupfd_cloexec == -1)
257           {
258             int flags = fcntl (result, F_GETFD);
259             if (flags < 0 || fcntl (result, F_SETFD, flags | FD_CLOEXEC) == -1)
260               {
261                 int saved_errno = errno;
262                 close (result);
263                 errno = saved_errno;
264                 result = -1;
265               }
266           }
267         break;
268 #endif /* HAVE_FCNTL */
269       } /* F_DUPFD_CLOEXEC */
270
271 #if !HAVE_FCNTL
272     case F_GETFD:
273       {
274 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
275         HANDLE handle = (HANDLE) _get_osfhandle (fd);
276         DWORD flags;
277         if (handle == INVALID_HANDLE_VALUE
278             || GetHandleInformation (handle, &flags) == 0)
279           errno = EBADF;
280         else
281           result = (flags & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
282 # else /* !W32 */
283         /* Use dup2 to reject invalid file descriptors.  No way to
284            access this information, so punt.  */
285         if (0 <= dup2 (fd, fd))
286           result = 0;
287 # endif /* !W32 */
288         break;
289       } /* F_GETFD */
290 #endif /* !HAVE_FCNTL */
291
292       /* Implementing F_SETFD on mingw is not trivial - there is no
293          API for changing the O_NOINHERIT bit on an fd, and merely
294          changing the HANDLE_FLAG_INHERIT bit on the underlying handle
295          can lead to odd state.  It may be possible by duplicating the
296          handle, using _open_osfhandle with the right flags, then
297          using dup2 to move the duplicate onto the original, but that
298          is not supported for now.  */
299
300     default:
301       {
302 #if HAVE_FCNTL
303         void *p = va_arg (arg, void *);
304         result = fcntl (fd, action, p);
305 #else
306         errno = EINVAL;
307 #endif
308         break;
309       }
310     }
311   va_end (arg);
312   return result;
313 }