Add missing changelog entry
[external/binutils.git] / gdb / fbsd-nat.c
1 /* Native-dependent code for FreeBSD.
2
3    Copyright (C) 2002-2019 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 "gdbsupport/byte-vector.h"
22 #include "gdbcore.h"
23 #include "inferior.h"
24 #include "regcache.h"
25 #include "regset.h"
26 #include "gdbarch.h"
27 #include "gdbcmd.h"
28 #include "gdbthread.h"
29 #include "gdbsupport/gdb_wait.h"
30 #include "inf-ptrace.h"
31 #include <sys/types.h>
32 #include <sys/procfs.h>
33 #include <sys/ptrace.h>
34 #include <sys/signal.h>
35 #include <sys/sysctl.h>
36 #include <sys/user.h>
37 #if defined(HAVE_KINFO_GETFILE) || defined(HAVE_KINFO_GETVMMAP)
38 #include <libutil.h>
39 #endif
40 #if !defined(HAVE_KINFO_GETVMMAP)
41 #include "gdbsupport/filestuff.h"
42 #endif
43
44 #include "elf-bfd.h"
45 #include "fbsd-nat.h"
46 #include "fbsd-tdep.h"
47
48 #include <list>
49
50 /* Return the name of a file that can be opened to get the symbols for
51    the child process identified by PID.  */
52
53 char *
54 fbsd_nat_target::pid_to_exec_file (int pid)
55 {
56   ssize_t len;
57   static char buf[PATH_MAX];
58   char name[PATH_MAX];
59
60 #ifdef KERN_PROC_PATHNAME
61   size_t buflen;
62   int mib[4];
63
64   mib[0] = CTL_KERN;
65   mib[1] = KERN_PROC;
66   mib[2] = KERN_PROC_PATHNAME;
67   mib[3] = pid;
68   buflen = sizeof buf;
69   if (sysctl (mib, 4, buf, &buflen, NULL, 0) == 0)
70     /* The kern.proc.pathname.<pid> sysctl returns a length of zero
71        for processes without an associated executable such as kernel
72        processes.  */
73     return buflen == 0 ? NULL : buf;
74 #endif
75
76   xsnprintf (name, PATH_MAX, "/proc/%d/exe", pid);
77   len = readlink (name, buf, PATH_MAX - 1);
78   if (len != -1)
79     {
80       buf[len] = '\0';
81       return buf;
82     }
83
84   return NULL;
85 }
86
87 #ifdef HAVE_KINFO_GETVMMAP
88 /* Iterate over all the memory regions in the current inferior,
89    calling FUNC for each memory region.  OBFD is passed as the last
90    argument to FUNC.  */
91
92 int
93 fbsd_nat_target::find_memory_regions (find_memory_region_ftype func,
94                                       void *obfd)
95 {
96   pid_t pid = inferior_ptid.pid ();
97   struct kinfo_vmentry *kve;
98   uint64_t size;
99   int i, nitems;
100
101   gdb::unique_xmalloc_ptr<struct kinfo_vmentry>
102     vmentl (kinfo_getvmmap (pid, &nitems));
103   if (vmentl == NULL)
104     perror_with_name (_("Couldn't fetch VM map entries."));
105
106   for (i = 0, kve = vmentl.get (); i < nitems; i++, kve++)
107     {
108       /* Skip unreadable segments and those where MAP_NOCORE has been set.  */
109       if (!(kve->kve_protection & KVME_PROT_READ)
110           || kve->kve_flags & KVME_FLAG_NOCOREDUMP)
111         continue;
112
113       /* Skip segments with an invalid type.  */
114       if (kve->kve_type != KVME_TYPE_DEFAULT
115           && kve->kve_type != KVME_TYPE_VNODE
116           && kve->kve_type != KVME_TYPE_SWAP
117           && kve->kve_type != KVME_TYPE_PHYS)
118         continue;
119
120       size = kve->kve_end - kve->kve_start;
121       if (info_verbose)
122         {
123           fprintf_filtered (gdb_stdout, 
124                             "Save segment, %ld bytes at %s (%c%c%c)\n",
125                             (long) size,
126                             paddress (target_gdbarch (), kve->kve_start),
127                             kve->kve_protection & KVME_PROT_READ ? 'r' : '-',
128                             kve->kve_protection & KVME_PROT_WRITE ? 'w' : '-',
129                             kve->kve_protection & KVME_PROT_EXEC ? 'x' : '-');
130         }
131
132       /* Invoke the callback function to create the corefile segment.
133          Pass MODIFIED as true, we do not know the real modification state.  */
134       func (kve->kve_start, size, kve->kve_protection & KVME_PROT_READ,
135             kve->kve_protection & KVME_PROT_WRITE,
136             kve->kve_protection & KVME_PROT_EXEC, 1, obfd);
137     }
138   return 0;
139 }
140 #else
141 static int
142 fbsd_read_mapping (FILE *mapfile, unsigned long *start, unsigned long *end,
143                    char *protection)
144 {
145   /* FreeBSD 5.1-RELEASE uses a 256-byte buffer.  */
146   char buf[256];
147   int resident, privateresident;
148   unsigned long obj;
149   int ret = EOF;
150
151   /* As of FreeBSD 5.0-RELEASE, the layout is described in
152      /usr/src/sys/fs/procfs/procfs_map.c.  Somewhere in 5.1-CURRENT a
153      new column was added to the procfs map.  Therefore we can't use
154      fscanf since we need to support older releases too.  */
155   if (fgets (buf, sizeof buf, mapfile) != NULL)
156     ret = sscanf (buf, "%lx %lx %d %d %lx %s", start, end,
157                   &resident, &privateresident, &obj, protection);
158
159   return (ret != 0 && ret != EOF);
160 }
161
162 /* Iterate over all the memory regions in the current inferior,
163    calling FUNC for each memory region.  OBFD is passed as the last
164    argument to FUNC.  */
165
166 int
167 fbsd_nat_target::find_memory_regions (find_memory_region_ftype func,
168                                       void *obfd)
169 {
170   pid_t pid = inferior_ptid.pid ();
171   unsigned long start, end, size;
172   char protection[4];
173   int read, write, exec;
174
175   std::string mapfilename = string_printf ("/proc/%ld/map", (long) pid);
176   gdb_file_up mapfile (fopen (mapfilename.c_str (), "r"));
177   if (mapfile == NULL)
178     error (_("Couldn't open %s."), mapfilename.c_str ());
179
180   if (info_verbose)
181     fprintf_filtered (gdb_stdout, 
182                       "Reading memory regions from %s\n", mapfilename.c_str ());
183
184   /* Now iterate until end-of-file.  */
185   while (fbsd_read_mapping (mapfile.get (), &start, &end, &protection[0]))
186     {
187       size = end - start;
188
189       read = (strchr (protection, 'r') != 0);
190       write = (strchr (protection, 'w') != 0);
191       exec = (strchr (protection, 'x') != 0);
192
193       if (info_verbose)
194         {
195           fprintf_filtered (gdb_stdout, 
196                             "Save segment, %ld bytes at %s (%c%c%c)\n",
197                             size, paddress (target_gdbarch (), start),
198                             read ? 'r' : '-',
199                             write ? 'w' : '-',
200                             exec ? 'x' : '-');
201         }
202
203       /* Invoke the callback function to create the corefile segment.
204          Pass MODIFIED as true, we do not know the real modification state.  */
205       func (start, size, read, write, exec, 1, obfd);
206     }
207
208   return 0;
209 }
210 #endif
211
212 /* Fetch the command line for a running process.  */
213
214 static gdb::unique_xmalloc_ptr<char>
215 fbsd_fetch_cmdline (pid_t pid)
216 {
217   size_t len;
218   int mib[4];
219
220   len = 0;
221   mib[0] = CTL_KERN;
222   mib[1] = KERN_PROC;
223   mib[2] = KERN_PROC_ARGS;
224   mib[3] = pid;
225   if (sysctl (mib, 4, NULL, &len, NULL, 0) == -1)
226     return nullptr;
227
228   if (len == 0)
229     return nullptr;
230
231   gdb::unique_xmalloc_ptr<char> cmdline ((char *) xmalloc (len));
232   if (sysctl (mib, 4, cmdline.get (), &len, NULL, 0) == -1)
233     return nullptr;
234
235   /* Join the arguments with spaces to form a single string.  */
236   char *cp = cmdline.get ();
237   for (size_t i = 0; i < len - 1; i++)
238     if (cp[i] == '\0')
239       cp[i] = ' ';
240   cp[len - 1] = '\0';
241
242   return cmdline;
243 }
244
245 /* Fetch the external variant of the kernel's internal process
246    structure for the process PID into KP.  */
247
248 static bool
249 fbsd_fetch_kinfo_proc (pid_t pid, struct kinfo_proc *kp)
250 {
251   size_t len;
252   int mib[4];
253
254   len = sizeof *kp;
255   mib[0] = CTL_KERN;
256   mib[1] = KERN_PROC;
257   mib[2] = KERN_PROC_PID;
258   mib[3] = pid;
259   return (sysctl (mib, 4, kp, &len, NULL, 0) == 0);
260 }
261
262 /* Implement the "info_proc" target_ops method.  */
263
264 bool
265 fbsd_nat_target::info_proc (const char *args, enum info_proc_what what)
266 {
267 #ifdef HAVE_KINFO_GETFILE
268   gdb::unique_xmalloc_ptr<struct kinfo_file> fdtbl;
269   int nfd = 0;
270 #endif
271   struct kinfo_proc kp;
272   pid_t pid;
273   bool do_cmdline = false;
274   bool do_cwd = false;
275   bool do_exe = false;
276 #ifdef HAVE_KINFO_GETFILE
277   bool do_files = false;
278 #endif
279 #ifdef HAVE_KINFO_GETVMMAP
280   bool do_mappings = false;
281 #endif
282   bool do_status = false;
283
284   switch (what)
285     {
286     case IP_MINIMAL:
287       do_cmdline = true;
288       do_cwd = true;
289       do_exe = true;
290       break;
291 #ifdef HAVE_KINFO_GETVMMAP
292     case IP_MAPPINGS:
293       do_mappings = true;
294       break;
295 #endif
296     case IP_STATUS:
297     case IP_STAT:
298       do_status = true;
299       break;
300     case IP_CMDLINE:
301       do_cmdline = true;
302       break;
303     case IP_EXE:
304       do_exe = true;
305       break;
306     case IP_CWD:
307       do_cwd = true;
308       break;
309 #ifdef HAVE_KINFO_GETFILE
310     case IP_FILES:
311       do_files = true;
312       break;
313 #endif
314     case IP_ALL:
315       do_cmdline = true;
316       do_cwd = true;
317       do_exe = true;
318 #ifdef HAVE_KINFO_GETFILE
319       do_files = true;
320 #endif
321 #ifdef HAVE_KINFO_GETVMMAP
322       do_mappings = true;
323 #endif
324       do_status = true;
325       break;
326     default:
327       error (_("Not supported on this target."));
328     }
329
330   gdb_argv built_argv (args);
331   if (built_argv.count () == 0)
332     {
333       pid = inferior_ptid.pid ();
334       if (pid == 0)
335         error (_("No current process: you must name one."));
336     }
337   else if (built_argv.count () == 1 && isdigit (built_argv[0][0]))
338     pid = strtol (built_argv[0], NULL, 10);
339   else
340     error (_("Invalid arguments."));
341
342   printf_filtered (_("process %d\n"), pid);
343 #ifdef HAVE_KINFO_GETFILE
344   if (do_cwd || do_exe || do_files)
345     fdtbl.reset (kinfo_getfile (pid, &nfd));
346 #endif
347
348   if (do_cmdline)
349     {
350       gdb::unique_xmalloc_ptr<char> cmdline = fbsd_fetch_cmdline (pid);
351       if (cmdline != nullptr)
352         printf_filtered ("cmdline = '%s'\n", cmdline.get ());
353       else
354         warning (_("unable to fetch command line"));
355     }
356   if (do_cwd)
357     {
358       const char *cwd = NULL;
359 #ifdef HAVE_KINFO_GETFILE
360       struct kinfo_file *kf = fdtbl.get ();
361       for (int i = 0; i < nfd; i++, kf++)
362         {
363           if (kf->kf_type == KF_TYPE_VNODE && kf->kf_fd == KF_FD_TYPE_CWD)
364             {
365               cwd = kf->kf_path;
366               break;
367             }
368         }
369 #endif
370       if (cwd != NULL)
371         printf_filtered ("cwd = '%s'\n", cwd);
372       else
373         warning (_("unable to fetch current working directory"));
374     }
375   if (do_exe)
376     {
377       const char *exe = NULL;
378 #ifdef HAVE_KINFO_GETFILE
379       struct kinfo_file *kf = fdtbl.get ();
380       for (int i = 0; i < nfd; i++, kf++)
381         {
382           if (kf->kf_type == KF_TYPE_VNODE && kf->kf_fd == KF_FD_TYPE_TEXT)
383             {
384               exe = kf->kf_path;
385               break;
386             }
387         }
388 #endif
389       if (exe == NULL)
390         exe = pid_to_exec_file (pid);
391       if (exe != NULL)
392         printf_filtered ("exe = '%s'\n", exe);
393       else
394         warning (_("unable to fetch executable path name"));
395     }
396 #ifdef HAVE_KINFO_GETFILE
397   if (do_files)
398     {
399       struct kinfo_file *kf = fdtbl.get ();
400
401       if (nfd > 0)
402         {
403           fbsd_info_proc_files_header ();
404           for (int i = 0; i < nfd; i++, kf++)
405             fbsd_info_proc_files_entry (kf->kf_type, kf->kf_fd, kf->kf_flags,
406                                         kf->kf_offset, kf->kf_vnode_type,
407                                         kf->kf_sock_domain, kf->kf_sock_type,
408                                         kf->kf_sock_protocol, &kf->kf_sa_local,
409                                         &kf->kf_sa_peer, kf->kf_path);
410         }
411       else
412         warning (_("unable to fetch list of open files"));
413     }
414 #endif
415 #ifdef HAVE_KINFO_GETVMMAP
416   if (do_mappings)
417     {
418       int nvment;
419       gdb::unique_xmalloc_ptr<struct kinfo_vmentry>
420         vmentl (kinfo_getvmmap (pid, &nvment));
421
422       if (vmentl != nullptr)
423         {
424           int addr_bit = TARGET_CHAR_BIT * sizeof (void *);
425           fbsd_info_proc_mappings_header (addr_bit);
426
427           struct kinfo_vmentry *kve = vmentl.get ();
428           for (int i = 0; i < nvment; i++, kve++)
429             fbsd_info_proc_mappings_entry (addr_bit, kve->kve_start,
430                                            kve->kve_end, kve->kve_offset,
431                                            kve->kve_flags, kve->kve_protection,
432                                            kve->kve_path);
433         }
434       else
435         warning (_("unable to fetch virtual memory map"));
436     }
437 #endif
438   if (do_status)
439     {
440       if (!fbsd_fetch_kinfo_proc (pid, &kp))
441         warning (_("Failed to fetch process information"));
442       else
443         {
444           const char *state;
445           int pgtok;
446
447           printf_filtered ("Name: %s\n", kp.ki_comm);
448           switch (kp.ki_stat)
449             {
450             case SIDL:
451               state = "I (idle)";
452               break;
453             case SRUN:
454               state = "R (running)";
455               break;
456             case SSTOP:
457               state = "T (stopped)";
458               break;
459             case SZOMB:
460               state = "Z (zombie)";
461               break;
462             case SSLEEP:
463               state = "S (sleeping)";
464               break;
465             case SWAIT:
466               state = "W (interrupt wait)";
467               break;
468             case SLOCK:
469               state = "L (blocked on lock)";
470               break;
471             default:
472               state = "? (unknown)";
473               break;
474             }
475           printf_filtered ("State: %s\n", state);
476           printf_filtered ("Parent process: %d\n", kp.ki_ppid);
477           printf_filtered ("Process group: %d\n", kp.ki_pgid);
478           printf_filtered ("Session id: %d\n", kp.ki_sid);
479           printf_filtered ("TTY: %ju\n", (uintmax_t) kp.ki_tdev);
480           printf_filtered ("TTY owner process group: %d\n", kp.ki_tpgid);
481           printf_filtered ("User IDs (real, effective, saved): %d %d %d\n",
482                            kp.ki_ruid, kp.ki_uid, kp.ki_svuid);
483           printf_filtered ("Group IDs (real, effective, saved): %d %d %d\n",
484                            kp.ki_rgid, kp.ki_groups[0], kp.ki_svgid);
485           printf_filtered ("Groups: ");
486           for (int i = 0; i < kp.ki_ngroups; i++)
487             printf_filtered ("%d ", kp.ki_groups[i]);
488           printf_filtered ("\n");
489           printf_filtered ("Minor faults (no memory page): %ld\n",
490                            kp.ki_rusage.ru_minflt);
491           printf_filtered ("Minor faults, children: %ld\n",
492                            kp.ki_rusage_ch.ru_minflt);
493           printf_filtered ("Major faults (memory page faults): %ld\n",
494                            kp.ki_rusage.ru_majflt);
495           printf_filtered ("Major faults, children: %ld\n",
496                            kp.ki_rusage_ch.ru_majflt);
497           printf_filtered ("utime: %jd.%06ld\n",
498                            (intmax_t) kp.ki_rusage.ru_utime.tv_sec,
499                            kp.ki_rusage.ru_utime.tv_usec);
500           printf_filtered ("stime: %jd.%06ld\n",
501                            (intmax_t) kp.ki_rusage.ru_stime.tv_sec,
502                            kp.ki_rusage.ru_stime.tv_usec);
503           printf_filtered ("utime, children: %jd.%06ld\n",
504                            (intmax_t) kp.ki_rusage_ch.ru_utime.tv_sec,
505                            kp.ki_rusage_ch.ru_utime.tv_usec);
506           printf_filtered ("stime, children: %jd.%06ld\n",
507                            (intmax_t) kp.ki_rusage_ch.ru_stime.tv_sec,
508                            kp.ki_rusage_ch.ru_stime.tv_usec);
509           printf_filtered ("'nice' value: %d\n", kp.ki_nice);
510           printf_filtered ("Start time: %jd.%06ld\n", kp.ki_start.tv_sec,
511                            kp.ki_start.tv_usec);
512           pgtok = getpagesize () / 1024;
513           printf_filtered ("Virtual memory size: %ju kB\n",
514                            (uintmax_t) kp.ki_size / 1024);
515           printf_filtered ("Data size: %ju kB\n",
516                            (uintmax_t) kp.ki_dsize * pgtok);
517           printf_filtered ("Stack size: %ju kB\n",
518                            (uintmax_t) kp.ki_ssize * pgtok);
519           printf_filtered ("Text size: %ju kB\n",
520                            (uintmax_t) kp.ki_tsize * pgtok);
521           printf_filtered ("Resident set size: %ju kB\n",
522                            (uintmax_t) kp.ki_rssize * pgtok);
523           printf_filtered ("Maximum RSS: %ju kB\n",
524                            (uintmax_t) kp.ki_rusage.ru_maxrss);
525           printf_filtered ("Pending Signals: ");
526           for (int i = 0; i < _SIG_WORDS; i++)
527             printf_filtered ("%08x ", kp.ki_siglist.__bits[i]);
528           printf_filtered ("\n");
529           printf_filtered ("Ignored Signals: ");
530           for (int i = 0; i < _SIG_WORDS; i++)
531             printf_filtered ("%08x ", kp.ki_sigignore.__bits[i]);
532           printf_filtered ("\n");
533           printf_filtered ("Caught Signals: ");
534           for (int i = 0; i < _SIG_WORDS; i++)
535             printf_filtered ("%08x ", kp.ki_sigcatch.__bits[i]);
536           printf_filtered ("\n");
537         }
538     }
539
540   return true;
541 }
542
543 /*
544  * The current layout of siginfo_t on FreeBSD was adopted in SVN
545  * revision 153154 which shipped in FreeBSD versions 7.0 and later.
546  * Don't bother supporting the older layout on older kernels.  The
547  * older format was also never used in core dump notes.
548  */
549 #if __FreeBSD_version >= 700009
550 #define USE_SIGINFO
551 #endif
552
553 #ifdef USE_SIGINFO
554 /* Return the size of siginfo for the current inferior.  */
555
556 #ifdef __LP64__
557 union sigval32 {
558   int sival_int;
559   uint32_t sival_ptr;
560 };
561
562 /* This structure matches the naming and layout of `siginfo_t' in
563    <sys/signal.h>.  In particular, the `si_foo' macros defined in that
564    header can be used with both types to copy fields in the `_reason'
565    union.  */
566
567 struct siginfo32
568 {
569   int si_signo;
570   int si_errno;
571   int si_code;
572   __pid_t si_pid;
573   __uid_t si_uid;
574   int si_status;
575   uint32_t si_addr;
576   union sigval32 si_value;
577   union
578   {
579     struct
580     {
581       int _trapno;
582     } _fault;
583     struct
584     {
585       int _timerid;
586       int _overrun;
587     } _timer;
588     struct
589     {
590       int _mqd;
591     } _mesgq;
592     struct
593     {
594       int32_t _band;
595     } _poll;
596     struct
597     {
598       int32_t __spare1__;
599       int __spare2__[7];
600     } __spare__;
601   } _reason;
602 };
603 #endif
604
605 static size_t
606 fbsd_siginfo_size ()
607 {
608 #ifdef __LP64__
609   struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
610
611   /* Is the inferior 32-bit?  If so, use the 32-bit siginfo size.  */
612   if (gdbarch_long_bit (gdbarch) == 32)
613     return sizeof (struct siginfo32);
614 #endif
615   return sizeof (siginfo_t);
616 }
617
618 /* Convert a native 64-bit siginfo object to a 32-bit object.  Note
619    that FreeBSD doesn't support writing to $_siginfo, so this only
620    needs to convert one way.  */
621
622 static void
623 fbsd_convert_siginfo (siginfo_t *si)
624 {
625 #ifdef __LP64__
626   struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
627
628   /* Is the inferior 32-bit?  If not, nothing to do.  */
629   if (gdbarch_long_bit (gdbarch) != 32)
630     return;
631
632   struct siginfo32 si32;
633
634   si32.si_signo = si->si_signo;
635   si32.si_errno = si->si_errno;
636   si32.si_code = si->si_code;
637   si32.si_pid = si->si_pid;
638   si32.si_uid = si->si_uid;
639   si32.si_status = si->si_status;
640   si32.si_addr = (uintptr_t) si->si_addr;
641
642   /* If sival_ptr is being used instead of sival_int on a big-endian
643      platform, then sival_int will be zero since it holds the upper
644      32-bits of the pointer value.  */
645 #if _BYTE_ORDER == _BIG_ENDIAN
646   if (si->si_value.sival_int == 0)
647     si32.si_value.sival_ptr = (uintptr_t) si->si_value.sival_ptr;
648   else
649     si32.si_value.sival_int = si->si_value.sival_int;
650 #else
651   si32.si_value.sival_int = si->si_value.sival_int;
652 #endif
653
654   /* Always copy the spare fields and then possibly overwrite them for
655      signal-specific or code-specific fields.  */
656   si32._reason.__spare__.__spare1__ = si->_reason.__spare__.__spare1__;
657   for (int i = 0; i < 7; i++)
658     si32._reason.__spare__.__spare2__[i] = si->_reason.__spare__.__spare2__[i];
659   switch (si->si_signo) {
660   case SIGILL:
661   case SIGFPE:
662   case SIGSEGV:
663   case SIGBUS:
664     si32.si_trapno = si->si_trapno;
665     break;
666   }
667   switch (si->si_code) {
668   case SI_TIMER:
669     si32.si_timerid = si->si_timerid;
670     si32.si_overrun = si->si_overrun;
671     break;
672   case SI_MESGQ:
673     si32.si_mqd = si->si_mqd;
674     break;
675   }
676
677   memcpy(si, &si32, sizeof (si32));
678 #endif
679 }
680 #endif
681
682 /* Implement the "xfer_partial" target_ops method.  */
683
684 enum target_xfer_status
685 fbsd_nat_target::xfer_partial (enum target_object object,
686                                const char *annex, gdb_byte *readbuf,
687                                const gdb_byte *writebuf,
688                                ULONGEST offset, ULONGEST len,
689                                ULONGEST *xfered_len)
690 {
691   pid_t pid = inferior_ptid.pid ();
692
693   switch (object)
694     {
695 #ifdef USE_SIGINFO
696     case TARGET_OBJECT_SIGNAL_INFO:
697       {
698         struct ptrace_lwpinfo pl;
699         size_t siginfo_size;
700
701         /* FreeBSD doesn't support writing to $_siginfo.  */
702         if (writebuf != NULL)
703           return TARGET_XFER_E_IO;
704
705         if (inferior_ptid.lwp_p ())
706           pid = inferior_ptid.lwp ();
707
708         siginfo_size = fbsd_siginfo_size ();
709         if (offset > siginfo_size)
710           return TARGET_XFER_E_IO;
711
712         if (ptrace (PT_LWPINFO, pid, (PTRACE_TYPE_ARG3) &pl, sizeof (pl)) == -1)
713           return TARGET_XFER_E_IO;
714
715         if (!(pl.pl_flags & PL_FLAG_SI))
716           return TARGET_XFER_E_IO;
717
718         fbsd_convert_siginfo (&pl.pl_siginfo);
719         if (offset + len > siginfo_size)
720           len = siginfo_size - offset;
721
722         memcpy (readbuf, ((gdb_byte *) &pl.pl_siginfo) + offset, len);
723         *xfered_len = len;
724         return TARGET_XFER_OK;
725       }
726 #endif
727 #ifdef KERN_PROC_AUXV
728     case TARGET_OBJECT_AUXV:
729       {
730         gdb::byte_vector buf_storage;
731         gdb_byte *buf;
732         size_t buflen;
733         int mib[4];
734
735         if (writebuf != NULL)
736           return TARGET_XFER_E_IO;
737         mib[0] = CTL_KERN;
738         mib[1] = KERN_PROC;
739         mib[2] = KERN_PROC_AUXV;
740         mib[3] = pid;
741         if (offset == 0)
742           {
743             buf = readbuf;
744             buflen = len;
745           }
746         else
747           {
748             buflen = offset + len;
749             buf_storage.resize (buflen);
750             buf = buf_storage.data ();
751           }
752         if (sysctl (mib, 4, buf, &buflen, NULL, 0) == 0)
753           {
754             if (offset != 0)
755               {
756                 if (buflen > offset)
757                   {
758                     buflen -= offset;
759                     memcpy (readbuf, buf + offset, buflen);
760                   }
761                 else
762                   buflen = 0;
763               }
764             *xfered_len = buflen;
765             return (buflen == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
766           }
767         return TARGET_XFER_E_IO;
768       }
769 #endif
770 #if defined(KERN_PROC_VMMAP) && defined(KERN_PROC_PS_STRINGS)
771     case TARGET_OBJECT_FREEBSD_VMMAP:
772     case TARGET_OBJECT_FREEBSD_PS_STRINGS:
773       {
774         gdb::byte_vector buf_storage;
775         gdb_byte *buf;
776         size_t buflen;
777         int mib[4];
778
779         int proc_target;
780         uint32_t struct_size;
781         switch (object)
782           {
783           case TARGET_OBJECT_FREEBSD_VMMAP:
784             proc_target = KERN_PROC_VMMAP;
785             struct_size = sizeof (struct kinfo_vmentry);
786             break;
787           case TARGET_OBJECT_FREEBSD_PS_STRINGS:
788             proc_target = KERN_PROC_PS_STRINGS;
789             struct_size = sizeof (void *);
790             break;
791           }
792
793         if (writebuf != NULL)
794           return TARGET_XFER_E_IO;
795
796         mib[0] = CTL_KERN;
797         mib[1] = KERN_PROC;
798         mib[2] = proc_target;
799         mib[3] = pid;
800
801         if (sysctl (mib, 4, NULL, &buflen, NULL, 0) != 0)
802           return TARGET_XFER_E_IO;
803         buflen += sizeof (struct_size);
804
805         if (offset >= buflen)
806           {
807             *xfered_len = 0;
808             return TARGET_XFER_EOF;
809           }
810
811         buf_storage.resize (buflen);
812         buf = buf_storage.data ();
813
814         memcpy (buf, &struct_size, sizeof (struct_size));
815         buflen -= sizeof (struct_size);
816         if (sysctl (mib, 4, buf + sizeof (struct_size), &buflen, NULL, 0) != 0)
817           return TARGET_XFER_E_IO;
818         buflen += sizeof (struct_size);
819
820         if (buflen - offset < len)
821           len = buflen - offset;
822         memcpy (readbuf, buf + offset, len);
823         *xfered_len = len;
824         return TARGET_XFER_OK;
825       }
826 #endif
827     default:
828       return inf_ptrace_target::xfer_partial (object, annex,
829                                               readbuf, writebuf, offset,
830                                               len, xfered_len);
831     }
832 }
833
834 #ifdef PT_LWPINFO
835 static int debug_fbsd_lwp;
836 static int debug_fbsd_nat;
837
838 static void
839 show_fbsd_lwp_debug (struct ui_file *file, int from_tty,
840                      struct cmd_list_element *c, const char *value)
841 {
842   fprintf_filtered (file, _("Debugging of FreeBSD lwp module is %s.\n"), value);
843 }
844
845 static void
846 show_fbsd_nat_debug (struct ui_file *file, int from_tty,
847                      struct cmd_list_element *c, const char *value)
848 {
849   fprintf_filtered (file, _("Debugging of FreeBSD native target is %s.\n"),
850                     value);
851 }
852
853 /*
854   FreeBSD's first thread support was via a "reentrant" version of libc
855   (libc_r) that first shipped in 2.2.7.  This library multiplexed all
856   of the threads in a process onto a single kernel thread.  This
857   library was supported via the bsd-uthread target.
858
859   FreeBSD 5.1 introduced two new threading libraries that made use of
860   multiple kernel threads.  The first (libkse) scheduled M user
861   threads onto N (<= M) kernel threads (LWPs).  The second (libthr)
862   bound each user thread to a dedicated kernel thread.  libkse shipped
863   as the default threading library (libpthread).
864
865   FreeBSD 5.3 added a libthread_db to abstract the interface across
866   the various thread libraries (libc_r, libkse, and libthr).
867
868   FreeBSD 7.0 switched the default threading library from from libkse
869   to libpthread and removed libc_r.
870
871   FreeBSD 8.0 removed libkse and the in-kernel support for it.  The
872   only threading library supported by 8.0 and later is libthr which
873   ties each user thread directly to an LWP.  To simplify the
874   implementation, this target only supports LWP-backed threads using
875   ptrace directly rather than libthread_db.
876
877   FreeBSD 11.0 introduced LWP event reporting via PT_LWP_EVENTS.
878 */
879
880 /* Return true if PTID is still active in the inferior.  */
881
882 bool
883 fbsd_nat_target::thread_alive (ptid_t ptid)
884 {
885   if (ptid.lwp_p ())
886     {
887       struct ptrace_lwpinfo pl;
888
889       if (ptrace (PT_LWPINFO, ptid.lwp (), (caddr_t) &pl, sizeof pl)
890           == -1)
891         return false;
892 #ifdef PL_FLAG_EXITED
893       if (pl.pl_flags & PL_FLAG_EXITED)
894         return false;
895 #endif
896     }
897
898   return true;
899 }
900
901 /* Convert PTID to a string.  */
902
903 std::string
904 fbsd_nat_target::pid_to_str (ptid_t ptid)
905 {
906   lwpid_t lwp;
907
908   lwp = ptid.lwp ();
909   if (lwp != 0)
910     {
911       int pid = ptid.pid ();
912
913       return string_printf ("LWP %d of process %d", lwp, pid);
914     }
915
916   return normal_pid_to_str (ptid);
917 }
918
919 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_TDNAME
920 /* Return the name assigned to a thread by an application.  Returns
921    the string in a static buffer.  */
922
923 const char *
924 fbsd_nat_target::thread_name (struct thread_info *thr)
925 {
926   struct ptrace_lwpinfo pl;
927   struct kinfo_proc kp;
928   int pid = thr->ptid.pid ();
929   long lwp = thr->ptid.lwp ();
930   static char buf[sizeof pl.pl_tdname + 1];
931
932   /* Note that ptrace_lwpinfo returns the process command in pl_tdname
933      if a name has not been set explicitly.  Return a NULL name in
934      that case.  */
935   if (!fbsd_fetch_kinfo_proc (pid, &kp))
936     perror_with_name (_("Failed to fetch process information"));
937   if (ptrace (PT_LWPINFO, lwp, (caddr_t) &pl, sizeof pl) == -1)
938     perror_with_name (("ptrace"));
939   if (strcmp (kp.ki_comm, pl.pl_tdname) == 0)
940     return NULL;
941   xsnprintf (buf, sizeof buf, "%s", pl.pl_tdname);
942   return buf;
943 }
944 #endif
945
946 /* Enable additional event reporting on new processes.
947
948    To catch fork events, PTRACE_FORK is set on every traced process
949    to enable stops on returns from fork or vfork.  Note that both the
950    parent and child will always stop, even if system call stops are
951    not enabled.
952
953    To catch LWP events, PTRACE_EVENTS is set on every traced process.
954    This enables stops on the birth for new LWPs (excluding the "main" LWP)
955    and the death of LWPs (excluding the last LWP in a process).  Note
956    that unlike fork events, the LWP that creates a new LWP does not
957    report an event.  */
958
959 static void
960 fbsd_enable_proc_events (pid_t pid)
961 {
962 #ifdef PT_GET_EVENT_MASK
963   int events;
964
965   if (ptrace (PT_GET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3)&events,
966               sizeof (events)) == -1)
967     perror_with_name (("ptrace"));
968   events |= PTRACE_FORK | PTRACE_LWP;
969 #ifdef PTRACE_VFORK
970   events |= PTRACE_VFORK;
971 #endif
972   if (ptrace (PT_SET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3)&events,
973               sizeof (events)) == -1)
974     perror_with_name (("ptrace"));
975 #else
976 #ifdef TDP_RFPPWAIT
977   if (ptrace (PT_FOLLOW_FORK, pid, (PTRACE_TYPE_ARG3)0, 1) == -1)
978     perror_with_name (("ptrace"));
979 #endif
980 #ifdef PT_LWP_EVENTS
981   if (ptrace (PT_LWP_EVENTS, pid, (PTRACE_TYPE_ARG3)0, 1) == -1)
982     perror_with_name (("ptrace"));
983 #endif
984 #endif
985 }
986
987 /* Add threads for any new LWPs in a process.
988
989    When LWP events are used, this function is only used to detect existing
990    threads when attaching to a process.  On older systems, this function is
991    called to discover new threads each time the thread list is updated.  */
992
993 static void
994 fbsd_add_threads (pid_t pid)
995 {
996   int i, nlwps;
997
998   gdb_assert (!in_thread_list (ptid_t (pid)));
999   nlwps = ptrace (PT_GETNUMLWPS, pid, NULL, 0);
1000   if (nlwps == -1)
1001     perror_with_name (("ptrace"));
1002
1003   gdb::unique_xmalloc_ptr<lwpid_t[]> lwps (XCNEWVEC (lwpid_t, nlwps));
1004
1005   nlwps = ptrace (PT_GETLWPLIST, pid, (caddr_t) lwps.get (), nlwps);
1006   if (nlwps == -1)
1007     perror_with_name (("ptrace"));
1008
1009   for (i = 0; i < nlwps; i++)
1010     {
1011       ptid_t ptid = ptid_t (pid, lwps[i], 0);
1012
1013       if (!in_thread_list (ptid))
1014         {
1015 #ifdef PT_LWP_EVENTS
1016           struct ptrace_lwpinfo pl;
1017
1018           /* Don't add exited threads.  Note that this is only called
1019              when attaching to a multi-threaded process.  */
1020           if (ptrace (PT_LWPINFO, lwps[i], (caddr_t) &pl, sizeof pl) == -1)
1021             perror_with_name (("ptrace"));
1022           if (pl.pl_flags & PL_FLAG_EXITED)
1023             continue;
1024 #endif
1025           if (debug_fbsd_lwp)
1026             fprintf_unfiltered (gdb_stdlog,
1027                                 "FLWP: adding thread for LWP %u\n",
1028                                 lwps[i]);
1029           add_thread (ptid);
1030         }
1031     }
1032 }
1033
1034 /* Implement the "update_thread_list" target_ops method.  */
1035
1036 void
1037 fbsd_nat_target::update_thread_list ()
1038 {
1039 #ifdef PT_LWP_EVENTS
1040   /* With support for thread events, threads are added/deleted from the
1041      list as events are reported, so just try deleting exited threads.  */
1042   delete_exited_threads ();
1043 #else
1044   prune_threads ();
1045
1046   fbsd_add_threads (inferior_ptid.pid ());
1047 #endif
1048 }
1049
1050 #ifdef TDP_RFPPWAIT
1051 /*
1052   To catch fork events, PT_FOLLOW_FORK is set on every traced process
1053   to enable stops on returns from fork or vfork.  Note that both the
1054   parent and child will always stop, even if system call stops are not
1055   enabled.
1056
1057   After a fork, both the child and parent process will stop and report
1058   an event.  However, there is no guarantee of order.  If the parent
1059   reports its stop first, then fbsd_wait explicitly waits for the new
1060   child before returning.  If the child reports its stop first, then
1061   the event is saved on a list and ignored until the parent's stop is
1062   reported.  fbsd_wait could have been changed to fetch the parent PID
1063   of the new child and used that to wait for the parent explicitly.
1064   However, if two threads in the parent fork at the same time, then
1065   the wait on the parent might return the "wrong" fork event.
1066
1067   The initial version of PT_FOLLOW_FORK did not set PL_FLAG_CHILD for
1068   the new child process.  This flag could be inferred by treating any
1069   events for an unknown pid as a new child.
1070
1071   In addition, the initial version of PT_FOLLOW_FORK did not report a
1072   stop event for the parent process of a vfork until after the child
1073   process executed a new program or exited.  The kernel was changed to
1074   defer the wait for exit or exec of the child until after posting the
1075   stop event shortly after the change to introduce PL_FLAG_CHILD.
1076   This could be worked around by reporting a vfork event when the
1077   child event posted and ignoring the subsequent event from the
1078   parent.
1079
1080   This implementation requires both of these fixes for simplicity's
1081   sake.  FreeBSD versions newer than 9.1 contain both fixes.
1082 */
1083
1084 static std::list<ptid_t> fbsd_pending_children;
1085
1086 /* Record a new child process event that is reported before the
1087    corresponding fork event in the parent.  */
1088
1089 static void
1090 fbsd_remember_child (ptid_t pid)
1091 {
1092   fbsd_pending_children.push_front (pid);
1093 }
1094
1095 /* Check for a previously-recorded new child process event for PID.
1096    If one is found, remove it from the list and return the PTID.  */
1097
1098 static ptid_t
1099 fbsd_is_child_pending (pid_t pid)
1100 {
1101   for (auto it = fbsd_pending_children.begin ();
1102        it != fbsd_pending_children.end (); it++)
1103     if (it->pid () == pid)
1104       {
1105         ptid_t ptid = *it;
1106         fbsd_pending_children.erase (it);
1107         return ptid;
1108       }
1109   return null_ptid;
1110 }
1111
1112 #ifndef PTRACE_VFORK
1113 static std::forward_list<ptid_t> fbsd_pending_vfork_done;
1114
1115 /* Record a pending vfork done event.  */
1116
1117 static void
1118 fbsd_add_vfork_done (ptid_t pid)
1119 {
1120   fbsd_pending_vfork_done.push_front (pid);
1121 }
1122
1123 /* Check for a pending vfork done event for a specific PID.  */
1124
1125 static int
1126 fbsd_is_vfork_done_pending (pid_t pid)
1127 {
1128   for (auto it = fbsd_pending_vfork_done.begin ();
1129        it != fbsd_pending_vfork_done.end (); it++)
1130     if (it->pid () == pid)
1131       return 1;
1132   return 0;
1133 }
1134
1135 /* Check for a pending vfork done event.  If one is found, remove it
1136    from the list and return the PTID.  */
1137
1138 static ptid_t
1139 fbsd_next_vfork_done (void)
1140 {
1141   if (!fbsd_pending_vfork_done.empty ())
1142     {
1143       ptid_t ptid = fbsd_pending_vfork_done.front ();
1144       fbsd_pending_vfork_done.pop_front ();
1145       return ptid;
1146     }
1147   return null_ptid;
1148 }
1149 #endif
1150 #endif
1151
1152 /* Implement the "resume" target_ops method.  */
1153
1154 void
1155 fbsd_nat_target::resume (ptid_t ptid, int step, enum gdb_signal signo)
1156 {
1157 #if defined(TDP_RFPPWAIT) && !defined(PTRACE_VFORK)
1158   pid_t pid;
1159
1160   /* Don't PT_CONTINUE a process which has a pending vfork done event.  */
1161   if (minus_one_ptid == ptid)
1162     pid = inferior_ptid.pid ();
1163   else
1164     pid = ptid.pid ();
1165   if (fbsd_is_vfork_done_pending (pid))
1166     return;
1167 #endif
1168
1169   if (debug_fbsd_lwp)
1170     fprintf_unfiltered (gdb_stdlog,
1171                         "FLWP: fbsd_resume for ptid (%d, %ld, %ld)\n",
1172                         ptid.pid (), ptid.lwp (),
1173                         ptid.tid ());
1174   if (ptid.lwp_p ())
1175     {
1176       /* If ptid is a specific LWP, suspend all other LWPs in the process.  */
1177       inferior *inf = find_inferior_ptid (ptid);
1178
1179       for (thread_info *tp : inf->non_exited_threads ())
1180         {
1181           int request;
1182
1183           if (tp->ptid.lwp () == ptid.lwp ())
1184             request = PT_RESUME;
1185           else
1186             request = PT_SUSPEND;
1187
1188           if (ptrace (request, tp->ptid.lwp (), NULL, 0) == -1)
1189             perror_with_name (("ptrace"));
1190         }
1191     }
1192   else
1193     {
1194       /* If ptid is a wildcard, resume all matching threads (they won't run
1195          until the process is continued however).  */
1196       for (thread_info *tp : all_non_exited_threads (ptid))
1197         if (ptrace (PT_RESUME, tp->ptid.lwp (), NULL, 0) == -1)
1198           perror_with_name (("ptrace"));
1199       ptid = inferior_ptid;
1200     }
1201
1202 #if __FreeBSD_version < 1200052
1203   /* When multiple threads within a process wish to report STOPPED
1204      events from wait(), the kernel picks one thread event as the
1205      thread event to report.  The chosen thread event is retrieved via
1206      PT_LWPINFO by passing the process ID as the request pid.  If
1207      multiple events are pending, then the subsequent wait() after
1208      resuming a process will report another STOPPED event after
1209      resuming the process to handle the next thread event and so on.
1210
1211      A single thread event is cleared as a side effect of resuming the
1212      process with PT_CONTINUE, PT_STEP, etc.  In older kernels,
1213      however, the request pid was used to select which thread's event
1214      was cleared rather than always clearing the event that was just
1215      reported.  To avoid clearing the event of the wrong LWP, always
1216      pass the process ID instead of an LWP ID to PT_CONTINUE or
1217      PT_SYSCALL.
1218
1219      In the case of stepping, the process ID cannot be used with
1220      PT_STEP since it would step the thread that reported an event
1221      which may not be the thread indicated by PTID.  For stepping, use
1222      PT_SETSTEP to enable stepping on the desired thread before
1223      resuming the process via PT_CONTINUE instead of using
1224      PT_STEP.  */
1225   if (step)
1226     {
1227       if (ptrace (PT_SETSTEP, get_ptrace_pid (ptid), NULL, 0) == -1)
1228         perror_with_name (("ptrace"));
1229       step = 0;
1230     }
1231   ptid = ptid_t (ptid.pid ());
1232 #endif
1233   inf_ptrace_target::resume (ptid, step, signo);
1234 }
1235
1236 #ifdef USE_SIGTRAP_SIGINFO
1237 /* Handle breakpoint and trace traps reported via SIGTRAP.  If the
1238    trap was a breakpoint or trace trap that should be reported to the
1239    core, return true.  */
1240
1241 static bool
1242 fbsd_handle_debug_trap (ptid_t ptid, const struct ptrace_lwpinfo &pl)
1243 {
1244
1245   /* Ignore traps without valid siginfo or for signals other than
1246      SIGTRAP.
1247
1248      FreeBSD kernels prior to r341800 can return stale siginfo for at
1249      least some events, but those events can be identified by
1250      additional flags set in pl_flags.  True breakpoint and
1251      single-step traps should not have other flags set in
1252      pl_flags.  */
1253   if (pl.pl_flags != PL_FLAG_SI || pl.pl_siginfo.si_signo != SIGTRAP)
1254     return false;
1255
1256   /* Trace traps are either a single step or a hardware watchpoint or
1257      breakpoint.  */
1258   if (pl.pl_siginfo.si_code == TRAP_TRACE)
1259     {
1260       if (debug_fbsd_nat)
1261         fprintf_unfiltered (gdb_stdlog,
1262                             "FNAT: trace trap for LWP %ld\n", ptid.lwp ());
1263       return true;
1264     }
1265
1266   if (pl.pl_siginfo.si_code == TRAP_BRKPT)
1267     {
1268       /* Fixup PC for the software breakpoint.  */
1269       struct regcache *regcache = get_thread_regcache (ptid);
1270       struct gdbarch *gdbarch = regcache->arch ();
1271       int decr_pc = gdbarch_decr_pc_after_break (gdbarch);
1272
1273       if (debug_fbsd_nat)
1274         fprintf_unfiltered (gdb_stdlog,
1275                             "FNAT: sw breakpoint trap for LWP %ld\n",
1276                             ptid.lwp ());
1277       if (decr_pc != 0)
1278         {
1279           CORE_ADDR pc;
1280
1281           pc = regcache_read_pc (regcache);
1282           regcache_write_pc (regcache, pc - decr_pc);
1283         }
1284       return true;
1285     }
1286
1287   return false;
1288 }
1289 #endif
1290
1291 /* Wait for the child specified by PTID to do something.  Return the
1292    process ID of the child, or MINUS_ONE_PTID in case of error; store
1293    the status in *OURSTATUS.  */
1294
1295 ptid_t
1296 fbsd_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1297                        int target_options)
1298 {
1299   ptid_t wptid;
1300
1301   while (1)
1302     {
1303 #ifndef PTRACE_VFORK
1304       wptid = fbsd_next_vfork_done ();
1305       if (wptid != null_ptid)
1306         {
1307           ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
1308           return wptid;
1309         }
1310 #endif
1311       wptid = inf_ptrace_target::wait (ptid, ourstatus, target_options);
1312       if (ourstatus->kind == TARGET_WAITKIND_STOPPED)
1313         {
1314           struct ptrace_lwpinfo pl;
1315           pid_t pid;
1316           int status;
1317
1318           pid = wptid.pid ();
1319           if (ptrace (PT_LWPINFO, pid, (caddr_t) &pl, sizeof pl) == -1)
1320             perror_with_name (("ptrace"));
1321
1322           wptid = ptid_t (pid, pl.pl_lwpid, 0);
1323
1324           if (debug_fbsd_nat)
1325             {
1326               fprintf_unfiltered (gdb_stdlog,
1327                                   "FNAT: stop for LWP %u event %d flags %#x\n",
1328                                   pl.pl_lwpid, pl.pl_event, pl.pl_flags);
1329               if (pl.pl_flags & PL_FLAG_SI)
1330                 fprintf_unfiltered (gdb_stdlog,
1331                                     "FNAT: si_signo %u si_code %u\n",
1332                                     pl.pl_siginfo.si_signo,
1333                                     pl.pl_siginfo.si_code);
1334             }
1335
1336 #ifdef PT_LWP_EVENTS
1337           if (pl.pl_flags & PL_FLAG_EXITED)
1338             {
1339               /* If GDB attaches to a multi-threaded process, exiting
1340                  threads might be skipped during post_attach that
1341                  have not yet reported their PL_FLAG_EXITED event.
1342                  Ignore EXITED events for an unknown LWP.  */
1343               thread_info *thr = find_thread_ptid (wptid);
1344               if (thr != nullptr)
1345                 {
1346                   if (debug_fbsd_lwp)
1347                     fprintf_unfiltered (gdb_stdlog,
1348                                         "FLWP: deleting thread for LWP %u\n",
1349                                         pl.pl_lwpid);
1350                   if (print_thread_events)
1351                     printf_unfiltered (_("[%s exited]\n"),
1352                                        target_pid_to_str (wptid).c_str ());
1353                   delete_thread (thr);
1354                 }
1355               if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1356                 perror_with_name (("ptrace"));
1357               continue;
1358             }
1359 #endif
1360
1361           /* Switch to an LWP PTID on the first stop in a new process.
1362              This is done after handling PL_FLAG_EXITED to avoid
1363              switching to an exited LWP.  It is done before checking
1364              PL_FLAG_BORN in case the first stop reported after
1365              attaching to an existing process is a PL_FLAG_BORN
1366              event.  */
1367           if (in_thread_list (ptid_t (pid)))
1368             {
1369               if (debug_fbsd_lwp)
1370                 fprintf_unfiltered (gdb_stdlog,
1371                                     "FLWP: using LWP %u for first thread\n",
1372                                     pl.pl_lwpid);
1373               thread_change_ptid (ptid_t (pid), wptid);
1374             }
1375
1376 #ifdef PT_LWP_EVENTS
1377           if (pl.pl_flags & PL_FLAG_BORN)
1378             {
1379               /* If GDB attaches to a multi-threaded process, newborn
1380                  threads might be added by fbsd_add_threads that have
1381                  not yet reported their PL_FLAG_BORN event.  Ignore
1382                  BORN events for an already-known LWP.  */
1383               if (!in_thread_list (wptid))
1384                 {
1385                   if (debug_fbsd_lwp)
1386                     fprintf_unfiltered (gdb_stdlog,
1387                                         "FLWP: adding thread for LWP %u\n",
1388                                         pl.pl_lwpid);
1389                   add_thread (wptid);
1390                 }
1391               ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1392               return wptid;
1393             }
1394 #endif
1395
1396 #ifdef TDP_RFPPWAIT
1397           if (pl.pl_flags & PL_FLAG_FORKED)
1398             {
1399 #ifndef PTRACE_VFORK
1400               struct kinfo_proc kp;
1401 #endif
1402               ptid_t child_ptid;
1403               pid_t child;
1404
1405               child = pl.pl_child_pid;
1406               ourstatus->kind = TARGET_WAITKIND_FORKED;
1407 #ifdef PTRACE_VFORK
1408               if (pl.pl_flags & PL_FLAG_VFORKED)
1409                 ourstatus->kind = TARGET_WAITKIND_VFORKED;
1410 #endif
1411
1412               /* Make sure the other end of the fork is stopped too.  */
1413               child_ptid = fbsd_is_child_pending (child);
1414               if (child_ptid == null_ptid)
1415                 {
1416                   pid = waitpid (child, &status, 0);
1417                   if (pid == -1)
1418                     perror_with_name (("waitpid"));
1419
1420                   gdb_assert (pid == child);
1421
1422                   if (ptrace (PT_LWPINFO, child, (caddr_t)&pl, sizeof pl) == -1)
1423                     perror_with_name (("ptrace"));
1424
1425                   gdb_assert (pl.pl_flags & PL_FLAG_CHILD);
1426                   child_ptid = ptid_t (child, pl.pl_lwpid, 0);
1427                 }
1428
1429               /* Enable additional events on the child process.  */
1430               fbsd_enable_proc_events (child_ptid.pid ());
1431
1432 #ifndef PTRACE_VFORK
1433               /* For vfork, the child process will have the P_PPWAIT
1434                  flag set.  */
1435               if (fbsd_fetch_kinfo_proc (child, &kp))
1436                 {
1437                   if (kp.ki_flag & P_PPWAIT)
1438                     ourstatus->kind = TARGET_WAITKIND_VFORKED;
1439                 }
1440               else
1441                 warning (_("Failed to fetch process information"));
1442 #endif
1443               ourstatus->value.related_pid = child_ptid;
1444
1445               return wptid;
1446             }
1447
1448           if (pl.pl_flags & PL_FLAG_CHILD)
1449             {
1450               /* Remember that this child forked, but do not report it
1451                  until the parent reports its corresponding fork
1452                  event.  */
1453               fbsd_remember_child (wptid);
1454               continue;
1455             }
1456
1457 #ifdef PTRACE_VFORK
1458           if (pl.pl_flags & PL_FLAG_VFORK_DONE)
1459             {
1460               ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
1461               return wptid;
1462             }
1463 #endif
1464 #endif
1465
1466 #ifdef PL_FLAG_EXEC
1467           if (pl.pl_flags & PL_FLAG_EXEC)
1468             {
1469               ourstatus->kind = TARGET_WAITKIND_EXECD;
1470               ourstatus->value.execd_pathname
1471                 = xstrdup (pid_to_exec_file (pid));
1472               return wptid;
1473             }
1474 #endif
1475
1476 #ifdef USE_SIGTRAP_SIGINFO
1477           if (fbsd_handle_debug_trap (wptid, pl))
1478             return wptid;
1479 #endif
1480
1481           /* Note that PL_FLAG_SCE is set for any event reported while
1482              a thread is executing a system call in the kernel.  In
1483              particular, signals that interrupt a sleep in a system
1484              call will report this flag as part of their event.  Stops
1485              explicitly for system call entry and exit always use
1486              SIGTRAP, so only treat SIGTRAP events as system call
1487              entry/exit events.  */
1488           if (pl.pl_flags & (PL_FLAG_SCE | PL_FLAG_SCX)
1489               && ourstatus->value.sig == SIGTRAP)
1490             {
1491 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1492               if (catch_syscall_enabled ())
1493                 {
1494                   if (catching_syscall_number (pl.pl_syscall_code))
1495                     {
1496                       if (pl.pl_flags & PL_FLAG_SCE)
1497                         ourstatus->kind = TARGET_WAITKIND_SYSCALL_ENTRY;
1498                       else
1499                         ourstatus->kind = TARGET_WAITKIND_SYSCALL_RETURN;
1500                       ourstatus->value.syscall_number = pl.pl_syscall_code;
1501                       return wptid;
1502                     }
1503                 }
1504 #endif
1505               /* If the core isn't interested in this event, just
1506                  continue the process explicitly and wait for another
1507                  event.  Note that PT_SYSCALL is "sticky" on FreeBSD
1508                  and once system call stops are enabled on a process
1509                  it stops for all system call entries and exits.  */
1510               if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1511                 perror_with_name (("ptrace"));
1512               continue;
1513             }
1514         }
1515       return wptid;
1516     }
1517 }
1518
1519 #ifdef USE_SIGTRAP_SIGINFO
1520 /* Implement the "stopped_by_sw_breakpoint" target_ops method.  */
1521
1522 bool
1523 fbsd_nat_target::stopped_by_sw_breakpoint ()
1524 {
1525   struct ptrace_lwpinfo pl;
1526
1527   if (ptrace (PT_LWPINFO, get_ptrace_pid (inferior_ptid), (caddr_t) &pl,
1528               sizeof pl) == -1)
1529     return false;
1530
1531   return (pl.pl_flags == PL_FLAG_SI
1532           && pl.pl_siginfo.si_signo == SIGTRAP
1533           && pl.pl_siginfo.si_code == TRAP_BRKPT);
1534 }
1535
1536 /* Implement the "supports_stopped_by_sw_breakpoint" target_ops
1537    method.  */
1538
1539 bool
1540 fbsd_nat_target::supports_stopped_by_sw_breakpoint ()
1541 {
1542   return true;
1543 }
1544 #endif
1545
1546 #ifdef TDP_RFPPWAIT
1547 /* Target hook for follow_fork.  On entry and at return inferior_ptid is
1548    the ptid of the followed inferior.  */
1549
1550 int
1551 fbsd_nat_target::follow_fork (int follow_child, int detach_fork)
1552 {
1553   if (!follow_child && detach_fork)
1554     {
1555       struct thread_info *tp = inferior_thread ();
1556       pid_t child_pid = tp->pending_follow.value.related_pid.pid ();
1557
1558       /* Breakpoints have already been detached from the child by
1559          infrun.c.  */
1560
1561       if (ptrace (PT_DETACH, child_pid, (PTRACE_TYPE_ARG3)1, 0) == -1)
1562         perror_with_name (("ptrace"));
1563
1564 #ifndef PTRACE_VFORK
1565       if (tp->pending_follow.kind == TARGET_WAITKIND_VFORKED)
1566         {
1567           /* We can't insert breakpoints until the child process has
1568              finished with the shared memory region.  The parent
1569              process doesn't wait for the child process to exit or
1570              exec until after it has been resumed from the ptrace stop
1571              to report the fork.  Once it has been resumed it doesn't
1572              stop again before returning to userland, so there is no
1573              reliable way to wait on the parent.
1574
1575              We can't stay attached to the child to wait for an exec
1576              or exit because it may invoke ptrace(PT_TRACE_ME)
1577              (e.g. if the parent process is a debugger forking a new
1578              child process).
1579
1580              In the end, the best we can do is to make sure it runs
1581              for a little while.  Hopefully it will be out of range of
1582              any breakpoints we reinsert.  Usually this is only the
1583              single-step breakpoint at vfork's return point.  */
1584
1585           usleep (10000);
1586
1587           /* Schedule a fake VFORK_DONE event to report on the next
1588              wait.  */
1589           fbsd_add_vfork_done (inferior_ptid);
1590         }
1591 #endif
1592     }
1593
1594   return 0;
1595 }
1596
1597 int
1598 fbsd_nat_target::insert_fork_catchpoint (int pid)
1599 {
1600   return 0;
1601 }
1602
1603 int
1604 fbsd_nat_target::remove_fork_catchpoint (int pid)
1605 {
1606   return 0;
1607 }
1608
1609 int
1610 fbsd_nat_target::insert_vfork_catchpoint (int pid)
1611 {
1612   return 0;
1613 }
1614
1615 int
1616 fbsd_nat_target::remove_vfork_catchpoint (int pid)
1617 {
1618   return 0;
1619 }
1620 #endif
1621
1622 /* Implement the "post_startup_inferior" target_ops method.  */
1623
1624 void
1625 fbsd_nat_target::post_startup_inferior (ptid_t pid)
1626 {
1627   fbsd_enable_proc_events (pid.pid ());
1628 }
1629
1630 /* Implement the "post_attach" target_ops method.  */
1631
1632 void
1633 fbsd_nat_target::post_attach (int pid)
1634 {
1635   fbsd_enable_proc_events (pid);
1636   fbsd_add_threads (pid);
1637 }
1638
1639 #ifdef PL_FLAG_EXEC
1640 /* If the FreeBSD kernel supports PL_FLAG_EXEC, then traced processes
1641    will always stop after exec.  */
1642
1643 int
1644 fbsd_nat_target::insert_exec_catchpoint (int pid)
1645 {
1646   return 0;
1647 }
1648
1649 int
1650 fbsd_nat_target::remove_exec_catchpoint (int pid)
1651 {
1652   return 0;
1653 }
1654 #endif
1655
1656 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1657 int
1658 fbsd_nat_target::set_syscall_catchpoint (int pid, bool needed,
1659                                          int any_count,
1660                                          gdb::array_view<const int> syscall_counts)
1661 {
1662
1663   /* Ignore the arguments.  inf-ptrace.c will use PT_SYSCALL which
1664      will catch all system call entries and exits.  The system calls
1665      are filtered by GDB rather than the kernel.  */
1666   return 0;
1667 }
1668 #endif
1669 #endif
1670
1671 void
1672 _initialize_fbsd_nat (void)
1673 {
1674 #ifdef PT_LWPINFO
1675   add_setshow_boolean_cmd ("fbsd-lwp", class_maintenance,
1676                            &debug_fbsd_lwp, _("\
1677 Set debugging of FreeBSD lwp module."), _("\
1678 Show debugging of FreeBSD lwp module."), _("\
1679 Enables printf debugging output."),
1680                            NULL,
1681                            &show_fbsd_lwp_debug,
1682                            &setdebuglist, &showdebuglist);
1683   add_setshow_boolean_cmd ("fbsd-nat", class_maintenance,
1684                            &debug_fbsd_nat, _("\
1685 Set debugging of FreeBSD native target."), _("\
1686 Show debugging of FreeBSD native target."), _("\
1687 Enables printf debugging output."),
1688                            NULL,
1689                            &show_fbsd_nat_debug,
1690                            &setdebuglist, &showdebuglist);
1691 #endif
1692 }