1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010
4 Free Software Foundation, Inc.
6 This file is part of GDB.
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "arch-utils.h"
28 #include "gdb_assert.h"
29 #include "gdb_string.h"
30 #include "linux-fork.h"
31 #include "linux-nat.h"
32 #include "gdbthread.h"
34 #include <sys/ptrace.h>
36 #include <sys/param.h>
37 #include "gdb_dirent.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 != PIDGET (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 (PIDGET (inferior_ptid)); /* safe recursion */
85 fp = XZALLOC (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 for (fp = fork_list; fp; fpprev = fp, fp = fp->next)
126 if (ptid_equal (fp->ptid, ptid))
133 fpprev->next = fp->next;
135 fork_list = fp->next;
139 /* Special case: if there is now only one process in the list,
140 and if it is (hopefully!) the current inferior_ptid, then
141 remove it, leaving the list empty -- we're now down to the
142 default case of debugging a single process. */
143 if (fork_list != NULL && fork_list->next == NULL &&
144 ptid_equal (fork_list->ptid, inferior_ptid))
146 /* Last fork -- delete from list and handle as solo process
147 (should be a safe recursion). */
148 delete_fork (inferior_ptid);
152 /* Find a fork_info by matching PTID. */
153 static struct fork_info *
154 find_fork_ptid (ptid_t ptid)
156 struct fork_info *fp;
158 for (fp = fork_list; fp; fp = fp->next)
159 if (ptid_equal (fp->ptid, ptid))
165 /* Find a fork_info by matching ID. */
166 static struct fork_info *
167 find_fork_id (int num)
169 struct fork_info *fp;
171 for (fp = fork_list; fp; fp = fp->next)
178 /* Find a fork_info by matching pid. */
179 extern struct fork_info *
180 find_fork_pid (pid_t pid)
182 struct fork_info *fp;
184 for (fp = fork_list; fp; fp = fp->next)
185 if (pid == ptid_get_pid (fp->ptid))
192 fork_id_to_ptid (int num)
194 struct fork_info *fork = find_fork_id (num);
198 return pid_to_ptid (-1);
202 init_fork_list (void)
204 struct fork_info *fp, *fpnext;
209 for (fp = fork_list; fp; fp = fpnext)
218 /* Fork list <-> gdb interface. */
220 /* Utility function for fork_load/fork_save.
221 Calls lseek in the (current) inferior process. */
224 call_lseek (int fd, off_t offset, int whence)
228 snprintf (&exp[0], sizeof (exp), "lseek (%d, %ld, %d)",
229 fd, (long) offset, whence);
230 return (off_t) parse_and_eval_long (&exp[0]);
233 /* Load infrun state for the fork PTID. */
236 fork_load_infrun_state (struct fork_info *fp)
238 extern void nullify_last_target_wait_ptid ();
241 linux_nat_switch_fork (fp->ptid);
243 if (fp->savedregs && fp->clobber_regs)
244 regcache_cpy (get_current_regcache (), fp->savedregs);
246 registers_changed ();
247 reinit_frame_cache ();
249 stop_pc = regcache_read_pc (get_current_regcache ());
250 nullify_last_target_wait_ptid ();
252 /* Now restore the file positions of open file descriptors. */
255 for (i = 0; i <= fp->maxfd; i++)
256 if (fp->filepos[i] != (off_t) -1)
257 call_lseek (i, fp->filepos[i], SEEK_SET);
258 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
259 this is native-only. If it ever has to be cross, we'll have
264 /* Save infrun state for the fork PTID.
265 Exported for use by linux child_follow_fork. */
268 fork_save_infrun_state (struct fork_info *fp, int clobber_regs)
270 char path[MAXPATHLEN];
275 regcache_xfree (fp->savedregs);
277 fp->savedregs = regcache_dup (get_current_regcache ());
278 fp->clobber_regs = clobber_regs;
282 /* Now save the 'state' (file position) of all open file descriptors.
283 Unfortunately fork does not take care of that for us... */
284 snprintf (path, MAXPATHLEN, "/proc/%ld/fd", (long) PIDGET (fp->ptid));
285 if ((d = opendir (path)) != NULL)
290 while ((de = readdir (d)) != NULL)
292 /* Count open file descriptors (actually find highest
294 tmp = strtol (&de->d_name[0], NULL, 10);
298 /* Allocate array of file positions. */
299 fp->filepos = xrealloc (fp->filepos,
300 (fp->maxfd + 1) * sizeof (*fp->filepos));
302 /* Initialize to -1 (invalid). */
303 for (tmp = 0; tmp <= fp->maxfd; tmp++)
304 fp->filepos[tmp] = -1;
306 /* Now find actual file positions. */
308 while ((de = readdir (d)) != NULL)
309 if (isdigit (de->d_name[0]))
311 tmp = strtol (&de->d_name[0], NULL, 10);
312 fp->filepos[tmp] = call_lseek (tmp, 0, SEEK_CUR);
319 /* Kill 'em all, let God sort 'em out... */
322 linux_fork_killall (void)
324 /* Walk list and kill every pid. No need to treat the
325 current inferior_ptid as special (we do not return a
326 status for it) -- however any process may be a child
327 or a parent, so may get a SIGCHLD from a previously
328 killed child. Wait them all out. */
329 struct fork_info *fp;
333 for (fp = fork_list; fp; fp = fp->next)
335 pid = PIDGET (fp->ptid);
337 /* Use SIGKILL instead of PTRACE_KILL because the former works even
338 if the thread is running, while the later doesn't. */
340 ret = waitpid (pid, &status, 0);
341 /* We might get a SIGCHLD instead of an exit status. This is
342 aggravated by the first kill above - a child has just
343 died. MVS comment cut-and-pasted from linux-nat. */
344 } while (ret == pid && WIFSTOPPED (status));
346 init_fork_list (); /* Clear list, prepare to start fresh. */
349 /* The current inferior_ptid has exited, but there are other viable
350 forks to debug. Delete the exiting one and context-switch to the
354 linux_fork_mourn_inferior (void)
356 /* Wait just one more time to collect the inferior's exit status.
357 Do not check whether this succeeds though, since we may be
358 dealing with a process that we attached to. Such a process will
359 only report its exit status to its original parent. */
362 waitpid (ptid_get_pid (inferior_ptid), &status, 0);
364 /* OK, presumably inferior_ptid is the one who has exited.
365 We need to delete that one from the fork_list, and switch
366 to the next available fork. */
367 delete_fork (inferior_ptid);
369 /* There should still be a fork - if there's only one left,
370 delete_fork won't remove it, because we haven't updated
371 inferior_ptid yet. */
372 gdb_assert (fork_list);
374 fork_load_infrun_state (fork_list);
375 printf_filtered (_("[Switching to %s]\n"),
376 target_pid_to_str (inferior_ptid));
378 /* If there's only one fork, switch back to non-fork mode. */
379 if (fork_list->next == NULL)
380 delete_fork (inferior_ptid);
383 /* The current inferior_ptid is being detached, but there are other
384 viable forks to debug. Detach and delete it and context-switch to
385 the first available. */
388 linux_fork_detach (char *args, int from_tty)
390 /* OK, inferior_ptid is the one we are detaching from. We need to
391 delete it from the fork_list, and switch to the next available
394 if (ptrace (PTRACE_DETACH, PIDGET (inferior_ptid), 0, 0))
395 error (_("Unable to detach %s"), target_pid_to_str (inferior_ptid));
397 delete_fork (inferior_ptid);
399 /* There should still be a fork - if there's only one left,
400 delete_fork won't remove it, because we haven't updated
401 inferior_ptid yet. */
402 gdb_assert (fork_list);
404 fork_load_infrun_state (fork_list);
407 printf_filtered (_("[Switching to %s]\n"),
408 target_pid_to_str (inferior_ptid));
410 /* If there's only one fork, switch back to non-fork mode. */
411 if (fork_list->next == NULL)
412 delete_fork (inferior_ptid);
416 inferior_call_waitpid_cleanup (void *fp)
418 struct fork_info *oldfp = fp;
420 /* Switch back to inferior_ptid. */
421 remove_breakpoints ();
422 fork_load_infrun_state (oldfp);
423 insert_breakpoints ();
427 inferior_call_waitpid (ptid_t pptid, int pid)
429 struct objfile *waitpid_objf;
430 struct value *waitpid_fn = NULL;
431 struct value *argv[4];
432 struct gdbarch *gdbarch = get_current_arch ();
433 struct fork_info *oldfp = NULL, *newfp = NULL;
434 struct cleanup *old_cleanup = NULL;
437 if (!ptid_equal (pptid, inferior_ptid))
439 /* Switch to pptid. */
440 oldfp = find_fork_ptid (inferior_ptid);
441 gdb_assert (oldfp != NULL);
442 newfp = find_fork_ptid (pptid);
443 gdb_assert (oldfp != NULL);
444 fork_save_infrun_state (oldfp, 1);
445 remove_breakpoints ();
446 fork_load_infrun_state (newfp);
447 insert_breakpoints ();
449 old_cleanup = make_cleanup (inferior_call_waitpid_cleanup, oldfp);
452 /* Get the waitpid_fn. */
453 if (lookup_minimal_symbol ("waitpid", NULL, NULL) != NULL)
454 waitpid_fn = find_function_in_inferior ("waitpid", &waitpid_objf);
455 if (!waitpid_fn && lookup_minimal_symbol ("_waitpid", NULL, NULL) != NULL)
456 waitpid_fn = find_function_in_inferior ("_waitpid", &waitpid_objf);
461 argv[0] = value_from_longest (builtin_type (gdbarch)->builtin_int, pid);
462 argv[1] = value_from_pointer (builtin_type (gdbarch)->builtin_data_ptr, 0);
463 argv[2] = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
466 call_function_by_hand (waitpid_fn, 3, argv);
472 do_cleanups (old_cleanup);
476 /* Fork list <-> user interface. */
479 delete_checkpoint_command (char *args, int from_tty)
482 struct fork_info *fi;
485 error (_("Requires argument (checkpoint id to delete)"));
487 ptid = fork_id_to_ptid (parse_and_eval_long (args));
488 if (ptid_equal (ptid, minus_one_ptid))
489 error (_("No such checkpoint id, %s"), args);
491 if (ptid_equal (ptid, inferior_ptid))
493 Please switch to another checkpoint before deleting the current one"));
495 if (ptrace (PTRACE_KILL, PIDGET (ptid), 0, 0))
496 error (_("Unable to kill pid %s"), target_pid_to_str (ptid));
498 fi = find_fork_ptid (ptid);
502 printf_filtered (_("Killed %s\n"), target_pid_to_str (ptid));
506 /* If fi->parent_ptid is not a part of lwp but it's a part of checkpoint
507 list, waitpid the ptid.
508 If fi->parent_ptid is a part of lwp and it is stoped, waitpid the
510 if ((!find_thread_ptid (fi->parent_ptid) && find_fork_ptid (fi->parent_ptid))
511 || (find_thread_ptid (fi->parent_ptid) && is_stopped (fi->parent_ptid)))
513 if (inferior_call_waitpid (fi->parent_ptid, PIDGET (ptid)))
514 warning (_("Unable to wait pid %s"), target_pid_to_str (ptid));
519 detach_checkpoint_command (char *args, int from_tty)
524 error (_("Requires argument (checkpoint id to detach)"));
526 ptid = fork_id_to_ptid (parse_and_eval_long (args));
527 if (ptid_equal (ptid, minus_one_ptid))
528 error (_("No such checkpoint id, %s"), args);
530 if (ptid_equal (ptid, inferior_ptid))
532 Please switch to another checkpoint before detaching the current one"));
534 if (ptrace (PTRACE_DETACH, PIDGET (ptid), 0, 0))
535 error (_("Unable to detach %s"), target_pid_to_str (ptid));
538 printf_filtered (_("Detached %s\n"), target_pid_to_str (ptid));
543 /* Print information about currently known checkpoints. */
546 info_checkpoints_command (char *arg, int from_tty)
548 struct gdbarch *gdbarch = get_current_arch ();
549 struct symtab_and_line sal;
550 struct fork_info *fp;
553 struct fork_info *printed = NULL;
556 requested = (int) parse_and_eval_long (arg);
558 for (fp = fork_list; fp; fp = fp->next)
560 if (requested > 0 && fp->num != requested)
564 if (ptid_equal (fp->ptid, inferior_ptid))
566 printf_filtered ("* ");
567 pc = regcache_read_pc (get_current_regcache ());
571 printf_filtered (" ");
572 pc = regcache_read_pc (fp->savedregs);
574 printf_filtered ("%d %s", fp->num, target_pid_to_str (fp->ptid));
576 printf_filtered (_(" (main process)"));
577 printf_filtered (_(" at "));
578 fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
580 sal = find_pc_line (pc, 0);
583 char *tmp = strrchr (sal.symtab->filename, '/');
586 printf_filtered (_(", file %s"), tmp + 1);
588 printf_filtered (_(", file %s"), sal.symtab->filename);
591 printf_filtered (_(", line %d"), sal.line);
592 if (!sal.symtab && !sal.line)
594 struct minimal_symbol *msym;
596 msym = lookup_minimal_symbol_by_pc (pc);
598 printf_filtered (", <%s>", SYMBOL_LINKAGE_NAME (msym));
601 putchar_filtered ('\n');
606 printf_filtered (_("No checkpoint number %d.\n"), requested);
608 printf_filtered (_("No checkpoints.\n"));
612 /* The PID of the process we're checkpointing. */
613 static int checkpointing_pid = 0;
616 linux_fork_checkpointing_p (int pid)
618 return (checkpointing_pid == pid);
622 checkpoint_command (char *args, int from_tty)
624 struct objfile *fork_objf;
625 struct gdbarch *gdbarch;
626 struct target_waitstatus last_target_waitstatus;
627 ptid_t last_target_ptid;
628 struct value *fork_fn = NULL, *ret;
629 struct fork_info *fp;
631 struct cleanup *old_chain;
633 /* Make the inferior fork, record its (and gdb's) state. */
635 if (lookup_minimal_symbol ("fork", NULL, NULL) != NULL)
636 fork_fn = find_function_in_inferior ("fork", &fork_objf);
638 if (lookup_minimal_symbol ("_fork", NULL, NULL) != NULL)
639 fork_fn = find_function_in_inferior ("fork", &fork_objf);
641 error (_("checkpoint: can't find fork function in inferior."));
643 gdbarch = get_objfile_arch (fork_objf);
644 ret = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
646 /* Tell linux-nat.c that we're checkpointing this inferior. */
647 old_chain = make_cleanup_restore_integer (&checkpointing_pid);
648 checkpointing_pid = PIDGET (inferior_ptid);
650 ret = call_function_by_hand (fork_fn, 0, &ret);
651 do_cleanups (old_chain);
652 if (!ret) /* Probably can't happen. */
653 error (_("checkpoint: call_function_by_hand returned null."));
655 retpid = value_as_long (ret);
656 get_last_target_status (&last_target_ptid, &last_target_waitstatus);
661 printf_filtered (_("checkpoint: fork returned pid %ld.\n"),
665 parent_pid = ptid_get_lwp (last_target_ptid);
667 parent_pid = ptid_get_pid (last_target_ptid);
668 printf_filtered (_(" gdb says parent = %ld.\n"),
673 fp = find_fork_pid (retpid);
675 error (_("Failed to find new fork"));
676 fork_save_infrun_state (fp, 1);
677 fp->parent_ptid = last_target_ptid;
681 linux_fork_context (struct fork_info *newfp, int from_tty)
683 /* Now we attempt to switch processes. */
684 struct fork_info *oldfp;
686 gdb_assert (newfp != NULL);
688 oldfp = find_fork_ptid (inferior_ptid);
689 gdb_assert (oldfp != NULL);
691 fork_save_infrun_state (oldfp, 1);
692 remove_breakpoints ();
693 fork_load_infrun_state (newfp);
694 insert_breakpoints ();
696 printf_filtered (_("Switching to %s\n"),
697 target_pid_to_str (inferior_ptid));
699 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
702 /* Switch inferior process (checkpoint) context, by checkpoint id. */
704 restart_command (char *args, int from_tty)
706 struct fork_info *fp;
709 error (_("Requires argument (checkpoint id to restart)"));
711 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
712 error (_("Not found: checkpoint id %s"), args);
714 linux_fork_context (fp, from_tty);
718 _initialize_linux_fork (void)
722 /* Checkpoint command: create a fork of the inferior process
723 and set it aside for later debugging. */
725 add_com ("checkpoint", class_obscure, checkpoint_command, _("\
726 Fork a duplicate process (experimental)."));
728 /* Restart command: restore the context of a specified checkpoint
731 add_com ("restart", class_obscure, restart_command, _("\
732 restart <n>: restore program context from a checkpoint.\n\
733 Argument 'n' is checkpoint ID, as displayed by 'info checkpoints'."));
735 /* Delete checkpoint command: kill the process and remove it from
738 add_cmd ("checkpoint", class_obscure, delete_checkpoint_command, _("\
739 Delete a checkpoint (experimental)."),
742 /* Detach checkpoint command: release the process to run independently,
743 and remove it from the fork list. */
745 add_cmd ("checkpoint", class_obscure, detach_checkpoint_command, _("\
746 Detach from a checkpoint (experimental)."),
749 /* Info checkpoints command: list all forks/checkpoints
750 currently under gdb's control. */
752 add_info ("checkpoints", info_checkpoints_command,
753 _("IDs of currently known checkpoints."));