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