1 /* Native-dependent code for FreeBSD.
3 Copyright (C) 2002-2018 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "byte-vector.h"
27 #include "gdbthread.h"
29 #include <sys/types.h>
30 #include <sys/procfs.h>
31 #include <sys/ptrace.h>
32 #include <sys/signal.h>
33 #include <sys/sysctl.h>
35 #if defined(HAVE_KINFO_GETFILE) || defined(HAVE_KINFO_GETVMMAP)
38 #if !defined(HAVE_KINFO_GETVMMAP)
39 #include "filestuff.h"
44 #include "fbsd-tdep.h"
48 /* Return the name of a file that can be opened to get the symbols for
49 the child process identified by PID. */
52 fbsd_pid_to_exec_file (struct target_ops *self, int pid)
55 static char buf[PATH_MAX];
58 #ifdef KERN_PROC_PATHNAME
64 mib[2] = KERN_PROC_PATHNAME;
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
71 return buflen == 0 ? NULL : buf;
74 xsnprintf (name, PATH_MAX, "/proc/%d/exe", pid);
75 len = readlink (name, buf, PATH_MAX - 1);
85 #ifdef HAVE_KINFO_GETVMMAP
86 /* Iterate over all the memory regions in the current inferior,
87 calling FUNC for each memory region. OBFD is passed as the last
91 fbsd_find_memory_regions (struct target_ops *self,
92 find_memory_region_ftype func, void *obfd)
94 pid_t pid = ptid_get_pid (inferior_ptid);
95 struct kinfo_vmentry *kve;
99 gdb::unique_xmalloc_ptr<struct kinfo_vmentry>
100 vmentl (kinfo_getvmmap (pid, &nitems));
102 perror_with_name (_("Couldn't fetch VM map entries."));
104 for (i = 0, kve = vmentl.get (); i < nitems; i++, kve++)
106 /* Skip unreadable segments and those where MAP_NOCORE has been set. */
107 if (!(kve->kve_protection & KVME_PROT_READ)
108 || kve->kve_flags & KVME_FLAG_NOCOREDUMP)
111 /* Skip segments with an invalid type. */
112 if (kve->kve_type != KVME_TYPE_DEFAULT
113 && kve->kve_type != KVME_TYPE_VNODE
114 && kve->kve_type != KVME_TYPE_SWAP
115 && kve->kve_type != KVME_TYPE_PHYS)
118 size = kve->kve_end - kve->kve_start;
121 fprintf_filtered (gdb_stdout,
122 "Save segment, %ld bytes at %s (%c%c%c)\n",
124 paddress (target_gdbarch (), kve->kve_start),
125 kve->kve_protection & KVME_PROT_READ ? 'r' : '-',
126 kve->kve_protection & KVME_PROT_WRITE ? 'w' : '-',
127 kve->kve_protection & KVME_PROT_EXEC ? 'x' : '-');
130 /* Invoke the callback function to create the corefile segment.
131 Pass MODIFIED as true, we do not know the real modification state. */
132 func (kve->kve_start, size, kve->kve_protection & KVME_PROT_READ,
133 kve->kve_protection & KVME_PROT_WRITE,
134 kve->kve_protection & KVME_PROT_EXEC, 1, obfd);
140 fbsd_read_mapping (FILE *mapfile, unsigned long *start, unsigned long *end,
143 /* FreeBSD 5.1-RELEASE uses a 256-byte buffer. */
145 int resident, privateresident;
149 /* As of FreeBSD 5.0-RELEASE, the layout is described in
150 /usr/src/sys/fs/procfs/procfs_map.c. Somewhere in 5.1-CURRENT a
151 new column was added to the procfs map. Therefore we can't use
152 fscanf since we need to support older releases too. */
153 if (fgets (buf, sizeof buf, mapfile) != NULL)
154 ret = sscanf (buf, "%lx %lx %d %d %lx %s", start, end,
155 &resident, &privateresident, &obj, protection);
157 return (ret != 0 && ret != EOF);
160 /* Iterate over all the memory regions in the current inferior,
161 calling FUNC for each memory region. OBFD is passed as the last
165 fbsd_find_memory_regions (struct target_ops *self,
166 find_memory_region_ftype func, void *obfd)
168 pid_t pid = ptid_get_pid (inferior_ptid);
169 unsigned long start, end, size;
171 int read, write, exec;
173 std::string mapfilename = string_printf ("/proc/%ld/map", (long) pid);
174 gdb_file_up mapfile (fopen (mapfilename.c_str (), "r"));
176 error (_("Couldn't open %s."), mapfilename.c_str ());
179 fprintf_filtered (gdb_stdout,
180 "Reading memory regions from %s\n", mapfilename.c_str ());
182 /* Now iterate until end-of-file. */
183 while (fbsd_read_mapping (mapfile.get (), &start, &end, &protection[0]))
187 read = (strchr (protection, 'r') != 0);
188 write = (strchr (protection, 'w') != 0);
189 exec = (strchr (protection, 'x') != 0);
193 fprintf_filtered (gdb_stdout,
194 "Save segment, %ld bytes at %s (%c%c%c)\n",
195 size, paddress (target_gdbarch (), start),
201 /* Invoke the callback function to create the corefile segment.
202 Pass MODIFIED as true, we do not know the real modification state. */
203 func (start, size, read, write, exec, 1, obfd);
210 /* Fetch the command line for a running process. */
212 static gdb::unique_xmalloc_ptr<char>
213 fbsd_fetch_cmdline (pid_t pid)
221 mib[2] = KERN_PROC_ARGS;
223 if (sysctl (mib, 4, NULL, &len, NULL, 0) == -1)
229 gdb::unique_xmalloc_ptr<char> cmdline ((char *) xmalloc (len));
230 if (sysctl (mib, 4, cmdline.get (), &len, NULL, 0) == -1)
236 /* Fetch the external variant of the kernel's internal process
237 structure for the process PID into KP. */
240 fbsd_fetch_kinfo_proc (pid_t pid, struct kinfo_proc *kp)
248 mib[2] = KERN_PROC_PID;
250 return (sysctl (mib, 4, kp, &len, NULL, 0) == 0);
253 /* Implement the "to_info_proc target_ops" method. */
256 fbsd_info_proc (struct target_ops *ops, const char *args,
257 enum info_proc_what what)
259 #ifdef HAVE_KINFO_GETFILE
260 gdb::unique_xmalloc_ptr<struct kinfo_file> fdtbl;
263 struct kinfo_proc kp;
266 bool do_cmdline = false;
269 #ifdef HAVE_KINFO_GETVMMAP
270 bool do_mappings = false;
272 bool do_status = false;
281 #ifdef HAVE_KINFO_GETVMMAP
303 #ifdef HAVE_KINFO_GETVMMAP
309 error (_("Not supported on this target."));
312 gdb_argv built_argv (args);
313 if (built_argv.count () == 0)
315 pid = ptid_get_pid (inferior_ptid);
317 error (_("No current process: you must name one."));
319 else if (built_argv.count () == 1 && isdigit (built_argv[0][0]))
320 pid = strtol (built_argv[0], NULL, 10);
322 error (_("Invalid arguments."));
324 printf_filtered (_("process %d\n"), pid);
325 #ifdef HAVE_KINFO_GETFILE
326 if (do_cwd || do_exe)
327 fdtbl.reset (kinfo_getfile (pid, &nfd));
332 gdb::unique_xmalloc_ptr<char> cmdline = fbsd_fetch_cmdline (pid);
333 if (cmdline != nullptr)
334 printf_filtered ("cmdline = '%s'\n", cmdline.get ());
336 warning (_("unable to fetch command line"));
340 const char *cwd = NULL;
341 #ifdef HAVE_KINFO_GETFILE
342 struct kinfo_file *kf = fdtbl.get ();
343 for (int i = 0; i < nfd; i++, kf++)
345 if (kf->kf_type == KF_TYPE_VNODE && kf->kf_fd == KF_FD_TYPE_CWD)
353 printf_filtered ("cwd = '%s'\n", cwd);
355 warning (_("unable to fetch current working directory"));
359 const char *exe = NULL;
360 #ifdef HAVE_KINFO_GETFILE
361 struct kinfo_file *kf = fdtbl.get ();
362 for (int i = 0; i < nfd; i++, kf++)
364 if (kf->kf_type == KF_TYPE_VNODE && kf->kf_fd == KF_FD_TYPE_TEXT)
372 exe = fbsd_pid_to_exec_file (ops, pid);
374 printf_filtered ("exe = '%s'\n", exe);
376 warning (_("unable to fetch executable path name"));
378 #ifdef HAVE_KINFO_GETVMMAP
382 gdb::unique_xmalloc_ptr<struct kinfo_vmentry>
383 vmentl (kinfo_getvmmap (pid, &nvment));
385 if (vmentl != nullptr)
387 printf_filtered (_("Mapped address spaces:\n\n"));
389 printf_filtered (" %18s %18s %10s %10s %9s %s\n",
392 " Size", " Offset", "Flags ", "File");
394 printf_filtered ("\t%10s %10s %10s %10s %9s %s\n",
397 " Size", " Offset", "Flags ", "File");
400 struct kinfo_vmentry *kve = vmentl.get ();
401 for (int i = 0; i < nvment; i++, kve++)
405 start = kve->kve_start;
408 printf_filtered (" %18s %18s %10s %10s %9s %s\n",
411 hex_string (end - start),
412 hex_string (kve->kve_offset),
413 fbsd_vm_map_entry_flags (kve->kve_flags,
414 kve->kve_protection),
417 printf_filtered ("\t%10s %10s %10s %10s %9s %s\n",
420 hex_string (end - start),
421 hex_string (kve->kve_offset),
422 fbsd_vm_map_entry_flags (kve->kve_flags,
423 kve->kve_protection),
429 warning (_("unable to fetch virtual memory map"));
434 if (!fbsd_fetch_kinfo_proc (pid, &kp))
435 warning (_("Failed to fetch process information"));
441 printf_filtered ("Name: %s\n", kp.ki_comm);
448 state = "R (running)";
451 state = "T (stopped)";
454 state = "Z (zombie)";
457 state = "S (sleeping)";
460 state = "W (interrupt wait)";
463 state = "L (blocked on lock)";
466 state = "? (unknown)";
469 printf_filtered ("State: %s\n", state);
470 printf_filtered ("Parent process: %d\n", kp.ki_ppid);
471 printf_filtered ("Process group: %d\n", kp.ki_pgid);
472 printf_filtered ("Session id: %d\n", kp.ki_sid);
473 printf_filtered ("TTY: %ju\n", (uintmax_t) kp.ki_tdev);
474 printf_filtered ("TTY owner process group: %d\n", kp.ki_tpgid);
475 printf_filtered ("User IDs (real, effective, saved): %d %d %d\n",
476 kp.ki_ruid, kp.ki_uid, kp.ki_svuid);
477 printf_filtered ("Group IDs (real, effective, saved): %d %d %d\n",
478 kp.ki_rgid, kp.ki_groups[0], kp.ki_svgid);
479 printf_filtered ("Groups: ");
480 for (int i = 0; i < kp.ki_ngroups; i++)
481 printf_filtered ("%d ", kp.ki_groups[i]);
482 printf_filtered ("\n");
483 printf_filtered ("Minor faults (no memory page): %ld\n",
484 kp.ki_rusage.ru_minflt);
485 printf_filtered ("Minor faults, children: %ld\n",
486 kp.ki_rusage_ch.ru_minflt);
487 printf_filtered ("Major faults (memory page faults): %ld\n",
488 kp.ki_rusage.ru_majflt);
489 printf_filtered ("Major faults, children: %ld\n",
490 kp.ki_rusage_ch.ru_majflt);
491 printf_filtered ("utime: %jd.%06ld\n",
492 (intmax_t) kp.ki_rusage.ru_utime.tv_sec,
493 kp.ki_rusage.ru_utime.tv_usec);
494 printf_filtered ("stime: %jd.%06ld\n",
495 (intmax_t) kp.ki_rusage.ru_stime.tv_sec,
496 kp.ki_rusage.ru_stime.tv_usec);
497 printf_filtered ("utime, children: %jd.%06ld\n",
498 (intmax_t) kp.ki_rusage_ch.ru_utime.tv_sec,
499 kp.ki_rusage_ch.ru_utime.tv_usec);
500 printf_filtered ("stime, children: %jd.%06ld\n",
501 (intmax_t) kp.ki_rusage_ch.ru_stime.tv_sec,
502 kp.ki_rusage_ch.ru_stime.tv_usec);
503 printf_filtered ("'nice' value: %d\n", kp.ki_nice);
504 printf_filtered ("Start time: %jd.%06ld\n", kp.ki_start.tv_sec,
505 kp.ki_start.tv_usec);
506 pgtok = getpagesize () / 1024;
507 printf_filtered ("Virtual memory size: %ju kB\n",
508 (uintmax_t) kp.ki_size / 1024);
509 printf_filtered ("Data size: %ju kB\n",
510 (uintmax_t) kp.ki_dsize * pgtok);
511 printf_filtered ("Stack size: %ju kB\n",
512 (uintmax_t) kp.ki_ssize * pgtok);
513 printf_filtered ("Text size: %ju kB\n",
514 (uintmax_t) kp.ki_tsize * pgtok);
515 printf_filtered ("Resident set size: %ju kB\n",
516 (uintmax_t) kp.ki_rssize * pgtok);
517 printf_filtered ("Maximum RSS: %ju kB\n",
518 (uintmax_t) kp.ki_rusage.ru_maxrss);
519 printf_filtered ("Pending Signals: ");
520 for (int i = 0; i < _SIG_WORDS; i++)
521 printf_filtered ("%08x ", kp.ki_siglist.__bits[i]);
522 printf_filtered ("\n");
523 printf_filtered ("Ignored Signals: ");
524 for (int i = 0; i < _SIG_WORDS; i++)
525 printf_filtered ("%08x ", kp.ki_sigignore.__bits[i]);
526 printf_filtered ("\n");
527 printf_filtered ("Caught Signals: ");
528 for (int i = 0; i < _SIG_WORDS; i++)
529 printf_filtered ("%08x ", kp.ki_sigcatch.__bits[i]);
530 printf_filtered ("\n");
535 #ifdef KERN_PROC_AUXV
536 static enum target_xfer_status (*super_xfer_partial) (struct target_ops *ops,
537 enum target_object object,
540 const gdb_byte *writebuf,
543 ULONGEST *xfered_len);
546 /* Return the size of siginfo for the current inferior. */
554 /* This structure matches the naming and layout of `siginfo_t' in
555 <sys/signal.h>. In particular, the `si_foo' macros defined in that
556 header can be used with both types to copy fields in the `_reason'
568 union sigval32 si_value;
601 struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
603 /* Is the inferior 32-bit? If so, use the 32-bit siginfo size. */
604 if (gdbarch_long_bit (gdbarch) == 32)
605 return sizeof (struct siginfo32);
607 return sizeof (siginfo_t);
610 /* Convert a native 64-bit siginfo object to a 32-bit object. Note
611 that FreeBSD doesn't support writing to $_siginfo, so this only
612 needs to convert one way. */
615 fbsd_convert_siginfo (siginfo_t *si)
618 struct gdbarch *gdbarch = get_frame_arch (get_current_frame ());
620 /* Is the inferior 32-bit? If not, nothing to do. */
621 if (gdbarch_long_bit (gdbarch) != 32)
624 struct siginfo32 si32;
626 si32.si_signo = si->si_signo;
627 si32.si_errno = si->si_errno;
628 si32.si_code = si->si_code;
629 si32.si_pid = si->si_pid;
630 si32.si_uid = si->si_uid;
631 si32.si_status = si->si_status;
632 si32.si_addr = (uintptr_t) si->si_addr;
634 /* If sival_ptr is being used instead of sival_int on a big-endian
635 platform, then sival_int will be zero since it holds the upper
636 32-bits of the pointer value. */
637 #if _BYTE_ORDER == _BIG_ENDIAN
638 if (si->si_value.sival_int == 0)
639 si32.si_value.sival_ptr = (uintptr_t) si->si_value.sival_ptr;
641 si32.si_value.sival_int = si->si_value.sival_int;
643 si32.si_value.sival_int = si->si_value.sival_int;
646 /* Always copy the spare fields and then possibly overwrite them for
647 signal-specific or code-specific fields. */
648 si32._reason.__spare__.__spare1__ = si->_reason.__spare__.__spare1__;
649 for (int i = 0; i < 7; i++)
650 si32._reason.__spare__.__spare2__[i] = si->_reason.__spare__.__spare2__[i];
651 switch (si->si_signo) {
656 si32.si_trapno = si->si_trapno;
659 switch (si->si_code) {
661 si32.si_timerid = si->si_timerid;
662 si32.si_overrun = si->si_overrun;
665 si32.si_mqd = si->si_mqd;
669 memcpy(si, &si32, sizeof (si32));
674 /* Implement the "to_xfer_partial target_ops" method. */
676 static enum target_xfer_status
677 fbsd_xfer_partial (struct target_ops *ops, enum target_object object,
678 const char *annex, gdb_byte *readbuf,
679 const gdb_byte *writebuf,
680 ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
682 pid_t pid = ptid_get_pid (inferior_ptid);
687 case TARGET_OBJECT_SIGNAL_INFO:
689 struct ptrace_lwpinfo pl;
692 /* FreeBSD doesn't support writing to $_siginfo. */
693 if (writebuf != NULL)
694 return TARGET_XFER_E_IO;
696 if (inferior_ptid.lwp_p ())
697 pid = inferior_ptid.lwp ();
699 siginfo_size = fbsd_siginfo_size ();
700 if (offset > siginfo_size)
701 return TARGET_XFER_E_IO;
703 if (ptrace (PT_LWPINFO, pid, (PTRACE_TYPE_ARG3) &pl, sizeof (pl)) == -1)
704 return TARGET_XFER_E_IO;
706 if (!(pl.pl_flags & PL_FLAG_SI))
707 return TARGET_XFER_E_IO;
709 fbsd_convert_siginfo (&pl.pl_siginfo);
710 if (offset + len > siginfo_size)
711 len = siginfo_size - offset;
713 memcpy (readbuf, ((gdb_byte *) &pl.pl_siginfo) + offset, len);
715 return TARGET_XFER_OK;
718 case TARGET_OBJECT_AUXV:
720 gdb::byte_vector buf_storage;
725 if (writebuf != NULL)
726 return TARGET_XFER_E_IO;
729 mib[2] = KERN_PROC_AUXV;
738 buflen = offset + len;
739 buf_storage.resize (buflen);
740 buf = buf_storage.data ();
742 if (sysctl (mib, 4, buf, &buflen, NULL, 0) == 0)
749 memcpy (readbuf, buf + offset, buflen);
754 *xfered_len = buflen;
755 return (buflen == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
757 return TARGET_XFER_E_IO;
760 return super_xfer_partial (ops, object, annex, readbuf, writebuf, offset,
767 static int debug_fbsd_lwp;
769 static void (*super_resume) (struct target_ops *,
773 static ptid_t (*super_wait) (struct target_ops *,
775 struct target_waitstatus *,
779 show_fbsd_lwp_debug (struct ui_file *file, int from_tty,
780 struct cmd_list_element *c, const char *value)
782 fprintf_filtered (file, _("Debugging of FreeBSD lwp module is %s.\n"), value);
786 FreeBSD's first thread support was via a "reentrant" version of libc
787 (libc_r) that first shipped in 2.2.7. This library multiplexed all
788 of the threads in a process onto a single kernel thread. This
789 library was supported via the bsd-uthread target.
791 FreeBSD 5.1 introduced two new threading libraries that made use of
792 multiple kernel threads. The first (libkse) scheduled M user
793 threads onto N (<= M) kernel threads (LWPs). The second (libthr)
794 bound each user thread to a dedicated kernel thread. libkse shipped
795 as the default threading library (libpthread).
797 FreeBSD 5.3 added a libthread_db to abstract the interface across
798 the various thread libraries (libc_r, libkse, and libthr).
800 FreeBSD 7.0 switched the default threading library from from libkse
801 to libpthread and removed libc_r.
803 FreeBSD 8.0 removed libkse and the in-kernel support for it. The
804 only threading library supported by 8.0 and later is libthr which
805 ties each user thread directly to an LWP. To simplify the
806 implementation, this target only supports LWP-backed threads using
807 ptrace directly rather than libthread_db.
809 FreeBSD 11.0 introduced LWP event reporting via PT_LWP_EVENTS.
812 /* Return true if PTID is still active in the inferior. */
815 fbsd_thread_alive (struct target_ops *ops, ptid_t ptid)
817 if (ptid_lwp_p (ptid))
819 struct ptrace_lwpinfo pl;
821 if (ptrace (PT_LWPINFO, ptid_get_lwp (ptid), (caddr_t) &pl, sizeof pl)
824 #ifdef PL_FLAG_EXITED
825 if (pl.pl_flags & PL_FLAG_EXITED)
833 /* Convert PTID to a string. Returns the string in a static
837 fbsd_pid_to_str (struct target_ops *ops, ptid_t ptid)
841 lwp = ptid_get_lwp (ptid);
845 int pid = ptid_get_pid (ptid);
847 xsnprintf (buf, sizeof buf, "LWP %d of process %d", lwp, pid);
851 return normal_pid_to_str (ptid);
854 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_TDNAME
855 /* Return the name assigned to a thread by an application. Returns
856 the string in a static buffer. */
859 fbsd_thread_name (struct target_ops *self, struct thread_info *thr)
861 struct ptrace_lwpinfo pl;
862 struct kinfo_proc kp;
863 int pid = ptid_get_pid (thr->ptid);
864 long lwp = ptid_get_lwp (thr->ptid);
865 static char buf[sizeof pl.pl_tdname + 1];
867 /* Note that ptrace_lwpinfo returns the process command in pl_tdname
868 if a name has not been set explicitly. Return a NULL name in
870 if (!fbsd_fetch_kinfo_proc (pid, &kp))
871 perror_with_name (_("Failed to fetch process information"));
872 if (ptrace (PT_LWPINFO, lwp, (caddr_t) &pl, sizeof pl) == -1)
873 perror_with_name (("ptrace"));
874 if (strcmp (kp.ki_comm, pl.pl_tdname) == 0)
876 xsnprintf (buf, sizeof buf, "%s", pl.pl_tdname);
881 /* Enable additional event reporting on new processes.
883 To catch fork events, PTRACE_FORK is set on every traced process
884 to enable stops on returns from fork or vfork. Note that both the
885 parent and child will always stop, even if system call stops are
888 To catch LWP events, PTRACE_EVENTS is set on every traced process.
889 This enables stops on the birth for new LWPs (excluding the "main" LWP)
890 and the death of LWPs (excluding the last LWP in a process). Note
891 that unlike fork events, the LWP that creates a new LWP does not
895 fbsd_enable_proc_events (pid_t pid)
897 #ifdef PT_GET_EVENT_MASK
900 if (ptrace (PT_GET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3)&events,
901 sizeof (events)) == -1)
902 perror_with_name (("ptrace"));
903 events |= PTRACE_FORK | PTRACE_LWP;
905 events |= PTRACE_VFORK;
907 if (ptrace (PT_SET_EVENT_MASK, pid, (PTRACE_TYPE_ARG3)&events,
908 sizeof (events)) == -1)
909 perror_with_name (("ptrace"));
912 if (ptrace (PT_FOLLOW_FORK, pid, (PTRACE_TYPE_ARG3)0, 1) == -1)
913 perror_with_name (("ptrace"));
916 if (ptrace (PT_LWP_EVENTS, pid, (PTRACE_TYPE_ARG3)0, 1) == -1)
917 perror_with_name (("ptrace"));
922 /* Add threads for any new LWPs in a process.
924 When LWP events are used, this function is only used to detect existing
925 threads when attaching to a process. On older systems, this function is
926 called to discover new threads each time the thread list is updated. */
929 fbsd_add_threads (pid_t pid)
933 gdb_assert (!in_thread_list (pid_to_ptid (pid)));
934 nlwps = ptrace (PT_GETNUMLWPS, pid, NULL, 0);
936 perror_with_name (("ptrace"));
938 gdb::unique_xmalloc_ptr<lwpid_t[]> lwps (XCNEWVEC (lwpid_t, nlwps));
940 nlwps = ptrace (PT_GETLWPLIST, pid, (caddr_t) lwps.get (), nlwps);
942 perror_with_name (("ptrace"));
944 for (i = 0; i < nlwps; i++)
946 ptid_t ptid = ptid_build (pid, lwps[i], 0);
948 if (!in_thread_list (ptid))
951 struct ptrace_lwpinfo pl;
953 /* Don't add exited threads. Note that this is only called
954 when attaching to a multi-threaded process. */
955 if (ptrace (PT_LWPINFO, lwps[i], (caddr_t) &pl, sizeof pl) == -1)
956 perror_with_name (("ptrace"));
957 if (pl.pl_flags & PL_FLAG_EXITED)
961 fprintf_unfiltered (gdb_stdlog,
962 "FLWP: adding thread for LWP %u\n",
969 /* Implement the "to_update_thread_list" target_ops method. */
972 fbsd_update_thread_list (struct target_ops *ops)
975 /* With support for thread events, threads are added/deleted from the
976 list as events are reported, so just try deleting exited threads. */
977 delete_exited_threads ();
981 fbsd_add_threads (ptid_get_pid (inferior_ptid));
987 To catch fork events, PT_FOLLOW_FORK is set on every traced process
988 to enable stops on returns from fork or vfork. Note that both the
989 parent and child will always stop, even if system call stops are not
992 After a fork, both the child and parent process will stop and report
993 an event. However, there is no guarantee of order. If the parent
994 reports its stop first, then fbsd_wait explicitly waits for the new
995 child before returning. If the child reports its stop first, then
996 the event is saved on a list and ignored until the parent's stop is
997 reported. fbsd_wait could have been changed to fetch the parent PID
998 of the new child and used that to wait for the parent explicitly.
999 However, if two threads in the parent fork at the same time, then
1000 the wait on the parent might return the "wrong" fork event.
1002 The initial version of PT_FOLLOW_FORK did not set PL_FLAG_CHILD for
1003 the new child process. This flag could be inferred by treating any
1004 events for an unknown pid as a new child.
1006 In addition, the initial version of PT_FOLLOW_FORK did not report a
1007 stop event for the parent process of a vfork until after the child
1008 process executed a new program or exited. The kernel was changed to
1009 defer the wait for exit or exec of the child until after posting the
1010 stop event shortly after the change to introduce PL_FLAG_CHILD.
1011 This could be worked around by reporting a vfork event when the
1012 child event posted and ignoring the subsequent event from the
1015 This implementation requires both of these fixes for simplicity's
1016 sake. FreeBSD versions newer than 9.1 contain both fixes.
1019 static std::list<ptid_t> fbsd_pending_children;
1021 /* Record a new child process event that is reported before the
1022 corresponding fork event in the parent. */
1025 fbsd_remember_child (ptid_t pid)
1027 fbsd_pending_children.push_front (pid);
1030 /* Check for a previously-recorded new child process event for PID.
1031 If one is found, remove it from the list and return the PTID. */
1034 fbsd_is_child_pending (pid_t pid)
1036 for (auto it = fbsd_pending_children.begin ();
1037 it != fbsd_pending_children.end (); it++)
1038 if (it->pid () == pid)
1041 fbsd_pending_children.erase (it);
1047 #ifndef PTRACE_VFORK
1048 static std::forward_list<ptid_t> fbsd_pending_vfork_done;
1050 /* Record a pending vfork done event. */
1053 fbsd_add_vfork_done (ptid_t pid)
1055 fbsd_pending_vfork_done.push_front (pid);
1058 /* Check for a pending vfork done event for a specific PID. */
1061 fbsd_is_vfork_done_pending (pid_t pid)
1063 for (auto it = fbsd_pending_vfork_done.begin ();
1064 it != fbsd_pending_vfork_done.end (); it++)
1065 if (it->pid () == pid)
1070 /* Check for a pending vfork done event. If one is found, remove it
1071 from the list and return the PTID. */
1074 fbsd_next_vfork_done (void)
1076 if (!fbsd_pending_vfork_done.empty ())
1078 ptid_t ptid = fbsd_pending_vfork_done.front ();
1079 fbsd_pending_vfork_done.pop_front ();
1087 /* Implement the "to_resume" target_ops method. */
1090 fbsd_resume (struct target_ops *ops,
1091 ptid_t ptid, int step, enum gdb_signal signo)
1093 #if defined(TDP_RFPPWAIT) && !defined(PTRACE_VFORK)
1096 /* Don't PT_CONTINUE a process which has a pending vfork done event. */
1097 if (ptid_equal (minus_one_ptid, ptid))
1098 pid = ptid_get_pid (inferior_ptid);
1100 pid = ptid_get_pid (ptid);
1101 if (fbsd_is_vfork_done_pending (pid))
1106 fprintf_unfiltered (gdb_stdlog,
1107 "FLWP: fbsd_resume for ptid (%d, %ld, %ld)\n",
1108 ptid_get_pid (ptid), ptid_get_lwp (ptid),
1109 ptid_get_tid (ptid));
1110 if (ptid_lwp_p (ptid))
1112 /* If ptid is a specific LWP, suspend all other LWPs in the process. */
1113 struct thread_info *tp;
1116 ALL_NON_EXITED_THREADS (tp)
1118 if (ptid_get_pid (tp->ptid) != ptid_get_pid (ptid))
1121 if (ptid_get_lwp (tp->ptid) == ptid_get_lwp (ptid))
1122 request = PT_RESUME;
1124 request = PT_SUSPEND;
1126 if (ptrace (request, ptid_get_lwp (tp->ptid), NULL, 0) == -1)
1127 perror_with_name (("ptrace"));
1132 /* If ptid is a wildcard, resume all matching threads (they won't run
1133 until the process is continued however). */
1134 struct thread_info *tp;
1136 ALL_NON_EXITED_THREADS (tp)
1138 if (!ptid_match (tp->ptid, ptid))
1141 if (ptrace (PT_RESUME, ptid_get_lwp (tp->ptid), NULL, 0) == -1)
1142 perror_with_name (("ptrace"));
1144 ptid = inferior_ptid;
1146 super_resume (ops, ptid, step, signo);
1149 /* Wait for the child specified by PTID to do something. Return the
1150 process ID of the child, or MINUS_ONE_PTID in case of error; store
1151 the status in *OURSTATUS. */
1154 fbsd_wait (struct target_ops *ops,
1155 ptid_t ptid, struct target_waitstatus *ourstatus,
1162 #ifndef PTRACE_VFORK
1163 wptid = fbsd_next_vfork_done ();
1164 if (!ptid_equal (wptid, null_ptid))
1166 ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
1170 wptid = super_wait (ops, ptid, ourstatus, target_options);
1171 if (ourstatus->kind == TARGET_WAITKIND_STOPPED)
1173 struct ptrace_lwpinfo pl;
1177 pid = ptid_get_pid (wptid);
1178 if (ptrace (PT_LWPINFO, pid, (caddr_t) &pl, sizeof pl) == -1)
1179 perror_with_name (("ptrace"));
1181 wptid = ptid_build (pid, pl.pl_lwpid, 0);
1183 #ifdef PT_LWP_EVENTS
1184 if (pl.pl_flags & PL_FLAG_EXITED)
1186 /* If GDB attaches to a multi-threaded process, exiting
1187 threads might be skipped during fbsd_post_attach that
1188 have not yet reported their PL_FLAG_EXITED event.
1189 Ignore EXITED events for an unknown LWP. */
1190 if (in_thread_list (wptid))
1193 fprintf_unfiltered (gdb_stdlog,
1194 "FLWP: deleting thread for LWP %u\n",
1196 if (print_thread_events)
1197 printf_unfiltered (_("[%s exited]\n"), target_pid_to_str
1199 delete_thread (wptid);
1201 if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1202 perror_with_name (("ptrace"));
1207 /* Switch to an LWP PTID on the first stop in a new process.
1208 This is done after handling PL_FLAG_EXITED to avoid
1209 switching to an exited LWP. It is done before checking
1210 PL_FLAG_BORN in case the first stop reported after
1211 attaching to an existing process is a PL_FLAG_BORN
1213 if (in_thread_list (pid_to_ptid (pid)))
1216 fprintf_unfiltered (gdb_stdlog,
1217 "FLWP: using LWP %u for first thread\n",
1219 thread_change_ptid (pid_to_ptid (pid), wptid);
1222 #ifdef PT_LWP_EVENTS
1223 if (pl.pl_flags & PL_FLAG_BORN)
1225 /* If GDB attaches to a multi-threaded process, newborn
1226 threads might be added by fbsd_add_threads that have
1227 not yet reported their PL_FLAG_BORN event. Ignore
1228 BORN events for an already-known LWP. */
1229 if (!in_thread_list (wptid))
1232 fprintf_unfiltered (gdb_stdlog,
1233 "FLWP: adding thread for LWP %u\n",
1237 ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
1243 if (pl.pl_flags & PL_FLAG_FORKED)
1245 #ifndef PTRACE_VFORK
1246 struct kinfo_proc kp;
1251 child = pl.pl_child_pid;
1252 ourstatus->kind = TARGET_WAITKIND_FORKED;
1254 if (pl.pl_flags & PL_FLAG_VFORKED)
1255 ourstatus->kind = TARGET_WAITKIND_VFORKED;
1258 /* Make sure the other end of the fork is stopped too. */
1259 child_ptid = fbsd_is_child_pending (child);
1260 if (ptid_equal (child_ptid, null_ptid))
1262 pid = waitpid (child, &status, 0);
1264 perror_with_name (("waitpid"));
1266 gdb_assert (pid == child);
1268 if (ptrace (PT_LWPINFO, child, (caddr_t)&pl, sizeof pl) == -1)
1269 perror_with_name (("ptrace"));
1271 gdb_assert (pl.pl_flags & PL_FLAG_CHILD);
1272 child_ptid = ptid_build (child, pl.pl_lwpid, 0);
1275 /* Enable additional events on the child process. */
1276 fbsd_enable_proc_events (ptid_get_pid (child_ptid));
1278 #ifndef PTRACE_VFORK
1279 /* For vfork, the child process will have the P_PPWAIT
1281 if (fbsd_fetch_kinfo_proc (child, &kp))
1283 if (kp.ki_flag & P_PPWAIT)
1284 ourstatus->kind = TARGET_WAITKIND_VFORKED;
1287 warning (_("Failed to fetch process information"));
1289 ourstatus->value.related_pid = child_ptid;
1294 if (pl.pl_flags & PL_FLAG_CHILD)
1296 /* Remember that this child forked, but do not report it
1297 until the parent reports its corresponding fork
1299 fbsd_remember_child (wptid);
1304 if (pl.pl_flags & PL_FLAG_VFORK_DONE)
1306 ourstatus->kind = TARGET_WAITKIND_VFORK_DONE;
1313 if (pl.pl_flags & PL_FLAG_EXEC)
1315 ourstatus->kind = TARGET_WAITKIND_EXECD;
1316 ourstatus->value.execd_pathname
1317 = xstrdup (fbsd_pid_to_exec_file (NULL, pid));
1322 /* Note that PL_FLAG_SCE is set for any event reported while
1323 a thread is executing a system call in the kernel. In
1324 particular, signals that interrupt a sleep in a system
1325 call will report this flag as part of their event. Stops
1326 explicitly for system call entry and exit always use
1327 SIGTRAP, so only treat SIGTRAP events as system call
1328 entry/exit events. */
1329 if (pl.pl_flags & (PL_FLAG_SCE | PL_FLAG_SCX)
1330 && ourstatus->value.sig == SIGTRAP)
1332 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1333 if (catch_syscall_enabled ())
1335 if (catching_syscall_number (pl.pl_syscall_code))
1337 if (pl.pl_flags & PL_FLAG_SCE)
1338 ourstatus->kind = TARGET_WAITKIND_SYSCALL_ENTRY;
1340 ourstatus->kind = TARGET_WAITKIND_SYSCALL_RETURN;
1341 ourstatus->value.syscall_number = pl.pl_syscall_code;
1346 /* If the core isn't interested in this event, just
1347 continue the process explicitly and wait for another
1348 event. Note that PT_SYSCALL is "sticky" on FreeBSD
1349 and once system call stops are enabled on a process
1350 it stops for all system call entries and exits. */
1351 if (ptrace (PT_CONTINUE, pid, (caddr_t) 1, 0) == -1)
1352 perror_with_name (("ptrace"));
1361 /* Target hook for follow_fork. On entry and at return inferior_ptid is
1362 the ptid of the followed inferior. */
1365 fbsd_follow_fork (struct target_ops *ops, int follow_child,
1368 if (!follow_child && detach_fork)
1370 struct thread_info *tp = inferior_thread ();
1371 pid_t child_pid = ptid_get_pid (tp->pending_follow.value.related_pid);
1373 /* Breakpoints have already been detached from the child by
1376 if (ptrace (PT_DETACH, child_pid, (PTRACE_TYPE_ARG3)1, 0) == -1)
1377 perror_with_name (("ptrace"));
1379 #ifndef PTRACE_VFORK
1380 if (tp->pending_follow.kind == TARGET_WAITKIND_VFORKED)
1382 /* We can't insert breakpoints until the child process has
1383 finished with the shared memory region. The parent
1384 process doesn't wait for the child process to exit or
1385 exec until after it has been resumed from the ptrace stop
1386 to report the fork. Once it has been resumed it doesn't
1387 stop again before returning to userland, so there is no
1388 reliable way to wait on the parent.
1390 We can't stay attached to the child to wait for an exec
1391 or exit because it may invoke ptrace(PT_TRACE_ME)
1392 (e.g. if the parent process is a debugger forking a new
1395 In the end, the best we can do is to make sure it runs
1396 for a little while. Hopefully it will be out of range of
1397 any breakpoints we reinsert. Usually this is only the
1398 single-step breakpoint at vfork's return point. */
1402 /* Schedule a fake VFORK_DONE event to report on the next
1404 fbsd_add_vfork_done (inferior_ptid);
1413 fbsd_insert_fork_catchpoint (struct target_ops *self, int pid)
1419 fbsd_remove_fork_catchpoint (struct target_ops *self, int pid)
1425 fbsd_insert_vfork_catchpoint (struct target_ops *self, int pid)
1431 fbsd_remove_vfork_catchpoint (struct target_ops *self, int pid)
1437 /* Implement the "to_post_startup_inferior" target_ops method. */
1440 fbsd_post_startup_inferior (struct target_ops *self, ptid_t pid)
1442 fbsd_enable_proc_events (ptid_get_pid (pid));
1445 /* Implement the "to_post_attach" target_ops method. */
1448 fbsd_post_attach (struct target_ops *self, int pid)
1450 fbsd_enable_proc_events (pid);
1451 fbsd_add_threads (pid);
1455 /* If the FreeBSD kernel supports PL_FLAG_EXEC, then traced processes
1456 will always stop after exec. */
1459 fbsd_insert_exec_catchpoint (struct target_ops *self, int pid)
1465 fbsd_remove_exec_catchpoint (struct target_ops *self, int pid)
1471 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1473 fbsd_set_syscall_catchpoint (struct target_ops *self, int pid, bool needed,
1475 gdb::array_view<const int> syscall_counts)
1478 /* Ignore the arguments. inf-ptrace.c will use PT_SYSCALL which
1479 will catch all system call entries and exits. The system calls
1480 are filtered by GDB rather than the kernel. */
1487 fbsd_nat_add_target (struct target_ops *t)
1489 t->to_pid_to_exec_file = fbsd_pid_to_exec_file;
1490 t->to_find_memory_regions = fbsd_find_memory_regions;
1491 t->to_info_proc = fbsd_info_proc;
1492 #ifdef KERN_PROC_AUXV
1493 super_xfer_partial = t->to_xfer_partial;
1494 t->to_xfer_partial = fbsd_xfer_partial;
1497 t->to_thread_alive = fbsd_thread_alive;
1498 t->to_pid_to_str = fbsd_pid_to_str;
1499 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_TDNAME
1500 t->to_thread_name = fbsd_thread_name;
1502 t->to_update_thread_list = fbsd_update_thread_list;
1503 t->to_has_thread_control = tc_schedlock;
1504 super_resume = t->to_resume;
1505 t->to_resume = fbsd_resume;
1506 super_wait = t->to_wait;
1507 t->to_wait = fbsd_wait;
1508 t->to_post_startup_inferior = fbsd_post_startup_inferior;
1509 t->to_post_attach = fbsd_post_attach;
1511 t->to_follow_fork = fbsd_follow_fork;
1512 t->to_insert_fork_catchpoint = fbsd_insert_fork_catchpoint;
1513 t->to_remove_fork_catchpoint = fbsd_remove_fork_catchpoint;
1514 t->to_insert_vfork_catchpoint = fbsd_insert_vfork_catchpoint;
1515 t->to_remove_vfork_catchpoint = fbsd_remove_vfork_catchpoint;
1518 t->to_insert_exec_catchpoint = fbsd_insert_exec_catchpoint;
1519 t->to_remove_exec_catchpoint = fbsd_remove_exec_catchpoint;
1521 #ifdef HAVE_STRUCT_PTRACE_LWPINFO_PL_SYSCALL_CODE
1522 t->to_set_syscall_catchpoint = fbsd_set_syscall_catchpoint;
1529 _initialize_fbsd_nat (void)
1532 add_setshow_boolean_cmd ("fbsd-lwp", class_maintenance,
1533 &debug_fbsd_lwp, _("\
1534 Set debugging of FreeBSD lwp module."), _("\
1535 Show debugging of FreeBSD lwp module."), _("\
1536 Enables printf debugging output."),
1538 &show_fbsd_lwp_debug,
1539 &setdebuglist, &showdebuglist);