Update years in copyright notice for the GDB files.
[external/binutils.git] / gdb / i386-nat.c
1 /* Native-dependent code for the i386.
2
3    Copyright (C) 2001-2013 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "i386-nat.h"
22 #include "breakpoint.h"
23 #include "command.h"
24 #include "gdbcmd.h"
25 #include "target.h"
26 #include "gdb_assert.h"
27 #include "inferior.h"
28
29 /* Support for hardware watchpoints and breakpoints using the i386
30    debug registers.
31
32    This provides several functions for inserting and removing
33    hardware-assisted breakpoints and watchpoints, testing if one or
34    more of the watchpoints triggered and at what address, checking
35    whether a given region can be watched, etc.
36
37    The functions below implement debug registers sharing by reference
38    counts, and allow to watch regions up to 16 bytes long.  */
39
40 struct i386_dr_low_type i386_dr_low;
41
42
43 /* Support for 8-byte wide hw watchpoints.  */
44 #define TARGET_HAS_DR_LEN_8 (i386_dr_low.debug_register_length == 8)
45
46 /* DR7 Debug Control register fields.  */
47
48 /* How many bits to skip in DR7 to get to R/W and LEN fields.  */
49 #define DR_CONTROL_SHIFT        16
50 /* How many bits in DR7 per R/W and LEN field for each watchpoint.  */
51 #define DR_CONTROL_SIZE         4
52
53 /* Watchpoint/breakpoint read/write fields in DR7.  */
54 #define DR_RW_EXECUTE   (0x0)   /* Break on instruction execution.  */
55 #define DR_RW_WRITE     (0x1)   /* Break on data writes.  */
56 #define DR_RW_READ      (0x3)   /* Break on data reads or writes.  */
57
58 /* This is here for completeness.  No platform supports this
59    functionality yet (as of March 2001).  Note that the DE flag in the
60    CR4 register needs to be set to support this.  */
61 #ifndef DR_RW_IORW
62 #define DR_RW_IORW      (0x2)   /* Break on I/O reads or writes.  */
63 #endif
64
65 /* Watchpoint/breakpoint length fields in DR7.  The 2-bit left shift
66    is so we could OR this with the read/write field defined above.  */
67 #define DR_LEN_1        (0x0 << 2) /* 1-byte region watch or breakpoint.  */
68 #define DR_LEN_2        (0x1 << 2) /* 2-byte region watch.  */
69 #define DR_LEN_4        (0x3 << 2) /* 4-byte region watch.  */
70 #define DR_LEN_8        (0x2 << 2) /* 8-byte region watch (AMD64).  */
71
72 /* Local and Global Enable flags in DR7.
73
74    When the Local Enable flag is set, the breakpoint/watchpoint is
75    enabled only for the current task; the processor automatically
76    clears this flag on every task switch.  When the Global Enable flag
77    is set, the breakpoint/watchpoint is enabled for all tasks; the
78    processor never clears this flag.
79
80    Currently, all watchpoint are locally enabled.  If you need to
81    enable them globally, read the comment which pertains to this in
82    i386_insert_aligned_watchpoint below.  */
83 #define DR_LOCAL_ENABLE_SHIFT   0 /* Extra shift to the local enable bit.  */
84 #define DR_GLOBAL_ENABLE_SHIFT  1 /* Extra shift to the global enable bit.  */
85 #define DR_ENABLE_SIZE          2 /* Two enable bits per debug register.  */
86
87 /* Local and global exact breakpoint enable flags (a.k.a. slowdown
88    flags).  These are only required on i386, to allow detection of the
89    exact instruction which caused a watchpoint to break; i486 and
90    later processors do that automatically.  We set these flags for
91    backwards compatibility.  */
92 #define DR_LOCAL_SLOWDOWN       (0x100)
93 #define DR_GLOBAL_SLOWDOWN      (0x200)
94
95 /* Fields reserved by Intel.  This includes the GD (General Detect
96    Enable) flag, which causes a debug exception to be generated when a
97    MOV instruction accesses one of the debug registers.
98
99    FIXME: My Intel manual says we should use 0xF800, not 0xFC00.  */
100 #define DR_CONTROL_RESERVED     (0xFC00)
101
102 /* Auxiliary helper macros.  */
103
104 /* A value that masks all fields in DR7 that are reserved by Intel.  */
105 #define I386_DR_CONTROL_MASK    (~DR_CONTROL_RESERVED)
106
107 /* The I'th debug register is vacant if its Local and Global Enable
108    bits are reset in the Debug Control register.  */
109 #define I386_DR_VACANT(state, i)                                        \
110   (((state)->dr_control_mirror & (3 << (DR_ENABLE_SIZE * (i)))) == 0)
111
112 /* Locally enable the break/watchpoint in the I'th debug register.  */
113 #define I386_DR_LOCAL_ENABLE(state, i) \
114   do { \
115     (state)->dr_control_mirror |= \
116       (1 << (DR_LOCAL_ENABLE_SHIFT + DR_ENABLE_SIZE * (i))); \
117   } while (0)
118
119 /* Globally enable the break/watchpoint in the I'th debug register.  */
120 #define I386_DR_GLOBAL_ENABLE(state, i) \
121   do { \
122     (state)->dr_control_mirror |= \
123       (1 << (DR_GLOBAL_ENABLE_SHIFT + DR_ENABLE_SIZE * (i))); \
124   } while (0)
125
126 /* Disable the break/watchpoint in the I'th debug register.  */
127 #define I386_DR_DISABLE(state, i) \
128   do { \
129     (state)->dr_control_mirror &= \
130       ~(3 << (DR_ENABLE_SIZE * (i))); \
131   } while (0)
132
133 /* Set in DR7 the RW and LEN fields for the I'th debug register.  */
134 #define I386_DR_SET_RW_LEN(state, i, rwlen) \
135   do { \
136     (state)->dr_control_mirror &= \
137       ~(0x0f << (DR_CONTROL_SHIFT + DR_CONTROL_SIZE * (i))); \
138     (state)->dr_control_mirror |= \
139       ((rwlen) << (DR_CONTROL_SHIFT + DR_CONTROL_SIZE * (i))); \
140   } while (0)
141
142 /* Get from DR7 the RW and LEN fields for the I'th debug register.  */
143 #define I386_DR_GET_RW_LEN(dr7, i) \
144   (((dr7) \
145     >> (DR_CONTROL_SHIFT + DR_CONTROL_SIZE * (i))) & 0x0f)
146
147 /* Mask that this I'th watchpoint has triggered.  */
148 #define I386_DR_WATCH_MASK(i)   (1 << (i))
149
150 /* Did the watchpoint whose address is in the I'th register break?  */
151 #define I386_DR_WATCH_HIT(dr6, i) ((dr6) & (1 << (i)))
152
153 /* A macro to loop over all debug registers.  */
154 #define ALL_DEBUG_REGISTERS(i)  for (i = 0; i < DR_NADDR; i++)
155
156 /* Clear the reference counts and forget everything we knew about the
157    debug registers.  */
158
159 static void
160 i386_init_dregs (struct i386_debug_reg_state *state)
161 {
162   int i;
163
164   ALL_DEBUG_REGISTERS (i)
165     {
166       state->dr_mirror[i] = 0;
167       state->dr_ref_count[i] = 0;
168     }
169   state->dr_control_mirror = 0;
170   state->dr_status_mirror  = 0;
171 }
172
173 /* Per-inferior data key.  */
174 static const struct inferior_data *i386_inferior_data;
175
176 /* Per-inferior data.  */
177 struct i386_inferior_data
178 {
179   /* Copy of i386 hardware debug registers for performance reasons.  */
180   struct i386_debug_reg_state state;
181 };
182
183 /* Per-inferior hook for register_inferior_data_with_cleanup.  */
184
185 static void
186 i386_inferior_data_cleanup (struct inferior *inf, void *arg)
187 {
188   struct i386_inferior_data *inf_data = arg;
189
190   xfree (inf_data);
191 }
192
193 /* Get data specific for INFERIOR_PTID LWP.  Return special data area
194    for processes being detached.  */
195
196 static struct i386_inferior_data *
197 i386_inferior_data_get (void)
198 {
199   struct inferior *inf = current_inferior ();
200   struct i386_inferior_data *inf_data;
201
202   inf_data = inferior_data (inf, i386_inferior_data);
203   if (inf_data == NULL)
204     {
205       inf_data = xzalloc (sizeof (*inf_data));
206       set_inferior_data (current_inferior (), i386_inferior_data, inf_data);
207     }
208
209   if (inf->pid != ptid_get_pid (inferior_ptid))
210     {
211       /* INFERIOR_PTID is being detached from the inferior INF.
212          Provide local cache specific for the detached LWP.  */
213
214       static struct i386_inferior_data detached_inf_data_local;
215       static int detached_inf_pid = -1;
216
217       if (detached_inf_pid != ptid_get_pid (inferior_ptid))
218         {
219           /* Reinitialize the local cache if INFERIOR_PTID is
220              different from the LWP last detached.
221  
222              Linux kernel before 2.6.33 commit
223              72f674d203cd230426437cdcf7dd6f681dad8b0d
224              will inherit hardware debug registers from parent
225              on fork/vfork/clone.  Newer Linux kernels create such tasks with
226              zeroed debug registers.
227
228              GDB will remove all breakpoints (and watchpoints) from the forked
229              off process.  We also need to reset the debug registers in that
230              process to be compatible with the older Linux kernels.
231
232              Copy the debug registers mirrors into the new process so that all
233              breakpoints and watchpoints can be removed together.  The debug
234              registers mirror will become zeroed in the end before detaching
235              the forked off process.  */
236
237           detached_inf_pid = ptid_get_pid (inferior_ptid);
238           detached_inf_data_local = *inf_data;
239         }
240
241       return &detached_inf_data_local;
242     }
243
244   return inf_data;
245 }
246
247 /* Get debug registers state for INFERIOR_PTID, see
248    i386_inferior_data_get.  */
249
250 struct i386_debug_reg_state *
251 i386_debug_reg_state (void)
252 {
253   return &i386_inferior_data_get ()->state;
254 }
255
256 /* Whether or not to print the mirrored debug registers.  */
257 static int maint_show_dr;
258
259 /* Types of operations supported by i386_handle_nonaligned_watchpoint.  */
260 typedef enum { WP_INSERT, WP_REMOVE, WP_COUNT } i386_wp_op_t;
261
262 /* Internal functions.  */
263
264 /* Return the value of a 4-bit field for DR7 suitable for watching a
265    region of LEN bytes for accesses of type TYPE.  LEN is assumed to
266    have the value of 1, 2, or 4.  */
267 static unsigned i386_length_and_rw_bits (int len, enum target_hw_bp_type type);
268
269 /* Insert a watchpoint at address ADDR, which is assumed to be aligned
270    according to the length of the region to watch.  LEN_RW_BITS is the
271    value of the bit-field from DR7 which describes the length and
272    access type of the region to be watched by this watchpoint.  Return
273    0 on success, -1 on failure.  */
274 static int i386_insert_aligned_watchpoint (struct i386_debug_reg_state *state,
275                                            CORE_ADDR addr,
276                                            unsigned len_rw_bits);
277
278 /* Remove a watchpoint at address ADDR, which is assumed to be aligned
279    according to the length of the region to watch.  LEN_RW_BITS is the
280    value of the bits from DR7 which describes the length and access
281    type of the region watched by this watchpoint.  Return 0 on
282    success, -1 on failure.  */
283 static int i386_remove_aligned_watchpoint (struct i386_debug_reg_state *state,
284                                            CORE_ADDR addr,
285                                            unsigned len_rw_bits);
286
287 /* Insert or remove a (possibly non-aligned) watchpoint, or count the
288    number of debug registers required to watch a region at address
289    ADDR whose length is LEN for accesses of type TYPE.  Return 0 on
290    successful insertion or removal, a positive number when queried
291    about the number of registers, or -1 on failure.  If WHAT is not a
292    valid value, bombs through internal_error.  */
293 static int i386_handle_nonaligned_watchpoint (struct i386_debug_reg_state *state,
294                                               i386_wp_op_t what,
295                                               CORE_ADDR addr, int len,
296                                               enum target_hw_bp_type type);
297
298 /* Implementation.  */
299
300 /* Clear the reference counts and forget everything we knew about the
301    debug registers.  */
302
303 void
304 i386_cleanup_dregs (void)
305 {
306   struct i386_debug_reg_state *state = i386_debug_reg_state ();
307
308   i386_init_dregs (state);
309 }
310
311 /* Print the values of the mirrored debug registers.  This is called
312    when maint_show_dr is non-zero.  To set that up, type "maint
313    show-debug-regs" at GDB's prompt.  */
314
315 static void
316 i386_show_dr (struct i386_debug_reg_state *state,
317               const char *func, CORE_ADDR addr,
318               int len, enum target_hw_bp_type type)
319 {
320   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
321   int i;
322
323   puts_unfiltered (func);
324   if (addr || len)
325     printf_unfiltered (" (addr=%lx, len=%d, type=%s)",
326                        /* This code is for ia32, so casting CORE_ADDR
327                           to unsigned long should be okay.  */
328                        (unsigned long)addr, len,
329                        type == hw_write ? "data-write"
330                        : (type == hw_read ? "data-read"
331                           : (type == hw_access ? "data-read/write"
332                              : (type == hw_execute ? "instruction-execute"
333                                 /* FIXME: if/when I/O read/write
334                                    watchpoints are supported, add them
335                                    here.  */
336                                 : "??unknown??"))));
337   puts_unfiltered (":\n");
338   printf_unfiltered ("\tCONTROL (DR7): %s          STATUS (DR6): %s\n",
339                      phex (state->dr_control_mirror, 8),
340                      phex (state->dr_status_mirror, 8));
341   ALL_DEBUG_REGISTERS(i)
342     {
343       printf_unfiltered ("\
344 \tDR%d: addr=0x%s, ref.count=%d  DR%d: addr=0x%s, ref.count=%d\n",
345                          i, phex (state->dr_mirror[i], addr_size),
346                          state->dr_ref_count[i],
347                          i + 1, phex (state->dr_mirror[i + 1], addr_size),
348                          state->dr_ref_count[i+1]);
349       i++;
350     }
351 }
352
353 /* Return the value of a 4-bit field for DR7 suitable for watching a
354    region of LEN bytes for accesses of type TYPE.  LEN is assumed to
355    have the value of 1, 2, or 4.  */
356
357 static unsigned
358 i386_length_and_rw_bits (int len, enum target_hw_bp_type type)
359 {
360   unsigned rw;
361
362   switch (type)
363     {
364       case hw_execute:
365         rw = DR_RW_EXECUTE;
366         break;
367       case hw_write:
368         rw = DR_RW_WRITE;
369         break;
370       case hw_read:
371         internal_error (__FILE__, __LINE__,
372                         _("The i386 doesn't support "
373                           "data-read watchpoints.\n"));
374       case hw_access:
375         rw = DR_RW_READ;
376         break;
377 #if 0
378         /* Not yet supported.  */
379       case hw_io_access:
380         rw = DR_RW_IORW;
381         break;
382 #endif
383       default:
384         internal_error (__FILE__, __LINE__, _("\
385 Invalid hardware breakpoint type %d in i386_length_and_rw_bits.\n"),
386                         (int) type);
387     }
388
389   switch (len)
390     {
391       case 1:
392         return (DR_LEN_1 | rw);
393       case 2:
394         return (DR_LEN_2 | rw);
395       case 4:
396         return (DR_LEN_4 | rw);
397       case 8:
398         if (TARGET_HAS_DR_LEN_8)
399           return (DR_LEN_8 | rw);
400         /* ELSE FALL THROUGH */
401       default:
402         internal_error (__FILE__, __LINE__, _("\
403 Invalid hardware breakpoint length %d in i386_length_and_rw_bits.\n"), len);
404     }
405 }
406
407 /* Insert a watchpoint at address ADDR, which is assumed to be aligned
408    according to the length of the region to watch.  LEN_RW_BITS is the
409    value of the bits from DR7 which describes the length and access
410    type of the region to be watched by this watchpoint.  Return 0 on
411    success, -1 on failure.  */
412
413 static int
414 i386_insert_aligned_watchpoint (struct i386_debug_reg_state *state,
415                                 CORE_ADDR addr, unsigned len_rw_bits)
416 {
417   int i;
418
419   if (!i386_dr_low.set_addr || !i386_dr_low.set_control)
420     return -1;
421
422   /* First, look for an occupied debug register with the same address
423      and the same RW and LEN definitions.  If we find one, we can
424      reuse it for this watchpoint as well (and save a register).  */
425   ALL_DEBUG_REGISTERS(i)
426     {
427       if (!I386_DR_VACANT (state, i)
428           && state->dr_mirror[i] == addr
429           && I386_DR_GET_RW_LEN (state->dr_control_mirror, i) == len_rw_bits)
430         {
431           state->dr_ref_count[i]++;
432           return 0;
433         }
434     }
435
436   /* Next, look for a vacant debug register.  */
437   ALL_DEBUG_REGISTERS(i)
438     {
439       if (I386_DR_VACANT (state, i))
440         break;
441     }
442
443   /* No more debug registers!  */
444   if (i >= DR_NADDR)
445     return -1;
446
447   /* Now set up the register I to watch our region.  */
448
449   /* Record the info in our local mirrored array.  */
450   state->dr_mirror[i] = addr;
451   state->dr_ref_count[i] = 1;
452   I386_DR_SET_RW_LEN (state, i, len_rw_bits);
453   /* Note: we only enable the watchpoint locally, i.e. in the current
454      task.  Currently, no i386 target allows or supports global
455      watchpoints; however, if any target would want that in the
456      future, GDB should probably provide a command to control whether
457      to enable watchpoints globally or locally, and the code below
458      should use global or local enable and slow-down flags as
459      appropriate.  */
460   I386_DR_LOCAL_ENABLE (state, i);
461   state->dr_control_mirror |= DR_LOCAL_SLOWDOWN;
462   state->dr_control_mirror &= I386_DR_CONTROL_MASK;
463
464   return 0;
465 }
466
467 /* Remove a watchpoint at address ADDR, which is assumed to be aligned
468    according to the length of the region to watch.  LEN_RW_BITS is the
469    value of the bits from DR7 which describes the length and access
470    type of the region watched by this watchpoint.  Return 0 on
471    success, -1 on failure.  */
472
473 static int
474 i386_remove_aligned_watchpoint (struct i386_debug_reg_state *state,
475                                 CORE_ADDR addr, unsigned len_rw_bits)
476 {
477   int i, retval = -1;
478
479   ALL_DEBUG_REGISTERS(i)
480     {
481       if (!I386_DR_VACANT (state, i)
482           && state->dr_mirror[i] == addr
483           && I386_DR_GET_RW_LEN (state->dr_control_mirror, i) == len_rw_bits)
484         {
485           if (--state->dr_ref_count[i] == 0) /* no longer in use?  */
486             {
487               /* Reset our mirror.  */
488               state->dr_mirror[i] = 0;
489               I386_DR_DISABLE (state, i);
490             }
491           retval = 0;
492         }
493     }
494
495   return retval;
496 }
497
498 /* Insert or remove a (possibly non-aligned) watchpoint, or count the
499    number of debug registers required to watch a region at address
500    ADDR whose length is LEN for accesses of type TYPE.  Return 0 on
501    successful insertion or removal, a positive number when queried
502    about the number of registers, or -1 on failure.  If WHAT is not a
503    valid value, bombs through internal_error.  */
504
505 static int
506 i386_handle_nonaligned_watchpoint (struct i386_debug_reg_state *state,
507                                    i386_wp_op_t what, CORE_ADDR addr, int len,
508                                    enum target_hw_bp_type type)
509 {
510   int retval = 0;
511   int max_wp_len = TARGET_HAS_DR_LEN_8 ? 8 : 4;
512
513   static int size_try_array[8][8] =
514   {
515     {1, 1, 1, 1, 1, 1, 1, 1},   /* Trying size one.  */
516     {2, 1, 2, 1, 2, 1, 2, 1},   /* Trying size two.  */
517     {2, 1, 2, 1, 2, 1, 2, 1},   /* Trying size three.  */
518     {4, 1, 2, 1, 4, 1, 2, 1},   /* Trying size four.  */
519     {4, 1, 2, 1, 4, 1, 2, 1},   /* Trying size five.  */
520     {4, 1, 2, 1, 4, 1, 2, 1},   /* Trying size six.  */
521     {4, 1, 2, 1, 4, 1, 2, 1},   /* Trying size seven.  */
522     {8, 1, 2, 1, 4, 1, 2, 1},   /* Trying size eight.  */
523   };
524
525   while (len > 0)
526     {
527       int align = addr % max_wp_len;
528       /* Four (eight on AMD64) is the maximum length a debug register
529          can watch.  */
530       int try = (len > max_wp_len ? (max_wp_len - 1) : len - 1);
531       int size = size_try_array[try][align];
532
533       if (what == WP_COUNT)
534         {
535           /* size_try_array[] is defined such that each iteration
536              through the loop is guaranteed to produce an address and a
537              size that can be watched with a single debug register.
538              Thus, for counting the registers required to watch a
539              region, we simply need to increment the count on each
540              iteration.  */
541           retval++;
542         }
543       else
544         {
545           unsigned len_rw = i386_length_and_rw_bits (size, type);
546
547           if (what == WP_INSERT)
548             retval = i386_insert_aligned_watchpoint (state, addr, len_rw);
549           else if (what == WP_REMOVE)
550             retval = i386_remove_aligned_watchpoint (state, addr, len_rw);
551           else
552             internal_error (__FILE__, __LINE__, _("\
553 Invalid value %d of operation in i386_handle_nonaligned_watchpoint.\n"),
554                             (int)what);
555           if (retval)
556             break;
557         }
558
559       addr += size;
560       len -= size;
561     }
562
563   return retval;
564 }
565
566 /* Update the inferior's debug registers with the new debug registers
567    state, in NEW_STATE, and then update our local mirror to match.  */
568
569 static void
570 i386_update_inferior_debug_regs (struct i386_debug_reg_state *new_state)
571 {
572   struct i386_debug_reg_state *state = i386_debug_reg_state ();
573   int i;
574
575   ALL_DEBUG_REGISTERS (i)
576     {
577       if (I386_DR_VACANT (new_state, i) != I386_DR_VACANT (state, i))
578         i386_dr_low.set_addr (i, new_state->dr_mirror[i]);
579       else
580         gdb_assert (new_state->dr_mirror[i] == state->dr_mirror[i]);
581     }
582
583   if (new_state->dr_control_mirror != state->dr_control_mirror)
584     i386_dr_low.set_control (new_state->dr_control_mirror);
585
586   *state = *new_state;
587 }
588
589 /* Insert a watchpoint to watch a memory region which starts at
590    address ADDR and whose length is LEN bytes.  Watch memory accesses
591    of the type TYPE.  Return 0 on success, -1 on failure.  */
592
593 static int
594 i386_insert_watchpoint (CORE_ADDR addr, int len, int type,
595                         struct expression *cond)
596 {
597   struct i386_debug_reg_state *state = i386_debug_reg_state ();
598   int retval;
599   /* Work on a local copy of the debug registers, and on success,
600      commit the change back to the inferior.  */
601   struct i386_debug_reg_state local_state = *state;
602
603   if (type == hw_read)
604     return 1; /* unsupported */
605
606   if (((len != 1 && len !=2 && len !=4) && !(TARGET_HAS_DR_LEN_8 && len == 8))
607       || addr % len != 0)
608     retval = i386_handle_nonaligned_watchpoint (&local_state,
609                                                 WP_INSERT, addr, len, type);
610   else
611     {
612       unsigned len_rw = i386_length_and_rw_bits (len, type);
613
614       retval = i386_insert_aligned_watchpoint (&local_state,
615                                                addr, len_rw);
616     }
617
618   if (retval == 0)
619     i386_update_inferior_debug_regs (&local_state);
620
621   if (maint_show_dr)
622     i386_show_dr (state, "insert_watchpoint", addr, len, type);
623
624   return retval;
625 }
626
627 /* Remove a watchpoint that watched the memory region which starts at
628    address ADDR, whose length is LEN bytes, and for accesses of the
629    type TYPE.  Return 0 on success, -1 on failure.  */
630 static int
631 i386_remove_watchpoint (CORE_ADDR addr, int len, int type,
632                         struct expression *cond)
633 {
634   struct i386_debug_reg_state *state = i386_debug_reg_state ();
635   int retval;
636   /* Work on a local copy of the debug registers, and on success,
637      commit the change back to the inferior.  */
638   struct i386_debug_reg_state local_state = *state;
639
640   if (((len != 1 && len !=2 && len !=4) && !(TARGET_HAS_DR_LEN_8 && len == 8))
641       || addr % len != 0)
642     retval = i386_handle_nonaligned_watchpoint (&local_state,
643                                                 WP_REMOVE, addr, len, type);
644   else
645     {
646       unsigned len_rw = i386_length_and_rw_bits (len, type);
647
648       retval = i386_remove_aligned_watchpoint (&local_state,
649                                                addr, len_rw);
650     }
651
652   if (retval == 0)
653     i386_update_inferior_debug_regs (&local_state);
654
655   if (maint_show_dr)
656     i386_show_dr (state, "remove_watchpoint", addr, len, type);
657
658   return retval;
659 }
660
661 /* Return non-zero if we can watch a memory region that starts at
662    address ADDR and whose length is LEN bytes.  */
663
664 static int
665 i386_region_ok_for_watchpoint (CORE_ADDR addr, int len)
666 {
667   struct i386_debug_reg_state *state = i386_debug_reg_state ();
668   int nregs;
669
670   /* Compute how many aligned watchpoints we would need to cover this
671      region.  */
672   nregs = i386_handle_nonaligned_watchpoint (state,
673                                              WP_COUNT, addr, len, hw_write);
674   return nregs <= DR_NADDR ? 1 : 0;
675 }
676
677 /* If the inferior has some watchpoint that triggered, set the
678    address associated with that watchpoint and return non-zero.
679    Otherwise, return zero.  */
680
681 static int
682 i386_stopped_data_address (struct target_ops *ops, CORE_ADDR *addr_p)
683 {
684   struct i386_debug_reg_state *state = i386_debug_reg_state ();
685   CORE_ADDR addr = 0;
686   int i;
687   int rc = 0;
688   /* The current thread's DR_STATUS.  We always need to read this to
689      check whether some watchpoint caused the trap.  */
690   unsigned status;
691   /* We need DR_CONTROL as well, but only iff DR_STATUS indicates a
692      data breakpoint trap.  Only fetch it when necessary, to avoid an
693      unnecessary extra syscall when no watchpoint triggered.  */
694   int control_p = 0;
695   unsigned control = 0;
696
697   /* In non-stop/async, threads can be running while we change the
698      STATE (and friends).  Say, we set a watchpoint, and let threads
699      resume.  Now, say you delete the watchpoint, or add/remove
700      watchpoints such that STATE changes while threads are running.
701      On targets that support non-stop, inserting/deleting watchpoints
702      updates the STATE only.  It does not update the real thread's
703      debug registers; that's only done prior to resume.  Instead, if
704      threads are running when the mirror changes, a temporary and
705      transparent stop on all threads is forced so they can get their
706      copy of the debug registers updated on re-resume.  Now, say,
707      a thread hit a watchpoint before having been updated with the new
708      STATE contents, and we haven't yet handled the corresponding
709      SIGTRAP.  If we trusted STATE below, we'd mistake the real
710      trapped address (from the last time we had updated debug
711      registers in the thread) with whatever was currently in STATE.
712      So to fix this, STATE always represents intention, what we _want_
713      threads to have in debug registers.  To get at the address and
714      cause of the trap, we need to read the state the thread still has
715      in its debug registers.
716
717      In sum, always get the current debug register values the current
718      thread has, instead of trusting the global mirror.  If the thread
719      was running when we last changed watchpoints, the mirror no
720      longer represents what was set in this thread's debug
721      registers.  */
722   status = i386_dr_low.get_status ();
723
724   ALL_DEBUG_REGISTERS(i)
725     {
726       if (!I386_DR_WATCH_HIT (status, i))
727         continue;
728
729       if (!control_p)
730         {
731           control = i386_dr_low.get_control ();
732           control_p = 1;
733         }
734
735       /* This second condition makes sure DRi is set up for a data
736          watchpoint, not a hardware breakpoint.  The reason is that
737          GDB doesn't call the target_stopped_data_address method
738          except for data watchpoints.  In other words, I'm being
739          paranoiac.  */
740       if (I386_DR_GET_RW_LEN (control, i) != 0)
741         {
742           addr = i386_dr_low.get_addr (i);
743           rc = 1;
744           if (maint_show_dr)
745             i386_show_dr (state, "watchpoint_hit", addr, -1, hw_write);
746         }
747     }
748   if (maint_show_dr && addr == 0)
749     i386_show_dr (state, "stopped_data_addr", 0, 0, hw_write);
750
751   if (rc)
752     *addr_p = addr;
753   return rc;
754 }
755
756 static int
757 i386_stopped_by_watchpoint (void)
758 {
759   CORE_ADDR addr = 0;
760   return i386_stopped_data_address (&current_target, &addr);
761 }
762
763 /* Insert a hardware-assisted breakpoint at BP_TGT->placed_address.
764    Return 0 on success, EBUSY on failure.  */
765 static int
766 i386_insert_hw_breakpoint (struct gdbarch *gdbarch,
767                            struct bp_target_info *bp_tgt)
768 {
769   struct i386_debug_reg_state *state = i386_debug_reg_state ();
770   unsigned len_rw = i386_length_and_rw_bits (1, hw_execute);
771   CORE_ADDR addr = bp_tgt->placed_address;
772   /* Work on a local copy of the debug registers, and on success,
773      commit the change back to the inferior.  */
774   struct i386_debug_reg_state local_state = *state;
775   int retval = i386_insert_aligned_watchpoint (&local_state,
776                                                addr, len_rw) ? EBUSY : 0;
777
778   if (retval == 0)
779     i386_update_inferior_debug_regs (&local_state);
780
781   if (maint_show_dr)
782     i386_show_dr (state, "insert_hwbp", addr, 1, hw_execute);
783
784   return retval;
785 }
786
787 /* Remove a hardware-assisted breakpoint at BP_TGT->placed_address.
788    Return 0 on success, -1 on failure.  */
789
790 static int
791 i386_remove_hw_breakpoint (struct gdbarch *gdbarch,
792                            struct bp_target_info *bp_tgt)
793 {
794   struct i386_debug_reg_state *state = i386_debug_reg_state ();
795   unsigned len_rw = i386_length_and_rw_bits (1, hw_execute);
796   CORE_ADDR addr = bp_tgt->placed_address;
797   /* Work on a local copy of the debug registers, and on success,
798      commit the change back to the inferior.  */
799   struct i386_debug_reg_state local_state = *state;
800   int retval = i386_remove_aligned_watchpoint (&local_state,
801                                                addr, len_rw);
802
803   if (retval == 0)
804     i386_update_inferior_debug_regs (&local_state);
805
806   if (maint_show_dr)
807     i386_show_dr (state, "remove_hwbp", addr, 1, hw_execute);
808
809   return retval;
810 }
811
812 /* Returns the number of hardware watchpoints of type TYPE that we can
813    set.  Value is positive if we can set CNT watchpoints, zero if
814    setting watchpoints of type TYPE is not supported, and negative if
815    CNT is more than the maximum number of watchpoints of type TYPE
816    that we can support.  TYPE is one of bp_hardware_watchpoint,
817    bp_read_watchpoint, bp_write_watchpoint, or bp_hardware_breakpoint.
818    CNT is the number of such watchpoints used so far (including this
819    one).  OTHERTYPE is non-zero if other types of watchpoints are
820    currently enabled.
821
822    We always return 1 here because we don't have enough information
823    about possible overlap of addresses that they want to watch.  As an
824    extreme example, consider the case where all the watchpoints watch
825    the same address and the same region length: then we can handle a
826    virtually unlimited number of watchpoints, due to debug register
827    sharing implemented via reference counts in i386-nat.c.  */
828
829 static int
830 i386_can_use_hw_breakpoint (int type, int cnt, int othertype)
831 {
832   return 1;
833 }
834
835 static void
836 add_show_debug_regs_command (void)
837 {
838   /* A maintenance command to enable printing the internal DRi mirror
839      variables.  */
840   add_setshow_boolean_cmd ("show-debug-regs", class_maintenance,
841                            &maint_show_dr, _("\
842 Set whether to show variables that mirror the x86 debug registers."), _("\
843 Show whether to show variables that mirror the x86 debug registers."), _("\
844 Use \"on\" to enable, \"off\" to disable.\n\
845 If enabled, the debug registers values are shown when GDB inserts\n\
846 or removes a hardware breakpoint or watchpoint, and when the inferior\n\
847 triggers a breakpoint or watchpoint."),
848                            NULL,
849                            NULL,
850                            &maintenance_set_cmdlist,
851                            &maintenance_show_cmdlist);
852 }
853
854 /* There are only two global functions left.  */
855
856 void
857 i386_use_watchpoints (struct target_ops *t)
858 {
859   /* After a watchpoint trap, the PC points to the instruction after the
860      one that caused the trap.  Therefore we don't need to step over it.
861      But we do need to reset the status register to avoid another trap.  */
862   t->to_have_continuable_watchpoint = 1;
863
864   t->to_can_use_hw_breakpoint = i386_can_use_hw_breakpoint;
865   t->to_region_ok_for_hw_watchpoint = i386_region_ok_for_watchpoint;
866   t->to_stopped_by_watchpoint = i386_stopped_by_watchpoint;
867   t->to_stopped_data_address = i386_stopped_data_address;
868   t->to_insert_watchpoint = i386_insert_watchpoint;
869   t->to_remove_watchpoint = i386_remove_watchpoint;
870   t->to_insert_hw_breakpoint = i386_insert_hw_breakpoint;
871   t->to_remove_hw_breakpoint = i386_remove_hw_breakpoint;
872
873   if (i386_inferior_data == NULL)
874     i386_inferior_data
875       = register_inferior_data_with_cleanup (NULL, i386_inferior_data_cleanup);
876 }
877
878 void
879 i386_set_debug_register_length (int len)
880 {
881   /* This function should be called only once for each native target.  */
882   gdb_assert (i386_dr_low.debug_register_length == 0);
883   gdb_assert (len == 4 || len == 8);
884   i386_dr_low.debug_register_length = len;
885   add_show_debug_regs_command ();
886 }