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