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