1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005, 2006, 2007, 2008, 2009 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"
27 #include "gdb_assert.h"
28 #include "gdb_string.h"
29 #include "linux-fork.h"
30 #include "linux-nat.h"
32 #include <sys/ptrace.h>
34 #include <sys/param.h>
35 #include "gdb_dirent.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;
49 int num; /* Convenient handle (GDB fork id) */
50 struct regcache *savedregs; /* Convenient for info fork, saves
51 having to actually switch contexts. */
52 int clobber_regs; /* True if we should restore saved regs. */
53 off_t *filepos; /* Set of open file descriptors' offsets. */
57 /* Fork list methods: */
62 return (fork_list != NULL);
65 /* Add a fork to the internal fork list. */
72 if (fork_list == NULL && pid != PIDGET (inferior_ptid))
74 /* Special case -- if this is the first fork in the list
75 (the list is hitherto empty), and if this new fork is
76 NOT the current inferior_ptid, then add inferior_ptid
77 first, as a special zeroeth fork id. */
78 highest_fork_num = -1;
79 add_fork (PIDGET (inferior_ptid)); /* safe recursion */
82 fp = XZALLOC (struct fork_info);
83 fp->ptid = ptid_build (pid, pid, 0);
84 fp->num = ++highest_fork_num;
91 free_fork (struct fork_info *fp)
93 /* Notes on step-resume breakpoints: since this is a concern for
94 threads, let's convince ourselves that it's not a concern for
95 forks. There are two ways for a fork_info to be created. First,
96 by the checkpoint command, in which case we're at a gdb prompt
97 and there can't be any step-resume breakpoint. Second, by a fork
98 in the user program, in which case we *may* have stepped into the
99 fork call, but regardless of whether we follow the parent or the
100 child, we will return to the same place and the step-resume
101 breakpoint, if any, will take care of itself as usual. And
102 unlike threads, we do not save a private copy of the step-resume
103 breakpoint -- so we're OK. */
108 regcache_xfree (fp->savedregs);
116 delete_fork (ptid_t ptid)
118 struct fork_info *fp, *fpprev;
122 for (fp = fork_list; fp; fpprev = fp, fp = fp->next)
123 if (ptid_equal (fp->ptid, ptid))
130 fpprev->next = fp->next;
132 fork_list = fp->next;
136 /* Special case: if there is now only one process in the list,
137 and if it is (hopefully!) the current inferior_ptid, then
138 remove it, leaving the list empty -- we're now down to the
139 default case of debugging a single process. */
140 if (fork_list != NULL && fork_list->next == NULL &&
141 ptid_equal (fork_list->ptid, inferior_ptid))
143 /* Last fork -- delete from list and handle as solo process
144 (should be a safe recursion). */
145 delete_fork (inferior_ptid);
149 /* Find a fork_info by matching PTID. */
150 static struct fork_info *
151 find_fork_ptid (ptid_t ptid)
153 struct fork_info *fp;
155 for (fp = fork_list; fp; fp = fp->next)
156 if (ptid_equal (fp->ptid, ptid))
162 /* Find a fork_info by matching ID. */
163 static struct fork_info *
164 find_fork_id (int num)
166 struct fork_info *fp;
168 for (fp = fork_list; fp; fp = fp->next)
175 /* Find a fork_info by matching pid. */
176 extern struct fork_info *
177 find_fork_pid (pid_t pid)
179 struct fork_info *fp;
181 for (fp = fork_list; fp; fp = fp->next)
182 if (pid == ptid_get_pid (fp->ptid))
189 fork_id_to_ptid (int num)
191 struct fork_info *fork = find_fork_id (num);
195 return pid_to_ptid (-1);
199 init_fork_list (void)
201 struct fork_info *fp, *fpnext;
206 for (fp = fork_list; fp; fp = fpnext)
215 /* Fork list <-> gdb interface. */
217 /* Utility function for fork_load/fork_save.
218 Calls lseek in the (current) inferior process. */
221 call_lseek (int fd, off_t offset, int whence)
225 snprintf (&exp[0], sizeof (exp), "lseek (%d, %ld, %d)",
226 fd, (long) offset, whence);
227 return (off_t) parse_and_eval_long (&exp[0]);
230 /* Load infrun state for the fork PTID. */
233 fork_load_infrun_state (struct fork_info *fp)
235 extern void nullify_last_target_wait_ptid ();
238 linux_nat_switch_fork (fp->ptid);
240 if (fp->savedregs && fp->clobber_regs)
241 regcache_cpy (get_current_regcache (), fp->savedregs);
243 registers_changed ();
244 reinit_frame_cache ();
246 stop_pc = regcache_read_pc (get_current_regcache ());
247 nullify_last_target_wait_ptid ();
249 /* Now restore the file positions of open file descriptors. */
252 for (i = 0; i <= fp->maxfd; i++)
253 if (fp->filepos[i] != (off_t) -1)
254 call_lseek (i, fp->filepos[i], SEEK_SET);
255 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
256 this is native-only. If it ever has to be cross, we'll have
261 /* Save infrun state for the fork PTID.
262 Exported for use by linux child_follow_fork. */
265 fork_save_infrun_state (struct fork_info *fp, int clobber_regs)
267 char path[MAXPATHLEN];
272 regcache_xfree (fp->savedregs);
274 fp->savedregs = regcache_dup (get_current_regcache ());
275 fp->clobber_regs = clobber_regs;
279 /* Now save the 'state' (file position) of all open file descriptors.
280 Unfortunately fork does not take care of that for us... */
281 snprintf (path, MAXPATHLEN, "/proc/%ld/fd", (long) PIDGET (fp->ptid));
282 if ((d = opendir (path)) != NULL)
287 while ((de = readdir (d)) != NULL)
289 /* Count open file descriptors (actually find highest
291 tmp = strtol (&de->d_name[0], NULL, 10);
295 /* Allocate array of file positions. */
296 fp->filepos = xrealloc (fp->filepos,
297 (fp->maxfd + 1) * sizeof (*fp->filepos));
299 /* Initialize to -1 (invalid). */
300 for (tmp = 0; tmp <= fp->maxfd; tmp++)
301 fp->filepos[tmp] = -1;
303 /* Now find actual file positions. */
305 while ((de = readdir (d)) != NULL)
306 if (isdigit (de->d_name[0]))
308 tmp = strtol (&de->d_name[0], NULL, 10);
309 fp->filepos[tmp] = call_lseek (tmp, 0, SEEK_CUR);
316 /* Kill 'em all, let God sort 'em out... */
319 linux_fork_killall (void)
321 /* Walk list and kill every pid. No need to treat the
322 current inferior_ptid as special (we do not return a
323 status for it) -- however any process may be a child
324 or a parent, so may get a SIGCHLD from a previously
325 killed child. Wait them all out. */
326 struct fork_info *fp;
330 for (fp = fork_list; fp; fp = fp->next)
332 pid = PIDGET (fp->ptid);
334 /* Use SIGKILL instead of PTRACE_KILL because the former works even
335 if the thread is running, while the later doesn't. */
337 ret = waitpid (pid, &status, 0);
338 /* We might get a SIGCHLD instead of an exit status. This is
339 aggravated by the first kill above - a child has just
340 died. MVS comment cut-and-pasted from linux-nat. */
341 } while (ret == pid && WIFSTOPPED (status));
343 init_fork_list (); /* Clear list, prepare to start fresh. */
346 /* The current inferior_ptid has exited, but there are other viable
347 forks to debug. Delete the exiting one and context-switch to the
351 linux_fork_mourn_inferior (void)
353 /* Wait just one more time to collect the inferior's exit status.
354 Do not check whether this succeeds though, since we may be
355 dealing with a process that we attached to. Such a process will
356 only report its exit status to its original parent. */
359 waitpid (ptid_get_pid (inferior_ptid), &status, 0);
361 /* OK, presumably inferior_ptid is the one who has exited.
362 We need to delete that one from the fork_list, and switch
363 to the next available fork. */
364 delete_fork (inferior_ptid);
366 /* There should still be a fork - if there's only one left,
367 delete_fork won't remove it, because we haven't updated
368 inferior_ptid yet. */
369 gdb_assert (fork_list);
371 fork_load_infrun_state (fork_list);
372 printf_filtered (_("[Switching to %s]\n"),
373 target_pid_to_str (inferior_ptid));
375 /* If there's only one fork, switch back to non-fork mode. */
376 if (fork_list->next == NULL)
377 delete_fork (inferior_ptid);
380 /* The current inferior_ptid is being detached, but there are other
381 viable forks to debug. Detach and delete it and context-switch to
382 the first available. */
385 linux_fork_detach (char *args, int from_tty)
387 /* OK, inferior_ptid is the one we are detaching from. We need to
388 delete it from the fork_list, and switch to the next available
391 if (ptrace (PTRACE_DETACH, PIDGET (inferior_ptid), 0, 0))
392 error (_("Unable to detach %s"), target_pid_to_str (inferior_ptid));
394 delete_fork (inferior_ptid);
396 /* There should still be a fork - if there's only one left,
397 delete_fork won't remove it, because we haven't updated
398 inferior_ptid yet. */
399 gdb_assert (fork_list);
401 fork_load_infrun_state (fork_list);
404 printf_filtered (_("[Switching to %s]\n"),
405 target_pid_to_str (inferior_ptid));
407 /* If there's only one fork, switch back to non-fork mode. */
408 if (fork_list->next == NULL)
409 delete_fork (inferior_ptid);
412 /* Fork list <-> user interface. */
415 delete_checkpoint_command (char *args, int from_tty)
420 error (_("Requires argument (checkpoint id to delete)"));
422 ptid = fork_id_to_ptid (parse_and_eval_long (args));
423 if (ptid_equal (ptid, minus_one_ptid))
424 error (_("No such checkpoint id, %s"), args);
426 if (ptid_equal (ptid, inferior_ptid))
428 Please switch to another checkpoint before deleting the current one"));
430 if (ptrace (PTRACE_KILL, PIDGET (ptid), 0, 0))
431 error (_("Unable to kill pid %s"), target_pid_to_str (ptid));
434 printf_filtered (_("Killed %s\n"), target_pid_to_str (ptid));
440 detach_checkpoint_command (char *args, int from_tty)
445 error (_("Requires argument (checkpoint id to detach)"));
447 ptid = fork_id_to_ptid (parse_and_eval_long (args));
448 if (ptid_equal (ptid, minus_one_ptid))
449 error (_("No such checkpoint id, %s"), args);
451 if (ptid_equal (ptid, inferior_ptid))
453 Please switch to another checkpoint before detaching the current one"));
455 if (ptrace (PTRACE_DETACH, PIDGET (ptid), 0, 0))
456 error (_("Unable to detach %s"), target_pid_to_str (ptid));
459 printf_filtered (_("Detached %s\n"), target_pid_to_str (ptid));
464 /* Print information about currently known checkpoints. */
467 info_checkpoints_command (char *arg, int from_tty)
469 struct gdbarch *gdbarch = get_current_arch ();
470 struct frame_info *cur_frame;
471 struct symtab_and_line sal;
472 struct symtab *cur_symtab;
473 struct fork_info *fp;
477 struct fork_info *printed = NULL;
480 requested = (int) parse_and_eval_long (arg);
482 for (fp = fork_list; fp; fp = fp->next)
484 if (requested > 0 && fp->num != requested)
488 if (ptid_equal (fp->ptid, inferior_ptid))
490 printf_filtered ("* ");
491 pc = regcache_read_pc (get_current_regcache ());
495 printf_filtered (" ");
496 pc = regcache_read_pc (fp->savedregs);
498 printf_filtered ("%d %s", fp->num, target_pid_to_str (fp->ptid));
500 printf_filtered (_(" (main process)"));
501 printf_filtered (_(" at "));
502 fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
504 sal = find_pc_line (pc, 0);
507 char *tmp = strrchr (sal.symtab->filename, '/');
510 printf_filtered (_(", file %s"), tmp + 1);
512 printf_filtered (_(", file %s"), sal.symtab->filename);
515 printf_filtered (_(", line %d"), sal.line);
516 if (!sal.symtab && !sal.line)
518 struct minimal_symbol *msym;
520 msym = lookup_minimal_symbol_by_pc (pc);
522 printf_filtered (", <%s>", SYMBOL_LINKAGE_NAME (msym));
525 putchar_filtered ('\n');
530 printf_filtered (_("No checkpoint number %d.\n"), requested);
532 printf_filtered (_("No checkpoints.\n"));
536 /* The PID of the process we're checkpointing. */
537 static int checkpointing_pid = 0;
540 linux_fork_checkpointing_p (int pid)
542 return (checkpointing_pid == pid);
546 checkpoint_command (char *args, int from_tty)
548 struct objfile *fork_objf;
549 struct gdbarch *gdbarch;
550 struct target_waitstatus last_target_waitstatus;
551 ptid_t last_target_ptid;
552 struct value *fork_fn = NULL, *ret;
553 struct fork_info *fp;
555 struct cleanup *old_chain;
558 /* Make the inferior fork, record its (and gdb's) state. */
560 if (lookup_minimal_symbol ("fork", NULL, NULL) != NULL)
561 fork_fn = find_function_in_inferior ("fork", &fork_objf);
563 if (lookup_minimal_symbol ("_fork", NULL, NULL) != NULL)
564 fork_fn = find_function_in_inferior ("fork", &fork_objf);
566 error (_("checkpoint: can't find fork function in inferior."));
568 gdbarch = get_objfile_arch (fork_objf);
569 ret = value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
571 /* Tell linux-nat.c that we're checkpointing this inferior. */
572 old_chain = make_cleanup_restore_integer (&checkpointing_pid);
573 checkpointing_pid = PIDGET (inferior_ptid);
575 ret = call_function_by_hand (fork_fn, 0, &ret);
576 do_cleanups (old_chain);
577 if (!ret) /* Probably can't happen. */
578 error (_("checkpoint: call_function_by_hand returned null."));
580 retpid = value_as_long (ret);
581 get_last_target_status (&last_target_ptid, &last_target_waitstatus);
586 printf_filtered (_("checkpoint: fork returned pid %ld.\n"),
590 parent_pid = ptid_get_lwp (last_target_ptid);
592 parent_pid = ptid_get_pid (last_target_ptid);
593 printf_filtered (_(" gdb says parent = %ld.\n"),
598 fp = find_fork_pid (retpid);
600 error (_("Failed to find new fork"));
601 fork_save_infrun_state (fp, 1);
605 linux_fork_context (struct fork_info *newfp, int from_tty)
607 /* Now we attempt to switch processes. */
608 struct fork_info *oldfp;
612 gdb_assert (newfp != NULL);
614 oldfp = find_fork_ptid (inferior_ptid);
615 gdb_assert (oldfp != NULL);
617 fork_save_infrun_state (oldfp, 1);
618 remove_breakpoints ();
619 fork_load_infrun_state (newfp);
620 insert_breakpoints ();
622 printf_filtered (_("Switching to %s\n"),
623 target_pid_to_str (inferior_ptid));
625 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
628 /* Switch inferior process (checkpoint) context, by checkpoint id. */
630 restart_command (char *args, int from_tty)
632 struct fork_info *fp;
635 error (_("Requires argument (checkpoint id to restart)"));
637 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
638 error (_("Not found: checkpoint id %s"), args);
640 linux_fork_context (fp, from_tty);
644 _initialize_linux_fork (void)
648 /* Checkpoint command: create a fork of the inferior process
649 and set it aside for later debugging. */
651 add_com ("checkpoint", class_obscure, checkpoint_command, _("\
652 Fork a duplicate process (experimental)."));
654 /* Restart command: restore the context of a specified checkpoint
657 add_com ("restart", class_obscure, restart_command, _("\
658 restart <n>: restore program context from a checkpoint.\n\
659 Argument 'n' is checkpoint ID, as displayed by 'info checkpoints'."));
661 /* Delete checkpoint command: kill the process and remove it from
664 add_cmd ("checkpoint", class_obscure, delete_checkpoint_command, _("\
665 Delete a checkpoint (experimental)."),
668 /* Detach checkpoint command: release the process to run independently,
669 and remove it from the fork list. */
671 add_cmd ("checkpoint", class_obscure, detach_checkpoint_command, _("\
672 Detach from a checkpoint (experimental)."),
675 /* Info checkpoints command: list all forks/checkpoints
676 currently under gdb's control. */
678 add_info ("checkpoints", info_checkpoints_command,
679 _("IDs of currently known checkpoints."));