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"
21 #include "event-top.h"
25 #include "cli/cli-cmds.h"
28 #include "linux-fork.h"
29 #include "linux-nat.h"
30 #include "gdbthread.h"
33 #include "nat/gdb_ptrace.h"
34 #include "gdbsupport/gdb_wait.h"
35 #include "gdbsupport/eintr.h"
36 #include "target/waitstatus.h"
42 /* Fork list data structure: */
45 explicit fork_info (pid_t pid
)
52 /* Notes on step-resume breakpoints: since this is a concern for
53 threads, let's convince ourselves that it's not a concern for
54 forks. There are two ways for a fork_info to be created.
55 First, by the checkpoint command, in which case we're at a gdb
56 prompt and there can't be any step-resume breakpoint. Second,
57 by a fork in the user program, in which case we *may* have
58 stepped into the fork call, but regardless of whether we follow
59 the parent or the child, we will return to the same place and
60 the step-resume breakpoint, if any, will take care of itself as
61 usual. And unlike threads, we do not save a private copy of
62 the step-resume breakpoint -- so we're OK. */
70 ptid_t ptid
= null_ptid
;
71 ptid_t parent_ptid
= null_ptid
;
73 /* Convenient handle (GDB fork id). */
76 /* Convenient for info fork, saves having to actually switch
78 readonly_detached_regcache
*savedregs
= nullptr;
82 /* Set of open file descriptors' offsets. */
83 off_t
*filepos
= nullptr;
88 static std::list
<fork_info
> fork_list
;
89 static int highest_fork_num
;
91 /* Fork list methods: */
96 return !fork_list
.empty ();
99 /* Return the last fork in the list. */
101 static struct fork_info
*
102 find_last_fork (void)
104 if (fork_list
.empty ())
107 return &fork_list
.back ();
110 /* Return true iff there's one fork in the list. */
115 return fork_list
.size () == 1;
118 /* Add a new fork to the internal fork list. */
123 fork_list
.emplace_back (pid
);
126 highest_fork_num
= 0;
128 fork_info
*fp
= &fork_list
.back ();
129 fp
->num
= ++highest_fork_num
;
133 delete_fork (ptid_t ptid
)
135 linux_target
->low_forget_process (ptid
.pid ());
137 for (auto it
= fork_list
.begin (); it
!= fork_list
.end (); ++it
)
138 if (it
->ptid
== ptid
)
140 fork_list
.erase (it
);
142 /* Special case: if there is now only one process in the list,
143 and if it is (hopefully!) the current inferior_ptid, then
144 remove it, leaving the list empty -- we're now down to the
145 default case of debugging a single process. */
146 if (one_fork_p () && fork_list
.front ().ptid
== inferior_ptid
)
148 /* Last fork -- delete from list and handle as solo
149 process (should be a safe recursion). */
150 delete_fork (inferior_ptid
);
156 /* Find a fork_info by matching PTID. */
157 static struct fork_info
*
158 find_fork_ptid (ptid_t ptid
)
160 for (fork_info
&fi
: fork_list
)
167 /* Find a fork_info by matching ID. */
168 static struct fork_info
*
169 find_fork_id (int num
)
171 for (fork_info
&fi
: fork_list
)
178 /* Find a fork_info by matching pid. */
179 extern struct fork_info
*
180 find_fork_pid (pid_t pid
)
182 for (fork_info
&fi
: fork_list
)
183 if (pid
== fi
.ptid
.pid ())
190 fork_id_to_ptid (int num
)
192 struct fork_info
*fork
= find_fork_id (num
);
199 /* Fork list <-> gdb interface. */
201 /* Utility function for fork_load/fork_save.
202 Calls lseek in the (current) inferior process. */
205 call_lseek (int fd
, off_t offset
, int whence
)
209 snprintf (&exp
[0], sizeof (exp
), "(long) lseek (%d, %ld, %d)",
210 fd
, (long) offset
, whence
);
211 return (off_t
) parse_and_eval_long (&exp
[0]);
214 /* Load infrun state for the fork PTID. */
217 fork_load_infrun_state (struct fork_info
*fp
)
221 linux_nat_switch_fork (fp
->ptid
);
224 get_thread_regcache (inferior_thread ())->restore (fp
->savedregs
);
226 registers_changed ();
227 reinit_frame_cache ();
229 inferior_thread ()->set_stop_pc
230 (regcache_read_pc (get_thread_regcache (inferior_thread ())));
231 inferior_thread ()->set_executing (false);
232 inferior_thread ()->set_resumed (false);
233 nullify_last_target_wait_ptid ();
235 /* Now restore the file positions of open file descriptors. */
238 for (i
= 0; i
<= fp
->maxfd
; i
++)
239 if (fp
->filepos
[i
] != (off_t
) -1)
240 call_lseek (i
, fp
->filepos
[i
], SEEK_SET
);
241 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
242 this is native-only. If it ever has to be cross, we'll have
247 /* Save infrun state for the fork FP. */
250 fork_save_infrun_state (struct fork_info
*fp
)
257 delete fp
->savedregs
;
259 fp
->savedregs
= new readonly_detached_regcache
260 (*get_thread_regcache (inferior_thread ()));
261 fp
->pc
= regcache_read_pc (get_thread_regcache (inferior_thread ()));
263 /* Now save the 'state' (file position) of all open file descriptors.
264 Unfortunately fork does not take care of that for us... */
265 snprintf (path
, PATH_MAX
, "/proc/%ld/fd", (long) fp
->ptid
.pid ());
266 if ((d
= opendir (path
)) != NULL
)
271 while ((de
= readdir (d
)) != NULL
)
273 /* Count open file descriptors (actually find highest
275 tmp
= strtol (&de
->d_name
[0], NULL
, 10);
279 /* Allocate array of file positions. */
280 fp
->filepos
= XRESIZEVEC (off_t
, fp
->filepos
, fp
->maxfd
+ 1);
282 /* Initialize to -1 (invalid). */
283 for (tmp
= 0; tmp
<= fp
->maxfd
; tmp
++)
284 fp
->filepos
[tmp
] = -1;
286 /* Now find actual file positions. */
288 while ((de
= readdir (d
)) != NULL
)
289 if (isdigit (de
->d_name
[0]))
291 tmp
= strtol (&de
->d_name
[0], NULL
, 10);
292 fp
->filepos
[tmp
] = call_lseek (tmp
, 0, SEEK_CUR
);
298 /* Kill 'em all, let God sort 'em out... */
301 linux_fork_killall (void)
303 /* Walk list and kill every pid. No need to treat the
304 current inferior_ptid as special (we do not return a
305 status for it) -- however any process may be a child
306 or a parent, so may get a SIGCHLD from a previously
307 killed child. Wait them all out. */
309 for (fork_info
&fi
: fork_list
)
311 pid_t pid
= fi
.ptid
.pid ();
315 /* Use SIGKILL instead of PTRACE_KILL because the former works even
316 if the thread is running, while the later doesn't. */
318 ret
= gdb::waitpid (pid
, &status
, 0);
319 /* We might get a SIGCHLD instead of an exit status. This is
320 aggravated by the first kill above - a child has just
321 died. MVS comment cut-and-pasted from linux-nat. */
322 } while (ret
== pid
&& WIFSTOPPED (status
));
325 /* Clear list, prepare to start fresh. */
329 /* The current inferior_ptid has exited, but there are other viable
330 forks to debug. Delete the exiting one and context-switch to the
334 linux_fork_mourn_inferior (void)
336 struct fork_info
*last
;
339 /* Wait just one more time to collect the inferior's exit status.
340 Do not check whether this succeeds though, since we may be
341 dealing with a process that we attached to. Such a process will
342 only report its exit status to its original parent. */
343 gdb::waitpid (inferior_ptid
.pid (), &status
, 0);
345 /* OK, presumably inferior_ptid is the one who has exited.
346 We need to delete that one from the fork_list, and switch
347 to the next available fork. */
348 delete_fork (inferior_ptid
);
350 /* There should still be a fork - if there's only one left,
351 delete_fork won't remove it, because we haven't updated
352 inferior_ptid yet. */
353 gdb_assert (!fork_list
.empty ());
355 last
= find_last_fork ();
356 fork_load_infrun_state (last
);
357 gdb_printf (_("[Switching to %s]\n"),
358 target_pid_to_str (inferior_ptid
).c_str ());
360 /* If there's only one fork, switch back to non-fork mode. */
362 delete_fork (inferior_ptid
);
365 /* The current inferior_ptid is being detached, but there are other
366 viable forks to debug. Detach and delete it and context-switch to
367 the first available. */
370 linux_fork_detach (int from_tty
, lwp_info
*lp
)
372 gdb_assert (lp
!= nullptr);
373 gdb_assert (lp
->ptid
== inferior_ptid
);
375 /* OK, inferior_ptid is the one we are detaching from. We need to
376 delete it from the fork_list, and switch to the next available
377 fork. But before doing the detach, do make sure that the lwp
378 hasn't exited or been terminated first. */
380 if (lp
->waitstatus
.kind () != TARGET_WAITKIND_EXITED
381 && lp
->waitstatus
.kind () != TARGET_WAITKIND_THREAD_EXITED
382 && lp
->waitstatus
.kind () != TARGET_WAITKIND_SIGNALLED
)
384 if (ptrace (PTRACE_DETACH
, inferior_ptid
.pid (), 0, 0))
385 error (_("Unable to detach %s"),
386 target_pid_to_str (inferior_ptid
).c_str ());
389 delete_fork (inferior_ptid
);
391 /* There should still be a fork - if there's only one left,
392 delete_fork won't remove it, because we haven't updated
393 inferior_ptid yet. */
394 gdb_assert (!fork_list
.empty ());
396 fork_load_infrun_state (&fork_list
.front ());
399 gdb_printf (_("[Switching to %s]\n"),
400 target_pid_to_str (inferior_ptid
).c_str ());
402 /* If there's only one fork, switch back to non-fork mode. */
404 delete_fork (inferior_ptid
);
407 /* Temporarily switch to the infrun state stored on the fork_info
408 identified by a given ptid_t. When this object goes out of scope,
409 restore the currently selected infrun state. */
411 class scoped_switch_fork_info
414 /* Switch to the infrun state held on the fork_info identified by
415 PPTID. If PPTID is the current inferior then no switch is done. */
416 explicit scoped_switch_fork_info (ptid_t pptid
)
419 if (pptid
!= inferior_ptid
)
421 struct fork_info
*newfp
= nullptr;
423 /* Switch to pptid. */
424 m_oldfp
= find_fork_ptid (inferior_ptid
);
425 gdb_assert (m_oldfp
!= nullptr);
426 newfp
= find_fork_ptid (pptid
);
427 gdb_assert (newfp
!= nullptr);
428 fork_save_infrun_state (m_oldfp
);
429 remove_breakpoints ();
430 fork_load_infrun_state (newfp
);
431 insert_breakpoints ();
435 /* Restore the previously selected infrun state. If the constructor
436 didn't need to switch states, then nothing is done here either. */
437 ~scoped_switch_fork_info ()
439 if (m_oldfp
!= nullptr)
441 /* Switch back to inferior_ptid. */
444 remove_breakpoints ();
445 fork_load_infrun_state (m_oldfp
);
446 insert_breakpoints ();
448 catch (const gdb_exception_quit
&ex
)
450 /* We can't throw from a destructor, so re-set the quit flag
451 for later QUIT checking. */
454 catch (const gdb_exception_forced_quit
&ex
)
456 /* Like above, but (eventually) cause GDB to terminate by
457 setting sync_quit_force_run. */
458 set_force_quit_flag ();
460 catch (const gdb_exception
&ex
)
462 warning (_("Couldn't restore checkpoint state in %s: %s"),
463 target_pid_to_str (m_oldfp
->ptid
).c_str (),
469 DISABLE_COPY_AND_ASSIGN (scoped_switch_fork_info
);
472 /* The fork_info for the previously selected infrun state, or nullptr if
473 we were already in the desired state, and nothing needs to be
475 struct fork_info
*m_oldfp
;
479 inferior_call_waitpid (ptid_t pptid
, int pid
)
481 struct objfile
*waitpid_objf
;
482 struct value
*waitpid_fn
= NULL
;
485 scoped_switch_fork_info
switch_fork_info (pptid
);
487 /* Get the waitpid_fn. */
488 if (lookup_minimal_symbol (current_program_space
, "waitpid").minsym
490 waitpid_fn
= find_function_in_inferior ("waitpid", &waitpid_objf
);
492 && (lookup_minimal_symbol (current_program_space
, "_waitpid").minsym
494 waitpid_fn
= find_function_in_inferior ("_waitpid", &waitpid_objf
);
495 if (waitpid_fn
!= nullptr)
497 struct gdbarch
*gdbarch
= get_current_arch ();
498 struct value
*argv
[3], *retv
;
501 argv
[0] = value_from_longest (builtin_type (gdbarch
)->builtin_int
, pid
);
502 argv
[1] = value_from_pointer (builtin_type (gdbarch
)->builtin_data_ptr
, 0);
503 argv
[2] = value_from_longest (builtin_type (gdbarch
)->builtin_int
, 0);
505 retv
= call_function_by_hand (waitpid_fn
, NULL
, argv
);
507 if (value_as_long (retv
) >= 0)
514 /* Fork list <-> user interface. */
517 delete_checkpoint_command (const char *args
, int from_tty
)
520 struct fork_info
*fi
;
523 error (_("Requires argument (checkpoint id to delete)"));
525 ptid
= fork_id_to_ptid (parse_and_eval_long (args
));
526 if (ptid
== minus_one_ptid
)
527 error (_("No such checkpoint id, %s"), args
);
529 if (ptid
== inferior_ptid
)
531 Please switch to another checkpoint before deleting the current one"));
533 if (ptrace (PTRACE_KILL
, ptid
.pid (), 0, 0))
534 error (_("Unable to kill pid %s"), target_pid_to_str (ptid
).c_str ());
536 fi
= find_fork_ptid (ptid
);
538 pptid
= fi
->parent_ptid
;
541 gdb_printf (_("Killed %s\n"), target_pid_to_str (ptid
).c_str ());
545 if (pptid
== null_ptid
)
548 /* Wait to collect the inferior's exit status. Do not check whether
549 this succeeds though, since we may be dealing with a process that we
550 attached to. Such a process will only report its exit status to its
552 gdb::waitpid (ptid
.pid (), &status
, 0);
556 /* If fi->parent_ptid is not a part of lwp but it's a part of checkpoint
557 list, waitpid the ptid.
558 If fi->parent_ptid is a part of lwp and it is stopped, waitpid the
560 thread_info
*parent
= linux_target
->find_thread (pptid
);
561 if ((parent
== NULL
&& find_fork_ptid (pptid
))
562 || (parent
!= NULL
&& parent
->state
== THREAD_STOPPED
))
564 if (inferior_call_waitpid (pptid
, ptid
.pid ()))
565 warning (_("Unable to wait pid %s"),
566 target_pid_to_str (ptid
).c_str ());
571 detach_checkpoint_command (const char *args
, int from_tty
)
576 error (_("Requires argument (checkpoint id to detach)"));
578 ptid
= fork_id_to_ptid (parse_and_eval_long (args
));
579 if (ptid
== minus_one_ptid
)
580 error (_("No such checkpoint id, %s"), args
);
582 if (ptid
== inferior_ptid
)
584 Please switch to another checkpoint before detaching the current one"));
586 if (ptrace (PTRACE_DETACH
, ptid
.pid (), 0, 0))
587 error (_("Unable to detach %s"), target_pid_to_str (ptid
).c_str ());
590 gdb_printf (_("Detached %s\n"), target_pid_to_str (ptid
).c_str ());
595 /* Print information about currently known checkpoints. */
598 info_checkpoints_command (const char *arg
, int from_tty
)
600 struct gdbarch
*gdbarch
= get_current_arch ();
602 bool printed
= false;
605 requested
= (int) parse_and_eval_long (arg
);
607 for (const fork_info
&fi
: fork_list
)
609 if (requested
> 0 && fi
.num
!= requested
)
613 bool is_current
= fi
.ptid
== inferior_ptid
;
619 gdb_printf ("%d %s", fi
.num
, target_pid_to_str (fi
.ptid
).c_str ());
621 gdb_printf (_(" (main process)"));
623 if (is_current
&& inferior_thread ()->state
== THREAD_RUNNING
)
625 gdb_printf (_(" <running>\n"));
629 gdb_printf (_(" at "));
632 ? regcache_read_pc (get_thread_regcache (inferior_thread ()))
634 gdb_puts (paddress (gdbarch
, pc
));
636 symtab_and_line sal
= find_pc_line (pc
, 0);
638 gdb_printf (_(", file %s"),
639 symtab_to_filename_for_display (sal
.symtab
));
641 gdb_printf (_(", line %d"), sal
.line
);
642 if (!sal
.symtab
&& !sal
.line
)
644 bound_minimal_symbol msym
= lookup_minimal_symbol_by_pc (pc
);
646 gdb_printf (", <%s>", msym
.minsym
->linkage_name ());
655 gdb_printf (_("No checkpoint number %d.\n"), requested
);
657 gdb_printf (_("No checkpoints.\n"));
661 /* The PID of the process we're checkpointing. */
662 static int checkpointing_pid
= 0;
665 linux_fork_checkpointing_p (int pid
)
667 return (checkpointing_pid
== pid
);
670 /* Return true if the current inferior is multi-threaded. */
673 inf_has_multiple_threads ()
677 /* Return true as soon as we see the second thread of the current
679 for (thread_info
*tp ATTRIBUTE_UNUSED
: current_inferior ()->threads ())
687 checkpoint_command (const char *args
, int from_tty
)
689 struct objfile
*fork_objf
;
690 struct gdbarch
*gdbarch
;
691 struct target_waitstatus last_target_waitstatus
;
692 ptid_t last_target_ptid
;
693 struct value
*fork_fn
= NULL
, *ret
;
694 struct fork_info
*fp
;
697 if (!target_has_execution ())
698 error (_("The program is not being run."));
700 /* Ensure that the inferior is not multithreaded. */
701 update_thread_list ();
702 if (inf_has_multiple_threads ())
703 error (_("checkpoint: can't checkpoint multiple threads."));
705 /* Make the inferior fork, record its (and gdb's) state. */
707 if (lookup_minimal_symbol (current_program_space
, "fork").minsym
!= nullptr)
708 fork_fn
= find_function_in_inferior ("fork", &fork_objf
);
710 if (lookup_minimal_symbol (current_program_space
, "_fork").minsym
712 fork_fn
= find_function_in_inferior ("fork", &fork_objf
);
714 error (_("checkpoint: can't find fork function in inferior."));
716 gdbarch
= fork_objf
->arch ();
717 ret
= value_from_longest (builtin_type (gdbarch
)->builtin_int
, 0);
719 /* Tell linux-nat.c that we're checkpointing this inferior. */
721 scoped_restore save_pid
722 = make_scoped_restore (&checkpointing_pid
, inferior_ptid
.pid ());
724 ret
= call_function_by_hand (fork_fn
, NULL
, {});
727 if (!ret
) /* Probably can't happen. */
728 error (_("checkpoint: call_function_by_hand returned null."));
730 retpid
= value_as_long (ret
);
731 get_last_target_status (nullptr, &last_target_ptid
, &last_target_waitstatus
);
733 fp
= find_fork_pid (retpid
);
739 gdb_printf (_("checkpoint %d: fork returned pid %ld.\n"),
740 fp
!= NULL
? fp
->num
: -1, (long) retpid
);
743 parent_pid
= last_target_ptid
.lwp ();
745 parent_pid
= last_target_ptid
.pid ();
746 gdb_printf (_(" gdb says parent = %ld.\n"),
752 error (_("Failed to find new fork"));
756 /* Special case -- if this is the first fork in the list (the
757 list was hitherto empty), then add inferior_ptid first, as a
758 special zeroeth fork id. */
759 fork_list
.emplace_front (inferior_ptid
.pid ());
762 fork_save_infrun_state (fp
);
763 fp
->parent_ptid
= last_target_ptid
;
767 linux_fork_context (struct fork_info
*newfp
, int from_tty
)
769 /* Now we attempt to switch processes. */
770 struct fork_info
*oldfp
;
772 gdb_assert (newfp
!= NULL
);
774 oldfp
= find_fork_ptid (inferior_ptid
);
775 gdb_assert (oldfp
!= NULL
);
777 fork_save_infrun_state (oldfp
);
778 remove_breakpoints ();
779 fork_load_infrun_state (newfp
);
780 insert_breakpoints ();
782 gdb_printf (_("Switching to %s\n"),
783 target_pid_to_str (inferior_ptid
).c_str ());
785 print_stack_frame (get_selected_frame (NULL
), 1, SRC_AND_LOC
, 1);
788 /* Switch inferior process (checkpoint) context, by checkpoint id. */
790 restart_command (const char *args
, int from_tty
)
792 struct fork_info
*fp
;
795 error (_("Requires argument (checkpoint id to restart)"));
797 if ((fp
= find_fork_id (parse_and_eval_long (args
))) == NULL
)
798 error (_("Not found: checkpoint id %s"), args
);
800 linux_fork_context (fp
, from_tty
);
803 void _initialize_linux_fork ();
805 _initialize_linux_fork ()
807 /* Checkpoint command: create a fork of the inferior process
808 and set it aside for later debugging. */
810 add_com ("checkpoint", class_obscure
, checkpoint_command
, _("\
811 Fork a duplicate process (experimental)."));
813 /* Restart command: restore the context of a specified checkpoint
816 add_com ("restart", class_obscure
, restart_command
, _("\
817 Restore program context from a checkpoint.\n\
819 Argument N is checkpoint ID, as displayed by 'info checkpoints'."));
821 /* Delete checkpoint command: kill the process and remove it from
824 add_cmd ("checkpoint", class_obscure
, delete_checkpoint_command
, _("\
825 Delete a checkpoint (experimental)."),
828 /* Detach checkpoint command: release the process to run independently,
829 and remove it from the fork list. */
831 add_cmd ("checkpoint", class_obscure
, detach_checkpoint_command
, _("\
832 Detach from a checkpoint (experimental)."),
835 /* Info checkpoints command: list all forks/checkpoints
836 currently under gdb's control. */
838 add_info ("checkpoints", info_checkpoints_command
,
839 _("IDs of currently known checkpoints."));