1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005-2024 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 "arch-utils.h"
27 #include "linux-fork.h"
28 #include "linux-nat.h"
29 #include "gdbthread.h"
32 #include "nat/gdb_ptrace.h"
33 #include "gdbsupport/gdb_wait.h"
34 #include "target/waitstatus.h"
40 /* Fork list data structure: */
43 explicit fork_info (pid_t pid
)
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. */
68 ptid_t ptid
= null_ptid
;
69 ptid_t parent_ptid
= null_ptid
;
71 /* Convenient handle (GDB fork id). */
74 /* Convenient for info fork, saves having to actually switch
76 readonly_detached_regcache
*savedregs
= nullptr;
80 /* Set of open file descriptors' offsets. */
81 off_t
*filepos
= nullptr;
86 static std::list
<fork_info
> fork_list
;
87 static int highest_fork_num
;
89 /* Fork list methods: */
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 ())
105 return &fork_list
.back ();
108 /* Return true iff there's one fork in the list. */
113 return fork_list
.size () == 1;
116 /* Add a new fork to the internal fork list. */
121 fork_list
.emplace_back (pid
);
124 highest_fork_num
= 0;
126 fork_info
*fp
= &fork_list
.back ();
127 fp
->num
= ++highest_fork_num
;
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
);
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
)
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
)
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 ())
188 fork_id_to_ptid (int num
)
190 struct fork_info
*fork
= find_fork_id (num
);
197 /* Fork list <-> gdb interface. */
199 /* Utility function for fork_load/fork_save.
200 Calls lseek in the (current) inferior process. */
203 call_lseek (int fd
, off_t offset
, int whence
)
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. */
215 fork_load_infrun_state (struct fork_info
*fp
)
219 linux_nat_switch_fork (fp
->ptid
);
222 get_thread_regcache (inferior_thread ())->restore (fp
->savedregs
);
224 registers_changed ();
225 reinit_frame_cache ();
227 inferior_thread ()->set_stop_pc
228 (regcache_read_pc (get_thread_regcache (inferior_thread ())));
229 inferior_thread ()->set_executing (false);
230 inferior_thread ()->set_resumed (false);
231 nullify_last_target_wait_ptid ();
233 /* Now restore the file positions of open file descriptors. */
236 for (i
= 0; i
<= fp
->maxfd
; i
++)
237 if (fp
->filepos
[i
] != (off_t
) -1)
238 call_lseek (i
, fp
->filepos
[i
], SEEK_SET
);
239 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
240 this is native-only. If it ever has to be cross, we'll have
245 /* Save infrun state for the fork FP. */
248 fork_save_infrun_state (struct fork_info
*fp
)
255 delete fp
->savedregs
;
257 fp
->savedregs
= new readonly_detached_regcache
258 (*get_thread_regcache (inferior_thread ()));
259 fp
->pc
= regcache_read_pc (get_thread_regcache (inferior_thread ()));
261 /* Now save the 'state' (file position) of all open file descriptors.
262 Unfortunately fork does not take care of that for us... */
263 snprintf (path
, PATH_MAX
, "/proc/%ld/fd", (long) fp
->ptid
.pid ());
264 if ((d
= opendir (path
)) != NULL
)
269 while ((de
= readdir (d
)) != NULL
)
271 /* Count open file descriptors (actually find highest
273 tmp
= strtol (&de
->d_name
[0], NULL
, 10);
277 /* Allocate array of file positions. */
278 fp
->filepos
= XRESIZEVEC (off_t
, fp
->filepos
, fp
->maxfd
+ 1);
280 /* Initialize to -1 (invalid). */
281 for (tmp
= 0; tmp
<= fp
->maxfd
; tmp
++)
282 fp
->filepos
[tmp
] = -1;
284 /* Now find actual file positions. */
286 while ((de
= readdir (d
)) != NULL
)
287 if (isdigit (de
->d_name
[0]))
289 tmp
= strtol (&de
->d_name
[0], NULL
, 10);
290 fp
->filepos
[tmp
] = call_lseek (tmp
, 0, SEEK_CUR
);
296 /* Kill 'em all, let God sort 'em out... */
299 linux_fork_killall (void)
301 /* Walk list and kill every pid. No need to treat the
302 current inferior_ptid as special (we do not return a
303 status for it) -- however any process may be a child
304 or a parent, so may get a SIGCHLD from a previously
305 killed child. Wait them all out. */
307 for (fork_info
&fi
: fork_list
)
309 pid_t pid
= fi
.ptid
.pid ();
313 /* Use SIGKILL instead of PTRACE_KILL because the former works even
314 if the thread is running, while the later doesn't. */
316 ret
= waitpid (pid
, &status
, 0);
317 /* We might get a SIGCHLD instead of an exit status. This is
318 aggravated by the first kill above - a child has just
319 died. MVS comment cut-and-pasted from linux-nat. */
320 } while (ret
== pid
&& WIFSTOPPED (status
));
323 /* Clear list, prepare to start fresh. */
327 /* The current inferior_ptid has exited, but there are other viable
328 forks to debug. Delete the exiting one and context-switch to the
332 linux_fork_mourn_inferior (void)
334 struct fork_info
*last
;
337 /* Wait just one more time to collect the inferior's exit status.
338 Do not check whether this succeeds though, since we may be
339 dealing with a process that we attached to. Such a process will
340 only report its exit status to its original parent. */
341 waitpid (inferior_ptid
.pid (), &status
, 0);
343 /* OK, presumably inferior_ptid is the one who has exited.
344 We need to delete that one from the fork_list, and switch
345 to the next available fork. */
346 delete_fork (inferior_ptid
);
348 /* There should still be a fork - if there's only one left,
349 delete_fork won't remove it, because we haven't updated
350 inferior_ptid yet. */
351 gdb_assert (!fork_list
.empty ());
353 last
= find_last_fork ();
354 fork_load_infrun_state (last
);
355 gdb_printf (_("[Switching to %s]\n"),
356 target_pid_to_str (inferior_ptid
).c_str ());
358 /* If there's only one fork, switch back to non-fork mode. */
360 delete_fork (inferior_ptid
);
363 /* The current inferior_ptid is being detached, but there are other
364 viable forks to debug. Detach and delete it and context-switch to
365 the first available. */
368 linux_fork_detach (int from_tty
, lwp_info
*lp
)
370 gdb_assert (lp
!= nullptr);
371 gdb_assert (lp
->ptid
== inferior_ptid
);
373 /* OK, inferior_ptid is the one we are detaching from. We need to
374 delete it from the fork_list, and switch to the next available
375 fork. But before doing the detach, do make sure that the lwp
376 hasn't exited or been terminated first. */
378 if (lp
->waitstatus
.kind () != TARGET_WAITKIND_EXITED
379 && lp
->waitstatus
.kind () != TARGET_WAITKIND_THREAD_EXITED
380 && lp
->waitstatus
.kind () != TARGET_WAITKIND_SIGNALLED
)
382 if (ptrace (PTRACE_DETACH
, inferior_ptid
.pid (), 0, 0))
383 error (_("Unable to detach %s"),
384 target_pid_to_str (inferior_ptid
).c_str ());
387 delete_fork (inferior_ptid
);
389 /* There should still be a fork - if there's only one left,
390 delete_fork won't remove it, because we haven't updated
391 inferior_ptid yet. */
392 gdb_assert (!fork_list
.empty ());
394 fork_load_infrun_state (&fork_list
.front ());
397 gdb_printf (_("[Switching to %s]\n"),
398 target_pid_to_str (inferior_ptid
).c_str ());
400 /* If there's only one fork, switch back to non-fork mode. */
402 delete_fork (inferior_ptid
);
405 /* Temporarily switch to the infrun state stored on the fork_info
406 identified by a given ptid_t. When this object goes out of scope,
407 restore the currently selected infrun state. */
409 class scoped_switch_fork_info
412 /* Switch to the infrun state held on the fork_info identified by
413 PPTID. If PPTID is the current inferior then no switch is done. */
414 explicit scoped_switch_fork_info (ptid_t pptid
)
417 if (pptid
!= inferior_ptid
)
419 struct fork_info
*newfp
= nullptr;
421 /* Switch to pptid. */
422 m_oldfp
= find_fork_ptid (inferior_ptid
);
423 gdb_assert (m_oldfp
!= nullptr);
424 newfp
= find_fork_ptid (pptid
);
425 gdb_assert (newfp
!= nullptr);
426 fork_save_infrun_state (m_oldfp
);
427 remove_breakpoints ();
428 fork_load_infrun_state (newfp
);
429 insert_breakpoints ();
433 /* Restore the previously selected infrun state. If the constructor
434 didn't need to switch states, then nothing is done here either. */
435 ~scoped_switch_fork_info ()
437 if (m_oldfp
!= nullptr)
439 /* Switch back to inferior_ptid. */
442 remove_breakpoints ();
443 fork_load_infrun_state (m_oldfp
);
444 insert_breakpoints ();
446 catch (const gdb_exception_quit
&ex
)
448 /* We can't throw from a destructor, so re-set the quit flag
449 for later QUIT checking. */
452 catch (const gdb_exception_forced_quit
&ex
)
454 /* Like above, but (eventually) cause GDB to terminate by
455 setting sync_quit_force_run. */
456 set_force_quit_flag ();
458 catch (const gdb_exception
&ex
)
460 warning (_("Couldn't restore checkpoint state in %s: %s"),
461 target_pid_to_str (m_oldfp
->ptid
).c_str (),
467 DISABLE_COPY_AND_ASSIGN (scoped_switch_fork_info
);
470 /* The fork_info for the previously selected infrun state, or nullptr if
471 we were already in the desired state, and nothing needs to be
473 struct fork_info
*m_oldfp
;
477 inferior_call_waitpid (ptid_t pptid
, int pid
)
479 struct objfile
*waitpid_objf
;
480 struct value
*waitpid_fn
= NULL
;
483 scoped_switch_fork_info
switch_fork_info (pptid
);
485 /* Get the waitpid_fn. */
486 if (lookup_minimal_symbol ("waitpid", NULL
, NULL
).minsym
!= NULL
)
487 waitpid_fn
= find_function_in_inferior ("waitpid", &waitpid_objf
);
489 && lookup_minimal_symbol ("_waitpid", NULL
, NULL
).minsym
!= NULL
)
490 waitpid_fn
= find_function_in_inferior ("_waitpid", &waitpid_objf
);
491 if (waitpid_fn
!= nullptr)
493 struct gdbarch
*gdbarch
= get_current_arch ();
494 struct value
*argv
[3], *retv
;
497 argv
[0] = value_from_longest (builtin_type (gdbarch
)->builtin_int
, pid
);
498 argv
[1] = value_from_pointer (builtin_type (gdbarch
)->builtin_data_ptr
, 0);
499 argv
[2] = value_from_longest (builtin_type (gdbarch
)->builtin_int
, 0);
501 retv
= call_function_by_hand (waitpid_fn
, NULL
, argv
);
503 if (value_as_long (retv
) >= 0)
510 /* Fork list <-> user interface. */
513 delete_checkpoint_command (const char *args
, int from_tty
)
516 struct fork_info
*fi
;
519 error (_("Requires argument (checkpoint id to delete)"));
521 ptid
= fork_id_to_ptid (parse_and_eval_long (args
));
522 if (ptid
== minus_one_ptid
)
523 error (_("No such checkpoint id, %s"), args
);
525 if (ptid
== inferior_ptid
)
527 Please switch to another checkpoint before deleting the current one"));
529 if (ptrace (PTRACE_KILL
, ptid
.pid (), 0, 0))
530 error (_("Unable to kill pid %s"), target_pid_to_str (ptid
).c_str ());
532 fi
= find_fork_ptid (ptid
);
534 pptid
= fi
->parent_ptid
;
537 gdb_printf (_("Killed %s\n"), target_pid_to_str (ptid
).c_str ());
541 if (pptid
== null_ptid
)
544 /* Wait to collect the inferior's exit status. Do not check whether
545 this succeeds though, since we may be dealing with a process that we
546 attached to. Such a process will only report its exit status to its
548 waitpid (ptid
.pid (), &status
, 0);
552 /* If fi->parent_ptid is not a part of lwp but it's a part of checkpoint
553 list, waitpid the ptid.
554 If fi->parent_ptid is a part of lwp and it is stopped, waitpid the
556 thread_info
*parent
= linux_target
->find_thread (pptid
);
557 if ((parent
== NULL
&& find_fork_ptid (pptid
))
558 || (parent
!= NULL
&& parent
->state
== THREAD_STOPPED
))
560 if (inferior_call_waitpid (pptid
, ptid
.pid ()))
561 warning (_("Unable to wait pid %s"),
562 target_pid_to_str (ptid
).c_str ());
567 detach_checkpoint_command (const char *args
, int from_tty
)
572 error (_("Requires argument (checkpoint id to detach)"));
574 ptid
= fork_id_to_ptid (parse_and_eval_long (args
));
575 if (ptid
== minus_one_ptid
)
576 error (_("No such checkpoint id, %s"), args
);
578 if (ptid
== inferior_ptid
)
580 Please switch to another checkpoint before detaching the current one"));
582 if (ptrace (PTRACE_DETACH
, ptid
.pid (), 0, 0))
583 error (_("Unable to detach %s"), target_pid_to_str (ptid
).c_str ());
586 gdb_printf (_("Detached %s\n"), target_pid_to_str (ptid
).c_str ());
591 /* Print information about currently known checkpoints. */
594 info_checkpoints_command (const char *arg
, int from_tty
)
596 struct gdbarch
*gdbarch
= get_current_arch ();
598 bool printed
= false;
601 requested
= (int) parse_and_eval_long (arg
);
603 for (const fork_info
&fi
: fork_list
)
605 if (requested
> 0 && fi
.num
!= requested
)
609 bool is_current
= fi
.ptid
== inferior_ptid
;
615 gdb_printf ("%d %s", fi
.num
, target_pid_to_str (fi
.ptid
).c_str ());
617 gdb_printf (_(" (main process)"));
619 if (is_current
&& inferior_thread ()->state
== THREAD_RUNNING
)
621 gdb_printf (_(" <running>\n"));
625 gdb_printf (_(" at "));
628 ? regcache_read_pc (get_thread_regcache (inferior_thread ()))
630 gdb_puts (paddress (gdbarch
, pc
));
632 symtab_and_line sal
= find_pc_line (pc
, 0);
634 gdb_printf (_(", file %s"),
635 symtab_to_filename_for_display (sal
.symtab
));
637 gdb_printf (_(", line %d"), sal
.line
);
638 if (!sal
.symtab
&& !sal
.line
)
640 struct bound_minimal_symbol msym
;
642 msym
= lookup_minimal_symbol_by_pc (pc
);
644 gdb_printf (", <%s>", msym
.minsym
->linkage_name ());
653 gdb_printf (_("No checkpoint number %d.\n"), requested
);
655 gdb_printf (_("No checkpoints.\n"));
659 /* The PID of the process we're checkpointing. */
660 static int checkpointing_pid
= 0;
663 linux_fork_checkpointing_p (int pid
)
665 return (checkpointing_pid
== pid
);
668 /* Return true if the current inferior is multi-threaded. */
671 inf_has_multiple_threads ()
675 /* Return true as soon as we see the second thread of the current
677 for (thread_info
*tp ATTRIBUTE_UNUSED
: current_inferior ()->threads ())
685 checkpoint_command (const char *args
, int from_tty
)
687 struct objfile
*fork_objf
;
688 struct gdbarch
*gdbarch
;
689 struct target_waitstatus last_target_waitstatus
;
690 ptid_t last_target_ptid
;
691 struct value
*fork_fn
= NULL
, *ret
;
692 struct fork_info
*fp
;
695 if (!target_has_execution ())
696 error (_("The program is not being run."));
698 /* Ensure that the inferior is not multithreaded. */
699 update_thread_list ();
700 if (inf_has_multiple_threads ())
701 error (_("checkpoint: can't checkpoint multiple threads."));
703 /* Make the inferior fork, record its (and gdb's) state. */
705 if (lookup_minimal_symbol ("fork", NULL
, NULL
).minsym
!= NULL
)
706 fork_fn
= find_function_in_inferior ("fork", &fork_objf
);
708 if (lookup_minimal_symbol ("_fork", NULL
, NULL
).minsym
!= NULL
)
709 fork_fn
= find_function_in_inferior ("fork", &fork_objf
);
711 error (_("checkpoint: can't find fork function in inferior."));
713 gdbarch
= fork_objf
->arch ();
714 ret
= value_from_longest (builtin_type (gdbarch
)->builtin_int
, 0);
716 /* Tell linux-nat.c that we're checkpointing this inferior. */
718 scoped_restore save_pid
719 = make_scoped_restore (&checkpointing_pid
, inferior_ptid
.pid ());
721 ret
= call_function_by_hand (fork_fn
, NULL
, {});
724 if (!ret
) /* Probably can't happen. */
725 error (_("checkpoint: call_function_by_hand returned null."));
727 retpid
= value_as_long (ret
);
728 get_last_target_status (nullptr, &last_target_ptid
, &last_target_waitstatus
);
730 fp
= find_fork_pid (retpid
);
736 gdb_printf (_("checkpoint %d: fork returned pid %ld.\n"),
737 fp
!= NULL
? fp
->num
: -1, (long) retpid
);
740 parent_pid
= last_target_ptid
.lwp ();
742 parent_pid
= last_target_ptid
.pid ();
743 gdb_printf (_(" gdb says parent = %ld.\n"),
749 error (_("Failed to find new fork"));
753 /* Special case -- if this is the first fork in the list (the
754 list was hitherto empty), then add inferior_ptid first, as a
755 special zeroeth fork id. */
756 fork_list
.emplace_front (inferior_ptid
.pid ());
759 fork_save_infrun_state (fp
);
760 fp
->parent_ptid
= last_target_ptid
;
764 linux_fork_context (struct fork_info
*newfp
, int from_tty
)
766 /* Now we attempt to switch processes. */
767 struct fork_info
*oldfp
;
769 gdb_assert (newfp
!= NULL
);
771 oldfp
= find_fork_ptid (inferior_ptid
);
772 gdb_assert (oldfp
!= NULL
);
774 fork_save_infrun_state (oldfp
);
775 remove_breakpoints ();
776 fork_load_infrun_state (newfp
);
777 insert_breakpoints ();
779 gdb_printf (_("Switching to %s\n"),
780 target_pid_to_str (inferior_ptid
).c_str ());
782 print_stack_frame (get_selected_frame (NULL
), 1, SRC_AND_LOC
, 1);
785 /* Switch inferior process (checkpoint) context, by checkpoint id. */
787 restart_command (const char *args
, int from_tty
)
789 struct fork_info
*fp
;
792 error (_("Requires argument (checkpoint id to restart)"));
794 if ((fp
= find_fork_id (parse_and_eval_long (args
))) == NULL
)
795 error (_("Not found: checkpoint id %s"), args
);
797 linux_fork_context (fp
, from_tty
);
800 void _initialize_linux_fork ();
802 _initialize_linux_fork ()
804 /* Checkpoint command: create a fork of the inferior process
805 and set it aside for later debugging. */
807 add_com ("checkpoint", class_obscure
, checkpoint_command
, _("\
808 Fork a duplicate process (experimental)."));
810 /* Restart command: restore the context of a specified checkpoint
813 add_com ("restart", class_obscure
, restart_command
, _("\
814 Restore program context from a checkpoint.\n\
816 Argument N is checkpoint ID, as displayed by 'info checkpoints'."));
818 /* Delete checkpoint command: kill the process and remove it from
821 add_cmd ("checkpoint", class_obscure
, delete_checkpoint_command
, _("\
822 Delete a checkpoint (experimental)."),
825 /* Detach checkpoint command: release the process to run independently,
826 and remove it from the fork list. */
828 add_cmd ("checkpoint", class_obscure
, detach_checkpoint_command
, _("\
829 Detach from a checkpoint (experimental)."),
832 /* Info checkpoints command: list all forks/checkpoints
833 currently under gdb's control. */
835 add_info ("checkpoints", info_checkpoints_command
,
836 _("IDs of currently known checkpoints."));