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