1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005-2019 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/>. */
21 #include "arch-utils.h"
28 #include "linux-fork.h"
29 #include "linux-nat.h"
30 #include "gdbthread.h"
33 #include "nat/gdb_ptrace.h"
34 #include "common/gdb_wait.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 /* True if we should restore saved regs. */
83 /* Set of open file descriptors' offsets. */
84 off_t
*filepos
= nullptr;
89 static std::list
<fork_info
> fork_list
;
90 static int highest_fork_num
;
92 /* Fork list methods: */
97 return !fork_list
.empty ();
100 /* Return the last fork in the list. */
102 static struct fork_info
*
103 find_last_fork (void)
105 if (fork_list
.empty ())
108 return &fork_list
.back ();
111 /* Return true iff there's one fork in the list. */
116 return (!fork_list
.empty ()
117 && &fork_list
.front () == &fork_list
.back ());
120 /* Add a new fork to the internal fork list. */
125 fork_list
.emplace_back (pid
);
128 highest_fork_num
= 0;
130 fork_info
*fp
= &fork_list
.back ();
131 fp
->num
= ++highest_fork_num
;
135 delete_fork (ptid_t ptid
)
137 linux_target
->low_forget_process (ptid
.pid ());
139 for (auto it
= fork_list
.begin (); it
!= fork_list
.end (); ++it
)
140 if (it
->ptid
== ptid
)
142 fork_list
.erase (it
);
144 /* Special case: if there is now only one process in the list,
145 and if it is (hopefully!) the current inferior_ptid, then
146 remove it, leaving the list empty -- we're now down to the
147 default case of debugging a single process. */
148 if (one_fork_p () && fork_list
.front ().ptid
== inferior_ptid
)
150 /* Last fork -- delete from list and handle as solo
151 process (should be a safe recursion). */
152 delete_fork (inferior_ptid
);
158 /* Find a fork_info by matching PTID. */
159 static struct fork_info
*
160 find_fork_ptid (ptid_t ptid
)
162 for (fork_info
&fi
: fork_list
)
169 /* Find a fork_info by matching ID. */
170 static struct fork_info
*
171 find_fork_id (int num
)
173 for (fork_info
&fi
: fork_list
)
180 /* Find a fork_info by matching pid. */
181 extern struct fork_info
*
182 find_fork_pid (pid_t pid
)
184 for (fork_info
&fi
: fork_list
)
185 if (pid
== fi
.ptid
.pid ())
192 fork_id_to_ptid (int num
)
194 struct fork_info
*fork
= find_fork_id (num
);
201 /* Fork list <-> gdb interface. */
203 /* Utility function for fork_load/fork_save.
204 Calls lseek in the (current) inferior process. */
207 call_lseek (int fd
, off_t offset
, int whence
)
211 snprintf (&exp
[0], sizeof (exp
), "(long) lseek (%d, %ld, %d)",
212 fd
, (long) offset
, whence
);
213 return (off_t
) parse_and_eval_long (&exp
[0]);
216 /* Load infrun state for the fork PTID. */
219 fork_load_infrun_state (struct fork_info
*fp
)
221 extern void nullify_last_target_wait_ptid ();
224 linux_nat_switch_fork (fp
->ptid
);
226 if (fp
->savedregs
&& fp
->clobber_regs
)
227 get_current_regcache ()->restore (fp
->savedregs
);
229 registers_changed ();
230 reinit_frame_cache ();
232 inferior_thread ()->suspend
.stop_pc
233 = regcache_read_pc (get_current_regcache ());
234 nullify_last_target_wait_ptid ();
236 /* Now restore the file positions of open file descriptors. */
239 for (i
= 0; i
<= fp
->maxfd
; i
++)
240 if (fp
->filepos
[i
] != (off_t
) -1)
241 call_lseek (i
, fp
->filepos
[i
], SEEK_SET
);
242 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
243 this is native-only. If it ever has to be cross, we'll have
248 /* Save infrun state for the fork PTID.
249 Exported for use by linux child_follow_fork. */
252 fork_save_infrun_state (struct fork_info
*fp
, int clobber_regs
)
259 delete fp
->savedregs
;
261 fp
->savedregs
= new readonly_detached_regcache (*get_current_regcache ());
262 fp
->pc
= regcache_read_pc (get_current_regcache ());
263 fp
->clobber_regs
= clobber_regs
;
267 /* Now save the 'state' (file position) of all open file descriptors.
268 Unfortunately fork does not take care of that for us... */
269 snprintf (path
, PATH_MAX
, "/proc/%ld/fd",
270 (long) fp
->ptid
.pid ());
271 if ((d
= opendir (path
)) != NULL
)
276 while ((de
= readdir (d
)) != NULL
)
278 /* Count open file descriptors (actually find highest
280 tmp
= strtol (&de
->d_name
[0], NULL
, 10);
284 /* Allocate array of file positions. */
285 fp
->filepos
= XRESIZEVEC (off_t
, fp
->filepos
, fp
->maxfd
+ 1);
287 /* Initialize to -1 (invalid). */
288 for (tmp
= 0; tmp
<= fp
->maxfd
; tmp
++)
289 fp
->filepos
[tmp
] = -1;
291 /* Now find actual file positions. */
293 while ((de
= readdir (d
)) != NULL
)
294 if (isdigit (de
->d_name
[0]))
296 tmp
= strtol (&de
->d_name
[0], NULL
, 10);
297 fp
->filepos
[tmp
] = call_lseek (tmp
, 0, SEEK_CUR
);
304 /* Kill 'em all, let God sort 'em out... */
307 linux_fork_killall (void)
309 /* Walk list and kill every pid. No need to treat the
310 current inferior_ptid as special (we do not return a
311 status for it) -- however any process may be a child
312 or a parent, so may get a SIGCHLD from a previously
313 killed child. Wait them all out. */
315 for (fork_info
&fi
: fork_list
)
317 pid_t pid
= fi
.ptid
.pid ();
321 /* Use SIGKILL instead of PTRACE_KILL because the former works even
322 if the thread is running, while the later doesn't. */
324 ret
= waitpid (pid
, &status
, 0);
325 /* We might get a SIGCHLD instead of an exit status. This is
326 aggravated by the first kill above - a child has just
327 died. MVS comment cut-and-pasted from linux-nat. */
328 } while (ret
== pid
&& WIFSTOPPED (status
));
331 /* Clear list, prepare to start fresh. */
335 /* The current inferior_ptid has exited, but there are other viable
336 forks to debug. Delete the exiting one and context-switch to the
340 linux_fork_mourn_inferior (void)
342 struct fork_info
*last
;
345 /* Wait just one more time to collect the inferior's exit status.
346 Do not check whether this succeeds though, since we may be
347 dealing with a process that we attached to. Such a process will
348 only report its exit status to its original parent. */
349 waitpid (inferior_ptid
.pid (), &status
, 0);
351 /* OK, presumably inferior_ptid is the one who has exited.
352 We need to delete that one from the fork_list, and switch
353 to the next available fork. */
354 delete_fork (inferior_ptid
);
356 /* There should still be a fork - if there's only one left,
357 delete_fork won't remove it, because we haven't updated
358 inferior_ptid yet. */
359 gdb_assert (!fork_list
.empty ());
361 last
= find_last_fork ();
362 fork_load_infrun_state (last
);
363 printf_filtered (_("[Switching to %s]\n"),
364 target_pid_to_str (inferior_ptid
));
366 /* If there's only one fork, switch back to non-fork mode. */
368 delete_fork (inferior_ptid
);
371 /* The current inferior_ptid is being detached, but there are other
372 viable forks to debug. Detach and delete it and context-switch to
373 the first available. */
376 linux_fork_detach (int from_tty
)
378 /* OK, inferior_ptid is the one we are detaching from. We need to
379 delete it from the fork_list, and switch to the next available
382 if (ptrace (PTRACE_DETACH
, inferior_ptid
.pid (), 0, 0))
383 error (_("Unable to detach %s"), target_pid_to_str (inferior_ptid
));
385 delete_fork (inferior_ptid
);
387 /* There should still be a fork - if there's only one left,
388 delete_fork won't remove it, because we haven't updated
389 inferior_ptid yet. */
390 gdb_assert (!fork_list
.empty ());
392 fork_load_infrun_state (&fork_list
.front ());
395 printf_filtered (_("[Switching to %s]\n"),
396 target_pid_to_str (inferior_ptid
));
398 /* If there's only one fork, switch back to non-fork mode. */
400 delete_fork (inferior_ptid
);
403 /* Temporarily switch to the infrun state stored on the fork_info
404 identified by a given ptid_t. When this object goes out of scope,
405 restore the currently selected infrun state. */
407 class scoped_switch_fork_info
410 /* Switch to the infrun state held on the fork_info identified by
411 PPTID. If PPTID is the current inferior then no switch is done. */
412 explicit scoped_switch_fork_info (ptid_t pptid
)
415 if (pptid
!= inferior_ptid
)
417 struct fork_info
*newfp
= nullptr;
419 /* Switch to pptid. */
420 m_oldfp
= find_fork_ptid (inferior_ptid
);
421 gdb_assert (m_oldfp
!= nullptr);
422 newfp
= find_fork_ptid (pptid
);
423 gdb_assert (newfp
!= nullptr);
424 fork_save_infrun_state (m_oldfp
, 1);
425 remove_breakpoints ();
426 fork_load_infrun_state (newfp
);
427 insert_breakpoints ();
431 /* Restore the previously selected infrun state. If the constructor
432 didn't need to switch states, then nothing is done here either. */
433 ~scoped_switch_fork_info ()
435 if (m_oldfp
!= nullptr)
437 /* Switch back to inferior_ptid. */
440 remove_breakpoints ();
441 fork_load_infrun_state (m_oldfp
);
442 insert_breakpoints ();
444 CATCH (ex
, RETURN_MASK_ALL
)
446 warning (_("Couldn't restore checkpoint state in %s: %s"),
447 target_pid_to_str (m_oldfp
->ptid
), ex
.message
);
453 DISABLE_COPY_AND_ASSIGN (scoped_switch_fork_info
);
456 /* The fork_info for the previously selected infrun state, or nullptr if
457 we were already in the desired state, and nothing needs to be
459 struct fork_info
*m_oldfp
;
463 inferior_call_waitpid (ptid_t pptid
, int pid
)
465 struct objfile
*waitpid_objf
;
466 struct value
*waitpid_fn
= NULL
;
469 scoped_switch_fork_info
switch_fork_info (pptid
);
471 /* Get the waitpid_fn. */
472 if (lookup_minimal_symbol ("waitpid", NULL
, NULL
).minsym
!= NULL
)
473 waitpid_fn
= find_function_in_inferior ("waitpid", &waitpid_objf
);
475 && lookup_minimal_symbol ("_waitpid", NULL
, NULL
).minsym
!= NULL
)
476 waitpid_fn
= find_function_in_inferior ("_waitpid", &waitpid_objf
);
477 if (waitpid_fn
!= nullptr)
479 struct gdbarch
*gdbarch
= get_current_arch ();
480 struct value
*argv
[3], *retv
;
483 argv
[0] = value_from_longest (builtin_type (gdbarch
)->builtin_int
, pid
);
484 argv
[1] = value_from_pointer (builtin_type (gdbarch
)->builtin_data_ptr
, 0);
485 argv
[2] = value_from_longest (builtin_type (gdbarch
)->builtin_int
, 0);
487 retv
= call_function_by_hand (waitpid_fn
, NULL
, argv
);
489 if (value_as_long (retv
) >= 0)
496 /* Fork list <-> user interface. */
499 delete_checkpoint_command (const char *args
, int from_tty
)
502 struct fork_info
*fi
;
505 error (_("Requires argument (checkpoint id to delete)"));
507 ptid
= fork_id_to_ptid (parse_and_eval_long (args
));
508 if (ptid
== minus_one_ptid
)
509 error (_("No such checkpoint id, %s"), args
);
511 if (ptid
== inferior_ptid
)
513 Please switch to another checkpoint before deleting the current one"));
515 if (ptrace (PTRACE_KILL
, ptid
.pid (), 0, 0))
516 error (_("Unable to kill pid %s"), target_pid_to_str (ptid
));
518 fi
= find_fork_ptid (ptid
);
520 pptid
= fi
->parent_ptid
;
523 printf_filtered (_("Killed %s\n"), target_pid_to_str (ptid
));
527 /* If fi->parent_ptid is not a part of lwp but it's a part of checkpoint
528 list, waitpid the ptid.
529 If fi->parent_ptid is a part of lwp and it is stopped, waitpid the
531 thread_info
*parent
= find_thread_ptid (pptid
);
532 if ((parent
== NULL
&& find_fork_ptid (pptid
))
533 || (parent
!= NULL
&& parent
->state
== THREAD_STOPPED
))
535 if (inferior_call_waitpid (pptid
, ptid
.pid ()))
536 warning (_("Unable to wait pid %s"), target_pid_to_str (ptid
));
541 detach_checkpoint_command (const char *args
, int from_tty
)
546 error (_("Requires argument (checkpoint id to detach)"));
548 ptid
= fork_id_to_ptid (parse_and_eval_long (args
));
549 if (ptid
== minus_one_ptid
)
550 error (_("No such checkpoint id, %s"), args
);
552 if (ptid
== inferior_ptid
)
554 Please switch to another checkpoint before detaching the current one"));
556 if (ptrace (PTRACE_DETACH
, ptid
.pid (), 0, 0))
557 error (_("Unable to detach %s"), target_pid_to_str (ptid
));
560 printf_filtered (_("Detached %s\n"), target_pid_to_str (ptid
));
565 /* Print information about currently known checkpoints. */
568 info_checkpoints_command (const char *arg
, int from_tty
)
570 struct gdbarch
*gdbarch
= get_current_arch ();
572 const fork_info
*printed
= NULL
;
575 requested
= (int) parse_and_eval_long (arg
);
577 for (const fork_info
&fi
: fork_list
)
579 if (requested
> 0 && fi
.num
!= requested
)
583 if (fi
.ptid
== inferior_ptid
)
584 printf_filtered ("* ");
586 printf_filtered (" ");
589 printf_filtered ("%d %s", fi
.num
, target_pid_to_str (fi
.ptid
));
591 printf_filtered (_(" (main process)"));
592 printf_filtered (_(" at "));
593 fputs_filtered (paddress (gdbarch
, pc
), gdb_stdout
);
595 symtab_and_line sal
= find_pc_line (pc
, 0);
597 printf_filtered (_(", file %s"),
598 symtab_to_filename_for_display (sal
.symtab
));
600 printf_filtered (_(", line %d"), sal
.line
);
601 if (!sal
.symtab
&& !sal
.line
)
603 struct bound_minimal_symbol msym
;
605 msym
= lookup_minimal_symbol_by_pc (pc
);
607 printf_filtered (", <%s>", MSYMBOL_LINKAGE_NAME (msym
.minsym
));
610 putchar_filtered ('\n');
615 printf_filtered (_("No checkpoint number %d.\n"), requested
);
617 printf_filtered (_("No checkpoints.\n"));
621 /* The PID of the process we're checkpointing. */
622 static int checkpointing_pid
= 0;
625 linux_fork_checkpointing_p (int pid
)
627 return (checkpointing_pid
== pid
);
630 /* Return true if the current inferior is multi-threaded. */
633 inf_has_multiple_threads ()
637 /* Return true as soon as we see the second thread of the current
639 for (thread_info
*tp ATTRIBUTE_UNUSED
: current_inferior ()->threads ())
647 checkpoint_command (const char *args
, int from_tty
)
649 struct objfile
*fork_objf
;
650 struct gdbarch
*gdbarch
;
651 struct target_waitstatus last_target_waitstatus
;
652 ptid_t last_target_ptid
;
653 struct value
*fork_fn
= NULL
, *ret
;
654 struct fork_info
*fp
;
657 if (!target_has_execution
)
658 error (_("The program is not being run."));
660 /* Ensure that the inferior is not multithreaded. */
661 update_thread_list ();
662 if (inf_has_multiple_threads ())
663 error (_("checkpoint: can't checkpoint multiple threads."));
665 /* Make the inferior fork, record its (and gdb's) state. */
667 if (lookup_minimal_symbol ("fork", NULL
, NULL
).minsym
!= NULL
)
668 fork_fn
= find_function_in_inferior ("fork", &fork_objf
);
670 if (lookup_minimal_symbol ("_fork", NULL
, NULL
).minsym
!= NULL
)
671 fork_fn
= find_function_in_inferior ("fork", &fork_objf
);
673 error (_("checkpoint: can't find fork function in inferior."));
675 gdbarch
= get_objfile_arch (fork_objf
);
676 ret
= value_from_longest (builtin_type (gdbarch
)->builtin_int
, 0);
678 /* Tell linux-nat.c that we're checkpointing this inferior. */
680 scoped_restore save_pid
681 = make_scoped_restore (&checkpointing_pid
, inferior_ptid
.pid ());
683 ret
= call_function_by_hand (fork_fn
, NULL
, {});
686 if (!ret
) /* Probably can't happen. */
687 error (_("checkpoint: call_function_by_hand returned null."));
689 retpid
= value_as_long (ret
);
690 get_last_target_status (&last_target_ptid
, &last_target_waitstatus
);
692 fp
= find_fork_pid (retpid
);
698 printf_filtered (_("checkpoint %d: fork returned pid %ld.\n"),
699 fp
!= NULL
? fp
->num
: -1, (long) retpid
);
702 parent_pid
= last_target_ptid
.lwp ();
704 parent_pid
= last_target_ptid
.pid ();
705 printf_filtered (_(" gdb says parent = %ld.\n"),
711 error (_("Failed to find new fork"));
715 /* Special case -- if this is the first fork in the list (the
716 list was hitherto empty), then add inferior_ptid first, as a
717 special zeroeth fork id. */
718 fork_list
.emplace_front (inferior_ptid
.pid ());
721 fork_save_infrun_state (fp
, 1);
722 fp
->parent_ptid
= last_target_ptid
;
726 linux_fork_context (struct fork_info
*newfp
, int from_tty
)
728 /* Now we attempt to switch processes. */
729 struct fork_info
*oldfp
;
731 gdb_assert (newfp
!= NULL
);
733 oldfp
= find_fork_ptid (inferior_ptid
);
734 gdb_assert (oldfp
!= NULL
);
736 fork_save_infrun_state (oldfp
, 1);
737 remove_breakpoints ();
738 fork_load_infrun_state (newfp
);
739 insert_breakpoints ();
741 printf_filtered (_("Switching to %s\n"),
742 target_pid_to_str (inferior_ptid
));
744 print_stack_frame (get_selected_frame (NULL
), 1, SRC_AND_LOC
, 1);
747 /* Switch inferior process (checkpoint) context, by checkpoint id. */
749 restart_command (const char *args
, int from_tty
)
751 struct fork_info
*fp
;
754 error (_("Requires argument (checkpoint id to restart)"));
756 if ((fp
= find_fork_id (parse_and_eval_long (args
))) == NULL
)
757 error (_("Not found: checkpoint id %s"), args
);
759 linux_fork_context (fp
, from_tty
);
763 _initialize_linux_fork (void)
765 /* Checkpoint command: create a fork of the inferior process
766 and set it aside for later debugging. */
768 add_com ("checkpoint", class_obscure
, checkpoint_command
, _("\
769 Fork a duplicate process (experimental)."));
771 /* Restart command: restore the context of a specified checkpoint
774 add_com ("restart", class_obscure
, restart_command
, _("\
775 restart N: restore program context from a checkpoint.\n\
776 Argument N is checkpoint ID, as displayed by 'info checkpoints'."));
778 /* Delete checkpoint command: kill the process and remove it from
781 add_cmd ("checkpoint", class_obscure
, delete_checkpoint_command
, _("\
782 Delete a checkpoint (experimental)."),
785 /* Detach checkpoint command: release the process to run independently,
786 and remove it from the fork list. */
788 add_cmd ("checkpoint", class_obscure
, detach_checkpoint_command
, _("\
789 Detach from a checkpoint (experimental)."),
792 /* Info checkpoints command: list all forks/checkpoints
793 currently under gdb's control. */
795 add_info ("checkpoints", info_checkpoints_command
,
796 _("IDs of currently known checkpoints."));