* linux-fork.c (delete_fork_command, detach_fork_command): Use
[deliverable/binutils-gdb.git] / gdb / linux-fork.c
1 /* GNU/Linux native-dependent code for debugging multiple forks.
2
3 Copyright (C) 2005, 2006 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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. */
21
22 #include "defs.h"
23 #include "inferior.h"
24 #include "regcache.h"
25 #include "gdbcmd.h"
26 #include "infcall.h"
27 #include "gdb_string.h"
28 #include "linux-fork.h"
29
30 #include <sys/ptrace.h>
31 #include <sys/wait.h>
32 #include <sys/param.h>
33 #include <dirent.h>
34 #include <ctype.h>
35
36 struct fork_info *fork_list;
37 static int highest_fork_num;
38
39 /* Prevent warning from -Wmissing-prototypes. */
40 extern void _initialize_linux_fork (void);
41
42 int detach_fork = 1; /* Default behavior is to detach
43 newly forked processes (legacy). */
44
45 /* Fork list data structure: */
46 struct fork_info
47 {
48 struct fork_info *next;
49 ptid_t ptid;
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 ULONGEST pc; /* PC for info fork. */
55 off_t *filepos; /* Set of open file descriptors' offsets. */
56 int maxfd;
57 };
58
59 /* Fork list methods: */
60
61 extern int
62 forks_exist_p (void)
63 {
64 return (fork_list != NULL);
65 }
66
67 /* Add a fork to internal fork list.
68 Called from linux child_follow_fork. */
69
70 extern struct fork_info *
71 add_fork (pid_t pid)
72 {
73 struct fork_info *fp;
74
75 if (fork_list == NULL &&
76 pid != PIDGET (inferior_ptid))
77 {
78 /* Special case -- if this is the first fork in the list
79 (the list is hitherto empty), and if this new fork is
80 NOT the current inferior_ptid, then add inferior_ptid
81 first, as a special zeroeth fork id. */
82 highest_fork_num = -1;
83 add_fork (PIDGET (inferior_ptid)); /* safe recursion */
84 }
85
86 fp = XZALLOC (struct fork_info);
87 fp->ptid = pid_to_ptid (pid);
88 fp->num = ++highest_fork_num;
89 fp->next = fork_list;
90 fork_list = fp;
91 return fp;
92 }
93
94 static void
95 free_fork (struct fork_info *fp)
96 {
97 /* Notes on step-resume breakpoints: since this is a concern for
98 threads, let's convince ourselves that it's not a concern for
99 forks. There are two ways for a fork_info to be created. First,
100 by the checkpoint command, in which case we're at a gdb prompt
101 and there can't be any step-resume breakpoint. Second, by a fork
102 in the user program, in which case we *may* have stepped into the
103 fork call, but regardless of whether we follow the parent or the
104 child, we will return to the same place and the step-resume
105 breakpoint, if any, will take care of itself as usual. And
106 unlike threads, we do not save a private copy of the step-resume
107 breakpoint -- so we're OK. */
108
109 if (fp)
110 {
111 if (fp->savedregs)
112 regcache_xfree (fp->savedregs);
113 if (fp->filepos)
114 xfree (fp->filepos);
115 xfree (fp);
116 }
117 }
118
119 static void
120 delete_fork (ptid_t ptid)
121 {
122 struct fork_info *fp, *fpprev;
123
124 fpprev = NULL;
125
126 for (fp = fork_list; fp; fpprev = fp, fp = fp->next)
127 if (ptid_equal (fp->ptid, ptid))
128 break;
129
130 if (!fp)
131 return;
132
133 if (fpprev)
134 fpprev->next = fp->next;
135 else
136 fork_list = fp->next;
137
138 free_fork (fp);
139
140 /* Special case: if there is now only one process in the list,
141 and if it is (hopefully!) the current inferior_ptid, then
142 remove it, leaving the list empty -- we're now down to the
143 default case of debugging a single process. */
144 if (fork_list != NULL && fork_list->next == NULL &&
145 ptid_equal (fork_list->ptid, inferior_ptid))
146 {
147 /* Last fork -- delete from list and handle as solo process
148 (should be a safe recursion). */
149 delete_fork (inferior_ptid);
150 }
151 }
152
153 /* Find a fork_info by matching PTID. */
154 static struct fork_info *
155 find_fork_ptid (ptid_t ptid)
156 {
157 struct fork_info *fp;
158
159 for (fp = fork_list; fp; fp = fp->next)
160 if (ptid_equal (fp->ptid, ptid))
161 return fp;
162
163 return NULL;
164 }
165
166 /* Find a fork_info by matching ID. */
167 static struct fork_info *
168 find_fork_id (int num)
169 {
170 struct fork_info *fp;
171
172 for (fp = fork_list; fp; fp = fp->next)
173 if (fp->num == num)
174 return fp;
175
176 return NULL;
177 }
178
179 /* Find a fork_info by matching pid. */
180 extern struct fork_info *
181 find_fork_pid (pid_t pid)
182 {
183 struct fork_info *fp;
184
185 for (fp = fork_list; fp; fp = fp->next)
186 if (pid == ptid_get_pid (fp->ptid))
187 return fp;
188
189 return NULL;
190 }
191
192 static ptid_t
193 fork_id_to_ptid (int num)
194 {
195 struct fork_info *fork = find_fork_id (num);
196 if (fork)
197 return fork->ptid;
198 else
199 return pid_to_ptid (-1);
200 }
201
202 static void
203 init_fork_list (void)
204 {
205 struct fork_info *fp, *fpnext;
206
207 if (!fork_list)
208 return;
209
210 for (fp = fork_list; fp; fp = fpnext)
211 {
212 fpnext = fp->next;
213 free_fork (fp);
214 }
215
216 fork_list = NULL;
217 }
218
219 /* Fork list <-> gdb interface. */
220
221 /* Utility function for fork_load/fork_save.
222 Calls lseek in the (current) inferior process. */
223
224 static off_t
225 call_lseek (int fd, off_t offset, int whence)
226 {
227 char exp[80];
228
229 snprintf (&exp[0], sizeof (exp), "lseek (%d, %ld, %d)",
230 fd, (long) offset, whence);
231 return (off_t) parse_and_eval_long (&exp[0]);
232 }
233
234 /* Load infrun state for the fork PTID. */
235
236 static void
237 fork_load_infrun_state (struct fork_info *fp)
238 {
239 extern void nullify_last_target_wait_ptid ();
240 int i;
241
242 if (fp->savedregs && fp->clobber_regs)
243 regcache_cpy (current_regcache, fp->savedregs);
244
245 nullify_last_target_wait_ptid ();
246
247 /* Now restore the file positions of open file descriptors. */
248 if (fp->filepos)
249 {
250 for (i = 0; i <= fp->maxfd; i++)
251 if (fp->filepos[i] != (off_t) -1)
252 call_lseek (i, fp->filepos[i], SEEK_SET);
253 /* NOTE: I can get away with using SEEK_SET and SEEK_CUR because
254 this is native-only. If it ever has to be cross, we'll have
255 to rethink this. */
256 }
257 }
258
259 /* Save infrun state for the fork PTID.
260 Exported for use by linux child_follow_fork. */
261
262 extern void
263 fork_save_infrun_state (struct fork_info *fp, int clobber_regs)
264 {
265 char path[MAXPATHLEN];
266 struct dirent *de;
267 DIR *d;
268
269 if (fp->savedregs)
270 regcache_xfree (fp->savedregs);
271
272 fp->savedregs = regcache_dup (current_regcache);
273 fp->clobber_regs = clobber_regs;
274 fp->pc = read_pc ();
275
276 if (clobber_regs)
277 {
278 /* Now save the 'state' (file position) of all open file descriptors.
279 Unfortunately fork does not take care of that for us... */
280 snprintf (path, MAXPATHLEN, "/proc/%ld/fd", (long) PIDGET (fp->ptid));
281 if ((d = opendir (path)) != NULL)
282 {
283 long tmp;
284
285 fp->maxfd = 0;
286 while ((de = readdir (d)) != NULL)
287 {
288 /* Count open file descriptors (actually find highest
289 numbered). */
290 tmp = strtol (&de->d_name[0], NULL, 10);
291 if (fp->maxfd < tmp)
292 fp->maxfd = tmp;
293 }
294 /* Allocate array of file positions. */
295 fp->filepos = xrealloc (fp->filepos,
296 (fp->maxfd + 1) * sizeof (*fp->filepos));
297
298 /* Initialize to -1 (invalid). */
299 for (tmp = 0; tmp <= fp->maxfd; tmp++)
300 fp->filepos[tmp] = -1;
301
302 /* Now find actual file positions. */
303 rewinddir (d);
304 while ((de = readdir (d)) != NULL)
305 if (isdigit (de->d_name[0]))
306 {
307 tmp = strtol (&de->d_name[0], NULL, 10);
308 fp->filepos[tmp] = call_lseek (tmp, 0, SEEK_CUR);
309 }
310 closedir (d);
311 }
312 }
313 }
314
315 /* Kill 'em all, let God sort 'em out... */
316
317 extern void
318 linux_fork_killall (void)
319 {
320 /* Walk list and kill every pid. No need to treat the
321 current inferior_ptid as special (we do not return a
322 status for it) -- however any process may be a child
323 or a parent, so may get a SIGCHLD from a previously
324 killed child. Wait them all out. */
325 pid_t pid, ret;
326 int status;
327
328 do {
329 pid = PIDGET (fork_list->ptid);
330 do {
331 ptrace (PT_KILL, pid, 0, 0);
332 ret = waitpid (pid, &status, 0);
333 } while (ret == pid && WIFSTOPPED (status));
334 delete_fork (fork_list->ptid);
335 } while (fork_list != NULL);
336 }
337
338 /* The current inferior_ptid has exited, but there are other viable
339 forks to debug. Delete the exiting one and context-switch to the
340 first available. */
341
342 extern void
343 linux_fork_mourn_inferior (void)
344 {
345 /* Wait just one more time to collect the inferior's exit status.
346 Do not check whether this succeeds though, since we may be
347 dealing with a process that we attached to. Such a process will
348 only report its exit status to its original parent. */
349 int status;
350
351 waitpid (ptid_get_pid (inferior_ptid), &status, 0);
352
353 /* OK, presumably inferior_ptid is the one who has exited.
354 We need to delete that one from the fork_list, and switch
355 to the next available fork. */
356 delete_fork (inferior_ptid);
357 if (fork_list) /* Paranoia, shouldn't happen. */
358 {
359 inferior_ptid = fork_list[0].ptid;
360 printf_filtered (_("[Switching to %s]\n"),
361 target_pid_to_str (inferior_ptid));
362 }
363 }
364
365 /* Fork list <-> user interface. */
366
367 static void
368 delete_fork_command (char *args, int from_tty)
369 {
370 ptid_t ptid;
371
372 if (!args || !*args)
373 error (_("Requires argument (fork/checkpoint id to delete)"));
374
375 ptid = fork_id_to_ptid (parse_and_eval_long (args));
376 if (ptid_equal (ptid, minus_one_ptid))
377 error (_("No such fork/checkpoint id, %s"), args);
378
379 if (ptid_equal (ptid, inferior_ptid))
380 error (_("Please switch to another fork/checkpoint before deleting the current one"));
381
382 if (ptrace (PTRACE_KILL, PIDGET (ptid), 0, 0))
383 error (_("Unable to kill pid %s"), target_tid_to_str (ptid));
384
385 if (from_tty)
386 printf_filtered (_("Killed %s\n"), target_pid_to_str (ptid));
387
388 delete_fork (ptid);
389 }
390
391 static void
392 detach_fork_command (char *args, int from_tty)
393 {
394 ptid_t ptid;
395
396 if (!args || !*args)
397 error (_("Requires argument (fork id to detach)"));
398
399 ptid = fork_id_to_ptid (parse_and_eval_long (args));
400 if (ptid_equal (ptid, minus_one_ptid))
401 error (_("No such fork id, %s"), args);
402
403 if (ptid_equal (ptid, inferior_ptid))
404 error (_("Please switch to another fork before detaching the current one"));
405
406 if (ptrace (PTRACE_DETACH, PIDGET (ptid), 0, 0))
407 error (_("Unable to detach %s"), target_pid_to_str (ptid));
408
409 if (from_tty)
410 printf_filtered (_("Detached %s\n"), target_pid_to_str (ptid));
411
412 delete_fork (ptid);
413 }
414
415 /* Print information about currently known forks. */
416
417 static void
418 info_forks_command (char *arg, int from_tty)
419 {
420 struct frame_info *cur_frame;
421 struct symtab_and_line sal;
422 struct symtab *cur_symtab;
423 struct fork_info *fp;
424 int cur_line;
425 ULONGEST pc;
426
427 for (fp = fork_list; fp; fp = fp->next)
428 {
429 if (ptid_equal (fp->ptid, inferior_ptid))
430 {
431 printf_filtered ("* ");
432 pc = read_pc ();
433 }
434 else
435 {
436 printf_filtered (" ");
437 pc = fp->pc;
438 }
439 printf_filtered ("%d %s", fp->num, target_pid_to_str (fp->ptid));
440 if (fp->num == 0)
441 printf_filtered (_(" (main process)"));
442 printf_filtered (_(" at "));
443 deprecated_print_address_numeric (pc, 1, gdb_stdout);
444
445 sal = find_pc_line (pc, 0);
446 if (sal.symtab)
447 {
448 char *tmp = strrchr (sal.symtab->filename, '/');
449
450 if (tmp)
451 printf_filtered (_(", file %s"), tmp + 1);
452 else
453 printf_filtered (_(", file %s"), sal.symtab->filename);
454 }
455 if (sal.line)
456 printf_filtered (_(", line %d"), sal.line);
457 if (!sal.symtab && !sal.line)
458 {
459 struct minimal_symbol *msym;
460
461 msym = lookup_minimal_symbol_by_pc (pc);
462 if (msym)
463 printf_filtered (", <%s>", SYMBOL_LINKAGE_NAME (msym));
464 }
465
466 putchar_filtered ('\n');
467 }
468 }
469
470 /* Save/restore mode variable 'detach_fork':
471 We need to temporarily take over this mode variable, while
472 preserving the user-specified state, and make sure that it
473 gets restored in case of error.
474
475 The int pointer that we use comes from the caller, so we can
476 be called more than once (even though currently we don't need to). */
477
478 static void
479 restore_detach_fork (void *arg)
480 {
481 detach_fork = *(int *) arg;
482 }
483
484 static struct cleanup *
485 save_detach_fork (int *saved_val)
486 {
487 *saved_val = detach_fork;
488 return make_cleanup (restore_detach_fork, (void *) saved_val);
489 }
490
491 static void
492 checkpoint_command (char *args, int from_tty)
493 {
494 struct target_waitstatus last_target_waitstatus;
495 ptid_t last_target_ptid;
496 struct value *fork_fn = NULL, *ret;
497 struct fork_info *fp;
498 pid_t retpid;
499 struct cleanup *old_chain;
500 long i;
501 /* Make this temp var static, 'cause it's used in the error context. */
502 static int temp_detach_fork;
503
504 /* Make the inferior fork, record its (and gdb's) state. */
505
506 if (lookup_minimal_symbol ("fork", NULL, NULL) != NULL)
507 fork_fn = find_function_in_inferior ("fork");
508 if (!fork_fn)
509 if (lookup_minimal_symbol ("_fork", NULL, NULL) != NULL)
510 fork_fn = find_function_in_inferior ("fork");
511 if (!fork_fn)
512 error (_("checkpoint: can't find fork function in inferior."));
513
514 ret = value_from_longest (builtin_type_int, 0);
515 old_chain = save_detach_fork (&temp_detach_fork);
516 detach_fork = 0;
517 ret = call_function_by_hand (fork_fn, 0, &ret);
518 do_cleanups (old_chain);
519 if (!ret) /* Probably can't happen. */
520 error (_("checkpoint: call_function_by_hand returned null."));
521
522 retpid = value_as_long (ret);
523 get_last_target_status (&last_target_ptid, &last_target_waitstatus);
524 if (from_tty)
525 {
526 int parent_pid;
527
528 printf_filtered (_("checkpoint: fork returned pid %ld.\n"),
529 (long) retpid);
530 if (info_verbose)
531 {
532 parent_pid = ptid_get_lwp (last_target_ptid);
533 if (parent_pid == 0)
534 parent_pid = ptid_get_pid (last_target_ptid);
535 printf_filtered (_(" gdb says parent = %ld.\n"),
536 (long) parent_pid);
537 }
538 }
539
540 fp = find_fork_pid (retpid);
541 if (!fp)
542 error (_("Failed to find new fork"));
543 fork_save_infrun_state (fp, 1);
544 }
545
546 static void
547 linux_fork_context (struct fork_info *newfp, int from_tty)
548 {
549 /* Now we attempt to switch processes. */
550 struct fork_info *oldfp = find_fork_ptid (inferior_ptid);
551 ptid_t ptid;
552 int id, i;
553
554 if (!newfp)
555 error (_("No such fork/process"));
556
557 if (!oldfp)
558 {
559 oldfp = add_fork (ptid_get_pid (inferior_ptid));
560 }
561
562 fork_save_infrun_state (oldfp, 1);
563 inferior_ptid = newfp->ptid;
564 fork_load_infrun_state (newfp);
565 registers_changed ();
566 reinit_frame_cache ();
567 stop_pc = read_pc ();
568 select_frame (get_current_frame ());
569
570 printf_filtered (_("Switching to %s\n"),
571 target_pid_to_str (inferior_ptid));
572
573 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC);
574 }
575
576 /* Switch inferior process (fork) context, by process id. */
577 static void
578 process_command (char *args, int from_tty)
579 {
580 struct fork_info *fp;
581
582 if (!args || !*args)
583 error (_("Requires argument (process id to switch to)"));
584
585 if ((fp = find_fork_pid (parse_and_eval_long (args))) == NULL)
586 error (_("Not found: process id %s"), args);
587
588 linux_fork_context (fp, from_tty);
589 }
590
591 /* Switch inferior process (fork) context, by fork id. */
592 static void
593 fork_command (char *args, int from_tty)
594 {
595 struct fork_info *fp;
596
597 if (!args || !*args)
598 error (_("Requires argument (fork id to switch to)"));
599
600 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
601 error (_("Not found: fork id %s"), args);
602
603 linux_fork_context (fp, from_tty);
604 }
605
606 /* Switch inferior process (fork) context, by checkpoint id. */
607 static void
608 restart_command (char *args, int from_tty)
609 {
610 struct fork_info *fp;
611
612 if (!args || !*args)
613 error (_("Requires argument (checkpoint id to restart)"));
614
615 if ((fp = find_fork_id (parse_and_eval_long (args))) == NULL)
616 error (_("Not found: checkpoint id %s"), args);
617
618 linux_fork_context (fp, from_tty);
619 }
620
621 void
622 _initialize_linux_fork (void)
623 {
624 init_fork_list ();
625
626 /* Set/show detach-on-fork: user-settable mode. */
627
628 add_setshow_boolean_cmd ("detach-on-fork", class_obscure, &detach_fork, _("\
629 Set whether gdb will detach the child of a fork."), _("\
630 Show whether gdb will detach the child of a fork."), _("\
631 Tells gdb whether to detach the child of a fork."),
632 NULL, NULL, &setlist, &showlist);
633
634 /* Set/show restart-auto-finish: user-settable count. Causes the
635 first "restart" of a fork to do some number of "finish" commands
636 before returning to user.
637
638 Useful because otherwise the virgin fork process will be stopped
639 somewhere in the un-interesting fork system call. */
640
641 /* Checkpoint command: create a fork of the inferior process
642 and set it aside for later debugging. */
643
644 add_com ("checkpoint", class_obscure, checkpoint_command, _("\
645 Fork a duplicate process (experimental)."));
646
647 /* Restart command: restore the context of a specified fork
648 process. May be used for "program forks" as well as for
649 "debugger forks" (checkpoints). */
650
651 add_com ("restart", class_obscure, restart_command, _("\
652 restart <n>: restore program context from a checkpoint.\n\
653 Argument 'n' is checkpoint ID, as displayed by 'info checkpoints'."));
654
655 /* Delete-checkpoint command: kill the process and remove it from
656 fork list. */
657
658 add_com ("delete-checkpoint", class_obscure, delete_fork_command, _("\
659 Delete a fork/checkpoint (experimental)."));
660
661 /* Detach-checkpoint command: release the process to run independantly,
662 and remove it from the fork list. */
663
664 add_com ("detach-checkpoint", class_obscure, detach_fork_command, _("\
665 Detach from a fork/checkpoint (experimental)."));
666
667 /* Info checkpoints command: list all forks/checkpoints
668 currently under gdb's control. */
669
670 add_info ("checkpoints", info_forks_command,
671 _("IDs of currently known forks/checkpoints."));
672
673 /* Command aliases (let "fork" and "checkpoint" be used
674 interchangeably). */
675
676 add_com_alias ("delete-fork", "delete-checkpoint", class_obscure, 1);
677 add_com_alias ("detach-fork", "detach-checkpoint", class_obscure, 1);
678 add_info_alias ("forks", "checkpoints", 0);
679
680 /* "fork <n>" (by analogy to "thread <n>"). */
681 add_com ("fork", class_obscure, fork_command, _("\
682 fork <n>: Switch between forked processes.\n\
683 Argument 'n' is fork ID, as displayed by 'info forks'."));
684
685 /* "process <proc id>" as opposed to "fork <fork id>". */
686 add_com ("process", class_obscure, process_command, _("\
687 process <pid>: Switch between forked processes.\n\
688 Argument 'pid' is process ID, as displayed by 'info forks' or 'shell ps'."));
689 }
This page took 0.055626 seconds and 5 git commands to generate.