1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005-2016 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"
38 struct fork_info *fork_list;
39 static int highest_fork_num;
41 /* Prevent warning from -Wmissing-prototypes. */
42 extern void _initialize_linux_fork (void);
44 /* Fork list data structure: */
47 struct fork_info *next;
50 int num; /* Convenient handle (GDB fork id). */
51 struct regcache *savedregs; /* Convenient for info fork, saves
52 having to actually switch contexts. */
53 int clobber_regs; /* True if we should restore saved regs. */
54 off_t *filepos; /* Set of open file descriptors' offsets. */
58 /* Fork list methods: */
63 return (fork_list != NULL);
66 /* Return the last fork in the list. */
68 static struct fork_info *
71 struct fork_info *last;
73 if (fork_list == NULL)
76 for (last = fork_list; last->next != NULL; last = last->next)
81 /* Add a fork to the internal fork list. */
88 if (fork_list == NULL && pid != ptid_get_pid (inferior_ptid))
90 /* Special case -- if this is the first fork in the list
91 (the list is hitherto empty), and if this new fork is
92 NOT the current inferior_ptid, then add inferior_ptid
93 first, as a special zeroeth fork id. */
94 highest_fork_num = -1;
95 add_fork (ptid_get_pid (inferior_ptid)); /* safe recursion */
98 fp = XCNEW (struct fork_info);
99 fp->ptid = ptid_build (pid, pid, 0);
100 fp->num = ++highest_fork_num;
102 if (fork_list == NULL)
106 struct fork_info *last = find_last_fork ();
115 free_fork (struct fork_info *fp)
117 /* Notes on step-resume breakpoints: since this is a concern for
118 threads, let's convince ourselves that it's not a concern for
119 forks. There are two ways for a fork_info to be created. First,
120 by the checkpoint command, in which case we're at a gdb prompt
121 and there can't be any step-resume breakpoint. Second, by a fork
122 in the user program, in which case we *may* have stepped into the
123 fork call, but regardless of whether we follow the parent or the
124 child, we will return to the same place and the step-resume
125 breakpoint, if any, will take care of itself as usual. And
126 unlike threads, we do not save a private copy of the step-resume
127 breakpoint -- so we're OK. */
132 regcache_xfree (fp->savedregs);
140 delete_fork (ptid_t ptid)
142 struct fork_info *fp, *fpprev;
146 linux_nat_forget_process (ptid_get_pid (ptid));
148 for (fp = fork_list; fp; fpprev = fp, fp = fp->next)
149 if (ptid_equal (fp->ptid, ptid))
156 fpprev->next = fp->next;
158 fork_list = fp->next;
162 /* Special case: if there is now only one process in the list,
163 and if it is (hopefully!) the current inferior_ptid, then
164 remove it, leaving the list empty -- we're now down to the
165 default case of debugging a single process. */
166 if (fork_list != NULL && fork_list->next == NULL &&
167 ptid_equal (fork_list->ptid, inferior_ptid))
169 /* Last fork -- delete from list and handle as solo process
170 (should be a safe recursion). */
171 delete_fork (inferior_ptid);
175 /* Find a fork_info by matching PTID. */
176 static struct fork_info *
177 find_fork_ptid (ptid_t ptid)
179 struct fork_info *fp;
181 for (fp = fork_list; fp; fp = fp->next)
182 if (ptid_equal (fp->ptid, ptid))
188 /* Find a fork_info by matching ID. */
189 static struct fork_info *
190 find_fork_id (int num)
192 struct fork_info *fp;
194 for (fp = fork_list; fp; fp = fp->next)
201 /* Find a fork_info by matching pid. */
202 extern struct fork_info *
203 find_fork_pid (pid_t pid)
205 struct fork_info *fp;
207 for (fp = fork_list; fp; fp = fp->next)
208 if (pid == ptid_get_pid (fp->ptid))
215 fork_id_to_ptid (int num)
217 struct fork_info *fork = find_fork_id (num);
221 return pid_to_ptid (-1);
225 init_fork_list (void)
227 struct fork_info *fp, *fpnext;
232 for (fp = fork_list; fp; fp = fpnext)
241 /* Fork list <-> gdb interface. */
243 /* Utility function for fork_load/fork_save.
244 Calls lseek in the (current) inferior process. */
247 call_lseek (int fd, off_t offset, int whence)
251 snprintf (&exp[0], sizeof (exp), "lseek (%d, %ld, %d)",
252 fd, (long) offset, whence);
253 return (off_t) parse_and_eval_long (&exp[0]);
256 /* Load infrun state for the fork PTID. */
259 fork_load_infrun_state (struct fork_info *fp)
261 extern void nullify_last_target_wait_ptid ();
264 linux_nat_switch_fork (fp->ptid);
266 if (fp->savedregs && fp->clobber_regs)
267 regcache_cpy (get_current_regcache (), fp->savedregs);
269 registers_changed ();
270 reinit_frame_cache ();
272 stop_pc = regcache_read_pc (get_current_regcache ());
273 nullify_last_target_wait_ptid ();
275 /* Now restore the file positions of open file descriptors. */
278 for (i = 0; i <= fp->maxfd; i++)
279 if (fp->filepos[i] != (off_t) -1)
280 call_lseek (i, fp->filepos[i], SEEK_SET);
281 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
282 this is native-only. If it ever has to be cross, we'll have
287 /* Save infrun state for the fork PTID.
288 Exported for use by linux child_follow_fork. */
291 fork_save_infrun_state (struct fork_info *fp, int clobber_regs)
298 regcache_xfree (fp->savedregs);
300 fp->savedregs = regcache_dup (get_current_regcache ());
301 fp->clobber_regs = clobber_regs;
305 /* Now save the 'state' (file position) of all open file descriptors.
306 Unfortunately fork does not take care of that for us... */
307 snprintf (path, PATH_MAX, "/proc/%ld/fd",
308 (long) ptid_get_pid (fp->ptid));
309 if ((d = opendir (path)) != NULL)
314 while ((de = readdir (d)) != NULL)
316 /* Count open file descriptors (actually find highest
318 tmp = strtol (&de->d_name[0], NULL, 10);
322 /* Allocate array of file positions. */
323 fp->filepos = XRESIZEVEC (off_t, fp->filepos, fp->maxfd + 1);
325 /* Initialize to -1 (invalid). */
326 for (tmp = 0; tmp <= fp->maxfd; tmp++)
327 fp->filepos[tmp] = -1;
329 /* Now find actual file positions. */
331 while ((de = readdir (d)) != NULL)
332 if (isdigit (de->d_name[0]))
334 tmp = strtol (&de->d_name[0], NULL, 10);
335 fp->filepos[tmp] = call_lseek (tmp, 0, SEEK_CUR);
342 /* Kill 'em all, let God sort 'em out... */
345 linux_fork_killall (void)
347 /* Walk list and kill every pid. No need to treat the
348 current inferior_ptid as special (we do not return a
349 status for it) -- however any process may be a child
350 or a parent, so may get a SIGCHLD from a previously
351 killed child. Wait them all out. */
352 struct fork_info *fp;
356 for (fp = fork_list; fp; fp = fp->next)
358 pid = ptid_get_pid (fp->ptid);
360 /* Use SIGKILL instead of PTRACE_KILL because the former works even
361 if the thread is running, while the later doesn't. */
363 ret = waitpid (pid, &status, 0);
364 /* We might get a SIGCHLD instead of an exit status. This is
365 aggravated by the first kill above - a child has just
366 died. MVS comment cut-and-pasted from linux-nat. */
367 } while (ret == pid && WIFSTOPPED (status));
369 init_fork_list (); /* Clear list, prepare to start fresh. */
372 /* The current inferior_ptid has exited, but there are other viable
373 forks to debug. Delete the exiting one and context-switch to the
377 linux_fork_mourn_inferior (void)
379 struct fork_info *last;
382 /* Wait just one more time to collect the inferior's exit status.
383 Do not check whether this succeeds though, since we may be
384 dealing with a process that we attached to. Such a process will
385 only report its exit status to its original parent. */
386 waitpid (ptid_get_pid (inferior_ptid), &status, 0);
388 /* OK, presumably inferior_ptid is the one who has exited.
389 We need to delete that one from the fork_list, and switch
390 to the next available fork. */
391 delete_fork (inferior_ptid);
393 /* There should still be a fork - if there's only one left,
394 delete_fork won't remove it, because we haven't updated
395 inferior_ptid yet. */
396 gdb_assert (fork_list);
398 last = find_last_fork ();
399 fork_load_infrun_state (last);
400 printf_filtered (_("[Switching to %s]\n"),
401 target_pid_to_str (inferior_ptid));
403 /* If there's only one fork, switch back to non-fork mode. */
404 if (fork_list->next == NULL)
405 delete_fork (inferior_ptid);
408 /* The current inferior_ptid is being detached, but there are other
409 viable forks to debug. Detach and delete it and context-switch to
410 the first available. */
413 linux_fork_detach (const char *args, int from_tty)
415 /* OK, inferior_ptid is the one we are detaching from. We need to
416 delete it from the fork_list, and switch to the next available
419 if (ptrace (PTRACE_DETACH, ptid_get_pid (inferior_ptid), 0, 0))
420 error (_("Unable to detach %s"), target_pid_to_str (inferior_ptid));
422 delete_fork (inferior_ptid);
424 /* There should still be a fork - if there's only one left,
425 delete_fork won't remove it, because we haven't updated
426 inferior_ptid yet. */
427 gdb_assert (fork_list);
429 fork_load_infrun_state (fork_list);
432 printf_filtered (_("[Switching to %s]\n"),
433 target_pid_to_str (inferior_ptid));
435 /* If there's only one fork, switch back to non-fork mode. */
436 if (fork_list->next == NULL)
437 delete_fork (inferior_ptid);
441 inferior_call_waitpid_cleanup (void *fp)
443 struct fork_info *oldfp = (struct fork_info *) fp;
447 /* Switch back to inferior_ptid. */
448 remove_breakpoints ();
449 fork_load_infrun_state (oldfp);
450 insert_breakpoints ();
455 inferior_call_waitpid (ptid_t pptid, int pid)
457 struct objfile *waitpid_objf;
458 struct value *waitpid_fn = NULL;
459 struct value *argv[4], *retv;
460 struct gdbarch *gdbarch = get_current_arch ();
461 struct fork_info *oldfp = NULL, *newfp = NULL;
462 struct cleanup *old_cleanup;
465 if (!ptid_equal (pptid, inferior_ptid))
467 /* Switch to pptid. */
468 oldfp = find_fork_ptid (inferior_ptid);
469 gdb_assert (oldfp != NULL);
470 newfp = find_fork_ptid (pptid);
471 gdb_assert (newfp != NULL);
472 fork_save_infrun_state (oldfp, 1);
473 remove_breakpoints ();
474 fork_load_infrun_state (newfp);
475 insert_breakpoints ();
478 old_cleanup = make_cleanup (inferior_call_waitpid_cleanup, oldfp);
480 /* Get the waitpid_fn. */
481 if (lookup_minimal_symbol ("waitpid", NULL, NULL).minsym != NULL)
482 waitpid_fn = find_function_in_inferior ("waitpid", &waitpid_objf);
484 && lookup_minimal_symbol ("_waitpid", NULL, NULL).minsym != NULL)
485 waitpid_fn = find_function_in_inferior ("_waitpid", &waitpid_objf);
490 argv[0] = value_from_longest (builtin_type (gdbarch)->builtin_int, pid);
491 argv[1] = value_from_pointer (builtin_type (gdbarch)->builtin_data_ptr, 0);
492 argv[2] = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
495 retv = call_function_by_hand (waitpid_fn, 3, argv);
496 if (value_as_long (retv) < 0)
502 do_cleanups (old_cleanup);
506 /* Fork list <-> user interface. */
509 delete_checkpoint_command (char *args, int from_tty)
512 struct fork_info *fi;
515 error (_("Requires argument (checkpoint id to delete)"));
517 ptid = fork_id_to_ptid (parse_and_eval_long (args));
518 if (ptid_equal (ptid, minus_one_ptid))
519 error (_("No such checkpoint id, %s"), args);
521 if (ptid_equal (ptid, inferior_ptid))
523 Please switch to another checkpoint before deleting the current one"));
525 if (ptrace (PTRACE_KILL, ptid_get_pid (ptid), 0, 0))
526 error (_("Unable to kill pid %s"), target_pid_to_str (ptid));
528 fi = find_fork_ptid (ptid);
530 pptid = fi->parent_ptid;
533 printf_filtered (_("Killed %s\n"), target_pid_to_str (ptid));
537 /* If fi->parent_ptid is not a part of lwp but it's a part of checkpoint
538 list, waitpid the ptid.
539 If fi->parent_ptid is a part of lwp and it is stoped, waitpid the
541 if ((!find_thread_ptid (pptid) && find_fork_ptid (pptid))
542 || (find_thread_ptid (pptid) && is_stopped (pptid)))
544 if (inferior_call_waitpid (pptid, ptid_get_pid (ptid)))
545 warning (_("Unable to wait pid %s"), target_pid_to_str (ptid));
550 detach_checkpoint_command (char *args, int from_tty)
555 error (_("Requires argument (checkpoint id to detach)"));
557 ptid = fork_id_to_ptid (parse_and_eval_long (args));
558 if (ptid_equal (ptid, minus_one_ptid))
559 error (_("No such checkpoint id, %s"), args);
561 if (ptid_equal (ptid, inferior_ptid))
563 Please switch to another checkpoint before detaching the current one"));
565 if (ptrace (PTRACE_DETACH, ptid_get_pid (ptid), 0, 0))
566 error (_("Unable to detach %s"), target_pid_to_str (ptid));
569 printf_filtered (_("Detached %s\n"), target_pid_to_str (ptid));
574 /* Print information about currently known checkpoints. */
577 info_checkpoints_command (char *arg, int from_tty)
579 struct gdbarch *gdbarch = get_current_arch ();
580 struct symtab_and_line sal;
581 struct fork_info *fp;
584 struct fork_info *printed = NULL;
587 requested = (int) parse_and_eval_long (arg);
589 for (fp = fork_list; fp; fp = fp->next)
591 if (requested > 0 && fp->num != requested)
595 if (ptid_equal (fp->ptid, inferior_ptid))
597 printf_filtered ("* ");
598 pc = regcache_read_pc (get_current_regcache ());
602 printf_filtered (" ");
603 pc = regcache_read_pc (fp->savedregs);
605 printf_filtered ("%d %s", fp->num, target_pid_to_str (fp->ptid));
607 printf_filtered (_(" (main process)"));
608 printf_filtered (_(" at "));
609 fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
611 sal = find_pc_line (pc, 0);
613 printf_filtered (_(", file %s"),
614 symtab_to_filename_for_display (sal.symtab));
616 printf_filtered (_(", line %d"), sal.line);
617 if (!sal.symtab && !sal.line)
619 struct bound_minimal_symbol msym;
621 msym = lookup_minimal_symbol_by_pc (pc);
623 printf_filtered (", <%s>", MSYMBOL_LINKAGE_NAME (msym.minsym));
626 putchar_filtered ('\n');
631 printf_filtered (_("No checkpoint number %d.\n"), requested);
633 printf_filtered (_("No checkpoints.\n"));
637 /* The PID of the process we're checkpointing. */
638 static int checkpointing_pid = 0;
641 linux_fork_checkpointing_p (int pid)
643 return (checkpointing_pid == pid);
646 /* Callback for iterate over threads. Used to check whether
647 the current inferior is multi-threaded. Returns true as soon
648 as it sees the second thread of the current inferior. */
651 inf_has_multiple_thread_cb (struct thread_info *tp, void *data)
653 int *count_p = (int *) data;
655 if (current_inferior ()->pid == ptid_get_pid (tp->ptid))
658 /* Stop the iteration if multiple threads have been detected. */
662 /* Return true if the current inferior is multi-threaded. */
665 inf_has_multiple_threads (void)
669 iterate_over_threads (inf_has_multiple_thread_cb, &count);
674 checkpoint_command (char *args, int from_tty)
676 struct objfile *fork_objf;
677 struct gdbarch *gdbarch;
678 struct target_waitstatus last_target_waitstatus;
679 ptid_t last_target_ptid;
680 struct value *fork_fn = NULL, *ret;
681 struct fork_info *fp;
683 struct cleanup *old_chain;
685 if (!target_has_execution)
686 error (_("The program is not being run."));
688 /* Ensure that the inferior is not multithreaded. */
689 update_thread_list ();
690 if (inf_has_multiple_threads ())
691 error (_("checkpoint: can't checkpoint multiple threads."));
693 /* Make the inferior fork, record its (and gdb's) state. */
695 if (lookup_minimal_symbol ("fork", NULL, NULL).minsym != NULL)
696 fork_fn = find_function_in_inferior ("fork", &fork_objf);
698 if (lookup_minimal_symbol ("_fork", NULL, NULL).minsym != NULL)
699 fork_fn = find_function_in_inferior ("fork", &fork_objf);
701 error (_("checkpoint: can't find fork function in inferior."));
703 gdbarch = get_objfile_arch (fork_objf);
704 ret = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
706 /* Tell linux-nat.c that we're checkpointing this inferior. */
707 old_chain = make_cleanup_restore_integer (&checkpointing_pid);
708 checkpointing_pid = ptid_get_pid (inferior_ptid);
710 ret = call_function_by_hand (fork_fn, 0, &ret);
711 do_cleanups (old_chain);
712 if (!ret) /* Probably can't happen. */
713 error (_("checkpoint: call_function_by_hand returned null."));
715 retpid = value_as_long (ret);
716 get_last_target_status (&last_target_ptid, &last_target_waitstatus);
718 fp = find_fork_pid (retpid);
724 printf_filtered (_("checkpoint %d: fork returned pid %ld.\n"),
725 fp != NULL ? fp->num : -1, (long) retpid);
728 parent_pid = ptid_get_lwp (last_target_ptid);
730 parent_pid = ptid_get_pid (last_target_ptid);
731 printf_filtered (_(" gdb says parent = %ld.\n"),
737 error (_("Failed to find new fork"));
738 fork_save_infrun_state (fp, 1);
739 fp->parent_ptid = last_target_ptid;
743 linux_fork_context (struct fork_info *newfp, int from_tty)
745 /* Now we attempt to switch processes. */
746 struct fork_info *oldfp;
748 gdb_assert (newfp != NULL);
750 oldfp = find_fork_ptid (inferior_ptid);
751 gdb_assert (oldfp != NULL);
753 fork_save_infrun_state (oldfp, 1);
754 remove_breakpoints ();
755 fork_load_infrun_state (newfp);
756 insert_breakpoints ();
758 printf_filtered (_("Switching to %s\n"),
759 target_pid_to_str (inferior_ptid));
761 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
764 /* Switch inferior process (checkpoint) context, by checkpoint id. */
766 restart_command (char *args, int from_tty)
768 struct fork_info *fp;
771 error (_("Requires argument (checkpoint id to restart)"));
773 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
774 error (_("Not found: checkpoint id %s"), args);
776 linux_fork_context (fp, from_tty);
780 _initialize_linux_fork (void)
784 /* Checkpoint command: create a fork of the inferior process
785 and set it aside for later debugging. */
787 add_com ("checkpoint", class_obscure, checkpoint_command, _("\
788 Fork a duplicate process (experimental)."));
790 /* Restart command: restore the context of a specified checkpoint
793 add_com ("restart", class_obscure, restart_command, _("\
794 restart <n>: restore program context from a checkpoint.\n\
795 Argument 'n' is checkpoint ID, as displayed by 'info checkpoints'."));
797 /* Delete checkpoint command: kill the process and remove it from
800 add_cmd ("checkpoint", class_obscure, delete_checkpoint_command, _("\
801 Delete a checkpoint (experimental)."),
804 /* Detach checkpoint command: release the process to run independently,
805 and remove it from the fork list. */
807 add_cmd ("checkpoint", class_obscure, detach_checkpoint_command, _("\
808 Detach from a checkpoint (experimental)."),
811 /* Info checkpoints command: list all forks/checkpoints
812 currently under gdb's control. */
814 add_info ("checkpoints", info_checkpoints_command,
815 _("IDs of currently known checkpoints."));