Fix up mix of man(7)/mdoc(7).
[netbsd-mini2440.git] / gnu / dist / gdb6 / gdb / linux-fork.c
blobe96275b8d577ef3252010a1b5db45b4dfb41704b
1 /* GNU/Linux native-dependent code for debugging multiple forks.
3 Copyright (C) 2005, 2006 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 2 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, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 #include "defs.h"
23 #include "inferior.h"
24 #include "regcache.h"
25 #include "gdbcmd.h"
26 #include "infcall.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>
33 #include <sys/wait.h>
34 #include <sys/param.h>
35 #include <dirent.h>
36 #include <ctype.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 int detach_fork = 1; /* Default behavior is to detach
45 newly forked processes (legacy). */
47 /* Fork list data structure: */
48 struct fork_info
50 struct fork_info *next;
51 ptid_t ptid;
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 ULONGEST pc; /* PC for info fork. */
57 off_t *filepos; /* Set of open file descriptors' offsets. */
58 int maxfd;
61 /* Fork list methods: */
63 extern int
64 forks_exist_p (void)
66 return (fork_list != NULL);
69 /* Add a fork to internal fork list.
70 Called from linux child_follow_fork. */
72 extern struct fork_info *
73 add_fork (pid_t pid)
75 struct fork_info *fp;
77 if (fork_list == NULL && pid != PIDGET (inferior_ptid))
79 /* Special case -- if this is the first fork in the list
80 (the list is hitherto empty), and if this new fork is
81 NOT the current inferior_ptid, then add inferior_ptid
82 first, as a special zeroeth fork id. */
83 highest_fork_num = -1;
84 add_fork (PIDGET (inferior_ptid)); /* safe recursion */
87 fp = XZALLOC (struct fork_info);
88 fp->ptid = ptid_build (pid, pid, 0);
89 fp->num = ++highest_fork_num;
90 fp->next = fork_list;
91 fork_list = fp;
92 return fp;
95 static void
96 free_fork (struct fork_info *fp)
98 /* Notes on step-resume breakpoints: since this is a concern for
99 threads, let's convince ourselves that it's not a concern for
100 forks. There are two ways for a fork_info to be created. First,
101 by the checkpoint command, in which case we're at a gdb prompt
102 and there can't be any step-resume breakpoint. Second, by a fork
103 in the user program, in which case we *may* have stepped into the
104 fork call, but regardless of whether we follow the parent or the
105 child, we will return to the same place and the step-resume
106 breakpoint, if any, will take care of itself as usual. And
107 unlike threads, we do not save a private copy of the step-resume
108 breakpoint -- so we're OK. */
110 if (fp)
112 if (fp->savedregs)
113 regcache_xfree (fp->savedregs);
114 if (fp->filepos)
115 xfree (fp->filepos);
116 xfree (fp);
120 static void
121 delete_fork (ptid_t ptid)
123 struct fork_info *fp, *fpprev;
125 fpprev = NULL;
127 for (fp = fork_list; fp; fpprev = fp, fp = fp->next)
128 if (ptid_equal (fp->ptid, ptid))
129 break;
131 if (!fp)
132 return;
134 if (fpprev)
135 fpprev->next = fp->next;
136 else
137 fork_list = fp->next;
139 free_fork (fp);
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))
162 return fp;
164 return NULL;
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)
174 if (fp->num == num)
175 return fp;
177 return NULL;
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))
188 return fp;
190 return NULL;
193 static ptid_t
194 fork_id_to_ptid (int num)
196 struct fork_info *fork = find_fork_id (num);
197 if (fork)
198 return fork->ptid;
199 else
200 return pid_to_ptid (-1);
203 static void
204 init_fork_list (void)
206 struct fork_info *fp, *fpnext;
208 if (!fork_list)
209 return;
211 for (fp = fork_list; fp; fp = fpnext)
213 fpnext = fp->next;
214 free_fork (fp);
217 fork_list = NULL;
220 /* Fork list <-> gdb interface. */
222 /* Utility function for fork_load/fork_save.
223 Calls lseek in the (current) inferior process. */
225 static off_t
226 call_lseek (int fd, off_t offset, int whence)
228 char exp[80];
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. */
237 static void
238 fork_load_infrun_state (struct fork_info *fp)
240 extern void nullify_last_target_wait_ptid ();
241 int i;
243 inferior_ptid = fp->ptid;
245 linux_nat_switch_fork (inferior_ptid);
247 if (fp->savedregs && fp->clobber_regs)
248 regcache_cpy (current_regcache, fp->savedregs);
250 registers_changed ();
251 reinit_frame_cache ();
253 /* We must select a new frame before making any inferior calls to
254 avoid warnings. */
255 select_frame (get_current_frame ());
257 stop_pc = read_pc ();
258 nullify_last_target_wait_ptid ();
260 /* Now restore the file positions of open file descriptors. */
261 if (fp->filepos)
263 for (i = 0; i <= fp->maxfd; i++)
264 if (fp->filepos[i] != (off_t) -1)
265 call_lseek (i, fp->filepos[i], SEEK_SET);
266 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
267 this is native-only. If it ever has to be cross, we'll have
268 to rethink this. */
272 /* Save infrun state for the fork PTID.
273 Exported for use by linux child_follow_fork. */
275 extern void
276 fork_save_infrun_state (struct fork_info *fp, int clobber_regs)
278 char path[MAXPATHLEN];
279 struct dirent *de;
280 DIR *d;
282 if (fp->savedregs)
283 regcache_xfree (fp->savedregs);
285 fp->savedregs = regcache_dup (current_regcache);
286 fp->clobber_regs = clobber_regs;
287 fp->pc = read_pc ();
289 if (clobber_regs)
291 /* Now save the 'state' (file position) of all open file descriptors.
292 Unfortunately fork does not take care of that for us... */
293 snprintf (path, MAXPATHLEN, "/proc/%ld/fd", (long) PIDGET (fp->ptid));
294 if ((d = opendir (path)) != NULL)
296 long tmp;
298 fp->maxfd = 0;
299 while ((de = readdir (d)) != NULL)
301 /* Count open file descriptors (actually find highest
302 numbered). */
303 tmp = strtol (&de->d_name[0], NULL, 10);
304 if (fp->maxfd < tmp)
305 fp->maxfd = tmp;
307 /* Allocate array of file positions. */
308 fp->filepos = xrealloc (fp->filepos,
309 (fp->maxfd + 1) * sizeof (*fp->filepos));
311 /* Initialize to -1 (invalid). */
312 for (tmp = 0; tmp <= fp->maxfd; tmp++)
313 fp->filepos[tmp] = -1;
315 /* Now find actual file positions. */
316 rewinddir (d);
317 while ((de = readdir (d)) != NULL)
318 if (isdigit (de->d_name[0]))
320 tmp = strtol (&de->d_name[0], NULL, 10);
321 fp->filepos[tmp] = call_lseek (tmp, 0, SEEK_CUR);
323 closedir (d);
328 /* Kill 'em all, let God sort 'em out... */
330 extern void
331 linux_fork_killall (void)
333 /* Walk list and kill every pid. No need to treat the
334 current inferior_ptid as special (we do not return a
335 status for it) -- however any process may be a child
336 or a parent, so may get a SIGCHLD from a previously
337 killed child. Wait them all out. */
338 struct fork_info *fp;
339 pid_t pid, ret;
340 int status;
342 for (fp = fork_list; fp; fp = fp->next)
344 pid = PIDGET (fp->ptid);
345 do {
346 ptrace (PT_KILL, pid, 0, 0);
347 ret = waitpid (pid, &status, 0);
348 /* We might get a SIGCHLD instead of an exit status. This is
349 aggravated by the first kill above - a child has just
350 died. MVS comment cut-and-pasted from linux-nat. */
351 } while (ret == pid && WIFSTOPPED (status));
353 init_fork_list (); /* Clear list, prepare to start fresh. */
356 /* The current inferior_ptid has exited, but there are other viable
357 forks to debug. Delete the exiting one and context-switch to the
358 first available. */
360 extern void
361 linux_fork_mourn_inferior (void)
363 /* Wait just one more time to collect the inferior's exit status.
364 Do not check whether this succeeds though, since we may be
365 dealing with a process that we attached to. Such a process will
366 only report its exit status to its original parent. */
367 int status;
369 waitpid (ptid_get_pid (inferior_ptid), &status, 0);
371 /* OK, presumably inferior_ptid is the one who has exited.
372 We need to delete that one from the fork_list, and switch
373 to the next available fork. */
374 delete_fork (inferior_ptid);
376 /* There should still be a fork - if there's only one left,
377 delete_fork won't remove it, because we haven't updated
378 inferior_ptid yet. */
379 gdb_assert (fork_list);
381 fork_load_infrun_state (fork_list);
382 printf_filtered (_("[Switching to %s]\n"),
383 target_pid_to_str (inferior_ptid));
385 /* If there's only one fork, switch back to non-fork mode. */
386 if (fork_list->next == NULL)
387 delete_fork (inferior_ptid);
390 /* Fork list <-> user interface. */
392 static void
393 delete_fork_command (char *args, int from_tty)
395 ptid_t ptid;
397 if (!args || !*args)
398 error (_("Requires argument (fork/checkpoint id to delete)"));
400 ptid = fork_id_to_ptid (parse_and_eval_long (args));
401 if (ptid_equal (ptid, minus_one_ptid))
402 error (_("No such fork/checkpoint id, %s"), args);
404 if (ptid_equal (ptid, inferior_ptid))
405 error (_("Please switch to another fork/checkpoint before deleting the current one"));
407 if (ptrace (PTRACE_KILL, PIDGET (ptid), 0, 0))
408 error (_("Unable to kill pid %s"), target_tid_to_str (ptid));
410 if (from_tty)
411 printf_filtered (_("Killed %s\n"), target_pid_to_str (ptid));
413 delete_fork (ptid);
416 static void
417 detach_fork_command (char *args, int from_tty)
419 ptid_t ptid;
421 if (!args || !*args)
422 error (_("Requires argument (fork id to detach)"));
424 ptid = fork_id_to_ptid (parse_and_eval_long (args));
425 if (ptid_equal (ptid, minus_one_ptid))
426 error (_("No such fork id, %s"), args);
428 if (ptid_equal (ptid, inferior_ptid))
429 error (_("Please switch to another fork before detaching the current one"));
431 if (ptrace (PTRACE_DETACH, PIDGET (ptid), 0, 0))
432 error (_("Unable to detach %s"), target_pid_to_str (ptid));
434 if (from_tty)
435 printf_filtered (_("Detached %s\n"), target_pid_to_str (ptid));
437 delete_fork (ptid);
440 /* Print information about currently known forks. */
442 static void
443 info_forks_command (char *arg, int from_tty)
445 struct frame_info *cur_frame;
446 struct symtab_and_line sal;
447 struct symtab *cur_symtab;
448 struct fork_info *fp;
449 int cur_line;
450 ULONGEST pc;
451 int requested = -1;
452 struct fork_info *printed = NULL;
454 if (arg && *arg)
455 requested = (int) parse_and_eval_long (arg);
457 for (fp = fork_list; fp; fp = fp->next)
459 if (requested > 0 && fp->num != requested)
460 continue;
462 printed = fp;
463 if (ptid_equal (fp->ptid, inferior_ptid))
465 printf_filtered ("* ");
466 pc = read_pc ();
468 else
470 printf_filtered (" ");
471 pc = fp->pc;
473 printf_filtered ("%d %s", fp->num, target_pid_to_str (fp->ptid));
474 if (fp->num == 0)
475 printf_filtered (_(" (main process)"));
476 printf_filtered (_(" at "));
477 deprecated_print_address_numeric (pc, 1, gdb_stdout);
479 sal = find_pc_line (pc, 0);
480 if (sal.symtab)
482 char *tmp = strrchr (sal.symtab->filename, '/');
484 if (tmp)
485 printf_filtered (_(", file %s"), tmp + 1);
486 else
487 printf_filtered (_(", file %s"), sal.symtab->filename);
489 if (sal.line)
490 printf_filtered (_(", line %d"), sal.line);
491 if (!sal.symtab && !sal.line)
493 struct minimal_symbol *msym;
495 msym = lookup_minimal_symbol_by_pc (pc);
496 if (msym)
497 printf_filtered (", <%s>", SYMBOL_LINKAGE_NAME (msym));
500 putchar_filtered ('\n');
502 if (printed == NULL)
504 if (requested > 0)
505 printf_filtered (_("No fork number %d.\n"), requested);
506 else
507 printf_filtered (_("No forks.\n"));
511 /* Save/restore mode variable 'detach_fork':
512 We need to temporarily take over this mode variable, while
513 preserving the user-specified state, and make sure that it
514 gets restored in case of error.
516 The int pointer that we use comes from the caller, so we can
517 be called more than once (even though currently we don't need to). */
519 static void
520 restore_detach_fork (void *arg)
522 detach_fork = *(int *) arg;
525 static struct cleanup *
526 save_detach_fork (int *saved_val)
528 *saved_val = detach_fork;
529 return make_cleanup (restore_detach_fork, (void *) saved_val);
532 static void
533 checkpoint_command (char *args, int from_tty)
535 struct target_waitstatus last_target_waitstatus;
536 ptid_t last_target_ptid;
537 struct value *fork_fn = NULL, *ret;
538 struct fork_info *fp;
539 pid_t retpid;
540 struct cleanup *old_chain;
541 long i;
542 /* Make this temp var static, 'cause it's used in the error context. */
543 static int temp_detach_fork;
545 /* Make the inferior fork, record its (and gdb's) state. */
547 if (lookup_minimal_symbol ("fork", NULL, NULL) != NULL)
548 fork_fn = find_function_in_inferior ("fork");
549 if (!fork_fn)
550 if (lookup_minimal_symbol ("_fork", NULL, NULL) != NULL)
551 fork_fn = find_function_in_inferior ("fork");
552 if (!fork_fn)
553 error (_("checkpoint: can't find fork function in inferior."));
555 ret = value_from_longest (builtin_type_int, 0);
556 old_chain = save_detach_fork (&temp_detach_fork);
557 detach_fork = 0;
558 ret = call_function_by_hand (fork_fn, 0, &ret);
559 do_cleanups (old_chain);
560 if (!ret) /* Probably can't happen. */
561 error (_("checkpoint: call_function_by_hand returned null."));
563 retpid = value_as_long (ret);
564 get_last_target_status (&last_target_ptid, &last_target_waitstatus);
565 if (from_tty)
567 int parent_pid;
569 printf_filtered (_("checkpoint: fork returned pid %ld.\n"),
570 (long) retpid);
571 if (info_verbose)
573 parent_pid = ptid_get_lwp (last_target_ptid);
574 if (parent_pid == 0)
575 parent_pid = ptid_get_pid (last_target_ptid);
576 printf_filtered (_(" gdb says parent = %ld.\n"),
577 (long) parent_pid);
581 fp = find_fork_pid (retpid);
582 if (!fp)
583 error (_("Failed to find new fork"));
584 fork_save_infrun_state (fp, 1);
587 static void
588 linux_fork_context (struct fork_info *newfp, int from_tty)
590 /* Now we attempt to switch processes. */
591 struct fork_info *oldfp = find_fork_ptid (inferior_ptid);
592 ptid_t ptid;
593 int id, i;
595 if (!newfp)
596 error (_("No such fork/process"));
598 if (!oldfp)
599 oldfp = add_fork (ptid_get_pid (inferior_ptid));
601 fork_save_infrun_state (oldfp, 1);
602 fork_load_infrun_state (newfp);
604 printf_filtered (_("Switching to %s\n"),
605 target_pid_to_str (inferior_ptid));
607 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
610 /* Switch inferior process (fork) context, by process id. */
611 static void
612 process_command (char *args, int from_tty)
614 struct fork_info *fp;
616 if (!args || !*args)
617 error (_("Requires argument (process id to switch to)"));
619 if ((fp = find_fork_pid (parse_and_eval_long (args))) == NULL)
620 error (_("Not found: process id %s"), args);
622 linux_fork_context (fp, from_tty);
625 /* Switch inferior process (fork) context, by fork id. */
626 static void
627 fork_command (char *args, int from_tty)
629 struct fork_info *fp;
631 if (!args || !*args)
632 error (_("Requires argument (fork id to switch to)"));
634 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
635 error (_("Not found: fork id %s"), args);
637 linux_fork_context (fp, from_tty);
640 /* Switch inferior process (fork) context, by checkpoint id. */
641 static void
642 restart_command (char *args, int from_tty)
644 struct fork_info *fp;
646 if (!args || !*args)
647 error (_("Requires argument (checkpoint id to restart)"));
649 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
650 error (_("Not found: checkpoint id %s"), args);
652 linux_fork_context (fp, from_tty);
655 void
656 _initialize_linux_fork (void)
658 init_fork_list ();
660 /* Set/show detach-on-fork: user-settable mode. */
662 add_setshow_boolean_cmd ("detach-on-fork", class_obscure, &detach_fork, _("\
663 Set whether gdb will detach the child of a fork."), _("\
664 Show whether gdb will detach the child of a fork."), _("\
665 Tells gdb whether to detach the child of a fork."),
666 NULL, NULL, &setlist, &showlist);
668 /* Set/show restart-auto-finish: user-settable count. Causes the
669 first "restart" of a fork to do some number of "finish" commands
670 before returning to user.
672 Useful because otherwise the virgin fork process will be stopped
673 somewhere in the un-interesting fork system call. */
675 /* Checkpoint command: create a fork of the inferior process
676 and set it aside for later debugging. */
678 add_com ("checkpoint", class_obscure, checkpoint_command, _("\
679 Fork a duplicate process (experimental)."));
681 /* Restart command: restore the context of a specified fork
682 process. May be used for "program forks" as well as for
683 "debugger forks" (checkpoints). */
685 add_com ("restart", class_obscure, restart_command, _("\
686 restart <n>: restore program context from a checkpoint.\n\
687 Argument 'n' is checkpoint ID, as displayed by 'info checkpoints'."));
689 /* Delete checkpoint command: kill the process and remove it from
690 fork list. */
692 add_cmd ("checkpoint", class_obscure, delete_fork_command, _("\
693 Delete a fork/checkpoint (experimental)."),
694 &deletelist);
696 /* Detach-checkpoint command: release the process to run independantly,
697 and remove it from the fork list. */
699 add_com ("detach-checkpoint", class_obscure, detach_fork_command, _("\
700 Detach from a fork/checkpoint (experimental)."));
702 /* Info checkpoints command: list all forks/checkpoints
703 currently under gdb's control. */
705 add_info ("checkpoints", info_forks_command,
706 _("IDs of currently known forks/checkpoints."));
708 /* Command aliases (let "fork" and "checkpoint" be used
709 interchangeably). */
711 add_alias_cmd ("fork", "checkpoint", class_obscure, 1, &deletelist);
712 add_com_alias ("detach-fork", "detach-checkpoint", class_obscure, 1);
713 add_info_alias ("forks", "checkpoints", 0);
715 /* "fork <n>" (by analogy to "thread <n>"). */
716 add_com ("fork", class_obscure, fork_command, _("\
717 fork <n>: Switch between forked processes.\n\
718 Argument 'n' is fork ID, as displayed by 'info forks'."));
720 /* "process <proc id>" as opposed to "fork <fork id>". */
721 add_com ("process", class_obscure, process_command, _("\
722 process <pid>: Switch between forked processes.\n\
723 Argument 'pid' is process ID, as displayed by 'info forks' or 'shell ps'."));