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