1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005-2014 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 "gdb_assert.h"
30 #include "linux-fork.h"
31 #include "linux-nat.h"
32 #include "gdbthread.h"
35 #include <sys/ptrace.h>
40 struct fork_info *fork_list;
41 static int highest_fork_num;
43 /* Prevent warning from -Wmissing-prototypes. */
44 extern void _initialize_linux_fork (void);
46 /* Fork list data structure: */
49 struct fork_info *next;
52 int num; /* Convenient handle (GDB fork id). */
53 struct regcache *savedregs; /* Convenient for info fork, saves
54 having to actually switch contexts. */
55 int clobber_regs; /* True if we should restore saved regs. */
56 off_t *filepos; /* Set of open file descriptors' offsets. */
60 /* Fork list methods: */
65 return (fork_list != NULL);
68 /* Add a fork to the internal fork list. */
75 if (fork_list == NULL && pid != ptid_get_pid (inferior_ptid))
77 /* Special case -- if this is the first fork in the list
78 (the list is hitherto empty), and if this new fork is
79 NOT the current inferior_ptid, then add inferior_ptid
80 first, as a special zeroeth fork id. */
81 highest_fork_num = -1;
82 add_fork (ptid_get_pid (inferior_ptid)); /* safe recursion */
85 fp = XCNEW (struct fork_info);
86 fp->ptid = ptid_build (pid, pid, 0);
87 fp->num = ++highest_fork_num;
94 free_fork (struct fork_info *fp)
96 /* Notes on step-resume breakpoints: since this is a concern for
97 threads, let's convince ourselves that it's not a concern for
98 forks. There are two ways for a fork_info to be created. First,
99 by the checkpoint command, in which case we're at a gdb prompt
100 and there can't be any step-resume breakpoint. Second, by a fork
101 in the user program, in which case we *may* have stepped into the
102 fork call, but regardless of whether we follow the parent or the
103 child, we will return to the same place and the step-resume
104 breakpoint, if any, will take care of itself as usual. And
105 unlike threads, we do not save a private copy of the step-resume
106 breakpoint -- so we're OK. */
111 regcache_xfree (fp->savedregs);
119 delete_fork (ptid_t ptid)
121 struct fork_info *fp, *fpprev;
125 linux_nat_forget_process (ptid_get_pid (ptid));
127 for (fp = fork_list; fp; fpprev = fp, fp = fp->next)
128 if (ptid_equal (fp->ptid, ptid))
135 fpprev->next = fp->next;
137 fork_list = fp->next;
141 /* Special case: if there is now only one process in the list,
142 and if it is (hopefully!) the current inferior_ptid, then
143 remove it, leaving the list empty -- we're now down to the
144 default case of debugging a single process. */
145 if (fork_list != NULL && fork_list->next == NULL &&
146 ptid_equal (fork_list->ptid, inferior_ptid))
148 /* Last fork -- delete from list and handle as solo process
149 (should be a safe recursion). */
150 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 struct fork_info *fp;
160 for (fp = fork_list; fp; fp = fp->next)
161 if (ptid_equal (fp->ptid, ptid))
167 /* Find a fork_info by matching ID. */
168 static struct fork_info *
169 find_fork_id (int num)
171 struct fork_info *fp;
173 for (fp = fork_list; fp; fp = fp->next)
180 /* Find a fork_info by matching pid. */
181 extern struct fork_info *
182 find_fork_pid (pid_t pid)
184 struct fork_info *fp;
186 for (fp = fork_list; fp; fp = fp->next)
187 if (pid == ptid_get_pid (fp->ptid))
194 fork_id_to_ptid (int num)
196 struct fork_info *fork = find_fork_id (num);
200 return pid_to_ptid (-1);
204 init_fork_list (void)
206 struct fork_info *fp, *fpnext;
211 for (fp = fork_list; fp; fp = fpnext)
220 /* Fork list <-> gdb interface. */
222 /* Utility function for fork_load/fork_save.
223 Calls lseek in the (current) inferior process. */
226 call_lseek (int fd, off_t offset, int whence)
230 snprintf (&exp[0], sizeof (exp), "lseek (%d, %ld, %d)",
231 fd, (long) offset, whence);
232 return (off_t) parse_and_eval_long (&exp[0]);
235 /* Load infrun state for the fork PTID. */
238 fork_load_infrun_state (struct fork_info *fp)
240 extern void nullify_last_target_wait_ptid ();
243 linux_nat_switch_fork (fp->ptid);
245 if (fp->savedregs && fp->clobber_regs)
246 regcache_cpy (get_current_regcache (), fp->savedregs);
248 registers_changed ();
249 reinit_frame_cache ();
251 stop_pc = regcache_read_pc (get_current_regcache ());
252 nullify_last_target_wait_ptid ();
254 /* Now restore the file positions of open file descriptors. */
257 for (i = 0; i <= fp->maxfd; i++)
258 if (fp->filepos[i] != (off_t) -1)
259 call_lseek (i, fp->filepos[i], SEEK_SET);
260 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
261 this is native-only. If it ever has to be cross, we'll have
266 /* Save infrun state for the fork PTID.
267 Exported for use by linux child_follow_fork. */
270 fork_save_infrun_state (struct fork_info *fp, int clobber_regs)
277 regcache_xfree (fp->savedregs);
279 fp->savedregs = regcache_dup (get_current_regcache ());
280 fp->clobber_regs = clobber_regs;
284 /* Now save the 'state' (file position) of all open file descriptors.
285 Unfortunately fork does not take care of that for us... */
286 snprintf (path, PATH_MAX, "/proc/%ld/fd",
287 (long) ptid_get_pid (fp->ptid));
288 if ((d = opendir (path)) != NULL)
293 while ((de = readdir (d)) != NULL)
295 /* Count open file descriptors (actually find highest
297 tmp = strtol (&de->d_name[0], NULL, 10);
301 /* Allocate array of file positions. */
302 fp->filepos = xrealloc (fp->filepos,
303 (fp->maxfd + 1) * sizeof (*fp->filepos));
305 /* Initialize to -1 (invalid). */
306 for (tmp = 0; tmp <= fp->maxfd; tmp++)
307 fp->filepos[tmp] = -1;
309 /* Now find actual file positions. */
311 while ((de = readdir (d)) != NULL)
312 if (isdigit (de->d_name[0]))
314 tmp = strtol (&de->d_name[0], NULL, 10);
315 fp->filepos[tmp] = call_lseek (tmp, 0, SEEK_CUR);
322 /* Kill 'em all, let God sort 'em out... */
325 linux_fork_killall (void)
327 /* Walk list and kill every pid. No need to treat the
328 current inferior_ptid as special (we do not return a
329 status for it) -- however any process may be a child
330 or a parent, so may get a SIGCHLD from a previously
331 killed child. Wait them all out. */
332 struct fork_info *fp;
336 for (fp = fork_list; fp; fp = fp->next)
338 pid = ptid_get_pid (fp->ptid);
340 /* Use SIGKILL instead of PTRACE_KILL because the former works even
341 if the thread is running, while the later doesn't. */
343 ret = waitpid (pid, &status, 0);
344 /* We might get a SIGCHLD instead of an exit status. This is
345 aggravated by the first kill above - a child has just
346 died. MVS comment cut-and-pasted from linux-nat. */
347 } while (ret == pid && WIFSTOPPED (status));
349 init_fork_list (); /* Clear list, prepare to start fresh. */
352 /* The current inferior_ptid has exited, but there are other viable
353 forks to debug. Delete the exiting one and context-switch to the
357 linux_fork_mourn_inferior (void)
359 /* Wait just one more time to collect the inferior's exit status.
360 Do not check whether this succeeds though, since we may be
361 dealing with a process that we attached to. Such a process will
362 only report its exit status to its original parent. */
365 waitpid (ptid_get_pid (inferior_ptid), &status, 0);
367 /* OK, presumably inferior_ptid is the one who has exited.
368 We need to delete that one from the fork_list, and switch
369 to the next available fork. */
370 delete_fork (inferior_ptid);
372 /* There should still be a fork - if there's only one left,
373 delete_fork won't remove it, because we haven't updated
374 inferior_ptid yet. */
375 gdb_assert (fork_list);
377 fork_load_infrun_state (fork_list);
378 printf_filtered (_("[Switching to %s]\n"),
379 target_pid_to_str (inferior_ptid));
381 /* If there's only one fork, switch back to non-fork mode. */
382 if (fork_list->next == NULL)
383 delete_fork (inferior_ptid);
386 /* The current inferior_ptid is being detached, but there are other
387 viable forks to debug. Detach and delete it and context-switch to
388 the first available. */
391 linux_fork_detach (const char *args, int from_tty)
393 /* OK, inferior_ptid is the one we are detaching from. We need to
394 delete it from the fork_list, and switch to the next available
397 if (ptrace (PTRACE_DETACH, ptid_get_pid (inferior_ptid), 0, 0))
398 error (_("Unable to detach %s"), target_pid_to_str (inferior_ptid));
400 delete_fork (inferior_ptid);
402 /* There should still be a fork - if there's only one left,
403 delete_fork won't remove it, because we haven't updated
404 inferior_ptid yet. */
405 gdb_assert (fork_list);
407 fork_load_infrun_state (fork_list);
410 printf_filtered (_("[Switching to %s]\n"),
411 target_pid_to_str (inferior_ptid));
413 /* If there's only one fork, switch back to non-fork mode. */
414 if (fork_list->next == NULL)
415 delete_fork (inferior_ptid);
419 inferior_call_waitpid_cleanup (void *fp)
421 struct fork_info *oldfp = fp;
425 /* Switch back to inferior_ptid. */
426 remove_breakpoints ();
427 fork_load_infrun_state (oldfp);
428 insert_breakpoints ();
433 inferior_call_waitpid (ptid_t pptid, int pid)
435 struct objfile *waitpid_objf;
436 struct value *waitpid_fn = NULL;
437 struct value *argv[4], *retv;
438 struct gdbarch *gdbarch = get_current_arch ();
439 struct fork_info *oldfp = NULL, *newfp = NULL;
440 struct cleanup *old_cleanup;
443 if (!ptid_equal (pptid, inferior_ptid))
445 /* Switch to pptid. */
446 oldfp = find_fork_ptid (inferior_ptid);
447 gdb_assert (oldfp != NULL);
448 newfp = find_fork_ptid (pptid);
449 gdb_assert (newfp != NULL);
450 fork_save_infrun_state (oldfp, 1);
451 remove_breakpoints ();
452 fork_load_infrun_state (newfp);
453 insert_breakpoints ();
456 old_cleanup = make_cleanup (inferior_call_waitpid_cleanup, oldfp);
458 /* Get the waitpid_fn. */
459 if (lookup_minimal_symbol ("waitpid", NULL, NULL).minsym != NULL)
460 waitpid_fn = find_function_in_inferior ("waitpid", &waitpid_objf);
462 && lookup_minimal_symbol ("_waitpid", NULL, NULL).minsym != NULL)
463 waitpid_fn = find_function_in_inferior ("_waitpid", &waitpid_objf);
468 argv[0] = value_from_longest (builtin_type (gdbarch)->builtin_int, pid);
469 argv[1] = value_from_pointer (builtin_type (gdbarch)->builtin_data_ptr, 0);
470 argv[2] = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
473 retv = call_function_by_hand (waitpid_fn, 3, argv);
474 if (value_as_long (retv) < 0)
480 do_cleanups (old_cleanup);
484 /* Fork list <-> user interface. */
487 delete_checkpoint_command (char *args, int from_tty)
490 struct fork_info *fi;
493 error (_("Requires argument (checkpoint id to delete)"));
495 ptid = fork_id_to_ptid (parse_and_eval_long (args));
496 if (ptid_equal (ptid, minus_one_ptid))
497 error (_("No such checkpoint id, %s"), args);
499 if (ptid_equal (ptid, inferior_ptid))
501 Please switch to another checkpoint before deleting the current one"));
503 if (ptrace (PTRACE_KILL, ptid_get_pid (ptid), 0, 0))
504 error (_("Unable to kill pid %s"), target_pid_to_str (ptid));
506 fi = find_fork_ptid (ptid);
508 pptid = fi->parent_ptid;
511 printf_filtered (_("Killed %s\n"), target_pid_to_str (ptid));
515 /* If fi->parent_ptid is not a part of lwp but it's a part of checkpoint
516 list, waitpid the ptid.
517 If fi->parent_ptid is a part of lwp and it is stoped, waitpid the
519 if ((!find_thread_ptid (pptid) && find_fork_ptid (pptid))
520 || (find_thread_ptid (pptid) && is_stopped (pptid)))
522 if (inferior_call_waitpid (pptid, ptid_get_pid (ptid)))
523 warning (_("Unable to wait pid %s"), target_pid_to_str (ptid));
528 detach_checkpoint_command (char *args, int from_tty)
533 error (_("Requires argument (checkpoint id to detach)"));
535 ptid = fork_id_to_ptid (parse_and_eval_long (args));
536 if (ptid_equal (ptid, minus_one_ptid))
537 error (_("No such checkpoint id, %s"), args);
539 if (ptid_equal (ptid, inferior_ptid))
541 Please switch to another checkpoint before detaching the current one"));
543 if (ptrace (PTRACE_DETACH, ptid_get_pid (ptid), 0, 0))
544 error (_("Unable to detach %s"), target_pid_to_str (ptid));
547 printf_filtered (_("Detached %s\n"), target_pid_to_str (ptid));
552 /* Print information about currently known checkpoints. */
555 info_checkpoints_command (char *arg, int from_tty)
557 struct gdbarch *gdbarch = get_current_arch ();
558 struct symtab_and_line sal;
559 struct fork_info *fp;
562 struct fork_info *printed = NULL;
565 requested = (int) parse_and_eval_long (arg);
567 for (fp = fork_list; fp; fp = fp->next)
569 if (requested > 0 && fp->num != requested)
573 if (ptid_equal (fp->ptid, inferior_ptid))
575 printf_filtered ("* ");
576 pc = regcache_read_pc (get_current_regcache ());
580 printf_filtered (" ");
581 pc = regcache_read_pc (fp->savedregs);
583 printf_filtered ("%d %s", fp->num, target_pid_to_str (fp->ptid));
585 printf_filtered (_(" (main process)"));
586 printf_filtered (_(" at "));
587 fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
589 sal = find_pc_line (pc, 0);
591 printf_filtered (_(", file %s"),
592 symtab_to_filename_for_display (sal.symtab));
594 printf_filtered (_(", line %d"), sal.line);
595 if (!sal.symtab && !sal.line)
597 struct bound_minimal_symbol msym;
599 msym = lookup_minimal_symbol_by_pc (pc);
601 printf_filtered (", <%s>", MSYMBOL_LINKAGE_NAME (msym.minsym));
604 putchar_filtered ('\n');
609 printf_filtered (_("No checkpoint number %d.\n"), requested);
611 printf_filtered (_("No checkpoints.\n"));
615 /* The PID of the process we're checkpointing. */
616 static int checkpointing_pid = 0;
619 linux_fork_checkpointing_p (int pid)
621 return (checkpointing_pid == pid);
624 /* Callback for iterate over threads. Used to check whether
625 the current inferior is multi-threaded. Returns true as soon
626 as it sees the second thread of the current inferior. */
629 inf_has_multiple_thread_cb (struct thread_info *tp, void *data)
631 int *count_p = (int *) data;
633 if (current_inferior ()->pid == ptid_get_pid (tp->ptid))
636 /* Stop the iteration if multiple threads have been detected. */
640 /* Return true if the current inferior is multi-threaded. */
643 inf_has_multiple_threads (void)
647 iterate_over_threads (inf_has_multiple_thread_cb, &count);
652 checkpoint_command (char *args, int from_tty)
654 struct objfile *fork_objf;
655 struct gdbarch *gdbarch;
656 struct target_waitstatus last_target_waitstatus;
657 ptid_t last_target_ptid;
658 struct value *fork_fn = NULL, *ret;
659 struct fork_info *fp;
661 struct cleanup *old_chain;
663 if (!target_has_execution)
664 error (_("The program is not being run."));
666 /* Ensure that the inferior is not multithreaded. */
667 update_thread_list ();
668 if (inf_has_multiple_threads ())
669 error (_("checkpoint: can't checkpoint multiple threads."));
671 /* Make the inferior fork, record its (and gdb's) state. */
673 if (lookup_minimal_symbol ("fork", NULL, NULL).minsym != NULL)
674 fork_fn = find_function_in_inferior ("fork", &fork_objf);
676 if (lookup_minimal_symbol ("_fork", NULL, NULL).minsym != NULL)
677 fork_fn = find_function_in_inferior ("fork", &fork_objf);
679 error (_("checkpoint: can't find fork function in inferior."));
681 gdbarch = get_objfile_arch (fork_objf);
682 ret = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
684 /* Tell linux-nat.c that we're checkpointing this inferior. */
685 old_chain = make_cleanup_restore_integer (&checkpointing_pid);
686 checkpointing_pid = ptid_get_pid (inferior_ptid);
688 ret = call_function_by_hand (fork_fn, 0, &ret);
689 do_cleanups (old_chain);
690 if (!ret) /* Probably can't happen. */
691 error (_("checkpoint: call_function_by_hand returned null."));
693 retpid = value_as_long (ret);
694 get_last_target_status (&last_target_ptid, &last_target_waitstatus);
699 printf_filtered (_("checkpoint: fork returned pid %ld.\n"),
703 parent_pid = ptid_get_lwp (last_target_ptid);
705 parent_pid = ptid_get_pid (last_target_ptid);
706 printf_filtered (_(" gdb says parent = %ld.\n"),
711 fp = find_fork_pid (retpid);
713 error (_("Failed to find new fork"));
714 fork_save_infrun_state (fp, 1);
715 fp->parent_ptid = last_target_ptid;
719 linux_fork_context (struct fork_info *newfp, int from_tty)
721 /* Now we attempt to switch processes. */
722 struct fork_info *oldfp;
724 gdb_assert (newfp != NULL);
726 oldfp = find_fork_ptid (inferior_ptid);
727 gdb_assert (oldfp != NULL);
729 fork_save_infrun_state (oldfp, 1);
730 remove_breakpoints ();
731 fork_load_infrun_state (newfp);
732 insert_breakpoints ();
734 printf_filtered (_("Switching to %s\n"),
735 target_pid_to_str (inferior_ptid));
737 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
740 /* Switch inferior process (checkpoint) context, by checkpoint id. */
742 restart_command (char *args, int from_tty)
744 struct fork_info *fp;
747 error (_("Requires argument (checkpoint id to restart)"));
749 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
750 error (_("Not found: checkpoint id %s"), args);
752 linux_fork_context (fp, from_tty);
756 _initialize_linux_fork (void)
760 /* Checkpoint command: create a fork of the inferior process
761 and set it aside for later debugging. */
763 add_com ("checkpoint", class_obscure, checkpoint_command, _("\
764 Fork a duplicate process (experimental)."));
766 /* Restart command: restore the context of a specified checkpoint
769 add_com ("restart", class_obscure, restart_command, _("\
770 restart <n>: restore program context from a checkpoint.\n\
771 Argument 'n' is checkpoint ID, as displayed by 'info checkpoints'."));
773 /* Delete checkpoint command: kill the process and remove it from
776 add_cmd ("checkpoint", class_obscure, delete_checkpoint_command, _("\
777 Delete a checkpoint (experimental)."),
780 /* Detach checkpoint command: release the process to run independently,
781 and remove it from the fork list. */
783 add_cmd ("checkpoint", class_obscure, detach_checkpoint_command, _("\
784 Detach from a checkpoint (experimental)."),
787 /* Info checkpoints command: list all forks/checkpoints
788 currently under gdb's control. */
790 add_info ("checkpoints", info_checkpoints_command,
791 _("IDs of currently known checkpoints."));