gdb/riscv: Use legacy register numbers in default target description
[external/binutils.git] / gdb / common / filestuff.c
1 /* Low-level file-handling.
2    Copyright (C) 2012-2019 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 \f
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 \f
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 \f
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 \f
306
307 /* See filestuff.h.  */
308
309 int
310 gdb_open_cloexec (const char *filename, int flags, unsigned long mode)
311 {
312   int fd = open (filename, flags | O_CLOEXEC, mode);
313
314   if (fd >= 0)
315     maybe_mark_cloexec (fd);
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 /* Helper function which does the work for make_cleanup_close.  */
430
431 static void
432 do_close_cleanup (void *arg)
433 {
434   int *fd = (int *) arg;
435
436   close (*fd);
437 }
438
439 /* See filestuff.h.  */
440
441 struct cleanup *
442 make_cleanup_close (int fd)
443 {
444   int *saved_fd = XNEW (int);
445
446   *saved_fd = fd;
447   return make_cleanup_dtor (do_close_cleanup, saved_fd, xfree);
448 }
449
450 /* See common/filestuff.h.  */
451
452 bool
453 is_regular_file (const char *name, int *errno_ptr)
454 {
455   struct stat st;
456   const int status = stat (name, &st);
457
458   /* Stat should never fail except when the file does not exist.
459      If stat fails, analyze the source of error and return true
460      unless the file does not exist, to avoid returning false results
461      on obscure systems where stat does not work as expected.  */
462
463   if (status != 0)
464     {
465       if (errno != ENOENT)
466         return true;
467       *errno_ptr = ENOENT;
468       return false;
469     }
470
471   if (S_ISREG (st.st_mode))
472     return true;
473
474   if (S_ISDIR (st.st_mode))
475     *errno_ptr = EISDIR;
476   else
477     *errno_ptr = EINVAL;
478   return false;
479 }
480
481 /* See common/filestuff.h.  */
482
483 bool
484 mkdir_recursive (const char *dir)
485 {
486   gdb::unique_xmalloc_ptr<char> holder (xstrdup (dir));
487   char * const start = holder.get ();
488   char *component_start = start;
489   char *component_end = start;
490
491   while (1)
492     {
493       /* Find the beginning of the next component.  */
494       while (*component_start == '/')
495         component_start++;
496
497       /* Are we done?  */
498       if (*component_start == '\0')
499         return true;
500
501       /* Find the slash or null-terminator after this component.  */
502       component_end = component_start;
503       while (*component_end != '/' && *component_end != '\0')
504         component_end++;
505
506       /* Temporarily replace the slash with a null terminator, so we can create
507          the directory up to this component.  */
508       char saved_char = *component_end;
509       *component_end = '\0';
510
511       /* If we get EEXIST and the existing path is a directory, then we're
512          happy.  If it exists, but it's a regular file and this is not the last
513          component, we'll fail at the next component.  If this is the last
514          component, the caller will fail with ENOTDIR when trying to
515          open/create a file under that path.  */
516       if (mkdir (start, 0700) != 0)
517         if (errno != EEXIST)
518           return false;
519
520       /* Restore the overwritten char.  */
521       *component_end = saved_char;
522       component_start = component_end;
523     }
524 }