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