[gdb/testsuite] Fix race in gdb.threads/detach-step-over.exp
[binutils-gdb.git] / gdbsupport / filestuff.cc
blobcf5fb13bd0c851fb52dbd2f1b29dad9fd7b881be
1 /* Low-level file-handling.
2 Copyright (C) 2012-2022 Free Software Foundation, Inc.
4 This file is part of GDB.
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.
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.
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/>. */
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>
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
39 #ifdef HAVE_KINFO_GETFILE
40 #include <sys/user.h>
41 #include <libutil.h>
42 #endif
44 #ifdef HAVE_SYS_RESOURCE_H
45 #include <sys/resource.h>
46 #endif /* HAVE_SYS_RESOURCE_H */
48 #ifndef O_CLOEXEC
49 #define O_CLOEXEC 0
50 #endif
52 #ifndef O_NOINHERIT
53 #define O_NOINHERIT 0
54 #endif
56 #ifndef SOCK_CLOEXEC
57 #define SOCK_CLOEXEC 0
58 #endif
62 #ifndef HAVE_FDWALK
64 #include <dirent.h>
66 /* Replacement for fdwalk, if the system doesn't define it. Walks all
67 open file descriptors (though this implementation may walk closed
68 ones as well, depending on the host platform's capabilities) and
69 call FUNC with ARG. If FUNC returns non-zero, stops immediately
70 and returns the same value. Otherwise, returns zero when
71 finished. */
73 static int
74 fdwalk (int (*func) (void *, int), void *arg)
76 /* Checking __linux__ isn't great but it isn't clear what would be
77 better. There doesn't seem to be a good way to check for this in
78 configure. */
79 #ifdef __linux__
80 DIR *dir;
82 dir = opendir ("/proc/self/fd");
83 if (dir != NULL)
85 struct dirent *entry;
86 int result = 0;
88 for (entry = readdir (dir); entry != NULL; entry = readdir (dir))
90 long fd;
91 char *tail;
93 errno = 0;
94 fd = strtol (entry->d_name, &tail, 10);
95 if (*tail != '\0' || errno != 0)
96 continue;
97 if ((int) fd != fd)
99 /* What can we do here really? */
100 continue;
103 if (fd == dirfd (dir))
104 continue;
106 result = func (arg, fd);
107 if (result != 0)
108 break;
111 closedir (dir);
112 return result;
114 /* We may fall through to the next case. */
115 #endif
116 #ifdef HAVE_KINFO_GETFILE
117 int nfd;
118 gdb::unique_xmalloc_ptr<struct kinfo_file[]> fdtbl
119 (kinfo_getfile (getpid (), &nfd));
120 if (fdtbl != NULL)
122 for (int i = 0; i < nfd; i++)
124 if (fdtbl[i].kf_fd >= 0)
126 int result = func (arg, fdtbl[i].kf_fd);
127 if (result != 0)
128 return result;
131 return 0;
133 /* We may fall through to the next case. */
134 #endif
137 int max, fd;
139 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
140 struct rlimit rlim;
142 if (getrlimit (RLIMIT_NOFILE, &rlim) == 0 && rlim.rlim_max != RLIM_INFINITY)
143 max = rlim.rlim_max;
144 else
145 #endif
147 #ifdef _SC_OPEN_MAX
148 max = sysconf (_SC_OPEN_MAX);
149 #else
150 /* Whoops. */
151 return 0;
152 #endif /* _SC_OPEN_MAX */
155 for (fd = 0; fd < max; ++fd)
157 struct stat sb;
158 int result;
160 /* Only call FUNC for open fds. */
161 if (fstat (fd, &sb) == -1)
162 continue;
164 result = func (arg, fd);
165 if (result != 0)
166 return result;
169 return 0;
173 #endif /* HAVE_FDWALK */
177 /* A vector holding all the fds open when notice_open_fds was called. We
178 don't use a hashtab because we don't expect there to be many open fds. */
180 static std::vector<int> open_fds;
182 /* An fdwalk callback function used by notice_open_fds. It puts the
183 given file descriptor into the vec. */
185 static int
186 do_mark_open_fd (void *ignore, int fd)
188 open_fds.push_back (fd);
189 return 0;
192 /* See filestuff.h. */
194 void
195 notice_open_fds (void)
197 fdwalk (do_mark_open_fd, NULL);
200 /* See filestuff.h. */
202 void
203 mark_fd_no_cloexec (int fd)
205 do_mark_open_fd (NULL, fd);
208 /* See filestuff.h. */
210 void
211 unmark_fd_no_cloexec (int fd)
213 auto it = std::remove (open_fds.begin (), open_fds.end (), fd);
215 if (it != open_fds.end ())
216 open_fds.erase (it);
217 else
218 gdb_assert_not_reached ("fd not found in open_fds");
221 /* Helper function for close_most_fds that closes the file descriptor
222 if appropriate. */
224 static int
225 do_close (void *ignore, int fd)
227 for (int val : open_fds)
229 if (fd == val)
231 /* Keep this one open. */
232 return 0;
236 close (fd);
237 return 0;
240 /* See filestuff.h. */
242 void
243 close_most_fds (void)
245 fdwalk (do_close, NULL);
250 /* This is a tri-state flag. When zero it means we haven't yet tried
251 O_CLOEXEC. When positive it means that O_CLOEXEC works on this
252 host. When negative, it means that O_CLOEXEC doesn't work. We
253 track this state because, while gdb might have been compiled
254 against a libc that supplies O_CLOEXEC, there is no guarantee that
255 the kernel supports it. */
257 static int trust_o_cloexec;
259 /* Mark FD as close-on-exec, ignoring errors. Update
260 TRUST_O_CLOEXEC. */
262 static void
263 mark_cloexec (int fd)
265 #ifdef HAVE_F_GETFD
266 int old = fcntl (fd, F_GETFD, 0);
268 if (old != -1)
270 fcntl (fd, F_SETFD, old | FD_CLOEXEC);
272 if (trust_o_cloexec == 0)
274 if ((old & FD_CLOEXEC) != 0)
275 trust_o_cloexec = 1;
276 else
277 trust_o_cloexec = -1;
280 #endif /* HAVE_F_GETFD */
283 /* Depending on TRUST_O_CLOEXEC, mark FD as close-on-exec. */
285 static void
286 maybe_mark_cloexec (int fd)
288 if (trust_o_cloexec <= 0)
289 mark_cloexec (fd);
292 #ifdef HAVE_SOCKETS
294 /* Like maybe_mark_cloexec, but for callers that use SOCK_CLOEXEC. */
296 static void
297 socket_mark_cloexec (int fd)
299 if (SOCK_CLOEXEC == 0 || trust_o_cloexec <= 0)
300 mark_cloexec (fd);
303 #endif
307 /* See filestuff.h. */
309 scoped_fd
310 gdb_open_cloexec (const char *filename, int flags, unsigned long mode)
312 scoped_fd fd (open (filename, flags | O_CLOEXEC, mode));
314 if (fd.get () >= 0)
315 maybe_mark_cloexec (fd.get ());
317 return fd;
320 /* See filestuff.h. */
322 gdb_file_up
323 gdb_fopen_cloexec (const char *filename, const char *opentype)
325 FILE *result;
326 /* Probe for "e" support once. But, if we can tell the operating
327 system doesn't know about close on exec mode "e" without probing,
328 skip it. E.g., the Windows runtime issues an "Invalid parameter
329 passed to C runtime function" OutputDebugString warning for
330 unknown modes. Assume that if O_CLOEXEC is zero, then "e" isn't
331 supported. On MinGW, O_CLOEXEC is an alias of O_NOINHERIT, and
332 "e" isn't supported. */
333 static int fopen_e_ever_failed_einval =
334 O_CLOEXEC == 0 || O_CLOEXEC == O_NOINHERIT;
336 if (!fopen_e_ever_failed_einval)
338 char *copy;
340 copy = (char *) alloca (strlen (opentype) + 2);
341 strcpy (copy, opentype);
342 /* This is a glibc extension but we try it unconditionally on
343 this path. */
344 strcat (copy, "e");
345 result = fopen (filename, copy);
347 if (result == NULL && errno == EINVAL)
349 result = fopen (filename, opentype);
350 if (result != NULL)
351 fopen_e_ever_failed_einval = 1;
354 else
355 result = fopen (filename, opentype);
357 if (result != NULL)
358 maybe_mark_cloexec (fileno (result));
360 return gdb_file_up (result);
363 #ifdef HAVE_SOCKETS
364 /* See filestuff.h. */
367 gdb_socketpair_cloexec (int domain, int style, int protocol,
368 int filedes[2])
370 #ifdef HAVE_SOCKETPAIR
371 int result = socketpair (domain, style | SOCK_CLOEXEC, protocol, filedes);
373 if (result != -1)
375 socket_mark_cloexec (filedes[0]);
376 socket_mark_cloexec (filedes[1]);
379 return result;
380 #else
381 gdb_assert_not_reached ("socketpair not available on this host");
382 #endif
385 /* See filestuff.h. */
388 gdb_socket_cloexec (int domain, int style, int protocol)
390 int result = socket (domain, style | SOCK_CLOEXEC, protocol);
392 if (result != -1)
393 socket_mark_cloexec (result);
395 return result;
397 #endif
399 /* See filestuff.h. */
402 gdb_pipe_cloexec (int filedes[2])
404 int result;
406 #ifdef HAVE_PIPE2
407 result = pipe2 (filedes, O_CLOEXEC);
408 if (result != -1)
410 maybe_mark_cloexec (filedes[0]);
411 maybe_mark_cloexec (filedes[1]);
413 #else
414 #ifdef HAVE_PIPE
415 result = pipe (filedes);
416 if (result != -1)
418 mark_cloexec (filedes[0]);
419 mark_cloexec (filedes[1]);
421 #else /* HAVE_PIPE */
422 gdb_assert_not_reached ("pipe not available on this host");
423 #endif /* HAVE_PIPE */
424 #endif /* HAVE_PIPE2 */
426 return result;
429 /* See gdbsupport/filestuff.h. */
431 bool
432 is_regular_file (const char *name, int *errno_ptr)
434 struct stat st;
435 const int status = stat (name, &st);
437 /* Stat should never fail except when the file does not exist.
438 If stat fails, analyze the source of error and return true
439 unless the file does not exist, to avoid returning false results
440 on obscure systems where stat does not work as expected. */
442 if (status != 0)
444 if (errno != ENOENT)
445 return true;
446 *errno_ptr = ENOENT;
447 return false;
450 if (S_ISREG (st.st_mode))
451 return true;
453 if (S_ISDIR (st.st_mode))
454 *errno_ptr = EISDIR;
455 else
456 *errno_ptr = EINVAL;
457 return false;
460 /* See gdbsupport/filestuff.h. */
462 bool
463 mkdir_recursive (const char *dir)
465 auto holder = make_unique_xstrdup (dir);
466 char * const start = holder.get ();
467 char *component_start = start;
468 char *component_end = start;
470 while (1)
472 /* Find the beginning of the next component. */
473 while (*component_start == '/')
474 component_start++;
476 /* Are we done? */
477 if (*component_start == '\0')
478 return true;
480 /* Find the slash or null-terminator after this component. */
481 component_end = component_start;
482 while (*component_end != '/' && *component_end != '\0')
483 component_end++;
485 /* Temporarily replace the slash with a null terminator, so we can create
486 the directory up to this component. */
487 char saved_char = *component_end;
488 *component_end = '\0';
490 /* If we get EEXIST and the existing path is a directory, then we're
491 happy. If it exists, but it's a regular file and this is not the last
492 component, we'll fail at the next component. If this is the last
493 component, the caller will fail with ENOTDIR when trying to
494 open/create a file under that path. */
495 if (mkdir (start, 0700) != 0)
496 if (errno != EEXIST)
497 return false;
499 /* Restore the overwritten char. */
500 *component_end = saved_char;
501 component_start = component_end;
505 /* See gdbsupport/filestuff.h. */
507 gdb::optional<std::string>
508 read_text_file_to_string (const char *path)
510 gdb_file_up file = gdb_fopen_cloexec (path, "r");
511 if (file == nullptr)
512 return {};
514 std::string res;
515 for (;;)
517 std::string::size_type start_size = res.size ();
518 constexpr int chunk_size = 1024;
520 /* Resize to accomodate CHUNK_SIZE bytes. */
521 res.resize (start_size + chunk_size);
523 int n = fread (&res[start_size], 1, chunk_size, file.get ());
524 if (n == chunk_size)
525 continue;
527 gdb_assert (n < chunk_size);
529 /* Less than CHUNK means EOF or error. If it's an error, return
530 no value. */
531 if (ferror (file.get ()))
532 return {};
534 /* Resize the string according to the data we read. */
535 res.resize (start_size + n);
536 break;
539 return res;