Pull out common parts of _initialize_{i386,amd64}_linux_nat
[external/binutils.git] / gdb / i386-linux-nat.c
1 /* Native-dependent code for GNU/Linux i386.
2
3    Copyright (C) 1999-2014 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 "i386-nat.h"
22 #include "inferior.h"
23 #include "gdbcore.h"
24 #include "regcache.h"
25 #include "regset.h"
26 #include "target.h"
27 #include "linux-nat.h"
28 #include "nat/linux-btrace.h"
29 #include "btrace.h"
30
31 #include "gdb_assert.h"
32 #include <string.h>
33 #include "elf/common.h"
34 #include <sys/uio.h>
35 #include <sys/ptrace.h>
36 #include <sys/user.h>
37 #include <sys/procfs.h>
38
39 #ifdef HAVE_SYS_REG_H
40 #include <sys/reg.h>
41 #endif
42
43 #ifndef ORIG_EAX
44 #define ORIG_EAX -1
45 #endif
46
47 #ifdef HAVE_SYS_DEBUGREG_H
48 #include <sys/debugreg.h>
49 #endif
50
51 /* Prototypes for supply_gregset etc.  */
52 #include "gregset.h"
53
54 #include "i387-tdep.h"
55 #include "i386-tdep.h"
56 #include "i386-linux-tdep.h"
57
58 /* Defines ps_err_e, struct ps_prochandle.  */
59 #include "gdb_proc_service.h"
60
61 #include "i386-xstate.h"
62
63 #ifndef PTRACE_GETREGSET
64 #define PTRACE_GETREGSET        0x4204
65 #endif
66
67 #ifndef PTRACE_SETREGSET
68 #define PTRACE_SETREGSET        0x4205
69 #endif
70
71 /* Per-thread arch-specific data we want to keep.  */
72
73 struct arch_lwp_info
74 {
75   /* Non-zero if our copy differs from what's recorded in the thread.  */
76   int debug_registers_changed;
77 };
78
79 /* Does the current host support PTRACE_GETREGSET?  */
80 static int have_ptrace_getregset = -1;
81 \f
82
83 /* The register sets used in GNU/Linux ELF core-dumps are identical to
84    the register sets in `struct user' that is used for a.out
85    core-dumps, and is also used by `ptrace'.  The corresponding types
86    are `elf_gregset_t' for the general-purpose registers (with
87    `elf_greg_t' the type of a single GP register) and `elf_fpregset_t'
88    for the floating-point registers.
89
90    Those types used to be available under the names `gregset_t' and
91    `fpregset_t' too, and this file used those names in the past.  But
92    those names are now used for the register sets used in the
93    `mcontext_t' type, and have a different size and layout.  */
94
95 /* Which ptrace request retrieves which registers?
96    These apply to the corresponding SET requests as well.  */
97
98 #define GETREGS_SUPPLIES(regno) \
99   ((0 <= (regno) && (regno) <= 15) || (regno) == I386_LINUX_ORIG_EAX_REGNUM)
100
101 #define GETFPXREGS_SUPPLIES(regno) \
102   (I386_ST0_REGNUM <= (regno) && (regno) < I386_SSE_NUM_REGS)
103
104 #define GETXSTATEREGS_SUPPLIES(regno) \
105   (I386_ST0_REGNUM <= (regno) && (regno) < I386_AVX512_NUM_REGS)
106
107 /* Does the current host support the GETREGS request?  */
108 int have_ptrace_getregs =
109 #ifdef HAVE_PTRACE_GETREGS
110   1
111 #else
112   0
113 #endif
114 ;
115
116 /* Does the current host support the GETFPXREGS request?  The header
117    file may or may not define it, and even if it is defined, the
118    kernel will return EIO if it's running on a pre-SSE processor.
119
120    My instinct is to attach this to some architecture- or
121    target-specific data structure, but really, a particular GDB
122    process can only run on top of one kernel at a time.  So it's okay
123    for this to be a simple variable.  */
124 int have_ptrace_getfpxregs =
125 #ifdef HAVE_PTRACE_GETFPXREGS
126   -1
127 #else
128   0
129 #endif
130 ;
131 \f
132
133 /* Accessing registers through the U area, one at a time.  */
134
135 /* Fetch one register.  */
136
137 static void
138 fetch_register (struct regcache *regcache, int regno)
139 {
140   int tid;
141   int val;
142
143   gdb_assert (!have_ptrace_getregs);
144   if (i386_linux_gregset_reg_offset[regno] == -1)
145     {
146       regcache_raw_supply (regcache, regno, NULL);
147       return;
148     }
149
150   /* GNU/Linux LWP ID's are process ID's.  */
151   tid = ptid_get_lwp (inferior_ptid);
152   if (tid == 0)
153     tid = ptid_get_pid (inferior_ptid); /* Not a threaded program.  */
154
155   errno = 0;
156   val = ptrace (PTRACE_PEEKUSER, tid,
157                 i386_linux_gregset_reg_offset[regno], 0);
158   if (errno != 0)
159     error (_("Couldn't read register %s (#%d): %s."), 
160            gdbarch_register_name (get_regcache_arch (regcache), regno),
161            regno, safe_strerror (errno));
162
163   regcache_raw_supply (regcache, regno, &val);
164 }
165
166 /* Store one register.  */
167
168 static void
169 store_register (const struct regcache *regcache, int regno)
170 {
171   int tid;
172   int val;
173
174   gdb_assert (!have_ptrace_getregs);
175   if (i386_linux_gregset_reg_offset[regno] == -1)
176     return;
177
178   /* GNU/Linux LWP ID's are process ID's.  */
179   tid = ptid_get_lwp (inferior_ptid);
180   if (tid == 0)
181     tid = ptid_get_pid (inferior_ptid); /* Not a threaded program.  */
182
183   errno = 0;
184   regcache_raw_collect (regcache, regno, &val);
185   ptrace (PTRACE_POKEUSER, tid,
186           i386_linux_gregset_reg_offset[regno], val);
187   if (errno != 0)
188     error (_("Couldn't write register %s (#%d): %s."),
189            gdbarch_register_name (get_regcache_arch (regcache), regno),
190            regno, safe_strerror (errno));
191 }
192 \f
193
194 /* Transfering the general-purpose registers between GDB, inferiors
195    and core files.  */
196
197 /* Fill GDB's register array with the general-purpose register values
198    in *GREGSETP.  */
199
200 void
201 supply_gregset (struct regcache *regcache, const elf_gregset_t *gregsetp)
202 {
203   const gdb_byte *regp = (const gdb_byte *) gregsetp;
204   int i;
205
206   for (i = 0; i < I386_NUM_GREGS; i++)
207     regcache_raw_supply (regcache, i,
208                          regp + i386_linux_gregset_reg_offset[i]);
209
210   if (I386_LINUX_ORIG_EAX_REGNUM
211         < gdbarch_num_regs (get_regcache_arch (regcache)))
212     regcache_raw_supply (regcache, I386_LINUX_ORIG_EAX_REGNUM, regp
213                          + i386_linux_gregset_reg_offset[I386_LINUX_ORIG_EAX_REGNUM]);
214 }
215
216 /* Fill register REGNO (if it is a general-purpose register) in
217    *GREGSETPS with the value in GDB's register array.  If REGNO is -1,
218    do this for all registers.  */
219
220 void
221 fill_gregset (const struct regcache *regcache,
222               elf_gregset_t *gregsetp, int regno)
223 {
224   gdb_byte *regp = (gdb_byte *) gregsetp;
225   int i;
226
227   for (i = 0; i < I386_NUM_GREGS; i++)
228     if (regno == -1 || regno == i)
229       regcache_raw_collect (regcache, i,
230                             regp + i386_linux_gregset_reg_offset[i]);
231
232   if ((regno == -1 || regno == I386_LINUX_ORIG_EAX_REGNUM)
233       && I386_LINUX_ORIG_EAX_REGNUM
234            < gdbarch_num_regs (get_regcache_arch (regcache)))
235     regcache_raw_collect (regcache, I386_LINUX_ORIG_EAX_REGNUM, regp
236                           + i386_linux_gregset_reg_offset[I386_LINUX_ORIG_EAX_REGNUM]);
237 }
238
239 #ifdef HAVE_PTRACE_GETREGS
240
241 /* Fetch all general-purpose registers from process/thread TID and
242    store their values in GDB's register array.  */
243
244 static void
245 fetch_regs (struct regcache *regcache, int tid)
246 {
247   elf_gregset_t regs;
248   elf_gregset_t *regs_p = &regs;
249
250   if (ptrace (PTRACE_GETREGS, tid, 0, (int) &regs) < 0)
251     {
252       if (errno == EIO)
253         {
254           /* The kernel we're running on doesn't support the GETREGS
255              request.  Reset `have_ptrace_getregs'.  */
256           have_ptrace_getregs = 0;
257           return;
258         }
259
260       perror_with_name (_("Couldn't get registers"));
261     }
262
263   supply_gregset (regcache, (const elf_gregset_t *) regs_p);
264 }
265
266 /* Store all valid general-purpose registers in GDB's register array
267    into the process/thread specified by TID.  */
268
269 static void
270 store_regs (const struct regcache *regcache, int tid, int regno)
271 {
272   elf_gregset_t regs;
273
274   if (ptrace (PTRACE_GETREGS, tid, 0, (int) &regs) < 0)
275     perror_with_name (_("Couldn't get registers"));
276
277   fill_gregset (regcache, &regs, regno);
278   
279   if (ptrace (PTRACE_SETREGS, tid, 0, (int) &regs) < 0)
280     perror_with_name (_("Couldn't write registers"));
281 }
282
283 #else
284
285 static void fetch_regs (struct regcache *regcache, int tid) {}
286 static void store_regs (const struct regcache *regcache, int tid, int regno) {}
287
288 #endif
289 \f
290
291 /* Transfering floating-point registers between GDB, inferiors and cores.  */
292
293 /* Fill GDB's register array with the floating-point register values in
294    *FPREGSETP.  */
295
296 void 
297 supply_fpregset (struct regcache *regcache, const elf_fpregset_t *fpregsetp)
298 {
299   i387_supply_fsave (regcache, -1, fpregsetp);
300 }
301
302 /* Fill register REGNO (if it is a floating-point register) in
303    *FPREGSETP with the value in GDB's register array.  If REGNO is -1,
304    do this for all registers.  */
305
306 void
307 fill_fpregset (const struct regcache *regcache,
308                elf_fpregset_t *fpregsetp, int regno)
309 {
310   i387_collect_fsave (regcache, regno, fpregsetp);
311 }
312
313 #ifdef HAVE_PTRACE_GETREGS
314
315 /* Fetch all floating-point registers from process/thread TID and store
316    thier values in GDB's register array.  */
317
318 static void
319 fetch_fpregs (struct regcache *regcache, int tid)
320 {
321   elf_fpregset_t fpregs;
322
323   if (ptrace (PTRACE_GETFPREGS, tid, 0, (int) &fpregs) < 0)
324     perror_with_name (_("Couldn't get floating point status"));
325
326   supply_fpregset (regcache, (const elf_fpregset_t *) &fpregs);
327 }
328
329 /* Store all valid floating-point registers in GDB's register array
330    into the process/thread specified by TID.  */
331
332 static void
333 store_fpregs (const struct regcache *regcache, int tid, int regno)
334 {
335   elf_fpregset_t fpregs;
336
337   if (ptrace (PTRACE_GETFPREGS, tid, 0, (int) &fpregs) < 0)
338     perror_with_name (_("Couldn't get floating point status"));
339
340   fill_fpregset (regcache, &fpregs, regno);
341
342   if (ptrace (PTRACE_SETFPREGS, tid, 0, (int) &fpregs) < 0)
343     perror_with_name (_("Couldn't write floating point status"));
344 }
345
346 #else
347
348 static void
349 fetch_fpregs (struct regcache *regcache, int tid)
350 {
351 }
352
353 static void
354 store_fpregs (const struct regcache *regcache, int tid, int regno)
355 {
356 }
357
358 #endif
359 \f
360
361 /* Transfering floating-point and SSE registers to and from GDB.  */
362
363 /* Fetch all registers covered by the PTRACE_GETREGSET request from
364    process/thread TID and store their values in GDB's register array.
365    Return non-zero if successful, zero otherwise.  */
366
367 static int
368 fetch_xstateregs (struct regcache *regcache, int tid)
369 {
370   char xstateregs[I386_XSTATE_MAX_SIZE];
371   struct iovec iov;
372
373   if (!have_ptrace_getregset)
374     return 0;
375
376   iov.iov_base = xstateregs;
377   iov.iov_len = sizeof(xstateregs);
378   if (ptrace (PTRACE_GETREGSET, tid, (unsigned int) NT_X86_XSTATE,
379               &iov) < 0)
380     perror_with_name (_("Couldn't read extended state status"));
381
382   i387_supply_xsave (regcache, -1, xstateregs);
383   return 1;
384 }
385
386 /* Store all valid registers in GDB's register array covered by the
387    PTRACE_SETREGSET request into the process/thread specified by TID.
388    Return non-zero if successful, zero otherwise.  */
389
390 static int
391 store_xstateregs (const struct regcache *regcache, int tid, int regno)
392 {
393   char xstateregs[I386_XSTATE_MAX_SIZE];
394   struct iovec iov;
395
396   if (!have_ptrace_getregset)
397     return 0;
398   
399   iov.iov_base = xstateregs;
400   iov.iov_len = sizeof(xstateregs);
401   if (ptrace (PTRACE_GETREGSET, tid, (unsigned int) NT_X86_XSTATE,
402               &iov) < 0)
403     perror_with_name (_("Couldn't read extended state status"));
404
405   i387_collect_xsave (regcache, regno, xstateregs, 0);
406
407   if (ptrace (PTRACE_SETREGSET, tid, (unsigned int) NT_X86_XSTATE,
408               (int) &iov) < 0)
409     perror_with_name (_("Couldn't write extended state status"));
410
411   return 1;
412 }
413
414 #ifdef HAVE_PTRACE_GETFPXREGS
415
416 /* Fetch all registers covered by the PTRACE_GETFPXREGS request from
417    process/thread TID and store their values in GDB's register array.
418    Return non-zero if successful, zero otherwise.  */
419
420 static int
421 fetch_fpxregs (struct regcache *regcache, int tid)
422 {
423   elf_fpxregset_t fpxregs;
424
425   if (! have_ptrace_getfpxregs)
426     return 0;
427
428   if (ptrace (PTRACE_GETFPXREGS, tid, 0, (int) &fpxregs) < 0)
429     {
430       if (errno == EIO)
431         {
432           have_ptrace_getfpxregs = 0;
433           return 0;
434         }
435
436       perror_with_name (_("Couldn't read floating-point and SSE registers"));
437     }
438
439   i387_supply_fxsave (regcache, -1, (const elf_fpxregset_t *) &fpxregs);
440   return 1;
441 }
442
443 /* Store all valid registers in GDB's register array covered by the
444    PTRACE_SETFPXREGS request into the process/thread specified by TID.
445    Return non-zero if successful, zero otherwise.  */
446
447 static int
448 store_fpxregs (const struct regcache *regcache, int tid, int regno)
449 {
450   elf_fpxregset_t fpxregs;
451
452   if (! have_ptrace_getfpxregs)
453     return 0;
454   
455   if (ptrace (PTRACE_GETFPXREGS, tid, 0, &fpxregs) == -1)
456     {
457       if (errno == EIO)
458         {
459           have_ptrace_getfpxregs = 0;
460           return 0;
461         }
462
463       perror_with_name (_("Couldn't read floating-point and SSE registers"));
464     }
465
466   i387_collect_fxsave (regcache, regno, &fpxregs);
467
468   if (ptrace (PTRACE_SETFPXREGS, tid, 0, &fpxregs) == -1)
469     perror_with_name (_("Couldn't write floating-point and SSE registers"));
470
471   return 1;
472 }
473
474 #else
475
476 static int
477 fetch_fpxregs (struct regcache *regcache, int tid)
478 {
479   return 0;
480 }
481
482 static int
483 store_fpxregs (const struct regcache *regcache, int tid, int regno)
484 {
485   return 0;
486 }
487
488 #endif /* HAVE_PTRACE_GETFPXREGS */
489 \f
490
491 /* Transferring arbitrary registers between GDB and inferior.  */
492
493 /* Fetch register REGNO from the child process.  If REGNO is -1, do
494    this for all registers (including the floating point and SSE
495    registers).  */
496
497 static void
498 i386_linux_fetch_inferior_registers (struct target_ops *ops,
499                                      struct regcache *regcache, int regno)
500 {
501   int tid;
502
503   /* Use the old method of peeking around in `struct user' if the
504      GETREGS request isn't available.  */
505   if (!have_ptrace_getregs)
506     {
507       int i;
508
509       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
510         if (regno == -1 || regno == i)
511           fetch_register (regcache, i);
512
513       return;
514     }
515
516   /* GNU/Linux LWP ID's are process ID's.  */
517   tid = ptid_get_lwp (inferior_ptid);
518   if (tid == 0)
519     tid = ptid_get_pid (inferior_ptid); /* Not a threaded program.  */
520
521   /* Use the PTRACE_GETFPXREGS request whenever possible, since it
522      transfers more registers in one system call, and we'll cache the
523      results.  But remember that fetch_fpxregs can fail, and return
524      zero.  */
525   if (regno == -1)
526     {
527       fetch_regs (regcache, tid);
528
529       /* The call above might reset `have_ptrace_getregs'.  */
530       if (!have_ptrace_getregs)
531         {
532           i386_linux_fetch_inferior_registers (ops, regcache, regno);
533           return;
534         }
535
536       if (fetch_xstateregs (regcache, tid))
537         return;
538       if (fetch_fpxregs (regcache, tid))
539         return;
540       fetch_fpregs (regcache, tid);
541       return;
542     }
543
544   if (GETREGS_SUPPLIES (regno))
545     {
546       fetch_regs (regcache, tid);
547       return;
548     }
549
550   if (GETXSTATEREGS_SUPPLIES (regno))
551     {
552       if (fetch_xstateregs (regcache, tid))
553         return;
554     }
555
556   if (GETFPXREGS_SUPPLIES (regno))
557     {
558       if (fetch_fpxregs (regcache, tid))
559         return;
560
561       /* Either our processor or our kernel doesn't support the SSE
562          registers, so read the FP registers in the traditional way,
563          and fill the SSE registers with dummy values.  It would be
564          more graceful to handle differences in the register set using
565          gdbarch.  Until then, this will at least make things work
566          plausibly.  */
567       fetch_fpregs (regcache, tid);
568       return;
569     }
570
571   internal_error (__FILE__, __LINE__,
572                   _("Got request for bad register number %d."), regno);
573 }
574
575 /* Store register REGNO back into the child process.  If REGNO is -1,
576    do this for all registers (including the floating point and SSE
577    registers).  */
578 static void
579 i386_linux_store_inferior_registers (struct target_ops *ops,
580                                      struct regcache *regcache, int regno)
581 {
582   int tid;
583
584   /* Use the old method of poking around in `struct user' if the
585      SETREGS request isn't available.  */
586   if (!have_ptrace_getregs)
587     {
588       int i;
589
590       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
591         if (regno == -1 || regno == i)
592           store_register (regcache, i);
593
594       return;
595     }
596
597   /* GNU/Linux LWP ID's are process ID's.  */
598   tid = ptid_get_lwp (inferior_ptid);
599   if (tid == 0)
600     tid = ptid_get_pid (inferior_ptid); /* Not a threaded program.  */
601
602   /* Use the PTRACE_SETFPXREGS requests whenever possible, since it
603      transfers more registers in one system call.  But remember that
604      store_fpxregs can fail, and return zero.  */
605   if (regno == -1)
606     {
607       store_regs (regcache, tid, regno);
608       if (store_xstateregs (regcache, tid, regno))
609         return;
610       if (store_fpxregs (regcache, tid, regno))
611         return;
612       store_fpregs (regcache, tid, regno);
613       return;
614     }
615
616   if (GETREGS_SUPPLIES (regno))
617     {
618       store_regs (regcache, tid, regno);
619       return;
620     }
621
622   if (GETXSTATEREGS_SUPPLIES (regno))
623     {
624       if (store_xstateregs (regcache, tid, regno))
625         return;
626     }
627
628   if (GETFPXREGS_SUPPLIES (regno))
629     {
630       if (store_fpxregs (regcache, tid, regno))
631         return;
632
633       /* Either our processor or our kernel doesn't support the SSE
634          registers, so just write the FP registers in the traditional
635          way.  */
636       store_fpregs (regcache, tid, regno);
637       return;
638     }
639
640   internal_error (__FILE__, __LINE__,
641                   _("Got request to store bad register number %d."), regno);
642 }
643 \f
644
645 /* Support for debug registers.  */
646
647 /* Get debug register REGNUM value from only the one LWP of PTID.  */
648
649 static unsigned long
650 x86_linux_dr_get (ptid_t ptid, int regnum)
651 {
652   int tid;
653   unsigned long value;
654
655   tid = ptid_get_lwp (ptid);
656   if (tid == 0)
657     tid = ptid_get_pid (ptid);
658
659   errno = 0;
660   value = ptrace (PTRACE_PEEKUSER, tid,
661                   offsetof (struct user, u_debugreg[regnum]), 0);
662   if (errno != 0)
663     perror_with_name (_("Couldn't read debug register"));
664
665   return value;
666 }
667
668 /* Set debug register REGNUM to VALUE in only the one LWP of PTID.  */
669
670 static void
671 x86_linux_dr_set (ptid_t ptid, int regnum, unsigned long value)
672 {
673   int tid;
674
675   tid = ptid_get_lwp (ptid);
676   if (tid == 0)
677     tid = ptid_get_pid (ptid);
678
679   errno = 0;
680   ptrace (PTRACE_POKEUSER, tid,
681           offsetof (struct user, u_debugreg[regnum]), value);
682   if (errno != 0)
683     perror_with_name (_("Couldn't write debug register"));
684 }
685
686 /* Return the inferior's debug register REGNUM.  */
687
688 static CORE_ADDR
689 x86_linux_dr_get_addr (int regnum)
690 {
691   /* DR6 and DR7 are retrieved with some other way.  */
692   gdb_assert (DR_FIRSTADDR <= regnum && regnum <= DR_LASTADDR);
693
694   return x86_linux_dr_get (inferior_ptid, regnum);
695 }
696
697 /* Return the inferior's DR7 debug control register.  */
698
699 static unsigned long
700 x86_linux_dr_get_control (void)
701 {
702   return x86_linux_dr_get (inferior_ptid, DR_CONTROL);
703 }
704
705 /* Get DR_STATUS from only the one LWP of INFERIOR_PTID.  */
706
707 static unsigned long
708 x86_linux_dr_get_status (void)
709 {
710   return x86_linux_dr_get (inferior_ptid, DR_STATUS);
711 }
712
713 /* Callback for iterate_over_lwps.  Update the debug registers of
714    LWP.  */
715
716 static int
717 update_debug_registers_callback (struct lwp_info *lwp, void *arg)
718 {
719   if (lwp->arch_private == NULL)
720     lwp->arch_private = XCNEW (struct arch_lwp_info);
721
722   /* The actual update is done later just before resuming the lwp, we
723      just mark that the registers need updating.  */
724   lwp->arch_private->debug_registers_changed = 1;
725
726   /* If the lwp isn't stopped, force it to momentarily pause, so we
727      can update its debug registers.  */
728   if (!lwp->stopped)
729     linux_stop_lwp (lwp);
730
731   /* Continue the iteration.  */
732   return 0;
733 }
734
735 /* Set DR_CONTROL to ADDR in all LWPs of the current inferior.  */
736
737 static void
738 x86_linux_dr_set_control (unsigned long control)
739 {
740   ptid_t pid_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
741
742   iterate_over_lwps (pid_ptid, update_debug_registers_callback, NULL);
743 }
744
745 /* Set address REGNUM (zero based) to ADDR in all LWPs of the current
746    inferior.  */
747
748 static void
749 x86_linux_dr_set_addr (int regnum, CORE_ADDR addr)
750 {
751   ptid_t pid_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
752
753   gdb_assert (regnum >= 0 && regnum <= DR_LASTADDR - DR_FIRSTADDR);
754
755   iterate_over_lwps (pid_ptid, update_debug_registers_callback, NULL);
756 }
757
758 /* Called when resuming a thread.
759    If the debug regs have changed, update the thread's copies.  */
760
761 static void
762 x86_linux_prepare_to_resume (struct lwp_info *lwp)
763 {
764   int clear_status = 0;
765
766   /* NULL means this is the main thread still going through the shell,
767      or, no watchpoint has been set yet.  In that case, there's
768      nothing to do.  */
769   if (lwp->arch_private == NULL)
770     return;
771
772   if (lwp->arch_private->debug_registers_changed)
773     {
774       struct i386_debug_reg_state *state
775         = i386_debug_reg_state (ptid_get_pid (lwp->ptid));
776       int i;
777
778       /* See amd64_linux_prepare_to_resume for Linux kernel note on
779          i386_linux_dr_set calls ordering.  */
780
781       x86_linux_dr_set (lwp->ptid, DR_CONTROL, 0);
782
783       for (i = DR_FIRSTADDR; i <= DR_LASTADDR; i++)
784         if (state->dr_ref_count[i] > 0)
785           {
786             x86_linux_dr_set (lwp->ptid, i, state->dr_mirror[i]);
787
788             /* If we're setting a watchpoint, any change the inferior
789                had done itself to the debug registers needs to be
790                discarded, otherwise, i386_stopped_data_address can get
791                confused.  */
792             clear_status = 1;
793           }
794
795       if (state->dr_control_mirror != 0)
796         x86_linux_dr_set (lwp->ptid, DR_CONTROL, state->dr_control_mirror);
797
798       lwp->arch_private->debug_registers_changed = 0;
799     }
800
801   if (clear_status || lwp->stopped_by_watchpoint)
802     x86_linux_dr_set (lwp->ptid, DR_STATUS, 0);
803 }
804
805 static void
806 x86_linux_new_thread (struct lwp_info *lp)
807 {
808   struct arch_lwp_info *info = XCNEW (struct arch_lwp_info);
809
810   info->debug_registers_changed = 1;
811
812   lp->arch_private = info;
813 }
814
815 /* linux_nat_new_fork hook.   */
816
817 static void
818 x86_linux_new_fork (struct lwp_info *parent, pid_t child_pid)
819 {
820   pid_t parent_pid;
821   struct i386_debug_reg_state *parent_state;
822   struct i386_debug_reg_state *child_state;
823
824   /* NULL means no watchpoint has ever been set in the parent.  In
825      that case, there's nothing to do.  */
826   if (parent->arch_private == NULL)
827     return;
828
829   /* Linux kernel before 2.6.33 commit
830      72f674d203cd230426437cdcf7dd6f681dad8b0d
831      will inherit hardware debug registers from parent
832      on fork/vfork/clone.  Newer Linux kernels create such tasks with
833      zeroed debug registers.
834
835      GDB core assumes the child inherits the watchpoints/hw
836      breakpoints of the parent, and will remove them all from the
837      forked off process.  Copy the debug registers mirrors into the
838      new process so that all breakpoints and watchpoints can be
839      removed together.  The debug registers mirror will become zeroed
840      in the end before detaching the forked off process, thus making
841      this compatible with older Linux kernels too.  */
842
843   parent_pid = ptid_get_pid (parent->ptid);
844   parent_state = i386_debug_reg_state (parent_pid);
845   child_state = i386_debug_reg_state (child_pid);
846   *child_state = *parent_state;
847 }
848
849 \f
850
851 /* Helper for ps_get_thread_area.  Sets BASE_ADDR to a pointer to
852    the thread local storage (or its descriptor) and returns PS_OK
853    on success.  Returns PS_ERR on failure.  */
854
855 static ps_err_e
856 x86_linux_get_thread_area (pid_t pid, void *addr, unsigned int *base_addr)
857 {
858   /* NOTE: cagney/2003-08-26: The definition of this buffer is found
859      in the kernel header <asm-i386/ldt.h>.  It, after padding, is 4 x
860      4 byte integers in size: `entry_number', `base_addr', `limit',
861      and a bunch of status bits.
862
863      The values returned by this ptrace call should be part of the
864      regcache buffer, and ps_get_thread_area should channel its
865      request through the regcache.  That way remote targets could
866      provide the value using the remote protocol and not this direct
867      call.
868
869      Is this function needed?  I'm guessing that the `base' is the
870      address of a descriptor that libthread_db uses to find the
871      thread local address base that GDB needs.  Perhaps that
872      descriptor is defined by the ABI.  Anyway, given that
873      libthread_db calls this function without prompting (gdb
874      requesting tls base) I guess it needs info in there anyway.  */
875   unsigned int desc[4];
876
877   /* This code assumes that "int" is 32 bits and that
878      GET_THREAD_AREA returns no more than 4 int values.  */
879   gdb_assert (sizeof (int) == 4);
880
881 #ifndef PTRACE_GET_THREAD_AREA
882 #define PTRACE_GET_THREAD_AREA 25
883 #endif
884
885   if (ptrace (PTRACE_GET_THREAD_AREA, pid, addr, &desc) < 0)
886     return PS_ERR;
887
888   *base_addr = desc[1];
889   return PS_OK;
890 }
891
892 /* Called by libthread_db.  Returns a pointer to the thread local
893    storage (or its descriptor).  */
894
895 ps_err_e
896 ps_get_thread_area (const struct ps_prochandle *ph,
897                     lwpid_t lwpid, int idx, void **base)
898 {
899   unsigned int base_addr;
900   ps_err_e result;
901
902   result = x86_linux_get_thread_area (lwpid, (void *) idx, &base_addr);
903
904   if (result == PS_OK)
905     *(int *) base = base_addr;
906
907   return result;
908 }
909 \f
910
911 /* The instruction for a GNU/Linux system call is:
912        int $0x80
913    or 0xcd 0x80.  */
914
915 static const unsigned char linux_syscall[] = { 0xcd, 0x80 };
916
917 #define LINUX_SYSCALL_LEN (sizeof linux_syscall)
918
919 /* The system call number is stored in the %eax register.  */
920 #define LINUX_SYSCALL_REGNUM I386_EAX_REGNUM
921
922 /* We are specifically interested in the sigreturn and rt_sigreturn
923    system calls.  */
924
925 #ifndef SYS_sigreturn
926 #define SYS_sigreturn           0x77
927 #endif
928 #ifndef SYS_rt_sigreturn
929 #define SYS_rt_sigreturn        0xad
930 #endif
931
932 /* Offset to saved processor flags, from <asm/sigcontext.h>.  */
933 #define LINUX_SIGCONTEXT_EFLAGS_OFFSET (64)
934
935 /* Resume execution of the inferior process.
936    If STEP is nonzero, single-step it.
937    If SIGNAL is nonzero, give it that signal.  */
938
939 static void
940 i386_linux_resume (struct target_ops *ops,
941                    ptid_t ptid, int step, enum gdb_signal signal)
942 {
943   int pid = ptid_get_pid (ptid);
944
945   int request;
946
947   if (catch_syscall_enabled () > 0)
948    request = PTRACE_SYSCALL;
949   else
950     request = PTRACE_CONT;
951
952   if (step)
953     {
954       struct regcache *regcache = get_thread_regcache (pid_to_ptid (pid));
955       struct gdbarch *gdbarch = get_regcache_arch (regcache);
956       enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
957       ULONGEST pc;
958       gdb_byte buf[LINUX_SYSCALL_LEN];
959
960       request = PTRACE_SINGLESTEP;
961
962       regcache_cooked_read_unsigned (regcache,
963                                      gdbarch_pc_regnum (gdbarch), &pc);
964
965       /* Returning from a signal trampoline is done by calling a
966          special system call (sigreturn or rt_sigreturn, see
967          i386-linux-tdep.c for more information).  This system call
968          restores the registers that were saved when the signal was
969          raised, including %eflags.  That means that single-stepping
970          won't work.  Instead, we'll have to modify the signal context
971          that's about to be restored, and set the trace flag there.  */
972
973       /* First check if PC is at a system call.  */
974       if (target_read_memory (pc, buf, LINUX_SYSCALL_LEN) == 0
975           && memcmp (buf, linux_syscall, LINUX_SYSCALL_LEN) == 0)
976         {
977           ULONGEST syscall;
978           regcache_cooked_read_unsigned (regcache,
979                                          LINUX_SYSCALL_REGNUM, &syscall);
980
981           /* Then check the system call number.  */
982           if (syscall == SYS_sigreturn || syscall == SYS_rt_sigreturn)
983             {
984               ULONGEST sp, addr;
985               unsigned long int eflags;
986
987               regcache_cooked_read_unsigned (regcache, I386_ESP_REGNUM, &sp);
988               if (syscall == SYS_rt_sigreturn)
989                 addr = read_memory_unsigned_integer (sp + 8, 4, byte_order)
990                   + 20;
991               else
992                 addr = sp;
993
994               /* Set the trace flag in the context that's about to be
995                  restored.  */
996               addr += LINUX_SIGCONTEXT_EFLAGS_OFFSET;
997               read_memory (addr, (gdb_byte *) &eflags, 4);
998               eflags |= 0x0100;
999               write_memory (addr, (gdb_byte *) &eflags, 4);
1000             }
1001         }
1002     }
1003
1004   if (ptrace (request, pid, 0, gdb_signal_to_host (signal)) == -1)
1005     perror_with_name (("ptrace"));
1006 }
1007
1008 static void (*super_post_startup_inferior) (struct target_ops *self,
1009                                             ptid_t ptid);
1010
1011 static void
1012 x86_linux_child_post_startup_inferior (struct target_ops *self, ptid_t ptid)
1013 {
1014   i386_cleanup_dregs ();
1015   super_post_startup_inferior (self, ptid);
1016 }
1017
1018 #ifdef __x86_64__
1019 /* Value of CS segment register:
1020      64bit process: 0x33
1021      32bit process: 0x23  */
1022 #define AMD64_LINUX_USER64_CS 0x33
1023
1024 /* Value of DS segment register:
1025      LP64 process: 0x0
1026      X32 process: 0x2b  */
1027 #define AMD64_LINUX_X32_DS 0x2b
1028 #endif
1029
1030 /* Get Linux/x86 target description from running target.  */
1031
1032 static const struct target_desc *
1033 x86_linux_read_description (struct target_ops *ops)
1034 {
1035   int tid;
1036   int is_64bit = 0;
1037 #ifdef __x86_64__
1038   int is_x32;
1039 #endif
1040   static uint64_t xcr0;
1041   uint64_t xcr0_features_bits;
1042
1043   /* GNU/Linux LWP ID's are process ID's.  */
1044   tid = ptid_get_lwp (inferior_ptid);
1045   if (tid == 0)
1046     tid = ptid_get_pid (inferior_ptid); /* Not a threaded program.  */
1047
1048 #ifdef __x86_64__
1049   {
1050     unsigned long cs;
1051     unsigned long ds;
1052
1053     /* Get CS register.  */
1054     errno = 0;
1055     cs = ptrace (PTRACE_PEEKUSER, tid,
1056                  offsetof (struct user_regs_struct, cs), 0);
1057     if (errno != 0)
1058       perror_with_name (_("Couldn't get CS register"));
1059
1060     is_64bit = cs == AMD64_LINUX_USER64_CS;
1061
1062     /* Get DS register.  */
1063     errno = 0;
1064     ds = ptrace (PTRACE_PEEKUSER, tid,
1065                  offsetof (struct user_regs_struct, ds), 0);
1066     if (errno != 0)
1067       perror_with_name (_("Couldn't get DS register"));
1068
1069     is_x32 = ds == AMD64_LINUX_X32_DS;
1070
1071     if (sizeof (void *) == 4 && is_64bit && !is_x32)
1072       error (_("Can't debug 64-bit process with 32-bit GDB"));
1073   }
1074 #elif HAVE_PTRACE_GETFPXREGS
1075   if (have_ptrace_getfpxregs == -1)
1076     {
1077       elf_fpxregset_t fpxregs;
1078
1079       if (ptrace (PTRACE_GETFPXREGS, tid, 0, (int) &fpxregs) < 0)
1080         {
1081           have_ptrace_getfpxregs = 0;
1082           have_ptrace_getregset = 0;
1083           return tdesc_i386_mmx_linux;
1084         }
1085     }
1086 #endif
1087
1088   if (have_ptrace_getregset == -1)
1089     {
1090       uint64_t xstateregs[(I386_XSTATE_SSE_SIZE / sizeof (uint64_t))];
1091       struct iovec iov;
1092
1093       iov.iov_base = xstateregs;
1094       iov.iov_len = sizeof (xstateregs);
1095
1096       /* Check if PTRACE_GETREGSET works.  */
1097       if (ptrace (PTRACE_GETREGSET, tid,
1098                   (unsigned int) NT_X86_XSTATE, &iov) < 0)
1099         have_ptrace_getregset = 0;
1100       else
1101         {
1102           have_ptrace_getregset = 1;
1103
1104           /* Get XCR0 from XSAVE extended state.  */
1105           xcr0 = xstateregs[(I386_LINUX_XSAVE_XCR0_OFFSET
1106                              / sizeof (uint64_t))];
1107         }
1108     }
1109
1110   /* Check the native XCR0 only if PTRACE_GETREGSET is available.  If
1111      PTRACE_GETREGSET is not available then set xcr0_features_bits to
1112      zero so that the "no-features" descriptions are returned by the
1113      switches below.  */
1114   if (have_ptrace_getregset)
1115     xcr0_features_bits = xcr0 & I386_XSTATE_ALL_MASK;
1116   else
1117     xcr0_features_bits = 0;
1118
1119   if (is_64bit)
1120     {
1121 #ifdef __x86_64__
1122       switch (xcr0_features_bits)
1123         {
1124         case I386_XSTATE_MPX_AVX512_MASK:
1125         case I386_XSTATE_AVX512_MASK:
1126           if (is_x32)
1127             return tdesc_x32_avx512_linux;
1128           else
1129             return tdesc_amd64_avx512_linux;
1130         case I386_XSTATE_MPX_MASK:
1131           if (is_x32)
1132             return tdesc_x32_avx_linux; /* No MPX on x32 using AVX.  */
1133           else
1134             return tdesc_amd64_mpx_linux;
1135         case I386_XSTATE_AVX_MASK:
1136           if (is_x32)
1137             return tdesc_x32_avx_linux;
1138           else
1139             return tdesc_amd64_avx_linux;
1140         default:
1141           if (is_x32)
1142             return tdesc_x32_linux;
1143           else
1144             return tdesc_amd64_linux;
1145         }
1146 #endif
1147     }
1148   else
1149     {
1150       switch (xcr0_features_bits)
1151         {
1152         case I386_XSTATE_MPX_AVX512_MASK:
1153         case I386_XSTATE_AVX512_MASK:
1154           return tdesc_i386_avx512_linux;
1155         case I386_XSTATE_MPX_MASK:
1156           return tdesc_i386_mpx_linux;
1157         case I386_XSTATE_AVX_MASK:
1158           return tdesc_i386_avx_linux;
1159         default:
1160           return tdesc_i386_linux;
1161         }
1162     }
1163
1164   gdb_assert_not_reached ("failed to return tdesc");
1165 }
1166
1167 /* Enable branch tracing.  */
1168
1169 static struct btrace_target_info *
1170 x86_linux_enable_btrace (struct target_ops *self, ptid_t ptid)
1171 {
1172   struct btrace_target_info *tinfo;
1173   struct gdbarch *gdbarch;
1174
1175   errno = 0;
1176   tinfo = linux_enable_btrace (ptid);
1177
1178   if (tinfo == NULL)
1179     error (_("Could not enable branch tracing for %s: %s."),
1180            target_pid_to_str (ptid), safe_strerror (errno));
1181
1182   /* Fill in the size of a pointer in bits.  */
1183   gdbarch = target_thread_architecture (ptid);
1184   tinfo->ptr_bits = gdbarch_ptr_bit (gdbarch);
1185
1186   return tinfo;
1187 }
1188
1189 /* Disable branch tracing.  */
1190
1191 static void
1192 x86_linux_disable_btrace (struct target_ops *self,
1193                           struct btrace_target_info *tinfo)
1194 {
1195   enum btrace_error errcode = linux_disable_btrace (tinfo);
1196
1197   if (errcode != BTRACE_ERR_NONE)
1198     error (_("Could not disable branch tracing."));
1199 }
1200
1201 /* Teardown branch tracing.  */
1202
1203 static void
1204 x86_linux_teardown_btrace (struct target_ops *self,
1205                            struct btrace_target_info *tinfo)
1206 {
1207   /* Ignore errors.  */
1208   linux_disable_btrace (tinfo);
1209 }
1210
1211 static enum btrace_error
1212 x86_linux_read_btrace (struct target_ops *self,
1213                        VEC (btrace_block_s) **data,
1214                        struct btrace_target_info *btinfo,
1215                        enum btrace_read_type type)
1216 {
1217   return linux_read_btrace (data, btinfo, type);
1218 }
1219
1220 /* Create an x86 GNU/Linux target.  */
1221
1222 static struct target_ops *
1223 x86_linux_create_target (void)
1224 {
1225   /* Fill in the generic GNU/Linux methods.  */
1226   struct target_ops *t = linux_target ();
1227
1228   /* Initialize the debug register function vectors.  */
1229   i386_use_watchpoints (t);
1230   i386_dr_low.set_control = x86_linux_dr_set_control;
1231   i386_dr_low.set_addr = x86_linux_dr_set_addr;
1232   i386_dr_low.get_addr = x86_linux_dr_get_addr;
1233   i386_dr_low.get_status = x86_linux_dr_get_status;
1234   i386_dr_low.get_control = x86_linux_dr_get_control;
1235   i386_set_debug_register_length (sizeof (void *));
1236
1237   /* Override the GNU/Linux inferior startup hook.  */
1238   super_post_startup_inferior = t->to_post_startup_inferior;
1239   t->to_post_startup_inferior = x86_linux_child_post_startup_inferior;
1240
1241   /* Add the description reader.  */
1242   t->to_read_description = x86_linux_read_description;
1243
1244   /* Add btrace methods.  */
1245   t->to_supports_btrace = linux_supports_btrace;
1246   t->to_enable_btrace = x86_linux_enable_btrace;
1247   t->to_disable_btrace = x86_linux_disable_btrace;
1248   t->to_teardown_btrace = x86_linux_teardown_btrace;
1249   t->to_read_btrace = x86_linux_read_btrace;
1250
1251   return t;
1252 }
1253
1254 /* Add an x86 GNU/Linux target.  */
1255
1256 static void
1257 x86_linux_add_target (struct target_ops *t)
1258 {
1259   linux_nat_add_target (t);
1260   linux_nat_set_new_thread (t, x86_linux_new_thread);
1261   linux_nat_set_new_fork (t, x86_linux_new_fork);
1262   linux_nat_set_forget_process (t, i386_forget_process);
1263   linux_nat_set_prepare_to_resume (t, x86_linux_prepare_to_resume);
1264 }
1265
1266 /* -Wmissing-prototypes */
1267 extern initialize_file_ftype _initialize_i386_linux_nat;
1268
1269 void
1270 _initialize_i386_linux_nat (void)
1271 {
1272   /* Create a generic x86 GNU/Linux target.  */
1273   struct target_ops *t = x86_linux_create_target ();
1274
1275   /* Override the default ptrace resume method.  */
1276   t->to_resume = i386_linux_resume;
1277
1278   /* Add our register access methods.  */
1279   t->to_fetch_registers = i386_linux_fetch_inferior_registers;
1280   t->to_store_registers = i386_linux_store_inferior_registers;
1281
1282   /* Add the target.  */
1283   x86_linux_add_target (t);
1284 }