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