Sort includes for files gdb/[a-f]*.[chyl].
[external/binutils.git] / gdb / fbsd-tdep.c
1 /* Target-dependent code for FreeBSD, architecture-independent.
2
3    Copyright (C) 2002-2019 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21
22 /* Standard C includes.  */
23 #include <arpa/inet.h>
24 #include <sys/socket.h>
25
26 /* Local non-gdb includes.  */
27 #include "auxv.h"
28 #include "elf-bfd.h"
29 #include "fbsd-tdep.h"
30 #include "gdbcore.h"
31 #include "gdbthread.h"
32 #include "inferior.h"
33 #include "objfiles.h"
34 #include "regcache.h"
35 #include "regset.h"
36 #include "xml-syscall.h"
37
38 /* This enum is derived from FreeBSD's <sys/signal.h>.  */
39
40 enum
41   {
42     FREEBSD_SIGHUP = 1,
43     FREEBSD_SIGINT = 2,
44     FREEBSD_SIGQUIT = 3,
45     FREEBSD_SIGILL = 4,
46     FREEBSD_SIGTRAP = 5,
47     FREEBSD_SIGABRT = 6,
48     FREEBSD_SIGEMT = 7,
49     FREEBSD_SIGFPE = 8,
50     FREEBSD_SIGKILL = 9,
51     FREEBSD_SIGBUS = 10,
52     FREEBSD_SIGSEGV = 11,
53     FREEBSD_SIGSYS = 12,
54     FREEBSD_SIGPIPE = 13,
55     FREEBSD_SIGALRM = 14,
56     FREEBSD_SIGTERM = 15,
57     FREEBSD_SIGURG = 16,
58     FREEBSD_SIGSTOP = 17,
59     FREEBSD_SIGTSTP = 18,
60     FREEBSD_SIGCONT = 19,
61     FREEBSD_SIGCHLD = 20,
62     FREEBSD_SIGTTIN = 21,
63     FREEBSD_SIGTTOU = 22,
64     FREEBSD_SIGIO = 23,
65     FREEBSD_SIGXCPU = 24,
66     FREEBSD_SIGXFSZ = 25,
67     FREEBSD_SIGVTALRM = 26,
68     FREEBSD_SIGPROF = 27,
69     FREEBSD_SIGWINCH = 28,
70     FREEBSD_SIGINFO = 29,
71     FREEBSD_SIGUSR1 = 30,
72     FREEBSD_SIGUSR2 = 31,
73     FREEBSD_SIGTHR = 32,
74     FREEBSD_SIGLIBRT = 33,
75     FREEBSD_SIGRTMIN = 65,
76     FREEBSD_SIGRTMAX = 126,
77   };
78
79 /* FreeBSD kernels 12.0 and later include a copy of the
80    'ptrace_lwpinfo' structure returned by the PT_LWPINFO ptrace
81    operation in an ELF core note (NT_FREEBSD_PTLWPINFO) for each LWP.
82    The constants below define the offset of field members and flags in
83    this structure used by methods in this file.  Note that the
84    'ptrace_lwpinfo' struct in the note is preceded by a 4 byte integer
85    containing the size of the structure.  */
86
87 #define LWPINFO_OFFSET          0x4
88
89 /* Offsets in ptrace_lwpinfo.  */
90 #define LWPINFO_PL_FLAGS        0x8
91 #define LWPINFO64_PL_SIGINFO    0x30
92 #define LWPINFO32_PL_SIGINFO    0x2c
93
94 /* Flags in pl_flags.  */
95 #define PL_FLAG_SI      0x20    /* siginfo is valid */
96
97 /* Sizes of siginfo_t.  */
98 #define SIZE64_SIGINFO_T        80
99 #define SIZE32_SIGINFO_T        64
100
101 /* Offsets in data structure used in NT_FREEBSD_PROCSTAT_VMMAP core
102    dump notes.  See <sys/user.h> for the definition of struct
103    kinfo_vmentry.  This data structure should have the same layout on
104    all architectures.
105
106    Note that FreeBSD 7.0 used an older version of this structure
107    (struct kinfo_ovmentry), but the NT_FREEBSD_PROCSTAT_VMMAP core
108    dump note wasn't introduced until FreeBSD 9.2.  As a result, the
109    core dump note has always used the 7.1 and later structure
110    format.  */
111
112 #define KVE_STRUCTSIZE          0x0
113 #define KVE_START               0x8
114 #define KVE_END                 0x10
115 #define KVE_OFFSET              0x18
116 #define KVE_FLAGS               0x2c
117 #define KVE_PROTECTION          0x38
118 #define KVE_PATH                0x88
119
120 /* Flags in the 'kve_protection' field in struct kinfo_vmentry.  These
121    match the KVME_PROT_* constants in <sys/user.h>.  */
122
123 #define KINFO_VME_PROT_READ     0x00000001
124 #define KINFO_VME_PROT_WRITE    0x00000002
125 #define KINFO_VME_PROT_EXEC     0x00000004
126
127 /* Flags in the 'kve_flags' field in struct kinfo_vmentry.  These
128    match the KVME_FLAG_* constants in <sys/user.h>.  */
129
130 #define KINFO_VME_FLAG_COW              0x00000001
131 #define KINFO_VME_FLAG_NEEDS_COPY       0x00000002
132 #define KINFO_VME_FLAG_NOCOREDUMP       0x00000004
133 #define KINFO_VME_FLAG_SUPER            0x00000008
134 #define KINFO_VME_FLAG_GROWS_UP         0x00000010
135 #define KINFO_VME_FLAG_GROWS_DOWN       0x00000020
136
137 /* Offsets in data structure used in NT_FREEBSD_PROCSTAT_FILES core
138    dump notes.  See <sys/user.h> for the definition of struct
139    kinfo_file.  This data structure should have the same layout on all
140    architectures.
141
142    Note that FreeBSD 7.0 used an older version of this structure
143    (struct kinfo_ofile), but the NT_FREEBSD_PROCSTAT_FILES core dump
144    note wasn't introduced until FreeBSD 9.2.  As a result, the core
145    dump note has always used the 7.1 and later structure format.  */
146
147 #define KF_STRUCTSIZE           0x0
148 #define KF_TYPE                 0x4
149 #define KF_FD                   0x8
150 #define KF_FLAGS                0x10
151 #define KF_OFFSET               0x18
152 #define KF_VNODE_TYPE           0x20
153 #define KF_SOCK_DOMAIN          0x24
154 #define KF_SOCK_TYPE            0x28
155 #define KF_SOCK_PROTOCOL        0x2c
156 #define KF_SA_LOCAL             0x30
157 #define KF_SA_PEER              0xb0
158 #define KF_PATH                 0x170
159
160 /* Constants for the 'kf_type' field in struct kinfo_file.  These
161    match the KF_TYPE_* constants in <sys/user.h>.  */
162
163 #define KINFO_FILE_TYPE_VNODE   1
164 #define KINFO_FILE_TYPE_SOCKET  2
165 #define KINFO_FILE_TYPE_PIPE    3
166 #define KINFO_FILE_TYPE_FIFO    4
167 #define KINFO_FILE_TYPE_KQUEUE  5
168 #define KINFO_FILE_TYPE_CRYPTO  6
169 #define KINFO_FILE_TYPE_MQUEUE  7
170 #define KINFO_FILE_TYPE_SHM     8
171 #define KINFO_FILE_TYPE_SEM     9
172 #define KINFO_FILE_TYPE_PTS     10
173 #define KINFO_FILE_TYPE_PROCDESC 11
174
175 /* Special values for the 'kf_fd' field in struct kinfo_file.  These
176    match the KF_FD_TYPE_* constants in <sys/user.h>.  */
177
178 #define KINFO_FILE_FD_TYPE_CWD  -1
179 #define KINFO_FILE_FD_TYPE_ROOT -2
180 #define KINFO_FILE_FD_TYPE_JAIL -3
181 #define KINFO_FILE_FD_TYPE_TRACE -4
182 #define KINFO_FILE_FD_TYPE_TEXT -5
183 #define KINFO_FILE_FD_TYPE_CTTY -6
184
185 /* Flags in the 'kf_flags' field in struct kinfo_file.  These match
186    the KF_FLAG_* constants in <sys/user.h>.  */
187
188 #define KINFO_FILE_FLAG_READ            0x00000001
189 #define KINFO_FILE_FLAG_WRITE           0x00000002
190 #define KINFO_FILE_FLAG_APPEND          0x00000004
191 #define KINFO_FILE_FLAG_ASYNC           0x00000008
192 #define KINFO_FILE_FLAG_FSYNC           0x00000010
193 #define KINFO_FILE_FLAG_NONBLOCK        0x00000020
194 #define KINFO_FILE_FLAG_DIRECT          0x00000040
195 #define KINFO_FILE_FLAG_HASLOCK         0x00000080
196 #define KINFO_FILE_FLAG_EXEC            0x00004000
197
198 /* Constants for the 'kf_vnode_type' field in struct kinfo_file.
199    These match the KF_VTYPE_* constants in <sys/user.h>.  */
200
201 #define KINFO_FILE_VTYPE_VREG   1
202 #define KINFO_FILE_VTYPE_VDIR   2
203 #define KINFO_FILE_VTYPE_VCHR   4
204 #define KINFO_FILE_VTYPE_VLNK   5
205 #define KINFO_FILE_VTYPE_VSOCK  6
206 #define KINFO_FILE_VTYPE_VFIFO  7
207
208 /* Constants for socket address families.  These match AF_* constants
209    in <sys/socket.h>.  */
210
211 #define FBSD_AF_UNIX            1
212 #define FBSD_AF_INET            2
213 #define FBSD_AF_INET6           28
214
215 /* Constants for socket types.  These match SOCK_* constants in
216    <sys/socket.h>.  */
217
218 #define FBSD_SOCK_STREAM        1
219 #define FBSD_SOCK_DGRAM         2
220 #define FBSD_SOCK_SEQPACKET     5
221
222 /* Constants for IP protocols.  These match IPPROTO_* constants in
223    <netinet/in.h>.  */
224
225 #define FBSD_IPPROTO_ICMP       1
226 #define FBSD_IPPROTO_TCP        6
227 #define FBSD_IPPROTO_UDP        17
228 #define FBSD_IPPROTO_SCTP       132
229
230 /* Socket address structures.  These have the same layout on all
231    FreeBSD architectures.  In addition, multibyte fields such as IP
232    addresses are always stored in network byte order.  */
233
234 struct fbsd_sockaddr_in
235 {
236   uint8_t sin_len;
237   uint8_t sin_family;
238   uint8_t sin_port[2];
239   uint8_t sin_addr[4];
240   char sin_zero[8];
241 };
242
243 struct fbsd_sockaddr_in6
244 {
245   uint8_t sin6_len;
246   uint8_t sin6_family;
247   uint8_t sin6_port[2];
248   uint32_t sin6_flowinfo;
249   uint8_t sin6_addr[16];
250   uint32_t sin6_scope_id;
251 };
252
253 struct fbsd_sockaddr_un
254 {
255   uint8_t sun_len;
256   uint8_t sun_family;
257   char sun_path[104];
258 };
259
260 /* Number of 32-bit words in a signal set.  This matches _SIG_WORDS in
261    <sys/_sigset.h> and is the same value on all architectures.  */
262
263 #define SIG_WORDS               4
264
265 /* Offsets in data structure used in NT_FREEBSD_PROCSTAT_PROC core
266    dump notes.  See <sys/user.h> for the definition of struct
267    kinfo_proc.  This data structure has different layouts on different
268    architectures mostly due to ILP32 vs LP64.  However, FreeBSD/i386
269    uses a 32-bit time_t while all other architectures use a 64-bit
270    time_t.
271
272    The core dump note actually contains one kinfo_proc structure for
273    each thread, but all of the process-wide data can be obtained from
274    the first structure.  One result of this note's format is that some
275    of the process-wide status available in the native target method
276    from the kern.proc.pid.<pid> sysctl such as ki_stat and ki_siglist
277    is not available from a core dump.  Instead, the per-thread data
278    structures contain the value of these fields for individual
279    threads.  */
280
281 struct kinfo_proc_layout
282 {
283   /* Offsets of struct kinfo_proc members.  */
284   int ki_layout;
285   int ki_pid;
286   int ki_ppid;
287   int ki_pgid;
288   int ki_tpgid;
289   int ki_sid;
290   int ki_tdev_freebsd11;
291   int ki_sigignore;
292   int ki_sigcatch;
293   int ki_uid;
294   int ki_ruid;
295   int ki_svuid;
296   int ki_rgid;
297   int ki_svgid;
298   int ki_ngroups;
299   int ki_groups;
300   int ki_size;
301   int ki_rssize;
302   int ki_tsize;
303   int ki_dsize;
304   int ki_ssize;
305   int ki_start;
306   int ki_nice;
307   int ki_comm;
308   int ki_tdev;
309   int ki_rusage;
310   int ki_rusage_ch;
311
312   /* Offsets of struct rusage members.  */
313   int ru_utime;
314   int ru_stime;
315   int ru_maxrss;
316   int ru_minflt;
317   int ru_majflt;
318 };
319
320 const struct kinfo_proc_layout kinfo_proc_layout_32 =
321   {
322     .ki_layout = 0x4,
323     .ki_pid = 0x28,
324     .ki_ppid = 0x2c,
325     .ki_pgid = 0x30,
326     .ki_tpgid = 0x34,
327     .ki_sid = 0x38,
328     .ki_tdev_freebsd11 = 0x44,
329     .ki_sigignore = 0x68,
330     .ki_sigcatch = 0x78,
331     .ki_uid = 0x88,
332     .ki_ruid = 0x8c,
333     .ki_svuid = 0x90,
334     .ki_rgid = 0x94,
335     .ki_svgid = 0x98,
336     .ki_ngroups = 0x9c,
337     .ki_groups = 0xa0,
338     .ki_size = 0xe0,
339     .ki_rssize = 0xe4,
340     .ki_tsize = 0xec,
341     .ki_dsize = 0xf0,
342     .ki_ssize = 0xf4,
343     .ki_start = 0x118,
344     .ki_nice = 0x145,
345     .ki_comm = 0x17f,
346     .ki_tdev = 0x1f0,
347     .ki_rusage = 0x220,
348     .ki_rusage_ch = 0x278,
349
350     .ru_utime = 0x0,
351     .ru_stime = 0x10,
352     .ru_maxrss = 0x20,
353     .ru_minflt = 0x30,
354     .ru_majflt = 0x34,
355   };
356
357 const struct kinfo_proc_layout kinfo_proc_layout_i386 =
358   {
359     .ki_layout = 0x4,
360     .ki_pid = 0x28,
361     .ki_ppid = 0x2c,
362     .ki_pgid = 0x30,
363     .ki_tpgid = 0x34,
364     .ki_sid = 0x38,
365     .ki_tdev_freebsd11 = 0x44,
366     .ki_sigignore = 0x68,
367     .ki_sigcatch = 0x78,
368     .ki_uid = 0x88,
369     .ki_ruid = 0x8c,
370     .ki_svuid = 0x90,
371     .ki_rgid = 0x94,
372     .ki_svgid = 0x98,
373     .ki_ngroups = 0x9c,
374     .ki_groups = 0xa0,
375     .ki_size = 0xe0,
376     .ki_rssize = 0xe4,
377     .ki_tsize = 0xec,
378     .ki_dsize = 0xf0,
379     .ki_ssize = 0xf4,
380     .ki_start = 0x118,
381     .ki_nice = 0x135,
382     .ki_comm = 0x16f,
383     .ki_tdev = 0x1e0,
384     .ki_rusage = 0x210,
385     .ki_rusage_ch = 0x258,
386
387     .ru_utime = 0x0,
388     .ru_stime = 0x8,
389     .ru_maxrss = 0x10,
390     .ru_minflt = 0x20,
391     .ru_majflt = 0x24,
392   };
393
394 const struct kinfo_proc_layout kinfo_proc_layout_64 =
395   {
396     .ki_layout = 0x4,
397     .ki_pid = 0x48,
398     .ki_ppid = 0x4c,
399     .ki_pgid = 0x50,
400     .ki_tpgid = 0x54,
401     .ki_sid = 0x58,
402     .ki_tdev_freebsd11 = 0x64,
403     .ki_sigignore = 0x88,
404     .ki_sigcatch = 0x98,
405     .ki_uid = 0xa8,
406     .ki_ruid = 0xac,
407     .ki_svuid = 0xb0,
408     .ki_rgid = 0xb4,
409     .ki_svgid = 0xb8,
410     .ki_ngroups = 0xbc,
411     .ki_groups = 0xc0,
412     .ki_size = 0x100,
413     .ki_rssize = 0x108,
414     .ki_tsize = 0x118,
415     .ki_dsize = 0x120,
416     .ki_ssize = 0x128,
417     .ki_start = 0x150,
418     .ki_nice = 0x185,
419     .ki_comm = 0x1bf,
420     .ki_tdev = 0x230,
421     .ki_rusage = 0x260,
422     .ki_rusage_ch = 0x2f0,
423
424     .ru_utime = 0x0,
425     .ru_stime = 0x10,
426     .ru_maxrss = 0x20,
427     .ru_minflt = 0x40,
428     .ru_majflt = 0x48,
429   };
430
431 static struct gdbarch_data *fbsd_gdbarch_data_handle;
432
433 struct fbsd_gdbarch_data
434   {
435     struct type *siginfo_type;
436   };
437
438 static void *
439 init_fbsd_gdbarch_data (struct gdbarch *gdbarch)
440 {
441   return GDBARCH_OBSTACK_ZALLOC (gdbarch, struct fbsd_gdbarch_data);
442 }
443
444 static struct fbsd_gdbarch_data *
445 get_fbsd_gdbarch_data (struct gdbarch *gdbarch)
446 {
447   return ((struct fbsd_gdbarch_data *)
448           gdbarch_data (gdbarch, fbsd_gdbarch_data_handle));
449 }
450
451 /* Per-program-space data for FreeBSD architectures.  */
452 static const struct program_space_data *fbsd_pspace_data_handle;
453
454 struct fbsd_pspace_data
455 {
456   /* Offsets in the runtime linker's 'Obj_Entry' structure.  */
457   LONGEST off_linkmap;
458   LONGEST off_tlsindex;
459   bool rtld_offsets_valid;
460 };
461
462 static struct fbsd_pspace_data *
463 get_fbsd_pspace_data (struct program_space *pspace)
464 {
465   struct fbsd_pspace_data *data;
466
467   data = ((struct fbsd_pspace_data *)
468           program_space_data (pspace, fbsd_pspace_data_handle));
469   if (data == NULL)
470     {
471       data = XCNEW (struct fbsd_pspace_data);
472       set_program_space_data (pspace, fbsd_pspace_data_handle, data);
473     }
474
475   return data;
476 }
477
478 /* The cleanup callback for FreeBSD architecture per-program-space data.  */
479
480 static void
481 fbsd_pspace_data_cleanup (struct program_space *pspace, void *data)
482 {
483   xfree (data);
484 }
485
486 /* This is how we want PTIDs from core files to be printed.  */
487
488 static std::string
489 fbsd_core_pid_to_str (struct gdbarch *gdbarch, ptid_t ptid)
490 {
491   if (ptid.lwp () != 0)
492     return string_printf ("LWP %ld", ptid.lwp ());
493
494   return normal_pid_to_str (ptid);
495 }
496
497 /* Extract the name assigned to a thread from a core.  Returns the
498    string in a static buffer.  */
499
500 static const char *
501 fbsd_core_thread_name (struct gdbarch *gdbarch, struct thread_info *thr)
502 {
503   static char buf[80];
504   struct bfd_section *section;
505   bfd_size_type size;
506
507   if (thr->ptid.lwp () != 0)
508     {
509       /* FreeBSD includes a NT_FREEBSD_THRMISC note for each thread
510          whose contents are defined by a "struct thrmisc" declared in
511          <sys/procfs.h> on FreeBSD.  The per-thread name is stored as
512          a null-terminated string as the first member of the
513          structure.  Rather than define the full structure here, just
514          extract the null-terminated name from the start of the
515          note.  */
516       thread_section_name section_name (".thrmisc", thr->ptid);
517
518       section = bfd_get_section_by_name (core_bfd, section_name.c_str ());
519       if (section != NULL && bfd_section_size (core_bfd, section) > 0)
520         {
521           /* Truncate the name if it is longer than "buf".  */
522           size = bfd_section_size (core_bfd, section);
523           if (size > sizeof buf - 1)
524             size = sizeof buf - 1;
525           if (bfd_get_section_contents (core_bfd, section, buf, (file_ptr) 0,
526                                         size)
527               && buf[0] != '\0')
528             {
529               buf[size] = '\0';
530
531               /* Note that each thread will report the process command
532                  as its thread name instead of an empty name if a name
533                  has not been set explicitly.  Return a NULL name in
534                  that case.  */
535               if (strcmp (buf, elf_tdata (core_bfd)->core->program) != 0)
536                 return buf;
537             }
538         }
539     }
540
541   return NULL;
542 }
543
544 /* Implement the "core_xfer_siginfo" gdbarch method.  */
545
546 static LONGEST
547 fbsd_core_xfer_siginfo (struct gdbarch *gdbarch, gdb_byte *readbuf,
548                         ULONGEST offset, ULONGEST len)
549 {
550   size_t siginfo_size;
551
552   if (gdbarch_long_bit (gdbarch) == 32)
553     siginfo_size = SIZE32_SIGINFO_T;
554   else
555     siginfo_size = SIZE64_SIGINFO_T;
556   if (offset > siginfo_size)
557     return -1;
558
559   thread_section_name section_name (".note.freebsdcore.lwpinfo", inferior_ptid);
560   asection *section = bfd_get_section_by_name (core_bfd, section_name.c_str ());
561   if (section == NULL)
562     return -1;
563
564   gdb_byte buf[4];
565   if (!bfd_get_section_contents (core_bfd, section, buf,
566                                  LWPINFO_OFFSET + LWPINFO_PL_FLAGS, 4))
567     return -1;
568
569   int pl_flags = extract_signed_integer (buf, 4, gdbarch_byte_order (gdbarch));
570   if (!(pl_flags & PL_FLAG_SI))
571     return -1;
572
573   if (offset + len > siginfo_size)
574     len = siginfo_size - offset;
575
576   ULONGEST siginfo_offset;
577   if (gdbarch_long_bit (gdbarch) == 32)
578     siginfo_offset = LWPINFO_OFFSET + LWPINFO32_PL_SIGINFO;
579   else
580     siginfo_offset = LWPINFO_OFFSET + LWPINFO64_PL_SIGINFO;
581
582   if (!bfd_get_section_contents (core_bfd, section, readbuf,
583                                  siginfo_offset + offset, len))
584     return -1;
585
586   return len;
587 }
588
589 static int
590 find_signalled_thread (struct thread_info *info, void *data)
591 {
592   if (info->suspend.stop_signal != GDB_SIGNAL_0
593       && info->ptid.pid () == inferior_ptid.pid ())
594     return 1;
595
596   return 0;
597 }
598
599 /* Structure for passing information from
600    fbsd_collect_thread_registers via an iterator to
601    fbsd_collect_regset_section_cb. */
602
603 struct fbsd_collect_regset_section_cb_data
604 {
605   const struct regcache *regcache;
606   bfd *obfd;
607   char *note_data;
608   int *note_size;
609   unsigned long lwp;
610   enum gdb_signal stop_signal;
611   int abort_iteration;
612 };
613
614 static void
615 fbsd_collect_regset_section_cb (const char *sect_name, int supply_size,
616                                 int collect_size, const struct regset *regset,
617                                 const char *human_name, void *cb_data)
618 {
619   char *buf;
620   struct fbsd_collect_regset_section_cb_data *data
621     = (struct fbsd_collect_regset_section_cb_data *) cb_data;
622
623   if (data->abort_iteration)
624     return;
625
626   gdb_assert (regset->collect_regset);
627
628   buf = (char *) xmalloc (collect_size);
629   regset->collect_regset (regset, data->regcache, -1, buf, collect_size);
630
631   /* PRSTATUS still needs to be treated specially.  */
632   if (strcmp (sect_name, ".reg") == 0)
633     data->note_data = (char *) elfcore_write_prstatus
634       (data->obfd, data->note_data, data->note_size, data->lwp,
635        gdb_signal_to_host (data->stop_signal), buf);
636   else
637     data->note_data = (char *) elfcore_write_register_note
638       (data->obfd, data->note_data, data->note_size,
639        sect_name, buf, collect_size);
640   xfree (buf);
641
642   if (data->note_data == NULL)
643     data->abort_iteration = 1;
644 }
645
646 /* Records the thread's register state for the corefile note
647    section.  */
648
649 static char *
650 fbsd_collect_thread_registers (const struct regcache *regcache,
651                                ptid_t ptid, bfd *obfd,
652                                char *note_data, int *note_size,
653                                enum gdb_signal stop_signal)
654 {
655   struct gdbarch *gdbarch = regcache->arch ();
656   struct fbsd_collect_regset_section_cb_data data;
657
658   data.regcache = regcache;
659   data.obfd = obfd;
660   data.note_data = note_data;
661   data.note_size = note_size;
662   data.stop_signal = stop_signal;
663   data.abort_iteration = 0;
664   data.lwp = ptid.lwp ();
665
666   gdbarch_iterate_over_regset_sections (gdbarch,
667                                         fbsd_collect_regset_section_cb,
668                                         &data, regcache);
669   return data.note_data;
670 }
671
672 struct fbsd_corefile_thread_data
673 {
674   struct gdbarch *gdbarch;
675   bfd *obfd;
676   char *note_data;
677   int *note_size;
678   enum gdb_signal stop_signal;
679 };
680
681 /* Records the thread's register state for the corefile note
682    section.  */
683
684 static void
685 fbsd_corefile_thread (struct thread_info *info,
686                       struct fbsd_corefile_thread_data *args)
687 {
688   struct regcache *regcache;
689
690   regcache = get_thread_arch_regcache (info->ptid, args->gdbarch);
691
692   target_fetch_registers (regcache, -1);
693
694   args->note_data = fbsd_collect_thread_registers
695     (regcache, info->ptid, args->obfd, args->note_data,
696      args->note_size, args->stop_signal);
697 }
698
699 /* Return a byte_vector containing the contents of a core dump note
700    for the target object of type OBJECT.  If STRUCTSIZE is non-zero,
701    the data is prefixed with a 32-bit integer size to match the format
702    used in FreeBSD NT_PROCSTAT_* notes.  */
703
704 static gdb::optional<gdb::byte_vector>
705 fbsd_make_note_desc (enum target_object object, uint32_t structsize)
706 {
707   gdb::optional<gdb::byte_vector> buf =
708     target_read_alloc (current_top_target (), object, NULL);
709   if (!buf || buf->empty ())
710     return {};
711
712   if (structsize == 0)
713     return buf;
714
715   gdb::byte_vector desc (sizeof (structsize) + buf->size ());
716   memcpy (desc.data (), &structsize, sizeof (structsize));
717   memcpy (desc.data () + sizeof (structsize), buf->data (), buf->size ());
718   return desc;
719 }
720
721 /* Create appropriate note sections for a corefile, returning them in
722    allocated memory.  */
723
724 static char *
725 fbsd_make_corefile_notes (struct gdbarch *gdbarch, bfd *obfd, int *note_size)
726 {
727   struct fbsd_corefile_thread_data thread_args;
728   char *note_data = NULL;
729   Elf_Internal_Ehdr *i_ehdrp;
730   struct thread_info *curr_thr, *signalled_thr;
731
732   /* Put a "FreeBSD" label in the ELF header.  */
733   i_ehdrp = elf_elfheader (obfd);
734   i_ehdrp->e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
735
736   gdb_assert (gdbarch_iterate_over_regset_sections_p (gdbarch));
737
738   if (get_exec_file (0))
739     {
740       const char *fname = lbasename (get_exec_file (0));
741       char *psargs = xstrdup (fname);
742
743       if (get_inferior_args ())
744         psargs = reconcat (psargs, psargs, " ", get_inferior_args (),
745                            (char *) NULL);
746
747       note_data = elfcore_write_prpsinfo (obfd, note_data, note_size,
748                                           fname, psargs);
749     }
750
751   /* Thread register information.  */
752   TRY
753     {
754       update_thread_list ();
755     }
756   CATCH (e, RETURN_MASK_ERROR)
757     {
758       exception_print (gdb_stderr, e);
759     }
760   END_CATCH
761
762   /* Like the kernel, prefer dumping the signalled thread first.
763      "First thread" is what tools use to infer the signalled thread.
764      In case there's more than one signalled thread, prefer the
765      current thread, if it is signalled.  */
766   curr_thr = inferior_thread ();
767   if (curr_thr->suspend.stop_signal != GDB_SIGNAL_0)
768     signalled_thr = curr_thr;
769   else
770     {
771       signalled_thr = iterate_over_threads (find_signalled_thread, NULL);
772       if (signalled_thr == NULL)
773         signalled_thr = curr_thr;
774     }
775
776   thread_args.gdbarch = gdbarch;
777   thread_args.obfd = obfd;
778   thread_args.note_data = note_data;
779   thread_args.note_size = note_size;
780   thread_args.stop_signal = signalled_thr->suspend.stop_signal;
781
782   fbsd_corefile_thread (signalled_thr, &thread_args);
783   for (thread_info *thr : current_inferior ()->non_exited_threads ())
784     {
785       if (thr == signalled_thr)
786         continue;
787
788       fbsd_corefile_thread (thr, &thread_args);
789     }
790
791   note_data = thread_args.note_data;
792
793   /* Auxiliary vector.  */
794   uint32_t structsize = gdbarch_ptr_bit (gdbarch) / 4; /* Elf_Auxinfo  */
795   gdb::optional<gdb::byte_vector> note_desc =
796     fbsd_make_note_desc (TARGET_OBJECT_AUXV, structsize);
797   if (note_desc && !note_desc->empty ())
798     {
799       note_data = elfcore_write_note (obfd, note_data, note_size, "FreeBSD",
800                                       NT_FREEBSD_PROCSTAT_AUXV,
801                                       note_desc->data (), note_desc->size ());
802       if (!note_data)
803         return NULL;
804     }
805
806   /* Virtual memory mappings.  */
807   note_desc = fbsd_make_note_desc (TARGET_OBJECT_FREEBSD_VMMAP, 0);
808   if (note_desc && !note_desc->empty ())
809     {
810       note_data = elfcore_write_note (obfd, note_data, note_size, "FreeBSD",
811                                       NT_FREEBSD_PROCSTAT_VMMAP,
812                                       note_desc->data (), note_desc->size ());
813       if (!note_data)
814         return NULL;
815     }
816
817   note_desc = fbsd_make_note_desc (TARGET_OBJECT_FREEBSD_PS_STRINGS, 0);
818   if (note_desc && !note_desc->empty ())
819     {
820       note_data = elfcore_write_note (obfd, note_data, note_size, "FreeBSD",
821                                       NT_FREEBSD_PROCSTAT_PSSTRINGS,
822                                       note_desc->data (), note_desc->size ());
823       if (!note_data)
824         return NULL;
825     }
826
827   return note_data;
828 }
829
830 /* Helper function to generate the file descriptor description for a
831    single open file in 'info proc files'.  */
832
833 static const char *
834 fbsd_file_fd (int kf_fd)
835 {
836   switch (kf_fd)
837     {
838     case KINFO_FILE_FD_TYPE_CWD:
839       return "cwd";
840     case KINFO_FILE_FD_TYPE_ROOT:
841       return "root";
842     case KINFO_FILE_FD_TYPE_JAIL:
843       return "jail";
844     case KINFO_FILE_FD_TYPE_TRACE:
845       return "trace";
846     case KINFO_FILE_FD_TYPE_TEXT:
847       return "text";
848     case KINFO_FILE_FD_TYPE_CTTY:
849       return "ctty";
850     default:
851       return int_string (kf_fd, 10, 1, 0, 0);
852     }
853 }
854
855 /* Helper function to generate the file type for a single open file in
856    'info proc files'.  */
857
858 static const char *
859 fbsd_file_type (int kf_type, int kf_vnode_type)
860 {
861   switch (kf_type)
862     {
863     case KINFO_FILE_TYPE_VNODE:
864       switch (kf_vnode_type)
865         {
866         case KINFO_FILE_VTYPE_VREG:
867           return "file";
868         case KINFO_FILE_VTYPE_VDIR:
869           return "dir";
870         case KINFO_FILE_VTYPE_VCHR:
871           return "chr";
872         case KINFO_FILE_VTYPE_VLNK:
873           return "link";
874         case KINFO_FILE_VTYPE_VSOCK:
875           return "socket";
876         case KINFO_FILE_VTYPE_VFIFO:
877           return "fifo";
878         default:
879           {
880             char *str = get_print_cell ();
881
882             xsnprintf (str, PRINT_CELL_SIZE, "vn:%d", kf_vnode_type);
883             return str;
884           }
885         }
886     case KINFO_FILE_TYPE_SOCKET:
887       return "socket";
888     case KINFO_FILE_TYPE_PIPE:
889       return "pipe";
890     case KINFO_FILE_TYPE_FIFO:
891       return "fifo";
892     case KINFO_FILE_TYPE_KQUEUE:
893       return "kqueue";
894     case KINFO_FILE_TYPE_CRYPTO:
895       return "crypto";
896     case KINFO_FILE_TYPE_MQUEUE:
897       return "mqueue";
898     case KINFO_FILE_TYPE_SHM:
899       return "shm";
900     case KINFO_FILE_TYPE_SEM:
901       return "sem";
902     case KINFO_FILE_TYPE_PTS:
903       return "pts";
904     case KINFO_FILE_TYPE_PROCDESC:
905       return "proc";
906     default:
907       return int_string (kf_type, 10, 1, 0, 0);
908     }
909 }
910
911 /* Helper function to generate the file flags for a single open file in
912    'info proc files'.  */
913
914 static const char *
915 fbsd_file_flags (int kf_flags)
916 {
917   static char file_flags[10];
918
919   file_flags[0] = (kf_flags & KINFO_FILE_FLAG_READ) ? 'r' : '-';
920   file_flags[1] = (kf_flags & KINFO_FILE_FLAG_WRITE) ? 'w' : '-';
921   file_flags[2] = (kf_flags & KINFO_FILE_FLAG_EXEC) ? 'x' : '-';
922   file_flags[3] = (kf_flags & KINFO_FILE_FLAG_APPEND) ? 'a' : '-';
923   file_flags[4] = (kf_flags & KINFO_FILE_FLAG_ASYNC) ? 's' : '-';
924   file_flags[5] = (kf_flags & KINFO_FILE_FLAG_FSYNC) ? 'f' : '-';
925   file_flags[6] = (kf_flags & KINFO_FILE_FLAG_NONBLOCK) ? 'n' : '-';
926   file_flags[7] = (kf_flags & KINFO_FILE_FLAG_DIRECT) ? 'd' : '-';
927   file_flags[8] = (kf_flags & KINFO_FILE_FLAG_HASLOCK) ? 'l' : '-';
928   file_flags[9] = '\0';
929
930   return file_flags;
931 }
932
933 /* Helper function to generate the name of an IP protocol.  */
934
935 static const char *
936 fbsd_ipproto (int protocol)
937 {
938   switch (protocol)
939     {
940     case FBSD_IPPROTO_ICMP:
941       return "icmp";
942     case FBSD_IPPROTO_TCP:
943       return "tcp";
944     case FBSD_IPPROTO_UDP:
945       return "udp";
946     case FBSD_IPPROTO_SCTP:
947       return "sctp";
948     default:
949       {
950         char *str = get_print_cell ();
951
952         xsnprintf (str, PRINT_CELL_SIZE, "ip<%d>", protocol);
953         return str;
954       }
955     }
956 }
957
958 /* Helper function to print out an IPv4 socket address.  */
959
960 static void
961 fbsd_print_sockaddr_in (const void *sockaddr)
962 {
963   const struct fbsd_sockaddr_in *sin =
964     reinterpret_cast<const struct fbsd_sockaddr_in *> (sockaddr);
965   char buf[INET_ADDRSTRLEN];
966
967   if (inet_ntop (AF_INET, sin->sin_addr, buf, sizeof buf) == nullptr)
968     error (_("Failed to format IPv4 address"));
969   printf_filtered ("%s:%u", buf,
970                    (sin->sin_port[0] << 8) | sin->sin_port[1]);
971 }
972
973 /* Helper function to print out an IPv6 socket address.  */
974
975 static void
976 fbsd_print_sockaddr_in6 (const void *sockaddr)
977 {
978   const struct fbsd_sockaddr_in6 *sin6 =
979     reinterpret_cast<const struct fbsd_sockaddr_in6 *> (sockaddr);
980   char buf[INET6_ADDRSTRLEN];
981
982   if (inet_ntop (AF_INET6, sin6->sin6_addr, buf, sizeof buf) == nullptr)
983     error (_("Failed to format IPv6 address"));
984   printf_filtered ("%s.%u", buf,
985                    (sin6->sin6_port[0] << 8) | sin6->sin6_port[1]);
986 }
987
988 /* See fbsd-tdep.h.  */
989
990 void
991 fbsd_info_proc_files_header ()
992 {
993   printf_filtered (_("Open files:\n\n"));
994   printf_filtered ("  %6s %6s %10s %9s %s\n",
995                    "FD", "Type", "Offset", "Flags  ", "Name");
996 }
997
998 /* See fbsd-tdep.h.  */
999
1000 void
1001 fbsd_info_proc_files_entry (int kf_type, int kf_fd, int kf_flags,
1002                             LONGEST kf_offset, int kf_vnode_type,
1003                             int kf_sock_domain, int kf_sock_type,
1004                             int kf_sock_protocol, const void *kf_sa_local,
1005                             const void *kf_sa_peer, const void *kf_path)
1006 {
1007   printf_filtered ("  %6s %6s %10s %8s ",
1008                    fbsd_file_fd (kf_fd),
1009                    fbsd_file_type (kf_type, kf_vnode_type),
1010                    kf_offset > -1 ? hex_string (kf_offset) : "-",
1011                    fbsd_file_flags (kf_flags));
1012   if (kf_type == KINFO_FILE_TYPE_SOCKET)
1013     {
1014       switch (kf_sock_domain)
1015         {
1016         case FBSD_AF_UNIX:
1017           {
1018             switch (kf_sock_type)
1019               {
1020               case FBSD_SOCK_STREAM:
1021                 printf_filtered ("unix stream:");
1022                 break;
1023               case FBSD_SOCK_DGRAM:
1024                 printf_filtered ("unix dgram:");
1025                 break;
1026               case FBSD_SOCK_SEQPACKET:
1027                 printf_filtered ("unix seqpacket:");
1028                 break;
1029               default:
1030                 printf_filtered ("unix <%d>:", kf_sock_type);
1031                 break;
1032               }
1033
1034             /* For local sockets, print out the first non-nul path
1035                rather than both paths.  */
1036             const struct fbsd_sockaddr_un *sun
1037               = reinterpret_cast<const struct fbsd_sockaddr_un *> (kf_sa_local);
1038             if (sun->sun_path[0] == 0)
1039               sun = reinterpret_cast<const struct fbsd_sockaddr_un *>
1040                 (kf_sa_peer);
1041             printf_filtered ("%s", sun->sun_path);
1042             break;
1043           }
1044         case FBSD_AF_INET:
1045           printf_filtered ("%s4 ", fbsd_ipproto (kf_sock_protocol));
1046           fbsd_print_sockaddr_in (kf_sa_local);
1047           printf_filtered (" -> ");
1048           fbsd_print_sockaddr_in (kf_sa_peer);
1049           break;
1050         case FBSD_AF_INET6:
1051           printf_filtered ("%s6 ", fbsd_ipproto (kf_sock_protocol));
1052           fbsd_print_sockaddr_in6 (kf_sa_local);
1053           printf_filtered (" -> ");
1054           fbsd_print_sockaddr_in6 (kf_sa_peer);
1055           break;
1056         }
1057     }
1058   else
1059     printf_filtered ("%s", reinterpret_cast<const char *> (kf_path));
1060   printf_filtered ("\n");
1061 }
1062
1063 /* Implement "info proc files" for a corefile.  */
1064
1065 static void
1066 fbsd_core_info_proc_files (struct gdbarch *gdbarch)
1067 {
1068   asection *section
1069     = bfd_get_section_by_name (core_bfd, ".note.freebsdcore.files");
1070   if (section == NULL)
1071     {
1072       warning (_("unable to find open files in core file"));
1073       return;
1074     }
1075
1076   size_t note_size = bfd_get_section_size (section);
1077   if (note_size < 4)
1078     error (_("malformed core note - too short for header"));
1079
1080   gdb::def_vector<unsigned char> contents (note_size);
1081   if (!bfd_get_section_contents (core_bfd, section, contents.data (),
1082                                  0, note_size))
1083     error (_("could not get core note contents"));
1084
1085   unsigned char *descdata = contents.data ();
1086   unsigned char *descend = descdata + note_size;
1087
1088   /* Skip over the structure size.  */
1089   descdata += 4;
1090
1091   fbsd_info_proc_files_header ();
1092
1093   while (descdata + KF_PATH < descend)
1094     {
1095       ULONGEST structsize = bfd_get_32 (core_bfd, descdata + KF_STRUCTSIZE);
1096       if (structsize < KF_PATH)
1097         error (_("malformed core note - file structure too small"));
1098
1099       LONGEST type = bfd_get_signed_32 (core_bfd, descdata + KF_TYPE);
1100       LONGEST fd = bfd_get_signed_32 (core_bfd, descdata + KF_FD);
1101       LONGEST flags = bfd_get_signed_32 (core_bfd, descdata + KF_FLAGS);
1102       LONGEST offset = bfd_get_signed_64 (core_bfd, descdata + KF_OFFSET);
1103       LONGEST vnode_type = bfd_get_signed_32 (core_bfd,
1104                                               descdata + KF_VNODE_TYPE);
1105       LONGEST sock_domain = bfd_get_signed_32 (core_bfd,
1106                                                descdata + KF_SOCK_DOMAIN);
1107       LONGEST sock_type = bfd_get_signed_32 (core_bfd, descdata + KF_SOCK_TYPE);
1108       LONGEST sock_protocol = bfd_get_signed_32 (core_bfd,
1109                                                  descdata + KF_SOCK_PROTOCOL);
1110       fbsd_info_proc_files_entry (type, fd, flags, offset, vnode_type,
1111                                   sock_domain, sock_type, sock_protocol,
1112                                   descdata + KF_SA_LOCAL, descdata + KF_SA_PEER,
1113                                   descdata + KF_PATH);
1114
1115       descdata += structsize;
1116     }
1117 }
1118
1119 /* Helper function to generate mappings flags for a single VM map
1120    entry in 'info proc mappings'.  */
1121
1122 static const char *
1123 fbsd_vm_map_entry_flags (int kve_flags, int kve_protection)
1124 {
1125   static char vm_flags[9];
1126
1127   vm_flags[0] = (kve_protection & KINFO_VME_PROT_READ) ? 'r' : '-';
1128   vm_flags[1] = (kve_protection & KINFO_VME_PROT_WRITE) ? 'w' : '-';
1129   vm_flags[2] = (kve_protection & KINFO_VME_PROT_EXEC) ? 'x' : '-';
1130   vm_flags[3] = ' ';
1131   vm_flags[4] = (kve_flags & KINFO_VME_FLAG_COW) ? 'C' : '-';
1132   vm_flags[5] = (kve_flags & KINFO_VME_FLAG_NEEDS_COPY) ? 'N' : '-';
1133   vm_flags[6] = (kve_flags & KINFO_VME_FLAG_SUPER) ? 'S' : '-';
1134   vm_flags[7] = (kve_flags & KINFO_VME_FLAG_GROWS_UP) ? 'U'
1135     : (kve_flags & KINFO_VME_FLAG_GROWS_DOWN) ? 'D' : '-';
1136   vm_flags[8] = '\0';
1137
1138   return vm_flags;
1139 }
1140
1141 /* See fbsd-tdep.h.  */
1142
1143 void
1144 fbsd_info_proc_mappings_header (int addr_bit)
1145 {
1146   printf_filtered (_("Mapped address spaces:\n\n"));
1147   if (addr_bit == 64)
1148     {
1149       printf_filtered ("  %18s %18s %10s %10s %9s %s\n",
1150                        "Start Addr",
1151                        "  End Addr",
1152                        "      Size", "    Offset", "Flags  ", "File");
1153     }
1154   else
1155     {
1156       printf_filtered ("\t%10s %10s %10s %10s %9s %s\n",
1157                        "Start Addr",
1158                        "  End Addr",
1159                        "      Size", "    Offset", "Flags  ", "File");
1160     }
1161 }
1162
1163 /* See fbsd-tdep.h.  */
1164
1165 void
1166 fbsd_info_proc_mappings_entry (int addr_bit, ULONGEST kve_start,
1167                                ULONGEST kve_end, ULONGEST kve_offset,
1168                                int kve_flags, int kve_protection,
1169                                const void *kve_path)
1170 {
1171   if (addr_bit == 64)
1172     {
1173       printf_filtered ("  %18s %18s %10s %10s %9s %s\n",
1174                        hex_string (kve_start),
1175                        hex_string (kve_end),
1176                        hex_string (kve_end - kve_start),
1177                        hex_string (kve_offset),
1178                        fbsd_vm_map_entry_flags (kve_flags, kve_protection),
1179                        reinterpret_cast<const char *> (kve_path));
1180     }
1181   else
1182     {
1183       printf_filtered ("\t%10s %10s %10s %10s %9s %s\n",
1184                        hex_string (kve_start),
1185                        hex_string (kve_end),
1186                        hex_string (kve_end - kve_start),
1187                        hex_string (kve_offset),
1188                        fbsd_vm_map_entry_flags (kve_flags, kve_protection),
1189                        reinterpret_cast<const char *> (kve_path));
1190     }
1191 }
1192
1193 /* Implement "info proc mappings" for a corefile.  */
1194
1195 static void
1196 fbsd_core_info_proc_mappings (struct gdbarch *gdbarch)
1197 {
1198   asection *section;
1199   unsigned char *descdata, *descend;
1200   size_t note_size;
1201
1202   section = bfd_get_section_by_name (core_bfd, ".note.freebsdcore.vmmap");
1203   if (section == NULL)
1204     {
1205       warning (_("unable to find mappings in core file"));
1206       return;
1207     }
1208
1209   note_size = bfd_get_section_size (section);
1210   if (note_size < 4)
1211     error (_("malformed core note - too short for header"));
1212
1213   gdb::def_vector<unsigned char> contents (note_size);
1214   if (!bfd_get_section_contents (core_bfd, section, contents.data (),
1215                                  0, note_size))
1216     error (_("could not get core note contents"));
1217
1218   descdata = contents.data ();
1219   descend = descdata + note_size;
1220
1221   /* Skip over the structure size.  */
1222   descdata += 4;
1223
1224   fbsd_info_proc_mappings_header (gdbarch_addr_bit (gdbarch));
1225   while (descdata + KVE_PATH < descend)
1226     {
1227       ULONGEST structsize = bfd_get_32 (core_bfd, descdata + KVE_STRUCTSIZE);
1228       if (structsize < KVE_PATH)
1229         error (_("malformed core note - vmmap entry too small"));
1230
1231       ULONGEST start = bfd_get_64 (core_bfd, descdata + KVE_START);
1232       ULONGEST end = bfd_get_64 (core_bfd, descdata + KVE_END);
1233       ULONGEST offset = bfd_get_64 (core_bfd, descdata + KVE_OFFSET);
1234       LONGEST flags = bfd_get_signed_32 (core_bfd, descdata + KVE_FLAGS);
1235       LONGEST prot = bfd_get_signed_32 (core_bfd, descdata + KVE_PROTECTION);
1236       fbsd_info_proc_mappings_entry (gdbarch_addr_bit (gdbarch), start, end,
1237                                      offset, flags, prot, descdata + KVE_PATH);
1238
1239       descdata += structsize;
1240     }
1241 }
1242
1243 /* Fetch the pathname of a vnode for a single file descriptor from the
1244    file table core note.  */
1245
1246 static gdb::unique_xmalloc_ptr<char>
1247 fbsd_core_vnode_path (struct gdbarch *gdbarch, int fd)
1248 {
1249   asection *section;
1250   unsigned char *descdata, *descend;
1251   size_t note_size;
1252
1253   section = bfd_get_section_by_name (core_bfd, ".note.freebsdcore.files");
1254   if (section == NULL)
1255     return nullptr;
1256
1257   note_size = bfd_get_section_size (section);
1258   if (note_size < 4)
1259     error (_("malformed core note - too short for header"));
1260
1261   gdb::def_vector<unsigned char> contents (note_size);
1262   if (!bfd_get_section_contents (core_bfd, section, contents.data (),
1263                                  0, note_size))
1264     error (_("could not get core note contents"));
1265
1266   descdata = contents.data ();
1267   descend = descdata + note_size;
1268
1269   /* Skip over the structure size.  */
1270   descdata += 4;
1271
1272   while (descdata + KF_PATH < descend)
1273     {
1274       ULONGEST structsize;
1275
1276       structsize = bfd_get_32 (core_bfd, descdata + KF_STRUCTSIZE);
1277       if (structsize < KF_PATH)
1278         error (_("malformed core note - file structure too small"));
1279
1280       if (bfd_get_32 (core_bfd, descdata + KF_TYPE) == KINFO_FILE_TYPE_VNODE
1281           && bfd_get_signed_32 (core_bfd, descdata + KF_FD) == fd)
1282         {
1283           char *path = (char *) descdata + KF_PATH;
1284           return gdb::unique_xmalloc_ptr<char> (xstrdup (path));
1285         }
1286
1287       descdata += structsize;
1288     }
1289   return nullptr;
1290 }
1291
1292 /* Helper function to read a struct timeval.  */
1293
1294 static void
1295 fbsd_core_fetch_timeval (struct gdbarch *gdbarch, unsigned char *data,
1296                          LONGEST &sec, ULONGEST &usec)
1297 {
1298   if (gdbarch_addr_bit (gdbarch) == 64)
1299     {
1300       sec = bfd_get_signed_64 (core_bfd, data);
1301       usec = bfd_get_64 (core_bfd, data + 8);
1302     }
1303   else if (bfd_get_arch (core_bfd) == bfd_arch_i386)
1304     {
1305       sec = bfd_get_signed_32 (core_bfd, data);
1306       usec = bfd_get_32 (core_bfd, data + 4);
1307     }
1308   else
1309     {
1310       sec = bfd_get_signed_64 (core_bfd, data);
1311       usec = bfd_get_32 (core_bfd, data + 8);
1312     }
1313 }
1314
1315 /* Print out the contents of a signal set.  */
1316
1317 static void
1318 fbsd_print_sigset (const char *descr, unsigned char *sigset)
1319 {
1320   printf_filtered ("%s: ", descr);
1321   for (int i = 0; i < SIG_WORDS; i++)
1322     printf_filtered ("%08x ",
1323                      (unsigned int) bfd_get_32 (core_bfd, sigset + i * 4));
1324   printf_filtered ("\n");
1325 }
1326
1327 /* Implement "info proc status" for a corefile.  */
1328
1329 static void
1330 fbsd_core_info_proc_status (struct gdbarch *gdbarch)
1331 {
1332   const struct kinfo_proc_layout *kp;
1333   asection *section;
1334   unsigned char *descdata;
1335   int addr_bit, long_bit;
1336   size_t note_size;
1337   ULONGEST value;
1338   LONGEST sec;
1339
1340   section = bfd_get_section_by_name (core_bfd, ".note.freebsdcore.proc");
1341   if (section == NULL)
1342     {
1343       warning (_("unable to find process info in core file"));
1344       return;
1345     }
1346
1347   addr_bit = gdbarch_addr_bit (gdbarch);
1348   if (addr_bit == 64)
1349     kp = &kinfo_proc_layout_64;
1350   else if (bfd_get_arch (core_bfd) == bfd_arch_i386)
1351     kp = &kinfo_proc_layout_i386;
1352   else
1353     kp = &kinfo_proc_layout_32;
1354   long_bit = gdbarch_long_bit (gdbarch);
1355
1356   /*
1357    * Ensure that the note is large enough for all of the fields fetched
1358    * by this function.  In particular, the note must contain the 32-bit
1359    * structure size, then it must be long enough to access the last
1360    * field used (ki_rusage_ch.ru_majflt) which is the size of a long.
1361    */
1362   note_size = bfd_get_section_size (section);
1363   if (note_size < (4 + kp->ki_rusage_ch + kp->ru_majflt
1364                    + long_bit / TARGET_CHAR_BIT))
1365     error (_("malformed core note - too short"));
1366
1367   gdb::def_vector<unsigned char> contents (note_size);
1368   if (!bfd_get_section_contents (core_bfd, section, contents.data (),
1369                                  0, note_size))
1370     error (_("could not get core note contents"));
1371
1372   descdata = contents.data ();
1373
1374   /* Skip over the structure size.  */
1375   descdata += 4;
1376
1377   /* Verify 'ki_layout' is 0.  */
1378   if (bfd_get_32 (core_bfd, descdata + kp->ki_layout) != 0)
1379     {
1380       warning (_("unsupported process information in core file"));
1381       return;
1382     }
1383
1384   printf_filtered ("Name: %.19s\n", descdata + kp->ki_comm);
1385   printf_filtered ("Process ID: %s\n",
1386                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_pid)));
1387   printf_filtered ("Parent process: %s\n",
1388                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_ppid)));
1389   printf_filtered ("Process group: %s\n",
1390                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_pgid)));
1391   printf_filtered ("Session id: %s\n",
1392                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_sid)));
1393
1394   /* FreeBSD 12.0 and later store a 64-bit dev_t at 'ki_tdev'.  Older
1395      kernels store a 32-bit dev_t at 'ki_tdev_freebsd11'.  In older
1396      kernels the 64-bit 'ki_tdev' field is in a reserved section of
1397      the structure that is cleared to zero.  Assume that a zero value
1398      in ki_tdev indicates a core dump from an older kernel and use the
1399      value in 'ki_tdev_freebsd11' instead.  */
1400   value = bfd_get_64 (core_bfd, descdata + kp->ki_tdev);
1401   if (value == 0)
1402     value = bfd_get_32 (core_bfd, descdata + kp->ki_tdev_freebsd11);
1403   printf_filtered ("TTY: %s\n", pulongest (value));
1404   printf_filtered ("TTY owner process group: %s\n",
1405                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_tpgid)));
1406   printf_filtered ("User IDs (real, effective, saved): %s %s %s\n",
1407                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_ruid)),
1408                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_uid)),
1409                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_svuid)));
1410   printf_filtered ("Group IDs (real, effective, saved): %s %s %s\n",
1411                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_rgid)),
1412                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_groups)),
1413                    pulongest (bfd_get_32 (core_bfd, descdata + kp->ki_svgid)));
1414   printf_filtered ("Groups: ");
1415   uint16_t ngroups = bfd_get_16 (core_bfd, descdata + kp->ki_ngroups);
1416   for (int i = 0; i < ngroups; i++)
1417     printf_filtered ("%s ",
1418                      pulongest (bfd_get_32 (core_bfd,
1419                                             descdata + kp->ki_groups + i * 4)));
1420   printf_filtered ("\n");
1421   value = bfd_get (long_bit, core_bfd,
1422                    descdata + kp->ki_rusage + kp->ru_minflt);
1423   printf_filtered ("Minor faults (no memory page): %s\n", pulongest (value));
1424   value = bfd_get (long_bit, core_bfd,
1425                    descdata + kp->ki_rusage_ch + kp->ru_minflt);
1426   printf_filtered ("Minor faults, children: %s\n", pulongest (value));
1427   value = bfd_get (long_bit, core_bfd,
1428                    descdata + kp->ki_rusage + kp->ru_majflt);
1429   printf_filtered ("Major faults (memory page faults): %s\n",
1430                    pulongest (value));
1431   value = bfd_get (long_bit, core_bfd,
1432                    descdata + kp->ki_rusage_ch + kp->ru_majflt);
1433   printf_filtered ("Major faults, children: %s\n", pulongest (value));
1434   fbsd_core_fetch_timeval (gdbarch,
1435                            descdata + kp->ki_rusage + kp->ru_utime,
1436                            sec, value);
1437   printf_filtered ("utime: %s.%06d\n", plongest (sec), (int) value);
1438   fbsd_core_fetch_timeval (gdbarch,
1439                            descdata + kp->ki_rusage + kp->ru_stime,
1440                            sec, value);
1441   printf_filtered ("stime: %s.%06d\n", plongest (sec), (int) value);
1442   fbsd_core_fetch_timeval (gdbarch,
1443                            descdata + kp->ki_rusage_ch + kp->ru_utime,
1444                            sec, value);
1445   printf_filtered ("utime, children: %s.%06d\n", plongest (sec), (int) value);
1446   fbsd_core_fetch_timeval (gdbarch,
1447                            descdata + kp->ki_rusage_ch + kp->ru_stime,
1448                            sec, value);
1449   printf_filtered ("stime, children: %s.%06d\n", plongest (sec), (int) value);
1450   printf_filtered ("'nice' value: %d\n",
1451                    bfd_get_signed_8 (core_bfd, descdata + kp->ki_nice));
1452   fbsd_core_fetch_timeval (gdbarch, descdata + kp->ki_start, sec, value);
1453   printf_filtered ("Start time: %s.%06d\n", plongest (sec), (int) value);
1454   printf_filtered ("Virtual memory size: %s kB\n",
1455                    pulongest (bfd_get (addr_bit, core_bfd,
1456                                        descdata + kp->ki_size) / 1024));
1457   printf_filtered ("Data size: %s pages\n",
1458                    pulongest (bfd_get (addr_bit, core_bfd,
1459                                        descdata + kp->ki_dsize)));
1460   printf_filtered ("Stack size: %s pages\n",
1461                    pulongest (bfd_get (addr_bit, core_bfd,
1462                                        descdata + kp->ki_ssize)));
1463   printf_filtered ("Text size: %s pages\n",
1464                    pulongest (bfd_get (addr_bit, core_bfd,
1465                                        descdata + kp->ki_tsize)));
1466   printf_filtered ("Resident set size: %s pages\n",
1467                    pulongest (bfd_get (addr_bit, core_bfd,
1468                                        descdata + kp->ki_rssize)));
1469   printf_filtered ("Maximum RSS: %s pages\n",
1470                    pulongest (bfd_get (long_bit, core_bfd,
1471                                        descdata + kp->ki_rusage
1472                                        + kp->ru_maxrss)));
1473   fbsd_print_sigset ("Ignored Signals", descdata + kp->ki_sigignore);
1474   fbsd_print_sigset ("Caught Signals", descdata + kp->ki_sigcatch);
1475 }
1476
1477 /* Implement the "core_info_proc" gdbarch method.  */
1478
1479 static void
1480 fbsd_core_info_proc (struct gdbarch *gdbarch, const char *args,
1481                      enum info_proc_what what)
1482 {
1483   bool do_cmdline = false;
1484   bool do_cwd = false;
1485   bool do_exe = false;
1486   bool do_files = false;
1487   bool do_mappings = false;
1488   bool do_status = false;
1489   int pid;
1490
1491   switch (what)
1492     {
1493     case IP_MINIMAL:
1494       do_cmdline = true;
1495       do_cwd = true;
1496       do_exe = true;
1497       break;
1498     case IP_MAPPINGS:
1499       do_mappings = true;
1500       break;
1501     case IP_STATUS:
1502     case IP_STAT:
1503       do_status = true;
1504       break;
1505     case IP_CMDLINE:
1506       do_cmdline = true;
1507       break;
1508     case IP_EXE:
1509       do_exe = true;
1510       break;
1511     case IP_CWD:
1512       do_cwd = true;
1513       break;
1514     case IP_FILES:
1515       do_files = true;
1516       break;
1517     case IP_ALL:
1518       do_cmdline = true;
1519       do_cwd = true;
1520       do_exe = true;
1521       do_files = true;
1522       do_mappings = true;
1523       do_status = true;
1524       break;
1525     default:
1526       return;
1527     }
1528
1529   pid = bfd_core_file_pid (core_bfd);
1530   if (pid != 0)
1531     printf_filtered (_("process %d\n"), pid);
1532
1533   if (do_cmdline)
1534     {
1535       const char *cmdline;
1536
1537       cmdline = bfd_core_file_failing_command (core_bfd);
1538       if (cmdline)
1539         printf_filtered ("cmdline = '%s'\n", cmdline);
1540       else
1541         warning (_("Command line unavailable"));
1542     }
1543   if (do_cwd)
1544     {
1545       gdb::unique_xmalloc_ptr<char> cwd =
1546         fbsd_core_vnode_path (gdbarch, KINFO_FILE_FD_TYPE_CWD);
1547       if (cwd)
1548         printf_filtered ("cwd = '%s'\n", cwd.get ());
1549       else
1550         warning (_("unable to read current working directory"));
1551     }
1552   if (do_exe)
1553     {
1554       gdb::unique_xmalloc_ptr<char> exe =
1555         fbsd_core_vnode_path (gdbarch, KINFO_FILE_FD_TYPE_TEXT);
1556       if (exe)
1557         printf_filtered ("exe = '%s'\n", exe.get ());
1558       else
1559         warning (_("unable to read executable path name"));
1560     }
1561   if (do_files)
1562     fbsd_core_info_proc_files (gdbarch);
1563   if (do_mappings)
1564     fbsd_core_info_proc_mappings (gdbarch);
1565   if (do_status)
1566     fbsd_core_info_proc_status (gdbarch);
1567 }
1568
1569 /* Print descriptions of FreeBSD-specific AUXV entries to FILE.  */
1570
1571 static void
1572 fbsd_print_auxv_entry (struct gdbarch *gdbarch, struct ui_file *file,
1573                        CORE_ADDR type, CORE_ADDR val)
1574 {
1575   const char *name = "???";
1576   const char *description = "";
1577   enum auxv_format format = AUXV_FORMAT_HEX;
1578
1579   switch (type)
1580     {
1581     case AT_NULL:
1582     case AT_IGNORE:
1583     case AT_EXECFD:
1584     case AT_PHDR:
1585     case AT_PHENT:
1586     case AT_PHNUM:
1587     case AT_PAGESZ:
1588     case AT_BASE:
1589     case AT_FLAGS:
1590     case AT_ENTRY:
1591     case AT_NOTELF:
1592     case AT_UID:
1593     case AT_EUID:
1594     case AT_GID:
1595     case AT_EGID:
1596       default_print_auxv_entry (gdbarch, file, type, val);
1597       return;
1598 #define _TAGNAME(tag) #tag
1599 #define TAGNAME(tag) _TAGNAME(AT_##tag)
1600 #define TAG(tag, text, kind) \
1601       case AT_FREEBSD_##tag: name = TAGNAME(tag); description = text; format = kind; break
1602       TAG (EXECPATH, _("Executable path"), AUXV_FORMAT_STR);
1603       TAG (CANARY, _("Canary for SSP"), AUXV_FORMAT_HEX);
1604       TAG (CANARYLEN, ("Length of the SSP canary"), AUXV_FORMAT_DEC);
1605       TAG (OSRELDATE, _("OSRELDATE"), AUXV_FORMAT_DEC);
1606       TAG (NCPUS, _("Number of CPUs"), AUXV_FORMAT_DEC);
1607       TAG (PAGESIZES, _("Pagesizes"), AUXV_FORMAT_HEX);
1608       TAG (PAGESIZESLEN, _("Number of pagesizes"), AUXV_FORMAT_DEC);
1609       TAG (TIMEKEEP, _("Pointer to timehands"), AUXV_FORMAT_HEX);
1610       TAG (STACKPROT, _("Initial stack protection"), AUXV_FORMAT_HEX);
1611       TAG (EHDRFLAGS, _("ELF header e_flags"), AUXV_FORMAT_HEX);
1612       TAG (HWCAP, _("Machine-dependent CPU capability hints"), AUXV_FORMAT_HEX);
1613       TAG (HWCAP2, _("Extension of AT_HWCAP"), AUXV_FORMAT_HEX);
1614     }
1615
1616   fprint_auxv_entry (file, name, description, format, type, val);
1617 }
1618
1619 /* Implement the "get_siginfo_type" gdbarch method.  */
1620
1621 static struct type *
1622 fbsd_get_siginfo_type (struct gdbarch *gdbarch)
1623 {
1624   struct fbsd_gdbarch_data *fbsd_gdbarch_data;
1625   struct type *int_type, *int32_type, *uint32_type, *long_type, *void_ptr_type;
1626   struct type *uid_type, *pid_type;
1627   struct type *sigval_type, *reason_type;
1628   struct type *siginfo_type;
1629   struct type *type;
1630
1631   fbsd_gdbarch_data = get_fbsd_gdbarch_data (gdbarch);
1632   if (fbsd_gdbarch_data->siginfo_type != NULL)
1633     return fbsd_gdbarch_data->siginfo_type;
1634
1635   int_type = arch_integer_type (gdbarch, gdbarch_int_bit (gdbarch),
1636                                 0, "int");
1637   int32_type = arch_integer_type (gdbarch, 32, 0, "int32_t");
1638   uint32_type = arch_integer_type (gdbarch, 32, 1, "uint32_t");
1639   long_type = arch_integer_type (gdbarch, gdbarch_long_bit (gdbarch),
1640                                  0, "long");
1641   void_ptr_type = lookup_pointer_type (builtin_type (gdbarch)->builtin_void);
1642
1643   /* union sigval */
1644   sigval_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_UNION);
1645   TYPE_NAME (sigval_type) = xstrdup ("sigval");
1646   append_composite_type_field (sigval_type, "sival_int", int_type);
1647   append_composite_type_field (sigval_type, "sival_ptr", void_ptr_type);
1648
1649   /* __pid_t */
1650   pid_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
1651                         TYPE_LENGTH (int32_type) * TARGET_CHAR_BIT, "__pid_t");
1652   TYPE_TARGET_TYPE (pid_type) = int32_type;
1653   TYPE_TARGET_STUB (pid_type) = 1;
1654
1655   /* __uid_t */
1656   uid_type = arch_type (gdbarch, TYPE_CODE_TYPEDEF,
1657                         TYPE_LENGTH (uint32_type) * TARGET_CHAR_BIT,
1658                         "__uid_t");
1659   TYPE_TARGET_TYPE (uid_type) = uint32_type;
1660   TYPE_TARGET_STUB (uid_type) = 1;
1661
1662   /* _reason */
1663   reason_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_UNION);
1664
1665   /* _fault */
1666   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
1667   append_composite_type_field (type, "si_trapno", int_type);
1668   append_composite_type_field (reason_type, "_fault", type);
1669
1670   /* _timer */
1671   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
1672   append_composite_type_field (type, "si_timerid", int_type);
1673   append_composite_type_field (type, "si_overrun", int_type);
1674   append_composite_type_field (reason_type, "_timer", type);
1675
1676   /* _mesgq */
1677   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
1678   append_composite_type_field (type, "si_mqd", int_type);
1679   append_composite_type_field (reason_type, "_mesgq", type);
1680
1681   /* _poll */
1682   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
1683   append_composite_type_field (type, "si_band", long_type);
1684   append_composite_type_field (reason_type, "_poll", type);
1685
1686   /* __spare__ */
1687   type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
1688   append_composite_type_field (type, "__spare1__", long_type);
1689   append_composite_type_field (type, "__spare2__",
1690                                init_vector_type (int_type, 7));
1691   append_composite_type_field (reason_type, "__spare__", type);
1692
1693   /* struct siginfo */
1694   siginfo_type = arch_composite_type (gdbarch, NULL, TYPE_CODE_STRUCT);
1695   TYPE_NAME (siginfo_type) = xstrdup ("siginfo");
1696   append_composite_type_field (siginfo_type, "si_signo", int_type);
1697   append_composite_type_field (siginfo_type, "si_errno", int_type);
1698   append_composite_type_field (siginfo_type, "si_code", int_type);
1699   append_composite_type_field (siginfo_type, "si_pid", pid_type);
1700   append_composite_type_field (siginfo_type, "si_uid", uid_type);
1701   append_composite_type_field (siginfo_type, "si_status", int_type);
1702   append_composite_type_field (siginfo_type, "si_addr", void_ptr_type);
1703   append_composite_type_field (siginfo_type, "si_value", sigval_type);
1704   append_composite_type_field (siginfo_type, "_reason", reason_type);
1705
1706   fbsd_gdbarch_data->siginfo_type = siginfo_type;
1707
1708   return siginfo_type;
1709 }
1710
1711 /* Implement the "gdb_signal_from_target" gdbarch method.  */
1712
1713 static enum gdb_signal
1714 fbsd_gdb_signal_from_target (struct gdbarch *gdbarch, int signal)
1715 {
1716   switch (signal)
1717     {
1718     case 0:
1719       return GDB_SIGNAL_0;
1720
1721     case FREEBSD_SIGHUP:
1722       return GDB_SIGNAL_HUP;
1723
1724     case FREEBSD_SIGINT:
1725       return GDB_SIGNAL_INT;
1726
1727     case FREEBSD_SIGQUIT:
1728       return GDB_SIGNAL_QUIT;
1729
1730     case FREEBSD_SIGILL:
1731       return GDB_SIGNAL_ILL;
1732
1733     case FREEBSD_SIGTRAP:
1734       return GDB_SIGNAL_TRAP;
1735
1736     case FREEBSD_SIGABRT:
1737       return GDB_SIGNAL_ABRT;
1738
1739     case FREEBSD_SIGEMT:
1740       return GDB_SIGNAL_EMT;
1741
1742     case FREEBSD_SIGFPE:
1743       return GDB_SIGNAL_FPE;
1744
1745     case FREEBSD_SIGKILL:
1746       return GDB_SIGNAL_KILL;
1747
1748     case FREEBSD_SIGBUS:
1749       return GDB_SIGNAL_BUS;
1750
1751     case FREEBSD_SIGSEGV:
1752       return GDB_SIGNAL_SEGV;
1753
1754     case FREEBSD_SIGSYS:
1755       return GDB_SIGNAL_SYS;
1756
1757     case FREEBSD_SIGPIPE:
1758       return GDB_SIGNAL_PIPE;
1759
1760     case FREEBSD_SIGALRM:
1761       return GDB_SIGNAL_ALRM;
1762
1763     case FREEBSD_SIGTERM:
1764       return GDB_SIGNAL_TERM;
1765
1766     case FREEBSD_SIGURG:
1767       return GDB_SIGNAL_URG;
1768
1769     case FREEBSD_SIGSTOP:
1770       return GDB_SIGNAL_STOP;
1771
1772     case FREEBSD_SIGTSTP:
1773       return GDB_SIGNAL_TSTP;
1774
1775     case FREEBSD_SIGCONT:
1776       return GDB_SIGNAL_CONT;
1777
1778     case FREEBSD_SIGCHLD:
1779       return GDB_SIGNAL_CHLD;
1780
1781     case FREEBSD_SIGTTIN:
1782       return GDB_SIGNAL_TTIN;
1783
1784     case FREEBSD_SIGTTOU:
1785       return GDB_SIGNAL_TTOU;
1786
1787     case FREEBSD_SIGIO:
1788       return GDB_SIGNAL_IO;
1789
1790     case FREEBSD_SIGXCPU:
1791       return GDB_SIGNAL_XCPU;
1792
1793     case FREEBSD_SIGXFSZ:
1794       return GDB_SIGNAL_XFSZ;
1795
1796     case FREEBSD_SIGVTALRM:
1797       return GDB_SIGNAL_VTALRM;
1798
1799     case FREEBSD_SIGPROF:
1800       return GDB_SIGNAL_PROF;
1801
1802     case FREEBSD_SIGWINCH:
1803       return GDB_SIGNAL_WINCH;
1804
1805     case FREEBSD_SIGINFO:
1806       return GDB_SIGNAL_INFO;
1807
1808     case FREEBSD_SIGUSR1:
1809       return GDB_SIGNAL_USR1;
1810
1811     case FREEBSD_SIGUSR2:
1812       return GDB_SIGNAL_USR2;
1813
1814     /* SIGTHR is the same as SIGLWP on FreeBSD. */
1815     case FREEBSD_SIGTHR:
1816       return GDB_SIGNAL_LWP;
1817
1818     case FREEBSD_SIGLIBRT:
1819       return GDB_SIGNAL_LIBRT;
1820     }
1821
1822   if (signal >= FREEBSD_SIGRTMIN && signal <= FREEBSD_SIGRTMAX)
1823     {
1824       int offset = signal - FREEBSD_SIGRTMIN;
1825
1826       return (enum gdb_signal) ((int) GDB_SIGNAL_REALTIME_65 + offset);
1827     }
1828
1829   return GDB_SIGNAL_UNKNOWN;
1830 }
1831
1832 /* Implement the "gdb_signal_to_target" gdbarch method.  */
1833
1834 static int
1835 fbsd_gdb_signal_to_target (struct gdbarch *gdbarch,
1836                 enum gdb_signal signal)
1837 {
1838   switch (signal)
1839     {
1840     case GDB_SIGNAL_0:
1841       return 0;
1842
1843     case GDB_SIGNAL_HUP:
1844       return FREEBSD_SIGHUP;
1845
1846     case GDB_SIGNAL_INT:
1847       return FREEBSD_SIGINT;
1848
1849     case GDB_SIGNAL_QUIT:
1850       return FREEBSD_SIGQUIT;
1851
1852     case GDB_SIGNAL_ILL:
1853       return FREEBSD_SIGILL;
1854
1855     case GDB_SIGNAL_TRAP:
1856       return FREEBSD_SIGTRAP;
1857
1858     case GDB_SIGNAL_ABRT:
1859       return FREEBSD_SIGABRT;
1860
1861     case GDB_SIGNAL_EMT:
1862       return FREEBSD_SIGEMT;
1863
1864     case GDB_SIGNAL_FPE:
1865       return FREEBSD_SIGFPE;
1866
1867     case GDB_SIGNAL_KILL:
1868       return FREEBSD_SIGKILL;
1869
1870     case GDB_SIGNAL_BUS:
1871       return FREEBSD_SIGBUS;
1872
1873     case GDB_SIGNAL_SEGV:
1874       return FREEBSD_SIGSEGV;
1875
1876     case GDB_SIGNAL_SYS:
1877       return FREEBSD_SIGSYS;
1878
1879     case GDB_SIGNAL_PIPE:
1880       return FREEBSD_SIGPIPE;
1881
1882     case GDB_SIGNAL_ALRM:
1883       return FREEBSD_SIGALRM;
1884
1885     case GDB_SIGNAL_TERM:
1886       return FREEBSD_SIGTERM;
1887
1888     case GDB_SIGNAL_URG:
1889       return FREEBSD_SIGURG;
1890
1891     case GDB_SIGNAL_STOP:
1892       return FREEBSD_SIGSTOP;
1893
1894     case GDB_SIGNAL_TSTP:
1895       return FREEBSD_SIGTSTP;
1896
1897     case GDB_SIGNAL_CONT:
1898       return FREEBSD_SIGCONT;
1899
1900     case GDB_SIGNAL_CHLD:
1901       return FREEBSD_SIGCHLD;
1902
1903     case GDB_SIGNAL_TTIN:
1904       return FREEBSD_SIGTTIN;
1905
1906     case GDB_SIGNAL_TTOU:
1907       return FREEBSD_SIGTTOU;
1908
1909     case GDB_SIGNAL_IO:
1910       return FREEBSD_SIGIO;
1911
1912     case GDB_SIGNAL_XCPU:
1913       return FREEBSD_SIGXCPU;
1914
1915     case GDB_SIGNAL_XFSZ:
1916       return FREEBSD_SIGXFSZ;
1917
1918     case GDB_SIGNAL_VTALRM:
1919       return FREEBSD_SIGVTALRM;
1920
1921     case GDB_SIGNAL_PROF:
1922       return FREEBSD_SIGPROF;
1923
1924     case GDB_SIGNAL_WINCH:
1925       return FREEBSD_SIGWINCH;
1926
1927     case GDB_SIGNAL_INFO:
1928       return FREEBSD_SIGINFO;
1929
1930     case GDB_SIGNAL_USR1:
1931       return FREEBSD_SIGUSR1;
1932
1933     case GDB_SIGNAL_USR2:
1934       return FREEBSD_SIGUSR2;
1935
1936     case GDB_SIGNAL_LWP:
1937       return FREEBSD_SIGTHR;
1938
1939     case GDB_SIGNAL_LIBRT:
1940       return FREEBSD_SIGLIBRT;
1941     }
1942
1943   if (signal >= GDB_SIGNAL_REALTIME_65
1944       && signal <= GDB_SIGNAL_REALTIME_126)
1945     {
1946       int offset = signal - GDB_SIGNAL_REALTIME_65;
1947
1948       return FREEBSD_SIGRTMIN + offset;
1949     }
1950
1951   return -1;
1952 }
1953
1954 /* Implement the "get_syscall_number" gdbarch method.  */
1955
1956 static LONGEST
1957 fbsd_get_syscall_number (struct gdbarch *gdbarch, thread_info *thread)
1958 {
1959
1960   /* FreeBSD doesn't use gdbarch_get_syscall_number since FreeBSD
1961      native targets fetch the system call number from the
1962      'pl_syscall_code' member of struct ptrace_lwpinfo in fbsd_wait.
1963      However, system call catching requires this function to be
1964      set.  */
1965
1966   internal_error (__FILE__, __LINE__, _("fbsd_get_sycall_number called"));
1967 }
1968
1969 /* Read an integer symbol value from the current target.  */
1970
1971 static LONGEST
1972 fbsd_read_integer_by_name (struct gdbarch *gdbarch, const char *name)
1973 {
1974   bound_minimal_symbol ms = lookup_minimal_symbol (name, NULL, NULL);
1975   if (ms.minsym == NULL)
1976     error (_("Unable to resolve symbol '%s'"), name);
1977
1978   gdb_byte buf[4];
1979   if (target_read_memory (BMSYMBOL_VALUE_ADDRESS (ms), buf, sizeof buf) != 0)
1980     error (_("Unable to read value of '%s'"), name);
1981
1982   return extract_signed_integer (buf, sizeof buf, gdbarch_byte_order (gdbarch));
1983 }
1984
1985 /* Lookup offsets of fields in the runtime linker's 'Obj_Entry'
1986    structure needed to determine the TLS index of an object file.  */
1987
1988 static void
1989 fbsd_fetch_rtld_offsets (struct gdbarch *gdbarch, struct fbsd_pspace_data *data)
1990 {
1991   TRY
1992     {
1993       /* Fetch offsets from debug symbols in rtld.  */
1994       struct symbol *obj_entry_sym
1995         = lookup_symbol_in_language ("Struct_Obj_Entry", NULL, STRUCT_DOMAIN,
1996                                      language_c, NULL).symbol;
1997       if (obj_entry_sym == NULL)
1998         error (_("Unable to find Struct_Obj_Entry symbol"));
1999       data->off_linkmap = lookup_struct_elt (SYMBOL_TYPE(obj_entry_sym),
2000                                              "linkmap", 0).offset / 8;
2001       data->off_tlsindex = lookup_struct_elt (SYMBOL_TYPE(obj_entry_sym),
2002                                               "tlsindex", 0).offset / 8;
2003       data->rtld_offsets_valid = true;
2004       return;
2005     }
2006   CATCH (e, RETURN_MASK_ERROR)
2007     {
2008       data->off_linkmap = -1;
2009     }
2010   END_CATCH
2011
2012   TRY
2013     {
2014       /* Fetch offsets from global variables in libthr.  Note that
2015          this does not work for single-threaded processes that are not
2016          linked against libthr.  */
2017       data->off_linkmap = fbsd_read_integer_by_name (gdbarch,
2018                                                      "_thread_off_linkmap");
2019       data->off_tlsindex = fbsd_read_integer_by_name (gdbarch,
2020                                                       "_thread_off_tlsindex");
2021       data->rtld_offsets_valid = true;
2022       return;
2023     }
2024   CATCH (e, RETURN_MASK_ERROR)
2025     {
2026       data->off_linkmap = -1;
2027     }
2028   END_CATCH
2029 }
2030
2031 /* Helper function to read the TLS index of an object file associated
2032    with a link map entry at LM_ADDR.  */
2033
2034 static LONGEST
2035 fbsd_get_tls_index (struct gdbarch *gdbarch, CORE_ADDR lm_addr)
2036 {
2037   struct fbsd_pspace_data *data = get_fbsd_pspace_data (current_program_space);
2038
2039   if (!data->rtld_offsets_valid)
2040     fbsd_fetch_rtld_offsets (gdbarch, data);
2041
2042   if (data->off_linkmap == -1)
2043     throw_error (TLS_GENERIC_ERROR,
2044                  _("Cannot fetch runtime linker structure offsets"));
2045
2046   /* Simulate container_of to convert from LM_ADDR to the Obj_Entry
2047      pointer and then compute the offset of the tlsindex member.  */
2048   CORE_ADDR tlsindex_addr = lm_addr - data->off_linkmap + data->off_tlsindex;
2049
2050   gdb_byte buf[4];
2051   if (target_read_memory (tlsindex_addr, buf, sizeof buf) != 0)
2052     throw_error (TLS_GENERIC_ERROR,
2053                  _("Cannot find thread-local variables on this target"));
2054
2055   return extract_signed_integer (buf, sizeof buf, gdbarch_byte_order (gdbarch));
2056 }
2057
2058 /* See fbsd-tdep.h.  */
2059
2060 CORE_ADDR
2061 fbsd_get_thread_local_address (struct gdbarch *gdbarch, CORE_ADDR dtv_addr,
2062                                CORE_ADDR lm_addr, CORE_ADDR offset)
2063 {
2064   LONGEST tls_index = fbsd_get_tls_index (gdbarch, lm_addr);
2065
2066   gdb_byte buf[gdbarch_ptr_bit (gdbarch) / TARGET_CHAR_BIT];
2067   if (target_read_memory (dtv_addr, buf, sizeof buf) != 0)
2068     throw_error (TLS_GENERIC_ERROR,
2069                  _("Cannot find thread-local variables on this target"));
2070
2071   const struct builtin_type *builtin = builtin_type (gdbarch);
2072   CORE_ADDR addr = gdbarch_pointer_to_address (gdbarch,
2073                                                builtin->builtin_data_ptr, buf);
2074
2075   addr += (tls_index + 1) * TYPE_LENGTH (builtin->builtin_data_ptr);
2076   if (target_read_memory (addr, buf, sizeof buf) != 0)
2077     throw_error (TLS_GENERIC_ERROR,
2078                  _("Cannot find thread-local variables on this target"));
2079
2080   addr = gdbarch_pointer_to_address (gdbarch, builtin->builtin_data_ptr, buf);
2081   return addr + offset;
2082 }
2083
2084 /* To be called from GDB_OSABI_FREEBSD handlers. */
2085
2086 void
2087 fbsd_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
2088 {
2089   set_gdbarch_core_pid_to_str (gdbarch, fbsd_core_pid_to_str);
2090   set_gdbarch_core_thread_name (gdbarch, fbsd_core_thread_name);
2091   set_gdbarch_core_xfer_siginfo (gdbarch, fbsd_core_xfer_siginfo);
2092   set_gdbarch_make_corefile_notes (gdbarch, fbsd_make_corefile_notes);
2093   set_gdbarch_core_info_proc (gdbarch, fbsd_core_info_proc);
2094   set_gdbarch_print_auxv_entry (gdbarch, fbsd_print_auxv_entry);
2095   set_gdbarch_get_siginfo_type (gdbarch, fbsd_get_siginfo_type);
2096   set_gdbarch_gdb_signal_from_target (gdbarch, fbsd_gdb_signal_from_target);
2097   set_gdbarch_gdb_signal_to_target (gdbarch, fbsd_gdb_signal_to_target);
2098
2099   /* `catch syscall' */
2100   set_xml_syscall_file_name (gdbarch, "syscalls/freebsd.xml");
2101   set_gdbarch_get_syscall_number (gdbarch, fbsd_get_syscall_number);
2102 }
2103
2104 void
2105 _initialize_fbsd_tdep (void)
2106 {
2107   fbsd_gdbarch_data_handle =
2108     gdbarch_data_register_post_init (init_fbsd_gdbarch_data);
2109   fbsd_pspace_data_handle
2110     = register_program_space_data_with_cleanup (NULL, fbsd_pspace_data_cleanup);
2111 }