1 /* Low-level file-handling.
2 Copyright (C) 2012-2024 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 "filestuff.h"
23 #include <sys/types.h>
30 #define HAVE_SOCKETS 1
31 #elif defined HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
33 /* Define HAVE_F_GETFD if we plan to use F_GETFD. */
34 #define HAVE_F_GETFD F_GETFD
35 #define HAVE_SOCKETS 1
38 #ifdef HAVE_KINFO_GETFILE
43 #ifdef HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif /* HAVE_SYS_RESOURCE_H */
56 #define SOCK_CLOEXEC 0
65 /* Replacement for fdwalk, if the system doesn't define it. Walks all
66 open file descriptors (though this implementation may walk closed
67 ones as well, depending on the host platform's capabilities) and
68 call FUNC with ARG. If FUNC returns non-zero, stops immediately
69 and returns the same value. Otherwise, returns zero when
73 fdwalk (int (*func
) (void *, int), void *arg
)
75 /* Checking __linux__ isn't great but it isn't clear what would be
76 better. There doesn't seem to be a good way to check for this in
81 dir
= opendir ("/proc/self/fd");
87 for (entry
= readdir (dir
); entry
!= NULL
; entry
= readdir (dir
))
93 fd
= strtol (entry
->d_name
, &tail
, 10);
94 if (*tail
!= '\0' || errno
!= 0)
98 /* What can we do here really? */
102 if (fd
== dirfd (dir
))
105 result
= func (arg
, fd
);
113 /* We may fall through to the next case. */
115 #ifdef HAVE_KINFO_GETFILE
117 gdb::unique_xmalloc_ptr
<struct kinfo_file
[]> fdtbl
118 (kinfo_getfile (getpid (), &nfd
));
121 for (int i
= 0; i
< nfd
; i
++)
123 if (fdtbl
[i
].kf_fd
>= 0)
125 int result
= func (arg
, fdtbl
[i
].kf_fd
);
132 /* We may fall through to the next case. */
138 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
141 if (getrlimit (RLIMIT_NOFILE
, &rlim
) == 0 && rlim
.rlim_max
!= RLIM_INFINITY
)
147 max
= sysconf (_SC_OPEN_MAX
);
151 #endif /* _SC_OPEN_MAX */
154 for (fd
= 0; fd
< max
; ++fd
)
159 /* Only call FUNC for open fds. */
160 if (fstat (fd
, &sb
) == -1)
163 result
= func (arg
, fd
);
172 #endif /* HAVE_FDWALK */
176 /* A vector holding all the fds open when notice_open_fds was called. We
177 don't use a hashtab because we don't expect there to be many open fds. */
179 static std::vector
<int> open_fds
;
181 /* An fdwalk callback function used by notice_open_fds. It puts the
182 given file descriptor into the vec. */
185 do_mark_open_fd (void *ignore
, int fd
)
187 open_fds
.push_back (fd
);
191 /* See filestuff.h. */
194 notice_open_fds (void)
196 fdwalk (do_mark_open_fd
, NULL
);
199 /* See filestuff.h. */
202 mark_fd_no_cloexec (int fd
)
204 do_mark_open_fd (NULL
, fd
);
207 /* See filestuff.h. */
210 unmark_fd_no_cloexec (int fd
)
212 auto it
= std::remove (open_fds
.begin (), open_fds
.end (), fd
);
214 if (it
!= open_fds
.end ())
217 gdb_assert_not_reached ("fd not found in open_fds");
220 /* Helper function for close_most_fds that closes the file descriptor
224 do_close (void *ignore
, int fd
)
226 for (int val
: open_fds
)
230 /* Keep this one open. */
239 /* See filestuff.h. */
242 close_most_fds (void)
244 fdwalk (do_close
, NULL
);
249 /* This is a tri-state flag. When zero it means we haven't yet tried
250 O_CLOEXEC. When positive it means that O_CLOEXEC works on this
251 host. When negative, it means that O_CLOEXEC doesn't work. We
252 track this state because, while gdb might have been compiled
253 against a libc that supplies O_CLOEXEC, there is no guarantee that
254 the kernel supports it. */
256 static int trust_o_cloexec
;
258 /* Mark FD as close-on-exec, ignoring errors. Update
262 mark_cloexec (int fd
)
265 int old
= fcntl (fd
, F_GETFD
, 0);
269 fcntl (fd
, F_SETFD
, old
| FD_CLOEXEC
);
271 if (trust_o_cloexec
== 0)
273 if ((old
& FD_CLOEXEC
) != 0)
276 trust_o_cloexec
= -1;
279 #endif /* HAVE_F_GETFD */
282 /* Depending on TRUST_O_CLOEXEC, mark FD as close-on-exec. */
285 maybe_mark_cloexec (int fd
)
287 if (trust_o_cloexec
<= 0)
293 /* Like maybe_mark_cloexec, but for callers that use SOCK_CLOEXEC. */
296 socket_mark_cloexec (int fd
)
298 if (SOCK_CLOEXEC
== 0 || trust_o_cloexec
<= 0)
306 /* See filestuff.h. */
309 gdb_open_cloexec (const char *filename
, int flags
, unsigned long mode
)
311 scoped_fd
fd (open (filename
, flags
| O_CLOEXEC
, mode
));
314 maybe_mark_cloexec (fd
.get ());
319 /* See filestuff.h. */
322 gdb_fopen_cloexec (const char *filename
, const char *opentype
)
325 /* Probe for "e" support once. But, if we can tell the operating
326 system doesn't know about close on exec mode "e" without probing,
327 skip it. E.g., the Windows runtime issues an "Invalid parameter
328 passed to C runtime function" OutputDebugString warning for
329 unknown modes. Assume that if O_CLOEXEC is zero, then "e" isn't
330 supported. On MinGW, O_CLOEXEC is an alias of O_NOINHERIT, and
331 "e" isn't supported. */
332 static int fopen_e_ever_failed_einval
=
333 O_CLOEXEC
== 0 || O_CLOEXEC
== O_NOINHERIT
;
335 if (!fopen_e_ever_failed_einval
)
339 copy
= (char *) alloca (strlen (opentype
) + 2);
340 strcpy (copy
, opentype
);
341 /* This is a glibc extension but we try it unconditionally on
344 result
= fopen (filename
, copy
);
346 if (result
== NULL
&& errno
== EINVAL
)
348 result
= fopen (filename
, opentype
);
350 fopen_e_ever_failed_einval
= 1;
354 result
= fopen (filename
, opentype
);
357 maybe_mark_cloexec (fileno (result
));
359 return gdb_file_up (result
);
363 /* See filestuff.h. */
366 gdb_socketpair_cloexec (int domain
, int style
, int protocol
,
369 #ifdef HAVE_SOCKETPAIR
370 int result
= socketpair (domain
, style
| SOCK_CLOEXEC
, protocol
, filedes
);
374 socket_mark_cloexec (filedes
[0]);
375 socket_mark_cloexec (filedes
[1]);
380 gdb_assert_not_reached ("socketpair not available on this host");
384 /* See filestuff.h. */
387 gdb_socket_cloexec (int domain
, int style
, int protocol
)
389 int result
= socket (domain
, style
| SOCK_CLOEXEC
, protocol
);
392 socket_mark_cloexec (result
);
398 /* See filestuff.h. */
401 gdb_pipe_cloexec (int filedes
[2])
406 result
= pipe2 (filedes
, O_CLOEXEC
);
409 maybe_mark_cloexec (filedes
[0]);
410 maybe_mark_cloexec (filedes
[1]);
414 result
= pipe (filedes
);
417 mark_cloexec (filedes
[0]);
418 mark_cloexec (filedes
[1]);
420 #else /* HAVE_PIPE */
421 gdb_assert_not_reached ("pipe not available on this host");
422 #endif /* HAVE_PIPE */
423 #endif /* HAVE_PIPE2 */
428 /* See gdbsupport/filestuff.h. */
431 is_regular_file (const char *name
, int *errno_ptr
)
434 const int status
= stat (name
, &st
);
436 /* Stat should never fail except when the file does not exist.
437 If stat fails, analyze the source of error and return true
438 unless the file does not exist, to avoid returning false results
439 on obscure systems where stat does not work as expected. */
449 if (S_ISREG (st
.st_mode
))
452 if (S_ISDIR (st
.st_mode
))
459 /* See gdbsupport/filestuff.h. */
462 mkdir_recursive (const char *dir
)
464 auto holder
= make_unique_xstrdup (dir
);
465 char * const start
= holder
.get ();
466 char *component_start
= start
;
467 char *component_end
= start
;
471 /* Find the beginning of the next component. */
472 while (*component_start
== '/')
476 if (*component_start
== '\0')
479 /* Find the slash or null-terminator after this component. */
480 component_end
= component_start
;
481 while (*component_end
!= '/' && *component_end
!= '\0')
484 /* Temporarily replace the slash with a null terminator, so we can create
485 the directory up to this component. */
486 char saved_char
= *component_end
;
487 *component_end
= '\0';
489 /* If we get EEXIST and the existing path is a directory, then we're
490 happy. If it exists, but it's a regular file and this is not the last
491 component, we'll fail at the next component. If this is the last
492 component, the caller will fail with ENOTDIR when trying to
493 open/create a file under that path. */
494 if (mkdir (start
, 0700) != 0)
498 /* Restore the overwritten char. */
499 *component_end
= saved_char
;
500 component_start
= component_end
;
504 /* See gdbsupport/filestuff.h. */
507 read_remainder_of_file (FILE *file
)
512 std::string::size_type start_size
= res
.size ();
513 constexpr int chunk_size
= 1024;
515 /* Resize to accommodate CHUNK_SIZE bytes. */
516 res
.resize (start_size
+ chunk_size
);
518 int n
= fread (&res
[start_size
], 1, chunk_size
, file
);
522 gdb_assert (n
< chunk_size
);
524 /* Less than CHUNK means EOF or error. If it's an error, return
529 /* Resize the string according to the data we read. */
530 res
.resize (start_size
+ n
);
537 /* See gdbsupport/filestuff.h. */
539 std::optional
<std::string
>
540 read_text_file_to_string (const char *path
)
542 gdb_file_up file
= gdb_fopen_cloexec (path
, "r");
546 return read_remainder_of_file (file
.get ());