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