Accept and ignore the R_BPF_64_NODLYD32 relocation.
[binutils-gdb.git] / gdb / linux-fork.c
blob52e385411c7e656b51fca270c649e21620ebb98f
1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005-2023 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "inferior.h"
23 #include "infrun.h"
24 #include "regcache.h"
25 #include "gdbcmd.h"
26 #include "infcall.h"
27 #include "objfiles.h"
28 #include "linux-fork.h"
29 #include "linux-nat.h"
30 #include "gdbthread.h"
31 #include "source.h"
33 #include "nat/gdb_ptrace.h"
34 #include "gdbsupport/gdb_wait.h"
35 #include <dirent.h>
36 #include <ctype.h>
38 #include <list>
40 /* Fork list data structure: */
41 struct fork_info
43 explicit fork_info (pid_t pid)
44 : ptid (pid, pid)
48 ~fork_info ()
50 /* Notes on step-resume breakpoints: since this is a concern for
51 threads, let's convince ourselves that it's not a concern for
52 forks. There are two ways for a fork_info to be created.
53 First, by the checkpoint command, in which case we're at a gdb
54 prompt and there can't be any step-resume breakpoint. Second,
55 by a fork in the user program, in which case we *may* have
56 stepped into the fork call, but regardless of whether we follow
57 the parent or the child, we will return to the same place and
58 the step-resume breakpoint, if any, will take care of itself as
59 usual. And unlike threads, we do not save a private copy of
60 the step-resume breakpoint -- so we're OK. */
62 if (savedregs)
63 delete savedregs;
65 xfree (filepos);
68 ptid_t ptid = null_ptid;
69 ptid_t parent_ptid = null_ptid;
71 /* Convenient handle (GDB fork id). */
72 int num = 0;
74 /* Convenient for info fork, saves having to actually switch
75 contexts. */
76 readonly_detached_regcache *savedregs = nullptr;
78 CORE_ADDR pc = 0;
80 /* Set of open file descriptors' offsets. */
81 off_t *filepos = nullptr;
83 int maxfd = 0;
86 static std::list<fork_info> fork_list;
87 static int highest_fork_num;
89 /* Fork list methods: */
91 int
92 forks_exist_p (void)
94 return !fork_list.empty ();
97 /* Return the last fork in the list. */
99 static struct fork_info *
100 find_last_fork (void)
102 if (fork_list.empty ())
103 return NULL;
105 return &fork_list.back ();
108 /* Return true iff there's one fork in the list. */
110 static bool
111 one_fork_p ()
113 return fork_list.size () == 1;
116 /* Add a new fork to the internal fork list. */
118 void
119 add_fork (pid_t pid)
121 fork_list.emplace_back (pid);
123 if (one_fork_p ())
124 highest_fork_num = 0;
126 fork_info *fp = &fork_list.back ();
127 fp->num = ++highest_fork_num;
130 static void
131 delete_fork (ptid_t ptid)
133 linux_target->low_forget_process (ptid.pid ());
135 for (auto it = fork_list.begin (); it != fork_list.end (); ++it)
136 if (it->ptid == ptid)
138 fork_list.erase (it);
140 /* Special case: if there is now only one process in the list,
141 and if it is (hopefully!) the current inferior_ptid, then
142 remove it, leaving the list empty -- we're now down to the
143 default case of debugging a single process. */
144 if (one_fork_p () && fork_list.front ().ptid == inferior_ptid)
146 /* Last fork -- delete from list and handle as solo
147 process (should be a safe recursion). */
148 delete_fork (inferior_ptid);
150 return;
154 /* Find a fork_info by matching PTID. */
155 static struct fork_info *
156 find_fork_ptid (ptid_t ptid)
158 for (fork_info &fi : fork_list)
159 if (fi.ptid == ptid)
160 return &fi;
162 return NULL;
165 /* Find a fork_info by matching ID. */
166 static struct fork_info *
167 find_fork_id (int num)
169 for (fork_info &fi : fork_list)
170 if (fi.num == num)
171 return &fi;
173 return NULL;
176 /* Find a fork_info by matching pid. */
177 extern struct fork_info *
178 find_fork_pid (pid_t pid)
180 for (fork_info &fi : fork_list)
181 if (pid == fi.ptid.pid ())
182 return &fi;
184 return NULL;
187 static ptid_t
188 fork_id_to_ptid (int num)
190 struct fork_info *fork = find_fork_id (num);
191 if (fork)
192 return fork->ptid;
193 else
194 return ptid_t (-1);
197 /* Fork list <-> gdb interface. */
199 /* Utility function for fork_load/fork_save.
200 Calls lseek in the (current) inferior process. */
202 static off_t
203 call_lseek (int fd, off_t offset, int whence)
205 char exp[80];
207 snprintf (&exp[0], sizeof (exp), "(long) lseek (%d, %ld, %d)",
208 fd, (long) offset, whence);
209 return (off_t) parse_and_eval_long (&exp[0]);
212 /* Load infrun state for the fork PTID. */
214 static void
215 fork_load_infrun_state (struct fork_info *fp)
217 int i;
219 linux_nat_switch_fork (fp->ptid);
221 if (fp->savedregs)
222 get_current_regcache ()->restore (fp->savedregs);
224 registers_changed ();
225 reinit_frame_cache ();
227 inferior_thread ()->set_stop_pc (regcache_read_pc (get_current_regcache ()));
228 nullify_last_target_wait_ptid ();
230 /* Now restore the file positions of open file descriptors. */
231 if (fp->filepos)
233 for (i = 0; i <= fp->maxfd; i++)
234 if (fp->filepos[i] != (off_t) -1)
235 call_lseek (i, fp->filepos[i], SEEK_SET);
236 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
237 this is native-only. If it ever has to be cross, we'll have
238 to rethink this. */
242 /* Save infrun state for the fork FP. */
244 static void
245 fork_save_infrun_state (struct fork_info *fp)
247 char path[PATH_MAX];
248 struct dirent *de;
249 DIR *d;
251 if (fp->savedregs)
252 delete fp->savedregs;
254 fp->savedregs = new readonly_detached_regcache (*get_current_regcache ());
255 fp->pc = regcache_read_pc (get_current_regcache ());
257 /* Now save the 'state' (file position) of all open file descriptors.
258 Unfortunately fork does not take care of that for us... */
259 snprintf (path, PATH_MAX, "/proc/%ld/fd", (long) fp->ptid.pid ());
260 if ((d = opendir (path)) != NULL)
262 long tmp;
264 fp->maxfd = 0;
265 while ((de = readdir (d)) != NULL)
267 /* Count open file descriptors (actually find highest
268 numbered). */
269 tmp = strtol (&de->d_name[0], NULL, 10);
270 if (fp->maxfd < tmp)
271 fp->maxfd = tmp;
273 /* Allocate array of file positions. */
274 fp->filepos = XRESIZEVEC (off_t, fp->filepos, fp->maxfd + 1);
276 /* Initialize to -1 (invalid). */
277 for (tmp = 0; tmp <= fp->maxfd; tmp++)
278 fp->filepos[tmp] = -1;
280 /* Now find actual file positions. */
281 rewinddir (d);
282 while ((de = readdir (d)) != NULL)
283 if (isdigit (de->d_name[0]))
285 tmp = strtol (&de->d_name[0], NULL, 10);
286 fp->filepos[tmp] = call_lseek (tmp, 0, SEEK_CUR);
288 closedir (d);
292 /* Kill 'em all, let God sort 'em out... */
294 void
295 linux_fork_killall (void)
297 /* Walk list and kill every pid. No need to treat the
298 current inferior_ptid as special (we do not return a
299 status for it) -- however any process may be a child
300 or a parent, so may get a SIGCHLD from a previously
301 killed child. Wait them all out. */
303 for (fork_info &fi : fork_list)
305 pid_t pid = fi.ptid.pid ();
306 int status;
307 pid_t ret;
308 do {
309 /* Use SIGKILL instead of PTRACE_KILL because the former works even
310 if the thread is running, while the later doesn't. */
311 kill (pid, SIGKILL);
312 ret = waitpid (pid, &status, 0);
313 /* We might get a SIGCHLD instead of an exit status. This is
314 aggravated by the first kill above - a child has just
315 died. MVS comment cut-and-pasted from linux-nat. */
316 } while (ret == pid && WIFSTOPPED (status));
319 /* Clear list, prepare to start fresh. */
320 fork_list.clear ();
323 /* The current inferior_ptid has exited, but there are other viable
324 forks to debug. Delete the exiting one and context-switch to the
325 first available. */
327 void
328 linux_fork_mourn_inferior (void)
330 struct fork_info *last;
331 int status;
333 /* Wait just one more time to collect the inferior's exit status.
334 Do not check whether this succeeds though, since we may be
335 dealing with a process that we attached to. Such a process will
336 only report its exit status to its original parent. */
337 waitpid (inferior_ptid.pid (), &status, 0);
339 /* OK, presumably inferior_ptid is the one who has exited.
340 We need to delete that one from the fork_list, and switch
341 to the next available fork. */
342 delete_fork (inferior_ptid);
344 /* There should still be a fork - if there's only one left,
345 delete_fork won't remove it, because we haven't updated
346 inferior_ptid yet. */
347 gdb_assert (!fork_list.empty ());
349 last = find_last_fork ();
350 fork_load_infrun_state (last);
351 gdb_printf (_("[Switching to %s]\n"),
352 target_pid_to_str (inferior_ptid).c_str ());
354 /* If there's only one fork, switch back to non-fork mode. */
355 if (one_fork_p ())
356 delete_fork (inferior_ptid);
359 /* The current inferior_ptid is being detached, but there are other
360 viable forks to debug. Detach and delete it and context-switch to
361 the first available. */
363 void
364 linux_fork_detach (int from_tty)
366 /* OK, inferior_ptid is the one we are detaching from. We need to
367 delete it from the fork_list, and switch to the next available
368 fork. */
370 if (ptrace (PTRACE_DETACH, inferior_ptid.pid (), 0, 0))
371 error (_("Unable to detach %s"),
372 target_pid_to_str (inferior_ptid).c_str ());
374 delete_fork (inferior_ptid);
376 /* There should still be a fork - if there's only one left,
377 delete_fork won't remove it, because we haven't updated
378 inferior_ptid yet. */
379 gdb_assert (!fork_list.empty ());
381 fork_load_infrun_state (&fork_list.front ());
383 if (from_tty)
384 gdb_printf (_("[Switching to %s]\n"),
385 target_pid_to_str (inferior_ptid).c_str ());
387 /* If there's only one fork, switch back to non-fork mode. */
388 if (one_fork_p ())
389 delete_fork (inferior_ptid);
392 /* Temporarily switch to the infrun state stored on the fork_info
393 identified by a given ptid_t. When this object goes out of scope,
394 restore the currently selected infrun state. */
396 class scoped_switch_fork_info
398 public:
399 /* Switch to the infrun state held on the fork_info identified by
400 PPTID. If PPTID is the current inferior then no switch is done. */
401 explicit scoped_switch_fork_info (ptid_t pptid)
402 : m_oldfp (nullptr)
404 if (pptid != inferior_ptid)
406 struct fork_info *newfp = nullptr;
408 /* Switch to pptid. */
409 m_oldfp = find_fork_ptid (inferior_ptid);
410 gdb_assert (m_oldfp != nullptr);
411 newfp = find_fork_ptid (pptid);
412 gdb_assert (newfp != nullptr);
413 fork_save_infrun_state (m_oldfp);
414 remove_breakpoints ();
415 fork_load_infrun_state (newfp);
416 insert_breakpoints ();
420 /* Restore the previously selected infrun state. If the constructor
421 didn't need to switch states, then nothing is done here either. */
422 ~scoped_switch_fork_info ()
424 if (m_oldfp != nullptr)
426 /* Switch back to inferior_ptid. */
429 remove_breakpoints ();
430 fork_load_infrun_state (m_oldfp);
431 insert_breakpoints ();
433 catch (const gdb_exception_quit &ex)
435 /* We can't throw from a destructor, so re-set the quit flag
436 for later QUIT checking. */
437 set_quit_flag ();
439 catch (const gdb_exception_forced_quit &ex)
441 /* Like above, but (eventually) cause GDB to terminate by
442 setting sync_quit_force_run. */
443 set_force_quit_flag ();
445 catch (const gdb_exception &ex)
447 warning (_("Couldn't restore checkpoint state in %s: %s"),
448 target_pid_to_str (m_oldfp->ptid).c_str (),
449 ex.what ());
454 DISABLE_COPY_AND_ASSIGN (scoped_switch_fork_info);
456 private:
457 /* The fork_info for the previously selected infrun state, or nullptr if
458 we were already in the desired state, and nothing needs to be
459 restored. */
460 struct fork_info *m_oldfp;
463 static int
464 inferior_call_waitpid (ptid_t pptid, int pid)
466 struct objfile *waitpid_objf;
467 struct value *waitpid_fn = NULL;
468 int ret = -1;
470 scoped_switch_fork_info switch_fork_info (pptid);
472 /* Get the waitpid_fn. */
473 if (lookup_minimal_symbol ("waitpid", NULL, NULL).minsym != NULL)
474 waitpid_fn = find_function_in_inferior ("waitpid", &waitpid_objf);
475 if (!waitpid_fn
476 && lookup_minimal_symbol ("_waitpid", NULL, NULL).minsym != NULL)
477 waitpid_fn = find_function_in_inferior ("_waitpid", &waitpid_objf);
478 if (waitpid_fn != nullptr)
480 struct gdbarch *gdbarch = get_current_arch ();
481 struct value *argv[3], *retv;
483 /* Get the argv. */
484 argv[0] = value_from_longest (builtin_type (gdbarch)->builtin_int, pid);
485 argv[1] = value_from_pointer (builtin_type (gdbarch)->builtin_data_ptr, 0);
486 argv[2] = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
488 retv = call_function_by_hand (waitpid_fn, NULL, argv);
490 if (value_as_long (retv) >= 0)
491 ret = 0;
494 return ret;
497 /* Fork list <-> user interface. */
499 static void
500 delete_checkpoint_command (const char *args, int from_tty)
502 ptid_t ptid, pptid;
503 struct fork_info *fi;
505 if (!args || !*args)
506 error (_("Requires argument (checkpoint id to delete)"));
508 ptid = fork_id_to_ptid (parse_and_eval_long (args));
509 if (ptid == minus_one_ptid)
510 error (_("No such checkpoint id, %s"), args);
512 if (ptid == inferior_ptid)
513 error (_("\
514 Please switch to another checkpoint before deleting the current one"));
516 if (ptrace (PTRACE_KILL, ptid.pid (), 0, 0))
517 error (_("Unable to kill pid %s"), target_pid_to_str (ptid).c_str ());
519 fi = find_fork_ptid (ptid);
520 gdb_assert (fi);
521 pptid = fi->parent_ptid;
523 if (from_tty)
524 gdb_printf (_("Killed %s\n"), target_pid_to_str (ptid).c_str ());
526 delete_fork (ptid);
528 /* If fi->parent_ptid is not a part of lwp but it's a part of checkpoint
529 list, waitpid the ptid.
530 If fi->parent_ptid is a part of lwp and it is stopped, waitpid the
531 ptid. */
532 thread_info *parent = linux_target->find_thread (pptid);
533 if ((parent == NULL && find_fork_ptid (pptid))
534 || (parent != NULL && parent->state == THREAD_STOPPED))
536 if (inferior_call_waitpid (pptid, ptid.pid ()))
537 warning (_("Unable to wait pid %s"),
538 target_pid_to_str (ptid).c_str ());
542 static void
543 detach_checkpoint_command (const char *args, int from_tty)
545 ptid_t ptid;
547 if (!args || !*args)
548 error (_("Requires argument (checkpoint id to detach)"));
550 ptid = fork_id_to_ptid (parse_and_eval_long (args));
551 if (ptid == minus_one_ptid)
552 error (_("No such checkpoint id, %s"), args);
554 if (ptid == inferior_ptid)
555 error (_("\
556 Please switch to another checkpoint before detaching the current one"));
558 if (ptrace (PTRACE_DETACH, ptid.pid (), 0, 0))
559 error (_("Unable to detach %s"), target_pid_to_str (ptid).c_str ());
561 if (from_tty)
562 gdb_printf (_("Detached %s\n"), target_pid_to_str (ptid).c_str ());
564 delete_fork (ptid);
567 /* Print information about currently known checkpoints. */
569 static void
570 info_checkpoints_command (const char *arg, int from_tty)
572 struct gdbarch *gdbarch = get_current_arch ();
573 int requested = -1;
574 const fork_info *printed = NULL;
576 if (arg && *arg)
577 requested = (int) parse_and_eval_long (arg);
579 for (const fork_info &fi : fork_list)
581 if (requested > 0 && fi.num != requested)
582 continue;
584 printed = &fi;
585 if (fi.ptid == inferior_ptid)
586 gdb_printf ("* ");
587 else
588 gdb_printf (" ");
590 ULONGEST pc = fi.pc;
591 gdb_printf ("%d %s", fi.num, target_pid_to_str (fi.ptid).c_str ());
592 if (fi.num == 0)
593 gdb_printf (_(" (main process)"));
594 gdb_printf (_(" at "));
595 gdb_puts (paddress (gdbarch, pc));
597 symtab_and_line sal = find_pc_line (pc, 0);
598 if (sal.symtab)
599 gdb_printf (_(", file %s"),
600 symtab_to_filename_for_display (sal.symtab));
601 if (sal.line)
602 gdb_printf (_(", line %d"), sal.line);
603 if (!sal.symtab && !sal.line)
605 struct bound_minimal_symbol msym;
607 msym = lookup_minimal_symbol_by_pc (pc);
608 if (msym.minsym)
609 gdb_printf (", <%s>", msym.minsym->linkage_name ());
612 gdb_putc ('\n');
614 if (printed == NULL)
616 if (requested > 0)
617 gdb_printf (_("No checkpoint number %d.\n"), requested);
618 else
619 gdb_printf (_("No checkpoints.\n"));
623 /* The PID of the process we're checkpointing. */
624 static int checkpointing_pid = 0;
627 linux_fork_checkpointing_p (int pid)
629 return (checkpointing_pid == pid);
632 /* Return true if the current inferior is multi-threaded. */
634 static bool
635 inf_has_multiple_threads ()
637 int count = 0;
639 /* Return true as soon as we see the second thread of the current
640 inferior. */
641 for (thread_info *tp ATTRIBUTE_UNUSED : current_inferior ()->threads ())
642 if (++count > 1)
643 return true;
645 return false;
648 static void
649 checkpoint_command (const char *args, int from_tty)
651 struct objfile *fork_objf;
652 struct gdbarch *gdbarch;
653 struct target_waitstatus last_target_waitstatus;
654 ptid_t last_target_ptid;
655 struct value *fork_fn = NULL, *ret;
656 struct fork_info *fp;
657 pid_t retpid;
659 if (!target_has_execution ())
660 error (_("The program is not being run."));
662 /* Ensure that the inferior is not multithreaded. */
663 update_thread_list ();
664 if (inf_has_multiple_threads ())
665 error (_("checkpoint: can't checkpoint multiple threads."));
667 /* Make the inferior fork, record its (and gdb's) state. */
669 if (lookup_minimal_symbol ("fork", NULL, NULL).minsym != NULL)
670 fork_fn = find_function_in_inferior ("fork", &fork_objf);
671 if (!fork_fn)
672 if (lookup_minimal_symbol ("_fork", NULL, NULL).minsym != NULL)
673 fork_fn = find_function_in_inferior ("fork", &fork_objf);
674 if (!fork_fn)
675 error (_("checkpoint: can't find fork function in inferior."));
677 gdbarch = fork_objf->arch ();
678 ret = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
680 /* Tell linux-nat.c that we're checkpointing this inferior. */
682 scoped_restore save_pid
683 = make_scoped_restore (&checkpointing_pid, inferior_ptid.pid ());
685 ret = call_function_by_hand (fork_fn, NULL, {});
688 if (!ret) /* Probably can't happen. */
689 error (_("checkpoint: call_function_by_hand returned null."));
691 retpid = value_as_long (ret);
692 get_last_target_status (nullptr, &last_target_ptid, &last_target_waitstatus);
694 fp = find_fork_pid (retpid);
696 if (from_tty)
698 int parent_pid;
700 gdb_printf (_("checkpoint %d: fork returned pid %ld.\n"),
701 fp != NULL ? fp->num : -1, (long) retpid);
702 if (info_verbose)
704 parent_pid = last_target_ptid.lwp ();
705 if (parent_pid == 0)
706 parent_pid = last_target_ptid.pid ();
707 gdb_printf (_(" gdb says parent = %ld.\n"),
708 (long) parent_pid);
712 if (!fp)
713 error (_("Failed to find new fork"));
715 if (one_fork_p ())
717 /* Special case -- if this is the first fork in the list (the
718 list was hitherto empty), then add inferior_ptid first, as a
719 special zeroeth fork id. */
720 fork_list.emplace_front (inferior_ptid.pid ());
723 fork_save_infrun_state (fp);
724 fp->parent_ptid = last_target_ptid;
727 static void
728 linux_fork_context (struct fork_info *newfp, int from_tty)
730 /* Now we attempt to switch processes. */
731 struct fork_info *oldfp;
733 gdb_assert (newfp != NULL);
735 oldfp = find_fork_ptid (inferior_ptid);
736 gdb_assert (oldfp != NULL);
738 fork_save_infrun_state (oldfp);
739 remove_breakpoints ();
740 fork_load_infrun_state (newfp);
741 insert_breakpoints ();
743 gdb_printf (_("Switching to %s\n"),
744 target_pid_to_str (inferior_ptid).c_str ());
746 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
749 /* Switch inferior process (checkpoint) context, by checkpoint id. */
750 static void
751 restart_command (const char *args, int from_tty)
753 struct fork_info *fp;
755 if (!args || !*args)
756 error (_("Requires argument (checkpoint id to restart)"));
758 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
759 error (_("Not found: checkpoint id %s"), args);
761 linux_fork_context (fp, from_tty);
764 void _initialize_linux_fork ();
765 void
766 _initialize_linux_fork ()
768 /* Checkpoint command: create a fork of the inferior process
769 and set it aside for later debugging. */
771 add_com ("checkpoint", class_obscure, checkpoint_command, _("\
772 Fork a duplicate process (experimental)."));
774 /* Restart command: restore the context of a specified checkpoint
775 process. */
777 add_com ("restart", class_obscure, restart_command, _("\
778 Restore program context from a checkpoint.\n\
779 Usage: restart N\n\
780 Argument N is checkpoint ID, as displayed by 'info checkpoints'."));
782 /* Delete checkpoint command: kill the process and remove it from
783 the fork list. */
785 add_cmd ("checkpoint", class_obscure, delete_checkpoint_command, _("\
786 Delete a checkpoint (experimental)."),
787 &deletelist);
789 /* Detach checkpoint command: release the process to run independently,
790 and remove it from the fork list. */
792 add_cmd ("checkpoint", class_obscure, detach_checkpoint_command, _("\
793 Detach from a checkpoint (experimental)."),
794 &detachlist);
796 /* Info checkpoints command: list all forks/checkpoints
797 currently under gdb's control. */
799 add_info ("checkpoints", info_checkpoints_command,
800 _("IDs of currently known checkpoints."));