1 /* Low-level file-handling. 2 Copyright (C) 2012-2023 Free Software Foundation, Inc. 3 4 This file is part of GDB. 5 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. 10 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. 15 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/>. */ 18 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> 27 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 38 39 #ifdef HAVE_KINFO_GETFILE 40 #include <sys/user.h> 41 #include <libutil.h> 42 #endif 43 44 #ifdef HAVE_SYS_RESOURCE_H 45 #include <sys/resource.h> 46 #endif /* HAVE_SYS_RESOURCE_H */ 47 48 #ifndef O_CLOEXEC 49 #define O_CLOEXEC 0 50 #endif 51 52 #ifndef O_NOINHERIT 53 #define O_NOINHERIT 0 54 #endif 55 56 #ifndef SOCK_CLOEXEC 57 #define SOCK_CLOEXEC 0 58 #endif 59 60 61 62 #ifndef HAVE_FDWALK 63 64 #include <dirent.h> 65 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. */ 72 73 static int 74 fdwalk (int (*func) (void *, int), void *arg) 75 { 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; 81 82 dir = opendir ("/proc/self/fd"); 83 if (dir != NULL) 84 { 85 struct dirent *entry; 86 int result = 0; 87 88 for (entry = readdir (dir); entry != NULL; entry = readdir (dir)) 89 { 90 long fd; 91 char *tail; 92 93 errno = 0; 94 fd = strtol (entry->d_name, &tail, 10); 95 if (*tail != '\0' || errno != 0) 96 continue; 97 if ((int) fd != fd) 98 { 99 /* What can we do here really? */ 100 continue; 101 } 102 103 if (fd == dirfd (dir)) 104 continue; 105 106 result = func (arg, fd); 107 if (result != 0) 108 break; 109 } 110 111 closedir (dir); 112 return result; 113 } 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) 121 { 122 for (int i = 0; i < nfd; i++) 123 { 124 if (fdtbl[i].kf_fd >= 0) 125 { 126 int result = func (arg, fdtbl[i].kf_fd); 127 if (result != 0) 128 return result; 129 } 130 } 131 return 0; 132 } 133 /* We may fall through to the next case. */ 134 #endif 135 136 { 137 int max, fd; 138 139 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE) 140 struct rlimit rlim; 141 142 if (getrlimit (RLIMIT_NOFILE, &rlim) == 0 && rlim.rlim_max != RLIM_INFINITY) 143 max = rlim.rlim_max; 144 else 145 #endif 146 { 147 #ifdef _SC_OPEN_MAX 148 max = sysconf (_SC_OPEN_MAX); 149 #else 150 /* Whoops. */ 151 return 0; 152 #endif /* _SC_OPEN_MAX */ 153 } 154 155 for (fd = 0; fd < max; ++fd) 156 { 157 struct stat sb; 158 int result; 159 160 /* Only call FUNC for open fds. */ 161 if (fstat (fd, &sb) == -1) 162 continue; 163 164 result = func (arg, fd); 165 if (result != 0) 166 return result; 167 } 168 169 return 0; 170 } 171 } 172 173 #endif /* HAVE_FDWALK */ 174 175 176 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. */ 179 180 static std::vector<int> open_fds; 181 182 /* An fdwalk callback function used by notice_open_fds. It puts the 183 given file descriptor into the vec. */ 184 185 static int 186 do_mark_open_fd (void *ignore, int fd) 187 { 188 open_fds.push_back (fd); 189 return 0; 190 } 191 192 /* See filestuff.h. */ 193 194 void 195 notice_open_fds (void) 196 { 197 fdwalk (do_mark_open_fd, NULL); 198 } 199 200 /* See filestuff.h. */ 201 202 void 203 mark_fd_no_cloexec (int fd) 204 { 205 do_mark_open_fd (NULL, fd); 206 } 207 208 /* See filestuff.h. */ 209 210 void 211 unmark_fd_no_cloexec (int fd) 212 { 213 auto it = std::remove (open_fds.begin (), open_fds.end (), fd); 214 215 if (it != open_fds.end ()) 216 open_fds.erase (it); 217 else 218 gdb_assert_not_reached ("fd not found in open_fds"); 219 } 220 221 /* Helper function for close_most_fds that closes the file descriptor 222 if appropriate. */ 223 224 static int 225 do_close (void *ignore, int fd) 226 { 227 for (int val : open_fds) 228 { 229 if (fd == val) 230 { 231 /* Keep this one open. */ 232 return 0; 233 } 234 } 235 236 close (fd); 237 return 0; 238 } 239 240 /* See filestuff.h. */ 241 242 void 243 close_most_fds (void) 244 { 245 fdwalk (do_close, NULL); 246 } 247 248 249 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. */ 256 257 static int trust_o_cloexec; 258 259 /* Mark FD as close-on-exec, ignoring errors. Update 260 TRUST_O_CLOEXEC. */ 261 262 static void 263 mark_cloexec (int fd) 264 { 265 #ifdef HAVE_F_GETFD 266 int old = fcntl (fd, F_GETFD, 0); 267 268 if (old != -1) 269 { 270 fcntl (fd, F_SETFD, old | FD_CLOEXEC); 271 272 if (trust_o_cloexec == 0) 273 { 274 if ((old & FD_CLOEXEC) != 0) 275 trust_o_cloexec = 1; 276 else 277 trust_o_cloexec = -1; 278 } 279 } 280 #endif /* HAVE_F_GETFD */ 281 } 282 283 /* Depending on TRUST_O_CLOEXEC, mark FD as close-on-exec. */ 284 285 static void 286 maybe_mark_cloexec (int fd) 287 { 288 if (trust_o_cloexec <= 0) 289 mark_cloexec (fd); 290 } 291 292 #ifdef HAVE_SOCKETS 293 294 /* Like maybe_mark_cloexec, but for callers that use SOCK_CLOEXEC. */ 295 296 static void 297 socket_mark_cloexec (int fd) 298 { 299 if (SOCK_CLOEXEC == 0 || trust_o_cloexec <= 0) 300 mark_cloexec (fd); 301 } 302 303 #endif 304 305 306 307 /* See filestuff.h. */ 308 309 scoped_fd 310 gdb_open_cloexec (const char *filename, int flags, unsigned long mode) 311 { 312 scoped_fd fd (open (filename, flags | O_CLOEXEC, mode)); 313 314 if (fd.get () >= 0) 315 maybe_mark_cloexec (fd.get ()); 316 317 return fd; 318 } 319 320 /* See filestuff.h. */ 321 322 gdb_file_up 323 gdb_fopen_cloexec (const char *filename, const char *opentype) 324 { 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; 335 336 if (!fopen_e_ever_failed_einval) 337 { 338 char *copy; 339 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); 346 347 if (result == NULL && errno == EINVAL) 348 { 349 result = fopen (filename, opentype); 350 if (result != NULL) 351 fopen_e_ever_failed_einval = 1; 352 } 353 } 354 else 355 result = fopen (filename, opentype); 356 357 if (result != NULL) 358 maybe_mark_cloexec (fileno (result)); 359 360 return gdb_file_up (result); 361 } 362 363 #ifdef HAVE_SOCKETS 364 /* See filestuff.h. */ 365 366 int 367 gdb_socketpair_cloexec (int domain, int style, int protocol, 368 int filedes[2]) 369 { 370 #ifdef HAVE_SOCKETPAIR 371 int result = socketpair (domain, style | SOCK_CLOEXEC, protocol, filedes); 372 373 if (result != -1) 374 { 375 socket_mark_cloexec (filedes[0]); 376 socket_mark_cloexec (filedes[1]); 377 } 378 379 return result; 380 #else 381 gdb_assert_not_reached ("socketpair not available on this host"); 382 #endif 383 } 384 385 /* See filestuff.h. */ 386 387 int 388 gdb_socket_cloexec (int domain, int style, int protocol) 389 { 390 int result = socket (domain, style | SOCK_CLOEXEC, protocol); 391 392 if (result != -1) 393 socket_mark_cloexec (result); 394 395 return result; 396 } 397 #endif 398 399 /* See filestuff.h. */ 400 401 int 402 gdb_pipe_cloexec (int filedes[2]) 403 { 404 int result; 405 406 #ifdef HAVE_PIPE2 407 result = pipe2 (filedes, O_CLOEXEC); 408 if (result != -1) 409 { 410 maybe_mark_cloexec (filedes[0]); 411 maybe_mark_cloexec (filedes[1]); 412 } 413 #else 414 #ifdef HAVE_PIPE 415 result = pipe (filedes); 416 if (result != -1) 417 { 418 mark_cloexec (filedes[0]); 419 mark_cloexec (filedes[1]); 420 } 421 #else /* HAVE_PIPE */ 422 gdb_assert_not_reached ("pipe not available on this host"); 423 #endif /* HAVE_PIPE */ 424 #endif /* HAVE_PIPE2 */ 425 426 return result; 427 } 428 429 /* See gdbsupport/filestuff.h. */ 430 431 bool 432 is_regular_file (const char *name, int *errno_ptr) 433 { 434 struct stat st; 435 const int status = stat (name, &st); 436 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. */ 441 442 if (status != 0) 443 { 444 if (errno != ENOENT) 445 return true; 446 *errno_ptr = ENOENT; 447 return false; 448 } 449 450 if (S_ISREG (st.st_mode)) 451 return true; 452 453 if (S_ISDIR (st.st_mode)) 454 *errno_ptr = EISDIR; 455 else 456 *errno_ptr = EINVAL; 457 return false; 458 } 459 460 /* See gdbsupport/filestuff.h. */ 461 462 bool 463 mkdir_recursive (const char *dir) 464 { 465 auto holder = make_unique_xstrdup (dir); 466 char * const start = holder.get (); 467 char *component_start = start; 468 char *component_end = start; 469 470 while (1) 471 { 472 /* Find the beginning of the next component. */ 473 while (*component_start == '/') 474 component_start++; 475 476 /* Are we done? */ 477 if (*component_start == '\0') 478 return true; 479 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++; 484 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'; 489 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; 498 499 /* Restore the overwritten char. */ 500 *component_end = saved_char; 501 component_start = component_end; 502 } 503 } 504 505 /* See gdbsupport/filestuff.h. */ 506 507 gdb::optional<std::string> 508 read_text_file_to_string (const char *path) 509 { 510 gdb_file_up file = gdb_fopen_cloexec (path, "r"); 511 if (file == nullptr) 512 return {}; 513 514 std::string res; 515 for (;;) 516 { 517 std::string::size_type start_size = res.size (); 518 constexpr int chunk_size = 1024; 519 520 /* Resize to accomodate CHUNK_SIZE bytes. */ 521 res.resize (start_size + chunk_size); 522 523 int n = fread (&res[start_size], 1, chunk_size, file.get ()); 524 if (n == chunk_size) 525 continue; 526 527 gdb_assert (n < chunk_size); 528 529 /* Less than CHUNK means EOF or error. If it's an error, return 530 no value. */ 531 if (ferror (file.get ())) 532 return {}; 533 534 /* Resize the string according to the data we read. */ 535 res.resize (start_size + n); 536 break; 537 } 538 539 return res; 540 } 541