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