Use debug_printf to print debug message
[external/binutils.git] / gdb / aarch64-linux-nat.c
1 /* Native-dependent code for GNU/Linux AArch64.
2
3    Copyright (C) 2011-2015 Free Software Foundation, Inc.
4    Contributed by ARM Ltd.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22
23 #include "inferior.h"
24 #include "gdbcore.h"
25 #include "regcache.h"
26 #include "linux-nat.h"
27 #include "target-descriptions.h"
28 #include "auxv.h"
29 #include "gdbcmd.h"
30 #include "aarch64-tdep.h"
31 #include "aarch64-linux-tdep.h"
32 #include "aarch32-linux-nat.h"
33
34 #include "elf/external.h"
35 #include "elf/common.h"
36
37 #include <sys/ptrace.h>
38 #include <sys/utsname.h>
39 #include <asm/ptrace.h>
40
41 #include "gregset.h"
42
43 /* Defines ps_err_e, struct ps_prochandle.  */
44 #include "gdb_proc_service.h"
45
46 #ifndef TRAP_HWBKPT
47 #define TRAP_HWBKPT 0x0004
48 #endif
49
50 /* On GNU/Linux, threads are implemented as pseudo-processes, in which
51    case we may be tracing more than one process at a time.  In that
52    case, inferior_ptid will contain the main process ID and the
53    individual thread (process) ID.  get_thread_id () is used to get
54    the thread id if it's available, and the process id otherwise.  */
55
56 static int
57 get_thread_id (ptid_t ptid)
58 {
59   int tid = ptid_get_lwp (ptid);
60
61   if (0 == tid)
62     tid = ptid_get_pid (ptid);
63   return tid;
64 }
65
66 /* Macro definitions, data structures, and code for the hardware
67    breakpoint and hardware watchpoint support follow.  We use the
68    following abbreviations throughout the code:
69
70    hw - hardware
71    bp - breakpoint
72    wp - watchpoint  */
73
74 /* Maximum number of hardware breakpoint and watchpoint registers.
75    Neither of these values may exceed the width of dr_changed_t
76    measured in bits.  */
77
78 #define AARCH64_HBP_MAX_NUM 16
79 #define AARCH64_HWP_MAX_NUM 16
80
81 /* Alignment requirement in bytes for addresses written to
82    hardware breakpoint and watchpoint value registers.
83
84    A ptrace call attempting to set an address that does not meet the
85    alignment criteria will fail.  Limited support has been provided in
86    this port for unaligned watchpoints, such that from a GDB user
87    perspective, an unaligned watchpoint may be requested.
88
89    This is achieved by minimally enlarging the watched area to meet the
90    alignment requirement, and if necessary, splitting the watchpoint
91    over several hardware watchpoint registers.  */
92
93 #define AARCH64_HBP_ALIGNMENT 4
94 #define AARCH64_HWP_ALIGNMENT 8
95
96 /* The maximum length of a memory region that can be watched by one
97    hardware watchpoint register.  */
98
99 #define AARCH64_HWP_MAX_LEN_PER_REG 8
100
101 /* ptrace hardware breakpoint resource info is formatted as follows:
102
103    31             24             16               8              0
104    +---------------+--------------+---------------+---------------+
105    |   RESERVED    |   RESERVED   |   DEBUG_ARCH  |  NUM_SLOTS    |
106    +---------------+--------------+---------------+---------------+  */
107
108
109 /* Macros to extract fields from the hardware debug information word.  */
110 #define AARCH64_DEBUG_NUM_SLOTS(x) ((x) & 0xff)
111 #define AARCH64_DEBUG_ARCH(x) (((x) >> 8) & 0xff)
112
113 /* Macro for the expected version of the ARMv8-A debug architecture.  */
114 #define AARCH64_DEBUG_ARCH_V8 0x6
115
116 /* Number of hardware breakpoints/watchpoints the target supports.
117    They are initialized with values obtained via the ptrace calls
118    with NT_ARM_HW_BREAK and NT_ARM_HW_WATCH respectively.  */
119
120 static int aarch64_num_bp_regs;
121 static int aarch64_num_wp_regs;
122
123 /* Each bit of a variable of this type is used to indicate whether a
124    hardware breakpoint or watchpoint setting has been changed since
125    the last update.
126
127    Bit N corresponds to the Nth hardware breakpoint or watchpoint
128    setting which is managed in aarch64_debug_reg_state, where N is
129    valid between 0 and the total number of the hardware breakpoint or
130    watchpoint debug registers minus 1.
131
132    When bit N is 1, the corresponding breakpoint or watchpoint setting
133    has changed, and therefore the corresponding hardware debug
134    register needs to be updated via the ptrace interface.
135
136    In the per-thread arch-specific data area, we define two such
137    variables for per-thread hardware breakpoint and watchpoint
138    settings respectively.
139
140    This type is part of the mechanism which helps reduce the number of
141    ptrace calls to the kernel, i.e. avoid asking the kernel to write
142    to the debug registers with unchanged values.  */
143
144 typedef ULONGEST dr_changed_t;
145
146 /* Set each of the lower M bits of X to 1; assert X is wide enough.  */
147
148 #define DR_MARK_ALL_CHANGED(x, m)                                       \
149   do                                                                    \
150     {                                                                   \
151       gdb_assert (sizeof ((x)) * 8 >= (m));                             \
152       (x) = (((dr_changed_t)1 << (m)) - 1);                             \
153     } while (0)
154
155 #define DR_MARK_N_CHANGED(x, n)                                         \
156   do                                                                    \
157     {                                                                   \
158       (x) |= ((dr_changed_t)1 << (n));                                  \
159     } while (0)
160
161 #define DR_CLEAR_CHANGED(x)                                             \
162   do                                                                    \
163     {                                                                   \
164       (x) = 0;                                                          \
165     } while (0)
166
167 #define DR_HAS_CHANGED(x) ((x) != 0)
168 #define DR_N_HAS_CHANGED(x, n) ((x) & ((dr_changed_t)1 << (n)))
169
170 /* Structure for managing the hardware breakpoint/watchpoint resources.
171    DR_ADDR_* stores the address, DR_CTRL_* stores the control register
172    content, and DR_REF_COUNT_* counts the numbers of references to the
173    corresponding bp/wp, by which way the limited hardware resources
174    are not wasted on duplicated bp/wp settings (though so far gdb has
175    done a good job by not sending duplicated bp/wp requests).  */
176
177 struct aarch64_debug_reg_state
178 {
179   /* hardware breakpoint */
180   CORE_ADDR dr_addr_bp[AARCH64_HBP_MAX_NUM];
181   unsigned int dr_ctrl_bp[AARCH64_HBP_MAX_NUM];
182   unsigned int dr_ref_count_bp[AARCH64_HBP_MAX_NUM];
183
184   /* hardware watchpoint */
185   CORE_ADDR dr_addr_wp[AARCH64_HWP_MAX_NUM];
186   unsigned int dr_ctrl_wp[AARCH64_HWP_MAX_NUM];
187   unsigned int dr_ref_count_wp[AARCH64_HWP_MAX_NUM];
188 };
189
190 /* Per-process data.  We don't bind this to a per-inferior registry
191    because of targets like x86 GNU/Linux that need to keep track of
192    processes that aren't bound to any inferior (e.g., fork children,
193    checkpoints).  */
194
195 struct aarch64_process_info
196 {
197   /* Linked list.  */
198   struct aarch64_process_info *next;
199
200   /* The process identifier.  */
201   pid_t pid;
202
203   /* Copy of aarch64 hardware debug registers.  */
204   struct aarch64_debug_reg_state state;
205 };
206
207 static struct aarch64_process_info *aarch64_process_list = NULL;
208
209 /* Find process data for process PID.  */
210
211 static struct aarch64_process_info *
212 aarch64_find_process_pid (pid_t pid)
213 {
214   struct aarch64_process_info *proc;
215
216   for (proc = aarch64_process_list; proc; proc = proc->next)
217     if (proc->pid == pid)
218       return proc;
219
220   return NULL;
221 }
222
223 /* Add process data for process PID.  Returns newly allocated info
224    object.  */
225
226 static struct aarch64_process_info *
227 aarch64_add_process (pid_t pid)
228 {
229   struct aarch64_process_info *proc;
230
231   proc = xcalloc (1, sizeof (*proc));
232   proc->pid = pid;
233
234   proc->next = aarch64_process_list;
235   aarch64_process_list = proc;
236
237   return proc;
238 }
239
240 /* Get data specific info for process PID, creating it if necessary.
241    Never returns NULL.  */
242
243 static struct aarch64_process_info *
244 aarch64_process_info_get (pid_t pid)
245 {
246   struct aarch64_process_info *proc;
247
248   proc = aarch64_find_process_pid (pid);
249   if (proc == NULL)
250     proc = aarch64_add_process (pid);
251
252   return proc;
253 }
254
255 /* Called whenever GDB is no longer debugging process PID.  It deletes
256    data structures that keep track of debug register state.  */
257
258 static void
259 aarch64_forget_process (pid_t pid)
260 {
261   struct aarch64_process_info *proc, **proc_link;
262
263   proc = aarch64_process_list;
264   proc_link = &aarch64_process_list;
265
266   while (proc != NULL)
267     {
268       if (proc->pid == pid)
269         {
270           *proc_link = proc->next;
271
272           xfree (proc);
273           return;
274         }
275
276       proc_link = &proc->next;
277       proc = *proc_link;
278     }
279 }
280
281 /* Get debug registers state for process PID.  */
282
283 static struct aarch64_debug_reg_state *
284 aarch64_get_debug_reg_state (pid_t pid)
285 {
286   return &aarch64_process_info_get (pid)->state;
287 }
288
289 /* Per-thread arch-specific data we want to keep.  */
290
291 struct arch_lwp_info
292 {
293   /* When bit N is 1, it indicates the Nth hardware breakpoint or
294      watchpoint register pair needs to be updated when the thread is
295      resumed; see aarch64_linux_prepare_to_resume.  */
296   dr_changed_t dr_changed_bp;
297   dr_changed_t dr_changed_wp;
298 };
299
300 /* Call ptrace to set the thread TID's hardware breakpoint/watchpoint
301    registers with data from *STATE.  */
302
303 static void
304 aarch64_linux_set_debug_regs (const struct aarch64_debug_reg_state *state,
305                               int tid, int watchpoint)
306 {
307   int i, count;
308   struct iovec iov;
309   struct user_hwdebug_state regs;
310   const CORE_ADDR *addr;
311   const unsigned int *ctrl;
312
313   memset (&regs, 0, sizeof (regs));
314   iov.iov_base = &regs;
315   count = watchpoint ? aarch64_num_wp_regs : aarch64_num_bp_regs;
316   addr = watchpoint ? state->dr_addr_wp : state->dr_addr_bp;
317   ctrl = watchpoint ? state->dr_ctrl_wp : state->dr_ctrl_bp;
318   if (count == 0)
319     return;
320   iov.iov_len = (offsetof (struct user_hwdebug_state, dbg_regs[count - 1])
321                  + sizeof (regs.dbg_regs [count - 1]));
322
323   for (i = 0; i < count; i++)
324     {
325       regs.dbg_regs[i].addr = addr[i];
326       regs.dbg_regs[i].ctrl = ctrl[i];
327     }
328
329   if (ptrace (PTRACE_SETREGSET, tid,
330               watchpoint ? NT_ARM_HW_WATCH : NT_ARM_HW_BREAK,
331               (void *) &iov))
332     error (_("Unexpected error setting hardware debug registers"));
333 }
334
335 struct aarch64_dr_update_callback_param
336 {
337   int is_watchpoint;
338   unsigned int idx;
339 };
340
341 /* Callback for iterate_over_lwps.  Records the
342    information about the change of one hardware breakpoint/watchpoint
343    setting for the thread LWP.
344    The information is passed in via PTR.
345    N.B.  The actual updating of hardware debug registers is not
346    carried out until the moment the thread is resumed.  */
347
348 static int
349 debug_reg_change_callback (struct lwp_info *lwp, void *ptr)
350 {
351   struct aarch64_dr_update_callback_param *param_p
352     = (struct aarch64_dr_update_callback_param *) ptr;
353   int pid = get_thread_id (lwp->ptid);
354   int idx = param_p->idx;
355   int is_watchpoint = param_p->is_watchpoint;
356   struct arch_lwp_info *info = lwp->arch_private;
357   dr_changed_t *dr_changed_ptr;
358   dr_changed_t dr_changed;
359
360   if (info == NULL)
361     info = lwp->arch_private = XCNEW (struct arch_lwp_info);
362
363   if (show_debug_regs)
364     {
365       fprintf_unfiltered (gdb_stdlog,
366                           "debug_reg_change_callback: \n\tOn entry:\n");
367       fprintf_unfiltered (gdb_stdlog,
368                           "\tpid%d, dr_changed_bp=0x%s, "
369                           "dr_changed_wp=0x%s\n",
370                           pid, phex (info->dr_changed_bp, 8),
371                           phex (info->dr_changed_wp, 8));
372     }
373
374   dr_changed_ptr = is_watchpoint ? &info->dr_changed_wp
375     : &info->dr_changed_bp;
376   dr_changed = *dr_changed_ptr;
377
378   gdb_assert (idx >= 0
379               && (idx <= (is_watchpoint ? aarch64_num_wp_regs
380                           : aarch64_num_bp_regs)));
381
382   /* The actual update is done later just before resuming the lwp,
383      we just mark that one register pair needs updating.  */
384   DR_MARK_N_CHANGED (dr_changed, idx);
385   *dr_changed_ptr = dr_changed;
386
387   /* If the lwp isn't stopped, force it to momentarily pause, so
388      we can update its debug registers.  */
389   if (!lwp->stopped)
390     linux_stop_lwp (lwp);
391
392   if (show_debug_regs)
393     {
394       fprintf_unfiltered (gdb_stdlog,
395                           "\tOn exit:\n\tpid%d, dr_changed_bp=0x%s, "
396                           "dr_changed_wp=0x%s\n",
397                           pid, phex (info->dr_changed_bp, 8),
398                           phex (info->dr_changed_wp, 8));
399     }
400
401   /* Continue the iteration.  */
402   return 0;
403 }
404
405 /* Notify each thread that their IDXth breakpoint/watchpoint register
406    pair needs to be updated.  The message will be recorded in each
407    thread's arch-specific data area, the actual updating will be done
408    when the thread is resumed.  */
409
410 static void
411 aarch64_notify_debug_reg_change (const struct aarch64_debug_reg_state *state,
412                                  int is_watchpoint, unsigned int idx)
413 {
414   struct aarch64_dr_update_callback_param param;
415   ptid_t pid_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
416
417   param.is_watchpoint = is_watchpoint;
418   param.idx = idx;
419
420   iterate_over_lwps (pid_ptid, debug_reg_change_callback, (void *) &param);
421 }
422
423 /* Print the values of the cached breakpoint/watchpoint registers.  */
424
425 static void
426 aarch64_show_debug_reg_state (struct aarch64_debug_reg_state *state,
427                               const char *func, CORE_ADDR addr,
428                               int len, int type)
429 {
430   int i;
431
432   debug_printf ("%s", func);
433   if (addr || len)
434     debug_printf (" (addr=0x%08lx, len=%d, type=%s)",
435                   (unsigned long) addr, len,
436                   type == hw_write ? "hw-write-watchpoint"
437                   : (type == hw_read ? "hw-read-watchpoint"
438                      : (type == hw_access ? "hw-access-watchpoint"
439                         : (type == hw_execute ? "hw-breakpoint"
440                            : "??unknown??"))));
441   debug_printf (":\n");
442
443   debug_printf ("\tBREAKPOINTs:\n");
444   for (i = 0; i < aarch64_num_bp_regs; i++)
445     debug_printf ("\tBP%d: addr=0x%08lx, ctrl=0x%08x, ref.count=%d\n",
446                   i, state->dr_addr_bp[i],
447                   state->dr_ctrl_bp[i], state->dr_ref_count_bp[i]);
448
449   debug_printf ("\tWATCHPOINTs:\n");
450   for (i = 0; i < aarch64_num_wp_regs; i++)
451     debug_printf ("\tWP%d: addr=0x%08lx, ctrl=0x%08x, ref.count=%d\n",
452                   i, state->dr_addr_wp[i],
453                   state->dr_ctrl_wp[i], state->dr_ref_count_wp[i]);
454 }
455
456 /* Fill GDB's register array with the general-purpose register values
457    from the current thread.  */
458
459 static void
460 fetch_gregs_from_thread (struct regcache *regcache)
461 {
462   int ret, tid;
463   struct gdbarch *gdbarch = get_regcache_arch (regcache);
464   elf_gregset_t regs;
465   struct iovec iovec;
466
467   /* Make sure REGS can hold all registers contents on both aarch64
468      and arm.  */
469   gdb_static_assert (sizeof (regs) >= 18 * 4);
470
471   tid = get_thread_id (inferior_ptid);
472
473   iovec.iov_base = &regs;
474   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
475     iovec.iov_len = 18 * 4;
476   else
477     iovec.iov_len = sizeof (regs);
478
479   ret = ptrace (PTRACE_GETREGSET, tid, NT_PRSTATUS, &iovec);
480   if (ret < 0)
481     perror_with_name (_("Unable to fetch general registers."));
482
483   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
484     aarch32_gp_regcache_supply (regcache, (uint32_t *) regs, 1);
485   else
486     {
487       int regno;
488
489       for (regno = AARCH64_X0_REGNUM; regno <= AARCH64_CPSR_REGNUM; regno++)
490         regcache_raw_supply (regcache, regno, &regs[regno - AARCH64_X0_REGNUM]);
491     }
492 }
493
494 /* Store to the current thread the valid general-purpose register
495    values in the GDB's register array.  */
496
497 static void
498 store_gregs_to_thread (const struct regcache *regcache)
499 {
500   int ret, tid;
501   elf_gregset_t regs;
502   struct iovec iovec;
503   struct gdbarch *gdbarch = get_regcache_arch (regcache);
504
505   /* Make sure REGS can hold all registers contents on both aarch64
506      and arm.  */
507   gdb_static_assert (sizeof (regs) >= 18 * 4);
508   tid = get_thread_id (inferior_ptid);
509
510   iovec.iov_base = &regs;
511   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
512     iovec.iov_len = 18 * 4;
513   else
514     iovec.iov_len = sizeof (regs);
515
516   ret = ptrace (PTRACE_GETREGSET, tid, NT_PRSTATUS, &iovec);
517   if (ret < 0)
518     perror_with_name (_("Unable to fetch general registers."));
519
520   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
521     aarch32_gp_regcache_collect (regcache, (uint32_t *) regs, 1);
522   else
523     {
524       int regno;
525
526       for (regno = AARCH64_X0_REGNUM; regno <= AARCH64_CPSR_REGNUM; regno++)
527         if (REG_VALID == regcache_register_status (regcache, regno))
528           regcache_raw_collect (regcache, regno,
529                                 &regs[regno - AARCH64_X0_REGNUM]);
530     }
531
532   ret = ptrace (PTRACE_SETREGSET, tid, NT_PRSTATUS, &iovec);
533   if (ret < 0)
534     perror_with_name (_("Unable to store general registers."));
535 }
536
537 /* Fill GDB's register array with the fp/simd register values
538    from the current thread.  */
539
540 static void
541 fetch_fpregs_from_thread (struct regcache *regcache)
542 {
543   int ret, tid;
544   elf_fpregset_t regs;
545   struct iovec iovec;
546   struct gdbarch *gdbarch = get_regcache_arch (regcache);
547
548   /* Make sure REGS can hold all VFP registers contents on both aarch64
549      and arm.  */
550   gdb_static_assert (sizeof regs >= VFP_REGS_SIZE);
551
552   tid = get_thread_id (inferior_ptid);
553
554   iovec.iov_base = &regs;
555
556   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
557     {
558       iovec.iov_len = VFP_REGS_SIZE;
559
560       ret = ptrace (PTRACE_GETREGSET, tid, NT_ARM_VFP, &iovec);
561       if (ret < 0)
562         perror_with_name (_("Unable to fetch VFP registers."));
563
564       aarch32_vfp_regcache_supply (regcache, (gdb_byte *) &regs, 32);
565     }
566   else
567     {
568       int regno;
569
570       iovec.iov_len = sizeof (regs);
571
572       ret = ptrace (PTRACE_GETREGSET, tid, NT_FPREGSET, &iovec);
573       if (ret < 0)
574         perror_with_name (_("Unable to fetch vFP/SIMD registers."));
575
576       for (regno = AARCH64_V0_REGNUM; regno <= AARCH64_V31_REGNUM; regno++)
577         regcache_raw_supply (regcache, regno,
578                              &regs.vregs[regno - AARCH64_V0_REGNUM]);
579
580       regcache_raw_supply (regcache, AARCH64_FPSR_REGNUM, &regs.fpsr);
581       regcache_raw_supply (regcache, AARCH64_FPCR_REGNUM, &regs.fpcr);
582     }
583 }
584
585 /* Store to the current thread the valid fp/simd register
586    values in the GDB's register array.  */
587
588 static void
589 store_fpregs_to_thread (const struct regcache *regcache)
590 {
591   int ret, tid;
592   elf_fpregset_t regs;
593   struct iovec iovec;
594   struct gdbarch *gdbarch = get_regcache_arch (regcache);
595
596   /* Make sure REGS can hold all VFP registers contents on both aarch64
597      and arm.  */
598   gdb_static_assert (sizeof regs >= VFP_REGS_SIZE);
599   tid = get_thread_id (inferior_ptid);
600
601   iovec.iov_base = &regs;
602
603   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
604     {
605       iovec.iov_len = VFP_REGS_SIZE;
606
607       ret = ptrace (PTRACE_GETREGSET, tid, NT_ARM_VFP, &iovec);
608       if (ret < 0)
609         perror_with_name (_("Unable to fetch VFP registers."));
610
611       aarch32_vfp_regcache_collect (regcache, (gdb_byte *) &regs, 32);
612     }
613   else
614     {
615       int regno;
616
617       iovec.iov_len = sizeof (regs);
618
619       ret = ptrace (PTRACE_GETREGSET, tid, NT_FPREGSET, &iovec);
620       if (ret < 0)
621         perror_with_name (_("Unable to fetch FP/SIMD registers."));
622
623       for (regno = AARCH64_V0_REGNUM; regno <= AARCH64_V31_REGNUM; regno++)
624         if (REG_VALID == regcache_register_status (regcache, regno))
625           regcache_raw_collect (regcache, regno,
626                                 (char *) &regs.vregs[regno - AARCH64_V0_REGNUM]);
627
628       if (REG_VALID == regcache_register_status (regcache, AARCH64_FPSR_REGNUM))
629         regcache_raw_collect (regcache, AARCH64_FPSR_REGNUM,
630                               (char *) &regs.fpsr);
631       if (REG_VALID == regcache_register_status (regcache, AARCH64_FPCR_REGNUM))
632         regcache_raw_collect (regcache, AARCH64_FPCR_REGNUM,
633                               (char *) &regs.fpcr);
634     }
635
636   if (gdbarch_bfd_arch_info (gdbarch)->bits_per_word == 32)
637     {
638       ret = ptrace (PTRACE_SETREGSET, tid, NT_ARM_VFP, &iovec);
639       if (ret < 0)
640         perror_with_name (_("Unable to store VFP registers."));
641     }
642   else
643     {
644       ret = ptrace (PTRACE_SETREGSET, tid, NT_FPREGSET, &iovec);
645       if (ret < 0)
646         perror_with_name (_("Unable to store FP/SIMD registers."));
647     }
648 }
649
650 /* Implement the "to_fetch_register" target_ops method.  */
651
652 static void
653 aarch64_linux_fetch_inferior_registers (struct target_ops *ops,
654                                         struct regcache *regcache,
655                                         int regno)
656 {
657   if (regno == -1)
658     {
659       fetch_gregs_from_thread (regcache);
660       fetch_fpregs_from_thread (regcache);
661     }
662   else if (regno < AARCH64_V0_REGNUM)
663     fetch_gregs_from_thread (regcache);
664   else
665     fetch_fpregs_from_thread (regcache);
666 }
667
668 /* Implement the "to_store_register" target_ops method.  */
669
670 static void
671 aarch64_linux_store_inferior_registers (struct target_ops *ops,
672                                         struct regcache *regcache,
673                                         int regno)
674 {
675   if (regno == -1)
676     {
677       store_gregs_to_thread (regcache);
678       store_fpregs_to_thread (regcache);
679     }
680   else if (regno < AARCH64_V0_REGNUM)
681     store_gregs_to_thread (regcache);
682   else
683     store_fpregs_to_thread (regcache);
684 }
685
686 /* Fill register REGNO (if it is a general-purpose register) in
687    *GREGSETPS with the value in GDB's register array.  If REGNO is -1,
688    do this for all registers.  */
689
690 void
691 fill_gregset (const struct regcache *regcache,
692               gdb_gregset_t *gregsetp, int regno)
693 {
694   regcache_collect_regset (&aarch64_linux_gregset, regcache,
695                            regno, (gdb_byte *) gregsetp,
696                            AARCH64_LINUX_SIZEOF_GREGSET);
697 }
698
699 /* Fill GDB's register array with the general-purpose register values
700    in *GREGSETP.  */
701
702 void
703 supply_gregset (struct regcache *regcache, const gdb_gregset_t *gregsetp)
704 {
705   regcache_supply_regset (&aarch64_linux_gregset, regcache, -1,
706                           (const gdb_byte *) gregsetp,
707                           AARCH64_LINUX_SIZEOF_GREGSET);
708 }
709
710 /* Fill register REGNO (if it is a floating-point register) in
711    *FPREGSETP with the value in GDB's register array.  If REGNO is -1,
712    do this for all registers.  */
713
714 void
715 fill_fpregset (const struct regcache *regcache,
716                gdb_fpregset_t *fpregsetp, int regno)
717 {
718   regcache_collect_regset (&aarch64_linux_fpregset, regcache,
719                            regno, (gdb_byte *) fpregsetp,
720                            AARCH64_LINUX_SIZEOF_FPREGSET);
721 }
722
723 /* Fill GDB's register array with the floating-point register values
724    in *FPREGSETP.  */
725
726 void
727 supply_fpregset (struct regcache *regcache, const gdb_fpregset_t *fpregsetp)
728 {
729   regcache_supply_regset (&aarch64_linux_fpregset, regcache, -1,
730                           (const gdb_byte *) fpregsetp,
731                           AARCH64_LINUX_SIZEOF_FPREGSET);
732 }
733
734 /* Called when resuming a thread.
735    The hardware debug registers are updated when there is any change.  */
736
737 static void
738 aarch64_linux_prepare_to_resume (struct lwp_info *lwp)
739 {
740   struct arch_lwp_info *info = lwp->arch_private;
741
742   /* NULL means this is the main thread still going through the shell,
743      or, no watchpoint has been set yet.  In that case, there's
744      nothing to do.  */
745   if (info == NULL)
746     return;
747
748   if (DR_HAS_CHANGED (info->dr_changed_bp)
749       || DR_HAS_CHANGED (info->dr_changed_wp))
750     {
751       int tid = ptid_get_lwp (lwp->ptid);
752       struct aarch64_debug_reg_state *state
753         = aarch64_get_debug_reg_state (ptid_get_pid (lwp->ptid));
754
755       if (show_debug_regs)
756         fprintf_unfiltered (gdb_stdlog, "prepare_to_resume thread %d\n", tid);
757
758       /* Watchpoints.  */
759       if (DR_HAS_CHANGED (info->dr_changed_wp))
760         {
761           aarch64_linux_set_debug_regs (state, tid, 1);
762           DR_CLEAR_CHANGED (info->dr_changed_wp);
763         }
764
765       /* Breakpoints.  */
766       if (DR_HAS_CHANGED (info->dr_changed_bp))
767         {
768           aarch64_linux_set_debug_regs (state, tid, 0);
769           DR_CLEAR_CHANGED (info->dr_changed_bp);
770         }
771     }
772 }
773
774 static void
775 aarch64_linux_new_thread (struct lwp_info *lp)
776 {
777   struct arch_lwp_info *info = XCNEW (struct arch_lwp_info);
778
779   /* Mark that all the hardware breakpoint/watchpoint register pairs
780      for this thread need to be initialized.  */
781   DR_MARK_ALL_CHANGED (info->dr_changed_bp, aarch64_num_bp_regs);
782   DR_MARK_ALL_CHANGED (info->dr_changed_wp, aarch64_num_wp_regs);
783
784   lp->arch_private = info;
785 }
786
787 /* linux_nat_new_fork hook.   */
788
789 static void
790 aarch64_linux_new_fork (struct lwp_info *parent, pid_t child_pid)
791 {
792   pid_t parent_pid;
793   struct aarch64_debug_reg_state *parent_state;
794   struct aarch64_debug_reg_state *child_state;
795
796   /* NULL means no watchpoint has ever been set in the parent.  In
797      that case, there's nothing to do.  */
798   if (parent->arch_private == NULL)
799     return;
800
801   /* GDB core assumes the child inherits the watchpoints/hw
802      breakpoints of the parent, and will remove them all from the
803      forked off process.  Copy the debug registers mirrors into the
804      new process so that all breakpoints and watchpoints can be
805      removed together.  */
806
807   parent_pid = ptid_get_pid (parent->ptid);
808   parent_state = aarch64_get_debug_reg_state (parent_pid);
809   child_state = aarch64_get_debug_reg_state (child_pid);
810   *child_state = *parent_state;
811 }
812 \f
813
814 /* Called by libthread_db.  Returns a pointer to the thread local
815    storage (or its descriptor).  */
816
817 ps_err_e
818 ps_get_thread_area (const struct ps_prochandle *ph,
819                     lwpid_t lwpid, int idx, void **base)
820 {
821   struct iovec iovec;
822   uint64_t reg;
823
824   iovec.iov_base = &reg;
825   iovec.iov_len = sizeof (reg);
826
827   if (ptrace (PTRACE_GETREGSET, lwpid, NT_ARM_TLS, &iovec) != 0)
828     return PS_ERR;
829
830   /* IDX is the bias from the thread pointer to the beginning of the
831      thread descriptor.  It has to be subtracted due to implementation
832      quirks in libthread_db.  */
833   *base = (void *) (reg - idx);
834
835   return PS_OK;
836 }
837 \f
838
839 /* Get the hardware debug register capacity information from the
840    inferior represented by PTID.  */
841
842 static void
843 aarch64_linux_get_debug_reg_capacity (ptid_t ptid)
844 {
845   int tid;
846   struct iovec iov;
847   struct user_hwdebug_state dreg_state;
848
849   tid = ptid_get_pid (ptid);
850   iov.iov_base = &dreg_state;
851   iov.iov_len = sizeof (dreg_state);
852
853   /* Get hardware watchpoint register info.  */
854   if (ptrace (PTRACE_GETREGSET, tid, NT_ARM_HW_WATCH, &iov) == 0
855       && AARCH64_DEBUG_ARCH (dreg_state.dbg_info) == AARCH64_DEBUG_ARCH_V8)
856     {
857       aarch64_num_wp_regs = AARCH64_DEBUG_NUM_SLOTS (dreg_state.dbg_info);
858       if (aarch64_num_wp_regs > AARCH64_HWP_MAX_NUM)
859         {
860           warning (_("Unexpected number of hardware watchpoint registers"
861                      " reported by ptrace, got %d, expected %d."),
862                    aarch64_num_wp_regs, AARCH64_HWP_MAX_NUM);
863           aarch64_num_wp_regs = AARCH64_HWP_MAX_NUM;
864         }
865     }
866   else
867     {
868       warning (_("Unable to determine the number of hardware watchpoints"
869                  " available."));
870       aarch64_num_wp_regs = 0;
871     }
872
873   /* Get hardware breakpoint register info.  */
874   if (ptrace (PTRACE_GETREGSET, tid, NT_ARM_HW_BREAK, &iov) == 0
875       && AARCH64_DEBUG_ARCH (dreg_state.dbg_info) == AARCH64_DEBUG_ARCH_V8)
876     {
877       aarch64_num_bp_regs = AARCH64_DEBUG_NUM_SLOTS (dreg_state.dbg_info);
878       if (aarch64_num_bp_regs > AARCH64_HBP_MAX_NUM)
879         {
880           warning (_("Unexpected number of hardware breakpoint registers"
881                      " reported by ptrace, got %d, expected %d."),
882                    aarch64_num_bp_regs, AARCH64_HBP_MAX_NUM);
883           aarch64_num_bp_regs = AARCH64_HBP_MAX_NUM;
884         }
885     }
886   else
887     {
888       warning (_("Unable to determine the number of hardware breakpoints"
889                  " available."));
890       aarch64_num_bp_regs = 0;
891     }
892 }
893
894 static void (*super_post_startup_inferior) (struct target_ops *self,
895                                             ptid_t ptid);
896
897 /* Implement the "to_post_startup_inferior" target_ops method.  */
898
899 static void
900 aarch64_linux_child_post_startup_inferior (struct target_ops *self,
901                                            ptid_t ptid)
902 {
903   aarch64_forget_process (ptid_get_pid (ptid));
904   aarch64_linux_get_debug_reg_capacity (ptid);
905   super_post_startup_inferior (self, ptid);
906 }
907
908 extern struct target_desc *tdesc_arm_with_vfpv3;
909 extern struct target_desc *tdesc_arm_with_neon;
910
911 /* Implement the "to_read_description" target_ops method.  */
912
913 static const struct target_desc *
914 aarch64_linux_read_description (struct target_ops *ops)
915 {
916   CORE_ADDR at_phent;
917
918   if (target_auxv_search (ops, AT_PHENT, &at_phent) == 1)
919     {
920       if (at_phent == sizeof (Elf64_External_Phdr))
921         return tdesc_aarch64;
922       else
923         {
924           CORE_ADDR arm_hwcap = 0;
925
926           if (target_auxv_search (ops, AT_HWCAP, &arm_hwcap) != 1)
927             return ops->beneath->to_read_description (ops->beneath);
928
929 #ifndef COMPAT_HWCAP_VFP
930 #define COMPAT_HWCAP_VFP        (1 << 6)
931 #endif
932 #ifndef COMPAT_HWCAP_NEON
933 #define COMPAT_HWCAP_NEON       (1 << 12)
934 #endif
935 #ifndef COMPAT_HWCAP_VFPv3
936 #define COMPAT_HWCAP_VFPv3      (1 << 13)
937 #endif
938
939           if (arm_hwcap & COMPAT_HWCAP_VFP)
940             {
941               char *buf;
942               const struct target_desc *result = NULL;
943
944               if (arm_hwcap & COMPAT_HWCAP_NEON)
945                 result = tdesc_arm_with_neon;
946               else if (arm_hwcap & COMPAT_HWCAP_VFPv3)
947                 result = tdesc_arm_with_vfpv3;
948
949               return result;
950             }
951
952           return NULL;
953         }
954     }
955
956   return tdesc_aarch64;
957 }
958
959 /* Given the (potentially unaligned) watchpoint address in ADDR and
960    length in LEN, return the aligned address and aligned length in
961    *ALIGNED_ADDR_P and *ALIGNED_LEN_P, respectively.  The returned
962    aligned address and length will be valid values to write to the
963    hardware watchpoint value and control registers.
964
965    The given watchpoint may get truncated if more than one hardware
966    register is needed to cover the watched region.  *NEXT_ADDR_P
967    and *NEXT_LEN_P, if non-NULL, will return the address and length
968    of the remaining part of the watchpoint (which can be processed
969    by calling this routine again to generate another aligned address
970    and length pair.
971
972    See the comment above the function of the same name in
973    gdbserver/linux-aarch64-low.c for more information.  */
974
975 static void
976 aarch64_align_watchpoint (CORE_ADDR addr, int len, CORE_ADDR *aligned_addr_p,
977                           int *aligned_len_p, CORE_ADDR *next_addr_p,
978                           int *next_len_p)
979 {
980   int aligned_len;
981   unsigned int offset;
982   CORE_ADDR aligned_addr;
983   const unsigned int alignment = AARCH64_HWP_ALIGNMENT;
984   const unsigned int max_wp_len = AARCH64_HWP_MAX_LEN_PER_REG;
985
986   /* As assumed by the algorithm.  */
987   gdb_assert (alignment == max_wp_len);
988
989   if (len <= 0)
990     return;
991
992   /* Address to be put into the hardware watchpoint value register
993      must be aligned.  */
994   offset = addr & (alignment - 1);
995   aligned_addr = addr - offset;
996
997   gdb_assert (offset >= 0 && offset < alignment);
998   gdb_assert (aligned_addr >= 0 && aligned_addr <= addr);
999   gdb_assert (offset + len > 0);
1000
1001   if (offset + len >= max_wp_len)
1002     {
1003       /* Need more than one watchpoint registers; truncate it at the
1004          alignment boundary.  */
1005       aligned_len = max_wp_len;
1006       len -= (max_wp_len - offset);
1007       addr += (max_wp_len - offset);
1008       gdb_assert ((addr & (alignment - 1)) == 0);
1009     }
1010   else
1011     {
1012       /* Find the smallest valid length that is large enough to
1013          accommodate this watchpoint.  */
1014       static const unsigned char
1015         aligned_len_array[AARCH64_HWP_MAX_LEN_PER_REG] =
1016         { 1, 2, 4, 4, 8, 8, 8, 8 };
1017
1018       aligned_len = aligned_len_array[offset + len - 1];
1019       addr += len;
1020       len = 0;
1021     }
1022
1023   if (aligned_addr_p)
1024     *aligned_addr_p = aligned_addr;
1025   if (aligned_len_p)
1026     *aligned_len_p = aligned_len;
1027   if (next_addr_p)
1028     *next_addr_p = addr;
1029   if (next_len_p)
1030     *next_len_p = len;
1031 }
1032
1033 /* Returns the number of hardware watchpoints of type TYPE that we can
1034    set.  Value is positive if we can set CNT watchpoints, zero if
1035    setting watchpoints of type TYPE is not supported, and negative if
1036    CNT is more than the maximum number of watchpoints of type TYPE
1037    that we can support.  TYPE is one of bp_hardware_watchpoint,
1038    bp_read_watchpoint, bp_write_watchpoint, or bp_hardware_breakpoint.
1039    CNT is the number of such watchpoints used so far (including this
1040    one).  OTHERTYPE is non-zero if other types of watchpoints are
1041    currently enabled.
1042
1043    We always return 1 here because we don't have enough information
1044    about possible overlap of addresses that they want to watch.  As an
1045    extreme example, consider the case where all the watchpoints watch
1046    the same address and the same region length: then we can handle a
1047    virtually unlimited number of watchpoints, due to debug register
1048    sharing implemented via reference counts.  */
1049
1050 static int
1051 aarch64_linux_can_use_hw_breakpoint (struct target_ops *self,
1052                                      int type, int cnt, int othertype)
1053 {
1054   return 1;
1055 }
1056
1057 /* ptrace expects control registers to be formatted as follows:
1058
1059    31                             13          5      3      1     0
1060    +--------------------------------+----------+------+------+----+
1061    |         RESERVED (SBZ)         |  LENGTH  | TYPE | PRIV | EN |
1062    +--------------------------------+----------+------+------+----+
1063
1064    The TYPE field is ignored for breakpoints.  */
1065
1066 #define DR_CONTROL_ENABLED(ctrl)        (((ctrl) & 0x1) == 1)
1067 #define DR_CONTROL_LENGTH(ctrl)         (((ctrl) >> 5) & 0xff)
1068
1069 /* Utility function that returns the length in bytes of a watchpoint
1070    according to the content of a hardware debug control register CTRL.
1071    Note that the kernel currently only supports the following Byte
1072    Address Select (BAS) values: 0x1, 0x3, 0xf and 0xff, which means
1073    that for a hardware watchpoint, its valid length can only be 1
1074    byte, 2 bytes, 4 bytes or 8 bytes.  */
1075
1076 static inline unsigned int
1077 aarch64_watchpoint_length (unsigned int ctrl)
1078 {
1079   switch (DR_CONTROL_LENGTH (ctrl))
1080     {
1081     case 0x01:
1082       return 1;
1083     case 0x03:
1084       return 2;
1085     case 0x0f:
1086       return 4;
1087     case 0xff:
1088       return 8;
1089     default:
1090       return 0;
1091     }
1092 }
1093
1094 /* Given the hardware breakpoint or watchpoint type TYPE and its
1095    length LEN, return the expected encoding for a hardware
1096    breakpoint/watchpoint control register.  */
1097
1098 static unsigned int
1099 aarch64_point_encode_ctrl_reg (int type, int len)
1100 {
1101   unsigned int ctrl, ttype;
1102
1103   /* type */
1104   switch (type)
1105     {
1106     case hw_write:
1107       ttype = 2;
1108       break;
1109     case hw_read:
1110       ttype = 1;
1111       break;
1112     case hw_access:
1113       ttype = 3;
1114       break;
1115     case hw_execute:
1116       ttype = 0;
1117       break;
1118     default:
1119       perror_with_name (_("Unrecognized breakpoint/watchpoint type"));
1120     }
1121   ctrl = ttype << 3;
1122
1123   /* length bitmask */
1124   ctrl |= ((1 << len) - 1) << 5;
1125   /* enabled at el0 */
1126   ctrl |= (2 << 1) | 1;
1127
1128   return ctrl;
1129 }
1130
1131 /* Addresses to be written to the hardware breakpoint and watchpoint
1132    value registers need to be aligned; the alignment is 4-byte and
1133    8-type respectively.  Linux kernel rejects any non-aligned address
1134    it receives from the related ptrace call.  Furthermore, the kernel
1135    currently only supports the following Byte Address Select (BAS)
1136    values: 0x1, 0x3, 0xf and 0xff, which means that for a hardware
1137    watchpoint to be accepted by the kernel (via ptrace call), its
1138    valid length can only be 1 byte, 2 bytes, 4 bytes or 8 bytes.
1139    Despite these limitations, the unaligned watchpoint is supported in
1140    this port.
1141
1142    Return 0 for any non-compliant ADDR and/or LEN; return 1 otherwise.  */
1143
1144 static int
1145 aarch64_point_is_aligned (int is_watchpoint, CORE_ADDR addr, int len)
1146 {
1147   unsigned int alignment = is_watchpoint ? AARCH64_HWP_ALIGNMENT
1148     : AARCH64_HBP_ALIGNMENT;
1149
1150   if (addr & (alignment - 1))
1151     return 0;
1152
1153   if (len != 8 && len != 4 && len != 2 && len != 1)
1154     return 0;
1155
1156   return 1;
1157 }
1158
1159 /* Record the insertion of one breakpoint/watchpoint, as represented
1160    by ADDR and CTRL, in the cached debug register state area *STATE.  */
1161
1162 static int
1163 aarch64_dr_state_insert_one_point (struct aarch64_debug_reg_state *state,
1164                                    enum target_hw_bp_type type, CORE_ADDR addr,
1165                                    int len)
1166 {
1167   int i, idx, num_regs, is_watchpoint;
1168   unsigned int ctrl, *dr_ctrl_p, *dr_ref_count;
1169   CORE_ADDR *dr_addr_p;
1170
1171   /* Set up state pointers.  */
1172   is_watchpoint = (type != hw_execute);
1173   gdb_assert (aarch64_point_is_aligned (is_watchpoint, addr, len));
1174   if (is_watchpoint)
1175     {
1176       num_regs = aarch64_num_wp_regs;
1177       dr_addr_p = state->dr_addr_wp;
1178       dr_ctrl_p = state->dr_ctrl_wp;
1179       dr_ref_count = state->dr_ref_count_wp;
1180     }
1181   else
1182     {
1183       num_regs = aarch64_num_bp_regs;
1184       dr_addr_p = state->dr_addr_bp;
1185       dr_ctrl_p = state->dr_ctrl_bp;
1186       dr_ref_count = state->dr_ref_count_bp;
1187     }
1188
1189   ctrl = aarch64_point_encode_ctrl_reg (type, len);
1190
1191   /* Find an existing or free register in our cache.  */
1192   idx = -1;
1193   for (i = 0; i < num_regs; ++i)
1194     {
1195       if ((dr_ctrl_p[i] & 1) == 0)
1196         {
1197           gdb_assert (dr_ref_count[i] == 0);
1198           idx = i;
1199           /* no break; continue hunting for an existing one.  */
1200         }
1201       else if (dr_addr_p[i] == addr && dr_ctrl_p[i] == ctrl)
1202         {
1203           gdb_assert (dr_ref_count[i] != 0);
1204           idx = i;
1205           break;
1206         }
1207     }
1208
1209   /* No space.  */
1210   if (idx == -1)
1211     return -1;
1212
1213   /* Update our cache.  */
1214   if ((dr_ctrl_p[idx] & 1) == 0)
1215     {
1216       /* new entry */
1217       dr_addr_p[idx] = addr;
1218       dr_ctrl_p[idx] = ctrl;
1219       dr_ref_count[idx] = 1;
1220       /* Notify the change.  */
1221       aarch64_notify_debug_reg_change (state, is_watchpoint, idx);
1222     }
1223   else
1224     {
1225       /* existing entry */
1226       dr_ref_count[idx]++;
1227     }
1228
1229   return 0;
1230 }
1231
1232 /* Record the removal of one breakpoint/watchpoint, as represented by
1233    ADDR and CTRL, in the cached debug register state area *STATE.  */
1234
1235 static int
1236 aarch64_dr_state_remove_one_point (struct aarch64_debug_reg_state *state,
1237                                    enum target_hw_bp_type type, CORE_ADDR addr,
1238                                    int len)
1239 {
1240   int i, num_regs, is_watchpoint;
1241   unsigned int ctrl, *dr_ctrl_p, *dr_ref_count;
1242   CORE_ADDR *dr_addr_p;
1243
1244   /* Set up state pointers.  */
1245   is_watchpoint = (type != hw_execute);
1246   gdb_assert (aarch64_point_is_aligned (is_watchpoint, addr, len));
1247   if (is_watchpoint)
1248     {
1249       num_regs = aarch64_num_wp_regs;
1250       dr_addr_p = state->dr_addr_wp;
1251       dr_ctrl_p = state->dr_ctrl_wp;
1252       dr_ref_count = state->dr_ref_count_wp;
1253     }
1254   else
1255     {
1256       num_regs = aarch64_num_bp_regs;
1257       dr_addr_p = state->dr_addr_bp;
1258       dr_ctrl_p = state->dr_ctrl_bp;
1259       dr_ref_count = state->dr_ref_count_bp;
1260     }
1261
1262   ctrl = aarch64_point_encode_ctrl_reg (type, len);
1263
1264   /* Find the entry that matches the ADDR and CTRL.  */
1265   for (i = 0; i < num_regs; ++i)
1266     if (dr_addr_p[i] == addr && dr_ctrl_p[i] == ctrl)
1267       {
1268         gdb_assert (dr_ref_count[i] != 0);
1269         break;
1270       }
1271
1272   /* Not found.  */
1273   if (i == num_regs)
1274     return -1;
1275
1276   /* Clear our cache.  */
1277   if (--dr_ref_count[i] == 0)
1278     {
1279       /* Clear the enable bit.  */
1280       ctrl &= ~1;
1281       dr_addr_p[i] = 0;
1282       dr_ctrl_p[i] = ctrl;
1283       /* Notify the change.  */
1284       aarch64_notify_debug_reg_change (state, is_watchpoint, i);
1285     }
1286
1287   return 0;
1288 }
1289
1290 /* Implement insertion and removal of a single breakpoint.  */
1291
1292 static int
1293 aarch64_handle_breakpoint (enum target_hw_bp_type type, CORE_ADDR addr,
1294                            int len, int is_insert)
1295 {
1296   struct aarch64_debug_reg_state *state;
1297
1298   /* The hardware breakpoint on AArch64 should always be 4-byte
1299      aligned.  */
1300   if (!aarch64_point_is_aligned (0 /* is_watchpoint */ , addr, len))
1301     return -1;
1302
1303   state = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1304
1305   if (is_insert)
1306     return aarch64_dr_state_insert_one_point (state, type, addr, len);
1307   else
1308     return aarch64_dr_state_remove_one_point (state, type, addr, len);
1309 }
1310
1311 /* Insert a hardware-assisted breakpoint at BP_TGT->reqstd_address.
1312    Return 0 on success, -1 on failure.  */
1313
1314 static int
1315 aarch64_linux_insert_hw_breakpoint (struct target_ops *self,
1316                                     struct gdbarch *gdbarch,
1317                                     struct bp_target_info *bp_tgt)
1318 {
1319   int ret;
1320   CORE_ADDR addr = bp_tgt->placed_address = bp_tgt->reqstd_address;
1321   const int len = 4;
1322   const enum target_hw_bp_type type = hw_execute;
1323
1324   if (show_debug_regs)
1325     fprintf_unfiltered
1326       (gdb_stdlog,
1327        "insert_hw_breakpoint on entry (addr=0x%08lx, len=%d))\n",
1328        (unsigned long) addr, len);
1329
1330   ret = aarch64_handle_breakpoint (type, addr, len, 1 /* is_insert */);
1331
1332   if (show_debug_regs)
1333     {
1334       struct aarch64_debug_reg_state *state
1335         = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1336
1337       aarch64_show_debug_reg_state (state,
1338                                     "insert_hw_breakpoint", addr, len, type);
1339     }
1340
1341   return ret;
1342 }
1343
1344 /* Remove a hardware-assisted breakpoint at BP_TGT->placed_address.
1345    Return 0 on success, -1 on failure.  */
1346
1347 static int
1348 aarch64_linux_remove_hw_breakpoint (struct target_ops *self,
1349                                     struct gdbarch *gdbarch,
1350                                     struct bp_target_info *bp_tgt)
1351 {
1352   int ret;
1353   CORE_ADDR addr = bp_tgt->placed_address;
1354   const int len = 4;
1355   const enum target_hw_bp_type type = hw_execute;
1356
1357   if (show_debug_regs)
1358     fprintf_unfiltered
1359       (gdb_stdlog, "remove_hw_breakpoint on entry (addr=0x%08lx, len=%d))\n",
1360        (unsigned long) addr, len);
1361
1362   ret = aarch64_handle_breakpoint (type, addr, len, 0 /* is_insert */);
1363
1364   if (show_debug_regs)
1365     {
1366       struct aarch64_debug_reg_state *state
1367         = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1368
1369       aarch64_show_debug_reg_state (state,
1370                                     "remove_hw_watchpoint", addr, len, type);
1371     }
1372
1373   return ret;
1374 }
1375
1376 /* This is essentially the same as aarch64_handle_breakpoint, apart
1377    from that it is an aligned watchpoint to be handled.  */
1378
1379 static int
1380 aarch64_handle_aligned_watchpoint (enum target_hw_bp_type type, CORE_ADDR addr,
1381                                    int len, int is_insert)
1382 {
1383   struct aarch64_debug_reg_state *state
1384     = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1385
1386   if (is_insert)
1387     return aarch64_dr_state_insert_one_point (state, type, addr, len);
1388   else
1389     return aarch64_dr_state_remove_one_point (state, type, addr, len);
1390 }
1391
1392 /* Insert/remove unaligned watchpoint by calling
1393    aarch64_align_watchpoint repeatedly until the whole watched region,
1394    as represented by ADDR and LEN, has been properly aligned and ready
1395    to be written to one or more hardware watchpoint registers.
1396    IS_INSERT indicates whether this is an insertion or a deletion.
1397    Return 0 if succeed.  */
1398
1399 static int
1400 aarch64_handle_unaligned_watchpoint (int type, CORE_ADDR addr, int len,
1401                                      int is_insert)
1402 {
1403   struct aarch64_debug_reg_state *state
1404     = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1405
1406   while (len > 0)
1407     {
1408       CORE_ADDR aligned_addr;
1409       int aligned_len, ret;
1410
1411       aarch64_align_watchpoint (addr, len, &aligned_addr, &aligned_len,
1412                                 &addr, &len);
1413
1414       if (is_insert)
1415         ret = aarch64_dr_state_insert_one_point (state, type, aligned_addr,
1416                                                  aligned_len);
1417       else
1418         ret = aarch64_dr_state_remove_one_point (state, type, aligned_addr,
1419                                                  aligned_len);
1420
1421       if (show_debug_regs)
1422         debug_printf (
1423 "handle_unaligned_watchpoint: is_insert: %d\n"
1424 "                             aligned_addr: 0x%08lx, aligned_len: %d\n"
1425 "                                next_addr: 0x%08lx,    next_len: %d\n",
1426                  is_insert, aligned_addr, aligned_len, addr, len);
1427
1428       if (ret != 0)
1429         return ret;
1430     }
1431
1432   return 0;
1433 }
1434
1435 /* Implements insertion and removal of a single watchpoint.  */
1436
1437 static int
1438 aarch64_handle_watchpoint (int type, CORE_ADDR addr, int len, int is_insert)
1439 {
1440   if (aarch64_point_is_aligned (1 /* is_watchpoint */ , addr, len))
1441     return aarch64_handle_aligned_watchpoint (type, addr, len, is_insert);
1442   else
1443     return aarch64_handle_unaligned_watchpoint (type, addr, len, is_insert);
1444 }
1445
1446 /* Implement the "to_insert_watchpoint" target_ops method.
1447
1448    Insert a watchpoint to watch a memory region which starts at
1449    address ADDR and whose length is LEN bytes.  Watch memory accesses
1450    of the type TYPE.  Return 0 on success, -1 on failure.  */
1451
1452 static int
1453 aarch64_linux_insert_watchpoint (struct target_ops *self,
1454                                  CORE_ADDR addr, int len, int type,
1455                                  struct expression *cond)
1456 {
1457   int ret;
1458
1459   if (show_debug_regs)
1460     fprintf_unfiltered (gdb_stdlog,
1461                         "insert_watchpoint on entry (addr=0x%08lx, len=%d)\n",
1462                         (unsigned long) addr, len);
1463
1464   gdb_assert (type != hw_execute);
1465
1466   ret = aarch64_handle_watchpoint (type, addr, len, 1 /* is_insert */);
1467
1468   if (show_debug_regs)
1469     {
1470       struct aarch64_debug_reg_state *state
1471         = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1472
1473       aarch64_show_debug_reg_state (state,
1474                                     "insert_watchpoint", addr, len, type);
1475     }
1476
1477   return ret;
1478 }
1479
1480 /* Implement the "to_remove_watchpoint" target_ops method.
1481    Remove a watchpoint that watched the memory region which starts at
1482    address ADDR, whose length is LEN bytes, and for accesses of the
1483    type TYPE.  Return 0 on success, -1 on failure.  */
1484
1485 static int
1486 aarch64_linux_remove_watchpoint (struct target_ops *self,
1487                                  CORE_ADDR addr, int len, int type,
1488                                  struct expression *cond)
1489 {
1490   int ret;
1491
1492   if (show_debug_regs)
1493     fprintf_unfiltered (gdb_stdlog,
1494                         "remove_watchpoint on entry (addr=0x%08lx, len=%d)\n",
1495                         (unsigned long) addr, len);
1496
1497   gdb_assert (type != hw_execute);
1498
1499   ret = aarch64_handle_watchpoint (type, addr, len, 0 /* is_insert */);
1500
1501   if (show_debug_regs)
1502     {
1503       struct aarch64_debug_reg_state *state
1504         = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1505
1506       aarch64_show_debug_reg_state (state,
1507                                     "remove_watchpoint", addr, len, type);
1508     }
1509
1510   return ret;
1511 }
1512
1513 /* Implement the "to_region_ok_for_hw_watchpoint" target_ops method.  */
1514
1515 static int
1516 aarch64_linux_region_ok_for_hw_watchpoint (struct target_ops *self,
1517                                            CORE_ADDR addr, int len)
1518 {
1519   CORE_ADDR aligned_addr;
1520
1521   /* Can not set watchpoints for zero or negative lengths.  */
1522   if (len <= 0)
1523     return 0;
1524
1525   /* Must have hardware watchpoint debug register(s).  */
1526   if (aarch64_num_wp_regs == 0)
1527     return 0;
1528
1529   /* We support unaligned watchpoint address and arbitrary length,
1530      as long as the size of the whole watched area after alignment
1531      doesn't exceed size of the total area that all watchpoint debug
1532      registers can watch cooperatively.
1533
1534      This is a very relaxed rule, but unfortunately there are
1535      limitations, e.g. false-positive hits, due to limited support of
1536      hardware debug registers in the kernel.  See comment above
1537      aarch64_align_watchpoint for more information.  */
1538
1539   aligned_addr = addr & ~(AARCH64_HWP_MAX_LEN_PER_REG - 1);
1540   if (aligned_addr + aarch64_num_wp_regs * AARCH64_HWP_MAX_LEN_PER_REG
1541       < addr + len)
1542     return 0;
1543
1544   /* All tests passed so we are likely to be able to set the watchpoint.
1545      The reason that it is 'likely' rather than 'must' is because
1546      we don't check the current usage of the watchpoint registers, and
1547      there may not be enough registers available for this watchpoint.
1548      Ideally we should check the cached debug register state, however
1549      the checking is costly.  */
1550   return 1;
1551 }
1552
1553 /* Implement the "to_stopped_data_address" target_ops method.  */
1554
1555 static int
1556 aarch64_linux_stopped_data_address (struct target_ops *target,
1557                                     CORE_ADDR *addr_p)
1558 {
1559   siginfo_t siginfo;
1560   int i, tid;
1561   struct aarch64_debug_reg_state *state;
1562
1563   if (!linux_nat_get_siginfo (inferior_ptid, &siginfo))
1564     return 0;
1565
1566   /* This must be a hardware breakpoint.  */
1567   if (siginfo.si_signo != SIGTRAP
1568       || (siginfo.si_code & 0xffff) != TRAP_HWBKPT)
1569     return 0;
1570
1571   /* Check if the address matches any watched address.  */
1572   state = aarch64_get_debug_reg_state (ptid_get_pid (inferior_ptid));
1573   for (i = aarch64_num_wp_regs - 1; i >= 0; --i)
1574     {
1575       const unsigned int len = aarch64_watchpoint_length (state->dr_ctrl_wp[i]);
1576       const CORE_ADDR addr_trap = (CORE_ADDR) siginfo.si_addr;
1577       const CORE_ADDR addr_watch = state->dr_addr_wp[i];
1578
1579       if (state->dr_ref_count_wp[i]
1580           && DR_CONTROL_ENABLED (state->dr_ctrl_wp[i])
1581           && addr_trap >= addr_watch
1582           && addr_trap < addr_watch + len)
1583         {
1584           *addr_p = addr_trap;
1585           return 1;
1586         }
1587     }
1588
1589   return 0;
1590 }
1591
1592 /* Implement the "to_stopped_by_watchpoint" target_ops method.  */
1593
1594 static int
1595 aarch64_linux_stopped_by_watchpoint (struct target_ops *ops)
1596 {
1597   CORE_ADDR addr;
1598
1599   return aarch64_linux_stopped_data_address (ops, &addr);
1600 }
1601
1602 /* Implement the "to_watchpoint_addr_within_range" target_ops method.  */
1603
1604 static int
1605 aarch64_linux_watchpoint_addr_within_range (struct target_ops *target,
1606                                             CORE_ADDR addr,
1607                                             CORE_ADDR start, int length)
1608 {
1609   return start <= addr && start + length - 1 >= addr;
1610 }
1611
1612 /* Define AArch64 maintenance commands.  */
1613
1614 static void
1615 add_show_debug_regs_command (void)
1616 {
1617   /* A maintenance command to enable printing the internal DRi mirror
1618      variables.  */
1619   add_setshow_boolean_cmd ("show-debug-regs", class_maintenance,
1620                            &show_debug_regs, _("\
1621 Set whether to show variables that mirror the AArch64 debug registers."), _("\
1622 Show whether to show variables that mirror the AArch64 debug registers."), _("\
1623 Use \"on\" to enable, \"off\" to disable.\n\
1624 If enabled, the debug registers values are shown when GDB inserts\n\
1625 or removes a hardware breakpoint or watchpoint, and when the inferior\n\
1626 triggers a breakpoint or watchpoint."),
1627                            NULL,
1628                            NULL,
1629                            &maintenance_set_cmdlist,
1630                            &maintenance_show_cmdlist);
1631 }
1632
1633 /* -Wmissing-prototypes.  */
1634 void _initialize_aarch64_linux_nat (void);
1635
1636 void
1637 _initialize_aarch64_linux_nat (void)
1638 {
1639   struct target_ops *t;
1640
1641   /* Fill in the generic GNU/Linux methods.  */
1642   t = linux_target ();
1643
1644   add_show_debug_regs_command ();
1645
1646   /* Add our register access methods.  */
1647   t->to_fetch_registers = aarch64_linux_fetch_inferior_registers;
1648   t->to_store_registers = aarch64_linux_store_inferior_registers;
1649
1650   t->to_read_description = aarch64_linux_read_description;
1651
1652   t->to_can_use_hw_breakpoint = aarch64_linux_can_use_hw_breakpoint;
1653   t->to_insert_hw_breakpoint = aarch64_linux_insert_hw_breakpoint;
1654   t->to_remove_hw_breakpoint = aarch64_linux_remove_hw_breakpoint;
1655   t->to_region_ok_for_hw_watchpoint =
1656     aarch64_linux_region_ok_for_hw_watchpoint;
1657   t->to_insert_watchpoint = aarch64_linux_insert_watchpoint;
1658   t->to_remove_watchpoint = aarch64_linux_remove_watchpoint;
1659   t->to_stopped_by_watchpoint = aarch64_linux_stopped_by_watchpoint;
1660   t->to_stopped_data_address = aarch64_linux_stopped_data_address;
1661   t->to_watchpoint_addr_within_range =
1662     aarch64_linux_watchpoint_addr_within_range;
1663
1664   /* Override the GNU/Linux inferior startup hook.  */
1665   super_post_startup_inferior = t->to_post_startup_inferior;
1666   t->to_post_startup_inferior = aarch64_linux_child_post_startup_inferior;
1667
1668   /* Register the target.  */
1669   linux_nat_add_target (t);
1670   linux_nat_set_new_thread (t, aarch64_linux_new_thread);
1671   linux_nat_set_new_fork (t, aarch64_linux_new_fork);
1672   linux_nat_set_forget_process (t, aarch64_forget_process);
1673   linux_nat_set_prepare_to_resume (t, aarch64_linux_prepare_to_resume);
1674 }