Fix compile in the !HAVE_KINFO_GETVMMAP case.
[external/binutils.git] / gdb / fbsd-nat.c
1 /* Native-dependent code for FreeBSD.
2
3    Copyright (C) 2002-2017 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 "gdbcore.h"
22 #include "inferior.h"
23 #include "regcache.h"
24 #include "regset.h"
25 #include "gdbcmd.h"
26 #include "gdbthread.h"
27 #include "gdb_wait.h"
28 #include <sys/types.h>
29 #include <sys/procfs.h>
30 #include <sys/ptrace.h>
31 #include <sys/signal.h>
32 #include <sys/sysctl.h>
33 #include <sys/user.h>
34 #ifdef HAVE_KINFO_GETVMMAP
35 #include <libutil.h>
36 #else
37 #include "filestuff.h"
38 #endif
39
40 #include "elf-bfd.h"
41 #include "fbsd-nat.h"
42
43 /* Return the name of a file that can be opened to get the symbols for
44    the child process identified by PID.  */
45
46 static char *
47 fbsd_pid_to_exec_file (struct target_ops *self, int pid)
48 {
49   ssize_t len;
50   static char buf[PATH_MAX];
51   char name[PATH_MAX];
52
53 #ifdef KERN_PROC_PATHNAME
54   size_t buflen;
55   int mib[4];
56
57   mib[0] = CTL_KERN;
58   mib[1] = KERN_PROC;
59   mib[2] = KERN_PROC_PATHNAME;
60   mib[3] = pid;
61   buflen = sizeof buf;
62   if (sysctl (mib, 4, buf, &buflen, NULL, 0) == 0)
63     return buf;
64 #endif
65
66   xsnprintf (name, PATH_MAX, "/proc/%d/exe", pid);
67   len = readlink (name, buf, PATH_MAX - 1);
68   if (len != -1)
69     {
70       buf[len] = '\0';
71       return buf;
72     }
73
74   return NULL;
75 }
76
77 #ifdef HAVE_KINFO_GETVMMAP
78 /* Iterate over all the memory regions in the current inferior,
79    calling FUNC for each memory region.  OBFD is passed as the last
80    argument to FUNC.  */
81
82 static int
83 fbsd_find_memory_regions (struct target_ops *self,
84                           find_memory_region_ftype func, void *obfd)
85 {
86   pid_t pid = ptid_get_pid (inferior_ptid);
87   struct kinfo_vmentry *vmentl, *kve;
88   uint64_t size;
89   struct cleanup *cleanup;
90   int i, nitems;
91
92   vmentl = kinfo_getvmmap (pid, &nitems);
93   if (vmentl == NULL)
94     perror_with_name (_("Couldn't fetch VM map entries."));
95   cleanup = make_cleanup (free, vmentl);
96
97   for (i = 0; i < nitems; i++)
98     {
99       kve = &vmentl[i];
100
101       /* Skip unreadable segments and those where MAP_NOCORE has been set.  */
102       if (!(kve->kve_protection & KVME_PROT_READ)
103           || kve->kve_flags & KVME_FLAG_NOCOREDUMP)
104         continue;
105
106       /* Skip segments with an invalid type.  */
107       if (kve->kve_type != KVME_TYPE_DEFAULT
108           && kve->kve_type != KVME_TYPE_VNODE
109           && kve->kve_type != KVME_TYPE_SWAP
110           && kve->kve_type != KVME_TYPE_PHYS)
111         continue;
112
113       size = kve->kve_end - kve->kve_start;
114       if (info_verbose)
115         {
116           fprintf_filtered (gdb_stdout, 
117                             "Save segment, %ld bytes at %s (%c%c%c)\n",
118                             (long) size,
119                             paddress (target_gdbarch (), kve->kve_start),
120                             kve->kve_protection & KVME_PROT_READ ? 'r' : '-',
121                             kve->kve_protection & KVME_PROT_WRITE ? 'w' : '-',
122                             kve->kve_protection & KVME_PROT_EXEC ? 'x' : '-');
123         }
124
125       /* Invoke the callback function to create the corefile segment.
126          Pass MODIFIED as true, we do not know the real modification state.  */
127       func (kve->kve_start, size, kve->kve_protection & KVME_PROT_READ,
128             kve->kve_protection & KVME_PROT_WRITE,
129             kve->kve_protection & KVME_PROT_EXEC, 1, obfd);
130     }
131   do_cleanups (cleanup);
132   return 0;
133 }
134 #else
135 static int
136 fbsd_read_mapping (FILE *mapfile, unsigned long *start, unsigned long *end,
137                    char *protection)
138 {
139   /* FreeBSD 5.1-RELEASE uses a 256-byte buffer.  */
140   char buf[256];
141   int resident, privateresident;
142   unsigned long obj;
143   int ret = EOF;
144
145   /* As of FreeBSD 5.0-RELEASE, the layout is described in
146      /usr/src/sys/fs/procfs/procfs_map.c.  Somewhere in 5.1-CURRENT a
147      new column was added to the procfs map.  Therefore we can't use
148      fscanf since we need to support older releases too.  */
149   if (fgets (buf, sizeof buf, mapfile) != NULL)
150     ret = sscanf (buf, "%lx %lx %d %d %lx %s", start, end,
151                   &resident, &privateresident, &obj, protection);
152
153   return (ret != 0 && ret != EOF);
154 }
155
156 /* Iterate over all the memory regions in the current inferior,
157    calling FUNC for each memory region.  OBFD is passed as the last
158    argument to FUNC.  */
159
160 static int
161 fbsd_find_memory_regions (struct target_ops *self,
162                           find_memory_region_ftype func, void *obfd)
163 {
164   pid_t pid = ptid_get_pid (inferior_ptid);
165   char *mapfilename;
166   unsigned long start, end, size;
167   char protection[4];
168   int read, write, exec;
169   struct cleanup *cleanup;
170
171   mapfilename = xstrprintf ("/proc/%ld/map", (long) pid);
172   cleanup = make_cleanup (xfree, mapfilename);
173   gdb_file_up mapfile (fopen (mapfilename, "r"));
174   if (mapfile == NULL)
175     error (_("Couldn't open %s."), mapfilename);
176
177   if (info_verbose)
178     fprintf_filtered (gdb_stdout, 
179                       "Reading memory regions from %s\n", mapfilename);
180
181   /* Now iterate until end-of-file.  */
182   while (fbsd_read_mapping (mapfile.get (), &start, &end, &protection[0]))
183     {
184       size = end - start;
185
186       read = (strchr (protection, 'r') != 0);
187       write = (strchr (protection, 'w') != 0);
188       exec = (strchr (protection, 'x') != 0);
189
190       if (info_verbose)
191         {
192           fprintf_filtered (gdb_stdout, 
193                             "Save segment, %ld bytes at %s (%c%c%c)\n",
194                             size, paddress (target_gdbarch (), start),
195                             read ? 'r' : '-',
196                             write ? 'w' : '-',
197                             exec ? 'x' : '-');
198         }
199
200       /* Invoke the callback function to create the corefile segment.
201          Pass MODIFIED as true, we do not know the real modification state.  */
202       func (start, size, read, write, exec, 1, obfd);
203     }
204
205   do_cleanups (cleanup);
206   return 0;
207 }
208 #endif
209
210 #ifdef KERN_PROC_AUXV
211 static enum target_xfer_status (*super_xfer_partial) (struct target_ops *ops,
212                                                       enum target_object object,
213                                                       const char *annex,
214                                                       gdb_byte *readbuf,
215                                                       const gdb_byte *writebuf,
216                                                       ULONGEST offset,
217                                                       ULONGEST len,
218                                                       ULONGEST *xfered_len);
219
220 #ifdef PT_LWPINFO
221 /* Return the size of siginfo for the current inferior.  */
222
223 #ifdef __LP64__
224 union sigval32 {
225   int sival_int;
226   uint32_t sival_ptr;
227 };
228
229 /* This structure matches the naming and layout of `siginfo_t' in
230    <sys/signal.h>.  In particular, the `si_foo' macros defined in that
231    header can be used with both types to copy fields in the `_reason'
232    union.  */
233
234 struct siginfo32
235 {
236   int si_signo;
237   int si_errno;
238   int si_code;
239   __pid_t si_pid;
240   __uid_t si_uid;
241   int si_status;
242   uint32_t si_addr;
243   union sigval32 si_value;
244   union
245   {
246     struct
247     {
248       int _trapno;
249     } _fault;
250     struct
251     {
252       int _timerid;
253       int _overrun;
254     } _timer;
255     struct
256     {
257       int _mqd;
258     } _mesgq;
259     struct
260     {
261       int32_t _band;
262     } _poll;
263     struct
264     {
265       int32_t __spare1__;
266       int __spare2__[7];
267     } __spare__;
268   } _reason;
269 };
270 #endif
271
272 static size_t
273 fbsd_siginfo_size ()
274 {
275 #ifdef __LP64__
276   struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
277
278   /* Is the inferior 32-bit?  If so, use the 32-bit siginfo size.  */
279   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
280     return sizeof (struct siginfo32);
281 #endif
282   return sizeof (siginfo_t);
283 }
284
285 /* Convert a native 64-bit siginfo object to a 32-bit object.  Note
286    that FreeBSD doesn't support writing to $_siginfo, so this only
287    needs to convert one way.  */
288
289 static void
290 fbsd_convert_siginfo (siginfo_t *si)
291 {
292 #ifdef __LP64__
293   struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
294
295   /* Is the inferior 32-bit?  If not, nothing to do.  */
296   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word != 32)
297     return;
298
299   struct siginfo32 si32;
300
301   si32.si_signo = si->si_signo;
302   si32.si_errno = si->si_errno;
303   si32.si_code = si->si_code;
304   si32.si_pid = si->si_pid;
305   si32.si_uid = si->si_uid;
306   si32.si_status = si->si_status;
307   si32.si_addr = (uintptr_t) si->si_addr;
308
309   /* If sival_ptr is being used instead of sival_int on a big-endian
310      platform, then sival_int will be zero since it holds the upper
311      32-bits of the pointer value.  */
312 #if _BYTE_ORDER == _BIG_ENDIAN
313   if (si->si_value.sival_int == 0)
314     si32->si_value.sival_ptr = (uintptr_t) si->si_value.sival_ptr;
315   else
316     si32.si_value.sival_int = si->si_value.sival_int;
317 #else
318   si32.si_value.sival_int = si->si_value.sival_int;
319 #endif
320
321   /* Always copy the spare fields and then possibly overwrite them for
322      signal-specific or code-specific fields.  */
323   si32._reason.__spare__.__spare1__ = si->_reason.__spare__.__spare1__;
324   for (int i = 0; i < 7; i++)
325     si32._reason.__spare__.__spare2__[i] = si->_reason.__spare__.__spare2__[i];
326   switch (si->si_signo) {
327   case SIGILL:
328   case SIGFPE:
329   case SIGSEGV:
330   case SIGBUS:
331     si32.si_trapno = si->si_trapno;
332     break;
333   }
334   switch (si->si_code) {
335   case SI_TIMER:
336     si32.si_timerid = si->si_timerid;
337     si32.si_overrun = si->si_overrun;
338     break;
339   case SI_MESGQ:
340     si32.si_mqd = si->si_mqd;
341     break;
342   }
343
344   memcpy(si, &si32, sizeof (si32));
345 #endif
346 }
347 #endif
348
349 /* Implement the "to_xfer_partial target_ops" method.  */
350
351 static enum target_xfer_status
352 fbsd_xfer_partial (struct target_ops *ops, enum target_object object,
353                    const char *annex, gdb_byte *readbuf,
354                    const gdb_byte *writebuf,
355                    ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
356 {
357   pid_t pid = ptid_get_pid (inferior_ptid);
358
359   switch (object)
360     {
361 #ifdef PT_LWPINFO
362     case TARGET_OBJECT_SIGNAL_INFO:
363       {
364         struct ptrace_lwpinfo pl;
365         size_t siginfo_size;
366
367         /* FreeBSD doesn't support writing to $_siginfo.  */
368         if (writebuf != NULL)
369           return TARGET_XFER_E_IO;
370
371         if (inferior_ptid.lwp_p ())
372           pid = inferior_ptid.lwp ();
373
374         siginfo_size = fbsd_siginfo_size ();
375         if (offset > siginfo_size)
376           return TARGET_XFER_E_IO;
377
378         if (ptrace (PT_LWPINFO, pid, (PTRACE_TYPE_ARG3) &pl, sizeof (pl)) == -1)
379           return TARGET_XFER_E_IO;
380
381         if (!(pl.pl_flags & PL_FLAG_SI))
382           return TARGET_XFER_E_IO;
383
384         fbsd_convert_siginfo (&pl.pl_siginfo);
385         if (offset + len > siginfo_size)
386           len = siginfo_size - offset;
387
388         memcpy (readbuf, ((gdb_byte *) &pl.pl_siginfo) + offset, len);
389         *xfered_len = len;
390         return TARGET_XFER_OK;
391       }
392 #endif
393     case TARGET_OBJECT_AUXV:
394       {
395         struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
396         unsigned char *buf;
397         size_t buflen;
398         int mib[4];
399
400         if (writebuf != NULL)
401           return TARGET_XFER_E_IO;
402         mib[0] = CTL_KERN;
403         mib[1] = KERN_PROC;
404         mib[2] = KERN_PROC_AUXV;
405         mib[3] = pid;
406         if (offset == 0)
407           {
408             buf = readbuf;
409             buflen = len;
410           }
411         else
412           {
413             buflen = offset + len;
414             buf = XCNEWVEC (unsigned char, buflen);
415             cleanup = make_cleanup (xfree, buf);
416           }
417         if (sysctl (mib, 4, buf, &buflen, NULL, 0) == 0)
418           {
419             if (offset != 0)
420               {
421                 if (buflen > offset)
422                   {
423                     buflen -= offset;
424                     memcpy (readbuf, buf + offset, buflen);
425                   }
426                 else
427                   buflen = 0;
428               }
429             do_cleanups (cleanup);
430             *xfered_len = buflen;
431             return (buflen == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
432           }
433         do_cleanups (cleanup);
434         return TARGET_XFER_E_IO;
435       }
436     default:
437       return super_xfer_partial (ops, object, annex, readbuf, writebuf, offset,
438                                  len, xfered_len);
439     }
440 }
441 #endif
442
443 #ifdef PT_LWPINFO
444 static int debug_fbsd_lwp;
445
446 static void (*super_resume) (struct target_ops *,
447                              ptid_t,
448                              int,
449                              enum gdb_signal);
450 static ptid_t (*super_wait) (struct target_ops *,
451                              ptid_t,
452                              struct target_waitstatus *,
453                              int);
454
455 static void
456 show_fbsd_lwp_debug (struct ui_file *file, int from_tty,
457                      struct cmd_list_element *c, const char *value)
458 {
459   fprintf_filtered (file, _("Debugging of FreeBSD lwp module is %s.\n"), value);
460 }
461
462 #if defined(TDP_RFPPWAIT) || defined(HAVE_STRUCT_PTRACE_LWPINFO_PL_TDNAME)
463 /* Fetch the external variant of the kernel's internal process
464    structure for the process PID into KP.  */
465
466 static void
467 fbsd_fetch_kinfo_proc (pid_t pid, struct kinfo_proc *kp)
468 {
469   size_t len;
470   int mib[4];
471
472   len = sizeof *kp;
473   mib[0] = CTL_KERN;
474   mib[1] = KERN_PROC;
475   mib[2] = KERN_PROC_PID;
476   mib[3] = pid;
477   if (sysctl (mib, 4, kp, &len, NULL, 0) == -1)
478     perror_with_name (("sysctl"));
479 }
480 #endif
481
482 /*
483   FreeBSD's first thread support was via a "reentrant" version of libc
484   (libc_r) that first shipped in 2.2.7.  This library multiplexed all
485   of the threads in a process onto a single kernel thread.  This
486   library was supported via the bsd-uthread target.
487
488   FreeBSD 5.1 introduced two new threading libraries that made use of
489   multiple kernel threads.  The first (libkse) scheduled M user
490   threads onto N (<= M) kernel threads (LWPs).  The second (libthr)
491   bound each user thread to a dedicated kernel thread.  libkse shipped
492   as the default threading library (libpthread).
493
494   FreeBSD 5.3 added a libthread_db to abstract the interface across
495   the various thread libraries (libc_r, libkse, and libthr).
496
497   FreeBSD 7.0 switched the default threading library from from libkse
498   to libpthread and removed libc_r.
499
500   FreeBSD 8.0 removed libkse and the in-kernel support for it.  The
501   only threading library supported by 8.0 and later is libthr which
502   ties each user thread directly to an LWP.  To simplify the
503   implementation, this target only supports LWP-backed threads using
504   ptrace directly rather than libthread_db.
505
506   FreeBSD 11.0 introduced LWP event reporting via PT_LWP_EVENTS.
507 */
508
509 /* Return true if PTID is still active in the inferior.  */
510
511 static int
512 fbsd_thread_alive (struct target_ops *ops, ptid_t ptid)
513 {
514   if (ptid_lwp_p (ptid))
515     {
516       struct ptrace_lwpinfo pl;
517
518       if (ptrace (PT_LWPINFO, ptid_get_lwp (ptid), (caddr_t) &pl, sizeof pl)
519           == -1)
520         return 0;
521 #ifdef PL_FLAG_EXITED
522       if (pl.pl_flags & PL_FLAG_EXITED)
523         return 0;
524 #endif
525     }
526
527   return 1;
528 }
529
530 /* Convert PTID to a string.  Returns the string in a static
531    buffer.  */
532
533 static const char *
534 fbsd_pid_to_str (struct target_ops *ops, ptid_t ptid)
535 {
536   lwpid_t lwp;
537
538   lwp = ptid_get_lwp (ptid);
539   if (lwp != 0)
540     {
541       static char buf[64];
542       int pid = ptid_get_pid (ptid);
543
544       xsnprintf (buf, sizeof buf, "LWP %d of process %d", lwp, pid);
545       return buf;
546     }
547
548   return normal_pid_to_str (ptid);
549 }
550
551 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_TDNAME
552 /* Return the name assigned to a thread by an application.  Returns
553    the string in a static buffer.  */
554
555 static const char *
556 fbsd_thread_name (struct target_ops *self, struct thread_info *thr)
557 {
558   struct ptrace_lwpinfo pl;
559   struct kinfo_proc kp;
560   int pid = ptid_get_pid (thr->ptid);
561   long lwp = ptid_get_lwp (thr->ptid);
562   static char buf[sizeof pl.pl_tdname + 1];
563
564   /* Note that ptrace_lwpinfo returns the process command in pl_tdname
565      if a name has not been set explicitly.  Return a NULL name in
566      that case.  */
567   fbsd_fetch_kinfo_proc (pid, &kp);
568   if (ptrace (PT_LWPINFO, lwp, (caddr_t) &pl, sizeof pl) == -1)
569     perror_with_name (("ptrace"));
570   if (strcmp (kp.ki_comm, pl.pl_tdname) == 0)
571     return NULL;
572   xsnprintf (buf, sizeof buf, "%s", pl.pl_tdname);
573   return buf;
574 }
575 #endif
576
577 /* Enable additional event reporting on new processes.
578
579    To catch fork events, PTRACE_FORK is set on every traced process
580    to enable stops on returns from fork or vfork.  Note that both the
581    parent and child will always stop, even if system call stops are
582    not enabled.
583
584    To catch LWP events, PTRACE_EVENTS is set on every traced process.
585    This enables stops on the birth for new LWPs (excluding the "main" LWP)
586    and the death of LWPs (excluding the last LWP in a process).  Note
587    that unlike fork events, the LWP that creates a new LWP does not
588    report an event.  */
589
590 static void
591 fbsd_enable_proc_events (pid_t pid)
592 {
593 #ifdef PT_GET_EVENT_MASK
594   int events;
595
596   if (ptrace (PT_GET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3)&events,
597               sizeof (events)) == -1)
598     perror_with_name (("ptrace"));
599   events |= PTRACE_FORK | PTRACE_LWP;
600 #ifdef PTRACE_VFORK
601   events |= PTRACE_VFORK;
602 #endif
603   if (ptrace (PT_SET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3)&events,
604               sizeof (events)) == -1)
605     perror_with_name (("ptrace"));
606 #else
607 #ifdef TDP_RFPPWAIT
608   if (ptrace (PT_FOLLOW_FORK, pid, (PTRACE_TYPE_ARG3)0, 1) == -1)
609     perror_with_name (("ptrace"));
610 #endif
611 #ifdef PT_LWP_EVENTS
612   if (ptrace (PT_LWP_EVENTS, pid, (PTRACE_TYPE_ARG3)0, 1) == -1)
613     perror_with_name (("ptrace"));
614 #endif
615 #endif
616 }
617
618 /* Add threads for any new LWPs in a process.
619
620    When LWP events are used, this function is only used to detect existing
621    threads when attaching to a process.  On older systems, this function is
622    called to discover new threads each time the thread list is updated.  */
623
624 static void
625 fbsd_add_threads (pid_t pid)
626 {
627   struct cleanup *cleanup;
628   lwpid_t *lwps;
629   int i, nlwps;
630
631   gdb_assert (!in_thread_list (pid_to_ptid (pid)));
632   nlwps = ptrace (PT_GETNUMLWPS, pid, NULL, 0);
633   if (nlwps == -1)
634     perror_with_name (("ptrace"));
635
636   lwps = XCNEWVEC (lwpid_t, nlwps);
637   cleanup = make_cleanup (xfree, lwps);
638
639   nlwps = ptrace (PT_GETLWPLIST, pid, (caddr_t) lwps, nlwps);
640   if (nlwps == -1)
641     perror_with_name (("ptrace"));
642
643   for (i = 0; i < nlwps; i++)
644     {
645       ptid_t ptid = ptid_build (pid, lwps[i], 0);
646
647       if (!in_thread_list (ptid))
648         {
649 #ifdef PT_LWP_EVENTS
650           struct ptrace_lwpinfo pl;
651
652           /* Don't add exited threads.  Note that this is only called
653              when attaching to a multi-threaded process.  */
654           if (ptrace (PT_LWPINFO, lwps[i], (caddr_t) &pl, sizeof pl) == -1)
655             perror_with_name (("ptrace"));
656           if (pl.pl_flags & PL_FLAG_EXITED)
657             continue;
658 #endif
659           if (debug_fbsd_lwp)
660             fprintf_unfiltered (gdb_stdlog,
661                                 "FLWP: adding thread for LWP %u\n",
662                                 lwps[i]);
663           add_thread (ptid);
664         }
665     }
666   do_cleanups (cleanup);
667 }
668
669 /* Implement the "to_update_thread_list" target_ops method.  */
670
671 static void
672 fbsd_update_thread_list (struct target_ops *ops)
673 {
674 #ifdef PT_LWP_EVENTS
675   /* With support for thread events, threads are added/deleted from the
676      list as events are reported, so just try deleting exited threads.  */
677   delete_exited_threads ();
678 #else
679   prune_threads ();
680
681   fbsd_add_threads (ptid_get_pid (inferior_ptid));
682 #endif
683 }
684
685 #ifdef TDP_RFPPWAIT
686 /*
687   To catch fork events, PT_FOLLOW_FORK is set on every traced process
688   to enable stops on returns from fork or vfork.  Note that both the
689   parent and child will always stop, even if system call stops are not
690   enabled.
691
692   After a fork, both the child and parent process will stop and report
693   an event.  However, there is no guarantee of order.  If the parent
694   reports its stop first, then fbsd_wait explicitly waits for the new
695   child before returning.  If the child reports its stop first, then
696   the event is saved on a list and ignored until the parent's stop is
697   reported.  fbsd_wait could have been changed to fetch the parent PID
698   of the new child and used that to wait for the parent explicitly.
699   However, if two threads in the parent fork at the same time, then
700   the wait on the parent might return the "wrong" fork event.
701
702   The initial version of PT_FOLLOW_FORK did not set PL_FLAG_CHILD for
703   the new child process.  This flag could be inferred by treating any
704   events for an unknown pid as a new child.
705
706   In addition, the initial version of PT_FOLLOW_FORK did not report a
707   stop event for the parent process of a vfork until after the child
708   process executed a new program or exited.  The kernel was changed to
709   defer the wait for exit or exec of the child until after posting the
710   stop event shortly after the change to introduce PL_FLAG_CHILD.
711   This could be worked around by reporting a vfork event when the
712   child event posted and ignoring the subsequent event from the
713   parent.
714
715   This implementation requires both of these fixes for simplicity's
716   sake.  FreeBSD versions newer than 9.1 contain both fixes.
717 */
718
719 struct fbsd_fork_info
720 {
721   struct fbsd_fork_info *next;
722   ptid_t ptid;
723 };
724
725 static struct fbsd_fork_info *fbsd_pending_children;
726
727 /* Record a new child process event that is reported before the
728    corresponding fork event in the parent.  */
729
730 static void
731 fbsd_remember_child (ptid_t pid)
732 {
733   struct fbsd_fork_info *info = XCNEW (struct fbsd_fork_info);
734
735   info->ptid = pid;
736   info->next = fbsd_pending_children;
737   fbsd_pending_children = info;
738 }
739
740 /* Check for a previously-recorded new child process event for PID.
741    If one is found, remove it from the list and return the PTID.  */
742
743 static ptid_t
744 fbsd_is_child_pending (pid_t pid)
745 {
746   struct fbsd_fork_info *info, *prev;
747   ptid_t ptid;
748
749   prev = NULL;
750   for (info = fbsd_pending_children; info; prev = info, info = info->next)
751     {
752       if (ptid_get_pid (info->ptid) == pid)
753         {
754           if (prev == NULL)
755             fbsd_pending_children = info->next;
756           else
757             prev->next = info->next;
758           ptid = info->ptid;
759           xfree (info);
760           return ptid;
761         }
762     }
763   return null_ptid;
764 }
765
766 #ifndef PTRACE_VFORK
767 static struct fbsd_fork_info *fbsd_pending_vfork_done;
768
769 /* Record a pending vfork done event.  */
770
771 static void
772 fbsd_add_vfork_done (ptid_t pid)
773 {
774   struct fbsd_fork_info *info = XCNEW (struct fbsd_fork_info);
775
776   info->ptid = pid;
777   info->next = fbsd_pending_vfork_done;
778   fbsd_pending_vfork_done = info;
779 }
780
781 /* Check for a pending vfork done event for a specific PID.  */
782
783 static int
784 fbsd_is_vfork_done_pending (pid_t pid)
785 {
786   struct fbsd_fork_info *info;
787
788   for (info = fbsd_pending_vfork_done; info != NULL; info = info->next)
789     {
790       if (ptid_get_pid (info->ptid) == pid)
791         return 1;
792     }
793   return 0;
794 }
795
796 /* Check for a pending vfork done event.  If one is found, remove it
797    from the list and return the PTID.  */
798
799 static ptid_t
800 fbsd_next_vfork_done (void)
801 {
802   struct fbsd_fork_info *info;
803   ptid_t ptid;
804
805   if (fbsd_pending_vfork_done != NULL)
806     {
807       info = fbsd_pending_vfork_done;
808       fbsd_pending_vfork_done = info->next;
809       ptid = info->ptid;
810       xfree (info);
811       return ptid;
812     }
813   return null_ptid;
814 }
815 #endif
816 #endif
817
818 /* Implement the "to_resume" target_ops method.  */
819
820 static void
821 fbsd_resume (struct target_ops *ops,
822              ptid_t ptid, int step, enum gdb_signal signo)
823 {
824 #if defined(TDP_RFPPWAIT) && !defined(PTRACE_VFORK)
825   pid_t pid;
826
827   /* Don't PT_CONTINUE a process which has a pending vfork done event.  */
828   if (ptid_equal (minus_one_ptid, ptid))
829     pid = ptid_get_pid (inferior_ptid);
830   else
831     pid = ptid_get_pid (ptid);
832   if (fbsd_is_vfork_done_pending (pid))
833     return;
834 #endif
835
836   if (debug_fbsd_lwp)
837     fprintf_unfiltered (gdb_stdlog,
838                         "FLWP: fbsd_resume for ptid (%d, %ld, %ld)\n",
839                         ptid_get_pid (ptid), ptid_get_lwp (ptid),
840                         ptid_get_tid (ptid));
841   if (ptid_lwp_p (ptid))
842     {
843       /* If ptid is a specific LWP, suspend all other LWPs in the process.  */
844       struct thread_info *tp;
845       int request;
846
847       ALL_NON_EXITED_THREADS (tp)
848         {
849           if (ptid_get_pid (tp->ptid) != ptid_get_pid (ptid))
850             continue;
851
852           if (ptid_get_lwp (tp->ptid) == ptid_get_lwp (ptid))
853             request = PT_RESUME;
854           else
855             request = PT_SUSPEND;
856
857           if (ptrace (request, ptid_get_lwp (tp->ptid), NULL, 0) == -1)
858             perror_with_name (("ptrace"));
859         }
860     }
861   else
862     {
863       /* If ptid is a wildcard, resume all matching threads (they won't run
864          until the process is continued however).  */
865       struct thread_info *tp;
866
867       ALL_NON_EXITED_THREADS (tp)
868         {
869           if (!ptid_match (tp->ptid, ptid))
870             continue;
871
872           if (ptrace (PT_RESUME, ptid_get_lwp (tp->ptid), NULL, 0) == -1)
873             perror_with_name (("ptrace"));
874         }
875       ptid = inferior_ptid;
876     }
877   super_resume (ops, ptid, step, signo);
878 }
879
880 /* Wait for the child specified by PTID to do something.  Return the
881    process ID of the child, or MINUS_ONE_PTID in case of error; store
882    the status in *OURSTATUS.  */
883
884 static ptid_t
885 fbsd_wait (struct target_ops *ops,
886            ptid_t ptid, struct target_waitstatus *ourstatus,
887            int target_options)
888 {
889   ptid_t wptid;
890
891   while (1)
892     {
893 #ifndef PTRACE_VFORK
894       wptid = fbsd_next_vfork_done ();
895       if (!ptid_equal (wptid, null_ptid))
896         {
897           ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
898           return wptid;
899         }
900 #endif
901       wptid = super_wait (ops, ptid, ourstatus, target_options);
902       if (ourstatus->kind == TARGET_WAITKIND_STOPPED)
903         {
904           struct ptrace_lwpinfo pl;
905           pid_t pid;
906           int status;
907
908           pid = ptid_get_pid (wptid);
909           if (ptrace (PT_LWPINFO, pid, (caddr_t) &pl, sizeof pl) == -1)
910             perror_with_name (("ptrace"));
911
912           wptid = ptid_build (pid, pl.pl_lwpid, 0);
913
914 #ifdef PT_LWP_EVENTS
915           if (pl.pl_flags & PL_FLAG_EXITED)
916             {
917               /* If GDB attaches to a multi-threaded process, exiting
918                  threads might be skipped during fbsd_post_attach that
919                  have not yet reported their PL_FLAG_EXITED event.
920                  Ignore EXITED events for an unknown LWP.  */
921               if (in_thread_list (wptid))
922                 {
923                   if (debug_fbsd_lwp)
924                     fprintf_unfiltered (gdb_stdlog,
925                                         "FLWP: deleting thread for LWP %u\n",
926                                         pl.pl_lwpid);
927                   if (print_thread_events)
928                     printf_unfiltered (_("[%s exited]\n"), target_pid_to_str
929                                        (wptid));
930                   delete_thread (wptid);
931                 }
932               if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
933                 perror_with_name (("ptrace"));
934               continue;
935             }
936 #endif
937
938           /* Switch to an LWP PTID on the first stop in a new process.
939              This is done after handling PL_FLAG_EXITED to avoid
940              switching to an exited LWP.  It is done before checking
941              PL_FLAG_BORN in case the first stop reported after
942              attaching to an existing process is a PL_FLAG_BORN
943              event.  */
944           if (in_thread_list (pid_to_ptid (pid)))
945             {
946               if (debug_fbsd_lwp)
947                 fprintf_unfiltered (gdb_stdlog,
948                                     "FLWP: using LWP %u for first thread\n",
949                                     pl.pl_lwpid);
950               thread_change_ptid (pid_to_ptid (pid), wptid);
951             }
952
953 #ifdef PT_LWP_EVENTS
954           if (pl.pl_flags & PL_FLAG_BORN)
955             {
956               /* If GDB attaches to a multi-threaded process, newborn
957                  threads might be added by fbsd_add_threads that have
958                  not yet reported their PL_FLAG_BORN event.  Ignore
959                  BORN events for an already-known LWP.  */
960               if (!in_thread_list (wptid))
961                 {
962                   if (debug_fbsd_lwp)
963                     fprintf_unfiltered (gdb_stdlog,
964                                         "FLWP: adding thread for LWP %u\n",
965                                         pl.pl_lwpid);
966                   add_thread (wptid);
967                 }
968               ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
969               return wptid;
970             }
971 #endif
972
973 #ifdef TDP_RFPPWAIT
974           if (pl.pl_flags & PL_FLAG_FORKED)
975             {
976 #ifndef PTRACE_VFORK
977               struct kinfo_proc kp;
978 #endif
979               ptid_t child_ptid;
980               pid_t child;
981
982               child = pl.pl_child_pid;
983               ourstatus->kind = TARGET_WAITKIND_FORKED;
984 #ifdef PTRACE_VFORK
985               if (pl.pl_flags & PL_FLAG_VFORKED)
986                 ourstatus->kind = TARGET_WAITKIND_VFORKED;
987 #endif
988
989               /* Make sure the other end of the fork is stopped too.  */
990               child_ptid = fbsd_is_child_pending (child);
991               if (ptid_equal (child_ptid, null_ptid))
992                 {
993                   pid = waitpid (child, &status, 0);
994                   if (pid == -1)
995                     perror_with_name (("waitpid"));
996
997                   gdb_assert (pid == child);
998
999                   if (ptrace (PT_LWPINFO, child, (caddr_t)&pl, sizeof pl) == -1)
1000                     perror_with_name (("ptrace"));
1001
1002                   gdb_assert (pl.pl_flags & PL_FLAG_CHILD);
1003                   child_ptid = ptid_build (child, pl.pl_lwpid, 0);
1004                 }
1005
1006               /* Enable additional events on the child process.  */
1007               fbsd_enable_proc_events (ptid_get_pid (child_ptid));
1008
1009 #ifndef PTRACE_VFORK
1010               /* For vfork, the child process will have the P_PPWAIT
1011                  flag set.  */
1012               fbsd_fetch_kinfo_proc (child, &kp);
1013               if (kp.ki_flag & P_PPWAIT)
1014                 ourstatus->kind = TARGET_WAITKIND_VFORKED;
1015 #endif
1016               ourstatus->value.related_pid = child_ptid;
1017
1018               return wptid;
1019             }
1020
1021           if (pl.pl_flags & PL_FLAG_CHILD)
1022             {
1023               /* Remember that this child forked, but do not report it
1024                  until the parent reports its corresponding fork
1025                  event.  */
1026               fbsd_remember_child (wptid);
1027               continue;
1028             }
1029
1030 #ifdef PTRACE_VFORK
1031           if (pl.pl_flags & PL_FLAG_VFORK_DONE)
1032             {
1033               ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
1034               return wptid;
1035             }
1036 #endif
1037 #endif
1038
1039 #ifdef PL_FLAG_EXEC
1040           if (pl.pl_flags & PL_FLAG_EXEC)
1041             {
1042               ourstatus->kind = TARGET_WAITKIND_EXECD;
1043               ourstatus->value.execd_pathname
1044                 = xstrdup (fbsd_pid_to_exec_file (NULL, pid));
1045               return wptid;
1046             }
1047 #endif
1048
1049           /* Note that PL_FLAG_SCE is set for any event reported while
1050              a thread is executing a system call in the kernel.  In
1051              particular, signals that interrupt a sleep in a system
1052              call will report this flag as part of their event.  Stops
1053              explicitly for system call entry and exit always use
1054              SIGTRAP, so only treat SIGTRAP events as system call
1055              entry/exit events.  */
1056           if (pl.pl_flags & (PL_FLAG_SCE | PL_FLAG_SCX)
1057               && ourstatus->value.sig == SIGTRAP)
1058             {
1059 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1060               if (catch_syscall_enabled ())
1061                 {
1062                   if (catching_syscall_number (pl.pl_syscall_code))
1063                     {
1064                       if (pl.pl_flags & PL_FLAG_SCE)
1065                         ourstatus->kind = TARGET_WAITKIND_SYSCALL_ENTRY;
1066                       else
1067                         ourstatus->kind = TARGET_WAITKIND_SYSCALL_RETURN;
1068                       ourstatus->value.syscall_number = pl.pl_syscall_code;
1069                       return wptid;
1070                     }
1071                 }
1072 #endif
1073               /* If the core isn't interested in this event, just
1074                  continue the process explicitly and wait for another
1075                  event.  Note that PT_SYSCALL is "sticky" on FreeBSD
1076                  and once system call stops are enabled on a process
1077                  it stops for all system call entries and exits.  */
1078               if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1079                 perror_with_name (("ptrace"));
1080               continue;
1081             }
1082         }
1083       return wptid;
1084     }
1085 }
1086
1087 #ifdef TDP_RFPPWAIT
1088 /* Target hook for follow_fork.  On entry and at return inferior_ptid is
1089    the ptid of the followed inferior.  */
1090
1091 static int
1092 fbsd_follow_fork (struct target_ops *ops, int follow_child,
1093                         int detach_fork)
1094 {
1095   if (!follow_child && detach_fork)
1096     {
1097       struct thread_info *tp = inferior_thread ();
1098       pid_t child_pid = ptid_get_pid (tp->pending_follow.value.related_pid);
1099
1100       /* Breakpoints have already been detached from the child by
1101          infrun.c.  */
1102
1103       if (ptrace (PT_DETACH, child_pid, (PTRACE_TYPE_ARG3)1, 0) == -1)
1104         perror_with_name (("ptrace"));
1105
1106 #ifndef PTRACE_VFORK
1107       if (tp->pending_follow.kind == TARGET_WAITKIND_VFORKED)
1108         {
1109           /* We can't insert breakpoints until the child process has
1110              finished with the shared memory region.  The parent
1111              process doesn't wait for the child process to exit or
1112              exec until after it has been resumed from the ptrace stop
1113              to report the fork.  Once it has been resumed it doesn't
1114              stop again before returning to userland, so there is no
1115              reliable way to wait on the parent.
1116
1117              We can't stay attached to the child to wait for an exec
1118              or exit because it may invoke ptrace(PT_TRACE_ME)
1119              (e.g. if the parent process is a debugger forking a new
1120              child process).
1121
1122              In the end, the best we can do is to make sure it runs
1123              for a little while.  Hopefully it will be out of range of
1124              any breakpoints we reinsert.  Usually this is only the
1125              single-step breakpoint at vfork's return point.  */
1126
1127           usleep (10000);
1128
1129           /* Schedule a fake VFORK_DONE event to report on the next
1130              wait.  */
1131           fbsd_add_vfork_done (inferior_ptid);
1132         }
1133 #endif
1134     }
1135
1136   return 0;
1137 }
1138
1139 static int
1140 fbsd_insert_fork_catchpoint (struct target_ops *self, int pid)
1141 {
1142   return 0;
1143 }
1144
1145 static int
1146 fbsd_remove_fork_catchpoint (struct target_ops *self, int pid)
1147 {
1148   return 0;
1149 }
1150
1151 static int
1152 fbsd_insert_vfork_catchpoint (struct target_ops *self, int pid)
1153 {
1154   return 0;
1155 }
1156
1157 static int
1158 fbsd_remove_vfork_catchpoint (struct target_ops *self, int pid)
1159 {
1160   return 0;
1161 }
1162 #endif
1163
1164 /* Implement the "to_post_startup_inferior" target_ops method.  */
1165
1166 static void
1167 fbsd_post_startup_inferior (struct target_ops *self, ptid_t pid)
1168 {
1169   fbsd_enable_proc_events (ptid_get_pid (pid));
1170 }
1171
1172 /* Implement the "to_post_attach" target_ops method.  */
1173
1174 static void
1175 fbsd_post_attach (struct target_ops *self, int pid)
1176 {
1177   fbsd_enable_proc_events (pid);
1178   fbsd_add_threads (pid);
1179 }
1180
1181 #ifdef PL_FLAG_EXEC
1182 /* If the FreeBSD kernel supports PL_FLAG_EXEC, then traced processes
1183    will always stop after exec.  */
1184
1185 static int
1186 fbsd_insert_exec_catchpoint (struct target_ops *self, int pid)
1187 {
1188   return 0;
1189 }
1190
1191 static int
1192 fbsd_remove_exec_catchpoint (struct target_ops *self, int pid)
1193 {
1194   return 0;
1195 }
1196 #endif
1197
1198 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1199 static int
1200 fbsd_set_syscall_catchpoint (struct target_ops *self, int pid, int needed,
1201                              int any_count, int table_size, int *table)
1202 {
1203
1204   /* Ignore the arguments.  inf-ptrace.c will use PT_SYSCALL which
1205      will catch all system call entries and exits.  The system calls
1206      are filtered by GDB rather than the kernel.  */
1207   return 0;
1208 }
1209 #endif
1210 #endif
1211
1212 void
1213 fbsd_nat_add_target (struct target_ops *t)
1214 {
1215   t->to_pid_to_exec_file = fbsd_pid_to_exec_file;
1216   t->to_find_memory_regions = fbsd_find_memory_regions;
1217 #ifdef KERN_PROC_AUXV
1218   super_xfer_partial = t->to_xfer_partial;
1219   t->to_xfer_partial = fbsd_xfer_partial;
1220 #endif
1221 #ifdef PT_LWPINFO
1222   t->to_thread_alive = fbsd_thread_alive;
1223   t->to_pid_to_str = fbsd_pid_to_str;
1224 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_TDNAME
1225   t->to_thread_name = fbsd_thread_name;
1226 #endif
1227   t->to_update_thread_list = fbsd_update_thread_list;
1228   t->to_has_thread_control = tc_schedlock;
1229   super_resume = t->to_resume;
1230   t->to_resume = fbsd_resume;
1231   super_wait = t->to_wait;
1232   t->to_wait = fbsd_wait;
1233   t->to_post_startup_inferior = fbsd_post_startup_inferior;
1234   t->to_post_attach = fbsd_post_attach;
1235 #ifdef TDP_RFPPWAIT
1236   t->to_follow_fork = fbsd_follow_fork;
1237   t->to_insert_fork_catchpoint = fbsd_insert_fork_catchpoint;
1238   t->to_remove_fork_catchpoint = fbsd_remove_fork_catchpoint;
1239   t->to_insert_vfork_catchpoint = fbsd_insert_vfork_catchpoint;
1240   t->to_remove_vfork_catchpoint = fbsd_remove_vfork_catchpoint;
1241 #endif
1242 #ifdef PL_FLAG_EXEC
1243   t->to_insert_exec_catchpoint = fbsd_insert_exec_catchpoint;
1244   t->to_remove_exec_catchpoint = fbsd_remove_exec_catchpoint;
1245 #endif
1246 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1247   t->to_set_syscall_catchpoint = fbsd_set_syscall_catchpoint;
1248 #endif
1249 #endif
1250   add_target (t);
1251 }
1252
1253 /* Provide a prototype to silence -Wmissing-prototypes.  */
1254 extern initialize_file_ftype _initialize_fbsd_nat;
1255
1256 void
1257 _initialize_fbsd_nat (void)
1258 {
1259 #ifdef PT_LWPINFO
1260   add_setshow_boolean_cmd ("fbsd-lwp", class_maintenance,
1261                            &debug_fbsd_lwp, _("\
1262 Set debugging of FreeBSD lwp module."), _("\
1263 Show debugging of FreeBSD lwp module."), _("\
1264 Enables printf debugging output."),
1265                            NULL,
1266                            &show_fbsd_lwp_debug,
1267                            &setdebuglist, &showdebuglist);
1268 #endif
1269 }