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"
22 #include <sys/types.h>
29 #define HAVE_SOCKETS 1
30 #elif defined HAVE_SYS_SOCKET_H
31 #include <sys/socket.h>
32 /* Define HAVE_F_GETFD if we plan to use F_GETFD. */
33 #define HAVE_F_GETFD F_GETFD
34 #define HAVE_SOCKETS 1
37 #ifdef HAVE_KINFO_GETFILE
42 #ifdef HAVE_SYS_RESOURCE_H
43 #include <sys/resource.h>
44 #endif /* HAVE_SYS_RESOURCE_H */
55 #define SOCK_CLOEXEC 0
64 /* Replacement for fdwalk, if the system doesn't define it. Walks all
65 open file descriptors (though this implementation may walk closed
66 ones as well, depending on the host platform's capabilities) and
67 call FUNC with ARG. If FUNC returns non-zero, stops immediately
68 and returns the same value. Otherwise, returns zero when
72 fdwalk (int (*func
) (void *, int), void *arg
)
74 /* Checking __linux__ isn't great but it isn't clear what would be
75 better. There doesn't seem to be a good way to check for this in
80 dir
= opendir ("/proc/self/fd");
86 for (entry
= readdir (dir
); entry
!= NULL
; entry
= readdir (dir
))
92 fd
= strtol (entry
->d_name
, &tail
, 10);
93 if (*tail
!= '\0' || errno
!= 0)
97 /* What can we do here really? */
101 if (fd
== dirfd (dir
))
104 result
= func (arg
, fd
);
112 /* We may fall through to the next case. */
114 #ifdef HAVE_KINFO_GETFILE
116 gdb::unique_xmalloc_ptr
<struct kinfo_file
[]> fdtbl
117 (kinfo_getfile (getpid (), &nfd
));
120 for (int i
= 0; i
< nfd
; i
++)
122 if (fdtbl
[i
].kf_fd
>= 0)
124 int result
= func (arg
, fdtbl
[i
].kf_fd
);
131 /* We may fall through to the next case. */
137 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
140 if (getrlimit (RLIMIT_NOFILE
, &rlim
) == 0 && rlim
.rlim_max
!= RLIM_INFINITY
)
146 max
= sysconf (_SC_OPEN_MAX
);
150 #endif /* _SC_OPEN_MAX */
153 for (fd
= 0; fd
< max
; ++fd
)
158 /* Only call FUNC for open fds. */
159 if (fstat (fd
, &sb
) == -1)
162 result
= func (arg
, fd
);
171 #endif /* HAVE_FDWALK */
175 /* A vector holding all the fds open when notice_open_fds was called. We
176 don't use a hashtab because we don't expect there to be many open fds. */
178 static std::vector
<int> open_fds
;
180 /* An fdwalk callback function used by notice_open_fds. It puts the
181 given file descriptor into the vec. */
184 do_mark_open_fd (void *ignore
, int fd
)
186 open_fds
.push_back (fd
);
190 /* See filestuff.h. */
193 notice_open_fds (void)
195 fdwalk (do_mark_open_fd
, NULL
);
198 /* See filestuff.h. */
201 mark_fd_no_cloexec (int fd
)
203 do_mark_open_fd (NULL
, fd
);
206 /* See filestuff.h. */
209 unmark_fd_no_cloexec (int fd
)
211 auto it
= std::remove (open_fds
.begin (), open_fds
.end (), fd
);
213 if (it
!= open_fds
.end ())
216 gdb_assert_not_reached ("fd not found in open_fds");
219 /* Helper function for close_most_fds that closes the file descriptor
223 do_close (void *ignore
, int fd
)
225 for (int val
: open_fds
)
229 /* Keep this one open. */
238 /* See filestuff.h. */
241 close_most_fds (void)
243 fdwalk (do_close
, NULL
);
248 /* This is a tri-state flag. When zero it means we haven't yet tried
249 O_CLOEXEC. When positive it means that O_CLOEXEC works on this
250 host. When negative, it means that O_CLOEXEC doesn't work. We
251 track this state because, while gdb might have been compiled
252 against a libc that supplies O_CLOEXEC, there is no guarantee that
253 the kernel supports it. */
255 static int trust_o_cloexec
;
257 /* Mark FD as close-on-exec, ignoring errors. Update
261 mark_cloexec (int fd
)
264 int old
= fcntl (fd
, F_GETFD
, 0);
268 fcntl (fd
, F_SETFD
, old
| FD_CLOEXEC
);
270 if (trust_o_cloexec
== 0)
272 if ((old
& FD_CLOEXEC
) != 0)
275 trust_o_cloexec
= -1;
278 #endif /* HAVE_F_GETFD */
281 /* Depending on TRUST_O_CLOEXEC, mark FD as close-on-exec. */
284 maybe_mark_cloexec (int fd
)
286 if (trust_o_cloexec
<= 0)
292 /* Like maybe_mark_cloexec, but for callers that use SOCK_CLOEXEC. */
295 socket_mark_cloexec (int fd
)
297 if (SOCK_CLOEXEC
== 0 || trust_o_cloexec
<= 0)
305 /* See filestuff.h. */
308 gdb_open_cloexec (const char *filename
, int flags
, unsigned long mode
)
310 scoped_fd
fd (open (filename
, flags
| O_CLOEXEC
, mode
));
313 maybe_mark_cloexec (fd
.get ());
318 /* See filestuff.h. */
321 gdb_fopen_cloexec (const char *filename
, const char *opentype
)
324 /* Probe for "e" support once. But, if we can tell the operating
325 system doesn't know about close on exec mode "e" without probing,
326 skip it. E.g., the Windows runtime issues an "Invalid parameter
327 passed to C runtime function" OutputDebugString warning for
328 unknown modes. Assume that if O_CLOEXEC is zero, then "e" isn't
329 supported. On MinGW, O_CLOEXEC is an alias of O_NOINHERIT, and
330 "e" isn't supported. */
331 static int fopen_e_ever_failed_einval
=
332 O_CLOEXEC
== 0 || O_CLOEXEC
== O_NOINHERIT
;
334 if (!fopen_e_ever_failed_einval
)
338 copy
= (char *) alloca (strlen (opentype
) + 2);
339 strcpy (copy
, opentype
);
340 /* This is a glibc extension but we try it unconditionally on
343 result
= fopen (filename
, copy
);
345 if (result
== NULL
&& errno
== EINVAL
)
347 result
= fopen (filename
, opentype
);
349 fopen_e_ever_failed_einval
= 1;
353 result
= fopen (filename
, opentype
);
356 maybe_mark_cloexec (fileno (result
));
358 return gdb_file_up (result
);
362 /* See filestuff.h. */
365 gdb_socketpair_cloexec (int domain
, int style
, int protocol
,
368 #ifdef HAVE_SOCKETPAIR
369 int result
= socketpair (domain
, style
| SOCK_CLOEXEC
, protocol
, filedes
);
373 socket_mark_cloexec (filedes
[0]);
374 socket_mark_cloexec (filedes
[1]);
379 gdb_assert_not_reached ("socketpair not available on this host");
383 /* See filestuff.h. */
386 gdb_socket_cloexec (int domain
, int style
, int protocol
)
388 int result
= socket (domain
, style
| SOCK_CLOEXEC
, protocol
);
391 socket_mark_cloexec (result
);
397 /* See filestuff.h. */
400 gdb_pipe_cloexec (int filedes
[2])
405 result
= pipe2 (filedes
, O_CLOEXEC
);
408 maybe_mark_cloexec (filedes
[0]);
409 maybe_mark_cloexec (filedes
[1]);
413 result
= pipe (filedes
);
416 mark_cloexec (filedes
[0]);
417 mark_cloexec (filedes
[1]);
419 #else /* HAVE_PIPE */
420 gdb_assert_not_reached ("pipe not available on this host");
421 #endif /* HAVE_PIPE */
422 #endif /* HAVE_PIPE2 */
427 /* See gdbsupport/filestuff.h. */
430 is_regular_file (const char *name
, int *errno_ptr
)
433 const int status
= stat (name
, &st
);
435 /* Stat should never fail except when the file does not exist.
436 If stat fails, analyze the source of error and return true
437 unless the file does not exist, to avoid returning false results
438 on obscure systems where stat does not work as expected. */
448 if (S_ISREG (st
.st_mode
))
451 if (S_ISDIR (st
.st_mode
))
458 /* See gdbsupport/filestuff.h. */
461 mkdir_recursive (const char *dir
)
463 auto holder
= make_unique_xstrdup (dir
);
464 char * const start
= holder
.get ();
465 char *component_start
= start
;
466 char *component_end
= start
;
470 /* Find the beginning of the next component. */
471 while (*component_start
== '/')
475 if (*component_start
== '\0')
478 /* Find the slash or null-terminator after this component. */
479 component_end
= component_start
;
480 while (*component_end
!= '/' && *component_end
!= '\0')
483 /* Temporarily replace the slash with a null terminator, so we can create
484 the directory up to this component. */
485 char saved_char
= *component_end
;
486 *component_end
= '\0';
488 /* If we get EEXIST and the existing path is a directory, then we're
489 happy. If it exists, but it's a regular file and this is not the last
490 component, we'll fail at the next component. If this is the last
491 component, the caller will fail with ENOTDIR when trying to
492 open/create a file under that path. */
493 if (mkdir (start
, 0700) != 0)
497 /* Restore the overwritten char. */
498 *component_end
= saved_char
;
499 component_start
= component_end
;
503 /* See gdbsupport/filestuff.h. */
506 read_remainder_of_file (FILE *file
)
511 std::string::size_type start_size
= res
.size ();
512 constexpr int chunk_size
= 1024;
514 /* Resize to accommodate CHUNK_SIZE bytes. */
515 res
.resize (start_size
+ chunk_size
);
517 int n
= fread (&res
[start_size
], 1, chunk_size
, file
);
521 gdb_assert (n
< chunk_size
);
523 /* Less than CHUNK means EOF or error. If it's an error, return
528 /* Resize the string according to the data we read. */
529 res
.resize (start_size
+ n
);
536 /* See gdbsupport/filestuff.h. */
538 std::optional
<std::string
>
539 read_text_file_to_string (const char *path
)
541 gdb_file_up file
= gdb_fopen_cloexec (path
, "r");
545 return read_remainder_of_file (file
.get ());