RISC-V: Support SiFive extensions: xsfvqmaccdod, xsfvqmaccqoq and xsfvfnrclipxfqf
[binutils-gdb.git] / gdb / fbsd-nat.c
blob6da32a4a50b25b7a214fd76ac5dcdc3ae09a1044
1 /* Native-dependent code for FreeBSD.
3 Copyright (C) 2002-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "gdbsupport/block-signals.h"
21 #include "gdbsupport/byte-vector.h"
22 #include "gdbsupport/event-loop.h"
23 #include "gdbcore.h"
24 #include "inferior.h"
25 #include "regcache.h"
26 #include "regset.h"
27 #include "gdbarch.h"
28 #include "cli/cli-cmds.h"
29 #include "gdbthread.h"
30 #include "gdbsupport/buildargv.h"
31 #include "gdbsupport/gdb_wait.h"
32 #include "inf-loop.h"
33 #include "inf-ptrace.h"
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_PROCCTL_H
36 #include <sys/procctl.h>
37 #endif
38 #include <sys/procfs.h>
39 #include <sys/ptrace.h>
40 #include <sys/signal.h>
41 #include <sys/sysctl.h>
42 #include <sys/user.h>
43 #include <libutil.h>
45 #include "elf-bfd.h"
46 #include "fbsd-nat.h"
47 #include "fbsd-tdep.h"
49 #ifndef PT_GETREGSET
50 #define PT_GETREGSET 42 /* Get a target register set */
51 #define PT_SETREGSET 43 /* Set a target register set */
52 #endif
54 /* Information stored about each inferior. */
55 struct fbsd_inferior : public private_inferior
57 /* Filter for resumed LWPs which can report events from wait. */
58 ptid_t resumed_lwps = null_ptid;
60 /* Number of LWPs this process contains. */
61 unsigned int num_lwps = 0;
63 /* Number of LWPs currently running. */
64 unsigned int running_lwps = 0;
66 /* Have a pending SIGSTOP event that needs to be discarded. */
67 bool pending_sigstop = false;
70 /* Return the fbsd_inferior attached to INF. */
72 static inline fbsd_inferior *
73 get_fbsd_inferior (inferior *inf)
75 return gdb::checked_static_cast<fbsd_inferior *> (inf->priv.get ());
78 /* See fbsd-nat.h. */
80 void
81 fbsd_nat_target::add_pending_event (const ptid_t &ptid,
82 const target_waitstatus &status)
84 gdb_assert (find_inferior_ptid (this, ptid) != nullptr);
85 m_pending_events.emplace_back (ptid, status);
88 /* See fbsd-nat.h. */
90 bool
91 fbsd_nat_target::have_pending_event (ptid_t filter)
93 for (const pending_event &event : m_pending_events)
94 if (event.ptid.matches (filter))
95 return true;
96 return false;
99 /* See fbsd-nat.h. */
101 std::optional<fbsd_nat_target::pending_event>
102 fbsd_nat_target::take_pending_event (ptid_t filter)
104 for (auto it = m_pending_events.begin (); it != m_pending_events.end (); it++)
105 if (it->ptid.matches (filter))
107 inferior *inf = find_inferior_ptid (this, it->ptid);
108 fbsd_inferior *fbsd_inf = get_fbsd_inferior (inf);
109 if (it->ptid.matches (fbsd_inf->resumed_lwps))
111 pending_event event = *it;
112 m_pending_events.erase (it);
113 return event;
116 return {};
119 /* Return the name of a file that can be opened to get the symbols for
120 the child process identified by PID. */
122 const char *
123 fbsd_nat_target::pid_to_exec_file (int pid)
125 static char buf[PATH_MAX];
126 size_t buflen;
127 int mib[4];
129 mib[0] = CTL_KERN;
130 mib[1] = KERN_PROC;
131 mib[2] = KERN_PROC_PATHNAME;
132 mib[3] = pid;
133 buflen = sizeof buf;
134 if (sysctl (mib, 4, buf, &buflen, NULL, 0) == 0)
135 /* The kern.proc.pathname.<pid> sysctl returns a length of zero
136 for processes without an associated executable such as kernel
137 processes. */
138 return buflen == 0 ? NULL : buf;
140 return NULL;
143 /* Iterate over all the memory regions in the current inferior,
144 calling FUNC for each memory region. DATA is passed as the last
145 argument to FUNC. */
148 fbsd_nat_target::find_memory_regions (find_memory_region_ftype func,
149 void *data)
151 pid_t pid = inferior_ptid.pid ();
152 struct kinfo_vmentry *kve;
153 uint64_t size;
154 int i, nitems;
156 gdb::unique_xmalloc_ptr<struct kinfo_vmentry>
157 vmentl (kinfo_getvmmap (pid, &nitems));
158 if (vmentl == NULL)
159 perror_with_name (_("Couldn't fetch VM map entries"));
161 for (i = 0, kve = vmentl.get (); i < nitems; i++, kve++)
163 /* Skip unreadable segments and those where MAP_NOCORE has been set. */
164 if (!(kve->kve_protection & KVME_PROT_READ)
165 || kve->kve_flags & KVME_FLAG_NOCOREDUMP)
166 continue;
168 /* Skip segments with an invalid type. */
169 if (kve->kve_type != KVME_TYPE_DEFAULT
170 && kve->kve_type != KVME_TYPE_VNODE
171 && kve->kve_type != KVME_TYPE_SWAP
172 && kve->kve_type != KVME_TYPE_PHYS)
173 continue;
175 size = kve->kve_end - kve->kve_start;
176 if (info_verbose)
178 gdb_printf ("Save segment, %ld bytes at %s (%c%c%c)\n",
179 (long) size,
180 paddress (current_inferior ()->arch (), kve->kve_start),
181 kve->kve_protection & KVME_PROT_READ ? 'r' : '-',
182 kve->kve_protection & KVME_PROT_WRITE ? 'w' : '-',
183 kve->kve_protection & KVME_PROT_EXEC ? 'x' : '-');
186 /* Invoke the callback function to create the corefile segment.
187 Pass MODIFIED as true, we do not know the real modification state. */
188 func (kve->kve_start, size, kve->kve_protection & KVME_PROT_READ,
189 kve->kve_protection & KVME_PROT_WRITE,
190 kve->kve_protection & KVME_PROT_EXEC, 1, false, data);
192 return 0;
195 /* Fetch the command line for a running process. */
197 static gdb::unique_xmalloc_ptr<char>
198 fbsd_fetch_cmdline (pid_t pid)
200 size_t len;
201 int mib[4];
203 len = 0;
204 mib[0] = CTL_KERN;
205 mib[1] = KERN_PROC;
206 mib[2] = KERN_PROC_ARGS;
207 mib[3] = pid;
208 if (sysctl (mib, 4, NULL, &len, NULL, 0) == -1)
209 return nullptr;
211 if (len == 0)
212 return nullptr;
214 gdb::unique_xmalloc_ptr<char> cmdline ((char *) xmalloc (len));
215 if (sysctl (mib, 4, cmdline.get (), &len, NULL, 0) == -1)
216 return nullptr;
218 /* Join the arguments with spaces to form a single string. */
219 char *cp = cmdline.get ();
220 for (size_t i = 0; i < len - 1; i++)
221 if (cp[i] == '\0')
222 cp[i] = ' ';
223 cp[len - 1] = '\0';
225 return cmdline;
228 /* Fetch the external variant of the kernel's internal process
229 structure for the process PID into KP. */
231 static bool
232 fbsd_fetch_kinfo_proc (pid_t pid, struct kinfo_proc *kp)
234 size_t len;
235 int mib[4];
237 len = sizeof *kp;
238 mib[0] = CTL_KERN;
239 mib[1] = KERN_PROC;
240 mib[2] = KERN_PROC_PID;
241 mib[3] = pid;
242 return (sysctl (mib, 4, kp, &len, NULL, 0) == 0);
245 /* Implement the "info_proc" target_ops method. */
247 bool
248 fbsd_nat_target::info_proc (const char *args, enum info_proc_what what)
250 gdb::unique_xmalloc_ptr<struct kinfo_file> fdtbl;
251 int nfd = 0;
252 struct kinfo_proc kp;
253 pid_t pid;
254 bool do_cmdline = false;
255 bool do_cwd = false;
256 bool do_exe = false;
257 bool do_files = false;
258 bool do_mappings = false;
259 bool do_status = false;
261 switch (what)
263 case IP_MINIMAL:
264 do_cmdline = true;
265 do_cwd = true;
266 do_exe = true;
267 break;
268 case IP_MAPPINGS:
269 do_mappings = true;
270 break;
271 case IP_STATUS:
272 case IP_STAT:
273 do_status = true;
274 break;
275 case IP_CMDLINE:
276 do_cmdline = true;
277 break;
278 case IP_EXE:
279 do_exe = true;
280 break;
281 case IP_CWD:
282 do_cwd = true;
283 break;
284 case IP_FILES:
285 do_files = true;
286 break;
287 case IP_ALL:
288 do_cmdline = true;
289 do_cwd = true;
290 do_exe = true;
291 do_files = true;
292 do_mappings = true;
293 do_status = true;
294 break;
295 default:
296 error (_("Not supported on this target."));
299 gdb_argv built_argv (args);
300 if (built_argv.count () == 0)
302 pid = inferior_ptid.pid ();
303 if (pid == 0)
304 error (_("No current process: you must name one."));
306 else if (built_argv.count () == 1 && isdigit (built_argv[0][0]))
307 pid = strtol (built_argv[0], NULL, 10);
308 else
309 error (_("Invalid arguments."));
311 gdb_printf (_("process %d\n"), pid);
312 if (do_cwd || do_exe || do_files)
313 fdtbl.reset (kinfo_getfile (pid, &nfd));
315 if (do_cmdline)
317 gdb::unique_xmalloc_ptr<char> cmdline = fbsd_fetch_cmdline (pid);
318 if (cmdline != nullptr)
319 gdb_printf ("cmdline = '%s'\n", cmdline.get ());
320 else
321 warning (_("unable to fetch command line"));
323 if (do_cwd)
325 const char *cwd = NULL;
326 struct kinfo_file *kf = fdtbl.get ();
327 for (int i = 0; i < nfd; i++, kf++)
329 if (kf->kf_type == KF_TYPE_VNODE && kf->kf_fd == KF_FD_TYPE_CWD)
331 cwd = kf->kf_path;
332 break;
335 if (cwd != NULL)
336 gdb_printf ("cwd = '%s'\n", cwd);
337 else
338 warning (_("unable to fetch current working directory"));
340 if (do_exe)
342 const char *exe = NULL;
343 struct kinfo_file *kf = fdtbl.get ();
344 for (int i = 0; i < nfd; i++, kf++)
346 if (kf->kf_type == KF_TYPE_VNODE && kf->kf_fd == KF_FD_TYPE_TEXT)
348 exe = kf->kf_path;
349 break;
352 if (exe == NULL)
353 exe = pid_to_exec_file (pid);
354 if (exe != NULL)
355 gdb_printf ("exe = '%s'\n", exe);
356 else
357 warning (_("unable to fetch executable path name"));
359 if (do_files)
361 struct kinfo_file *kf = fdtbl.get ();
363 if (nfd > 0)
365 fbsd_info_proc_files_header ();
366 for (int i = 0; i < nfd; i++, kf++)
367 fbsd_info_proc_files_entry (kf->kf_type, kf->kf_fd, kf->kf_flags,
368 kf->kf_offset, kf->kf_vnode_type,
369 kf->kf_sock_domain, kf->kf_sock_type,
370 kf->kf_sock_protocol, &kf->kf_sa_local,
371 &kf->kf_sa_peer, kf->kf_path);
373 else
374 warning (_("unable to fetch list of open files"));
376 if (do_mappings)
378 int nvment;
379 gdb::unique_xmalloc_ptr<struct kinfo_vmentry>
380 vmentl (kinfo_getvmmap (pid, &nvment));
382 if (vmentl != nullptr)
384 int addr_bit = TARGET_CHAR_BIT * sizeof (void *);
385 fbsd_info_proc_mappings_header (addr_bit);
387 struct kinfo_vmentry *kve = vmentl.get ();
388 for (int i = 0; i < nvment; i++, kve++)
389 fbsd_info_proc_mappings_entry (addr_bit, kve->kve_start,
390 kve->kve_end, kve->kve_offset,
391 kve->kve_flags, kve->kve_protection,
392 kve->kve_path);
394 else
395 warning (_("unable to fetch virtual memory map"));
397 if (do_status)
399 if (!fbsd_fetch_kinfo_proc (pid, &kp))
400 warning (_("Failed to fetch process information"));
401 else
403 const char *state;
404 int pgtok;
406 gdb_printf ("Name: %s\n", kp.ki_comm);
407 switch (kp.ki_stat)
409 case SIDL:
410 state = "I (idle)";
411 break;
412 case SRUN:
413 state = "R (running)";
414 break;
415 case SSTOP:
416 state = "T (stopped)";
417 break;
418 case SZOMB:
419 state = "Z (zombie)";
420 break;
421 case SSLEEP:
422 state = "S (sleeping)";
423 break;
424 case SWAIT:
425 state = "W (interrupt wait)";
426 break;
427 case SLOCK:
428 state = "L (blocked on lock)";
429 break;
430 default:
431 state = "? (unknown)";
432 break;
434 gdb_printf ("State: %s\n", state);
435 gdb_printf ("Parent process: %d\n", kp.ki_ppid);
436 gdb_printf ("Process group: %d\n", kp.ki_pgid);
437 gdb_printf ("Session id: %d\n", kp.ki_sid);
438 gdb_printf ("TTY: %s\n", pulongest (kp.ki_tdev));
439 gdb_printf ("TTY owner process group: %d\n", kp.ki_tpgid);
440 gdb_printf ("User IDs (real, effective, saved): %d %d %d\n",
441 kp.ki_ruid, kp.ki_uid, kp.ki_svuid);
442 gdb_printf ("Group IDs (real, effective, saved): %d %d %d\n",
443 kp.ki_rgid, kp.ki_groups[0], kp.ki_svgid);
444 gdb_printf ("Groups: ");
445 for (int i = 0; i < kp.ki_ngroups; i++)
446 gdb_printf ("%d ", kp.ki_groups[i]);
447 gdb_printf ("\n");
448 gdb_printf ("Minor faults (no memory page): %ld\n",
449 kp.ki_rusage.ru_minflt);
450 gdb_printf ("Minor faults, children: %ld\n",
451 kp.ki_rusage_ch.ru_minflt);
452 gdb_printf ("Major faults (memory page faults): %ld\n",
453 kp.ki_rusage.ru_majflt);
454 gdb_printf ("Major faults, children: %ld\n",
455 kp.ki_rusage_ch.ru_majflt);
456 gdb_printf ("utime: %s.%06ld\n",
457 plongest (kp.ki_rusage.ru_utime.tv_sec),
458 kp.ki_rusage.ru_utime.tv_usec);
459 gdb_printf ("stime: %s.%06ld\n",
460 plongest (kp.ki_rusage.ru_stime.tv_sec),
461 kp.ki_rusage.ru_stime.tv_usec);
462 gdb_printf ("utime, children: %s.%06ld\n",
463 plongest (kp.ki_rusage_ch.ru_utime.tv_sec),
464 kp.ki_rusage_ch.ru_utime.tv_usec);
465 gdb_printf ("stime, children: %s.%06ld\n",
466 plongest (kp.ki_rusage_ch.ru_stime.tv_sec),
467 kp.ki_rusage_ch.ru_stime.tv_usec);
468 gdb_printf ("'nice' value: %d\n", kp.ki_nice);
469 gdb_printf ("Start time: %s.%06ld\n",
470 plongest (kp.ki_start.tv_sec),
471 kp.ki_start.tv_usec);
472 pgtok = getpagesize () / 1024;
473 gdb_printf ("Virtual memory size: %s kB\n",
474 pulongest (kp.ki_size / 1024));
475 gdb_printf ("Data size: %s kB\n",
476 pulongest (kp.ki_dsize * pgtok));
477 gdb_printf ("Stack size: %s kB\n",
478 pulongest (kp.ki_ssize * pgtok));
479 gdb_printf ("Text size: %s kB\n",
480 pulongest (kp.ki_tsize * pgtok));
481 gdb_printf ("Resident set size: %s kB\n",
482 pulongest (kp.ki_rssize * pgtok));
483 gdb_printf ("Maximum RSS: %s kB\n",
484 pulongest (kp.ki_rusage.ru_maxrss));
485 gdb_printf ("Pending Signals: ");
486 for (int i = 0; i < _SIG_WORDS; i++)
487 gdb_printf ("%08x ", kp.ki_siglist.__bits[i]);
488 gdb_printf ("\n");
489 gdb_printf ("Ignored Signals: ");
490 for (int i = 0; i < _SIG_WORDS; i++)
491 gdb_printf ("%08x ", kp.ki_sigignore.__bits[i]);
492 gdb_printf ("\n");
493 gdb_printf ("Caught Signals: ");
494 for (int i = 0; i < _SIG_WORDS; i++)
495 gdb_printf ("%08x ", kp.ki_sigcatch.__bits[i]);
496 gdb_printf ("\n");
500 return true;
503 /* Return the size of siginfo for the current inferior. */
505 #ifdef __LP64__
506 union sigval32 {
507 int sival_int;
508 uint32_t sival_ptr;
511 /* This structure matches the naming and layout of `siginfo_t' in
512 <sys/signal.h>. In particular, the `si_foo' macros defined in that
513 header can be used with both types to copy fields in the `_reason'
514 union. */
516 struct siginfo32
518 int si_signo;
519 int si_errno;
520 int si_code;
521 __pid_t si_pid;
522 __uid_t si_uid;
523 int si_status;
524 uint32_t si_addr;
525 union sigval32 si_value;
526 union
528 struct
530 int _trapno;
531 } _fault;
532 struct
534 int _timerid;
535 int _overrun;
536 } _timer;
537 struct
539 int _mqd;
540 } _mesgq;
541 struct
543 int32_t _band;
544 } _poll;
545 struct
547 int32_t __spare1__;
548 int __spare2__[7];
549 } __spare__;
550 } _reason;
552 #endif
554 static size_t
555 fbsd_siginfo_size ()
557 #ifdef __LP64__
558 struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
560 /* Is the inferior 32-bit? If so, use the 32-bit siginfo size. */
561 if (gdbarch_long_bit (gdbarch) == 32)
562 return sizeof (struct siginfo32);
563 #endif
564 return sizeof (siginfo_t);
567 /* Convert a native 64-bit siginfo object to a 32-bit object. Note
568 that FreeBSD doesn't support writing to $_siginfo, so this only
569 needs to convert one way. */
571 static void
572 fbsd_convert_siginfo (siginfo_t *si)
574 #ifdef __LP64__
575 struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
577 /* Is the inferior 32-bit? If not, nothing to do. */
578 if (gdbarch_long_bit (gdbarch) != 32)
579 return;
581 struct siginfo32 si32;
583 si32.si_signo = si->si_signo;
584 si32.si_errno = si->si_errno;
585 si32.si_code = si->si_code;
586 si32.si_pid = si->si_pid;
587 si32.si_uid = si->si_uid;
588 si32.si_status = si->si_status;
589 si32.si_addr = (uintptr_t) si->si_addr;
591 /* If sival_ptr is being used instead of sival_int on a big-endian
592 platform, then sival_int will be zero since it holds the upper
593 32-bits of the pointer value. */
594 #if _BYTE_ORDER == _BIG_ENDIAN
595 if (si->si_value.sival_int == 0)
596 si32.si_value.sival_ptr = (uintptr_t) si->si_value.sival_ptr;
597 else
598 si32.si_value.sival_int = si->si_value.sival_int;
599 #else
600 si32.si_value.sival_int = si->si_value.sival_int;
601 #endif
603 /* Always copy the spare fields and then possibly overwrite them for
604 signal-specific or code-specific fields. */
605 si32._reason.__spare__.__spare1__ = si->_reason.__spare__.__spare1__;
606 for (int i = 0; i < 7; i++)
607 si32._reason.__spare__.__spare2__[i] = si->_reason.__spare__.__spare2__[i];
608 switch (si->si_signo) {
609 case SIGILL:
610 case SIGFPE:
611 case SIGSEGV:
612 case SIGBUS:
613 si32.si_trapno = si->si_trapno;
614 break;
616 switch (si->si_code) {
617 case SI_TIMER:
618 si32.si_timerid = si->si_timerid;
619 si32.si_overrun = si->si_overrun;
620 break;
621 case SI_MESGQ:
622 si32.si_mqd = si->si_mqd;
623 break;
626 memcpy(si, &si32, sizeof (si32));
627 #endif
630 /* Implement the "xfer_partial" target_ops method. */
632 enum target_xfer_status
633 fbsd_nat_target::xfer_partial (enum target_object object,
634 const char *annex, gdb_byte *readbuf,
635 const gdb_byte *writebuf,
636 ULONGEST offset, ULONGEST len,
637 ULONGEST *xfered_len)
639 pid_t pid = inferior_ptid.pid ();
641 switch (object)
643 case TARGET_OBJECT_SIGNAL_INFO:
645 struct ptrace_lwpinfo pl;
646 size_t siginfo_size;
648 /* FreeBSD doesn't support writing to $_siginfo. */
649 if (writebuf != NULL)
650 return TARGET_XFER_E_IO;
652 if (inferior_ptid.lwp_p ())
653 pid = inferior_ptid.lwp ();
655 siginfo_size = fbsd_siginfo_size ();
656 if (offset > siginfo_size)
657 return TARGET_XFER_E_IO;
659 if (ptrace (PT_LWPINFO, pid, (PTRACE_TYPE_ARG3) &pl, sizeof (pl)) == -1)
660 return TARGET_XFER_E_IO;
662 if (!(pl.pl_flags & PL_FLAG_SI))
663 return TARGET_XFER_E_IO;
665 fbsd_convert_siginfo (&pl.pl_siginfo);
666 if (offset + len > siginfo_size)
667 len = siginfo_size - offset;
669 memcpy (readbuf, ((gdb_byte *) &pl.pl_siginfo) + offset, len);
670 *xfered_len = len;
671 return TARGET_XFER_OK;
673 #ifdef KERN_PROC_AUXV
674 case TARGET_OBJECT_AUXV:
676 gdb::byte_vector buf_storage;
677 gdb_byte *buf;
678 size_t buflen;
679 int mib[4];
681 if (writebuf != NULL)
682 return TARGET_XFER_E_IO;
683 mib[0] = CTL_KERN;
684 mib[1] = KERN_PROC;
685 mib[2] = KERN_PROC_AUXV;
686 mib[3] = pid;
687 if (offset == 0)
689 buf = readbuf;
690 buflen = len;
692 else
694 buflen = offset + len;
695 buf_storage.resize (buflen);
696 buf = buf_storage.data ();
698 if (sysctl (mib, 4, buf, &buflen, NULL, 0) == 0)
700 if (offset != 0)
702 if (buflen > offset)
704 buflen -= offset;
705 memcpy (readbuf, buf + offset, buflen);
707 else
708 buflen = 0;
710 *xfered_len = buflen;
711 return (buflen == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
713 return TARGET_XFER_E_IO;
715 #endif
716 #if defined(KERN_PROC_VMMAP) && defined(KERN_PROC_PS_STRINGS)
717 case TARGET_OBJECT_FREEBSD_VMMAP:
718 case TARGET_OBJECT_FREEBSD_PS_STRINGS:
720 gdb::byte_vector buf_storage;
721 gdb_byte *buf;
722 size_t buflen;
723 int mib[4];
725 int proc_target;
726 uint32_t struct_size;
727 switch (object)
729 case TARGET_OBJECT_FREEBSD_VMMAP:
730 proc_target = KERN_PROC_VMMAP;
731 struct_size = sizeof (struct kinfo_vmentry);
732 break;
733 case TARGET_OBJECT_FREEBSD_PS_STRINGS:
734 proc_target = KERN_PROC_PS_STRINGS;
735 struct_size = sizeof (void *);
736 break;
739 if (writebuf != NULL)
740 return TARGET_XFER_E_IO;
742 mib[0] = CTL_KERN;
743 mib[1] = KERN_PROC;
744 mib[2] = proc_target;
745 mib[3] = pid;
747 if (sysctl (mib, 4, NULL, &buflen, NULL, 0) != 0)
748 return TARGET_XFER_E_IO;
749 buflen += sizeof (struct_size);
751 if (offset >= buflen)
753 *xfered_len = 0;
754 return TARGET_XFER_EOF;
757 buf_storage.resize (buflen);
758 buf = buf_storage.data ();
760 memcpy (buf, &struct_size, sizeof (struct_size));
761 buflen -= sizeof (struct_size);
762 if (sysctl (mib, 4, buf + sizeof (struct_size), &buflen, NULL, 0) != 0)
763 return TARGET_XFER_E_IO;
764 buflen += sizeof (struct_size);
766 if (buflen - offset < len)
767 len = buflen - offset;
768 memcpy (readbuf, buf + offset, len);
769 *xfered_len = len;
770 return TARGET_XFER_OK;
772 #endif
773 default:
774 return inf_ptrace_target::xfer_partial (object, annex,
775 readbuf, writebuf, offset,
776 len, xfered_len);
780 static bool debug_fbsd_lwp;
781 static bool debug_fbsd_nat;
783 static void
784 show_fbsd_lwp_debug (struct ui_file *file, int from_tty,
785 struct cmd_list_element *c, const char *value)
787 gdb_printf (file, _("Debugging of FreeBSD lwp module is %s.\n"), value);
790 static void
791 show_fbsd_nat_debug (struct ui_file *file, int from_tty,
792 struct cmd_list_element *c, const char *value)
794 gdb_printf (file, _("Debugging of FreeBSD native target is %s.\n"),
795 value);
798 #define fbsd_lwp_debug_printf(fmt, ...) \
799 debug_prefixed_printf_cond (debug_fbsd_lwp, "fbsd-lwp", fmt, ##__VA_ARGS__)
801 #define fbsd_nat_debug_printf(fmt, ...) \
802 debug_prefixed_printf_cond (debug_fbsd_nat, "fbsd-nat", fmt, ##__VA_ARGS__)
804 #define fbsd_nat_debug_start_end(fmt, ...) \
805 scoped_debug_start_end (debug_fbsd_nat, "fbsd-nat", fmt, ##__VA_ARGS__)
808 FreeBSD's first thread support was via a "reentrant" version of libc
809 (libc_r) that first shipped in 2.2.7. This library multiplexed all
810 of the threads in a process onto a single kernel thread. This
811 library was supported via the bsd-uthread target.
813 FreeBSD 5.1 introduced two new threading libraries that made use of
814 multiple kernel threads. The first (libkse) scheduled M user
815 threads onto N (<= M) kernel threads (LWPs). The second (libthr)
816 bound each user thread to a dedicated kernel thread. libkse shipped
817 as the default threading library (libpthread).
819 FreeBSD 5.3 added a libthread_db to abstract the interface across
820 the various thread libraries (libc_r, libkse, and libthr).
822 FreeBSD 7.0 switched the default threading library from from libkse
823 to libpthread and removed libc_r.
825 FreeBSD 8.0 removed libkse and the in-kernel support for it. The
826 only threading library supported by 8.0 and later is libthr which
827 ties each user thread directly to an LWP. To simplify the
828 implementation, this target only supports LWP-backed threads using
829 ptrace directly rather than libthread_db.
831 FreeBSD 11.0 introduced LWP event reporting via PT_LWP_EVENTS.
834 /* Return true if PTID is still active in the inferior. */
836 bool
837 fbsd_nat_target::thread_alive (ptid_t ptid)
839 if (ptid.lwp_p ())
841 struct ptrace_lwpinfo pl;
843 if (ptrace (PT_LWPINFO, ptid.lwp (), (caddr_t) &pl, sizeof pl)
844 == -1)
846 /* EBUSY means the associated process is running which means
847 the LWP does exist and belongs to a running process. */
848 if (errno == EBUSY)
849 return true;
850 return false;
852 #ifdef PL_FLAG_EXITED
853 if (pl.pl_flags & PL_FLAG_EXITED)
854 return false;
855 #endif
858 return true;
861 /* Convert PTID to a string. */
863 std::string
864 fbsd_nat_target::pid_to_str (ptid_t ptid)
866 lwpid_t lwp;
868 lwp = ptid.lwp ();
869 if (lwp != 0)
871 int pid = ptid.pid ();
873 return string_printf ("LWP %d of process %d", lwp, pid);
876 return normal_pid_to_str (ptid);
879 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_TDNAME
880 /* Return the name assigned to a thread by an application. Returns
881 the string in a static buffer. */
883 const char *
884 fbsd_nat_target::thread_name (struct thread_info *thr)
886 struct ptrace_lwpinfo pl;
887 struct kinfo_proc kp;
888 int pid = thr->ptid.pid ();
889 long lwp = thr->ptid.lwp ();
890 static char buf[sizeof pl.pl_tdname + 1];
892 /* Note that ptrace_lwpinfo returns the process command in pl_tdname
893 if a name has not been set explicitly. Return a NULL name in
894 that case. */
895 if (!fbsd_fetch_kinfo_proc (pid, &kp))
896 return nullptr;
897 if (ptrace (PT_LWPINFO, lwp, (caddr_t) &pl, sizeof pl) == -1)
898 return nullptr;
899 if (strcmp (kp.ki_comm, pl.pl_tdname) == 0)
900 return NULL;
901 xsnprintf (buf, sizeof buf, "%s", pl.pl_tdname);
902 return buf;
904 #endif
906 /* Enable additional event reporting on new processes.
908 To catch fork events, PTRACE_FORK is set on every traced process
909 to enable stops on returns from fork or vfork. Note that both the
910 parent and child will always stop, even if system call stops are
911 not enabled.
913 To catch LWP events, PTRACE_EVENTS is set on every traced process.
914 This enables stops on the birth for new LWPs (excluding the "main" LWP)
915 and the death of LWPs (excluding the last LWP in a process). Note
916 that unlike fork events, the LWP that creates a new LWP does not
917 report an event. */
919 static void
920 fbsd_enable_proc_events (pid_t pid)
922 #ifdef PT_GET_EVENT_MASK
923 int events;
925 if (ptrace (PT_GET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3) &events,
926 sizeof (events)) == -1)
927 perror_with_name (("ptrace (PT_GET_EVENT_MASK)"));
928 events |= PTRACE_FORK | PTRACE_LWP;
929 #ifdef PTRACE_VFORK
930 events |= PTRACE_VFORK;
931 #endif
932 if (ptrace (PT_SET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3) &events,
933 sizeof (events)) == -1)
934 perror_with_name (("ptrace (PT_SET_EVENT_MASK)"));
935 #else
936 #ifdef TDP_RFPPWAIT
937 if (ptrace (PT_FOLLOW_FORK, pid, (PTRACE_TYPE_ARG3) 0, 1) == -1)
938 perror_with_name (("ptrace (PT_FOLLOW_FORK)"));
939 #endif
940 #ifdef PT_LWP_EVENTS
941 if (ptrace (PT_LWP_EVENTS, pid, (PTRACE_TYPE_ARG3) 0, 1) == -1)
942 perror_with_name (("ptrace (PT_LWP_EVENTS)"));
943 #endif
944 #endif
947 /* Add threads for any new LWPs in a process.
949 When LWP events are used, this function is only used to detect existing
950 threads when attaching to a process. On older systems, this function is
951 called to discover new threads each time the thread list is updated. */
953 static void
954 fbsd_add_threads (fbsd_nat_target *target, pid_t pid)
956 int i, nlwps;
958 gdb_assert (!in_thread_list (target, ptid_t (pid)));
959 nlwps = ptrace (PT_GETNUMLWPS, pid, NULL, 0);
960 if (nlwps == -1)
961 perror_with_name (("ptrace (PT_GETNUMLWPS)"));
963 gdb::unique_xmalloc_ptr<lwpid_t[]> lwps (XCNEWVEC (lwpid_t, nlwps));
965 nlwps = ptrace (PT_GETLWPLIST, pid, (caddr_t) lwps.get (), nlwps);
966 if (nlwps == -1)
967 perror_with_name (("ptrace (PT_GETLWPLIST)"));
969 inferior *inf = find_inferior_ptid (target, ptid_t (pid));
970 fbsd_inferior *fbsd_inf = get_fbsd_inferior (inf);
971 gdb_assert (fbsd_inf != nullptr);
972 for (i = 0; i < nlwps; i++)
974 ptid_t ptid = ptid_t (pid, lwps[i]);
976 if (!in_thread_list (target, ptid))
978 #ifdef PT_LWP_EVENTS
979 struct ptrace_lwpinfo pl;
981 /* Don't add exited threads. Note that this is only called
982 when attaching to a multi-threaded process. */
983 if (ptrace (PT_LWPINFO, lwps[i], (caddr_t) &pl, sizeof pl) == -1)
984 perror_with_name (("ptrace (PT_LWPINFO)"));
985 if (pl.pl_flags & PL_FLAG_EXITED)
986 continue;
987 #endif
988 fbsd_lwp_debug_printf ("adding thread for LWP %u", lwps[i]);
989 add_thread (target, ptid);
990 #ifdef PT_LWP_EVENTS
991 fbsd_inf->num_lwps++;
992 #endif
995 #ifndef PT_LWP_EVENTS
996 fbsd_inf->num_lwps = nlwps;
997 #endif
1000 /* Implement the "update_thread_list" target_ops method. */
1002 void
1003 fbsd_nat_target::update_thread_list ()
1005 #ifdef PT_LWP_EVENTS
1006 /* With support for thread events, threads are added/deleted from the
1007 list as events are reported, so just try deleting exited threads. */
1008 delete_exited_threads ();
1009 #else
1010 prune_threads ();
1012 fbsd_add_threads (this, inferior_ptid.pid ());
1013 #endif
1016 /* Async mode support. */
1018 /* Implement the "can_async_p" target method. */
1020 bool
1021 fbsd_nat_target::can_async_p ()
1023 /* This flag should be checked in the common target.c code. */
1024 gdb_assert (target_async_permitted);
1026 /* Otherwise, this targets is always able to support async mode. */
1027 return true;
1030 /* SIGCHLD handler notifies the event-loop in async mode. */
1032 static void
1033 sigchld_handler (int signo)
1035 int old_errno = errno;
1037 fbsd_nat_target::async_file_mark_if_open ();
1039 errno = old_errno;
1042 /* Callback registered with the target events file descriptor. */
1044 static void
1045 handle_target_event (int error, gdb_client_data client_data)
1047 inferior_event_handler (INF_REG_EVENT);
1050 /* Implement the "async" target method. */
1052 void
1053 fbsd_nat_target::async (bool enable)
1055 if (enable == is_async_p ())
1056 return;
1058 /* Block SIGCHILD while we create/destroy the pipe, as the handler
1059 writes to it. */
1060 gdb::block_signals blocker;
1062 if (enable)
1064 if (!async_file_open ())
1065 internal_error ("failed to create event pipe.");
1067 add_file_handler (async_wait_fd (), handle_target_event, NULL, "fbsd-nat");
1069 /* Trigger a poll in case there are pending events to
1070 handle. */
1071 async_file_mark ();
1073 else
1075 delete_file_handler (async_wait_fd ());
1076 async_file_close ();
1080 #ifdef TDP_RFPPWAIT
1082 To catch fork events, PT_FOLLOW_FORK is set on every traced process
1083 to enable stops on returns from fork or vfork. Note that both the
1084 parent and child will always stop, even if system call stops are not
1085 enabled.
1087 After a fork, both the child and parent process will stop and report
1088 an event. However, there is no guarantee of order. If the parent
1089 reports its stop first, then fbsd_wait explicitly waits for the new
1090 child before returning. If the child reports its stop first, then
1091 the event is saved on a list and ignored until the parent's stop is
1092 reported. fbsd_wait could have been changed to fetch the parent PID
1093 of the new child and used that to wait for the parent explicitly.
1094 However, if two threads in the parent fork at the same time, then
1095 the wait on the parent might return the "wrong" fork event.
1097 The initial version of PT_FOLLOW_FORK did not set PL_FLAG_CHILD for
1098 the new child process. This flag could be inferred by treating any
1099 events for an unknown pid as a new child.
1101 In addition, the initial version of PT_FOLLOW_FORK did not report a
1102 stop event for the parent process of a vfork until after the child
1103 process executed a new program or exited. The kernel was changed to
1104 defer the wait for exit or exec of the child until after posting the
1105 stop event shortly after the change to introduce PL_FLAG_CHILD.
1106 This could be worked around by reporting a vfork event when the
1107 child event posted and ignoring the subsequent event from the
1108 parent.
1110 This implementation requires both of these fixes for simplicity's
1111 sake. FreeBSD versions newer than 9.1 contain both fixes.
1114 static std::list<ptid_t> fbsd_pending_children;
1116 /* Record a new child process event that is reported before the
1117 corresponding fork event in the parent. */
1119 static void
1120 fbsd_remember_child (ptid_t pid)
1122 fbsd_pending_children.push_front (pid);
1125 /* Check for a previously-recorded new child process event for PID.
1126 If one is found, remove it from the list and return the PTID. */
1128 static ptid_t
1129 fbsd_is_child_pending (pid_t pid)
1131 for (auto it = fbsd_pending_children.begin ();
1132 it != fbsd_pending_children.end (); it++)
1133 if (it->pid () == pid)
1135 ptid_t ptid = *it;
1136 fbsd_pending_children.erase (it);
1137 return ptid;
1139 return null_ptid;
1142 /* Wait for a child of a fork to report its stop. Returns the PTID of
1143 the new child process. */
1145 static ptid_t
1146 fbsd_wait_for_fork_child (pid_t pid)
1148 ptid_t ptid = fbsd_is_child_pending (pid);
1149 if (ptid != null_ptid)
1150 return ptid;
1152 int status;
1153 pid_t wpid = waitpid (pid, &status, 0);
1154 if (wpid == -1)
1155 perror_with_name (("waitpid"));
1157 gdb_assert (wpid == pid);
1159 struct ptrace_lwpinfo pl;
1160 if (ptrace (PT_LWPINFO, wpid, (caddr_t) &pl, sizeof pl) == -1)
1161 perror_with_name (("ptrace (PT_LWPINFO)"));
1163 gdb_assert (pl.pl_flags & PL_FLAG_CHILD);
1164 return ptid_t (wpid, pl.pl_lwpid);
1167 #ifndef PTRACE_VFORK
1168 /* Record a pending vfork done event. */
1170 static void
1171 fbsd_add_vfork_done (ptid_t pid)
1173 add_pending_event (ptid, target_waitstatus ().set_vfork_done ());
1175 /* If we're in async mode, need to tell the event loop there's
1176 something here to process. */
1177 if (target_is_async_p ())
1178 async_file_mark ();
1180 #endif
1181 #endif
1183 /* Resume a single process. */
1185 void
1186 fbsd_nat_target::resume_one_process (ptid_t ptid, int step,
1187 enum gdb_signal signo)
1189 fbsd_nat_debug_printf ("[%s], step %d, signo %d (%s)",
1190 target_pid_to_str (ptid).c_str (), step, signo,
1191 gdb_signal_to_name (signo));
1193 inferior *inf = find_inferior_ptid (this, ptid);
1194 fbsd_inferior *fbsd_inf = get_fbsd_inferior (inf);
1195 fbsd_inf->resumed_lwps = ptid;
1196 gdb_assert (fbsd_inf->running_lwps == 0);
1198 /* Don't PT_CONTINUE a thread or process which has a pending event. */
1199 if (have_pending_event (ptid))
1201 fbsd_nat_debug_printf ("found pending event");
1202 return;
1205 for (thread_info *tp : inf->non_exited_threads ())
1207 /* If ptid is a specific LWP, suspend all other LWPs in the
1208 process, otherwise resume all LWPs in the process.. */
1209 if (!ptid.lwp_p() || tp->ptid.lwp () == ptid.lwp ())
1211 if (ptrace (PT_RESUME, tp->ptid.lwp (), NULL, 0) == -1)
1212 perror_with_name (("ptrace (PT_RESUME)"));
1213 low_prepare_to_resume (tp);
1214 fbsd_inf->running_lwps++;
1216 else
1218 if (ptrace (PT_SUSPEND, tp->ptid.lwp (), NULL, 0) == -1)
1219 perror_with_name (("ptrace (PT_SUSPEND)"));
1223 if (ptid.pid () != inferior_ptid.pid ())
1225 step = 0;
1226 signo = GDB_SIGNAL_0;
1227 gdb_assert (!ptid.lwp_p ());
1229 else
1231 ptid = inferior_ptid;
1232 #if __FreeBSD_version < 1200052
1233 /* When multiple threads within a process wish to report STOPPED
1234 events from wait(), the kernel picks one thread event as the
1235 thread event to report. The chosen thread event is retrieved
1236 via PT_LWPINFO by passing the process ID as the request pid.
1237 If multiple events are pending, then the subsequent wait()
1238 after resuming a process will report another STOPPED event
1239 after resuming the process to handle the next thread event
1240 and so on.
1242 A single thread event is cleared as a side effect of resuming
1243 the process with PT_CONTINUE, PT_STEP, etc. In older
1244 kernels, however, the request pid was used to select which
1245 thread's event was cleared rather than always clearing the
1246 event that was just reported. To avoid clearing the event of
1247 the wrong LWP, always pass the process ID instead of an LWP
1248 ID to PT_CONTINUE or PT_SYSCALL.
1250 In the case of stepping, the process ID cannot be used with
1251 PT_STEP since it would step the thread that reported an event
1252 which may not be the thread indicated by PTID. For stepping,
1253 use PT_SETSTEP to enable stepping on the desired thread
1254 before resuming the process via PT_CONTINUE instead of using
1255 PT_STEP. */
1256 if (step)
1258 if (ptrace (PT_SETSTEP, get_ptrace_pid (ptid), NULL, 0) == -1)
1259 perror_with_name (("ptrace (PT_SETSTEP)"));
1260 step = 0;
1262 ptid = ptid_t (ptid.pid ());
1263 #endif
1266 inf_ptrace_target::resume (ptid, step, signo);
1269 /* Implement the "resume" target_ops method. */
1271 void
1272 fbsd_nat_target::resume (ptid_t scope_ptid, int step, enum gdb_signal signo)
1274 fbsd_nat_debug_start_end ("[%s], step %d, signo %d (%s)",
1275 target_pid_to_str (scope_ptid).c_str (), step, signo,
1276 gdb_signal_to_name (signo));
1278 gdb_assert (inferior_ptid.matches (scope_ptid));
1279 gdb_assert (!scope_ptid.tid_p ());
1281 if (scope_ptid == minus_one_ptid)
1283 for (inferior *inf : all_non_exited_inferiors (this))
1284 resume_one_process (ptid_t (inf->pid), step, signo);
1286 else
1288 resume_one_process (scope_ptid, step, signo);
1292 #ifdef USE_SIGTRAP_SIGINFO
1293 /* Handle breakpoint and trace traps reported via SIGTRAP. If the
1294 trap was a breakpoint or trace trap that should be reported to the
1295 core, return true. */
1297 static bool
1298 fbsd_handle_debug_trap (fbsd_nat_target *target, ptid_t ptid,
1299 const struct ptrace_lwpinfo &pl)
1302 /* Ignore traps without valid siginfo or for signals other than
1303 SIGTRAP.
1305 FreeBSD kernels prior to r341800 can return stale siginfo for at
1306 least some events, but those events can be identified by
1307 additional flags set in pl_flags. True breakpoint and
1308 single-step traps should not have other flags set in
1309 pl_flags. */
1310 if (pl.pl_flags != PL_FLAG_SI || pl.pl_siginfo.si_signo != SIGTRAP)
1311 return false;
1313 /* Trace traps are either a single step or a hardware watchpoint or
1314 breakpoint. */
1315 if (pl.pl_siginfo.si_code == TRAP_TRACE)
1317 fbsd_nat_debug_printf ("trace trap for LWP %ld", ptid.lwp ());
1318 return true;
1321 if (pl.pl_siginfo.si_code == TRAP_BRKPT)
1323 /* Fixup PC for the software breakpoint. */
1324 struct regcache *regcache = get_thread_regcache (target, ptid);
1325 struct gdbarch *gdbarch = regcache->arch ();
1326 int decr_pc = gdbarch_decr_pc_after_break (gdbarch);
1328 fbsd_nat_debug_printf ("sw breakpoint trap for LWP %ld", ptid.lwp ());
1329 if (decr_pc != 0)
1331 CORE_ADDR pc;
1333 pc = regcache_read_pc (regcache);
1334 regcache_write_pc (regcache, pc - decr_pc);
1336 return true;
1339 return false;
1341 #endif
1343 /* Wait for the child specified by PTID to do something. Return the
1344 process ID of the child, or MINUS_ONE_PTID in case of error; store
1345 the status in *OURSTATUS. */
1347 ptid_t
1348 fbsd_nat_target::wait_1 (ptid_t ptid, struct target_waitstatus *ourstatus,
1349 target_wait_flags target_options)
1351 ptid_t wptid;
1353 while (1)
1355 wptid = inf_ptrace_target::wait (ptid, ourstatus, target_options);
1356 if (ourstatus->kind () == TARGET_WAITKIND_STOPPED)
1358 struct ptrace_lwpinfo pl;
1359 pid_t pid = wptid.pid ();
1360 if (ptrace (PT_LWPINFO, pid, (caddr_t) &pl, sizeof pl) == -1)
1361 perror_with_name (("ptrace (PT_LWPINFO)"));
1363 wptid = ptid_t (pid, pl.pl_lwpid);
1365 if (debug_fbsd_nat)
1367 fbsd_nat_debug_printf ("stop for LWP %u event %d flags %#x",
1368 pl.pl_lwpid, pl.pl_event, pl.pl_flags);
1369 if (pl.pl_flags & PL_FLAG_SI)
1370 fbsd_nat_debug_printf ("si_signo %u si_code %u",
1371 pl.pl_siginfo.si_signo,
1372 pl.pl_siginfo.si_code);
1375 /* There may not be an inferior for this pid if this is a
1376 PL_FLAG_CHILD event. */
1377 inferior *inf = find_inferior_ptid (this, wptid);
1378 fbsd_inferior *fbsd_inf = inf == nullptr ? nullptr
1379 : get_fbsd_inferior (inf);
1380 gdb_assert (fbsd_inf != nullptr || pl.pl_flags & PL_FLAG_CHILD);
1382 #ifdef PT_LWP_EVENTS
1383 if (pl.pl_flags & PL_FLAG_EXITED)
1385 /* If GDB attaches to a multi-threaded process, exiting
1386 threads might be skipped during post_attach that
1387 have not yet reported their PL_FLAG_EXITED event.
1388 Ignore EXITED events for an unknown LWP. */
1389 thread_info *thr = this->find_thread (wptid);
1390 if (thr != nullptr)
1392 fbsd_lwp_debug_printf ("deleting thread for LWP %u",
1393 pl.pl_lwpid);
1394 low_delete_thread (thr);
1395 delete_thread (thr);
1396 fbsd_inf->num_lwps--;
1398 /* If this LWP was the only resumed LWP from the
1399 process, report an event to the core. */
1400 if (wptid == fbsd_inf->resumed_lwps)
1402 ourstatus->set_spurious ();
1403 return wptid;
1406 /* During process exit LWPs that were not resumed
1407 will report exit events. */
1408 if (wptid.matches (fbsd_inf->resumed_lwps))
1409 fbsd_inf->running_lwps--;
1411 if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1412 perror_with_name (("ptrace (PT_CONTINUE)"));
1413 continue;
1415 #endif
1417 /* Switch to an LWP PTID on the first stop in a new process.
1418 This is done after handling PL_FLAG_EXITED to avoid
1419 switching to an exited LWP. It is done before checking
1420 PL_FLAG_BORN in case the first stop reported after
1421 attaching to an existing process is a PL_FLAG_BORN
1422 event. */
1423 if (in_thread_list (this, ptid_t (pid)))
1425 fbsd_lwp_debug_printf ("using LWP %u for first thread",
1426 pl.pl_lwpid);
1427 thread_change_ptid (this, ptid_t (pid), wptid);
1430 #ifdef PT_LWP_EVENTS
1431 if (pl.pl_flags & PL_FLAG_BORN)
1433 /* If GDB attaches to a multi-threaded process, newborn
1434 threads might be added by fbsd_add_threads that have
1435 not yet reported their PL_FLAG_BORN event. Ignore
1436 BORN events for an already-known LWP. */
1437 if (!in_thread_list (this, wptid))
1439 fbsd_lwp_debug_printf ("adding thread for LWP %u",
1440 pl.pl_lwpid);
1441 add_thread (this, wptid);
1442 fbsd_inf->num_lwps++;
1444 if (wptid.matches(fbsd_inf->resumed_lwps))
1445 fbsd_inf->running_lwps++;
1447 ourstatus->set_spurious ();
1448 return wptid;
1450 #endif
1452 #ifdef TDP_RFPPWAIT
1453 if (pl.pl_flags & PL_FLAG_FORKED)
1455 #ifndef PTRACE_VFORK
1456 struct kinfo_proc kp;
1457 #endif
1458 bool is_vfork = false;
1459 ptid_t child_ptid;
1460 pid_t child;
1462 child = pl.pl_child_pid;
1463 #ifdef PTRACE_VFORK
1464 if (pl.pl_flags & PL_FLAG_VFORKED)
1465 is_vfork = true;
1466 #endif
1468 /* Make sure the other end of the fork is stopped too. */
1469 child_ptid = fbsd_wait_for_fork_child (child);
1471 /* Enable additional events on the child process. */
1472 fbsd_enable_proc_events (child_ptid.pid ());
1474 #ifndef PTRACE_VFORK
1475 /* For vfork, the child process will have the P_PPWAIT
1476 flag set. */
1477 if (fbsd_fetch_kinfo_proc (child, &kp))
1479 if (kp.ki_flag & P_PPWAIT)
1480 is_vfork = true;
1482 else
1483 warning (_("Failed to fetch process information"));
1484 #endif
1486 low_new_fork (wptid, child);
1488 if (is_vfork)
1489 ourstatus->set_vforked (child_ptid);
1490 else
1491 ourstatus->set_forked (child_ptid);
1493 return wptid;
1496 if (pl.pl_flags & PL_FLAG_CHILD)
1498 /* Remember that this child forked, but do not report it
1499 until the parent reports its corresponding fork
1500 event. */
1501 fbsd_remember_child (wptid);
1502 continue;
1505 #ifdef PTRACE_VFORK
1506 if (pl.pl_flags & PL_FLAG_VFORK_DONE)
1508 ourstatus->set_vfork_done ();
1509 return wptid;
1511 #endif
1512 #endif
1514 if (pl.pl_flags & PL_FLAG_EXEC)
1516 ourstatus->set_execd
1517 (make_unique_xstrdup (pid_to_exec_file (pid)));
1518 return wptid;
1521 #ifdef USE_SIGTRAP_SIGINFO
1522 if (fbsd_handle_debug_trap (this, wptid, pl))
1523 return wptid;
1524 #endif
1526 /* Note that PL_FLAG_SCE is set for any event reported while
1527 a thread is executing a system call in the kernel. In
1528 particular, signals that interrupt a sleep in a system
1529 call will report this flag as part of their event. Stops
1530 explicitly for system call entry and exit always use
1531 SIGTRAP, so only treat SIGTRAP events as system call
1532 entry/exit events. */
1533 if (pl.pl_flags & (PL_FLAG_SCE | PL_FLAG_SCX)
1534 && ourstatus->sig () == GDB_SIGNAL_TRAP)
1536 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1537 if (catch_syscall_enabled ())
1539 if (catching_syscall_number (pl.pl_syscall_code))
1541 if (pl.pl_flags & PL_FLAG_SCE)
1542 ourstatus->set_syscall_entry (pl.pl_syscall_code);
1543 else
1544 ourstatus->set_syscall_return (pl.pl_syscall_code);
1546 return wptid;
1549 #endif
1550 /* If the core isn't interested in this event, just
1551 continue the process explicitly and wait for another
1552 event. Note that PT_SYSCALL is "sticky" on FreeBSD
1553 and once system call stops are enabled on a process
1554 it stops for all system call entries and exits. */
1555 if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1556 perror_with_name (("ptrace (PT_CONTINUE)"));
1557 continue;
1560 /* If this is a pending SIGSTOP event from an earlier call
1561 to stop_process, discard the event and wait for another
1562 event. */
1563 if (ourstatus->sig () == GDB_SIGNAL_STOP && fbsd_inf->pending_sigstop)
1565 fbsd_nat_debug_printf ("ignoring SIGSTOP for pid %u", pid);
1566 fbsd_inf->pending_sigstop = false;
1567 if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1568 perror_with_name (("ptrace (PT_CONTINUE)"));
1569 continue;
1572 else
1573 fbsd_nat_debug_printf ("event [%s], [%s]",
1574 target_pid_to_str (wptid).c_str (),
1575 ourstatus->to_string ().c_str ());
1576 return wptid;
1580 /* Stop a given process. If the process is already stopped, record
1581 its pending event instead. */
1583 void
1584 fbsd_nat_target::stop_process (inferior *inf)
1586 fbsd_inferior *fbsd_inf = get_fbsd_inferior (inf);
1587 gdb_assert (fbsd_inf != nullptr);
1589 fbsd_inf->resumed_lwps = null_ptid;
1590 if (fbsd_inf->running_lwps == 0)
1591 return;
1593 ptid_t ptid (inf->pid);
1594 target_waitstatus status;
1595 ptid_t wptid = wait_1 (ptid, &status, TARGET_WNOHANG);
1597 if (wptid != minus_one_ptid)
1599 /* Save the current event as a pending event. */
1600 add_pending_event (wptid, status);
1601 fbsd_inf->running_lwps = 0;
1602 return;
1605 /* If a SIGSTOP is already pending, don't send a new one, but tell
1606 wait_1 to report a SIGSTOP. */
1607 if (fbsd_inf->pending_sigstop)
1609 fbsd_nat_debug_printf ("waiting for existing pending SIGSTOP for %u",
1610 inf->pid);
1611 fbsd_inf->pending_sigstop = false;
1613 else
1615 /* Ignore errors from kill as process exit might race with kill. */
1616 fbsd_nat_debug_printf ("killing %u with SIGSTOP", inf->pid);
1617 ::kill (inf->pid, SIGSTOP);
1620 /* Wait for SIGSTOP (or some other event) to be reported. */
1621 wptid = wait_1 (ptid, &status, 0);
1623 switch (status.kind ())
1625 case TARGET_WAITKIND_EXITED:
1626 case TARGET_WAITKIND_SIGNALLED:
1627 /* If the process has exited, we aren't going to get an
1628 event for the SIGSTOP. Save the current event and
1629 return. */
1630 add_pending_event (wptid, status);
1631 break;
1632 case TARGET_WAITKIND_IGNORE:
1633 /* wait() failed with ECHILD meaning the process no longer
1634 exists. This means a bug happened elsewhere, but at least
1635 the process is no longer running. */
1636 break;
1637 case TARGET_WAITKIND_STOPPED:
1638 /* If this is the SIGSTOP event, discard it and return
1639 leaving the process stopped. */
1640 if (status.sig () == GDB_SIGNAL_STOP)
1641 break;
1643 [[fallthrough]];
1644 default:
1645 /* Some other event has occurred. Save the current
1646 event. */
1647 add_pending_event (wptid, status);
1649 /* Ignore the next SIGSTOP for this process. */
1650 fbsd_nat_debug_printf ("ignoring next SIGSTOP for %u", inf->pid);
1651 fbsd_inf->pending_sigstop = true;
1652 break;
1654 fbsd_inf->running_lwps = 0;
1657 ptid_t
1658 fbsd_nat_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
1659 target_wait_flags target_options)
1661 fbsd_nat_debug_printf ("[%s], [%s]", target_pid_to_str (ptid).c_str (),
1662 target_options_to_string (target_options).c_str ());
1664 /* If there is a valid pending event, return it. */
1665 std::optional<pending_event> event = take_pending_event (ptid);
1666 if (event.has_value ())
1668 /* Stop any other inferiors currently running. */
1669 for (inferior *inf : all_non_exited_inferiors (this))
1670 stop_process (inf);
1672 fbsd_nat_debug_printf ("returning pending event [%s], [%s]",
1673 target_pid_to_str (event->ptid).c_str (),
1674 event->status.to_string ().c_str ());
1675 gdb_assert (event->ptid.matches (ptid));
1676 *ourstatus = event->status;
1677 return event->ptid;
1680 /* Ensure any subsequent events trigger a new event in the loop. */
1681 if (is_async_p ())
1682 async_file_flush ();
1684 ptid_t wptid;
1685 while (1)
1687 wptid = wait_1 (ptid, ourstatus, target_options);
1689 /* If no event was found, just return. */
1690 if (ourstatus->kind () == TARGET_WAITKIND_IGNORE
1691 || ourstatus->kind () == TARGET_WAITKIND_NO_RESUMED)
1692 break;
1694 inferior *winf = find_inferior_ptid (this, wptid);
1695 gdb_assert (winf != nullptr);
1696 fbsd_inferior *fbsd_inf = get_fbsd_inferior (winf);
1697 gdb_assert (fbsd_inf != nullptr);
1698 gdb_assert (fbsd_inf->resumed_lwps != null_ptid);
1699 gdb_assert (fbsd_inf->running_lwps > 0);
1701 /* If an event is reported for a thread or process while
1702 stepping some other thread, suspend the thread reporting the
1703 event and defer the event until it can be reported to the
1704 core. */
1705 if (!wptid.matches (fbsd_inf->resumed_lwps))
1707 add_pending_event (wptid, *ourstatus);
1708 fbsd_nat_debug_printf ("deferring event [%s], [%s]",
1709 target_pid_to_str (wptid).c_str (),
1710 ourstatus->to_string ().c_str ());
1711 if (ptrace (PT_SUSPEND, wptid.lwp (), NULL, 0) == -1)
1712 perror_with_name (("ptrace (PT_SUSPEND)"));
1713 if (ptrace (PT_CONTINUE, wptid.pid (), (caddr_t) 1, 0) == -1)
1714 perror_with_name (("ptrace (PT_CONTINUE)"));
1715 continue;
1718 /* This process is no longer running. */
1719 fbsd_inf->resumed_lwps = null_ptid;
1720 fbsd_inf->running_lwps = 0;
1722 /* Stop any other inferiors currently running. */
1723 for (inferior *inf : all_non_exited_inferiors (this))
1724 stop_process (inf);
1726 break;
1729 /* If we are in async mode and found an event, there may still be
1730 another event pending. Trigger the event pipe so that that the
1731 event loop keeps polling until no event is returned. */
1732 if (is_async_p ()
1733 && ((ourstatus->kind () != TARGET_WAITKIND_IGNORE
1734 && ourstatus->kind () != TARGET_WAITKIND_NO_RESUMED)
1735 || ptid != minus_one_ptid))
1736 async_file_mark ();
1738 fbsd_nat_debug_printf ("returning [%s], [%s]",
1739 target_pid_to_str (wptid).c_str (),
1740 ourstatus->to_string ().c_str ());
1741 return wptid;
1744 #ifdef USE_SIGTRAP_SIGINFO
1745 /* Implement the "stopped_by_sw_breakpoint" target_ops method. */
1747 bool
1748 fbsd_nat_target::stopped_by_sw_breakpoint ()
1750 struct ptrace_lwpinfo pl;
1752 if (ptrace (PT_LWPINFO, get_ptrace_pid (inferior_ptid), (caddr_t) &pl,
1753 sizeof pl) == -1)
1754 return false;
1756 return (pl.pl_flags == PL_FLAG_SI
1757 && pl.pl_siginfo.si_signo == SIGTRAP
1758 && pl.pl_siginfo.si_code == TRAP_BRKPT);
1761 /* Implement the "supports_stopped_by_sw_breakpoint" target_ops
1762 method. */
1764 bool
1765 fbsd_nat_target::supports_stopped_by_sw_breakpoint ()
1767 return true;
1769 #endif
1771 #ifdef PROC_ASLR_CTL
1772 class maybe_disable_address_space_randomization
1774 public:
1775 explicit maybe_disable_address_space_randomization (bool disable_randomization)
1777 if (disable_randomization)
1779 if (procctl (P_PID, getpid (), PROC_ASLR_STATUS, &m_aslr_ctl) == -1)
1781 warning (_("Failed to fetch current address space randomization "
1782 "status: %s"), safe_strerror (errno));
1783 return;
1786 m_aslr_ctl &= ~PROC_ASLR_ACTIVE;
1787 if (m_aslr_ctl == PROC_ASLR_FORCE_DISABLE)
1788 return;
1790 int ctl = PROC_ASLR_FORCE_DISABLE;
1791 if (procctl (P_PID, getpid (), PROC_ASLR_CTL, &ctl) == -1)
1793 warning (_("Error disabling address space randomization: %s"),
1794 safe_strerror (errno));
1795 return;
1798 m_aslr_ctl_set = true;
1802 ~maybe_disable_address_space_randomization ()
1804 if (m_aslr_ctl_set)
1806 if (procctl (P_PID, getpid (), PROC_ASLR_CTL, &m_aslr_ctl) == -1)
1807 warning (_("Error restoring address space randomization: %s"),
1808 safe_strerror (errno));
1812 DISABLE_COPY_AND_ASSIGN (maybe_disable_address_space_randomization);
1814 private:
1815 bool m_aslr_ctl_set = false;
1816 int m_aslr_ctl = 0;
1818 #endif
1820 void
1821 fbsd_nat_target::create_inferior (const char *exec_file,
1822 const std::string &allargs,
1823 char **env, int from_tty)
1825 #ifdef PROC_ASLR_CTL
1826 maybe_disable_address_space_randomization restore_aslr_ctl
1827 (disable_randomization);
1828 #endif
1830 fbsd_inferior *fbsd_inf = new fbsd_inferior;
1831 current_inferior ()->priv.reset (fbsd_inf);
1832 fbsd_inf->resumed_lwps = minus_one_ptid;
1833 fbsd_inf->num_lwps = 1;
1834 fbsd_inf->running_lwps = 1;
1835 inf_ptrace_target::create_inferior (exec_file, allargs, env, from_tty);
1838 void
1839 fbsd_nat_target::attach (const char *args, int from_tty)
1841 fbsd_inferior *fbsd_inf = new fbsd_inferior;
1842 current_inferior ()->priv.reset (fbsd_inf);
1843 fbsd_inf->resumed_lwps = minus_one_ptid;
1844 fbsd_inf->num_lwps = 1;
1845 fbsd_inf->running_lwps = 1;
1846 inf_ptrace_target::attach (args, from_tty);
1849 /* If this thread has a pending fork event, there is a child process
1850 GDB is attached to that the core of GDB doesn't know about.
1851 Detach from it. */
1853 void
1854 fbsd_nat_target::detach_fork_children (thread_info *tp)
1856 /* Check in thread_info::pending_waitstatus. */
1857 if (tp->has_pending_waitstatus ())
1859 const target_waitstatus &ws = tp->pending_waitstatus ();
1861 if (ws.kind () == TARGET_WAITKIND_VFORKED
1862 || ws.kind () == TARGET_WAITKIND_FORKED)
1864 pid_t pid = ws.child_ptid ().pid ();
1865 fbsd_nat_debug_printf ("detaching from child %d", pid);
1866 (void) ptrace (PT_DETACH, pid, (caddr_t) 1, 0);
1870 /* Check in thread_info::pending_follow. */
1871 if (tp->pending_follow.kind () == TARGET_WAITKIND_VFORKED
1872 || tp->pending_follow.kind () == TARGET_WAITKIND_FORKED)
1874 pid_t pid = tp->pending_follow.child_ptid ().pid ();
1875 fbsd_nat_debug_printf ("detaching from child %d", pid);
1876 (void) ptrace (PT_DETACH, pid, (caddr_t) 1, 0);
1880 /* Detach from any child processes associated with pending fork events
1881 for a stopped process. Returns true if the process has terminated
1882 and false if it is still alive. */
1884 bool
1885 fbsd_nat_target::detach_fork_children (inferior *inf)
1887 /* Detach any child processes associated with pending fork events in
1888 threads belonging to this process. */
1889 for (thread_info *tp : inf->non_exited_threads ())
1890 detach_fork_children (tp);
1892 /* Unwind state associated with any pending events. Reset
1893 fbsd_inf->resumed_lwps so that take_pending_event will harvest
1894 events. */
1895 fbsd_inferior *fbsd_inf = get_fbsd_inferior (inf);
1896 ptid_t ptid = ptid_t (inf->pid);
1897 fbsd_inf->resumed_lwps = ptid;
1899 while (1)
1901 std::optional<pending_event> event = take_pending_event (ptid);
1902 if (!event.has_value ())
1903 break;
1905 switch (event->status.kind ())
1907 case TARGET_WAITKIND_EXITED:
1908 case TARGET_WAITKIND_SIGNALLED:
1909 return true;
1910 case TARGET_WAITKIND_FORKED:
1911 case TARGET_WAITKIND_VFORKED:
1913 pid_t pid = event->status.child_ptid ().pid ();
1914 fbsd_nat_debug_printf ("detaching from child %d", pid);
1915 (void) ptrace (PT_DETACH, pid, (caddr_t) 1, 0);
1917 break;
1920 return false;
1923 /* Scan all of the threads for a stopped process invoking the supplied
1924 callback on the ptrace_lwpinfo object for threads other than the
1925 thread which reported the current stop. The callback can return
1926 true to terminate the iteration early. This function returns true
1927 if the callback returned true, otherwise it returns false. */
1929 typedef bool (ptrace_event_ftype) (const struct ptrace_lwpinfo &pl);
1931 static bool
1932 iterate_other_ptrace_events (pid_t pid,
1933 gdb::function_view<ptrace_event_ftype> callback)
1935 /* Fetch the LWP ID of the thread that just reported the last stop
1936 and ignore that LWP in the following loop. */
1937 ptrace_lwpinfo pl;
1938 if (ptrace (PT_LWPINFO, pid, (caddr_t) &pl, sizeof (pl)) != 0)
1939 perror_with_name (("ptrace (PT_LWPINFO)"));
1940 lwpid_t lwpid = pl.pl_lwpid;
1942 int nlwps = ptrace (PT_GETNUMLWPS, pid, NULL, 0);
1943 if (nlwps == -1)
1944 perror_with_name (("ptrace (PT_GETLWPLIST)"));
1945 if (nlwps == 1)
1946 return false;
1948 gdb::unique_xmalloc_ptr<lwpid_t[]> lwps (XCNEWVEC (lwpid_t, nlwps));
1950 nlwps = ptrace (PT_GETLWPLIST, pid, (caddr_t) lwps.get (), nlwps);
1951 if (nlwps == -1)
1952 perror_with_name (("ptrace (PT_GETLWPLIST)"));
1954 for (int i = 0; i < nlwps; i++)
1956 if (lwps[i] == lwpid)
1957 continue;
1959 if (ptrace (PT_LWPINFO, lwps[i], (caddr_t) &pl, sizeof (pl)) != 0)
1960 perror_with_name (("ptrace (PT_LWPINFO)"));
1962 if (callback (pl))
1963 return true;
1965 return false;
1968 /* True if there are any stopped threads with an interesting event. */
1970 static bool
1971 pending_ptrace_events (inferior *inf)
1973 auto lambda = [] (const struct ptrace_lwpinfo &pl)
1975 #if defined(PT_LWP_EVENTS) && __FreeBSD_kernel_version < 1400090
1976 if (pl.pl_flags == PL_FLAG_BORN)
1977 return true;
1978 #endif
1979 #ifdef TDP_RFPPWAIT
1980 if (pl.pl_flags & PL_FLAG_FORKED)
1981 return true;
1982 #endif
1983 if (pl.pl_event == PL_EVENT_SIGNAL)
1985 if ((pl.pl_flags & PL_FLAG_SI) == 0)
1987 /* Not sure which signal, assume it matters. */
1988 return true;
1990 if (pl.pl_siginfo.si_signo == SIGTRAP)
1991 return true;
1993 return false;
1995 return iterate_other_ptrace_events (inf->pid,
1996 gdb::make_function_view (lambda));
1999 void
2000 fbsd_nat_target::detach (inferior *inf, int from_tty)
2002 fbsd_nat_debug_start_end ("pid %d", inf->pid);
2004 stop_process (inf);
2006 remove_breakpoints_inf (inf);
2008 if (detach_fork_children (inf)) {
2009 /* No need to detach now. */
2010 target_announce_detach (from_tty);
2012 detach_success (inf);
2013 return;
2016 /* If there are any pending events (SIGSTOP from stop_process or a
2017 breakpoint hit that needs a PC fixup), drain events until the
2018 process can be safely detached. */
2019 fbsd_inferior *fbsd_inf = get_fbsd_inferior (inf);
2020 ptid_t ptid = ptid_t (inf->pid);
2021 if (fbsd_inf->pending_sigstop || pending_ptrace_events (inf))
2023 bool pending_sigstop = fbsd_inf->pending_sigstop;
2024 int sig = 0;
2026 if (pending_sigstop)
2027 fbsd_nat_debug_printf ("waiting for SIGSTOP");
2029 /* Force wait_1 to report the SIGSTOP instead of swallowing it. */
2030 fbsd_inf->pending_sigstop = false;
2032 /* Report event for all threads from wait_1. */
2033 fbsd_inf->resumed_lwps = ptid;
2037 if (ptrace (PT_CONTINUE, inf->pid, (caddr_t) 1, sig) != 0)
2038 perror_with_name (("ptrace(PT_CONTINUE)"));
2040 target_waitstatus ws;
2041 ptid_t wptid = wait_1 (ptid, &ws, 0);
2043 switch (ws.kind ())
2045 case TARGET_WAITKIND_EXITED:
2046 case TARGET_WAITKIND_SIGNALLED:
2047 /* No need to detach now. */
2048 target_announce_detach (from_tty);
2050 detach_success (inf);
2051 return;
2052 case TARGET_WAITKIND_FORKED:
2053 case TARGET_WAITKIND_VFORKED:
2055 pid_t pid = ws.child_ptid ().pid ();
2056 fbsd_nat_debug_printf ("detaching from child %d", pid);
2057 (void) ptrace (PT_DETACH, pid, (caddr_t) 1, 0);
2058 sig = 0;
2060 break;
2061 case TARGET_WAITKIND_STOPPED:
2062 sig = gdb_signal_to_host (ws.sig ());
2063 switch (sig)
2065 case SIGSTOP:
2066 if (pending_sigstop)
2068 sig = 0;
2069 pending_sigstop = false;
2071 break;
2072 case SIGTRAP:
2073 #ifndef USE_SIGTRAP_SIGINFO
2075 /* Update PC from software breakpoint hit. */
2076 struct regcache *regcache = get_thread_regcache (this, wptid);
2077 struct gdbarch *gdbarch = regcache->arch ();
2078 int decr_pc = gdbarch_decr_pc_after_break (gdbarch);
2080 if (decr_pc != 0)
2082 CORE_ADDR pc;
2084 pc = regcache_read_pc (regcache);
2085 if (breakpoint_inserted_here_p (regcache->aspace (),
2086 pc - decr_pc))
2088 fbsd_nat_debug_printf ("adjusted PC for LWP %ld",
2089 wptid.lwp ());
2090 regcache_write_pc (regcache, pc - decr_pc);
2094 #else
2095 /* pacify gcc */
2096 (void) wptid;
2097 #endif
2098 sig = 0;
2099 break;
2103 while (pending_sigstop || pending_ptrace_events (inf));
2106 target_announce_detach (from_tty);
2108 if (ptrace (PT_DETACH, inf->pid, (caddr_t) 1, 0) == -1)
2109 perror_with_name (("ptrace (PT_DETACH)"));
2111 detach_success (inf);
2114 /* Implement the "kill" target method. */
2116 void
2117 fbsd_nat_target::kill ()
2119 pid_t pid = inferior_ptid.pid ();
2120 if (pid == 0)
2121 return;
2123 inferior *inf = current_inferior ();
2124 stop_process (inf);
2126 if (detach_fork_children (inf)) {
2127 /* No need to kill now. */
2128 target_mourn_inferior (inferior_ptid);
2130 return;
2133 #ifdef TDP_RFPPWAIT
2134 /* If there are any threads that have forked a new child but not yet
2135 reported it because other threads reported events first, detach
2136 from the children before killing the parent. */
2137 auto lambda = [] (const struct ptrace_lwpinfo &pl)
2139 if (pl.pl_flags & PL_FLAG_FORKED)
2141 pid_t child = pl.pl_child_pid;
2143 /* If the child hasn't reported its stop yet, wait for it to
2144 stop. */
2145 fbsd_wait_for_fork_child (child);
2147 /* Detach from the child. */
2148 (void) ptrace (PT_DETACH, child, (caddr_t) 1, 0);
2150 return false;
2152 iterate_other_ptrace_events (pid, gdb::make_function_view (lambda));
2153 #endif
2155 if (ptrace (PT_KILL, pid, NULL, 0) == -1)
2156 perror_with_name (("ptrace (PT_KILL)"));
2158 int status;
2159 waitpid (pid, &status, 0);
2161 target_mourn_inferior (inferior_ptid);
2164 void
2165 fbsd_nat_target::mourn_inferior ()
2167 gdb_assert (!have_pending_event (ptid_t (current_inferior ()->pid)));
2168 inf_ptrace_target::mourn_inferior ();
2171 void
2172 fbsd_nat_target::follow_exec (inferior *follow_inf, ptid_t ptid,
2173 const char *execd_pathname)
2175 inferior *orig_inf = current_inferior ();
2177 inf_ptrace_target::follow_exec (follow_inf, ptid, execd_pathname);
2179 if (orig_inf != follow_inf)
2181 /* Migrate the fbsd_inferior to the new inferior. */
2182 follow_inf->priv.reset (orig_inf->priv.release ());
2186 #ifdef TDP_RFPPWAIT
2187 /* Target hook for follow_fork. On entry and at return inferior_ptid is
2188 the ptid of the followed inferior. */
2190 void
2191 fbsd_nat_target::follow_fork (inferior *child_inf, ptid_t child_ptid,
2192 target_waitkind fork_kind, bool follow_child,
2193 bool detach_fork)
2195 inf_ptrace_target::follow_fork (child_inf, child_ptid, fork_kind,
2196 follow_child, detach_fork);
2198 if (child_inf != nullptr)
2200 fbsd_inferior *fbsd_inf = new fbsd_inferior;
2201 child_inf->priv.reset (fbsd_inf);
2202 fbsd_inf->num_lwps = 1;
2205 if (!follow_child && detach_fork)
2207 pid_t child_pid = child_ptid.pid ();
2209 /* Breakpoints have already been detached from the child by
2210 infrun.c. */
2212 if (ptrace (PT_DETACH, child_pid, (PTRACE_TYPE_ARG3) 1, 0) == -1)
2213 perror_with_name (("ptrace (PT_DETACH)"));
2215 #ifndef PTRACE_VFORK
2216 if (fork_kind () == TARGET_WAITKIND_VFORKED)
2218 /* We can't insert breakpoints until the child process has
2219 finished with the shared memory region. The parent
2220 process doesn't wait for the child process to exit or
2221 exec until after it has been resumed from the ptrace stop
2222 to report the fork. Once it has been resumed it doesn't
2223 stop again before returning to userland, so there is no
2224 reliable way to wait on the parent.
2226 We can't stay attached to the child to wait for an exec
2227 or exit because it may invoke ptrace(PT_TRACE_ME)
2228 (e.g. if the parent process is a debugger forking a new
2229 child process).
2231 In the end, the best we can do is to make sure it runs
2232 for a little while. Hopefully it will be out of range of
2233 any breakpoints we reinsert. Usually this is only the
2234 single-step breakpoint at vfork's return point. */
2236 usleep (10000);
2238 /* Schedule a fake VFORK_DONE event to report on the next
2239 wait. */
2240 fbsd_add_vfork_done (inferior_ptid);
2242 #endif
2247 fbsd_nat_target::insert_fork_catchpoint (int pid)
2249 return 0;
2253 fbsd_nat_target::remove_fork_catchpoint (int pid)
2255 return 0;
2259 fbsd_nat_target::insert_vfork_catchpoint (int pid)
2261 return 0;
2265 fbsd_nat_target::remove_vfork_catchpoint (int pid)
2267 return 0;
2269 #endif
2271 /* Implement the virtual inf_ptrace_target::post_startup_inferior method. */
2273 void
2274 fbsd_nat_target::post_startup_inferior (ptid_t pid)
2276 fbsd_enable_proc_events (pid.pid ());
2279 /* Implement the "post_attach" target_ops method. */
2281 void
2282 fbsd_nat_target::post_attach (int pid)
2284 fbsd_enable_proc_events (pid);
2285 fbsd_add_threads (this, pid);
2288 /* Traced processes always stop after exec. */
2291 fbsd_nat_target::insert_exec_catchpoint (int pid)
2293 return 0;
2297 fbsd_nat_target::remove_exec_catchpoint (int pid)
2299 return 0;
2302 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
2304 fbsd_nat_target::set_syscall_catchpoint (int pid, bool needed,
2305 int any_count,
2306 gdb::array_view<const int> syscall_counts)
2309 /* Ignore the arguments. inf-ptrace.c will use PT_SYSCALL which
2310 will catch all system call entries and exits. The system calls
2311 are filtered by GDB rather than the kernel. */
2312 return 0;
2314 #endif
2316 bool
2317 fbsd_nat_target::supports_multi_process ()
2319 return true;
2322 bool
2323 fbsd_nat_target::supports_disable_randomization ()
2325 #ifdef PROC_ASLR_CTL
2326 return true;
2327 #else
2328 return false;
2329 #endif
2332 /* See fbsd-nat.h. */
2334 bool
2335 fbsd_nat_target::fetch_register_set (struct regcache *regcache, int regnum,
2336 int fetch_op, const struct regset *regset,
2337 int regbase, void *regs, size_t size)
2339 const struct regcache_map_entry *map
2340 = (const struct regcache_map_entry *) regset->regmap;
2341 pid_t pid = get_ptrace_pid (regcache->ptid ());
2343 if (regnum == -1
2344 || (regnum >= regbase && regcache_map_supplies (map, regnum - regbase,
2345 regcache->arch (), size)))
2347 if (ptrace (fetch_op, pid, (PTRACE_TYPE_ARG3) regs, 0) == -1)
2348 perror_with_name (_("Couldn't get registers"));
2350 regset->supply_regset (regset, regcache, regnum, regs, size);
2351 return true;
2353 return false;
2356 /* See fbsd-nat.h. */
2358 bool
2359 fbsd_nat_target::store_register_set (struct regcache *regcache, int regnum,
2360 int fetch_op, int store_op,
2361 const struct regset *regset, int regbase,
2362 void *regs, size_t size)
2364 const struct regcache_map_entry *map
2365 = (const struct regcache_map_entry *) regset->regmap;
2366 pid_t pid = get_ptrace_pid (regcache->ptid ());
2368 if (regnum == -1
2369 || (regnum >= regbase && regcache_map_supplies (map, regnum - regbase,
2370 regcache->arch (), size)))
2372 if (ptrace (fetch_op, pid, (PTRACE_TYPE_ARG3) regs, 0) == -1)
2373 perror_with_name (_("Couldn't get registers"));
2375 regset->collect_regset (regset, regcache, regnum, regs, size);
2377 if (ptrace (store_op, pid, (PTRACE_TYPE_ARG3) regs, 0) == -1)
2378 perror_with_name (_("Couldn't write registers"));
2379 return true;
2381 return false;
2384 /* See fbsd-nat.h. */
2386 size_t
2387 fbsd_nat_target::have_regset (ptid_t ptid, int note)
2389 pid_t pid = get_ptrace_pid (ptid);
2390 struct iovec iov;
2392 iov.iov_base = nullptr;
2393 iov.iov_len = 0;
2394 if (ptrace (PT_GETREGSET, pid, (PTRACE_TYPE_ARG3) &iov, note) == -1)
2395 return 0;
2396 return iov.iov_len;
2399 /* See fbsd-nat.h. */
2401 bool
2402 fbsd_nat_target::fetch_regset (struct regcache *regcache, int regnum, int note,
2403 const struct regset *regset, int regbase,
2404 void *regs, size_t size)
2406 const struct regcache_map_entry *map
2407 = (const struct regcache_map_entry *) regset->regmap;
2408 pid_t pid = get_ptrace_pid (regcache->ptid ());
2410 if (regnum == -1
2411 || (regnum >= regbase && regcache_map_supplies (map, regnum - regbase,
2412 regcache->arch (), size)))
2414 struct iovec iov;
2416 iov.iov_base = regs;
2417 iov.iov_len = size;
2418 if (ptrace (PT_GETREGSET, pid, (PTRACE_TYPE_ARG3) &iov, note) == -1)
2419 perror_with_name (_("Couldn't get registers"));
2421 regset->supply_regset (regset, regcache, regnum, regs, size);
2422 return true;
2424 return false;
2427 bool
2428 fbsd_nat_target::store_regset (struct regcache *regcache, int regnum, int note,
2429 const struct regset *regset, int regbase,
2430 void *regs, size_t size)
2432 const struct regcache_map_entry *map
2433 = (const struct regcache_map_entry *) regset->regmap;
2434 pid_t pid = get_ptrace_pid (regcache->ptid ());
2436 if (regnum == -1
2437 || (regnum >= regbase && regcache_map_supplies (map, regnum - regbase,
2438 regcache->arch (), size)))
2440 struct iovec iov;
2442 iov.iov_base = regs;
2443 iov.iov_len = size;
2444 if (ptrace (PT_GETREGSET, pid, (PTRACE_TYPE_ARG3) &iov, note) == -1)
2445 perror_with_name (_("Couldn't get registers"));
2447 regset->collect_regset (regset, regcache, regnum, regs, size);
2449 if (ptrace (PT_SETREGSET, pid, (PTRACE_TYPE_ARG3) &iov, note) == -1)
2450 perror_with_name (_("Couldn't write registers"));
2451 return true;
2453 return false;
2456 /* See fbsd-nat.h. */
2458 bool
2459 fbsd_nat_get_siginfo (ptid_t ptid, siginfo_t *siginfo)
2461 struct ptrace_lwpinfo pl;
2462 pid_t pid = get_ptrace_pid (ptid);
2464 if (ptrace (PT_LWPINFO, pid, (caddr_t) &pl, sizeof pl) == -1)
2465 return false;
2466 if (!(pl.pl_flags & PL_FLAG_SI))
2467 return false;;
2468 *siginfo = pl.pl_siginfo;
2469 return (true);
2472 void _initialize_fbsd_nat ();
2473 void
2474 _initialize_fbsd_nat ()
2476 add_setshow_boolean_cmd ("fbsd-lwp", class_maintenance,
2477 &debug_fbsd_lwp, _("\
2478 Set debugging of FreeBSD lwp module."), _("\
2479 Show debugging of FreeBSD lwp module."), _("\
2480 Enables printf debugging output."),
2481 NULL,
2482 &show_fbsd_lwp_debug,
2483 &setdebuglist, &showdebuglist);
2484 add_setshow_boolean_cmd ("fbsd-nat", class_maintenance,
2485 &debug_fbsd_nat, _("\
2486 Set debugging of FreeBSD native target."), _("\
2487 Show debugging of FreeBSD native target."), _("\
2488 Enables printf debugging output."),
2489 NULL,
2490 &show_fbsd_nat_debug,
2491 &setdebuglist, &showdebuglist);
2493 /* Install a SIGCHLD handler. */
2494 signal (SIGCHLD, sigchld_handler);