Add translations for various sub-directories
[binutils-gdb.git] / gdbsupport / filestuff.cc
blob9e07af28dc2db5975776763376d567c51de6376c
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"
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <algorithm>
26 #ifdef USE_WIN32API
27 #include <winsock2.h>
28 #include <windows.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
35 #endif
37 #ifdef HAVE_KINFO_GETFILE
38 #include <sys/user.h>
39 #include <libutil.h>
40 #endif
42 #ifdef HAVE_SYS_RESOURCE_H
43 #include <sys/resource.h>
44 #endif /* HAVE_SYS_RESOURCE_H */
46 #ifndef O_CLOEXEC
47 #define O_CLOEXEC 0
48 #endif
50 #ifndef O_NOINHERIT
51 #define O_NOINHERIT 0
52 #endif
54 #ifndef SOCK_CLOEXEC
55 #define SOCK_CLOEXEC 0
56 #endif
60 #ifndef HAVE_FDWALK
62 #include <dirent.h>
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
69 finished. */
71 static int
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
76 configure. */
77 #ifdef __linux__
78 DIR *dir;
80 dir = opendir ("/proc/self/fd");
81 if (dir != NULL)
83 struct dirent *entry;
84 int result = 0;
86 for (entry = readdir (dir); entry != NULL; entry = readdir (dir))
88 long fd;
89 char *tail;
91 errno = 0;
92 fd = strtol (entry->d_name, &tail, 10);
93 if (*tail != '\0' || errno != 0)
94 continue;
95 if ((int) fd != fd)
97 /* What can we do here really? */
98 continue;
101 if (fd == dirfd (dir))
102 continue;
104 result = func (arg, fd);
105 if (result != 0)
106 break;
109 closedir (dir);
110 return result;
112 /* We may fall through to the next case. */
113 #endif
114 #ifdef HAVE_KINFO_GETFILE
115 int nfd;
116 gdb::unique_xmalloc_ptr<struct kinfo_file[]> fdtbl
117 (kinfo_getfile (getpid (), &nfd));
118 if (fdtbl != NULL)
120 for (int i = 0; i < nfd; i++)
122 if (fdtbl[i].kf_fd >= 0)
124 int result = func (arg, fdtbl[i].kf_fd);
125 if (result != 0)
126 return result;
129 return 0;
131 /* We may fall through to the next case. */
132 #endif
135 int max, fd;
137 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
138 struct rlimit rlim;
140 if (getrlimit (RLIMIT_NOFILE, &rlim) == 0 && rlim.rlim_max != RLIM_INFINITY)
141 max = rlim.rlim_max;
142 else
143 #endif
145 #ifdef _SC_OPEN_MAX
146 max = sysconf (_SC_OPEN_MAX);
147 #else
148 /* Whoops. */
149 return 0;
150 #endif /* _SC_OPEN_MAX */
153 for (fd = 0; fd < max; ++fd)
155 struct stat sb;
156 int result;
158 /* Only call FUNC for open fds. */
159 if (fstat (fd, &sb) == -1)
160 continue;
162 result = func (arg, fd);
163 if (result != 0)
164 return result;
167 return 0;
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. */
183 static int
184 do_mark_open_fd (void *ignore, int fd)
186 open_fds.push_back (fd);
187 return 0;
190 /* See filestuff.h. */
192 void
193 notice_open_fds (void)
195 fdwalk (do_mark_open_fd, NULL);
198 /* See filestuff.h. */
200 void
201 mark_fd_no_cloexec (int fd)
203 do_mark_open_fd (NULL, fd);
206 /* See filestuff.h. */
208 void
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 ())
214 open_fds.erase (it);
215 else
216 gdb_assert_not_reached ("fd not found in open_fds");
219 /* Helper function for close_most_fds that closes the file descriptor
220 if appropriate. */
222 static int
223 do_close (void *ignore, int fd)
225 for (int val : open_fds)
227 if (fd == val)
229 /* Keep this one open. */
230 return 0;
234 close (fd);
235 return 0;
238 /* See filestuff.h. */
240 void
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
258 TRUST_O_CLOEXEC. */
260 static void
261 mark_cloexec (int fd)
263 #ifdef HAVE_F_GETFD
264 int old = fcntl (fd, F_GETFD, 0);
266 if (old != -1)
268 fcntl (fd, F_SETFD, old | FD_CLOEXEC);
270 if (trust_o_cloexec == 0)
272 if ((old & FD_CLOEXEC) != 0)
273 trust_o_cloexec = 1;
274 else
275 trust_o_cloexec = -1;
278 #endif /* HAVE_F_GETFD */
281 /* Depending on TRUST_O_CLOEXEC, mark FD as close-on-exec. */
283 static void
284 maybe_mark_cloexec (int fd)
286 if (trust_o_cloexec <= 0)
287 mark_cloexec (fd);
290 #ifdef HAVE_SOCKETS
292 /* Like maybe_mark_cloexec, but for callers that use SOCK_CLOEXEC. */
294 static void
295 socket_mark_cloexec (int fd)
297 if (SOCK_CLOEXEC == 0 || trust_o_cloexec <= 0)
298 mark_cloexec (fd);
301 #endif
305 /* See filestuff.h. */
307 scoped_fd
308 gdb_open_cloexec (const char *filename, int flags, unsigned long mode)
310 scoped_fd fd (open (filename, flags | O_CLOEXEC, mode));
312 if (fd.get () >= 0)
313 maybe_mark_cloexec (fd.get ());
315 return fd;
318 /* See filestuff.h. */
320 gdb_file_up
321 gdb_fopen_cloexec (const char *filename, const char *opentype)
323 FILE *result;
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)
336 char *copy;
338 copy = (char *) alloca (strlen (opentype) + 2);
339 strcpy (copy, opentype);
340 /* This is a glibc extension but we try it unconditionally on
341 this path. */
342 strcat (copy, "e");
343 result = fopen (filename, copy);
345 if (result == NULL && errno == EINVAL)
347 result = fopen (filename, opentype);
348 if (result != NULL)
349 fopen_e_ever_failed_einval = 1;
352 else
353 result = fopen (filename, opentype);
355 if (result != NULL)
356 maybe_mark_cloexec (fileno (result));
358 return gdb_file_up (result);
361 #ifdef HAVE_SOCKETS
362 /* See filestuff.h. */
365 gdb_socketpair_cloexec (int domain, int style, int protocol,
366 int filedes[2])
368 #ifdef HAVE_SOCKETPAIR
369 int result = socketpair (domain, style | SOCK_CLOEXEC, protocol, filedes);
371 if (result != -1)
373 socket_mark_cloexec (filedes[0]);
374 socket_mark_cloexec (filedes[1]);
377 return result;
378 #else
379 gdb_assert_not_reached ("socketpair not available on this host");
380 #endif
383 /* See filestuff.h. */
386 gdb_socket_cloexec (int domain, int style, int protocol)
388 int result = socket (domain, style | SOCK_CLOEXEC, protocol);
390 if (result != -1)
391 socket_mark_cloexec (result);
393 return result;
395 #endif
397 /* See filestuff.h. */
400 gdb_pipe_cloexec (int filedes[2])
402 int result;
404 #ifdef HAVE_PIPE2
405 result = pipe2 (filedes, O_CLOEXEC);
406 if (result != -1)
408 maybe_mark_cloexec (filedes[0]);
409 maybe_mark_cloexec (filedes[1]);
411 #else
412 #ifdef HAVE_PIPE
413 result = pipe (filedes);
414 if (result != -1)
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 */
424 return result;
427 /* See gdbsupport/filestuff.h. */
429 bool
430 is_regular_file (const char *name, int *errno_ptr)
432 struct stat st;
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. */
440 if (status != 0)
442 if (errno != ENOENT)
443 return true;
444 *errno_ptr = ENOENT;
445 return false;
448 if (S_ISREG (st.st_mode))
449 return true;
451 if (S_ISDIR (st.st_mode))
452 *errno_ptr = EISDIR;
453 else
454 *errno_ptr = EINVAL;
455 return false;
458 /* See gdbsupport/filestuff.h. */
460 bool
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;
468 while (1)
470 /* Find the beginning of the next component. */
471 while (*component_start == '/')
472 component_start++;
474 /* Are we done? */
475 if (*component_start == '\0')
476 return true;
478 /* Find the slash or null-terminator after this component. */
479 component_end = component_start;
480 while (*component_end != '/' && *component_end != '\0')
481 component_end++;
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)
494 if (errno != EEXIST)
495 return false;
497 /* Restore the overwritten char. */
498 *component_end = saved_char;
499 component_start = component_end;
503 /* See gdbsupport/filestuff.h. */
505 std::string
506 read_remainder_of_file (FILE *file)
508 std::string res;
509 for (;;)
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);
518 if (n == chunk_size)
519 continue;
521 gdb_assert (n < chunk_size);
523 /* Less than CHUNK means EOF or error. If it's an error, return
524 no value. */
525 if (ferror (file))
526 return {};
528 /* Resize the string according to the data we read. */
529 res.resize (start_size + n);
530 break;
533 return res;
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");
542 if (file == nullptr)
543 return {};
545 return read_remainder_of_file (file.get ());