* gas/config/tc-avr.c: Change ISA for devices with USB support to
[external/binutils.git] / gdb / gdbserver / linux-aarch64-low.c
1 /* GNU/Linux/AArch64 specific low level interface, for the remote server for
2    GDB.
3
4    Copyright (C) 2009-2013 Free Software Foundation, Inc.
5    Contributed by ARM Ltd.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "server.h"
23 #include "linux-low.h"
24 #include "elf/common.h"
25
26 #include <signal.h>
27 #include <sys/user.h>
28 #include <sys/ptrace.h>
29 #include <sys/uio.h>
30
31 #include "gdb_proc_service.h"
32
33 /* Defined in auto-generated files.  */
34 void init_registers_aarch64 (void);
35
36 #ifdef HAVE_SYS_REG_H
37 #include <sys/reg.h>
38 #endif
39
40 #define AARCH64_X_REGS_NUM 31
41 #define AARCH64_V_REGS_NUM 32
42 #define AARCH64_X0_REGNO    0
43 #define AARCH64_SP_REGNO   31
44 #define AARCH64_PC_REGNO   32
45 #define AARCH64_CPSR_REGNO 33
46 #define AARCH64_V0_REGNO   34
47
48 #define AARCH64_NUM_REGS (AARCH64_V0_REGNO + AARCH64_V_REGS_NUM)
49
50 static int
51 aarch64_regmap [] =
52 {
53   /* These offsets correspond to GET/SETREGSET */
54   /* x0...  */
55    0*8,  1*8,  2*8,  3*8,  4*8,  5*8,  6*8,  7*8,
56    8*8,  9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8,
57   16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8,
58   24*8, 25*8, 26*8, 27*8, 28*8,
59   29*8,
60   30*8,                         /* x30 lr */
61   31*8,                         /* x31 sp */
62   32*8,                         /*     pc */
63   33*8,                         /*     cpsr    4 bytes!*/
64
65   /* FP register offsets correspond to GET/SETFPREGSET */
66    0*16,  1*16,  2*16,  3*16,  4*16,  5*16,  6*16,  7*16,
67    8*16,  9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16,
68   16*16, 17*16, 18*16, 19*16, 20*16, 21*16, 22*16, 23*16,
69   24*16, 25*16, 26*16, 27*16, 28*16, 29*16, 30*16, 31*16
70 };
71
72 /* Here starts the macro definitions, data structures, and code for
73    the hardware breakpoint and hardware watchpoint support.  The
74    following is the abbreviations that are used frequently in the code
75    and comment:
76
77    hw - hardware
78    bp - breakpoint
79    wp - watchpoint  */
80
81 /* Maximum number of hardware breakpoint and watchpoint registers.
82    Neither of these values may exceed the width of dr_changed_t
83    measured in bits.  */
84
85 #define AARCH64_HBP_MAX_NUM 16
86 #define AARCH64_HWP_MAX_NUM 16
87
88 /* Alignment requirement in bytes of hardware breakpoint and
89    watchpoint address.  This is the requirement for the addresses that
90    can be written to the hardware breakpoint/watchpoint value
91    registers.  The kernel currently does not do any alignment on
92    addresses when receiving a writing request (via ptrace call) to
93    these debug registers, and it will reject any address that is
94    unaligned.
95    Some limited support has been provided in this gdbserver port for
96    unaligned watchpoints, so that from a gdb user point of view, an
97    unaligned watchpoint can still be set.  This is achieved by
98    minimally enlarging the watched area to meet the alignment
99    requirement, and if necessary, splitting the watchpoint over
100    several hardware watchpoint registers.  */
101
102 #define AARCH64_HBP_ALIGNMENT 4
103 #define AARCH64_HWP_ALIGNMENT 8
104
105 /* The maximum length of a memory region that can be watched by one
106    hardware watchpoint register.  */
107
108 #define AARCH64_HWP_MAX_LEN_PER_REG 8
109
110 /* Each bit of a variable of this type is used to indicate whether a
111    hardware breakpoint or watchpoint setting has been changed since
112    the last updating.  Bit N corresponds to the Nth hardware
113    breakpoint or watchpoint setting which is managed in
114    aarch64_debug_reg_state.  Where N is valid between 0 and the total
115    number of the hardware breakpoint or watchpoint debug registers
116    minus 1.  When the bit N is 1, it indicates the corresponding
117    breakpoint or watchpoint setting is changed, and thus the
118    corresponding hardware debug register needs to be updated via the
119    ptrace interface.
120
121    In the per-thread arch-specific data area, we define two such
122    variables for per-thread hardware breakpoint and watchpoint
123    settings respectively.
124
125    This type is part of the mechanism which helps reduce the number of
126    ptrace calls to the kernel, i.e. avoid asking the kernel to write
127    to the debug registers with unchanged values.  */
128
129 typedef unsigned long long dr_changed_t;
130
131 /* Set each of the lower M bits of X to 1; assert X is wide enough.  */
132
133 #define DR_MARK_ALL_CHANGED(x, m)                                       \
134   do                                                                    \
135     {                                                                   \
136       gdb_assert (sizeof ((x)) * 8 >= (m));                             \
137       (x) = (((dr_changed_t)1 << (m)) - 1);                             \
138     } while (0)
139
140 #define DR_MARK_N_CHANGED(x, n)                                         \
141   do                                                                    \
142     {                                                                   \
143       (x) |= ((dr_changed_t)1 << (n));                                  \
144     } while (0)
145
146 #define DR_CLEAR_CHANGED(x)                                             \
147   do                                                                    \
148     {                                                                   \
149       (x) = 0;                                                          \
150     } while (0)
151
152 #define DR_HAS_CHANGED(x) ((x) != 0)
153 #define DR_N_HAS_CHANGED(x, n) ((x) & ((dr_changed_t)1 << (n)))
154
155 /* Structure for managing the hardware breakpoint/watchpoint resources.
156    DR_ADDR_* stores the address, DR_CTRL_* stores the control register
157    content, and DR_REF_COUNT_* counts the numbers of references to the
158    corresponding bp/wp, by which way the limited hardware resources
159    are not wasted on duplicated bp/wp settings (though so far gdb has
160    done a good job by not sending duplicated bp/wp requests).  */
161
162 struct aarch64_debug_reg_state
163 {
164   /* hardware breakpoint */
165   CORE_ADDR dr_addr_bp[AARCH64_HBP_MAX_NUM];
166   unsigned int dr_ctrl_bp[AARCH64_HBP_MAX_NUM];
167   unsigned int dr_ref_count_bp[AARCH64_HBP_MAX_NUM];
168
169   /* hardware watchpoint */
170   CORE_ADDR dr_addr_wp[AARCH64_HWP_MAX_NUM];
171   unsigned int dr_ctrl_wp[AARCH64_HWP_MAX_NUM];
172   unsigned int dr_ref_count_wp[AARCH64_HWP_MAX_NUM];
173 };
174
175 /* Per-process arch-specific data we want to keep.  */
176
177 struct arch_process_info
178 {
179   /* Hardware breakpoint/watchpoint data.
180      The reason for them to be per-process rather than per-thread is
181      due to the lack of information in the gdbserver environment;
182      gdbserver is not told that whether a requested hardware
183      breakpoint/watchpoint is thread specific or not, so it has to set
184      each hw bp/wp for every thread in the current process.  The
185      higher level bp/wp management in gdb will resume a thread if a hw
186      bp/wp trap is not expected for it.  Since the hw bp/wp setting is
187      same for each thread, it is reasonable for the data to live here.
188      */
189   struct aarch64_debug_reg_state debug_reg_state;
190 };
191
192 /* Per-thread arch-specific data we want to keep.  */
193
194 struct arch_lwp_info
195 {
196   /* When bit N is 1, it indicates the Nth hardware breakpoint or
197      watchpoint register pair needs to be updated when the thread is
198      resumed; see aarch64_linux_prepare_to_resume.  */
199   dr_changed_t dr_changed_bp;
200   dr_changed_t dr_changed_wp;
201 };
202
203 /* Number of hardware breakpoints/watchpoints the target supports.
204    They are initialized with values obtained via the ptrace calls
205    with NT_ARM_HW_BREAK and NT_ARM_HW_WATCH respectively.  */
206
207 static int aarch64_num_bp_regs;
208 static int aarch64_num_wp_regs;
209
210 /* Hardware breakpoint/watchpoint types.
211    The values map to their encodings in the bit 4 and bit 3 of the
212    hardware breakpoint/watchpoint control registers.  */
213
214 enum target_point_type
215 {
216   hw_execute = 0,               /* Execute HW breakpoint */
217   hw_read = 1,                  /* Read    HW watchpoint */
218   hw_write = 2,                 /* Common  HW watchpoint */
219   hw_access = 3,                /* Access  HW watchpoint */
220   point_type_unsupported
221 };
222
223 #define Z_PACKET_SW_BP '0'
224 #define Z_PACKET_HW_BP '1'
225 #define Z_PACKET_WRITE_WP '2'
226 #define Z_PACKET_READ_WP '3'
227 #define Z_PACKET_ACCESS_WP '4'
228
229 /* Map the protocol breakpoint/watchpoint type TYPE to
230    enum target_point_type.  */
231
232 static enum target_point_type
233 Z_packet_to_point_type (char type)
234 {
235   switch (type)
236     {
237     case Z_PACKET_SW_BP:
238       /* Leave the handling of the sw breakpoint with the gdb client.  */
239       return point_type_unsupported;
240     case Z_PACKET_HW_BP:
241       return hw_execute;
242     case Z_PACKET_WRITE_WP:
243       return hw_write;
244     case Z_PACKET_READ_WP:
245       return hw_read;
246     case Z_PACKET_ACCESS_WP:
247       return hw_access;
248     default:
249       return point_type_unsupported;
250     }
251 }
252
253 static int
254 aarch64_cannot_store_register (int regno)
255 {
256   return regno >= AARCH64_NUM_REGS;
257 }
258
259 static int
260 aarch64_cannot_fetch_register (int regno)
261 {
262   return regno >= AARCH64_NUM_REGS;
263 }
264
265 static void
266 aarch64_fill_gregset (struct regcache *regcache, void *buf)
267 {
268   struct user_pt_regs *regset = buf;
269   int i;
270
271   for (i = 0; i < AARCH64_X_REGS_NUM; i++)
272     collect_register (regcache, AARCH64_X0_REGNO + i, &regset->regs[i]);
273   collect_register (regcache, AARCH64_SP_REGNO, &regset->sp);
274   collect_register (regcache, AARCH64_PC_REGNO, &regset->pc);
275   collect_register (regcache, AARCH64_CPSR_REGNO, &regset->pstate);
276 }
277
278 static void
279 aarch64_store_gregset (struct regcache *regcache, const void *buf)
280 {
281   const struct user_pt_regs *regset = buf;
282   int i;
283
284   for (i = 0; i < AARCH64_X_REGS_NUM; i++)
285     supply_register (regcache, AARCH64_X0_REGNO + i, &regset->regs[i]);
286   supply_register (regcache, AARCH64_SP_REGNO, &regset->sp);
287   supply_register (regcache, AARCH64_PC_REGNO, &regset->pc);
288   supply_register (regcache, AARCH64_CPSR_REGNO, &regset->pstate);
289 }
290
291 static void
292 aarch64_fill_fpregset (struct regcache *regcache, void *buf)
293 {
294   struct user_fpsimd_state *regset = buf;
295   int i;
296
297   for (i = 0; i < AARCH64_V_REGS_NUM; i++)
298     collect_register (regcache, AARCH64_V0_REGNO + i, &regset->vregs[i]);
299 }
300
301 static void
302 aarch64_store_fpregset (struct regcache *regcache, const void *buf)
303 {
304   const struct user_fpsimd_state *regset = buf;
305   int i;
306
307   for (i = 0; i < AARCH64_V_REGS_NUM; i++)
308     supply_register (regcache, AARCH64_V0_REGNO + i, &regset->vregs[i]);
309 }
310
311 /* Debugging of hardware breakpoint/watchpoint support.  */
312 extern int debug_hw_points;
313
314 /* Enable miscellaneous debugging output.  The name is historical - it
315    was originally used to debug LinuxThreads support.  */
316 extern int debug_threads;
317
318 static CORE_ADDR
319 aarch64_get_pc (struct regcache *regcache)
320 {
321   unsigned long pc;
322
323   collect_register_by_name (regcache, "pc", &pc);
324   if (debug_threads)
325     fprintf (stderr, "stop pc is %08lx\n", pc);
326   return pc;
327 }
328
329 static void
330 aarch64_set_pc (struct regcache *regcache, CORE_ADDR pc)
331 {
332   unsigned long newpc = pc;
333   supply_register_by_name (regcache, "pc", &newpc);
334 }
335
336 /* Correct in either endianness.  */
337
338 #define aarch64_breakpoint_len 4
339
340 static const unsigned long aarch64_breakpoint = 0x00800011;
341
342 static int
343 aarch64_breakpoint_at (CORE_ADDR where)
344 {
345   unsigned long insn;
346
347   (*the_target->read_memory) (where, (unsigned char *) &insn, 4);
348   if (insn == aarch64_breakpoint)
349     return 1;
350
351   return 0;
352 }
353
354 /* Print the values of the cached breakpoint/watchpoint registers.
355    This is enabled via the "set debug-hw-points" monitor command.  */
356
357 static void
358 aarch64_show_debug_reg_state (struct aarch64_debug_reg_state *state,
359                               const char *func, CORE_ADDR addr,
360                               int len, enum target_point_type type)
361 {
362   int i;
363
364   fprintf (stderr, "%s", func);
365   if (addr || len)
366     fprintf (stderr, " (addr=0x%08lx, len=%d, type=%s)",
367              (unsigned long) addr, len,
368              type == hw_write ? "hw-write-watchpoint"
369              : (type == hw_read ? "hw-read-watchpoint"
370                 : (type == hw_access ? "hw-access-watchpoint"
371                    : (type == hw_execute ? "hw-breakpoint"
372                       : "??unknown??"))));
373   fprintf (stderr, ":\n");
374
375   fprintf (stderr, "\tBREAKPOINTs:\n");
376   for (i = 0; i < aarch64_num_bp_regs; i++)
377     fprintf (stderr, "\tBP%d: addr=0x%s, ctrl=0x%08x, ref.count=%d\n",
378              i, paddress (state->dr_addr_bp[i]),
379              state->dr_ctrl_bp[i], state->dr_ref_count_bp[i]);
380
381   fprintf (stderr, "\tWATCHPOINTs:\n");
382   for (i = 0; i < aarch64_num_wp_regs; i++)
383     fprintf (stderr, "\tWP%d: addr=0x%s, ctrl=0x%08x, ref.count=%d\n",
384              i, paddress (state->dr_addr_wp[i]),
385              state->dr_ctrl_wp[i], state->dr_ref_count_wp[i]);
386 }
387
388 static void
389 aarch64_init_debug_reg_state (struct aarch64_debug_reg_state *state)
390 {
391   int i;
392
393   for (i = 0; i < AARCH64_HBP_MAX_NUM; ++i)
394     {
395       state->dr_addr_bp[i] = 0;
396       state->dr_ctrl_bp[i] = 0;
397       state->dr_ref_count_bp[i] = 0;
398     }
399
400   for (i = 0; i < AARCH64_HWP_MAX_NUM; ++i)
401     {
402       state->dr_addr_wp[i] = 0;
403       state->dr_ctrl_wp[i] = 0;
404       state->dr_ref_count_wp[i] = 0;
405     }
406 }
407
408 /* ptrace expects control registers to be formatted as follows:
409
410    31                             13          5      3      1     0
411    +--------------------------------+----------+------+------+----+
412    |         RESERVED (SBZ)         |  LENGTH  | TYPE | PRIV | EN |
413    +--------------------------------+----------+------+------+----+
414
415    The TYPE field is ignored for breakpoints.  */
416
417 #define DR_CONTROL_ENABLED(ctrl)        (((ctrl) & 0x1) == 1)
418 #define DR_CONTROL_LENGTH(ctrl)         (((ctrl) >> 5) & 0xff)
419
420 /* Utility function that returns the length in bytes of a watchpoint
421    according to the content of a hardware debug control register CTRL.
422    Note that the kernel currently only supports the following Byte
423    Address Select (BAS) values: 0x1, 0x3, 0xf and 0xff, which means
424    that for a hardware watchpoint, its valid length can only be 1
425    byte, 2 bytes, 4 bytes or 8 bytes.  */
426
427 static inline unsigned int
428 aarch64_watchpoint_length (unsigned int ctrl)
429 {
430   switch (DR_CONTROL_LENGTH (ctrl))
431     {
432     case 0x01:
433       return 1;
434     case 0x03:
435       return 2;
436     case 0x0f:
437       return 4;
438     case 0xff:
439       return 8;
440     default:
441       return 0;
442     }
443 }
444
445 /* Given the hardware breakpoint or watchpoint type TYPE and its
446    length LEN, return the expected encoding for a hardware
447    breakpoint/watchpoint control register.  */
448
449 static unsigned int
450 aarch64_point_encode_ctrl_reg (enum target_point_type type, int len)
451 {
452   unsigned int ctrl;
453
454   /* type */
455   ctrl = type << 3;
456   /* length bitmask */
457   ctrl |= ((1 << len) - 1) << 5;
458   /* enabled at el0 */
459   ctrl |= (2 << 1) | 1;
460
461   return ctrl;
462 }
463
464 /* Addresses to be written to the hardware breakpoint and watchpoint
465    value registers need to be aligned; the alignment is 4-byte and
466    8-type respectively.  Linux kernel rejects any non-aligned address
467    it receives from the related ptrace call.  Furthermore, the kernel
468    currently only supports the following Byte Address Select (BAS)
469    values: 0x1, 0x3, 0xf and 0xff, which means that for a hardware
470    watchpoint to be accepted by the kernel (via ptrace call), its
471    valid length can only be 1 byte, 2 bytes, 4 bytes or 8 bytes.
472    Despite these limitations, the unaligned watchpoint is supported in
473    this gdbserver port.
474
475    Return 0 for any non-compliant ADDR and/or LEN; return 1 otherwise.  */
476
477 static int
478 aarch64_point_is_aligned (int is_watchpoint, CORE_ADDR addr, int len)
479 {
480   unsigned int alignment = is_watchpoint ? AARCH64_HWP_ALIGNMENT
481     : AARCH64_HBP_ALIGNMENT;
482
483   if (addr & (alignment - 1))
484     return 0;
485
486   if (len != 8 && len != 4 && len != 2 && len != 1)
487     return 0;
488
489   return 1;
490 }
491
492 /* Given the (potentially unaligned) watchpoint address in ADDR and
493    length in LEN, return the aligned address and aligned length in
494    *ALIGNED_ADDR_P and *ALIGNED_LEN_P, respectively.  The returned
495    aligned address and length will be valid to be written to the
496    hardware watchpoint value and control registers.  See the comment
497    above aarch64_point_is_aligned for the information about the
498    alignment requirement.  The given watchpoint may get truncated if
499    more than one hardware register is needed to cover the watched
500    region.  *NEXT_ADDR_P and *NEXT_LEN_P, if non-NULL, will return the
501    address and length of the remaining part of the watchpoint (which
502    can be processed by calling this routine again to generate another
503    aligned address and length pair.
504
505    Essentially, unaligned watchpoint is achieved by minimally
506    enlarging the watched area to meet the alignment requirement, and
507    if necessary, splitting the watchpoint over several hardware
508    watchpoint registers.  The trade-off is that there will be
509    false-positive hits for the read-type or the access-type hardware
510    watchpoints; for the write type, which is more commonly used, there
511    will be no such issues, as the higher-level breakpoint management
512    in gdb always examines the exact watched region for any content
513    change, and transparently resumes a thread from a watchpoint trap
514    if there is no change to the watched region.
515
516    Another limitation is that because the watched region is enlarged,
517    the watchpoint fault address returned by
518    aarch64_stopped_data_address may be outside of the original watched
519    region, especially when the triggering instruction is accessing a
520    larger region.  When the fault address is not within any known
521    range, watchpoints_triggered in gdb will get confused, as the
522    higher-level watchpoint management is only aware of original
523    watched regions, and will think that some unknown watchpoint has
524    been triggered.  In such a case, gdb may stop without displaying
525    any detailed information.
526
527    Once the kernel provides the full support for Byte Address Select
528    (BAS) in the hardware watchpoint control register, these
529    limitations can be largely relaxed with some further work.  */
530
531 static void
532 aarch64_align_watchpoint (CORE_ADDR addr, int len, CORE_ADDR *aligned_addr_p,
533                           int *aligned_len_p, CORE_ADDR *next_addr_p,
534                           int *next_len_p)
535 {
536   int aligned_len;
537   unsigned int offset;
538   CORE_ADDR aligned_addr;
539   const unsigned int alignment = AARCH64_HWP_ALIGNMENT;
540   const unsigned int max_wp_len = AARCH64_HWP_MAX_LEN_PER_REG;
541
542   /* As assumed by the algorithm.  */
543   gdb_assert (alignment == max_wp_len);
544
545   if (len <= 0)
546     return;
547
548   /* Address to be put into the hardware watchpoint value register
549      must be aligned.  */
550   offset = addr & (alignment - 1);
551   aligned_addr = addr - offset;
552
553   gdb_assert (offset >= 0 && offset < alignment);
554   gdb_assert (aligned_addr >= 0 && aligned_addr <= addr);
555   gdb_assert ((offset + len) > 0);
556
557   if (offset + len >= max_wp_len)
558     {
559       /* Need more than one watchpoint registers; truncate it at the
560          alignment boundary.  */
561       aligned_len = max_wp_len;
562       len -= (max_wp_len - offset);
563       addr += (max_wp_len - offset);
564       gdb_assert ((addr & (alignment - 1)) == 0);
565     }
566   else
567     {
568       /* Find the smallest valid length that is large enough to
569          accommodate this watchpoint.  */
570       static const unsigned char
571         aligned_len_array[AARCH64_HWP_MAX_LEN_PER_REG] =
572         { 1, 2, 4, 4, 8, 8, 8, 8 };
573
574       aligned_len = aligned_len_array[offset + len - 1];
575       addr += len;
576       len = 0;
577     }
578
579   if (aligned_addr_p != NULL)
580     *aligned_addr_p = aligned_addr;
581   if (aligned_len_p != NULL)
582     *aligned_len_p = aligned_len;
583   if (next_addr_p != NULL)
584     *next_addr_p = addr;
585   if (next_len_p != NULL)
586     *next_len_p = len;
587 }
588
589 /* Call ptrace to set the thread TID's hardware breakpoint/watchpoint
590    registers with data from *STATE.  */
591
592 static void
593 aarch64_linux_set_debug_regs (const struct aarch64_debug_reg_state *state,
594                               int tid, int watchpoint)
595 {
596   int i, count;
597   struct iovec iov;
598   struct user_hwdebug_state regs;
599   const CORE_ADDR *addr;
600   const unsigned int *ctrl;
601
602   iov.iov_base = &regs;
603   iov.iov_len = sizeof (regs);
604   count = watchpoint ? aarch64_num_wp_regs : aarch64_num_bp_regs;
605   addr = watchpoint ? state->dr_addr_wp : state->dr_addr_bp;
606   ctrl = watchpoint ? state->dr_ctrl_wp : state->dr_ctrl_bp;
607
608   for (i = 0; i < count; i++)
609     {
610       regs.dbg_regs[i].addr = addr[i];
611       regs.dbg_regs[i].ctrl = ctrl[i];
612     }
613
614   if (ptrace (PTRACE_SETREGSET, tid,
615               watchpoint ? NT_ARM_HW_WATCH : NT_ARM_HW_BREAK,
616               (void *) &iov))
617     error (_("Unexpected error setting hardware debug registers"));
618 }
619
620 struct aarch64_dr_update_callback_param
621 {
622   int pid;
623   int is_watchpoint;
624   unsigned int idx;
625 };
626
627 /* Callback function which records the information about the change of
628    one hardware breakpoint/watchpoint setting for the thread ENTRY.
629    The information is passed in via PTR.
630    N.B.  The actual updating of hardware debug registers is not
631    carried out until the moment the thread is resumed.  */
632
633 static int
634 debug_reg_change_callback (struct inferior_list_entry *entry, void *ptr)
635 {
636   struct lwp_info *lwp = (struct lwp_info *) entry;
637   struct aarch64_dr_update_callback_param *param_p
638     = (struct aarch64_dr_update_callback_param *) ptr;
639   int pid = param_p->pid;
640   int idx = param_p->idx;
641   int is_watchpoint = param_p->is_watchpoint;
642   struct arch_lwp_info *info = lwp->arch_private;
643   dr_changed_t *dr_changed_ptr;
644   dr_changed_t dr_changed;
645
646   if (debug_hw_points)
647     {
648       fprintf (stderr, "debug_reg_change_callback: \n\tOn entry:\n");
649       fprintf (stderr, "\tpid%d, tid: %ld, dr_changed_bp=0x%llx, "
650                "dr_changed_wp=0x%llx\n",
651                pid, lwpid_of (lwp), info->dr_changed_bp,
652                info->dr_changed_wp);
653     }
654
655   dr_changed_ptr = is_watchpoint ? &info->dr_changed_wp
656     : &info->dr_changed_bp;
657   dr_changed = *dr_changed_ptr;
658
659   /* Only update the threads of this process.  */
660   if (pid_of (lwp) == pid)
661     {
662       gdb_assert (idx >= 0
663                   && (idx <= (is_watchpoint ? aarch64_num_wp_regs
664                               : aarch64_num_bp_regs)));
665
666       /* The following assertion is not right, as there can be changes
667          that have not been made to the hardware debug registers
668          before new changes overwrite the old ones.  This can happen,
669          for instance, when the breakpoint/watchpoint hit one of the
670          threads and the user enters continue; then what happens is:
671          1) all breakpoints/watchpoints are removed for all threads;
672          2) a single step is carried out for the thread that was hit;
673          3) all of the points are inserted again for all threads;
674          4) all threads are resumed.
675          The 2nd step will only affect the one thread in which the
676          bp/wp was hit, which means only that one thread is resumed;
677          remember that the actual updating only happen in
678          aarch64_linux_prepare_to_resume, so other threads remain
679          stopped during the removal and insertion of bp/wp.  Therefore
680          for those threads, the change of insertion of the bp/wp
681          overwrites that of the earlier removals.  (The situation may
682          be different when bp/wp is steppable, or in the non-stop
683          mode.)  */
684       /* gdb_assert (DR_N_HAS_CHANGED (dr_changed, idx) == 0);  */
685
686       /* The actual update is done later just before resuming the lwp,
687          we just mark that one register pair needs updating.  */
688       DR_MARK_N_CHANGED (dr_changed, idx);
689       *dr_changed_ptr = dr_changed;
690
691       /* If the lwp isn't stopped, force it to momentarily pause, so
692          we can update its debug registers.  */
693       if (!lwp->stopped)
694         linux_stop_lwp (lwp);
695     }
696
697   if (debug_hw_points)
698     {
699       fprintf (stderr, "\tOn exit:\n\tpid%d, tid: %ld, dr_changed_bp=0x%llx, "
700                "dr_changed_wp=0x%llx\n",
701                pid, lwpid_of (lwp), info->dr_changed_bp, info->dr_changed_wp);
702     }
703
704   return 0;
705 }
706
707 /* Notify each thread that their IDXth breakpoint/watchpoint register
708    pair needs to be updated.  The message will be recorded in each
709    thread's arch-specific data area, the actual updating will be done
710    when the thread is resumed.  */
711
712 void
713 aarch64_notify_debug_reg_change (const struct aarch64_debug_reg_state *state,
714                                  int is_watchpoint, unsigned int idx)
715 {
716   struct aarch64_dr_update_callback_param param;
717
718   /* Only update the threads of this process.  */
719   param.pid = pid_of (get_thread_lwp (current_inferior));
720
721   param.is_watchpoint = is_watchpoint;
722   param.idx = idx;
723
724   find_inferior (&all_lwps, debug_reg_change_callback, (void *) &param);
725 }
726
727
728 /* Return the pointer to the debug register state structure in the
729    current process' arch-specific data area.  */
730
731 static struct aarch64_debug_reg_state *
732 aarch64_get_debug_reg_state ()
733 {
734   struct process_info *proc;
735
736   proc = current_process ();
737   return &proc->private->arch_private->debug_reg_state;
738 }
739
740 /* Record the insertion of one breakpoint/watchpoint, as represented
741    by ADDR and CTRL, in the process' arch-specific data area *STATE.  */
742
743 static int
744 aarch64_dr_state_insert_one_point (struct aarch64_debug_reg_state *state,
745                                    enum target_point_type type,
746                                    CORE_ADDR addr, int len)
747 {
748   int i, idx, num_regs, is_watchpoint;
749   unsigned int ctrl, *dr_ctrl_p, *dr_ref_count;
750   CORE_ADDR *dr_addr_p;
751
752   /* Set up state pointers.  */
753   is_watchpoint = (type != hw_execute);
754   gdb_assert (aarch64_point_is_aligned (is_watchpoint, addr, len));
755   if (is_watchpoint)
756     {
757       num_regs = aarch64_num_wp_regs;
758       dr_addr_p = state->dr_addr_wp;
759       dr_ctrl_p = state->dr_ctrl_wp;
760       dr_ref_count = state->dr_ref_count_wp;
761     }
762   else
763     {
764       num_regs = aarch64_num_bp_regs;
765       dr_addr_p = state->dr_addr_bp;
766       dr_ctrl_p = state->dr_ctrl_bp;
767       dr_ref_count = state->dr_ref_count_bp;
768     }
769
770   ctrl = aarch64_point_encode_ctrl_reg (type, len);
771
772   /* Find an existing or free register in our cache.  */
773   idx = -1;
774   for (i = 0; i < num_regs; ++i)
775     {
776       if ((dr_ctrl_p[i] & 1) == 0)
777         {
778           gdb_assert (dr_ref_count[i] == 0);
779           idx = i;
780           /* no break; continue hunting for an exising one.  */
781         }
782       else if (dr_addr_p[i] == addr && dr_ctrl_p[i] == ctrl)
783         {
784           gdb_assert (dr_ref_count[i] != 0);
785           idx = i;
786           break;
787         }
788     }
789
790   /* No space.  */
791   if (idx == -1)
792     return -1;
793
794   /* Update our cache.  */
795   if ((dr_ctrl_p[idx] & 1) == 0)
796     {
797       /* new entry */
798       dr_addr_p[idx] = addr;
799       dr_ctrl_p[idx] = ctrl;
800       dr_ref_count[idx] = 1;
801       /* Notify the change.  */
802       aarch64_notify_debug_reg_change (state, is_watchpoint, idx);
803     }
804   else
805     {
806       /* existing entry */
807       dr_ref_count[idx]++;
808     }
809
810   return 0;
811 }
812
813 /* Record the removal of one breakpoint/watchpoint, as represented by
814    ADDR and CTRL, in the process' arch-specific data area *STATE.  */
815
816 static int
817 aarch64_dr_state_remove_one_point (struct aarch64_debug_reg_state *state,
818                                    enum target_point_type type,
819                                    CORE_ADDR addr, int len)
820 {
821   int i, num_regs, is_watchpoint;
822   unsigned int ctrl, *dr_ctrl_p, *dr_ref_count;
823   CORE_ADDR *dr_addr_p;
824
825   /* Set up state pointers.  */
826   is_watchpoint = (type != hw_execute);
827   gdb_assert (aarch64_point_is_aligned (is_watchpoint, addr, len));
828   if (is_watchpoint)
829     {
830       num_regs = aarch64_num_wp_regs;
831       dr_addr_p = state->dr_addr_wp;
832       dr_ctrl_p = state->dr_ctrl_wp;
833       dr_ref_count = state->dr_ref_count_wp;
834     }
835   else
836     {
837       num_regs = aarch64_num_bp_regs;
838       dr_addr_p = state->dr_addr_bp;
839       dr_ctrl_p = state->dr_ctrl_bp;
840       dr_ref_count = state->dr_ref_count_bp;
841     }
842
843   ctrl = aarch64_point_encode_ctrl_reg (type, len);
844
845   /* Find the entry that matches the ADDR and CTRL.  */
846   for (i = 0; i < num_regs; ++i)
847     if (dr_addr_p[i] == addr && dr_ctrl_p[i] == ctrl)
848       {
849         gdb_assert (dr_ref_count[i] != 0);
850         break;
851       }
852
853   /* Not found.  */
854   if (i == num_regs)
855     return -1;
856
857   /* Clear our cache.  */
858   if (--dr_ref_count[i] == 0)
859     {
860       /* Clear the enable bit.  */
861       ctrl &= ~1;
862       dr_addr_p[i] = 0;
863       dr_ctrl_p[i] = ctrl;
864       /* Notify the change.  */
865       aarch64_notify_debug_reg_change (state, is_watchpoint, i);
866     }
867
868   return 0;
869 }
870
871 static int
872 aarch64_handle_breakpoint (enum target_point_type type, CORE_ADDR addr,
873                            int len, int is_insert)
874 {
875   struct aarch64_debug_reg_state *state;
876
877   /* The hardware breakpoint on AArch64 should always be 4-byte
878      aligned.  */
879   if (!aarch64_point_is_aligned (0 /* is_watchpoint */ , addr, len))
880     return -1;
881
882   state = aarch64_get_debug_reg_state ();
883
884   if (is_insert)
885     return aarch64_dr_state_insert_one_point (state, type, addr, len);
886   else
887     return aarch64_dr_state_remove_one_point (state, type, addr, len);
888 }
889
890 /* This is essentially the same as aarch64_handle_breakpoint, apart
891    from that it is an aligned watchpoint to be handled.  */
892
893 static int
894 aarch64_handle_aligned_watchpoint (enum target_point_type type,
895                                    CORE_ADDR addr, int len, int is_insert)
896 {
897   struct aarch64_debug_reg_state *state;
898
899   state = aarch64_get_debug_reg_state ();
900
901   if (is_insert)
902     return aarch64_dr_state_insert_one_point (state, type, addr, len);
903   else
904     return aarch64_dr_state_remove_one_point (state, type, addr, len);
905 }
906
907 /* Insert/remove unaligned watchpoint by calling
908    aarch64_align_watchpoint repeatedly until the whole watched region,
909    as represented by ADDR and LEN, has been properly aligned and ready
910    to be written to one or more hardware watchpoint registers.
911    IS_INSERT indicates whether this is an insertion or a deletion.
912    Return 0 if succeed.  */
913
914 static int
915 aarch64_handle_unaligned_watchpoint (enum target_point_type type,
916                                      CORE_ADDR addr, int len, int is_insert)
917 {
918   struct aarch64_debug_reg_state *state
919     = aarch64_get_debug_reg_state ();
920
921   while (len > 0)
922     {
923       CORE_ADDR aligned_addr;
924       int aligned_len, ret;
925
926       aarch64_align_watchpoint (addr, len, &aligned_addr, &aligned_len,
927                                 &addr, &len);
928
929       if (is_insert)
930         ret = aarch64_dr_state_insert_one_point (state, type, aligned_addr,
931                                                  aligned_len);
932       else
933         ret = aarch64_dr_state_remove_one_point (state, type, aligned_addr,
934                                                  aligned_len);
935
936       if (debug_hw_points)
937         fprintf (stderr,
938  "handle_unaligned_watchpoint: is_insert: %d\n"
939  "                             aligned_addr: 0x%s, aligned_len: %d\n"
940  "                                next_addr: 0x%s,    next_len: %d\n",
941                  is_insert, paddress (aligned_addr), aligned_len,
942                  paddress (addr), len);
943
944       if (ret != 0)
945         return ret;
946     }
947
948   return 0;
949 }
950
951 static int
952 aarch64_handle_watchpoint (enum target_point_type type, CORE_ADDR addr,
953                            int len, int is_insert)
954 {
955   if (aarch64_point_is_aligned (1 /* is_watchpoint */ , addr, len))
956     return aarch64_handle_aligned_watchpoint (type, addr, len, is_insert);
957   else
958     return aarch64_handle_unaligned_watchpoint (type, addr, len, is_insert);
959 }
960
961 /* Insert a hardware breakpoint/watchpoint.
962    It actually only records the info of the to-be-inserted bp/wp;
963    the actual insertion will happen when threads are resumed.
964
965    Return 0 if succeed;
966    Return 1 if TYPE is unsupported type;
967    Return -1 if an error occurs.  */
968
969 static int
970 aarch64_insert_point (char type, CORE_ADDR addr, int len)
971 {
972   int ret;
973   enum target_point_type targ_type;
974
975   if (debug_hw_points)
976     fprintf (stderr, "insert_point on entry (addr=0x%08lx, len=%d)\n",
977              (unsigned long) addr, len);
978
979   /* Determine the type from the packet.  */
980   targ_type = Z_packet_to_point_type (type);
981   if (targ_type == point_type_unsupported)
982     return 1;
983
984   if (targ_type != hw_execute)
985     ret =
986       aarch64_handle_watchpoint (targ_type, addr, len, 1 /* is_insert */);
987   else
988     ret =
989       aarch64_handle_breakpoint (targ_type, addr, len, 1 /* is_insert */);
990
991   if (debug_hw_points > 1)
992     aarch64_show_debug_reg_state (aarch64_get_debug_reg_state (),
993                                   "insert_point", addr, len, targ_type);
994
995   return ret;
996 }
997
998 /* Remove a hardware breakpoint/watchpoint.
999    It actually only records the info of the to-be-removed bp/wp,
1000    the actual removal will be done when threads are resumed.
1001
1002    Return 0 if succeed;
1003    Return 1 if TYPE is an unsupported type;
1004    Return -1 if an error occurs.  */
1005
1006 static int
1007 aarch64_remove_point (char type, CORE_ADDR addr, int len)
1008 {
1009   int ret;
1010   enum target_point_type targ_type;
1011
1012   if (debug_hw_points)
1013     fprintf (stderr, "remove_point on entry (addr=0x%08lx, len=%d)\n",
1014              (unsigned long) addr, len);
1015
1016   /* Determine the type from the packet.  */
1017   targ_type = Z_packet_to_point_type (type);
1018   if (targ_type == point_type_unsupported)
1019     return 1;
1020
1021   /* Set up state pointers.  */
1022   if (targ_type != hw_execute)
1023     ret =
1024       aarch64_handle_watchpoint (targ_type, addr, len, 0 /* is_insert */);
1025   else
1026     ret =
1027       aarch64_handle_breakpoint (targ_type, addr, len, 0 /* is_insert */);
1028
1029   if (debug_hw_points > 1)
1030     aarch64_show_debug_reg_state (aarch64_get_debug_reg_state (),
1031                                   "remove_point", addr, len, targ_type);
1032
1033   return ret;
1034 }
1035
1036 /* Returns the address associated with the watchpoint that hit, if
1037    any; returns 0 otherwise.  */
1038
1039 static CORE_ADDR
1040 aarch64_stopped_data_address (void)
1041 {
1042   siginfo_t siginfo;
1043   int pid, i;
1044   struct aarch64_debug_reg_state *state;
1045
1046   pid = lwpid_of (get_thread_lwp (current_inferior));
1047
1048   /* Get the siginfo.  */
1049   if (ptrace (PTRACE_GETSIGINFO, pid, NULL, &siginfo) != 0)
1050     return (CORE_ADDR) 0;
1051
1052   /* Need to be a hardware breakpoint/watchpoint trap.  */
1053   if (siginfo.si_signo != SIGTRAP
1054       || (siginfo.si_code & 0xffff) != 0x0004 /* TRAP_HWBKPT */)
1055     return (CORE_ADDR) 0;
1056
1057   /* Check if the address matches any watched address.  */
1058   state = aarch64_get_debug_reg_state ();
1059   for (i = aarch64_num_wp_regs - 1; i >= 0; --i)
1060     {
1061       const unsigned int len = aarch64_watchpoint_length (state->dr_ctrl_wp[i]);
1062       const CORE_ADDR addr_trap = (CORE_ADDR) siginfo.si_addr;
1063       const CORE_ADDR addr_watch = state->dr_addr_wp[i];
1064       if (state->dr_ref_count_wp[i]
1065           && DR_CONTROL_ENABLED (state->dr_ctrl_wp[i])
1066           && addr_trap >= addr_watch
1067           && addr_trap < addr_watch + len)
1068         return addr_trap;
1069     }
1070
1071   return (CORE_ADDR) 0;
1072 }
1073
1074 /* Returns 1 if target was stopped due to a watchpoint hit, 0
1075    otherwise.  */
1076
1077 static int
1078 aarch64_stopped_by_watchpoint (void)
1079 {
1080   if (aarch64_stopped_data_address () != 0)
1081     return 1;
1082   else
1083     return 0;
1084 }
1085
1086 /* Fetch the thread-local storage pointer for libthread_db.  */
1087
1088 ps_err_e
1089 ps_get_thread_area (const struct ps_prochandle *ph,
1090                     lwpid_t lwpid, int idx, void **base)
1091 {
1092   struct iovec iovec;
1093   uint64_t reg;
1094
1095   iovec.iov_base = &reg;
1096   iovec.iov_len = sizeof (reg);
1097
1098   if (ptrace (PTRACE_GETREGSET, lwpid, NT_ARM_TLS, &iovec) != 0)
1099     return PS_ERR;
1100
1101   /* IDX is the bias from the thread pointer to the beginning of the
1102      thread descriptor.  It has to be subtracted due to implementation
1103      quirks in libthread_db.  */
1104   *base = (void *) (reg - idx);
1105
1106   return PS_OK;
1107 }
1108
1109 /* Called when a new process is created.  */
1110
1111 static struct arch_process_info *
1112 aarch64_linux_new_process (void)
1113 {
1114   struct arch_process_info *info = xcalloc (1, sizeof (*info));
1115
1116   aarch64_init_debug_reg_state (&info->debug_reg_state);
1117
1118   return info;
1119 }
1120
1121 /* Called when a new thread is detected.  */
1122
1123 static struct arch_lwp_info *
1124 aarch64_linux_new_thread (void)
1125 {
1126   struct arch_lwp_info *info = xcalloc (1, sizeof (*info));
1127
1128   /* Mark that all the hardware breakpoint/watchpoint register pairs
1129      for this thread need to be initialized (with data from
1130      aarch_process_info.debug_reg_state).  */
1131   DR_MARK_ALL_CHANGED (info->dr_changed_bp, aarch64_num_bp_regs);
1132   DR_MARK_ALL_CHANGED (info->dr_changed_wp, aarch64_num_wp_regs);
1133
1134   return info;
1135 }
1136
1137 /* Called when resuming a thread.
1138    If the debug regs have changed, update the thread's copies.  */
1139
1140 static void
1141 aarch64_linux_prepare_to_resume (struct lwp_info *lwp)
1142 {
1143   ptid_t ptid = ptid_of (lwp);
1144   struct arch_lwp_info *info = lwp->arch_private;
1145
1146   if (DR_HAS_CHANGED (info->dr_changed_bp)
1147       || DR_HAS_CHANGED (info->dr_changed_wp))
1148     {
1149       int tid = ptid_get_lwp (ptid);
1150       struct process_info *proc = find_process_pid (ptid_get_pid (ptid));
1151       struct aarch64_debug_reg_state *state
1152         = &proc->private->arch_private->debug_reg_state;
1153
1154       if (debug_hw_points)
1155         fprintf (stderr, "prepare_to_resume thread %ld\n", lwpid_of (lwp));
1156
1157       /* Watchpoints.  */
1158       if (DR_HAS_CHANGED (info->dr_changed_wp))
1159         {
1160           aarch64_linux_set_debug_regs (state, tid, 1);
1161           DR_CLEAR_CHANGED (info->dr_changed_wp);
1162         }
1163
1164       /* Breakpoints.  */
1165       if (DR_HAS_CHANGED (info->dr_changed_bp))
1166         {
1167           aarch64_linux_set_debug_regs (state, tid, 0);
1168           DR_CLEAR_CHANGED (info->dr_changed_bp);
1169         }
1170     }
1171 }
1172
1173 /* ptrace hardware breakpoint resource info is formatted as follows:
1174
1175    31             24             16               8              0
1176    +---------------+--------------+---------------+---------------+
1177    |   RESERVED    |   RESERVED   |   DEBUG_ARCH  |  NUM_SLOTS    |
1178    +---------------+--------------+---------------+---------------+  */
1179
1180 #define AARCH64_DEBUG_NUM_SLOTS(x) ((x) & 0xff)
1181 #define AARCH64_DEBUG_ARCH(x) (((x) >> 8) & 0xff)
1182 #define AARCH64_DEBUG_ARCH_V8 0x6
1183
1184 static void
1185 aarch64_arch_setup (void)
1186 {
1187   int pid;
1188   struct iovec iov;
1189   struct user_hwdebug_state dreg_state;
1190
1191   init_registers_aarch64 ();
1192
1193   pid = lwpid_of (get_thread_lwp (current_inferior));
1194   iov.iov_base = &dreg_state;
1195   iov.iov_len = sizeof (dreg_state);
1196
1197   /* Get hardware watchpoint register info.  */
1198   if (ptrace (PTRACE_GETREGSET, pid, NT_ARM_HW_WATCH, &iov) == 0
1199       && AARCH64_DEBUG_ARCH (dreg_state.dbg_info) == AARCH64_DEBUG_ARCH_V8)
1200     {
1201       aarch64_num_wp_regs = AARCH64_DEBUG_NUM_SLOTS (dreg_state.dbg_info);
1202       if (aarch64_num_wp_regs > AARCH64_HWP_MAX_NUM)
1203         {
1204           warning ("Unexpected number of hardware watchpoint registers reported"
1205                    " by ptrace, got %d, expected %d.",
1206                    aarch64_num_wp_regs, AARCH64_HWP_MAX_NUM);
1207           aarch64_num_wp_regs = AARCH64_HWP_MAX_NUM;
1208         }
1209     }
1210   else
1211     {
1212       warning ("Unable to determine the number of hardware watchpoints"
1213                " available.");
1214       aarch64_num_wp_regs = 0;
1215     }
1216
1217   /* Get hardware breakpoint register info.  */
1218   if (ptrace (PTRACE_GETREGSET, pid, NT_ARM_HW_BREAK, &iov) == 0
1219       && AARCH64_DEBUG_ARCH (dreg_state.dbg_info) == AARCH64_DEBUG_ARCH_V8)
1220     {
1221       aarch64_num_bp_regs = AARCH64_DEBUG_NUM_SLOTS (dreg_state.dbg_info);
1222       if (aarch64_num_bp_regs > AARCH64_HBP_MAX_NUM)
1223         {
1224           warning ("Unexpected number of hardware breakpoint registers reported"
1225                    " by ptrace, got %d, expected %d.",
1226                    aarch64_num_bp_regs, AARCH64_HBP_MAX_NUM);
1227           aarch64_num_bp_regs = AARCH64_HBP_MAX_NUM;
1228         }
1229     }
1230   else
1231     {
1232       warning ("Unable to determine the number of hardware breakpoints"
1233                " available.");
1234       aarch64_num_bp_regs = 0;
1235     }
1236 }
1237
1238 struct regset_info target_regsets[] =
1239 {
1240   { PTRACE_GETREGSET, PTRACE_SETREGSET, NT_PRSTATUS,
1241     sizeof (struct user_pt_regs), GENERAL_REGS,
1242     aarch64_fill_gregset, aarch64_store_gregset },
1243   { PTRACE_GETREGSET, PTRACE_SETREGSET, NT_FPREGSET,
1244     sizeof (struct user_fpsimd_state), FP_REGS,
1245     aarch64_fill_fpregset, aarch64_store_fpregset
1246   },
1247   { 0, 0, 0, -1, -1, NULL, NULL }
1248 };
1249
1250 struct linux_target_ops the_low_target =
1251 {
1252   aarch64_arch_setup,
1253   AARCH64_NUM_REGS,
1254   aarch64_regmap,
1255   NULL,
1256   aarch64_cannot_fetch_register,
1257   aarch64_cannot_store_register,
1258   NULL,
1259   aarch64_get_pc,
1260   aarch64_set_pc,
1261   (const unsigned char *) &aarch64_breakpoint,
1262   aarch64_breakpoint_len,
1263   NULL,
1264   0,
1265   aarch64_breakpoint_at,
1266   aarch64_insert_point,
1267   aarch64_remove_point,
1268   aarch64_stopped_by_watchpoint,
1269   aarch64_stopped_data_address,
1270   NULL,
1271   NULL,
1272   NULL,
1273   aarch64_linux_new_process,
1274   aarch64_linux_new_thread,
1275   aarch64_linux_prepare_to_resume,
1276 };