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