3fa035a63dd66b26fd094dbf89c141f41d4d7341
[external/binutils.git] / gdb / common / filestuff.c
1 /* Low-level file-handling.
2    Copyright (C) 2012-2018 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #include "common-defs.h"
20 #include "filestuff.h"
21 #include "gdb_vecs.h"
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <algorithm>
27
28 #ifdef USE_WIN32API
29 #include <winsock2.h>
30 #include <windows.h>
31 #define HAVE_SOCKETS 1
32 #elif defined HAVE_SYS_SOCKET_H
33 #include <sys/socket.h>
34 /* Define HAVE_F_GETFD if we plan to use F_GETFD.  */
35 #define HAVE_F_GETFD F_GETFD
36 #define HAVE_SOCKETS 1
37 #endif
38
39 #ifdef HAVE_SYS_RESOURCE_H
40 #include <sys/resource.h>
41 #endif /* HAVE_SYS_RESOURCE_H */
42
43 #ifndef O_CLOEXEC
44 #define O_CLOEXEC 0
45 #endif
46
47 #ifndef SOCK_CLOEXEC
48 #define SOCK_CLOEXEC 0
49 #endif
50
51 \f
52
53 #ifndef HAVE_FDWALK
54
55 #include <dirent.h>
56
57 /* Replacement for fdwalk, if the system doesn't define it.  Walks all
58    open file descriptors (though this implementation may walk closed
59    ones as well, depending on the host platform's capabilities) and
60    call FUNC with ARG.  If FUNC returns non-zero, stops immediately
61    and returns the same value.  Otherwise, returns zero when
62    finished.  */
63
64 static int
65 fdwalk (int (*func) (void *, int), void *arg)
66 {
67   /* Checking __linux__ isn't great but it isn't clear what would be
68      better.  There doesn't seem to be a good way to check for this in
69      configure.  */
70 #ifdef __linux__
71   DIR *dir;
72
73   dir = opendir ("/proc/self/fd");
74   if (dir != NULL)
75     {
76       struct dirent *entry;
77       int result = 0;
78
79       for (entry = readdir (dir); entry != NULL; entry = readdir (dir))
80         {
81           long fd;
82           char *tail;
83
84           errno = 0;
85           fd = strtol (entry->d_name, &tail, 10);
86           if (*tail != '\0' || errno != 0)
87             continue;
88           if ((int) fd != fd)
89             {
90               /* What can we do here really?  */
91               continue;
92             }
93
94           if (fd == dirfd (dir))
95             continue;
96
97           result = func (arg, fd);
98           if (result != 0)
99             break;
100         }
101
102       closedir (dir);
103       return result;
104     }
105   /* We may fall through to the next case.  */
106 #endif
107
108   {
109     int max, fd;
110
111 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
112     struct rlimit rlim;
113
114     if (getrlimit (RLIMIT_NOFILE, &rlim) == 0 && rlim.rlim_max != RLIM_INFINITY)
115       max = rlim.rlim_max;
116     else
117 #endif
118       {
119 #ifdef _SC_OPEN_MAX
120         max = sysconf (_SC_OPEN_MAX);
121 #else
122         /* Whoops.  */
123         return 0;
124 #endif /* _SC_OPEN_MAX */
125       }
126
127     for (fd = 0; fd < max; ++fd)
128       {
129         struct stat sb;
130         int result;
131
132         /* Only call FUNC for open fds.  */
133         if (fstat (fd, &sb) == -1)
134           continue;
135
136         result = func (arg, fd);
137         if (result != 0)
138           return result;
139       }
140
141     return 0;
142   }
143 }
144
145 #endif /* HAVE_FDWALK */
146
147 \f
148
149 /* A vector holding all the fds open when notice_open_fds was called.  We
150    don't use a hashtab because we don't expect there to be many open fds.  */
151
152 static std::vector<int> open_fds;
153
154 /* An fdwalk callback function used by notice_open_fds.  It puts the
155    given file descriptor into the vec.  */
156
157 static int
158 do_mark_open_fd (void *ignore, int fd)
159 {
160   open_fds.push_back (fd);
161   return 0;
162 }
163
164 /* See filestuff.h.  */
165
166 void
167 notice_open_fds (void)
168 {
169   fdwalk (do_mark_open_fd, NULL);
170 }
171
172 /* See filestuff.h.  */
173
174 void
175 mark_fd_no_cloexec (int fd)
176 {
177   do_mark_open_fd (NULL, fd);
178 }
179
180 /* See filestuff.h.  */
181
182 void
183 unmark_fd_no_cloexec (int fd)
184 {
185   auto it = std::remove (open_fds.begin (), open_fds.end (), fd);
186
187   if (it != open_fds.end ())
188     open_fds.erase (it);
189   else
190     gdb_assert_not_reached (_("fd not found in open_fds"));
191 }
192
193 /* Helper function for close_most_fds that closes the file descriptor
194    if appropriate.  */
195
196 static int
197 do_close (void *ignore, int fd)
198 {
199   for (int val : open_fds)
200     {
201       if (fd == val)
202         {
203           /* Keep this one open.  */
204           return 0;
205         }
206     }
207
208   close (fd);
209   return 0;
210 }
211
212 /* See filestuff.h.  */
213
214 void
215 close_most_fds (void)
216 {
217   fdwalk (do_close, NULL);
218 }
219
220 \f
221
222 /* This is a tri-state flag.  When zero it means we haven't yet tried
223    O_CLOEXEC.  When positive it means that O_CLOEXEC works on this
224    host.  When negative, it means that O_CLOEXEC doesn't work.  We
225    track this state because, while gdb might have been compiled
226    against a libc that supplies O_CLOEXEC, there is no guarantee that
227    the kernel supports it.  */
228
229 static int trust_o_cloexec;
230
231 /* Mark FD as close-on-exec, ignoring errors.  Update
232    TRUST_O_CLOEXEC.  */
233
234 static void
235 mark_cloexec (int fd)
236 {
237 #ifdef HAVE_F_GETFD
238   int old = fcntl (fd, F_GETFD, 0);
239
240   if (old != -1)
241     {
242       fcntl (fd, F_SETFD, old | FD_CLOEXEC);
243
244       if (trust_o_cloexec == 0)
245         {
246           if ((old & FD_CLOEXEC) != 0)
247             trust_o_cloexec = 1;
248           else
249             trust_o_cloexec = -1;
250         }
251     }
252 #endif /* HAVE_F_GETFD */
253 }
254
255 /* Depending on TRUST_O_CLOEXEC, mark FD as close-on-exec.  */
256
257 static void
258 maybe_mark_cloexec (int fd)
259 {
260   if (trust_o_cloexec <= 0)
261     mark_cloexec (fd);
262 }
263
264 #ifdef HAVE_SOCKETS
265
266 /* Like maybe_mark_cloexec, but for callers that use SOCK_CLOEXEC.  */
267
268 static void
269 socket_mark_cloexec (int fd)
270 {
271   if (SOCK_CLOEXEC == 0 || trust_o_cloexec <= 0)
272     mark_cloexec (fd);
273 }
274
275 #endif
276
277 \f
278
279 /* See filestuff.h.  */
280
281 int
282 gdb_open_cloexec (const char *filename, int flags, unsigned long mode)
283 {
284   int fd = open (filename, flags | O_CLOEXEC, mode);
285
286   if (fd >= 0)
287     maybe_mark_cloexec (fd);
288
289   return fd;
290 }
291
292 /* See filestuff.h.  */
293
294 gdb_file_up
295 gdb_fopen_cloexec (const char *filename, const char *opentype)
296 {
297   FILE *result;
298   /* Probe for "e" support once.  But, if we can tell the operating
299      system doesn't know about close on exec mode "e" without probing,
300      skip it.  E.g., the Windows runtime issues an "Invalid parameter
301      passed to C runtime function" OutputDebugString warning for
302      unknown modes.  Assume that if O_CLOEXEC is zero, then "e" isn't
303      supported.  On MinGW, O_CLOEXEC is an alias of O_NOINHERIT, and
304      "e" isn't supported.  */
305   static int fopen_e_ever_failed_einval =
306     O_CLOEXEC == 0 || O_CLOEXEC == O_NOINHERIT;
307
308   if (!fopen_e_ever_failed_einval)
309     {
310       char *copy;
311
312       copy = (char *) alloca (strlen (opentype) + 2);
313       strcpy (copy, opentype);
314       /* This is a glibc extension but we try it unconditionally on
315          this path.  */
316       strcat (copy, "e");
317       result = fopen (filename, copy);
318
319       if (result == NULL && errno == EINVAL)
320         {
321           result = fopen (filename, opentype);
322           if (result != NULL)
323             fopen_e_ever_failed_einval = 1;
324         }
325     }
326   else
327     result = fopen (filename, opentype);
328
329   if (result != NULL)
330     maybe_mark_cloexec (fileno (result));
331
332   return gdb_file_up (result);
333 }
334
335 #ifdef HAVE_SOCKETS
336 /* See filestuff.h.  */
337
338 int
339 gdb_socketpair_cloexec (int domain, int style, int protocol,
340                         int filedes[2])
341 {
342 #ifdef HAVE_SOCKETPAIR
343   int result = socketpair (domain, style | SOCK_CLOEXEC, protocol, filedes);
344
345   if (result != -1)
346     {
347       socket_mark_cloexec (filedes[0]);
348       socket_mark_cloexec (filedes[1]);
349     }
350
351   return result;
352 #else
353   gdb_assert_not_reached (_("socketpair not available on this host"));
354 #endif
355 }
356
357 /* See filestuff.h.  */
358
359 int
360 gdb_socket_cloexec (int domain, int style, int protocol)
361 {
362   int result = socket (domain, style | SOCK_CLOEXEC, protocol);
363
364   if (result != -1)
365     socket_mark_cloexec (result);
366
367   return result;
368 }
369 #endif
370
371 /* See filestuff.h.  */
372
373 int
374 gdb_pipe_cloexec (int filedes[2])
375 {
376   int result;
377
378 #ifdef HAVE_PIPE2
379   result = pipe2 (filedes, O_CLOEXEC);
380   if (result != -1)
381     {
382       maybe_mark_cloexec (filedes[0]);
383       maybe_mark_cloexec (filedes[1]);
384     }
385 #else
386 #ifdef HAVE_PIPE
387   result = pipe (filedes);
388   if (result != -1)
389     {
390       mark_cloexec (filedes[0]);
391       mark_cloexec (filedes[1]);
392     }
393 #else /* HAVE_PIPE */
394   gdb_assert_not_reached (_("pipe not available on this host"));
395 #endif /* HAVE_PIPE */
396 #endif /* HAVE_PIPE2 */
397
398   return result;
399 }
400
401 /* Helper function which does the work for make_cleanup_close.  */
402
403 static void
404 do_close_cleanup (void *arg)
405 {
406   int *fd = (int *) arg;
407
408   close (*fd);
409 }
410
411 /* See filestuff.h.  */
412
413 struct cleanup *
414 make_cleanup_close (int fd)
415 {
416   int *saved_fd = XNEW (int);
417
418   *saved_fd = fd;
419   return make_cleanup_dtor (do_close_cleanup, saved_fd, xfree);
420 }
421
422 /* See common/filestuff.h.  */
423
424 bool
425 is_regular_file (const char *name, int *errno_ptr)
426 {
427   struct stat st;
428   const int status = stat (name, &st);
429
430   /* Stat should never fail except when the file does not exist.
431      If stat fails, analyze the source of error and return true
432      unless the file does not exist, to avoid returning false results
433      on obscure systems where stat does not work as expected.  */
434
435   if (status != 0)
436     {
437       if (errno != ENOENT)
438         return true;
439       *errno_ptr = ENOENT;
440       return false;
441     }
442
443   if (S_ISREG (st.st_mode))
444     return true;
445
446   if (S_ISDIR (st.st_mode))
447     *errno_ptr = EISDIR;
448   else
449     *errno_ptr = EINVAL;
450   return false;
451 }
452
453 /* See common/filestuff.h.  */
454
455 bool
456 mkdir_recursive (const char *dir)
457 {
458   gdb::unique_xmalloc_ptr<char> holder (xstrdup (dir));
459   char * const start = holder.get ();
460   char *component_start = start;
461   char *component_end = start;
462
463   while (1)
464     {
465       /* Find the beginning of the next component.  */
466       while (*component_start == '/')
467         component_start++;
468
469       /* Are we done?  */
470       if (*component_start == '\0')
471         return true;
472
473       /* Find the slash or null-terminator after this component.  */
474       component_end = component_start;
475       while (*component_end != '/' && *component_end != '\0')
476         component_end++;
477
478       /* Temporarily replace the slash with a null terminator, so we can create
479          the directory up to this component.  */
480       char saved_char = *component_end;
481       *component_end = '\0';
482
483       /* If we get EEXIST and the existing path is a directory, then we're
484          happy.  If it exists, but it's a regular file and this is not the last
485          component, we'll fail at the next component.  If this is the last
486          component, the caller will fail with ENOTDIR when trying to
487          open/create a file under that path.  */
488       if (mkdir (start, 0700) != 0)
489         if (errno != EEXIST)
490           return false;
491
492       /* Restore the overwritten char.  */
493       *component_end = saved_char;
494       component_start = component_end;
495     }
496 }