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