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"
24 #include <sys/types.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
39 #ifdef HAVE_KINFO_GETFILE
44 #ifdef HAVE_SYS_RESOURCE_H
45 #include <sys/resource.h>
46 #endif /* HAVE_SYS_RESOURCE_H */
57 #define SOCK_CLOEXEC 0
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
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
82 dir
= opendir ("/proc/self/fd");
88 for (entry
= readdir (dir
); entry
!= NULL
; entry
= readdir (dir
))
94 fd
= strtol (entry
->d_name
, &tail
, 10);
95 if (*tail
!= '\0' || errno
!= 0)
99 /* What can we do here really? */
103 if (fd
== dirfd (dir
))
106 result
= func (arg
, fd
);
114 /* We may fall through to the next case. */
116 #ifdef HAVE_KINFO_GETFILE
118 gdb::unique_xmalloc_ptr
<struct kinfo_file
[]> fdtbl
119 (kinfo_getfile (getpid (), &nfd
));
122 for (int i
= 0; i
< nfd
; i
++)
124 if (fdtbl
[i
].kf_fd
>= 0)
126 int result
= func (arg
, fdtbl
[i
].kf_fd
);
133 /* We may fall through to the next case. */
139 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
142 if (getrlimit (RLIMIT_NOFILE
, &rlim
) == 0 && rlim
.rlim_max
!= RLIM_INFINITY
)
148 max
= sysconf (_SC_OPEN_MAX
);
152 #endif /* _SC_OPEN_MAX */
155 for (fd
= 0; fd
< max
; ++fd
)
160 /* Only call FUNC for open fds. */
161 if (fstat (fd
, &sb
) == -1)
164 result
= func (arg
, fd
);
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. */
186 do_mark_open_fd (void *ignore
, int fd
)
188 open_fds
.push_back (fd
);
192 /* See filestuff.h. */
195 notice_open_fds (void)
197 fdwalk (do_mark_open_fd
, NULL
);
200 /* See filestuff.h. */
203 mark_fd_no_cloexec (int fd
)
205 do_mark_open_fd (NULL
, fd
);
208 /* See filestuff.h. */
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 ())
218 gdb_assert_not_reached ("fd not found in open_fds");
221 /* Helper function for close_most_fds that closes the file descriptor
225 do_close (void *ignore
, int fd
)
227 for (int val
: open_fds
)
231 /* Keep this one open. */
240 /* See filestuff.h. */
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
263 mark_cloexec (int fd
)
266 int old
= fcntl (fd
, F_GETFD
, 0);
270 fcntl (fd
, F_SETFD
, old
| FD_CLOEXEC
);
272 if (trust_o_cloexec
== 0)
274 if ((old
& FD_CLOEXEC
) != 0)
277 trust_o_cloexec
= -1;
280 #endif /* HAVE_F_GETFD */
283 /* Depending on TRUST_O_CLOEXEC, mark FD as close-on-exec. */
286 maybe_mark_cloexec (int fd
)
288 if (trust_o_cloexec
<= 0)
294 /* Like maybe_mark_cloexec, but for callers that use SOCK_CLOEXEC. */
297 socket_mark_cloexec (int fd
)
299 if (SOCK_CLOEXEC
== 0 || trust_o_cloexec
<= 0)
307 /* See filestuff.h. */
310 gdb_open_cloexec (const char *filename
, int flags
, unsigned long mode
)
312 scoped_fd
fd (open (filename
, flags
| O_CLOEXEC
, mode
));
315 maybe_mark_cloexec (fd
.get ());
320 /* See filestuff.h. */
323 gdb_fopen_cloexec (const char *filename
, const char *opentype
)
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
)
340 copy
= (char *) alloca (strlen (opentype
) + 2);
341 strcpy (copy
, opentype
);
342 /* This is a glibc extension but we try it unconditionally on
345 result
= fopen (filename
, copy
);
347 if (result
== NULL
&& errno
== EINVAL
)
349 result
= fopen (filename
, opentype
);
351 fopen_e_ever_failed_einval
= 1;
355 result
= fopen (filename
, opentype
);
358 maybe_mark_cloexec (fileno (result
));
360 return gdb_file_up (result
);
364 /* See filestuff.h. */
367 gdb_socketpair_cloexec (int domain
, int style
, int protocol
,
370 #ifdef HAVE_SOCKETPAIR
371 int result
= socketpair (domain
, style
| SOCK_CLOEXEC
, protocol
, filedes
);
375 socket_mark_cloexec (filedes
[0]);
376 socket_mark_cloexec (filedes
[1]);
381 gdb_assert_not_reached ("socketpair not available on this host");
385 /* See filestuff.h. */
388 gdb_socket_cloexec (int domain
, int style
, int protocol
)
390 int result
= socket (domain
, style
| SOCK_CLOEXEC
, protocol
);
393 socket_mark_cloexec (result
);
399 /* See filestuff.h. */
402 gdb_pipe_cloexec (int filedes
[2])
407 result
= pipe2 (filedes
, O_CLOEXEC
);
410 maybe_mark_cloexec (filedes
[0]);
411 maybe_mark_cloexec (filedes
[1]);
415 result
= pipe (filedes
);
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 */
429 /* See gdbsupport/filestuff.h. */
432 is_regular_file (const char *name
, int *errno_ptr
)
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. */
450 if (S_ISREG (st
.st_mode
))
453 if (S_ISDIR (st
.st_mode
))
460 /* See gdbsupport/filestuff.h. */
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
;
472 /* Find the beginning of the next component. */
473 while (*component_start
== '/')
477 if (*component_start
== '\0')
480 /* Find the slash or null-terminator after this component. */
481 component_end
= component_start
;
482 while (*component_end
!= '/' && *component_end
!= '\0')
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)
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");
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 ());
527 gdb_assert (n
< chunk_size
);
529 /* Less than CHUNK means EOF or error. If it's an error, return
531 if (ferror (file
.get ()))
534 /* Resize the string according to the data we read. */
535 res
.resize (start_size
+ n
);