* blockframe.c (find_pc_partial_function_gnu_ifunc): Change type of
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 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 "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "record.h"
68 #include "gdb_regex.h"
69
70 /* readline include files */
71 #include "readline/readline.h"
72 #include "readline/history.h"
73
74 /* readline defines this.  */
75 #undef savestring
76
77 #include "mi/mi-common.h"
78 #include "python/python.h"
79
80 /* Prototypes for local functions.  */
81
82 static void enable_delete_command (char *, int);
83
84 static void enable_once_command (char *, int);
85
86 static void disable_command (char *, int);
87
88 static void enable_command (char *, int);
89
90 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
91                                                       void *),
92                                     void *);
93
94 static void ignore_command (char *, int);
95
96 static int breakpoint_re_set_one (void *);
97
98 static void breakpoint_re_set_default (struct breakpoint *);
99
100 static void create_sals_from_address_default (char **,
101                                               struct linespec_result *,
102                                               enum bptype, char *,
103                                               char **);
104
105 static void create_breakpoints_sal_default (struct gdbarch *,
106                                             struct linespec_result *,
107                                             struct linespec_sals *,
108                                             char *, enum bptype,
109                                             enum bpdisp, int, int,
110                                             int,
111                                             const struct breakpoint_ops *,
112                                             int, int, int);
113
114 static void decode_linespec_default (struct breakpoint *, char **,
115                                      struct symtabs_and_lines *);
116
117 static void clear_command (char *, int);
118
119 static void catch_command (char *, int);
120
121 static int can_use_hardware_watchpoint (struct value *);
122
123 static void break_command_1 (char *, int, int);
124
125 static void mention (struct breakpoint *);
126
127 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
128                                                                enum bptype,
129                                                                const struct breakpoint_ops *);
130 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
131                                                        const struct symtab_and_line *);
132
133 /* This function is used in gdbtk sources and thus can not be made
134    static.  */
135 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
136                                        struct symtab_and_line,
137                                        enum bptype,
138                                        const struct breakpoint_ops *);
139
140 static struct breakpoint *
141   momentary_breakpoint_from_master (struct breakpoint *orig,
142                                     enum bptype type,
143                                     const struct breakpoint_ops *ops);
144
145 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
146
147 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
148                                             CORE_ADDR bpaddr,
149                                             enum bptype bptype);
150
151 static void describe_other_breakpoints (struct gdbarch *,
152                                         struct program_space *, CORE_ADDR,
153                                         struct obj_section *, int);
154
155 static int breakpoint_address_match (struct address_space *aspace1,
156                                      CORE_ADDR addr1,
157                                      struct address_space *aspace2,
158                                      CORE_ADDR addr2);
159
160 static int watchpoint_locations_match (struct bp_location *loc1,
161                                        struct bp_location *loc2);
162
163 static int breakpoint_location_address_match (struct bp_location *bl,
164                                               struct address_space *aspace,
165                                               CORE_ADDR addr);
166
167 static void breakpoints_info (char *, int);
168
169 static void watchpoints_info (char *, int);
170
171 static int breakpoint_1 (char *, int, 
172                          int (*) (const struct breakpoint *));
173
174 static int breakpoint_cond_eval (void *);
175
176 static void cleanup_executing_breakpoints (void *);
177
178 static void commands_command (char *, int);
179
180 static void condition_command (char *, int);
181
182 typedef enum
183   {
184     mark_inserted,
185     mark_uninserted
186   }
187 insertion_state_t;
188
189 static int remove_breakpoint (struct bp_location *, insertion_state_t);
190 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
191
192 static enum print_stop_action print_bp_stop_message (bpstat bs);
193
194 static int watchpoint_check (void *);
195
196 static void maintenance_info_breakpoints (char *, int);
197
198 static int hw_breakpoint_used_count (void);
199
200 static int hw_watchpoint_use_count (struct breakpoint *);
201
202 static int hw_watchpoint_used_count_others (struct breakpoint *except,
203                                             enum bptype type,
204                                             int *other_type_used);
205
206 static void hbreak_command (char *, int);
207
208 static void thbreak_command (char *, int);
209
210 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp);
211
212 static void stop_command (char *arg, int from_tty);
213
214 static void stopin_command (char *arg, int from_tty);
215
216 static void stopat_command (char *arg, int from_tty);
217
218 static char *ep_parse_optional_if_clause (char **arg);
219
220 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
221                                        char *arg, int tempflag, int from_tty);
222
223 static void tcatch_command (char *arg, int from_tty);
224
225 static void detach_single_step_breakpoints (void);
226
227 static int single_step_breakpoint_inserted_here_p (struct address_space *,
228                                                    CORE_ADDR pc);
229
230 static void free_bp_location (struct bp_location *loc);
231 static void incref_bp_location (struct bp_location *loc);
232 static void decref_bp_location (struct bp_location **loc);
233
234 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
235
236 static void update_global_location_list (int);
237
238 static void update_global_location_list_nothrow (int);
239
240 static int is_hardware_watchpoint (const struct breakpoint *bpt);
241
242 static void insert_breakpoint_locations (void);
243
244 static int syscall_catchpoint_p (struct breakpoint *b);
245
246 static void tracepoints_info (char *, int);
247
248 static void delete_trace_command (char *, int);
249
250 static void enable_trace_command (char *, int);
251
252 static void disable_trace_command (char *, int);
253
254 static void trace_pass_command (char *, int);
255
256 static int is_masked_watchpoint (const struct breakpoint *b);
257
258 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
259    otherwise.  */
260
261 static int strace_marker_p (struct breakpoint *b);
262
263 static void init_catchpoint (struct breakpoint *b,
264                              struct gdbarch *gdbarch, int tempflag,
265                              char *cond_string,
266                              const struct breakpoint_ops *ops);
267
268 /* The abstract base class all breakpoint_ops structures inherit
269    from.  */
270 static struct breakpoint_ops base_breakpoint_ops;
271
272 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
273    that are implemented on top of software or hardware breakpoints
274    (user breakpoints, internal and momentary breakpoints, etc.).  */
275 static struct breakpoint_ops bkpt_base_breakpoint_ops;
276
277 /* Internal breakpoints class type.  */
278 static struct breakpoint_ops internal_breakpoint_ops;
279
280 /* Momentary breakpoints class type.  */
281 static struct breakpoint_ops momentary_breakpoint_ops;
282
283 /* The breakpoint_ops structure to be used in regular user created
284    breakpoints.  */
285 struct breakpoint_ops bkpt_breakpoint_ops;
286
287 /* A reference-counted struct command_line.  This lets multiple
288    breakpoints share a single command list.  */
289 struct counted_command_line
290 {
291   /* The reference count.  */
292   int refc;
293
294   /* The command list.  */
295   struct command_line *commands;
296 };
297
298 struct command_line *
299 breakpoint_commands (struct breakpoint *b)
300 {
301   return b->commands ? b->commands->commands : NULL;
302 }
303
304 /* Flag indicating that a command has proceeded the inferior past the
305    current breakpoint.  */
306
307 static int breakpoint_proceeded;
308
309 const char *
310 bpdisp_text (enum bpdisp disp)
311 {
312   /* NOTE: the following values are a part of MI protocol and
313      represent values of 'disp' field returned when inferior stops at
314      a breakpoint.  */
315   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
316
317   return bpdisps[(int) disp];
318 }
319
320 /* Prototypes for exported functions.  */
321 /* If FALSE, gdb will not use hardware support for watchpoints, even
322    if such is available.  */
323 static int can_use_hw_watchpoints;
324
325 static void
326 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
327                              struct cmd_list_element *c,
328                              const char *value)
329 {
330   fprintf_filtered (file,
331                     _("Debugger's willingness to use "
332                       "watchpoint hardware is %s.\n"),
333                     value);
334 }
335
336 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
337    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
338    for unrecognized breakpoint locations.
339    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
340 static enum auto_boolean pending_break_support;
341 static void
342 show_pending_break_support (struct ui_file *file, int from_tty,
343                             struct cmd_list_element *c,
344                             const char *value)
345 {
346   fprintf_filtered (file,
347                     _("Debugger's behavior regarding "
348                       "pending breakpoints is %s.\n"),
349                     value);
350 }
351
352 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
353    set with "break" but falling in read-only memory.
354    If 0, gdb will warn about such breakpoints, but won't automatically
355    use hardware breakpoints.  */
356 static int automatic_hardware_breakpoints;
357 static void
358 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
359                                      struct cmd_list_element *c,
360                                      const char *value)
361 {
362   fprintf_filtered (file,
363                     _("Automatic usage of hardware breakpoints is %s.\n"),
364                     value);
365 }
366
367 /* If on, gdb will keep breakpoints inserted even as inferior is
368    stopped, and immediately insert any new breakpoints.  If off, gdb
369    will insert breakpoints into inferior only when resuming it, and
370    will remove breakpoints upon stop.  If auto, GDB will behave as ON
371    if in non-stop mode, and as OFF if all-stop mode.*/
372
373 static const char always_inserted_auto[] = "auto";
374 static const char always_inserted_on[] = "on";
375 static const char always_inserted_off[] = "off";
376 static const char *const always_inserted_enums[] = {
377   always_inserted_auto,
378   always_inserted_off,
379   always_inserted_on,
380   NULL
381 };
382 static const char *always_inserted_mode = always_inserted_auto;
383 static void
384 show_always_inserted_mode (struct ui_file *file, int from_tty,
385                      struct cmd_list_element *c, const char *value)
386 {
387   if (always_inserted_mode == always_inserted_auto)
388     fprintf_filtered (file,
389                       _("Always inserted breakpoint "
390                         "mode is %s (currently %s).\n"),
391                       value,
392                       breakpoints_always_inserted_mode () ? "on" : "off");
393   else
394     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
395                       value);
396 }
397
398 int
399 breakpoints_always_inserted_mode (void)
400 {
401   return ((always_inserted_mode == always_inserted_on
402            || (always_inserted_mode == always_inserted_auto && non_stop))
403           && !RECORD_IS_USED);
404 }
405
406 void _initialize_breakpoint (void);
407
408 /* Are we executing breakpoint commands?  */
409 static int executing_breakpoint_commands;
410
411 /* Are overlay event breakpoints enabled? */
412 static int overlay_events_enabled;
413
414 /* See description in breakpoint.h. */
415 int target_exact_watchpoints = 0;
416
417 /* Walk the following statement or block through all breakpoints.
418    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
419    current breakpoint.  */
420
421 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
422
423 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
424         for (B = breakpoint_chain;      \
425              B ? (TMP=B->next, 1): 0;   \
426              B = TMP)
427
428 /* Similar iterator for the low-level breakpoints.  SAFE variant is
429    not provided so update_global_location_list must not be called
430    while executing the block of ALL_BP_LOCATIONS.  */
431
432 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
433         for (BP_TMP = bp_location;                                      \
434              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
435              BP_TMP++)
436
437 /* Iterator for tracepoints only.  */
438
439 #define ALL_TRACEPOINTS(B)  \
440   for (B = breakpoint_chain; B; B = B->next)  \
441     if (is_tracepoint (B))
442
443 /* Chains of all breakpoints defined.  */
444
445 struct breakpoint *breakpoint_chain;
446
447 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
448
449 static struct bp_location **bp_location;
450
451 /* Number of elements of BP_LOCATION.  */
452
453 static unsigned bp_location_count;
454
455 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
456    ADDRESS for the current elements of BP_LOCATION which get a valid
457    result from bp_location_has_shadow.  You can use it for roughly
458    limiting the subrange of BP_LOCATION to scan for shadow bytes for
459    an address you need to read.  */
460
461 static CORE_ADDR bp_location_placed_address_before_address_max;
462
463 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
464    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
465    BP_LOCATION which get a valid result from bp_location_has_shadow.
466    You can use it for roughly limiting the subrange of BP_LOCATION to
467    scan for shadow bytes for an address you need to read.  */
468
469 static CORE_ADDR bp_location_shadow_len_after_address_max;
470
471 /* The locations that no longer correspond to any breakpoint, unlinked
472    from bp_location array, but for which a hit may still be reported
473    by a target.  */
474 VEC(bp_location_p) *moribund_locations = NULL;
475
476 /* Number of last breakpoint made.  */
477
478 static int breakpoint_count;
479
480 /* The value of `breakpoint_count' before the last command that
481    created breakpoints.  If the last (break-like) command created more
482    than one breakpoint, then the difference between BREAKPOINT_COUNT
483    and PREV_BREAKPOINT_COUNT is more than one.  */
484 static int prev_breakpoint_count;
485
486 /* Number of last tracepoint made.  */
487
488 static int tracepoint_count;
489
490 static struct cmd_list_element *breakpoint_set_cmdlist;
491 static struct cmd_list_element *breakpoint_show_cmdlist;
492 struct cmd_list_element *save_cmdlist;
493
494 /* Return whether a breakpoint is an active enabled breakpoint.  */
495 static int
496 breakpoint_enabled (struct breakpoint *b)
497 {
498   return (b->enable_state == bp_enabled);
499 }
500
501 /* Set breakpoint count to NUM.  */
502
503 static void
504 set_breakpoint_count (int num)
505 {
506   prev_breakpoint_count = breakpoint_count;
507   breakpoint_count = num;
508   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
509 }
510
511 /* Used by `start_rbreak_breakpoints' below, to record the current
512    breakpoint count before "rbreak" creates any breakpoint.  */
513 static int rbreak_start_breakpoint_count;
514
515 /* Called at the start an "rbreak" command to record the first
516    breakpoint made.  */
517
518 void
519 start_rbreak_breakpoints (void)
520 {
521   rbreak_start_breakpoint_count = breakpoint_count;
522 }
523
524 /* Called at the end of an "rbreak" command to record the last
525    breakpoint made.  */
526
527 void
528 end_rbreak_breakpoints (void)
529 {
530   prev_breakpoint_count = rbreak_start_breakpoint_count;
531 }
532
533 /* Used in run_command to zero the hit count when a new run starts.  */
534
535 void
536 clear_breakpoint_hit_counts (void)
537 {
538   struct breakpoint *b;
539
540   ALL_BREAKPOINTS (b)
541     b->hit_count = 0;
542 }
543
544 /* Allocate a new counted_command_line with reference count of 1.
545    The new structure owns COMMANDS.  */
546
547 static struct counted_command_line *
548 alloc_counted_command_line (struct command_line *commands)
549 {
550   struct counted_command_line *result
551     = xmalloc (sizeof (struct counted_command_line));
552
553   result->refc = 1;
554   result->commands = commands;
555   return result;
556 }
557
558 /* Increment reference count.  This does nothing if CMD is NULL.  */
559
560 static void
561 incref_counted_command_line (struct counted_command_line *cmd)
562 {
563   if (cmd)
564     ++cmd->refc;
565 }
566
567 /* Decrement reference count.  If the reference count reaches 0,
568    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
569    nothing if *CMDP is NULL.  */
570
571 static void
572 decref_counted_command_line (struct counted_command_line **cmdp)
573 {
574   if (*cmdp)
575     {
576       if (--(*cmdp)->refc == 0)
577         {
578           free_command_lines (&(*cmdp)->commands);
579           xfree (*cmdp);
580         }
581       *cmdp = NULL;
582     }
583 }
584
585 /* A cleanup function that calls decref_counted_command_line.  */
586
587 static void
588 do_cleanup_counted_command_line (void *arg)
589 {
590   decref_counted_command_line (arg);
591 }
592
593 /* Create a cleanup that calls decref_counted_command_line on the
594    argument.  */
595
596 static struct cleanup *
597 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
598 {
599   return make_cleanup (do_cleanup_counted_command_line, cmdp);
600 }
601
602 \f
603 /* Return the breakpoint with the specified number, or NULL
604    if the number does not refer to an existing breakpoint.  */
605
606 struct breakpoint *
607 get_breakpoint (int num)
608 {
609   struct breakpoint *b;
610
611   ALL_BREAKPOINTS (b)
612     if (b->number == num)
613       return b;
614   
615   return NULL;
616 }
617
618 \f
619
620 void
621 set_breakpoint_condition (struct breakpoint *b, char *exp,
622                           int from_tty)
623 {
624   xfree (b->cond_string);
625   b->cond_string = NULL;
626
627   if (is_watchpoint (b))
628     {
629       struct watchpoint *w = (struct watchpoint *) b;
630
631       xfree (w->cond_exp);
632       w->cond_exp = NULL;
633     }
634   else
635     {
636       struct bp_location *loc;
637
638       for (loc = b->loc; loc; loc = loc->next)
639         {
640           xfree (loc->cond);
641           loc->cond = NULL;
642         }
643     }
644
645   if (*exp == 0)
646     {
647       if (from_tty)
648         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
649     }
650   else
651     {
652       char *arg = exp;
653
654       /* I don't know if it matters whether this is the string the user
655          typed in or the decompiled expression.  */
656       b->cond_string = xstrdup (arg);
657       b->condition_not_parsed = 0;
658
659       if (is_watchpoint (b))
660         {
661           struct watchpoint *w = (struct watchpoint *) b;
662
663           innermost_block = NULL;
664           arg = exp;
665           w->cond_exp = parse_exp_1 (&arg, 0, 0);
666           if (*arg)
667             error (_("Junk at end of expression"));
668           w->cond_exp_valid_block = innermost_block;
669         }
670       else
671         {
672           struct bp_location *loc;
673
674           for (loc = b->loc; loc; loc = loc->next)
675             {
676               arg = exp;
677               loc->cond =
678                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
679               if (*arg)
680                 error (_("Junk at end of expression"));
681             }
682         }
683     }
684   breakpoints_changed ();
685   observer_notify_breakpoint_modified (b);
686 }
687
688 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
689
690 static void
691 condition_command (char *arg, int from_tty)
692 {
693   struct breakpoint *b;
694   char *p;
695   int bnum;
696
697   if (arg == 0)
698     error_no_arg (_("breakpoint number"));
699
700   p = arg;
701   bnum = get_number (&p);
702   if (bnum == 0)
703     error (_("Bad breakpoint argument: '%s'"), arg);
704
705   ALL_BREAKPOINTS (b)
706     if (b->number == bnum)
707       {
708         /* Check if this breakpoint has a Python object assigned to
709            it, and if it has a definition of the "stop"
710            method.  This method and conditions entered into GDB from
711            the CLI are mutually exclusive.  */
712         if (b->py_bp_object
713             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
714           error (_("Cannot set a condition where a Python 'stop' "
715                    "method has been defined in the breakpoint."));
716         set_breakpoint_condition (b, p, from_tty);
717         return;
718       }
719
720   error (_("No breakpoint number %d."), bnum);
721 }
722
723 /* Check that COMMAND do not contain commands that are suitable
724    only for tracepoints and not suitable for ordinary breakpoints.
725    Throw if any such commands is found.  */
726
727 static void
728 check_no_tracepoint_commands (struct command_line *commands)
729 {
730   struct command_line *c;
731
732   for (c = commands; c; c = c->next)
733     {
734       int i;
735
736       if (c->control_type == while_stepping_control)
737         error (_("The 'while-stepping' command can "
738                  "only be used for tracepoints"));
739
740       for (i = 0; i < c->body_count; ++i)
741         check_no_tracepoint_commands ((c->body_list)[i]);
742
743       /* Not that command parsing removes leading whitespace and comment
744          lines and also empty lines.  So, we only need to check for
745          command directly.  */
746       if (strstr (c->line, "collect ") == c->line)
747         error (_("The 'collect' command can only be used for tracepoints"));
748
749       if (strstr (c->line, "teval ") == c->line)
750         error (_("The 'teval' command can only be used for tracepoints"));
751     }
752 }
753
754 /* Encapsulate tests for different types of tracepoints.  */
755
756 static int
757 is_tracepoint_type (enum bptype type)
758 {
759   return (type == bp_tracepoint
760           || type == bp_fast_tracepoint
761           || type == bp_static_tracepoint);
762 }
763
764 int
765 is_tracepoint (const struct breakpoint *b)
766 {
767   return is_tracepoint_type (b->type);
768 }
769
770 /* A helper function that validates that COMMANDS are valid for a
771    breakpoint.  This function will throw an exception if a problem is
772    found.  */
773
774 static void
775 validate_commands_for_breakpoint (struct breakpoint *b,
776                                   struct command_line *commands)
777 {
778   if (is_tracepoint (b))
779     {
780       /* We need to verify that each top-level element of commands is
781          valid for tracepoints, that there's at most one
782          while-stepping element, and that while-stepping's body has
783          valid tracing commands excluding nested while-stepping.  */
784       struct command_line *c;
785       struct command_line *while_stepping = 0;
786       for (c = commands; c; c = c->next)
787         {
788           if (c->control_type == while_stepping_control)
789             {
790               if (b->type == bp_fast_tracepoint)
791                 error (_("The 'while-stepping' command "
792                          "cannot be used for fast tracepoint"));
793               else if (b->type == bp_static_tracepoint)
794                 error (_("The 'while-stepping' command "
795                          "cannot be used for static tracepoint"));
796
797               if (while_stepping)
798                 error (_("The 'while-stepping' command "
799                          "can be used only once"));
800               else
801                 while_stepping = c;
802             }
803         }
804       if (while_stepping)
805         {
806           struct command_line *c2;
807
808           gdb_assert (while_stepping->body_count == 1);
809           c2 = while_stepping->body_list[0];
810           for (; c2; c2 = c2->next)
811             {
812               if (c2->control_type == while_stepping_control)
813                 error (_("The 'while-stepping' command cannot be nested"));
814             }
815         }
816     }
817   else
818     {
819       check_no_tracepoint_commands (commands);
820     }
821 }
822
823 /* Return a vector of all the static tracepoints set at ADDR.  The
824    caller is responsible for releasing the vector.  */
825
826 VEC(breakpoint_p) *
827 static_tracepoints_here (CORE_ADDR addr)
828 {
829   struct breakpoint *b;
830   VEC(breakpoint_p) *found = 0;
831   struct bp_location *loc;
832
833   ALL_BREAKPOINTS (b)
834     if (b->type == bp_static_tracepoint)
835       {
836         for (loc = b->loc; loc; loc = loc->next)
837           if (loc->address == addr)
838             VEC_safe_push(breakpoint_p, found, b);
839       }
840
841   return found;
842 }
843
844 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
845    validate that only allowed commands are included.  */
846
847 void
848 breakpoint_set_commands (struct breakpoint *b, 
849                          struct command_line *commands)
850 {
851   validate_commands_for_breakpoint (b, commands);
852
853   decref_counted_command_line (&b->commands);
854   b->commands = alloc_counted_command_line (commands);
855   breakpoints_changed ();
856   observer_notify_breakpoint_modified (b);
857 }
858
859 /* Set the internal `silent' flag on the breakpoint.  Note that this
860    is not the same as the "silent" that may appear in the breakpoint's
861    commands.  */
862
863 void
864 breakpoint_set_silent (struct breakpoint *b, int silent)
865 {
866   int old_silent = b->silent;
867
868   b->silent = silent;
869   if (old_silent != silent)
870     observer_notify_breakpoint_modified (b);
871 }
872
873 /* Set the thread for this breakpoint.  If THREAD is -1, make the
874    breakpoint work for any thread.  */
875
876 void
877 breakpoint_set_thread (struct breakpoint *b, int thread)
878 {
879   int old_thread = b->thread;
880
881   b->thread = thread;
882   if (old_thread != thread)
883     observer_notify_breakpoint_modified (b);
884 }
885
886 /* Set the task for this breakpoint.  If TASK is 0, make the
887    breakpoint work for any task.  */
888
889 void
890 breakpoint_set_task (struct breakpoint *b, int task)
891 {
892   int old_task = b->task;
893
894   b->task = task;
895   if (old_task != task)
896     observer_notify_breakpoint_modified (b);
897 }
898
899 void
900 check_tracepoint_command (char *line, void *closure)
901 {
902   struct breakpoint *b = closure;
903
904   validate_actionline (&line, b);
905 }
906
907 /* A structure used to pass information through
908    map_breakpoint_numbers.  */
909
910 struct commands_info
911 {
912   /* True if the command was typed at a tty.  */
913   int from_tty;
914
915   /* The breakpoint range spec.  */
916   char *arg;
917
918   /* Non-NULL if the body of the commands are being read from this
919      already-parsed command.  */
920   struct command_line *control;
921
922   /* The command lines read from the user, or NULL if they have not
923      yet been read.  */
924   struct counted_command_line *cmd;
925 };
926
927 /* A callback for map_breakpoint_numbers that sets the commands for
928    commands_command.  */
929
930 static void
931 do_map_commands_command (struct breakpoint *b, void *data)
932 {
933   struct commands_info *info = data;
934
935   if (info->cmd == NULL)
936     {
937       struct command_line *l;
938
939       if (info->control != NULL)
940         l = copy_command_lines (info->control->body_list[0]);
941       else
942         {
943           struct cleanup *old_chain;
944           char *str;
945
946           str = xstrprintf (_("Type commands for breakpoint(s) "
947                               "%s, one per line."),
948                             info->arg);
949
950           old_chain = make_cleanup (xfree, str);
951
952           l = read_command_lines (str,
953                                   info->from_tty, 1,
954                                   (is_tracepoint (b)
955                                    ? check_tracepoint_command : 0),
956                                   b);
957
958           do_cleanups (old_chain);
959         }
960
961       info->cmd = alloc_counted_command_line (l);
962     }
963
964   /* If a breakpoint was on the list more than once, we don't need to
965      do anything.  */
966   if (b->commands != info->cmd)
967     {
968       validate_commands_for_breakpoint (b, info->cmd->commands);
969       incref_counted_command_line (info->cmd);
970       decref_counted_command_line (&b->commands);
971       b->commands = info->cmd;
972       breakpoints_changed ();
973       observer_notify_breakpoint_modified (b);
974     }
975 }
976
977 static void
978 commands_command_1 (char *arg, int from_tty, 
979                     struct command_line *control)
980 {
981   struct cleanup *cleanups;
982   struct commands_info info;
983
984   info.from_tty = from_tty;
985   info.control = control;
986   info.cmd = NULL;
987   /* If we read command lines from the user, then `info' will hold an
988      extra reference to the commands that we must clean up.  */
989   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
990
991   if (arg == NULL || !*arg)
992     {
993       if (breakpoint_count - prev_breakpoint_count > 1)
994         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
995                           breakpoint_count);
996       else if (breakpoint_count > 0)
997         arg = xstrprintf ("%d", breakpoint_count);
998       else
999         {
1000           /* So that we don't try to free the incoming non-NULL
1001              argument in the cleanup below.  Mapping breakpoint
1002              numbers will fail in this case.  */
1003           arg = NULL;
1004         }
1005     }
1006   else
1007     /* The command loop has some static state, so we need to preserve
1008        our argument.  */
1009     arg = xstrdup (arg);
1010
1011   if (arg != NULL)
1012     make_cleanup (xfree, arg);
1013
1014   info.arg = arg;
1015
1016   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1017
1018   if (info.cmd == NULL)
1019     error (_("No breakpoints specified."));
1020
1021   do_cleanups (cleanups);
1022 }
1023
1024 static void
1025 commands_command (char *arg, int from_tty)
1026 {
1027   commands_command_1 (arg, from_tty, NULL);
1028 }
1029
1030 /* Like commands_command, but instead of reading the commands from
1031    input stream, takes them from an already parsed command structure.
1032
1033    This is used by cli-script.c to DTRT with breakpoint commands
1034    that are part of if and while bodies.  */
1035 enum command_control_type
1036 commands_from_control_command (char *arg, struct command_line *cmd)
1037 {
1038   commands_command_1 (arg, 0, cmd);
1039   return simple_control;
1040 }
1041
1042 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1043
1044 static int
1045 bp_location_has_shadow (struct bp_location *bl)
1046 {
1047   if (bl->loc_type != bp_loc_software_breakpoint)
1048     return 0;
1049   if (!bl->inserted)
1050     return 0;
1051   if (bl->target_info.shadow_len == 0)
1052     /* BL isn't valid, or doesn't shadow memory.  */
1053     return 0;
1054   return 1;
1055 }
1056
1057 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1058    by replacing any memory breakpoints with their shadowed contents.
1059
1060    The range of shadowed area by each bp_location is:
1061      bl->address - bp_location_placed_address_before_address_max
1062      up to bl->address + bp_location_shadow_len_after_address_max
1063    The range we were requested to resolve shadows for is:
1064      memaddr ... memaddr + len
1065    Thus the safe cutoff boundaries for performance optimization are
1066      memaddr + len <= (bl->address
1067                        - bp_location_placed_address_before_address_max)
1068    and:
1069      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1070
1071 void
1072 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1073                         const gdb_byte *writebuf_org,
1074                         ULONGEST memaddr, LONGEST len)
1075 {
1076   /* Left boundary, right boundary and median element of our binary
1077      search.  */
1078   unsigned bc_l, bc_r, bc;
1079
1080   /* Find BC_L which is a leftmost element which may affect BUF
1081      content.  It is safe to report lower value but a failure to
1082      report higher one.  */
1083
1084   bc_l = 0;
1085   bc_r = bp_location_count;
1086   while (bc_l + 1 < bc_r)
1087     {
1088       struct bp_location *bl;
1089
1090       bc = (bc_l + bc_r) / 2;
1091       bl = bp_location[bc];
1092
1093       /* Check first BL->ADDRESS will not overflow due to the added
1094          constant.  Then advance the left boundary only if we are sure
1095          the BC element can in no way affect the BUF content (MEMADDR
1096          to MEMADDR + LEN range).
1097
1098          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1099          offset so that we cannot miss a breakpoint with its shadow
1100          range tail still reaching MEMADDR.  */
1101
1102       if ((bl->address + bp_location_shadow_len_after_address_max
1103            >= bl->address)
1104           && (bl->address + bp_location_shadow_len_after_address_max
1105               <= memaddr))
1106         bc_l = bc;
1107       else
1108         bc_r = bc;
1109     }
1110
1111   /* Due to the binary search above, we need to make sure we pick the
1112      first location that's at BC_L's address.  E.g., if there are
1113      multiple locations at the same address, BC_L may end up pointing
1114      at a duplicate location, and miss the "master"/"inserted"
1115      location.  Say, given locations L1, L2 and L3 at addresses A and
1116      B:
1117
1118       L1@A, L2@A, L3@B, ...
1119
1120      BC_L could end up pointing at location L2, while the "master"
1121      location could be L1.  Since the `loc->inserted' flag is only set
1122      on "master" locations, we'd forget to restore the shadow of L1
1123      and L2.  */
1124   while (bc_l > 0
1125          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1126     bc_l--;
1127
1128   /* Now do full processing of the found relevant range of elements.  */
1129
1130   for (bc = bc_l; bc < bp_location_count; bc++)
1131   {
1132     struct bp_location *bl = bp_location[bc];
1133     CORE_ADDR bp_addr = 0;
1134     int bp_size = 0;
1135     int bptoffset = 0;
1136
1137     /* bp_location array has BL->OWNER always non-NULL.  */
1138     if (bl->owner->type == bp_none)
1139       warning (_("reading through apparently deleted breakpoint #%d?"),
1140                bl->owner->number);
1141
1142     /* Performance optimization: any further element can no longer affect BUF
1143        content.  */
1144
1145     if (bl->address >= bp_location_placed_address_before_address_max
1146         && memaddr + len <= (bl->address
1147                              - bp_location_placed_address_before_address_max))
1148       break;
1149
1150     if (!bp_location_has_shadow (bl))
1151       continue;
1152     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1153                                    current_program_space->aspace, 0))
1154       continue;
1155
1156     /* Addresses and length of the part of the breakpoint that
1157        we need to copy.  */
1158     bp_addr = bl->target_info.placed_address;
1159     bp_size = bl->target_info.shadow_len;
1160
1161     if (bp_addr + bp_size <= memaddr)
1162       /* The breakpoint is entirely before the chunk of memory we
1163          are reading.  */
1164       continue;
1165
1166     if (bp_addr >= memaddr + len)
1167       /* The breakpoint is entirely after the chunk of memory we are
1168          reading.  */
1169       continue;
1170
1171     /* Offset within shadow_contents.  */
1172     if (bp_addr < memaddr)
1173       {
1174         /* Only copy the second part of the breakpoint.  */
1175         bp_size -= memaddr - bp_addr;
1176         bptoffset = memaddr - bp_addr;
1177         bp_addr = memaddr;
1178       }
1179
1180     if (bp_addr + bp_size > memaddr + len)
1181       {
1182         /* Only copy the first part of the breakpoint.  */
1183         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1184       }
1185
1186     if (readbuf != NULL)
1187       {
1188         /* Update the read buffer with this inserted breakpoint's
1189            shadow.  */
1190         memcpy (readbuf + bp_addr - memaddr,
1191                 bl->target_info.shadow_contents + bptoffset, bp_size);
1192       }
1193     else
1194       {
1195         struct gdbarch *gdbarch = bl->gdbarch;
1196         const unsigned char *bp;
1197         CORE_ADDR placed_address = bl->target_info.placed_address;
1198         unsigned placed_size = bl->target_info.placed_size;
1199
1200         /* Update the shadow with what we want to write to memory.  */
1201         memcpy (bl->target_info.shadow_contents + bptoffset,
1202                 writebuf_org + bp_addr - memaddr, bp_size);
1203
1204         /* Determine appropriate breakpoint contents and size for this
1205            address.  */
1206         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1207
1208         /* Update the final write buffer with this inserted
1209            breakpoint's INSN.  */
1210         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1211       }
1212   }
1213 }
1214 \f
1215
1216 /* Return true if BPT is of any hardware watchpoint kind.  */
1217
1218 static int
1219 is_hardware_watchpoint (const struct breakpoint *bpt)
1220 {
1221   return (bpt->type == bp_hardware_watchpoint
1222           || bpt->type == bp_read_watchpoint
1223           || bpt->type == bp_access_watchpoint);
1224 }
1225
1226 /* Return true if BPT is of any watchpoint kind, hardware or
1227    software.  */
1228
1229 int
1230 is_watchpoint (const struct breakpoint *bpt)
1231 {
1232   return (is_hardware_watchpoint (bpt)
1233           || bpt->type == bp_watchpoint);
1234 }
1235
1236 /* Returns true if the current thread and its running state are safe
1237    to evaluate or update watchpoint B.  Watchpoints on local
1238    expressions need to be evaluated in the context of the thread that
1239    was current when the watchpoint was created, and, that thread needs
1240    to be stopped to be able to select the correct frame context.
1241    Watchpoints on global expressions can be evaluated on any thread,
1242    and in any state.  It is presently left to the target allowing
1243    memory accesses when threads are running.  */
1244
1245 static int
1246 watchpoint_in_thread_scope (struct watchpoint *b)
1247 {
1248   return (b->base.pspace == current_program_space
1249           && (ptid_equal (b->watchpoint_thread, null_ptid)
1250               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1251                   && !is_executing (inferior_ptid))));
1252 }
1253
1254 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1255    associated bp_watchpoint_scope breakpoint.  */
1256
1257 static void
1258 watchpoint_del_at_next_stop (struct watchpoint *w)
1259 {
1260   struct breakpoint *b = &w->base;
1261
1262   if (b->related_breakpoint != b)
1263     {
1264       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1265       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1266       b->related_breakpoint->disposition = disp_del_at_next_stop;
1267       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1268       b->related_breakpoint = b;
1269     }
1270   b->disposition = disp_del_at_next_stop;
1271 }
1272
1273 /* Assuming that B is a watchpoint:
1274    - Reparse watchpoint expression, if REPARSE is non-zero
1275    - Evaluate expression and store the result in B->val
1276    - Evaluate the condition if there is one, and store the result
1277      in b->loc->cond.
1278    - Update the list of values that must be watched in B->loc.
1279
1280    If the watchpoint disposition is disp_del_at_next_stop, then do
1281    nothing.  If this is local watchpoint that is out of scope, delete
1282    it.
1283
1284    Even with `set breakpoint always-inserted on' the watchpoints are
1285    removed + inserted on each stop here.  Normal breakpoints must
1286    never be removed because they might be missed by a running thread
1287    when debugging in non-stop mode.  On the other hand, hardware
1288    watchpoints (is_hardware_watchpoint; processed here) are specific
1289    to each LWP since they are stored in each LWP's hardware debug
1290    registers.  Therefore, such LWP must be stopped first in order to
1291    be able to modify its hardware watchpoints.
1292
1293    Hardware watchpoints must be reset exactly once after being
1294    presented to the user.  It cannot be done sooner, because it would
1295    reset the data used to present the watchpoint hit to the user.  And
1296    it must not be done later because it could display the same single
1297    watchpoint hit during multiple GDB stops.  Note that the latter is
1298    relevant only to the hardware watchpoint types bp_read_watchpoint
1299    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1300    not user-visible - its hit is suppressed if the memory content has
1301    not changed.
1302
1303    The following constraints influence the location where we can reset
1304    hardware watchpoints:
1305
1306    * target_stopped_by_watchpoint and target_stopped_data_address are
1307      called several times when GDB stops.
1308
1309    [linux] 
1310    * Multiple hardware watchpoints can be hit at the same time,
1311      causing GDB to stop.  GDB only presents one hardware watchpoint
1312      hit at a time as the reason for stopping, and all the other hits
1313      are presented later, one after the other, each time the user
1314      requests the execution to be resumed.  Execution is not resumed
1315      for the threads still having pending hit event stored in
1316      LWP_INFO->STATUS.  While the watchpoint is already removed from
1317      the inferior on the first stop the thread hit event is kept being
1318      reported from its cached value by linux_nat_stopped_data_address
1319      until the real thread resume happens after the watchpoint gets
1320      presented and thus its LWP_INFO->STATUS gets reset.
1321
1322    Therefore the hardware watchpoint hit can get safely reset on the
1323    watchpoint removal from inferior.  */
1324
1325 static void
1326 update_watchpoint (struct watchpoint *b, int reparse)
1327 {
1328   int within_current_scope;
1329   struct frame_id saved_frame_id;
1330   int frame_saved;
1331
1332   /* If this is a local watchpoint, we only want to check if the
1333      watchpoint frame is in scope if the current thread is the thread
1334      that was used to create the watchpoint.  */
1335   if (!watchpoint_in_thread_scope (b))
1336     return;
1337
1338   if (b->base.disposition == disp_del_at_next_stop)
1339     return;
1340  
1341   frame_saved = 0;
1342
1343   /* Determine if the watchpoint is within scope.  */
1344   if (b->exp_valid_block == NULL)
1345     within_current_scope = 1;
1346   else
1347     {
1348       struct frame_info *fi = get_current_frame ();
1349       struct gdbarch *frame_arch = get_frame_arch (fi);
1350       CORE_ADDR frame_pc = get_frame_pc (fi);
1351
1352       /* If we're in a function epilogue, unwinding may not work
1353          properly, so do not attempt to recreate locations at this
1354          point.  See similar comments in watchpoint_check.  */
1355       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1356         return;
1357
1358       /* Save the current frame's ID so we can restore it after
1359          evaluating the watchpoint expression on its own frame.  */
1360       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1361          took a frame parameter, so that we didn't have to change the
1362          selected frame.  */
1363       frame_saved = 1;
1364       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1365
1366       fi = frame_find_by_id (b->watchpoint_frame);
1367       within_current_scope = (fi != NULL);
1368       if (within_current_scope)
1369         select_frame (fi);
1370     }
1371
1372   /* We don't free locations.  They are stored in the bp_location array
1373      and update_global_location_list will eventually delete them and
1374      remove breakpoints if needed.  */
1375   b->base.loc = NULL;
1376
1377   if (within_current_scope && reparse)
1378     {
1379       char *s;
1380
1381       if (b->exp)
1382         {
1383           xfree (b->exp);
1384           b->exp = NULL;
1385         }
1386       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1387       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1388       /* If the meaning of expression itself changed, the old value is
1389          no longer relevant.  We don't want to report a watchpoint hit
1390          to the user when the old value and the new value may actually
1391          be completely different objects.  */
1392       value_free (b->val);
1393       b->val = NULL;
1394       b->val_valid = 0;
1395
1396       /* Note that unlike with breakpoints, the watchpoint's condition
1397          expression is stored in the breakpoint object, not in the
1398          locations (re)created below.  */
1399       if (b->base.cond_string != NULL)
1400         {
1401           if (b->cond_exp != NULL)
1402             {
1403               xfree (b->cond_exp);
1404               b->cond_exp = NULL;
1405             }
1406
1407           s = b->base.cond_string;
1408           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1409         }
1410     }
1411
1412   /* If we failed to parse the expression, for example because
1413      it refers to a global variable in a not-yet-loaded shared library,
1414      don't try to insert watchpoint.  We don't automatically delete
1415      such watchpoint, though, since failure to parse expression
1416      is different from out-of-scope watchpoint.  */
1417   if ( !target_has_execution)
1418     {
1419       /* Without execution, memory can't change.  No use to try and
1420          set watchpoint locations.  The watchpoint will be reset when
1421          the target gains execution, through breakpoint_re_set.  */
1422     }
1423   else if (within_current_scope && b->exp)
1424     {
1425       int pc = 0;
1426       struct value *val_chain, *v, *result, *next;
1427       struct program_space *frame_pspace;
1428
1429       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1430
1431       /* Avoid setting b->val if it's already set.  The meaning of
1432          b->val is 'the last value' user saw, and we should update
1433          it only if we reported that last value to user.  As it
1434          happens, the code that reports it updates b->val directly.
1435          We don't keep track of the memory value for masked
1436          watchpoints.  */
1437       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1438         {
1439           b->val = v;
1440           b->val_valid = 1;
1441         }
1442
1443       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1444
1445       /* Look at each value on the value chain.  */
1446       for (v = val_chain; v; v = value_next (v))
1447         {
1448           /* If it's a memory location, and GDB actually needed
1449              its contents to evaluate the expression, then we
1450              must watch it.  If the first value returned is
1451              still lazy, that means an error occurred reading it;
1452              watch it anyway in case it becomes readable.  */
1453           if (VALUE_LVAL (v) == lval_memory
1454               && (v == val_chain || ! value_lazy (v)))
1455             {
1456               struct type *vtype = check_typedef (value_type (v));
1457
1458               /* We only watch structs and arrays if user asked
1459                  for it explicitly, never if they just happen to
1460                  appear in the middle of some value chain.  */
1461               if (v == result
1462                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1463                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1464                 {
1465                   CORE_ADDR addr;
1466                   int len, type;
1467                   struct bp_location *loc, **tmp;
1468
1469                   addr = value_address (v);
1470                   len = TYPE_LENGTH (value_type (v));
1471                   type = hw_write;
1472                   if (b->base.type == bp_read_watchpoint)
1473                     type = hw_read;
1474                   else if (b->base.type == bp_access_watchpoint)
1475                     type = hw_access;
1476
1477                   loc = allocate_bp_location (&b->base);
1478                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1479                     ;
1480                   *tmp = loc;
1481                   loc->gdbarch = get_type_arch (value_type (v));
1482
1483                   loc->pspace = frame_pspace;
1484                   loc->address = addr;
1485                   loc->length = len;
1486                   loc->watchpoint_type = type;
1487                 }
1488             }
1489         }
1490
1491       /* Change the type of breakpoint between hardware assisted or
1492          an ordinary watchpoint depending on the hardware support
1493          and free hardware slots.  REPARSE is set when the inferior
1494          is started.  */
1495       if (reparse)
1496         {
1497           int reg_cnt;
1498           enum bp_loc_type loc_type;
1499           struct bp_location *bl;
1500
1501           reg_cnt = can_use_hardware_watchpoint (val_chain);
1502
1503           if (reg_cnt)
1504             {
1505               int i, target_resources_ok, other_type_used;
1506               enum bptype type;
1507
1508               /* Use an exact watchpoint when there's only one memory region to be
1509                  watched, and only one debug register is needed to watch it.  */
1510               b->exact = target_exact_watchpoints && reg_cnt == 1;
1511
1512               /* We need to determine how many resources are already
1513                  used for all other hardware watchpoints plus this one
1514                  to see if we still have enough resources to also fit
1515                  this watchpoint in as well.  */
1516
1517               /* If this is a software watchpoint, we try to turn it
1518                  to a hardware one -- count resources as if B was of
1519                  hardware watchpoint type.  */
1520               type = b->base.type;
1521               if (type == bp_watchpoint)
1522                 type = bp_hardware_watchpoint;
1523
1524               /* This watchpoint may or may not have been placed on
1525                  the list yet at this point (it won't be in the list
1526                  if we're trying to create it for the first time,
1527                  through watch_command), so always account for it
1528                  manually.  */
1529
1530               /* Count resources used by all watchpoints except B.  */
1531               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1532
1533               /* Add in the resources needed for B.  */
1534               i += hw_watchpoint_use_count (&b->base);
1535
1536               target_resources_ok
1537                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1538               if (target_resources_ok <= 0)
1539                 {
1540                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1541
1542                   if (target_resources_ok == 0 && !sw_mode)
1543                     error (_("Target does not support this type of "
1544                              "hardware watchpoint."));
1545                   else if (target_resources_ok < 0 && !sw_mode)
1546                     error (_("There are not enough available hardware "
1547                              "resources for this watchpoint."));
1548
1549                   /* Downgrade to software watchpoint.  */
1550                   b->base.type = bp_watchpoint;
1551                 }
1552               else
1553                 {
1554                   /* If this was a software watchpoint, we've just
1555                      found we have enough resources to turn it to a
1556                      hardware watchpoint.  Otherwise, this is a
1557                      nop.  */
1558                   b->base.type = type;
1559                 }
1560             }
1561           else if (!b->base.ops->works_in_software_mode (&b->base))
1562             error (_("Expression cannot be implemented with "
1563                      "read/access watchpoint."));
1564           else
1565             b->base.type = bp_watchpoint;
1566
1567           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1568                       : bp_loc_hardware_watchpoint);
1569           for (bl = b->base.loc; bl; bl = bl->next)
1570             bl->loc_type = loc_type;
1571         }
1572
1573       for (v = val_chain; v; v = next)
1574         {
1575           next = value_next (v);
1576           if (v != b->val)
1577             value_free (v);
1578         }
1579
1580       /* If a software watchpoint is not watching any memory, then the
1581          above left it without any location set up.  But,
1582          bpstat_stop_status requires a location to be able to report
1583          stops, so make sure there's at least a dummy one.  */
1584       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1585         {
1586           struct breakpoint *base = &b->base;
1587           base->loc = allocate_bp_location (base);
1588           base->loc->pspace = frame_pspace;
1589           base->loc->address = -1;
1590           base->loc->length = -1;
1591           base->loc->watchpoint_type = -1;
1592         }
1593     }
1594   else if (!within_current_scope)
1595     {
1596       printf_filtered (_("\
1597 Watchpoint %d deleted because the program has left the block\n\
1598 in which its expression is valid.\n"),
1599                        b->base.number);
1600       watchpoint_del_at_next_stop (b);
1601     }
1602
1603   /* Restore the selected frame.  */
1604   if (frame_saved)
1605     select_frame (frame_find_by_id (saved_frame_id));
1606 }
1607
1608
1609 /* Returns 1 iff breakpoint location should be
1610    inserted in the inferior.  We don't differentiate the type of BL's owner
1611    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1612    breakpoint_ops is not defined, because in insert_bp_location,
1613    tracepoint's insert_location will not be called.  */
1614 static int
1615 should_be_inserted (struct bp_location *bl)
1616 {
1617   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1618     return 0;
1619
1620   if (bl->owner->disposition == disp_del_at_next_stop)
1621     return 0;
1622
1623   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1624     return 0;
1625
1626   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1627     return 0;
1628
1629   /* This is set for example, when we're attached to the parent of a
1630      vfork, and have detached from the child.  The child is running
1631      free, and we expect it to do an exec or exit, at which point the
1632      OS makes the parent schedulable again (and the target reports
1633      that the vfork is done).  Until the child is done with the shared
1634      memory region, do not insert breakpoints in the parent, otherwise
1635      the child could still trip on the parent's breakpoints.  Since
1636      the parent is blocked anyway, it won't miss any breakpoint.  */
1637   if (bl->pspace->breakpoints_not_allowed)
1638     return 0;
1639
1640   return 1;
1641 }
1642
1643 /* Same as should_be_inserted but does the check assuming
1644    that the location is not duplicated.  */
1645
1646 static int
1647 unduplicated_should_be_inserted (struct bp_location *bl)
1648 {
1649   int result;
1650   const int save_duplicate = bl->duplicate;
1651
1652   bl->duplicate = 0;
1653   result = should_be_inserted (bl);
1654   bl->duplicate = save_duplicate;
1655   return result;
1656 }
1657
1658 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
1659    location.  Any error messages are printed to TMP_ERROR_STREAM; and
1660    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
1661    Returns 0 for success, 1 if the bp_location type is not supported or
1662    -1 for failure.
1663
1664    NOTE drow/2003-09-09: This routine could be broken down to an
1665    object-style method for each breakpoint or catchpoint type.  */
1666 static int
1667 insert_bp_location (struct bp_location *bl,
1668                     struct ui_file *tmp_error_stream,
1669                     int *disabled_breaks,
1670                     int *hw_breakpoint_error)
1671 {
1672   int val = 0;
1673
1674   if (!should_be_inserted (bl) || bl->inserted)
1675     return 0;
1676
1677   /* Initialize the target-specific information.  */
1678   memset (&bl->target_info, 0, sizeof (bl->target_info));
1679   bl->target_info.placed_address = bl->address;
1680   bl->target_info.placed_address_space = bl->pspace->aspace;
1681   bl->target_info.length = bl->length;
1682
1683   if (bl->loc_type == bp_loc_software_breakpoint
1684       || bl->loc_type == bp_loc_hardware_breakpoint)
1685     {
1686       if (bl->owner->type != bp_hardware_breakpoint)
1687         {
1688           /* If the explicitly specified breakpoint type
1689              is not hardware breakpoint, check the memory map to see
1690              if the breakpoint address is in read only memory or not.
1691
1692              Two important cases are:
1693              - location type is not hardware breakpoint, memory
1694              is readonly.  We change the type of the location to
1695              hardware breakpoint.
1696              - location type is hardware breakpoint, memory is
1697              read-write.  This means we've previously made the
1698              location hardware one, but then the memory map changed,
1699              so we undo.
1700              
1701              When breakpoints are removed, remove_breakpoints will use
1702              location types we've just set here, the only possible
1703              problem is that memory map has changed during running
1704              program, but it's not going to work anyway with current
1705              gdb.  */
1706           struct mem_region *mr 
1707             = lookup_mem_region (bl->target_info.placed_address);
1708           
1709           if (mr)
1710             {
1711               if (automatic_hardware_breakpoints)
1712                 {
1713                   enum bp_loc_type new_type;
1714                   
1715                   if (mr->attrib.mode != MEM_RW)
1716                     new_type = bp_loc_hardware_breakpoint;
1717                   else 
1718                     new_type = bp_loc_software_breakpoint;
1719                   
1720                   if (new_type != bl->loc_type)
1721                     {
1722                       static int said = 0;
1723
1724                       bl->loc_type = new_type;
1725                       if (!said)
1726                         {
1727                           fprintf_filtered (gdb_stdout,
1728                                             _("Note: automatically using "
1729                                               "hardware breakpoints for "
1730                                               "read-only addresses.\n"));
1731                           said = 1;
1732                         }
1733                     }
1734                 }
1735               else if (bl->loc_type == bp_loc_software_breakpoint
1736                        && mr->attrib.mode != MEM_RW)        
1737                 warning (_("cannot set software breakpoint "
1738                            "at readonly address %s"),
1739                          paddress (bl->gdbarch, bl->address));
1740             }
1741         }
1742         
1743       /* First check to see if we have to handle an overlay.  */
1744       if (overlay_debugging == ovly_off
1745           || bl->section == NULL
1746           || !(section_is_overlay (bl->section)))
1747         {
1748           /* No overlay handling: just set the breakpoint.  */
1749
1750           val = bl->owner->ops->insert_location (bl);
1751         }
1752       else
1753         {
1754           /* This breakpoint is in an overlay section.
1755              Shall we set a breakpoint at the LMA?  */
1756           if (!overlay_events_enabled)
1757             {
1758               /* Yes -- overlay event support is not active, 
1759                  so we must try to set a breakpoint at the LMA.
1760                  This will not work for a hardware breakpoint.  */
1761               if (bl->loc_type == bp_loc_hardware_breakpoint)
1762                 warning (_("hardware breakpoint %d not supported in overlay!"),
1763                          bl->owner->number);
1764               else
1765                 {
1766                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
1767                                                              bl->section);
1768                   /* Set a software (trap) breakpoint at the LMA.  */
1769                   bl->overlay_target_info = bl->target_info;
1770                   bl->overlay_target_info.placed_address = addr;
1771                   val = target_insert_breakpoint (bl->gdbarch,
1772                                                   &bl->overlay_target_info);
1773                   if (val != 0)
1774                     fprintf_unfiltered (tmp_error_stream,
1775                                         "Overlay breakpoint %d "
1776                                         "failed: in ROM?\n",
1777                                         bl->owner->number);
1778                 }
1779             }
1780           /* Shall we set a breakpoint at the VMA? */
1781           if (section_is_mapped (bl->section))
1782             {
1783               /* Yes.  This overlay section is mapped into memory.  */
1784               val = bl->owner->ops->insert_location (bl);
1785             }
1786           else
1787             {
1788               /* No.  This breakpoint will not be inserted.  
1789                  No error, but do not mark the bp as 'inserted'.  */
1790               return 0;
1791             }
1792         }
1793
1794       if (val)
1795         {
1796           /* Can't set the breakpoint.  */
1797           if (solib_name_from_address (bl->pspace, bl->address))
1798             {
1799               /* See also: disable_breakpoints_in_shlibs.  */
1800               val = 0;
1801               bl->shlib_disabled = 1;
1802               observer_notify_breakpoint_modified (bl->owner);
1803               if (!*disabled_breaks)
1804                 {
1805                   fprintf_unfiltered (tmp_error_stream, 
1806                                       "Cannot insert breakpoint %d.\n", 
1807                                       bl->owner->number);
1808                   fprintf_unfiltered (tmp_error_stream, 
1809                                       "Temporarily disabling shared "
1810                                       "library breakpoints:\n");
1811                 }
1812               *disabled_breaks = 1;
1813               fprintf_unfiltered (tmp_error_stream,
1814                                   "breakpoint #%d\n", bl->owner->number);
1815             }
1816           else
1817             {
1818               if (bl->loc_type == bp_loc_hardware_breakpoint)
1819                 {
1820                   *hw_breakpoint_error = 1;
1821                   fprintf_unfiltered (tmp_error_stream,
1822                                       "Cannot insert hardware "
1823                                       "breakpoint %d.\n",
1824                                       bl->owner->number);
1825                 }
1826               else
1827                 {
1828                   fprintf_unfiltered (tmp_error_stream, 
1829                                       "Cannot insert breakpoint %d.\n", 
1830                                       bl->owner->number);
1831                   fprintf_filtered (tmp_error_stream, 
1832                                     "Error accessing memory address ");
1833                   fputs_filtered (paddress (bl->gdbarch, bl->address),
1834                                   tmp_error_stream);
1835                   fprintf_filtered (tmp_error_stream, ": %s.\n",
1836                                     safe_strerror (val));
1837                 }
1838
1839             }
1840         }
1841       else
1842         bl->inserted = 1;
1843
1844       return val;
1845     }
1846
1847   else if (bl->loc_type == bp_loc_hardware_watchpoint
1848            /* NOTE drow/2003-09-08: This state only exists for removing
1849               watchpoints.  It's not clear that it's necessary...  */
1850            && bl->owner->disposition != disp_del_at_next_stop)
1851     {
1852       gdb_assert (bl->owner->ops != NULL
1853                   && bl->owner->ops->insert_location != NULL);
1854
1855       val = bl->owner->ops->insert_location (bl);
1856
1857       /* If trying to set a read-watchpoint, and it turns out it's not
1858          supported, try emulating one with an access watchpoint.  */
1859       if (val == 1 && bl->watchpoint_type == hw_read)
1860         {
1861           struct bp_location *loc, **loc_temp;
1862
1863           /* But don't try to insert it, if there's already another
1864              hw_access location that would be considered a duplicate
1865              of this one.  */
1866           ALL_BP_LOCATIONS (loc, loc_temp)
1867             if (loc != bl
1868                 && loc->watchpoint_type == hw_access
1869                 && watchpoint_locations_match (bl, loc))
1870               {
1871                 bl->duplicate = 1;
1872                 bl->inserted = 1;
1873                 bl->target_info = loc->target_info;
1874                 bl->watchpoint_type = hw_access;
1875                 val = 0;
1876                 break;
1877               }
1878
1879           if (val == 1)
1880             {
1881               bl->watchpoint_type = hw_access;
1882               val = bl->owner->ops->insert_location (bl);
1883
1884               if (val)
1885                 /* Back to the original value.  */
1886                 bl->watchpoint_type = hw_read;
1887             }
1888         }
1889
1890       bl->inserted = (val == 0);
1891     }
1892
1893   else if (bl->owner->type == bp_catchpoint)
1894     {
1895       gdb_assert (bl->owner->ops != NULL
1896                   && bl->owner->ops->insert_location != NULL);
1897
1898       val = bl->owner->ops->insert_location (bl);
1899       if (val)
1900         {
1901           bl->owner->enable_state = bp_disabled;
1902
1903           if (val == 1)
1904             warning (_("\
1905 Error inserting catchpoint %d: Your system does not support this type\n\
1906 of catchpoint."), bl->owner->number);
1907           else
1908             warning (_("Error inserting catchpoint %d."), bl->owner->number);
1909         }
1910
1911       bl->inserted = (val == 0);
1912
1913       /* We've already printed an error message if there was a problem
1914          inserting this catchpoint, and we've disabled the catchpoint,
1915          so just return success.  */
1916       return 0;
1917     }
1918
1919   return 0;
1920 }
1921
1922 /* This function is called when program space PSPACE is about to be
1923    deleted.  It takes care of updating breakpoints to not reference
1924    PSPACE anymore.  */
1925
1926 void
1927 breakpoint_program_space_exit (struct program_space *pspace)
1928 {
1929   struct breakpoint *b, *b_temp;
1930   struct bp_location *loc, **loc_temp;
1931
1932   /* Remove any breakpoint that was set through this program space.  */
1933   ALL_BREAKPOINTS_SAFE (b, b_temp)
1934     {
1935       if (b->pspace == pspace)
1936         delete_breakpoint (b);
1937     }
1938
1939   /* Breakpoints set through other program spaces could have locations
1940      bound to PSPACE as well.  Remove those.  */
1941   ALL_BP_LOCATIONS (loc, loc_temp)
1942     {
1943       struct bp_location *tmp;
1944
1945       if (loc->pspace == pspace)
1946         {
1947           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
1948           if (loc->owner->loc == loc)
1949             loc->owner->loc = loc->next;
1950           else
1951             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
1952               if (tmp->next == loc)
1953                 {
1954                   tmp->next = loc->next;
1955                   break;
1956                 }
1957         }
1958     }
1959
1960   /* Now update the global location list to permanently delete the
1961      removed locations above.  */
1962   update_global_location_list (0);
1963 }
1964
1965 /* Make sure all breakpoints are inserted in inferior.
1966    Throws exception on any error.
1967    A breakpoint that is already inserted won't be inserted
1968    again, so calling this function twice is safe.  */
1969 void
1970 insert_breakpoints (void)
1971 {
1972   struct breakpoint *bpt;
1973
1974   ALL_BREAKPOINTS (bpt)
1975     if (is_hardware_watchpoint (bpt))
1976       {
1977         struct watchpoint *w = (struct watchpoint *) bpt;
1978
1979         update_watchpoint (w, 0 /* don't reparse.  */);
1980       }
1981
1982   update_global_location_list (1);
1983
1984   /* update_global_location_list does not insert breakpoints when
1985      always_inserted_mode is not enabled.  Explicitly insert them
1986      now.  */
1987   if (!breakpoints_always_inserted_mode ())
1988     insert_breakpoint_locations ();
1989 }
1990
1991 /* Used when starting or continuing the program.  */
1992
1993 static void
1994 insert_breakpoint_locations (void)
1995 {
1996   struct breakpoint *bpt;
1997   struct bp_location *bl, **blp_tmp;
1998   int error_flag = 0;
1999   int val = 0;
2000   int disabled_breaks = 0;
2001   int hw_breakpoint_error = 0;
2002
2003   struct ui_file *tmp_error_stream = mem_fileopen ();
2004   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2005   
2006   /* Explicitly mark the warning -- this will only be printed if
2007      there was an error.  */
2008   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2009
2010   save_current_space_and_thread ();
2011
2012   ALL_BP_LOCATIONS (bl, blp_tmp)
2013     {
2014       if (!should_be_inserted (bl) || bl->inserted)
2015         continue;
2016
2017       /* There is no point inserting thread-specific breakpoints if
2018          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2019          has BL->OWNER always non-NULL.  */
2020       if (bl->owner->thread != -1
2021           && !valid_thread_id (bl->owner->thread))
2022         continue;
2023
2024       switch_to_program_space_and_thread (bl->pspace);
2025
2026       /* For targets that support global breakpoints, there's no need
2027          to select an inferior to insert breakpoint to.  In fact, even
2028          if we aren't attached to any process yet, we should still
2029          insert breakpoints.  */
2030       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2031           && ptid_equal (inferior_ptid, null_ptid))
2032         continue;
2033
2034       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2035                                     &hw_breakpoint_error);
2036       if (val)
2037         error_flag = val;
2038     }
2039
2040   /* If we failed to insert all locations of a watchpoint, remove
2041      them, as half-inserted watchpoint is of limited use.  */
2042   ALL_BREAKPOINTS (bpt)  
2043     {
2044       int some_failed = 0;
2045       struct bp_location *loc;
2046
2047       if (!is_hardware_watchpoint (bpt))
2048         continue;
2049
2050       if (!breakpoint_enabled (bpt))
2051         continue;
2052
2053       if (bpt->disposition == disp_del_at_next_stop)
2054         continue;
2055       
2056       for (loc = bpt->loc; loc; loc = loc->next)
2057         if (!loc->inserted && should_be_inserted (loc))
2058           {
2059             some_failed = 1;
2060             break;
2061           }
2062       if (some_failed)
2063         {
2064           for (loc = bpt->loc; loc; loc = loc->next)
2065             if (loc->inserted)
2066               remove_breakpoint (loc, mark_uninserted);
2067
2068           hw_breakpoint_error = 1;
2069           fprintf_unfiltered (tmp_error_stream,
2070                               "Could not insert hardware watchpoint %d.\n", 
2071                               bpt->number);
2072           error_flag = -1;
2073         }
2074     }
2075
2076   if (error_flag)
2077     {
2078       /* If a hardware breakpoint or watchpoint was inserted, add a
2079          message about possibly exhausted resources.  */
2080       if (hw_breakpoint_error)
2081         {
2082           fprintf_unfiltered (tmp_error_stream, 
2083                               "Could not insert hardware breakpoints:\n\
2084 You may have requested too many hardware breakpoints/watchpoints.\n");
2085         }
2086       target_terminal_ours_for_output ();
2087       error_stream (tmp_error_stream);
2088     }
2089
2090   do_cleanups (cleanups);
2091 }
2092
2093 /* Used when the program stops.
2094    Returns zero if successful, or non-zero if there was a problem
2095    removing a breakpoint location.  */
2096
2097 int
2098 remove_breakpoints (void)
2099 {
2100   struct bp_location *bl, **blp_tmp;
2101   int val = 0;
2102
2103   ALL_BP_LOCATIONS (bl, blp_tmp)
2104   {
2105     if (bl->inserted && !is_tracepoint (bl->owner))
2106       val |= remove_breakpoint (bl, mark_uninserted);
2107   }
2108   return val;
2109 }
2110
2111 /* Remove breakpoints of process PID.  */
2112
2113 int
2114 remove_breakpoints_pid (int pid)
2115 {
2116   struct bp_location *bl, **blp_tmp;
2117   int val;
2118   struct inferior *inf = find_inferior_pid (pid);
2119
2120   ALL_BP_LOCATIONS (bl, blp_tmp)
2121   {
2122     if (bl->pspace != inf->pspace)
2123       continue;
2124
2125     if (bl->inserted)
2126       {
2127         val = remove_breakpoint (bl, mark_uninserted);
2128         if (val != 0)
2129           return val;
2130       }
2131   }
2132   return 0;
2133 }
2134
2135 int
2136 reattach_breakpoints (int pid)
2137 {
2138   struct cleanup *old_chain;
2139   struct bp_location *bl, **blp_tmp;
2140   int val;
2141   struct ui_file *tmp_error_stream;
2142   int dummy1 = 0, dummy2 = 0;
2143   struct inferior *inf;
2144   struct thread_info *tp;
2145
2146   tp = any_live_thread_of_process (pid);
2147   if (tp == NULL)
2148     return 1;
2149
2150   inf = find_inferior_pid (pid);
2151   old_chain = save_inferior_ptid ();
2152
2153   inferior_ptid = tp->ptid;
2154
2155   tmp_error_stream = mem_fileopen ();
2156   make_cleanup_ui_file_delete (tmp_error_stream);
2157
2158   ALL_BP_LOCATIONS (bl, blp_tmp)
2159   {
2160     if (bl->pspace != inf->pspace)
2161       continue;
2162
2163     if (bl->inserted)
2164       {
2165         bl->inserted = 0;
2166         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2167         if (val != 0)
2168           {
2169             do_cleanups (old_chain);
2170             return val;
2171           }
2172       }
2173   }
2174   do_cleanups (old_chain);
2175   return 0;
2176 }
2177
2178 static int internal_breakpoint_number = -1;
2179
2180 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2181    If INTERNAL is non-zero, the breakpoint number will be populated
2182    from internal_breakpoint_number and that variable decremented.
2183    Otherwise the breakpoint number will be populated from
2184    breakpoint_count and that value incremented.  Internal breakpoints
2185    do not set the internal var bpnum.  */
2186 static void
2187 set_breakpoint_number (int internal, struct breakpoint *b)
2188 {
2189   if (internal)
2190     b->number = internal_breakpoint_number--;
2191   else
2192     {
2193       set_breakpoint_count (breakpoint_count + 1);
2194       b->number = breakpoint_count;
2195     }
2196 }
2197
2198 static struct breakpoint *
2199 create_internal_breakpoint (struct gdbarch *gdbarch,
2200                             CORE_ADDR address, enum bptype type,
2201                             const struct breakpoint_ops *ops)
2202 {
2203   struct symtab_and_line sal;
2204   struct breakpoint *b;
2205
2206   init_sal (&sal);              /* Initialize to zeroes.  */
2207
2208   sal.pc = address;
2209   sal.section = find_pc_overlay (sal.pc);
2210   sal.pspace = current_program_space;
2211
2212   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2213   b->number = internal_breakpoint_number--;
2214   b->disposition = disp_donttouch;
2215
2216   return b;
2217 }
2218
2219 static const char *const longjmp_names[] =
2220   {
2221     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2222   };
2223 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2224
2225 /* Per-objfile data private to breakpoint.c.  */
2226 struct breakpoint_objfile_data
2227 {
2228   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2229   struct minimal_symbol *overlay_msym;
2230
2231   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2232   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2233
2234   /* Minimal symbol for "std::terminate()" (if any).  */
2235   struct minimal_symbol *terminate_msym;
2236
2237   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2238   struct minimal_symbol *exception_msym;
2239 };
2240
2241 static const struct objfile_data *breakpoint_objfile_key;
2242
2243 /* Minimal symbol not found sentinel.  */
2244 static struct minimal_symbol msym_not_found;
2245
2246 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2247
2248 static int
2249 msym_not_found_p (const struct minimal_symbol *msym)
2250 {
2251   return msym == &msym_not_found;
2252 }
2253
2254 /* Return per-objfile data needed by breakpoint.c.
2255    Allocate the data if necessary.  */
2256
2257 static struct breakpoint_objfile_data *
2258 get_breakpoint_objfile_data (struct objfile *objfile)
2259 {
2260   struct breakpoint_objfile_data *bp_objfile_data;
2261
2262   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2263   if (bp_objfile_data == NULL)
2264     {
2265       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2266                                        sizeof (*bp_objfile_data));
2267
2268       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2269       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2270     }
2271   return bp_objfile_data;
2272 }
2273
2274 static void
2275 create_overlay_event_breakpoint (void)
2276 {
2277   struct objfile *objfile;
2278   const char *const func_name = "_ovly_debug_event";
2279
2280   ALL_OBJFILES (objfile)
2281     {
2282       struct breakpoint *b;
2283       struct breakpoint_objfile_data *bp_objfile_data;
2284       CORE_ADDR addr;
2285
2286       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2287
2288       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2289         continue;
2290
2291       if (bp_objfile_data->overlay_msym == NULL)
2292         {
2293           struct minimal_symbol *m;
2294
2295           m = lookup_minimal_symbol_text (func_name, objfile);
2296           if (m == NULL)
2297             {
2298               /* Avoid future lookups in this objfile.  */
2299               bp_objfile_data->overlay_msym = &msym_not_found;
2300               continue;
2301             }
2302           bp_objfile_data->overlay_msym = m;
2303         }
2304
2305       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2306       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2307                                       bp_overlay_event,
2308                                       &internal_breakpoint_ops);
2309       b->addr_string = xstrdup (func_name);
2310
2311       if (overlay_debugging == ovly_auto)
2312         {
2313           b->enable_state = bp_enabled;
2314           overlay_events_enabled = 1;
2315         }
2316       else
2317        {
2318          b->enable_state = bp_disabled;
2319          overlay_events_enabled = 0;
2320        }
2321     }
2322   update_global_location_list (1);
2323 }
2324
2325 static void
2326 create_longjmp_master_breakpoint (void)
2327 {
2328   struct program_space *pspace;
2329   struct cleanup *old_chain;
2330
2331   old_chain = save_current_program_space ();
2332
2333   ALL_PSPACES (pspace)
2334   {
2335     struct objfile *objfile;
2336
2337     set_current_program_space (pspace);
2338
2339     ALL_OBJFILES (objfile)
2340     {
2341       int i;
2342       struct gdbarch *gdbarch;
2343       struct breakpoint_objfile_data *bp_objfile_data;
2344
2345       gdbarch = get_objfile_arch (objfile);
2346       if (!gdbarch_get_longjmp_target_p (gdbarch))
2347         continue;
2348
2349       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2350
2351       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2352         {
2353           struct breakpoint *b;
2354           const char *func_name;
2355           CORE_ADDR addr;
2356
2357           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2358             continue;
2359
2360           func_name = longjmp_names[i];
2361           if (bp_objfile_data->longjmp_msym[i] == NULL)
2362             {
2363               struct minimal_symbol *m;
2364
2365               m = lookup_minimal_symbol_text (func_name, objfile);
2366               if (m == NULL)
2367                 {
2368                   /* Prevent future lookups in this objfile.  */
2369                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2370                   continue;
2371                 }
2372               bp_objfile_data->longjmp_msym[i] = m;
2373             }
2374
2375           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2376           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2377                                           &internal_breakpoint_ops);
2378           b->addr_string = xstrdup (func_name);
2379           b->enable_state = bp_disabled;
2380         }
2381     }
2382   }
2383   update_global_location_list (1);
2384
2385   do_cleanups (old_chain);
2386 }
2387
2388 /* Create a master std::terminate breakpoint.  */
2389 static void
2390 create_std_terminate_master_breakpoint (void)
2391 {
2392   struct program_space *pspace;
2393   struct cleanup *old_chain;
2394   const char *const func_name = "std::terminate()";
2395
2396   old_chain = save_current_program_space ();
2397
2398   ALL_PSPACES (pspace)
2399   {
2400     struct objfile *objfile;
2401     CORE_ADDR addr;
2402
2403     set_current_program_space (pspace);
2404
2405     ALL_OBJFILES (objfile)
2406     {
2407       struct breakpoint *b;
2408       struct breakpoint_objfile_data *bp_objfile_data;
2409
2410       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2411
2412       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2413         continue;
2414
2415       if (bp_objfile_data->terminate_msym == NULL)
2416         {
2417           struct minimal_symbol *m;
2418
2419           m = lookup_minimal_symbol (func_name, NULL, objfile);
2420           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2421                             && MSYMBOL_TYPE (m) != mst_file_text))
2422             {
2423               /* Prevent future lookups in this objfile.  */
2424               bp_objfile_data->terminate_msym = &msym_not_found;
2425               continue;
2426             }
2427           bp_objfile_data->terminate_msym = m;
2428         }
2429
2430       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
2431       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2432                                       bp_std_terminate_master,
2433                                       &internal_breakpoint_ops);
2434       b->addr_string = xstrdup (func_name);
2435       b->enable_state = bp_disabled;
2436     }
2437   }
2438
2439   update_global_location_list (1);
2440
2441   do_cleanups (old_chain);
2442 }
2443
2444 /* Install a master breakpoint on the unwinder's debug hook.  */
2445
2446 void
2447 create_exception_master_breakpoint (void)
2448 {
2449   struct objfile *objfile;
2450   const char *const func_name = "_Unwind_DebugHook";
2451
2452   ALL_OBJFILES (objfile)
2453     {
2454       struct breakpoint *b;
2455       struct gdbarch *gdbarch;
2456       struct breakpoint_objfile_data *bp_objfile_data;
2457       CORE_ADDR addr;
2458
2459       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2460
2461       if (msym_not_found_p (bp_objfile_data->exception_msym))
2462         continue;
2463
2464       gdbarch = get_objfile_arch (objfile);
2465
2466       if (bp_objfile_data->exception_msym == NULL)
2467         {
2468           struct minimal_symbol *debug_hook;
2469
2470           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2471           if (debug_hook == NULL)
2472             {
2473               bp_objfile_data->exception_msym = &msym_not_found;
2474               continue;
2475             }
2476
2477           bp_objfile_data->exception_msym = debug_hook;
2478         }
2479
2480       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2481       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2482                                                  &current_target);
2483       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2484                                       &internal_breakpoint_ops);
2485       b->addr_string = xstrdup (func_name);
2486       b->enable_state = bp_disabled;
2487     }
2488
2489   update_global_location_list (1);
2490 }
2491
2492 void
2493 update_breakpoints_after_exec (void)
2494 {
2495   struct breakpoint *b, *b_tmp;
2496   struct bp_location *bploc, **bplocp_tmp;
2497
2498   /* We're about to delete breakpoints from GDB's lists.  If the
2499      INSERTED flag is true, GDB will try to lift the breakpoints by
2500      writing the breakpoints' "shadow contents" back into memory.  The
2501      "shadow contents" are NOT valid after an exec, so GDB should not
2502      do that.  Instead, the target is responsible from marking
2503      breakpoints out as soon as it detects an exec.  We don't do that
2504      here instead, because there may be other attempts to delete
2505      breakpoints after detecting an exec and before reaching here.  */
2506   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
2507     if (bploc->pspace == current_program_space)
2508       gdb_assert (!bploc->inserted);
2509
2510   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2511   {
2512     if (b->pspace != current_program_space)
2513       continue;
2514
2515     /* Solib breakpoints must be explicitly reset after an exec().  */
2516     if (b->type == bp_shlib_event)
2517       {
2518         delete_breakpoint (b);
2519         continue;
2520       }
2521
2522     /* JIT breakpoints must be explicitly reset after an exec().  */
2523     if (b->type == bp_jit_event)
2524       {
2525         delete_breakpoint (b);
2526         continue;
2527       }
2528
2529     /* Thread event breakpoints must be set anew after an exec(),
2530        as must overlay event and longjmp master breakpoints.  */
2531     if (b->type == bp_thread_event || b->type == bp_overlay_event
2532         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
2533         || b->type == bp_exception_master)
2534       {
2535         delete_breakpoint (b);
2536         continue;
2537       }
2538
2539     /* Step-resume breakpoints are meaningless after an exec().  */
2540     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
2541       {
2542         delete_breakpoint (b);
2543         continue;
2544       }
2545
2546     /* Longjmp and longjmp-resume breakpoints are also meaningless
2547        after an exec.  */
2548     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
2549         || b->type == bp_exception || b->type == bp_exception_resume)
2550       {
2551         delete_breakpoint (b);
2552         continue;
2553       }
2554
2555     if (b->type == bp_catchpoint)
2556       {
2557         /* For now, none of the bp_catchpoint breakpoints need to
2558            do anything at this point.  In the future, if some of
2559            the catchpoints need to something, we will need to add
2560            a new method, and call this method from here.  */
2561         continue;
2562       }
2563
2564     /* bp_finish is a special case.  The only way we ought to be able
2565        to see one of these when an exec() has happened, is if the user
2566        caught a vfork, and then said "finish".  Ordinarily a finish just
2567        carries them to the call-site of the current callee, by setting
2568        a temporary bp there and resuming.  But in this case, the finish
2569        will carry them entirely through the vfork & exec.
2570
2571        We don't want to allow a bp_finish to remain inserted now.  But
2572        we can't safely delete it, 'cause finish_command has a handle to
2573        the bp on a bpstat, and will later want to delete it.  There's a
2574        chance (and I've seen it happen) that if we delete the bp_finish
2575        here, that its storage will get reused by the time finish_command
2576        gets 'round to deleting the "use to be a bp_finish" breakpoint.
2577        We really must allow finish_command to delete a bp_finish.
2578
2579        In the absence of a general solution for the "how do we know
2580        it's safe to delete something others may have handles to?"
2581        problem, what we'll do here is just uninsert the bp_finish, and
2582        let finish_command delete it.
2583
2584        (We know the bp_finish is "doomed" in the sense that it's
2585        momentary, and will be deleted as soon as finish_command sees
2586        the inferior stopped.  So it doesn't matter that the bp's
2587        address is probably bogus in the new a.out, unlike e.g., the
2588        solib breakpoints.)  */
2589
2590     if (b->type == bp_finish)
2591       {
2592         continue;
2593       }
2594
2595     /* Without a symbolic address, we have little hope of the
2596        pre-exec() address meaning the same thing in the post-exec()
2597        a.out.  */
2598     if (b->addr_string == NULL)
2599       {
2600         delete_breakpoint (b);
2601         continue;
2602       }
2603   }
2604   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
2605   create_overlay_event_breakpoint ();
2606   create_longjmp_master_breakpoint ();
2607   create_std_terminate_master_breakpoint ();
2608   create_exception_master_breakpoint ();
2609 }
2610
2611 int
2612 detach_breakpoints (int pid)
2613 {
2614   struct bp_location *bl, **blp_tmp;
2615   int val = 0;
2616   struct cleanup *old_chain = save_inferior_ptid ();
2617   struct inferior *inf = current_inferior ();
2618
2619   if (pid == PIDGET (inferior_ptid))
2620     error (_("Cannot detach breakpoints of inferior_ptid"));
2621
2622   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
2623   inferior_ptid = pid_to_ptid (pid);
2624   ALL_BP_LOCATIONS (bl, blp_tmp)
2625   {
2626     if (bl->pspace != inf->pspace)
2627       continue;
2628
2629     if (bl->inserted)
2630       val |= remove_breakpoint_1 (bl, mark_inserted);
2631   }
2632
2633   /* Detach single-step breakpoints as well.  */
2634   detach_single_step_breakpoints ();
2635
2636   do_cleanups (old_chain);
2637   return val;
2638 }
2639
2640 /* Remove the breakpoint location BL from the current address space.
2641    Note that this is used to detach breakpoints from a child fork.
2642    When we get here, the child isn't in the inferior list, and neither
2643    do we have objects to represent its address space --- we should
2644    *not* look at bl->pspace->aspace here.  */
2645
2646 static int
2647 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
2648 {
2649   int val;
2650
2651   /* BL is never in moribund_locations by our callers.  */
2652   gdb_assert (bl->owner != NULL);
2653
2654   if (bl->owner->enable_state == bp_permanent)
2655     /* Permanent breakpoints cannot be inserted or removed.  */
2656     return 0;
2657
2658   /* The type of none suggests that owner is actually deleted.
2659      This should not ever happen.  */
2660   gdb_assert (bl->owner->type != bp_none);
2661
2662   if (bl->loc_type == bp_loc_software_breakpoint
2663       || bl->loc_type == bp_loc_hardware_breakpoint)
2664     {
2665       /* "Normal" instruction breakpoint: either the standard
2666          trap-instruction bp (bp_breakpoint), or a
2667          bp_hardware_breakpoint.  */
2668
2669       /* First check to see if we have to handle an overlay.  */
2670       if (overlay_debugging == ovly_off
2671           || bl->section == NULL
2672           || !(section_is_overlay (bl->section)))
2673         {
2674           /* No overlay handling: just remove the breakpoint.  */
2675           val = bl->owner->ops->remove_location (bl);
2676         }
2677       else
2678         {
2679           /* This breakpoint is in an overlay section.
2680              Did we set a breakpoint at the LMA?  */
2681           if (!overlay_events_enabled)
2682               {
2683                 /* Yes -- overlay event support is not active, so we
2684                    should have set a breakpoint at the LMA.  Remove it.  
2685                 */
2686                 /* Ignore any failures: if the LMA is in ROM, we will
2687                    have already warned when we failed to insert it.  */
2688                 if (bl->loc_type == bp_loc_hardware_breakpoint)
2689                   target_remove_hw_breakpoint (bl->gdbarch,
2690                                                &bl->overlay_target_info);
2691                 else
2692                   target_remove_breakpoint (bl->gdbarch,
2693                                             &bl->overlay_target_info);
2694               }
2695           /* Did we set a breakpoint at the VMA? 
2696              If so, we will have marked the breakpoint 'inserted'.  */
2697           if (bl->inserted)
2698             {
2699               /* Yes -- remove it.  Previously we did not bother to
2700                  remove the breakpoint if the section had been
2701                  unmapped, but let's not rely on that being safe.  We
2702                  don't know what the overlay manager might do.  */
2703
2704               /* However, we should remove *software* breakpoints only
2705                  if the section is still mapped, or else we overwrite
2706                  wrong code with the saved shadow contents.  */
2707               if (bl->loc_type == bp_loc_hardware_breakpoint
2708                   || section_is_mapped (bl->section))
2709                 val = bl->owner->ops->remove_location (bl);
2710               else
2711                 val = 0;
2712             }
2713           else
2714             {
2715               /* No -- not inserted, so no need to remove.  No error.  */
2716               val = 0;
2717             }
2718         }
2719
2720       /* In some cases, we might not be able to remove a breakpoint
2721          in a shared library that has already been removed, but we
2722          have not yet processed the shlib unload event.  */
2723       if (val && solib_name_from_address (bl->pspace, bl->address))
2724         val = 0;
2725
2726       if (val)
2727         return val;
2728       bl->inserted = (is == mark_inserted);
2729     }
2730   else if (bl->loc_type == bp_loc_hardware_watchpoint)
2731     {
2732       gdb_assert (bl->owner->ops != NULL
2733                   && bl->owner->ops->remove_location != NULL);
2734
2735       bl->inserted = (is == mark_inserted);
2736       bl->owner->ops->remove_location (bl);
2737
2738       /* Failure to remove any of the hardware watchpoints comes here.  */
2739       if ((is == mark_uninserted) && (bl->inserted))
2740         warning (_("Could not remove hardware watchpoint %d."),
2741                  bl->owner->number);
2742     }
2743   else if (bl->owner->type == bp_catchpoint
2744            && breakpoint_enabled (bl->owner)
2745            && !bl->duplicate)
2746     {
2747       gdb_assert (bl->owner->ops != NULL
2748                   && bl->owner->ops->remove_location != NULL);
2749
2750       val = bl->owner->ops->remove_location (bl);
2751       if (val)
2752         return val;
2753
2754       bl->inserted = (is == mark_inserted);
2755     }
2756
2757   return 0;
2758 }
2759
2760 static int
2761 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
2762 {
2763   int ret;
2764   struct cleanup *old_chain;
2765
2766   /* BL is never in moribund_locations by our callers.  */
2767   gdb_assert (bl->owner != NULL);
2768
2769   if (bl->owner->enable_state == bp_permanent)
2770     /* Permanent breakpoints cannot be inserted or removed.  */
2771     return 0;
2772
2773   /* The type of none suggests that owner is actually deleted.
2774      This should not ever happen.  */
2775   gdb_assert (bl->owner->type != bp_none);
2776
2777   old_chain = save_current_space_and_thread ();
2778
2779   switch_to_program_space_and_thread (bl->pspace);
2780
2781   ret = remove_breakpoint_1 (bl, is);
2782
2783   do_cleanups (old_chain);
2784   return ret;
2785 }
2786
2787 /* Clear the "inserted" flag in all breakpoints.  */
2788
2789 void
2790 mark_breakpoints_out (void)
2791 {
2792   struct bp_location *bl, **blp_tmp;
2793
2794   ALL_BP_LOCATIONS (bl, blp_tmp)
2795     if (bl->pspace == current_program_space)
2796       bl->inserted = 0;
2797 }
2798
2799 /* Clear the "inserted" flag in all breakpoints and delete any
2800    breakpoints which should go away between runs of the program.
2801
2802    Plus other such housekeeping that has to be done for breakpoints
2803    between runs.
2804
2805    Note: this function gets called at the end of a run (by
2806    generic_mourn_inferior) and when a run begins (by
2807    init_wait_for_inferior).  */
2808
2809
2810
2811 void
2812 breakpoint_init_inferior (enum inf_context context)
2813 {
2814   struct breakpoint *b, *b_tmp;
2815   struct bp_location *bl, **blp_tmp;
2816   int ix;
2817   struct program_space *pspace = current_program_space;
2818
2819   /* If breakpoint locations are shared across processes, then there's
2820      nothing to do.  */
2821   if (gdbarch_has_global_breakpoints (target_gdbarch))
2822     return;
2823
2824   ALL_BP_LOCATIONS (bl, blp_tmp)
2825   {
2826     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
2827     if (bl->pspace == pspace
2828         && bl->owner->enable_state != bp_permanent)
2829       bl->inserted = 0;
2830   }
2831
2832   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2833   {
2834     if (b->loc && b->loc->pspace != pspace)
2835       continue;
2836
2837     switch (b->type)
2838       {
2839       case bp_call_dummy:
2840
2841         /* If the call dummy breakpoint is at the entry point it will
2842            cause problems when the inferior is rerun, so we better get
2843            rid of it.  */
2844
2845       case bp_watchpoint_scope:
2846
2847         /* Also get rid of scope breakpoints.  */
2848
2849       case bp_shlib_event:
2850
2851         /* Also remove solib event breakpoints.  Their addresses may
2852            have changed since the last time we ran the program.
2853            Actually we may now be debugging against different target;
2854            and so the solib backend that installed this breakpoint may
2855            not be used in by the target.  E.g.,
2856
2857            (gdb) file prog-linux
2858            (gdb) run               # native linux target
2859            ...
2860            (gdb) kill
2861            (gdb) file prog-win.exe
2862            (gdb) tar rem :9999     # remote Windows gdbserver.
2863         */
2864
2865         delete_breakpoint (b);
2866         break;
2867
2868       case bp_watchpoint:
2869       case bp_hardware_watchpoint:
2870       case bp_read_watchpoint:
2871       case bp_access_watchpoint:
2872         {
2873           struct watchpoint *w = (struct watchpoint *) b;
2874
2875           /* Likewise for watchpoints on local expressions.  */
2876           if (w->exp_valid_block != NULL)
2877             delete_breakpoint (b);
2878           else if (context == inf_starting)
2879             {
2880               /* Reset val field to force reread of starting value in
2881                  insert_breakpoints.  */
2882               if (w->val)
2883                 value_free (w->val);
2884               w->val = NULL;
2885               w->val_valid = 0;
2886           }
2887         }
2888         break;
2889       default:
2890         break;
2891       }
2892   }
2893
2894   /* Get rid of the moribund locations.  */
2895   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
2896     decref_bp_location (&bl);
2897   VEC_free (bp_location_p, moribund_locations);
2898 }
2899
2900 /* These functions concern about actual breakpoints inserted in the
2901    target --- to e.g. check if we need to do decr_pc adjustment or if
2902    we need to hop over the bkpt --- so we check for address space
2903    match, not program space.  */
2904
2905 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
2906    exists at PC.  It returns ordinary_breakpoint_here if it's an
2907    ordinary breakpoint, or permanent_breakpoint_here if it's a
2908    permanent breakpoint.
2909    - When continuing from a location with an ordinary breakpoint, we
2910      actually single step once before calling insert_breakpoints.
2911    - When continuing from a location with a permanent breakpoint, we
2912      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
2913      the target, to advance the PC past the breakpoint.  */
2914
2915 enum breakpoint_here
2916 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2917 {
2918   struct bp_location *bl, **blp_tmp;
2919   int any_breakpoint_here = 0;
2920
2921   ALL_BP_LOCATIONS (bl, blp_tmp)
2922     {
2923       if (bl->loc_type != bp_loc_software_breakpoint
2924           && bl->loc_type != bp_loc_hardware_breakpoint)
2925         continue;
2926
2927       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
2928       if ((breakpoint_enabled (bl->owner)
2929            || bl->owner->enable_state == bp_permanent)
2930           && breakpoint_location_address_match (bl, aspace, pc))
2931         {
2932           if (overlay_debugging 
2933               && section_is_overlay (bl->section)
2934               && !section_is_mapped (bl->section))
2935             continue;           /* unmapped overlay -- can't be a match */
2936           else if (bl->owner->enable_state == bp_permanent)
2937             return permanent_breakpoint_here;
2938           else
2939             any_breakpoint_here = 1;
2940         }
2941     }
2942
2943   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
2944 }
2945
2946 /* Return true if there's a moribund breakpoint at PC.  */
2947
2948 int
2949 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2950 {
2951   struct bp_location *loc;
2952   int ix;
2953
2954   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
2955     if (breakpoint_location_address_match (loc, aspace, pc))
2956       return 1;
2957
2958   return 0;
2959 }
2960
2961 /* Returns non-zero if there's a breakpoint inserted at PC, which is
2962    inserted using regular breakpoint_chain / bp_location array
2963    mechanism.  This does not check for single-step breakpoints, which
2964    are inserted and removed using direct target manipulation.  */
2965
2966 int
2967 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
2968                                     CORE_ADDR pc)
2969 {
2970   struct bp_location *bl, **blp_tmp;
2971
2972   ALL_BP_LOCATIONS (bl, blp_tmp)
2973     {
2974       if (bl->loc_type != bp_loc_software_breakpoint
2975           && bl->loc_type != bp_loc_hardware_breakpoint)
2976         continue;
2977
2978       if (bl->inserted
2979           && breakpoint_location_address_match (bl, aspace, pc))
2980         {
2981           if (overlay_debugging 
2982               && section_is_overlay (bl->section)
2983               && !section_is_mapped (bl->section))
2984             continue;           /* unmapped overlay -- can't be a match */
2985           else
2986             return 1;
2987         }
2988     }
2989   return 0;
2990 }
2991
2992 /* Returns non-zero iff there's either regular breakpoint
2993    or a single step breakpoint inserted at PC.  */
2994
2995 int
2996 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
2997 {
2998   if (regular_breakpoint_inserted_here_p (aspace, pc))
2999     return 1;
3000
3001   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3002     return 1;
3003
3004   return 0;
3005 }
3006
3007 /* This function returns non-zero iff there is a software breakpoint
3008    inserted at PC.  */
3009
3010 int
3011 software_breakpoint_inserted_here_p (struct address_space *aspace,
3012                                      CORE_ADDR pc)
3013 {
3014   struct bp_location *bl, **blp_tmp;
3015
3016   ALL_BP_LOCATIONS (bl, blp_tmp)
3017     {
3018       if (bl->loc_type != bp_loc_software_breakpoint)
3019         continue;
3020
3021       if (bl->inserted
3022           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3023                                        aspace, pc))
3024         {
3025           if (overlay_debugging 
3026               && section_is_overlay (bl->section)
3027               && !section_is_mapped (bl->section))
3028             continue;           /* unmapped overlay -- can't be a match */
3029           else
3030             return 1;
3031         }
3032     }
3033
3034   /* Also check for software single-step breakpoints.  */
3035   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3036     return 1;
3037
3038   return 0;
3039 }
3040
3041 int
3042 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3043                                        CORE_ADDR addr, ULONGEST len)
3044 {
3045   struct breakpoint *bpt;
3046
3047   ALL_BREAKPOINTS (bpt)
3048     {
3049       struct bp_location *loc;
3050
3051       if (bpt->type != bp_hardware_watchpoint
3052           && bpt->type != bp_access_watchpoint)
3053         continue;
3054
3055       if (!breakpoint_enabled (bpt))
3056         continue;
3057
3058       for (loc = bpt->loc; loc; loc = loc->next)
3059         if (loc->pspace->aspace == aspace && loc->inserted)
3060           {
3061             CORE_ADDR l, h;
3062
3063             /* Check for intersection.  */
3064             l = max (loc->address, addr);
3065             h = min (loc->address + loc->length, addr + len);
3066             if (l < h)
3067               return 1;
3068           }
3069     }
3070   return 0;
3071 }
3072
3073 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3074    PC is valid for process/thread PTID.  */
3075
3076 int
3077 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3078                          ptid_t ptid)
3079 {
3080   struct bp_location *bl, **blp_tmp;
3081   /* The thread and task IDs associated to PTID, computed lazily.  */
3082   int thread = -1;
3083   int task = 0;
3084   
3085   ALL_BP_LOCATIONS (bl, blp_tmp)
3086     {
3087       if (bl->loc_type != bp_loc_software_breakpoint
3088           && bl->loc_type != bp_loc_hardware_breakpoint)
3089         continue;
3090
3091       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3092       if (!breakpoint_enabled (bl->owner)
3093           && bl->owner->enable_state != bp_permanent)
3094         continue;
3095
3096       if (!breakpoint_location_address_match (bl, aspace, pc))
3097         continue;
3098
3099       if (bl->owner->thread != -1)
3100         {
3101           /* This is a thread-specific breakpoint.  Check that ptid
3102              matches that thread.  If thread hasn't been computed yet,
3103              it is now time to do so.  */
3104           if (thread == -1)
3105             thread = pid_to_thread_id (ptid);
3106           if (bl->owner->thread != thread)
3107             continue;
3108         }
3109
3110       if (bl->owner->task != 0)
3111         {
3112           /* This is a task-specific breakpoint.  Check that ptid
3113              matches that task.  If task hasn't been computed yet,
3114              it is now time to do so.  */
3115           if (task == 0)
3116             task = ada_get_task_number (ptid);
3117           if (bl->owner->task != task)
3118             continue;
3119         }
3120
3121       if (overlay_debugging 
3122           && section_is_overlay (bl->section)
3123           && !section_is_mapped (bl->section))
3124         continue;           /* unmapped overlay -- can't be a match */
3125
3126       return 1;
3127     }
3128
3129   return 0;
3130 }
3131 \f
3132
3133 /* bpstat stuff.  External routines' interfaces are documented
3134    in breakpoint.h.  */
3135
3136 int
3137 ep_is_catchpoint (struct breakpoint *ep)
3138 {
3139   return (ep->type == bp_catchpoint);
3140 }
3141
3142 /* Frees any storage that is part of a bpstat.  Does not walk the
3143    'next' chain.  */
3144
3145 static void
3146 bpstat_free (bpstat bs)
3147 {
3148   if (bs->old_val != NULL)
3149     value_free (bs->old_val);
3150   decref_counted_command_line (&bs->commands);
3151   decref_bp_location (&bs->bp_location_at);
3152   xfree (bs);
3153 }
3154
3155 /* Clear a bpstat so that it says we are not at any breakpoint.
3156    Also free any storage that is part of a bpstat.  */
3157
3158 void
3159 bpstat_clear (bpstat *bsp)
3160 {
3161   bpstat p;
3162   bpstat q;
3163
3164   if (bsp == 0)
3165     return;
3166   p = *bsp;
3167   while (p != NULL)
3168     {
3169       q = p->next;
3170       bpstat_free (p);
3171       p = q;
3172     }
3173   *bsp = NULL;
3174 }
3175
3176 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3177    is part of the bpstat is copied as well.  */
3178
3179 bpstat
3180 bpstat_copy (bpstat bs)
3181 {
3182   bpstat p = NULL;
3183   bpstat tmp;
3184   bpstat retval = NULL;
3185
3186   if (bs == NULL)
3187     return bs;
3188
3189   for (; bs != NULL; bs = bs->next)
3190     {
3191       tmp = (bpstat) xmalloc (sizeof (*tmp));
3192       memcpy (tmp, bs, sizeof (*tmp));
3193       incref_counted_command_line (tmp->commands);
3194       incref_bp_location (tmp->bp_location_at);
3195       if (bs->old_val != NULL)
3196         {
3197           tmp->old_val = value_copy (bs->old_val);
3198           release_value (tmp->old_val);
3199         }
3200
3201       if (p == NULL)
3202         /* This is the first thing in the chain.  */
3203         retval = tmp;
3204       else
3205         p->next = tmp;
3206       p = tmp;
3207     }
3208   p->next = NULL;
3209   return retval;
3210 }
3211
3212 /* Find the bpstat associated with this breakpoint.  */
3213
3214 bpstat
3215 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3216 {
3217   if (bsp == NULL)
3218     return NULL;
3219
3220   for (; bsp != NULL; bsp = bsp->next)
3221     {
3222       if (bsp->breakpoint_at == breakpoint)
3223         return bsp;
3224     }
3225   return NULL;
3226 }
3227
3228 /* Put in *NUM the breakpoint number of the first breakpoint we are
3229    stopped at.  *BSP upon return is a bpstat which points to the
3230    remaining breakpoints stopped at (but which is not guaranteed to be
3231    good for anything but further calls to bpstat_num).
3232
3233    Return 0 if passed a bpstat which does not indicate any breakpoints.
3234    Return -1 if stopped at a breakpoint that has been deleted since
3235    we set it.
3236    Return 1 otherwise.  */
3237
3238 int
3239 bpstat_num (bpstat *bsp, int *num)
3240 {
3241   struct breakpoint *b;
3242
3243   if ((*bsp) == NULL)
3244     return 0;                   /* No more breakpoint values */
3245
3246   /* We assume we'll never have several bpstats that correspond to a
3247      single breakpoint -- otherwise, this function might return the
3248      same number more than once and this will look ugly.  */
3249   b = (*bsp)->breakpoint_at;
3250   *bsp = (*bsp)->next;
3251   if (b == NULL)
3252     return -1;                  /* breakpoint that's been deleted since */
3253
3254   *num = b->number;             /* We have its number */
3255   return 1;
3256 }
3257
3258 /* See breakpoint.h.  */
3259
3260 void
3261 bpstat_clear_actions (void)
3262 {
3263   struct thread_info *tp;
3264   bpstat bs;
3265
3266   if (ptid_equal (inferior_ptid, null_ptid))
3267     return;
3268
3269   tp = find_thread_ptid (inferior_ptid);
3270   if (tp == NULL)
3271     return;
3272
3273   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3274     {
3275       decref_counted_command_line (&bs->commands);
3276
3277       if (bs->old_val != NULL)
3278         {
3279           value_free (bs->old_val);
3280           bs->old_val = NULL;
3281         }
3282     }
3283 }
3284
3285 /* Called when a command is about to proceed the inferior.  */
3286
3287 static void
3288 breakpoint_about_to_proceed (void)
3289 {
3290   if (!ptid_equal (inferior_ptid, null_ptid))
3291     {
3292       struct thread_info *tp = inferior_thread ();
3293
3294       /* Allow inferior function calls in breakpoint commands to not
3295          interrupt the command list.  When the call finishes
3296          successfully, the inferior will be standing at the same
3297          breakpoint as if nothing happened.  */
3298       if (tp->control.in_infcall)
3299         return;
3300     }
3301
3302   breakpoint_proceeded = 1;
3303 }
3304
3305 /* Stub for cleaning up our state if we error-out of a breakpoint
3306    command.  */
3307 static void
3308 cleanup_executing_breakpoints (void *ignore)
3309 {
3310   executing_breakpoint_commands = 0;
3311 }
3312
3313 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3314    or its equivalent.  */
3315
3316 static int
3317 command_line_is_silent (struct command_line *cmd)
3318 {
3319   return cmd && (strcmp ("silent", cmd->line) == 0
3320                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3321 }
3322
3323 /* Execute all the commands associated with all the breakpoints at
3324    this location.  Any of these commands could cause the process to
3325    proceed beyond this point, etc.  We look out for such changes by
3326    checking the global "breakpoint_proceeded" after each command.
3327
3328    Returns true if a breakpoint command resumed the inferior.  In that
3329    case, it is the caller's responsibility to recall it again with the
3330    bpstat of the current thread.  */
3331
3332 static int
3333 bpstat_do_actions_1 (bpstat *bsp)
3334 {
3335   bpstat bs;
3336   struct cleanup *old_chain;
3337   int again = 0;
3338
3339   /* Avoid endless recursion if a `source' command is contained
3340      in bs->commands.  */
3341   if (executing_breakpoint_commands)
3342     return 0;
3343
3344   executing_breakpoint_commands = 1;
3345   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3346
3347   prevent_dont_repeat ();
3348
3349   /* This pointer will iterate over the list of bpstat's.  */
3350   bs = *bsp;
3351
3352   breakpoint_proceeded = 0;
3353   for (; bs != NULL; bs = bs->next)
3354     {
3355       struct counted_command_line *ccmd;
3356       struct command_line *cmd;
3357       struct cleanup *this_cmd_tree_chain;
3358
3359       /* Take ownership of the BSP's command tree, if it has one.
3360
3361          The command tree could legitimately contain commands like
3362          'step' and 'next', which call clear_proceed_status, which
3363          frees stop_bpstat's command tree.  To make sure this doesn't
3364          free the tree we're executing out from under us, we need to
3365          take ownership of the tree ourselves.  Since a given bpstat's
3366          commands are only executed once, we don't need to copy it; we
3367          can clear the pointer in the bpstat, and make sure we free
3368          the tree when we're done.  */
3369       ccmd = bs->commands;
3370       bs->commands = NULL;
3371       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3372       cmd = ccmd ? ccmd->commands : NULL;
3373       if (command_line_is_silent (cmd))
3374         {
3375           /* The action has been already done by bpstat_stop_status.  */
3376           cmd = cmd->next;
3377         }
3378
3379       while (cmd != NULL)
3380         {
3381           execute_control_command (cmd);
3382
3383           if (breakpoint_proceeded)
3384             break;
3385           else
3386             cmd = cmd->next;
3387         }
3388
3389       /* We can free this command tree now.  */
3390       do_cleanups (this_cmd_tree_chain);
3391
3392       if (breakpoint_proceeded)
3393         {
3394           if (target_can_async_p ())
3395             /* If we are in async mode, then the target might be still
3396                running, not stopped at any breakpoint, so nothing for
3397                us to do here -- just return to the event loop.  */
3398             ;
3399           else
3400             /* In sync mode, when execute_control_command returns
3401                we're already standing on the next breakpoint.
3402                Breakpoint commands for that stop were not run, since
3403                execute_command does not run breakpoint commands --
3404                only command_line_handler does, but that one is not
3405                involved in execution of breakpoint commands.  So, we
3406                can now execute breakpoint commands.  It should be
3407                noted that making execute_command do bpstat actions is
3408                not an option -- in this case we'll have recursive
3409                invocation of bpstat for each breakpoint with a
3410                command, and can easily blow up GDB stack.  Instead, we
3411                return true, which will trigger the caller to recall us
3412                with the new stop_bpstat.  */
3413             again = 1;
3414           break;
3415         }
3416     }
3417   do_cleanups (old_chain);
3418   return again;
3419 }
3420
3421 void
3422 bpstat_do_actions (void)
3423 {
3424   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3425
3426   /* Do any commands attached to breakpoint we are stopped at.  */
3427   while (!ptid_equal (inferior_ptid, null_ptid)
3428          && target_has_execution
3429          && !is_exited (inferior_ptid)
3430          && !is_executing (inferior_ptid))
3431     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3432        and only return when it is stopped at the next breakpoint, we
3433        keep doing breakpoint actions until it returns false to
3434        indicate the inferior was not resumed.  */
3435     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3436       break;
3437
3438   discard_cleanups (cleanup_if_error);
3439 }
3440
3441 /* Print out the (old or new) value associated with a watchpoint.  */
3442
3443 static void
3444 watchpoint_value_print (struct value *val, struct ui_file *stream)
3445 {
3446   if (val == NULL)
3447     fprintf_unfiltered (stream, _("<unreadable>"));
3448   else
3449     {
3450       struct value_print_options opts;
3451       get_user_print_options (&opts);
3452       value_print (val, stream, &opts);
3453     }
3454 }
3455
3456 /* Generic routine for printing messages indicating why we
3457    stopped.  The behavior of this function depends on the value
3458    'print_it' in the bpstat structure.  Under some circumstances we
3459    may decide not to print anything here and delegate the task to
3460    normal_stop().  */
3461
3462 static enum print_stop_action
3463 print_bp_stop_message (bpstat bs)
3464 {
3465   switch (bs->print_it)
3466     {
3467     case print_it_noop:
3468       /* Nothing should be printed for this bpstat entry.  */
3469       return PRINT_UNKNOWN;
3470       break;
3471
3472     case print_it_done:
3473       /* We still want to print the frame, but we already printed the
3474          relevant messages.  */
3475       return PRINT_SRC_AND_LOC;
3476       break;
3477
3478     case print_it_normal:
3479       {
3480         struct breakpoint *b = bs->breakpoint_at;
3481
3482         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3483            which has since been deleted.  */
3484         if (b == NULL)
3485           return PRINT_UNKNOWN;
3486
3487         /* Normal case.  Call the breakpoint's print_it method.  */
3488         return b->ops->print_it (bs);
3489       }
3490       break;
3491
3492     default:
3493       internal_error (__FILE__, __LINE__,
3494                       _("print_bp_stop_message: unrecognized enum value"));
3495       break;
3496     }
3497 }
3498
3499 /* A helper function that prints a shared library stopped event.  */
3500
3501 static void
3502 print_solib_event (int is_catchpoint)
3503 {
3504   int any_deleted
3505     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
3506   int any_added
3507     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
3508
3509   if (!is_catchpoint)
3510     {
3511       if (any_added || any_deleted)
3512         ui_out_text (current_uiout,
3513                      _("Stopped due to shared library event:\n"));
3514       else
3515         ui_out_text (current_uiout,
3516                      _("Stopped due to shared library event (no "
3517                        "libraries added or removed)\n"));
3518     }
3519
3520   if (ui_out_is_mi_like_p (current_uiout))
3521     ui_out_field_string (current_uiout, "reason",
3522                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
3523
3524   if (any_deleted)
3525     {
3526       struct cleanup *cleanup;
3527       char *name;
3528       int ix;
3529
3530       ui_out_text (current_uiout, _("  Inferior unloaded "));
3531       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
3532                                                     "removed");
3533       for (ix = 0;
3534            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
3535                         ix, name);
3536            ++ix)
3537         {
3538           if (ix > 0)
3539             ui_out_text (current_uiout, "    ");
3540           ui_out_field_string (current_uiout, "library", name);
3541           ui_out_text (current_uiout, "\n");
3542         }
3543
3544       do_cleanups (cleanup);
3545     }
3546
3547   if (any_added)
3548     {
3549       struct so_list *iter;
3550       int ix;
3551       struct cleanup *cleanup;
3552
3553       ui_out_text (current_uiout, _("  Inferior loaded "));
3554       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
3555                                                     "added");
3556       for (ix = 0;
3557            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
3558                         ix, iter);
3559            ++ix)
3560         {
3561           if (ix > 0)
3562             ui_out_text (current_uiout, "    ");
3563           ui_out_field_string (current_uiout, "library", iter->so_name);
3564           ui_out_text (current_uiout, "\n");
3565         }
3566
3567       do_cleanups (cleanup);
3568     }
3569 }
3570
3571 /* Print a message indicating what happened.  This is called from
3572    normal_stop().  The input to this routine is the head of the bpstat
3573    list - a list of the eventpoints that caused this stop.  KIND is
3574    the target_waitkind for the stopping event.  This
3575    routine calls the generic print routine for printing a message
3576    about reasons for stopping.  This will print (for example) the
3577    "Breakpoint n," part of the output.  The return value of this
3578    routine is one of:
3579
3580    PRINT_UNKNOWN: Means we printed nothing.
3581    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
3582    code to print the location.  An example is 
3583    "Breakpoint 1, " which should be followed by
3584    the location.
3585    PRINT_SRC_ONLY: Means we printed something, but there is no need
3586    to also print the location part of the message.
3587    An example is the catch/throw messages, which
3588    don't require a location appended to the end.
3589    PRINT_NOTHING: We have done some printing and we don't need any 
3590    further info to be printed.  */
3591
3592 enum print_stop_action
3593 bpstat_print (bpstat bs, int kind)
3594 {
3595   int val;
3596
3597   /* Maybe another breakpoint in the chain caused us to stop.
3598      (Currently all watchpoints go on the bpstat whether hit or not.
3599      That probably could (should) be changed, provided care is taken
3600      with respect to bpstat_explains_signal).  */
3601   for (; bs; bs = bs->next)
3602     {
3603       val = print_bp_stop_message (bs);
3604       if (val == PRINT_SRC_ONLY 
3605           || val == PRINT_SRC_AND_LOC 
3606           || val == PRINT_NOTHING)
3607         return val;
3608     }
3609
3610   /* If we had hit a shared library event breakpoint,
3611      print_bp_stop_message would print out this message.  If we hit an
3612      OS-level shared library event, do the same thing.  */
3613   if (kind == TARGET_WAITKIND_LOADED)
3614     {
3615       print_solib_event (0);
3616       return PRINT_NOTHING;
3617     }
3618
3619   /* We reached the end of the chain, or we got a null BS to start
3620      with and nothing was printed.  */
3621   return PRINT_UNKNOWN;
3622 }
3623
3624 /* Evaluate the expression EXP and return 1 if value is zero.  This is
3625    used inside a catch_errors to evaluate the breakpoint condition.
3626    The argument is a "struct expression *" that has been cast to a
3627    "char *" to make it pass through catch_errors.  */
3628
3629 static int
3630 breakpoint_cond_eval (void *exp)
3631 {
3632   struct value *mark = value_mark ();
3633   int i = !value_true (evaluate_expression ((struct expression *) exp));
3634
3635   value_free_to_mark (mark);
3636   return i;
3637 }
3638
3639 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
3640
3641 static bpstat
3642 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
3643 {
3644   bpstat bs;
3645
3646   bs = (bpstat) xmalloc (sizeof (*bs));
3647   bs->next = NULL;
3648   **bs_link_pointer = bs;
3649   *bs_link_pointer = &bs->next;
3650   bs->breakpoint_at = bl->owner;
3651   bs->bp_location_at = bl;
3652   incref_bp_location (bl);
3653   /* If the condition is false, etc., don't do the commands.  */
3654   bs->commands = NULL;
3655   bs->old_val = NULL;
3656   bs->print_it = print_it_normal;
3657   return bs;
3658 }
3659 \f
3660 /* The target has stopped with waitstatus WS.  Check if any hardware
3661    watchpoints have triggered, according to the target.  */
3662
3663 int
3664 watchpoints_triggered (struct target_waitstatus *ws)
3665 {
3666   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
3667   CORE_ADDR addr;
3668   struct breakpoint *b;
3669
3670   if (!stopped_by_watchpoint)
3671     {
3672       /* We were not stopped by a watchpoint.  Mark all watchpoints
3673          as not triggered.  */
3674       ALL_BREAKPOINTS (b)
3675         if (is_hardware_watchpoint (b))
3676           {
3677             struct watchpoint *w = (struct watchpoint *) b;
3678
3679             w->watchpoint_triggered = watch_triggered_no;
3680           }
3681
3682       return 0;
3683     }
3684
3685   if (!target_stopped_data_address (&current_target, &addr))
3686     {
3687       /* We were stopped by a watchpoint, but we don't know where.
3688          Mark all watchpoints as unknown.  */
3689       ALL_BREAKPOINTS (b)
3690         if (is_hardware_watchpoint (b))
3691           {
3692             struct watchpoint *w = (struct watchpoint *) b;
3693
3694             w->watchpoint_triggered = watch_triggered_unknown;
3695           }
3696
3697       return stopped_by_watchpoint;
3698     }
3699
3700   /* The target could report the data address.  Mark watchpoints
3701      affected by this data address as triggered, and all others as not
3702      triggered.  */
3703
3704   ALL_BREAKPOINTS (b)
3705     if (is_hardware_watchpoint (b))
3706       {
3707         struct watchpoint *w = (struct watchpoint *) b;
3708         struct bp_location *loc;
3709
3710         w->watchpoint_triggered = watch_triggered_no;
3711         for (loc = b->loc; loc; loc = loc->next)
3712           {
3713             if (is_masked_watchpoint (b))
3714               {
3715                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
3716                 CORE_ADDR start = loc->address & w->hw_wp_mask;
3717
3718                 if (newaddr == start)
3719                   {
3720                     w->watchpoint_triggered = watch_triggered_yes;
3721                     break;
3722                   }
3723               }
3724             /* Exact match not required.  Within range is sufficient.  */
3725             else if (target_watchpoint_addr_within_range (&current_target,
3726                                                          addr, loc->address,
3727                                                          loc->length))
3728               {
3729                 w->watchpoint_triggered = watch_triggered_yes;
3730                 break;
3731               }
3732           }
3733       }
3734
3735   return 1;
3736 }
3737
3738 /* Possible return values for watchpoint_check (this can't be an enum
3739    because of check_errors).  */
3740 /* The watchpoint has been deleted.  */
3741 #define WP_DELETED 1
3742 /* The value has changed.  */
3743 #define WP_VALUE_CHANGED 2
3744 /* The value has not changed.  */
3745 #define WP_VALUE_NOT_CHANGED 3
3746 /* Ignore this watchpoint, no matter if the value changed or not.  */
3747 #define WP_IGNORE 4
3748
3749 #define BP_TEMPFLAG 1
3750 #define BP_HARDWAREFLAG 2
3751
3752 /* Evaluate watchpoint condition expression and check if its value
3753    changed.
3754
3755    P should be a pointer to struct bpstat, but is defined as a void *
3756    in order for this function to be usable with catch_errors.  */
3757
3758 static int
3759 watchpoint_check (void *p)
3760 {
3761   bpstat bs = (bpstat) p;
3762   struct watchpoint *b;
3763   struct frame_info *fr;
3764   int within_current_scope;
3765
3766   /* BS is built from an existing struct breakpoint.  */
3767   gdb_assert (bs->breakpoint_at != NULL);
3768   b = (struct watchpoint *) bs->breakpoint_at;
3769
3770   /* If this is a local watchpoint, we only want to check if the
3771      watchpoint frame is in scope if the current thread is the thread
3772      that was used to create the watchpoint.  */
3773   if (!watchpoint_in_thread_scope (b))
3774     return WP_IGNORE;
3775
3776   if (b->exp_valid_block == NULL)
3777     within_current_scope = 1;
3778   else
3779     {
3780       struct frame_info *frame = get_current_frame ();
3781       struct gdbarch *frame_arch = get_frame_arch (frame);
3782       CORE_ADDR frame_pc = get_frame_pc (frame);
3783
3784       /* in_function_epilogue_p() returns a non-zero value if we're
3785          still in the function but the stack frame has already been
3786          invalidated.  Since we can't rely on the values of local
3787          variables after the stack has been destroyed, we are treating
3788          the watchpoint in that state as `not changed' without further
3789          checking.  Don't mark watchpoints as changed if the current
3790          frame is in an epilogue - even if they are in some other
3791          frame, our view of the stack is likely to be wrong and
3792          frame_find_by_id could error out.  */
3793       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
3794         return WP_IGNORE;
3795
3796       fr = frame_find_by_id (b->watchpoint_frame);
3797       within_current_scope = (fr != NULL);
3798
3799       /* If we've gotten confused in the unwinder, we might have
3800          returned a frame that can't describe this variable.  */
3801       if (within_current_scope)
3802         {
3803           struct symbol *function;
3804
3805           function = get_frame_function (fr);
3806           if (function == NULL
3807               || !contained_in (b->exp_valid_block,
3808                                 SYMBOL_BLOCK_VALUE (function)))
3809             within_current_scope = 0;
3810         }
3811
3812       if (within_current_scope)
3813         /* If we end up stopping, the current frame will get selected
3814            in normal_stop.  So this call to select_frame won't affect
3815            the user.  */
3816         select_frame (fr);
3817     }
3818
3819   if (within_current_scope)
3820     {
3821       /* We use value_{,free_to_}mark because it could be a *long*
3822          time before we return to the command level and call
3823          free_all_values.  We can't call free_all_values because we
3824          might be in the middle of evaluating a function call.  */
3825
3826       int pc = 0;
3827       struct value *mark;
3828       struct value *new_val;
3829
3830       if (is_masked_watchpoint (&b->base))
3831         /* Since we don't know the exact trigger address (from
3832            stopped_data_address), just tell the user we've triggered
3833            a mask watchpoint.  */
3834         return WP_VALUE_CHANGED;
3835
3836       mark = value_mark ();
3837       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
3838
3839       /* We use value_equal_contents instead of value_equal because
3840          the latter coerces an array to a pointer, thus comparing just
3841          the address of the array instead of its contents.  This is
3842          not what we want.  */
3843       if ((b->val != NULL) != (new_val != NULL)
3844           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
3845         {
3846           if (new_val != NULL)
3847             {
3848               release_value (new_val);
3849               value_free_to_mark (mark);
3850             }
3851           bs->old_val = b->val;
3852           b->val = new_val;
3853           b->val_valid = 1;
3854           return WP_VALUE_CHANGED;
3855         }
3856       else
3857         {
3858           /* Nothing changed.  */
3859           value_free_to_mark (mark);
3860           return WP_VALUE_NOT_CHANGED;
3861         }
3862     }
3863   else
3864     {
3865       struct ui_out *uiout = current_uiout;
3866
3867       /* This seems like the only logical thing to do because
3868          if we temporarily ignored the watchpoint, then when
3869          we reenter the block in which it is valid it contains
3870          garbage (in the case of a function, it may have two
3871          garbage values, one before and one after the prologue).
3872          So we can't even detect the first assignment to it and
3873          watch after that (since the garbage may or may not equal
3874          the first value assigned).  */
3875       /* We print all the stop information in
3876          breakpoint_ops->print_it, but in this case, by the time we
3877          call breakpoint_ops->print_it this bp will be deleted
3878          already.  So we have no choice but print the information
3879          here.  */
3880       if (ui_out_is_mi_like_p (uiout))
3881         ui_out_field_string
3882           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
3883       ui_out_text (uiout, "\nWatchpoint ");
3884       ui_out_field_int (uiout, "wpnum", b->base.number);
3885       ui_out_text (uiout,
3886                    " deleted because the program has left the block in\n\
3887 which its expression is valid.\n");     
3888
3889       /* Make sure the watchpoint's commands aren't executed.  */
3890       decref_counted_command_line (&b->base.commands);
3891       watchpoint_del_at_next_stop (b);
3892
3893       return WP_DELETED;
3894     }
3895 }
3896
3897 /* Return true if it looks like target has stopped due to hitting
3898    breakpoint location BL.  This function does not check if we should
3899    stop, only if BL explains the stop.  */
3900
3901 static int
3902 bpstat_check_location (const struct bp_location *bl,
3903                        struct address_space *aspace, CORE_ADDR bp_addr,
3904                        const struct target_waitstatus *ws)
3905 {
3906   struct breakpoint *b = bl->owner;
3907
3908   /* BL is from an existing breakpoint.  */
3909   gdb_assert (b != NULL);
3910
3911   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
3912 }
3913
3914 /* Determine if the watched values have actually changed, and we
3915    should stop.  If not, set BS->stop to 0.  */
3916
3917 static void
3918 bpstat_check_watchpoint (bpstat bs)
3919 {
3920   const struct bp_location *bl;
3921   struct watchpoint *b;
3922
3923   /* BS is built for existing struct breakpoint.  */
3924   bl = bs->bp_location_at;
3925   gdb_assert (bl != NULL);
3926   b = (struct watchpoint *) bs->breakpoint_at;
3927   gdb_assert (b != NULL);
3928
3929     {
3930       int must_check_value = 0;
3931       
3932       if (b->base.type == bp_watchpoint)
3933         /* For a software watchpoint, we must always check the
3934            watched value.  */
3935         must_check_value = 1;
3936       else if (b->watchpoint_triggered == watch_triggered_yes)
3937         /* We have a hardware watchpoint (read, write, or access)
3938            and the target earlier reported an address watched by
3939            this watchpoint.  */
3940         must_check_value = 1;
3941       else if (b->watchpoint_triggered == watch_triggered_unknown
3942                && b->base.type == bp_hardware_watchpoint)
3943         /* We were stopped by a hardware watchpoint, but the target could
3944            not report the data address.  We must check the watchpoint's
3945            value.  Access and read watchpoints are out of luck; without
3946            a data address, we can't figure it out.  */
3947         must_check_value = 1;
3948
3949       if (must_check_value)
3950         {
3951           char *message
3952             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
3953                           b->base.number);
3954           struct cleanup *cleanups = make_cleanup (xfree, message);
3955           int e = catch_errors (watchpoint_check, bs, message,
3956                                 RETURN_MASK_ALL);
3957           do_cleanups (cleanups);
3958           switch (e)
3959             {
3960             case WP_DELETED:
3961               /* We've already printed what needs to be printed.  */
3962               bs->print_it = print_it_done;
3963               /* Stop.  */
3964               break;
3965             case WP_IGNORE:
3966               bs->print_it = print_it_noop;
3967               bs->stop = 0;
3968               break;
3969             case WP_VALUE_CHANGED:
3970               if (b->base.type == bp_read_watchpoint)
3971                 {
3972                   /* There are two cases to consider here:
3973
3974                      1. We're watching the triggered memory for reads.
3975                      In that case, trust the target, and always report
3976                      the watchpoint hit to the user.  Even though
3977                      reads don't cause value changes, the value may
3978                      have changed since the last time it was read, and
3979                      since we're not trapping writes, we will not see
3980                      those, and as such we should ignore our notion of
3981                      old value.
3982
3983                      2. We're watching the triggered memory for both
3984                      reads and writes.  There are two ways this may
3985                      happen:
3986
3987                      2.1. This is a target that can't break on data
3988                      reads only, but can break on accesses (reads or
3989                      writes), such as e.g., x86.  We detect this case
3990                      at the time we try to insert read watchpoints.
3991
3992                      2.2. Otherwise, the target supports read
3993                      watchpoints, but, the user set an access or write
3994                      watchpoint watching the same memory as this read
3995                      watchpoint.
3996
3997                      If we're watching memory writes as well as reads,
3998                      ignore watchpoint hits when we find that the
3999                      value hasn't changed, as reads don't cause
4000                      changes.  This still gives false positives when
4001                      the program writes the same value to memory as
4002                      what there was already in memory (we will confuse
4003                      it for a read), but it's much better than
4004                      nothing.  */
4005
4006                   int other_write_watchpoint = 0;
4007
4008                   if (bl->watchpoint_type == hw_read)
4009                     {
4010                       struct breakpoint *other_b;
4011
4012                       ALL_BREAKPOINTS (other_b)
4013                         if (other_b->type == bp_hardware_watchpoint
4014                             || other_b->type == bp_access_watchpoint)
4015                           {
4016                             struct watchpoint *other_w =
4017                               (struct watchpoint *) other_b;
4018
4019                             if (other_w->watchpoint_triggered
4020                                 == watch_triggered_yes)
4021                               {
4022                                 other_write_watchpoint = 1;
4023                                 break;
4024                               }
4025                           }
4026                     }
4027
4028                   if (other_write_watchpoint
4029                       || bl->watchpoint_type == hw_access)
4030                     {
4031                       /* We're watching the same memory for writes,
4032                          and the value changed since the last time we
4033                          updated it, so this trap must be for a write.
4034                          Ignore it.  */
4035                       bs->print_it = print_it_noop;
4036                       bs->stop = 0;
4037                     }
4038                 }
4039               break;
4040             case WP_VALUE_NOT_CHANGED:
4041               if (b->base.type == bp_hardware_watchpoint
4042                   || b->base.type == bp_watchpoint)
4043                 {
4044                   /* Don't stop: write watchpoints shouldn't fire if
4045                      the value hasn't changed.  */
4046                   bs->print_it = print_it_noop;
4047                   bs->stop = 0;
4048                 }
4049               /* Stop.  */
4050               break;
4051             default:
4052               /* Can't happen.  */
4053             case 0:
4054               /* Error from catch_errors.  */
4055               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4056               watchpoint_del_at_next_stop (b);
4057               /* We've already printed what needs to be printed.  */
4058               bs->print_it = print_it_done;
4059               break;
4060             }
4061         }
4062       else      /* must_check_value == 0 */
4063         {
4064           /* This is a case where some watchpoint(s) triggered, but
4065              not at the address of this watchpoint, or else no
4066              watchpoint triggered after all.  So don't print
4067              anything for this watchpoint.  */
4068           bs->print_it = print_it_noop;
4069           bs->stop = 0;
4070         }
4071     }
4072 }
4073
4074
4075 /* Check conditions (condition proper, frame, thread and ignore count)
4076    of breakpoint referred to by BS.  If we should not stop for this
4077    breakpoint, set BS->stop to 0.  */
4078
4079 static void
4080 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4081 {
4082   int thread_id = pid_to_thread_id (ptid);
4083   const struct bp_location *bl;
4084   struct breakpoint *b;
4085
4086   /* BS is built for existing struct breakpoint.  */
4087   bl = bs->bp_location_at;
4088   gdb_assert (bl != NULL);
4089   b = bs->breakpoint_at;
4090   gdb_assert (b != NULL);
4091
4092   if (frame_id_p (b->frame_id)
4093       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4094     bs->stop = 0;
4095   else if (bs->stop)
4096     {
4097       int value_is_zero = 0;
4098       struct expression *cond;
4099
4100       /* Evaluate Python breakpoints that have a "stop"
4101          method implemented.  */
4102       if (b->py_bp_object)
4103         bs->stop = gdbpy_should_stop (b->py_bp_object);
4104
4105       if (is_watchpoint (b))
4106         {
4107           struct watchpoint *w = (struct watchpoint *) b;
4108
4109           cond = w->cond_exp;
4110         }
4111       else
4112         cond = bl->cond;
4113
4114       if (cond && b->disposition != disp_del_at_next_stop)
4115         {
4116           int within_current_scope = 1;
4117           struct watchpoint * w;
4118
4119           /* We use value_mark and value_free_to_mark because it could
4120              be a long time before we return to the command level and
4121              call free_all_values.  We can't call free_all_values
4122              because we might be in the middle of evaluating a
4123              function call.  */
4124           struct value *mark = value_mark ();
4125
4126           if (is_watchpoint (b))
4127             w = (struct watchpoint *) b;
4128           else
4129             w = NULL;
4130
4131           /* Need to select the frame, with all that implies so that
4132              the conditions will have the right context.  Because we
4133              use the frame, we will not see an inlined function's
4134              variables when we arrive at a breakpoint at the start
4135              of the inlined function; the current frame will be the
4136              call site.  */
4137           if (w == NULL || w->cond_exp_valid_block == NULL)
4138             select_frame (get_current_frame ());
4139           else
4140             {
4141               struct frame_info *frame;
4142
4143               /* For local watchpoint expressions, which particular
4144                  instance of a local is being watched matters, so we
4145                  keep track of the frame to evaluate the expression
4146                  in.  To evaluate the condition however, it doesn't
4147                  really matter which instantiation of the function
4148                  where the condition makes sense triggers the
4149                  watchpoint.  This allows an expression like "watch
4150                  global if q > 10" set in `func', catch writes to
4151                  global on all threads that call `func', or catch
4152                  writes on all recursive calls of `func' by a single
4153                  thread.  We simply always evaluate the condition in
4154                  the innermost frame that's executing where it makes
4155                  sense to evaluate the condition.  It seems
4156                  intuitive.  */
4157               frame = block_innermost_frame (w->cond_exp_valid_block);
4158               if (frame != NULL)
4159                 select_frame (frame);
4160               else
4161                 within_current_scope = 0;
4162             }
4163           if (within_current_scope)
4164             value_is_zero
4165               = catch_errors (breakpoint_cond_eval, cond,
4166                               "Error in testing breakpoint condition:\n",
4167                               RETURN_MASK_ALL);
4168           else
4169             {
4170               warning (_("Watchpoint condition cannot be tested "
4171                          "in the current scope"));
4172               /* If we failed to set the right context for this
4173                  watchpoint, unconditionally report it.  */
4174               value_is_zero = 0;
4175             }
4176           /* FIXME-someday, should give breakpoint #.  */
4177           value_free_to_mark (mark);
4178         }
4179
4180       if (cond && value_is_zero)
4181         {
4182           bs->stop = 0;
4183         }
4184       else if (b->thread != -1 && b->thread != thread_id)
4185         {
4186           bs->stop = 0;
4187         }
4188       else if (b->ignore_count > 0)
4189         {
4190           b->ignore_count--;
4191           annotate_ignore_count_change ();
4192           bs->stop = 0;
4193           /* Increase the hit count even though we don't stop.  */
4194           ++(b->hit_count);
4195           observer_notify_breakpoint_modified (b);
4196         }       
4197     }
4198 }
4199
4200
4201 /* Get a bpstat associated with having just stopped at address
4202    BP_ADDR in thread PTID.
4203
4204    Determine whether we stopped at a breakpoint, etc, or whether we
4205    don't understand this stop.  Result is a chain of bpstat's such
4206    that:
4207
4208    if we don't understand the stop, the result is a null pointer.
4209
4210    if we understand why we stopped, the result is not null.
4211
4212    Each element of the chain refers to a particular breakpoint or
4213    watchpoint at which we have stopped.  (We may have stopped for
4214    several reasons concurrently.)
4215
4216    Each element of the chain has valid next, breakpoint_at,
4217    commands, FIXME??? fields.  */
4218
4219 bpstat
4220 bpstat_stop_status (struct address_space *aspace,
4221                     CORE_ADDR bp_addr, ptid_t ptid,
4222                     const struct target_waitstatus *ws)
4223 {
4224   struct breakpoint *b = NULL;
4225   struct bp_location *bl;
4226   struct bp_location *loc;
4227   /* First item of allocated bpstat's.  */
4228   bpstat bs_head = NULL, *bs_link = &bs_head;
4229   /* Pointer to the last thing in the chain currently.  */
4230   bpstat bs;
4231   int ix;
4232   int need_remove_insert;
4233   int removed_any;
4234
4235   /* First, build the bpstat chain with locations that explain a
4236      target stop, while being careful to not set the target running,
4237      as that may invalidate locations (in particular watchpoint
4238      locations are recreated).  Resuming will happen here with
4239      breakpoint conditions or watchpoint expressions that include
4240      inferior function calls.  */
4241
4242   ALL_BREAKPOINTS (b)
4243     {
4244       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4245         continue;
4246
4247       for (bl = b->loc; bl != NULL; bl = bl->next)
4248         {
4249           /* For hardware watchpoints, we look only at the first
4250              location.  The watchpoint_check function will work on the
4251              entire expression, not the individual locations.  For
4252              read watchpoints, the watchpoints_triggered function has
4253              checked all locations already.  */
4254           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4255             break;
4256
4257           if (bl->shlib_disabled)
4258             continue;
4259
4260           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4261             continue;
4262
4263           /* Come here if it's a watchpoint, or if the break address
4264              matches.  */
4265
4266           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4267                                                    explain stop.  */
4268
4269           /* Assume we stop.  Should we find a watchpoint that is not
4270              actually triggered, or if the condition of the breakpoint
4271              evaluates as false, we'll reset 'stop' to 0.  */
4272           bs->stop = 1;
4273           bs->print = 1;
4274
4275           /* If this is a scope breakpoint, mark the associated
4276              watchpoint as triggered so that we will handle the
4277              out-of-scope event.  We'll get to the watchpoint next
4278              iteration.  */
4279           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4280             {
4281               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4282
4283               w->watchpoint_triggered = watch_triggered_yes;
4284             }
4285         }
4286     }
4287
4288   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4289     {
4290       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4291         {
4292           bs = bpstat_alloc (loc, &bs_link);
4293           /* For hits of moribund locations, we should just proceed.  */
4294           bs->stop = 0;
4295           bs->print = 0;
4296           bs->print_it = print_it_noop;
4297         }
4298     }
4299
4300   /* A bit of special processing for shlib breakpoints.  We need to
4301      process solib loading here, so that the lists of loaded and
4302      unloaded libraries are correct before we handle "catch load" and
4303      "catch unload".  */
4304   for (bs = bs_head; bs != NULL; bs = bs->next)
4305     {
4306       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4307         {
4308           handle_solib_event ();
4309           break;
4310         }
4311     }
4312
4313   /* Now go through the locations that caused the target to stop, and
4314      check whether we're interested in reporting this stop to higher
4315      layers, or whether we should resume the target transparently.  */
4316
4317   removed_any = 0;
4318
4319   for (bs = bs_head; bs != NULL; bs = bs->next)
4320     {
4321       if (!bs->stop)
4322         continue;
4323
4324       b = bs->breakpoint_at;
4325       b->ops->check_status (bs);
4326       if (bs->stop)
4327         {
4328           bpstat_check_breakpoint_conditions (bs, ptid);
4329
4330           if (bs->stop)
4331             {
4332               ++(b->hit_count);
4333               observer_notify_breakpoint_modified (b);
4334
4335               /* We will stop here.  */
4336               if (b->disposition == disp_disable)
4337                 {
4338                   if (b->enable_state != bp_permanent)
4339                     b->enable_state = bp_disabled;
4340                   removed_any = 1;
4341                 }
4342               if (b->silent)
4343                 bs->print = 0;
4344               bs->commands = b->commands;
4345               incref_counted_command_line (bs->commands);
4346               if (command_line_is_silent (bs->commands
4347                                           ? bs->commands->commands : NULL))
4348                 bs->print = 0;
4349             }
4350
4351         }
4352
4353       /* Print nothing for this entry if we don't stop or don't
4354          print.  */
4355       if (!bs->stop || !bs->print)
4356         bs->print_it = print_it_noop;
4357     }
4358
4359   /* If we aren't stopping, the value of some hardware watchpoint may
4360      not have changed, but the intermediate memory locations we are
4361      watching may have.  Don't bother if we're stopping; this will get
4362      done later.  */
4363   need_remove_insert = 0;
4364   if (! bpstat_causes_stop (bs_head))
4365     for (bs = bs_head; bs != NULL; bs = bs->next)
4366       if (!bs->stop
4367           && bs->breakpoint_at
4368           && is_hardware_watchpoint (bs->breakpoint_at))
4369         {
4370           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4371
4372           update_watchpoint (w, 0 /* don't reparse.  */);
4373           need_remove_insert = 1;
4374         }
4375
4376   if (need_remove_insert)
4377     update_global_location_list (1);
4378   else if (removed_any)
4379     update_global_location_list (0);
4380
4381   return bs_head;
4382 }
4383
4384 static void
4385 handle_jit_event (void)
4386 {
4387   struct frame_info *frame;
4388   struct gdbarch *gdbarch;
4389
4390   /* Switch terminal for any messages produced by
4391      breakpoint_re_set.  */
4392   target_terminal_ours_for_output ();
4393
4394   frame = get_current_frame ();
4395   gdbarch = get_frame_arch (frame);
4396
4397   jit_event_handler (gdbarch);
4398
4399   target_terminal_inferior ();
4400 }
4401
4402 /* Handle an solib event by calling solib_add.  */
4403
4404 void
4405 handle_solib_event (void)
4406 {
4407   clear_program_space_solib_cache (current_inferior ()->pspace);
4408
4409   /* Check for any newly added shared libraries if we're supposed to
4410      be adding them automatically.  Switch terminal for any messages
4411      produced by breakpoint_re_set.  */
4412   target_terminal_ours_for_output ();
4413 #ifdef SOLIB_ADD
4414   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4415 #else
4416   solib_add (NULL, 0, &current_target, auto_solib_add);
4417 #endif
4418   target_terminal_inferior ();
4419 }
4420
4421 /* Prepare WHAT final decision for infrun.  */
4422
4423 /* Decide what infrun needs to do with this bpstat.  */
4424
4425 struct bpstat_what
4426 bpstat_what (bpstat bs_head)
4427 {
4428   struct bpstat_what retval;
4429   int jit_event = 0;
4430   bpstat bs;
4431
4432   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4433   retval.call_dummy = STOP_NONE;
4434   retval.is_longjmp = 0;
4435
4436   for (bs = bs_head; bs != NULL; bs = bs->next)
4437     {
4438       /* Extract this BS's action.  After processing each BS, we check
4439          if its action overrides all we've seem so far.  */
4440       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4441       enum bptype bptype;
4442
4443       if (bs->breakpoint_at == NULL)
4444         {
4445           /* I suspect this can happen if it was a momentary
4446              breakpoint which has since been deleted.  */
4447           bptype = bp_none;
4448         }
4449       else
4450         bptype = bs->breakpoint_at->type;
4451
4452       switch (bptype)
4453         {
4454         case bp_none:
4455           break;
4456         case bp_breakpoint:
4457         case bp_hardware_breakpoint:
4458         case bp_until:
4459         case bp_finish:
4460         case bp_shlib_event:
4461           if (bs->stop)
4462             {
4463               if (bs->print)
4464                 this_action = BPSTAT_WHAT_STOP_NOISY;
4465               else
4466                 this_action = BPSTAT_WHAT_STOP_SILENT;
4467             }
4468           else
4469             this_action = BPSTAT_WHAT_SINGLE;
4470           break;
4471         case bp_watchpoint:
4472         case bp_hardware_watchpoint:
4473         case bp_read_watchpoint:
4474         case bp_access_watchpoint:
4475           if (bs->stop)
4476             {
4477               if (bs->print)
4478                 this_action = BPSTAT_WHAT_STOP_NOISY;
4479               else
4480                 this_action = BPSTAT_WHAT_STOP_SILENT;
4481             }
4482           else
4483             {
4484               /* There was a watchpoint, but we're not stopping.
4485                  This requires no further action.  */
4486             }
4487           break;
4488         case bp_longjmp:
4489         case bp_exception:
4490           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
4491           retval.is_longjmp = bptype == bp_longjmp;
4492           break;
4493         case bp_longjmp_resume:
4494         case bp_exception_resume:
4495           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
4496           retval.is_longjmp = bptype == bp_longjmp_resume;
4497           break;
4498         case bp_step_resume:
4499           if (bs->stop)
4500             this_action = BPSTAT_WHAT_STEP_RESUME;
4501           else
4502             {
4503               /* It is for the wrong frame.  */
4504               this_action = BPSTAT_WHAT_SINGLE;
4505             }
4506           break;
4507         case bp_hp_step_resume:
4508           if (bs->stop)
4509             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
4510           else
4511             {
4512               /* It is for the wrong frame.  */
4513               this_action = BPSTAT_WHAT_SINGLE;
4514             }
4515           break;
4516         case bp_watchpoint_scope:
4517         case bp_thread_event:
4518         case bp_overlay_event:
4519         case bp_longjmp_master:
4520         case bp_std_terminate_master:
4521         case bp_exception_master:
4522           this_action = BPSTAT_WHAT_SINGLE;
4523           break;
4524         case bp_catchpoint:
4525           if (bs->stop)
4526             {
4527               if (bs->print)
4528                 this_action = BPSTAT_WHAT_STOP_NOISY;
4529               else
4530                 this_action = BPSTAT_WHAT_STOP_SILENT;
4531             }
4532           else
4533             {
4534               /* There was a catchpoint, but we're not stopping.
4535                  This requires no further action.  */
4536             }
4537           break;
4538         case bp_jit_event:
4539           jit_event = 1;
4540           this_action = BPSTAT_WHAT_SINGLE;
4541           break;
4542         case bp_call_dummy:
4543           /* Make sure the action is stop (silent or noisy),
4544              so infrun.c pops the dummy frame.  */
4545           retval.call_dummy = STOP_STACK_DUMMY;
4546           this_action = BPSTAT_WHAT_STOP_SILENT;
4547           break;
4548         case bp_std_terminate:
4549           /* Make sure the action is stop (silent or noisy),
4550              so infrun.c pops the dummy frame.  */
4551           retval.call_dummy = STOP_STD_TERMINATE;
4552           this_action = BPSTAT_WHAT_STOP_SILENT;
4553           break;
4554         case bp_tracepoint:
4555         case bp_fast_tracepoint:
4556         case bp_static_tracepoint:
4557           /* Tracepoint hits should not be reported back to GDB, and
4558              if one got through somehow, it should have been filtered
4559              out already.  */
4560           internal_error (__FILE__, __LINE__,
4561                           _("bpstat_what: tracepoint encountered"));
4562           break;
4563         case bp_gnu_ifunc_resolver:
4564           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
4565           this_action = BPSTAT_WHAT_SINGLE;
4566           break;
4567         case bp_gnu_ifunc_resolver_return:
4568           /* The breakpoint will be removed, execution will restart from the
4569              PC of the former breakpoint.  */
4570           this_action = BPSTAT_WHAT_KEEP_CHECKING;
4571           break;
4572         default:
4573           internal_error (__FILE__, __LINE__,
4574                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
4575         }
4576
4577       retval.main_action = max (retval.main_action, this_action);
4578     }
4579
4580   /* These operations may affect the bs->breakpoint_at state so they are
4581      delayed after MAIN_ACTION is decided above.  */
4582
4583   if (jit_event)
4584     {
4585       if (debug_infrun)
4586         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
4587
4588       handle_jit_event ();
4589     }
4590
4591   for (bs = bs_head; bs != NULL; bs = bs->next)
4592     {
4593       struct breakpoint *b = bs->breakpoint_at;
4594
4595       if (b == NULL)
4596         continue;
4597       switch (b->type)
4598         {
4599         case bp_gnu_ifunc_resolver:
4600           gnu_ifunc_resolver_stop (b);
4601           break;
4602         case bp_gnu_ifunc_resolver_return:
4603           gnu_ifunc_resolver_return_stop (b);
4604           break;
4605         }
4606     }
4607
4608   return retval;
4609 }
4610
4611 /* Nonzero if we should step constantly (e.g. watchpoints on machines
4612    without hardware support).  This isn't related to a specific bpstat,
4613    just to things like whether watchpoints are set.  */
4614
4615 int
4616 bpstat_should_step (void)
4617 {
4618   struct breakpoint *b;
4619
4620   ALL_BREAKPOINTS (b)
4621     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
4622       return 1;
4623   return 0;
4624 }
4625
4626 int
4627 bpstat_causes_stop (bpstat bs)
4628 {
4629   for (; bs != NULL; bs = bs->next)
4630     if (bs->stop)
4631       return 1;
4632
4633   return 0;
4634 }
4635
4636 \f
4637
4638 /* Compute a string of spaces suitable to indent the next line
4639    so it starts at the position corresponding to the table column
4640    named COL_NAME in the currently active table of UIOUT.  */
4641
4642 static char *
4643 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
4644 {
4645   static char wrap_indent[80];
4646   int i, total_width, width, align;
4647   char *text;
4648
4649   total_width = 0;
4650   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
4651     {
4652       if (strcmp (text, col_name) == 0)
4653         {
4654           gdb_assert (total_width < sizeof wrap_indent);
4655           memset (wrap_indent, ' ', total_width);
4656           wrap_indent[total_width] = 0;
4657
4658           return wrap_indent;
4659         }
4660
4661       total_width += width + 1;
4662     }
4663
4664   return NULL;
4665 }
4666
4667 /* Print the LOC location out of the list of B->LOC locations.  */
4668
4669 static void
4670 print_breakpoint_location (struct breakpoint *b,
4671                            struct bp_location *loc)
4672 {
4673   struct ui_out *uiout = current_uiout;
4674   struct cleanup *old_chain = save_current_program_space ();
4675
4676   if (loc != NULL && loc->shlib_disabled)
4677     loc = NULL;
4678
4679   if (loc != NULL)
4680     set_current_program_space (loc->pspace);
4681
4682   if (b->display_canonical)
4683     ui_out_field_string (uiout, "what", b->addr_string);
4684   else if (loc && loc->source_file)
4685     {
4686       struct symbol *sym 
4687         = find_pc_sect_function (loc->address, loc->section);
4688       if (sym)
4689         {
4690           ui_out_text (uiout, "in ");
4691           ui_out_field_string (uiout, "func",
4692                                SYMBOL_PRINT_NAME (sym));
4693           ui_out_text (uiout, " ");
4694           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
4695           ui_out_text (uiout, "at ");
4696         }
4697       ui_out_field_string (uiout, "file", loc->source_file);
4698       ui_out_text (uiout, ":");
4699       
4700       if (ui_out_is_mi_like_p (uiout))
4701         {
4702           struct symtab_and_line sal = find_pc_line (loc->address, 0);
4703           char *fullname = symtab_to_fullname (sal.symtab);
4704           
4705           if (fullname)
4706             ui_out_field_string (uiout, "fullname", fullname);
4707         }
4708       
4709       ui_out_field_int (uiout, "line", loc->line_number);
4710     }
4711   else if (loc)
4712     {
4713       struct ui_stream *stb = ui_out_stream_new (uiout);
4714       struct cleanup *stb_chain = make_cleanup_ui_out_stream_delete (stb);
4715
4716       print_address_symbolic (loc->gdbarch, loc->address, stb->stream,
4717                               demangle, "");
4718       ui_out_field_stream (uiout, "at", stb);
4719
4720       do_cleanups (stb_chain);
4721     }
4722   else
4723     ui_out_field_string (uiout, "pending", b->addr_string);
4724
4725   do_cleanups (old_chain);
4726 }
4727
4728 static const char *
4729 bptype_string (enum bptype type)
4730 {
4731   struct ep_type_description
4732     {
4733       enum bptype type;
4734       char *description;
4735     };
4736   static struct ep_type_description bptypes[] =
4737   {
4738     {bp_none, "?deleted?"},
4739     {bp_breakpoint, "breakpoint"},
4740     {bp_hardware_breakpoint, "hw breakpoint"},
4741     {bp_until, "until"},
4742     {bp_finish, "finish"},
4743     {bp_watchpoint, "watchpoint"},
4744     {bp_hardware_watchpoint, "hw watchpoint"},
4745     {bp_read_watchpoint, "read watchpoint"},
4746     {bp_access_watchpoint, "acc watchpoint"},
4747     {bp_longjmp, "longjmp"},
4748     {bp_longjmp_resume, "longjmp resume"},
4749     {bp_exception, "exception"},
4750     {bp_exception_resume, "exception resume"},
4751     {bp_step_resume, "step resume"},
4752     {bp_hp_step_resume, "high-priority step resume"},
4753     {bp_watchpoint_scope, "watchpoint scope"},
4754     {bp_call_dummy, "call dummy"},
4755     {bp_std_terminate, "std::terminate"},
4756     {bp_shlib_event, "shlib events"},
4757     {bp_thread_event, "thread events"},
4758     {bp_overlay_event, "overlay events"},
4759     {bp_longjmp_master, "longjmp master"},
4760     {bp_std_terminate_master, "std::terminate master"},
4761     {bp_exception_master, "exception master"},
4762     {bp_catchpoint, "catchpoint"},
4763     {bp_tracepoint, "tracepoint"},
4764     {bp_fast_tracepoint, "fast tracepoint"},
4765     {bp_static_tracepoint, "static tracepoint"},
4766     {bp_jit_event, "jit events"},
4767     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
4768     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
4769   };
4770
4771   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
4772       || ((int) type != bptypes[(int) type].type))
4773     internal_error (__FILE__, __LINE__,
4774                     _("bptypes table does not describe type #%d."),
4775                     (int) type);
4776
4777   return bptypes[(int) type].description;
4778 }
4779
4780 /* Print B to gdb_stdout.  */
4781
4782 static void
4783 print_one_breakpoint_location (struct breakpoint *b,
4784                                struct bp_location *loc,
4785                                int loc_number,
4786                                struct bp_location **last_loc,
4787                                int allflag)
4788 {
4789   struct command_line *l;
4790   static char bpenables[] = "nynny";
4791
4792   struct ui_out *uiout = current_uiout;
4793   int header_of_multiple = 0;
4794   int part_of_multiple = (loc != NULL);
4795   struct value_print_options opts;
4796
4797   get_user_print_options (&opts);
4798
4799   gdb_assert (!loc || loc_number != 0);
4800   /* See comment in print_one_breakpoint concerning treatment of
4801      breakpoints with single disabled location.  */
4802   if (loc == NULL 
4803       && (b->loc != NULL 
4804           && (b->loc->next != NULL || !b->loc->enabled)))
4805     header_of_multiple = 1;
4806   if (loc == NULL)
4807     loc = b->loc;
4808
4809   annotate_record ();
4810
4811   /* 1 */
4812   annotate_field (0);
4813   if (part_of_multiple)
4814     {
4815       char *formatted;
4816       formatted = xstrprintf ("%d.%d", b->number, loc_number);
4817       ui_out_field_string (uiout, "number", formatted);
4818       xfree (formatted);
4819     }
4820   else
4821     {
4822       ui_out_field_int (uiout, "number", b->number);
4823     }
4824
4825   /* 2 */
4826   annotate_field (1);
4827   if (part_of_multiple)
4828     ui_out_field_skip (uiout, "type");
4829   else
4830     ui_out_field_string (uiout, "type", bptype_string (b->type));
4831
4832   /* 3 */
4833   annotate_field (2);
4834   if (part_of_multiple)
4835     ui_out_field_skip (uiout, "disp");
4836   else
4837     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
4838
4839
4840   /* 4 */
4841   annotate_field (3);
4842   if (part_of_multiple)
4843     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
4844   else
4845     ui_out_field_fmt (uiout, "enabled", "%c", 
4846                       bpenables[(int) b->enable_state]);
4847   ui_out_spaces (uiout, 2);
4848
4849   
4850   /* 5 and 6 */
4851   if (b->ops != NULL && b->ops->print_one != NULL)
4852     {
4853       /* Although the print_one can possibly print all locations,
4854          calling it here is not likely to get any nice result.  So,
4855          make sure there's just one location.  */
4856       gdb_assert (b->loc == NULL || b->loc->next == NULL);
4857       b->ops->print_one (b, last_loc);
4858     }
4859   else
4860     switch (b->type)
4861       {
4862       case bp_none:
4863         internal_error (__FILE__, __LINE__,
4864                         _("print_one_breakpoint: bp_none encountered\n"));
4865         break;
4866
4867       case bp_watchpoint:
4868       case bp_hardware_watchpoint:
4869       case bp_read_watchpoint:
4870       case bp_access_watchpoint:
4871         {
4872           struct watchpoint *w = (struct watchpoint *) b;
4873
4874           /* Field 4, the address, is omitted (which makes the columns
4875              not line up too nicely with the headers, but the effect
4876              is relatively readable).  */
4877           if (opts.addressprint)
4878             ui_out_field_skip (uiout, "addr");
4879           annotate_field (5);
4880           ui_out_field_string (uiout, "what", w->exp_string);
4881         }
4882         break;
4883
4884       case bp_breakpoint:
4885       case bp_hardware_breakpoint:
4886       case bp_until:
4887       case bp_finish:
4888       case bp_longjmp:
4889       case bp_longjmp_resume:
4890       case bp_exception:
4891       case bp_exception_resume:
4892       case bp_step_resume:
4893       case bp_hp_step_resume:
4894       case bp_watchpoint_scope:
4895       case bp_call_dummy:
4896       case bp_std_terminate:
4897       case bp_shlib_event:
4898       case bp_thread_event:
4899       case bp_overlay_event:
4900       case bp_longjmp_master:
4901       case bp_std_terminate_master:
4902       case bp_exception_master:
4903       case bp_tracepoint:
4904       case bp_fast_tracepoint:
4905       case bp_static_tracepoint:
4906       case bp_jit_event:
4907       case bp_gnu_ifunc_resolver:
4908       case bp_gnu_ifunc_resolver_return:
4909         if (opts.addressprint)
4910           {
4911             annotate_field (4);
4912             if (header_of_multiple)
4913               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
4914             else if (b->loc == NULL || loc->shlib_disabled)
4915               ui_out_field_string (uiout, "addr", "<PENDING>");
4916             else
4917               ui_out_field_core_addr (uiout, "addr",
4918                                       loc->gdbarch, loc->address);
4919           }
4920         annotate_field (5);
4921         if (!header_of_multiple)
4922           print_breakpoint_location (b, loc);
4923         if (b->loc)
4924           *last_loc = b->loc;
4925         break;
4926       }
4927
4928
4929   /* For backward compatibility, don't display inferiors unless there
4930      are several.  */
4931   if (loc != NULL
4932       && !header_of_multiple
4933       && (allflag
4934           || (!gdbarch_has_global_breakpoints (target_gdbarch)
4935               && (number_of_program_spaces () > 1
4936                   || number_of_inferiors () > 1)
4937               /* LOC is for existing B, it cannot be in
4938                  moribund_locations and thus having NULL OWNER.  */
4939               && loc->owner->type != bp_catchpoint)))
4940     {
4941       struct inferior *inf;
4942       int first = 1;
4943
4944       for (inf = inferior_list; inf != NULL; inf = inf->next)
4945         {
4946           if (inf->pspace == loc->pspace)
4947             {
4948               if (first)
4949                 {
4950                   first = 0;
4951                   ui_out_text (uiout, " inf ");
4952                 }
4953               else
4954                 ui_out_text (uiout, ", ");
4955               ui_out_text (uiout, plongest (inf->num));
4956             }
4957         }
4958     }
4959
4960   if (!part_of_multiple)
4961     {
4962       if (b->thread != -1)
4963         {
4964           /* FIXME: This seems to be redundant and lost here; see the
4965              "stop only in" line a little further down.  */
4966           ui_out_text (uiout, " thread ");
4967           ui_out_field_int (uiout, "thread", b->thread);
4968         }
4969       else if (b->task != 0)
4970         {
4971           ui_out_text (uiout, " task ");
4972           ui_out_field_int (uiout, "task", b->task);
4973         }
4974     }
4975
4976   ui_out_text (uiout, "\n");
4977
4978   if (!part_of_multiple)
4979     b->ops->print_one_detail (b, uiout);
4980
4981   if (part_of_multiple && frame_id_p (b->frame_id))
4982     {
4983       annotate_field (6);
4984       ui_out_text (uiout, "\tstop only in stack frame at ");
4985       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
4986          the frame ID.  */
4987       ui_out_field_core_addr (uiout, "frame",
4988                               b->gdbarch, b->frame_id.stack_addr);
4989       ui_out_text (uiout, "\n");
4990     }
4991   
4992   if (!part_of_multiple && b->cond_string)
4993     {
4994       annotate_field (7);
4995       if (is_tracepoint (b))
4996         ui_out_text (uiout, "\ttrace only if ");
4997       else
4998         ui_out_text (uiout, "\tstop only if ");
4999       ui_out_field_string (uiout, "cond", b->cond_string);
5000       ui_out_text (uiout, "\n");
5001     }
5002
5003   if (!part_of_multiple && b->thread != -1)
5004     {
5005       /* FIXME should make an annotation for this.  */
5006       ui_out_text (uiout, "\tstop only in thread ");
5007       ui_out_field_int (uiout, "thread", b->thread);
5008       ui_out_text (uiout, "\n");
5009     }
5010   
5011   if (!part_of_multiple && b->hit_count)
5012     {
5013       /* FIXME should make an annotation for this.  */
5014       if (ep_is_catchpoint (b))
5015         ui_out_text (uiout, "\tcatchpoint");
5016       else if (is_tracepoint (b))
5017         ui_out_text (uiout, "\ttracepoint");
5018       else
5019         ui_out_text (uiout, "\tbreakpoint");
5020       ui_out_text (uiout, " already hit ");
5021       ui_out_field_int (uiout, "times", b->hit_count);
5022       if (b->hit_count == 1)
5023         ui_out_text (uiout, " time\n");
5024       else
5025         ui_out_text (uiout, " times\n");
5026     }
5027   
5028   /* Output the count also if it is zero, but only if this is mi.
5029      FIXME: Should have a better test for this.  */
5030   if (ui_out_is_mi_like_p (uiout))
5031     if (!part_of_multiple && b->hit_count == 0)
5032       ui_out_field_int (uiout, "times", b->hit_count);
5033
5034   if (!part_of_multiple && b->ignore_count)
5035     {
5036       annotate_field (8);
5037       ui_out_text (uiout, "\tignore next ");
5038       ui_out_field_int (uiout, "ignore", b->ignore_count);
5039       ui_out_text (uiout, " hits\n");
5040     }
5041
5042   if (!part_of_multiple && is_tracepoint (b))
5043     {
5044       struct tracepoint *tp = (struct tracepoint *) b;
5045
5046       if (tp->traceframe_usage)
5047         {
5048           ui_out_text (uiout, "\ttrace buffer usage ");
5049           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5050           ui_out_text (uiout, " bytes\n");
5051         }
5052     }
5053   
5054   l = b->commands ? b->commands->commands : NULL;
5055   if (!part_of_multiple && l)
5056     {
5057       struct cleanup *script_chain;
5058
5059       annotate_field (9);
5060       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5061       print_command_lines (uiout, l, 4);
5062       do_cleanups (script_chain);
5063     }
5064
5065   if (is_tracepoint (b))
5066     {
5067       struct tracepoint *t = (struct tracepoint *) b;
5068
5069       if (!part_of_multiple && t->pass_count)
5070         {
5071           annotate_field (10);
5072           ui_out_text (uiout, "\tpass count ");
5073           ui_out_field_int (uiout, "pass", t->pass_count);
5074           ui_out_text (uiout, " \n");
5075         }
5076     }
5077
5078   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5079     {
5080       if (is_watchpoint (b))
5081         {
5082           struct watchpoint *w = (struct watchpoint *) b;
5083
5084           ui_out_field_string (uiout, "original-location", w->exp_string);
5085         }
5086       else if (b->addr_string)
5087         ui_out_field_string (uiout, "original-location", b->addr_string);
5088     }
5089 }
5090
5091 static void
5092 print_one_breakpoint (struct breakpoint *b,
5093                       struct bp_location **last_loc, 
5094                       int allflag)
5095 {
5096   struct cleanup *bkpt_chain;
5097   struct ui_out *uiout = current_uiout;
5098
5099   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5100
5101   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5102   do_cleanups (bkpt_chain);
5103
5104   /* If this breakpoint has custom print function,
5105      it's already printed.  Otherwise, print individual
5106      locations, if any.  */
5107   if (b->ops == NULL || b->ops->print_one == NULL)
5108     {
5109       /* If breakpoint has a single location that is disabled, we
5110          print it as if it had several locations, since otherwise it's
5111          hard to represent "breakpoint enabled, location disabled"
5112          situation.
5113
5114          Note that while hardware watchpoints have several locations
5115          internally, that's not a property exposed to user.  */
5116       if (b->loc 
5117           && !is_hardware_watchpoint (b)
5118           && (b->loc->next || !b->loc->enabled))
5119         {
5120           struct bp_location *loc;
5121           int n = 1;
5122
5123           for (loc = b->loc; loc; loc = loc->next, ++n)
5124             {
5125               struct cleanup *inner2 =
5126                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5127               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5128               do_cleanups (inner2);
5129             }
5130         }
5131     }
5132 }
5133
5134 static int
5135 breakpoint_address_bits (struct breakpoint *b)
5136 {
5137   int print_address_bits = 0;
5138   struct bp_location *loc;
5139
5140   for (loc = b->loc; loc; loc = loc->next)
5141     {
5142       int addr_bit;
5143
5144       /* Software watchpoints that aren't watching memory don't have
5145          an address to print.  */
5146       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5147         continue;
5148
5149       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5150       if (addr_bit > print_address_bits)
5151         print_address_bits = addr_bit;
5152     }
5153
5154   return print_address_bits;
5155 }
5156
5157 struct captured_breakpoint_query_args
5158   {
5159     int bnum;
5160   };
5161
5162 static int
5163 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5164 {
5165   struct captured_breakpoint_query_args *args = data;
5166   struct breakpoint *b;
5167   struct bp_location *dummy_loc = NULL;
5168
5169   ALL_BREAKPOINTS (b)
5170     {
5171       if (args->bnum == b->number)
5172         {
5173           print_one_breakpoint (b, &dummy_loc, 0);
5174           return GDB_RC_OK;
5175         }
5176     }
5177   return GDB_RC_NONE;
5178 }
5179
5180 enum gdb_rc
5181 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5182                       char **error_message)
5183 {
5184   struct captured_breakpoint_query_args args;
5185
5186   args.bnum = bnum;
5187   /* For the moment we don't trust print_one_breakpoint() to not throw
5188      an error.  */
5189   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5190                                  error_message, RETURN_MASK_ALL) < 0)
5191     return GDB_RC_FAIL;
5192   else
5193     return GDB_RC_OK;
5194 }
5195
5196 /* Return true if this breakpoint was set by the user, false if it is
5197    internal or momentary.  */
5198
5199 int
5200 user_breakpoint_p (struct breakpoint *b)
5201 {
5202   return b->number > 0;
5203 }
5204
5205 /* Print information on user settable breakpoint (watchpoint, etc)
5206    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5207    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5208    FILTER is non-NULL, call it on each breakpoint and only include the
5209    ones for which it returns non-zero.  Return the total number of
5210    breakpoints listed.  */
5211
5212 static int
5213 breakpoint_1 (char *args, int allflag, 
5214               int (*filter) (const struct breakpoint *))
5215 {
5216   struct breakpoint *b;
5217   struct bp_location *last_loc = NULL;
5218   int nr_printable_breakpoints;
5219   struct cleanup *bkpttbl_chain;
5220   struct value_print_options opts;
5221   int print_address_bits = 0;
5222   int print_type_col_width = 14;
5223   struct ui_out *uiout = current_uiout;
5224
5225   get_user_print_options (&opts);
5226
5227   /* Compute the number of rows in the table, as well as the size
5228      required for address fields.  */
5229   nr_printable_breakpoints = 0;
5230   ALL_BREAKPOINTS (b)
5231     {
5232       /* If we have a filter, only list the breakpoints it accepts.  */
5233       if (filter && !filter (b))
5234         continue;
5235
5236       /* If we have an "args" string, it is a list of breakpoints to 
5237          accept.  Skip the others.  */
5238       if (args != NULL && *args != '\0')
5239         {
5240           if (allflag && parse_and_eval_long (args) != b->number)
5241             continue;
5242           if (!allflag && !number_is_in_list (args, b->number))
5243             continue;
5244         }
5245
5246       if (allflag || user_breakpoint_p (b))
5247         {
5248           int addr_bit, type_len;
5249
5250           addr_bit = breakpoint_address_bits (b);
5251           if (addr_bit > print_address_bits)
5252             print_address_bits = addr_bit;
5253
5254           type_len = strlen (bptype_string (b->type));
5255           if (type_len > print_type_col_width)
5256             print_type_col_width = type_len;
5257
5258           nr_printable_breakpoints++;
5259         }
5260     }
5261
5262   if (opts.addressprint)
5263     bkpttbl_chain 
5264       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5265                                              nr_printable_breakpoints,
5266                                              "BreakpointTable");
5267   else
5268     bkpttbl_chain 
5269       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5270                                              nr_printable_breakpoints,
5271                                              "BreakpointTable");
5272
5273   if (nr_printable_breakpoints > 0)
5274     annotate_breakpoints_headers ();
5275   if (nr_printable_breakpoints > 0)
5276     annotate_field (0);
5277   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5278   if (nr_printable_breakpoints > 0)
5279     annotate_field (1);
5280   ui_out_table_header (uiout, print_type_col_width, ui_left,
5281                        "type", "Type");                         /* 2 */
5282   if (nr_printable_breakpoints > 0)
5283     annotate_field (2);
5284   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5285   if (nr_printable_breakpoints > 0)
5286     annotate_field (3);
5287   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5288   if (opts.addressprint)
5289     {
5290       if (nr_printable_breakpoints > 0)
5291         annotate_field (4);
5292       if (print_address_bits <= 32)
5293         ui_out_table_header (uiout, 10, ui_left, 
5294                              "addr", "Address");                /* 5 */
5295       else
5296         ui_out_table_header (uiout, 18, ui_left, 
5297                              "addr", "Address");                /* 5 */
5298     }
5299   if (nr_printable_breakpoints > 0)
5300     annotate_field (5);
5301   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5302   ui_out_table_body (uiout);
5303   if (nr_printable_breakpoints > 0)
5304     annotate_breakpoints_table ();
5305
5306   ALL_BREAKPOINTS (b)
5307     {
5308       QUIT;
5309       /* If we have a filter, only list the breakpoints it accepts.  */
5310       if (filter && !filter (b))
5311         continue;
5312
5313       /* If we have an "args" string, it is a list of breakpoints to 
5314          accept.  Skip the others.  */
5315
5316       if (args != NULL && *args != '\0')
5317         {
5318           if (allflag)  /* maintenance info breakpoint */
5319             {
5320               if (parse_and_eval_long (args) != b->number)
5321                 continue;
5322             }
5323           else          /* all others */
5324             {
5325               if (!number_is_in_list (args, b->number))
5326                 continue;
5327             }
5328         }
5329       /* We only print out user settable breakpoints unless the
5330          allflag is set.  */
5331       if (allflag || user_breakpoint_p (b))
5332         print_one_breakpoint (b, &last_loc, allflag);
5333     }
5334
5335   do_cleanups (bkpttbl_chain);
5336
5337   if (nr_printable_breakpoints == 0)
5338     {
5339       /* If there's a filter, let the caller decide how to report
5340          empty list.  */
5341       if (!filter)
5342         {
5343           if (args == NULL || *args == '\0')
5344             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5345           else
5346             ui_out_message (uiout, 0, 
5347                             "No breakpoint or watchpoint matching '%s'.\n",
5348                             args);
5349         }
5350     }
5351   else
5352     {
5353       if (last_loc && !server_command)
5354         set_next_address (last_loc->gdbarch, last_loc->address);
5355     }
5356
5357   /* FIXME?  Should this be moved up so that it is only called when
5358      there have been breakpoints? */
5359   annotate_breakpoints_table_end ();
5360
5361   return nr_printable_breakpoints;
5362 }
5363
5364 /* Display the value of default-collect in a way that is generally
5365    compatible with the breakpoint list.  */
5366
5367 static void
5368 default_collect_info (void)
5369 {
5370   struct ui_out *uiout = current_uiout;
5371
5372   /* If it has no value (which is frequently the case), say nothing; a
5373      message like "No default-collect." gets in user's face when it's
5374      not wanted.  */
5375   if (!*default_collect)
5376     return;
5377
5378   /* The following phrase lines up nicely with per-tracepoint collect
5379      actions.  */
5380   ui_out_text (uiout, "default collect ");
5381   ui_out_field_string (uiout, "default-collect", default_collect);
5382   ui_out_text (uiout, " \n");
5383 }
5384   
5385 static void
5386 breakpoints_info (char *args, int from_tty)
5387 {
5388   breakpoint_1 (args, 0, NULL);
5389
5390   default_collect_info ();
5391 }
5392
5393 static void
5394 watchpoints_info (char *args, int from_tty)
5395 {
5396   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
5397   struct ui_out *uiout = current_uiout;
5398
5399   if (num_printed == 0)
5400     {
5401       if (args == NULL || *args == '\0')
5402         ui_out_message (uiout, 0, "No watchpoints.\n");
5403       else
5404         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
5405     }
5406 }
5407
5408 static void
5409 maintenance_info_breakpoints (char *args, int from_tty)
5410 {
5411   breakpoint_1 (args, 1, NULL);
5412
5413   default_collect_info ();
5414 }
5415
5416 static int
5417 breakpoint_has_pc (struct breakpoint *b,
5418                    struct program_space *pspace,
5419                    CORE_ADDR pc, struct obj_section *section)
5420 {
5421   struct bp_location *bl = b->loc;
5422
5423   for (; bl; bl = bl->next)
5424     {
5425       if (bl->pspace == pspace
5426           && bl->address == pc
5427           && (!overlay_debugging || bl->section == section))
5428         return 1;         
5429     }
5430   return 0;
5431 }
5432
5433 /* Print a message describing any user-breakpoints set at PC.  This
5434    concerns with logical breakpoints, so we match program spaces, not
5435    address spaces.  */
5436
5437 static void
5438 describe_other_breakpoints (struct gdbarch *gdbarch,
5439                             struct program_space *pspace, CORE_ADDR pc,
5440                             struct obj_section *section, int thread)
5441 {
5442   int others = 0;
5443   struct breakpoint *b;
5444
5445   ALL_BREAKPOINTS (b)
5446     others += (user_breakpoint_p (b)
5447                && breakpoint_has_pc (b, pspace, pc, section));
5448   if (others > 0)
5449     {
5450       if (others == 1)
5451         printf_filtered (_("Note: breakpoint "));
5452       else /* if (others == ???) */
5453         printf_filtered (_("Note: breakpoints "));
5454       ALL_BREAKPOINTS (b)
5455         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
5456           {
5457             others--;
5458             printf_filtered ("%d", b->number);
5459             if (b->thread == -1 && thread != -1)
5460               printf_filtered (" (all threads)");
5461             else if (b->thread != -1)
5462               printf_filtered (" (thread %d)", b->thread);
5463             printf_filtered ("%s%s ",
5464                              ((b->enable_state == bp_disabled
5465                                || b->enable_state == bp_call_disabled)
5466                               ? " (disabled)"
5467                               : b->enable_state == bp_permanent 
5468                               ? " (permanent)"
5469                               : ""),
5470                              (others > 1) ? "," 
5471                              : ((others == 1) ? " and" : ""));
5472           }
5473       printf_filtered (_("also set at pc "));
5474       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
5475       printf_filtered (".\n");
5476     }
5477 }
5478 \f
5479
5480 /* Return true iff it is meaningful to use the address member of
5481    BPT.  For some breakpoint types, the address member is irrelevant
5482    and it makes no sense to attempt to compare it to other addresses
5483    (or use it for any other purpose either).
5484
5485    More specifically, each of the following breakpoint types will
5486    always have a zero valued address and we don't want to mark
5487    breakpoints of any of these types to be a duplicate of an actual
5488    breakpoint at address zero:
5489
5490       bp_watchpoint
5491       bp_catchpoint
5492
5493 */
5494
5495 static int
5496 breakpoint_address_is_meaningful (struct breakpoint *bpt)
5497 {
5498   enum bptype type = bpt->type;
5499
5500   return (type != bp_watchpoint && type != bp_catchpoint);
5501 }
5502
5503 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
5504    true if LOC1 and LOC2 represent the same watchpoint location.  */
5505
5506 static int
5507 watchpoint_locations_match (struct bp_location *loc1, 
5508                             struct bp_location *loc2)
5509 {
5510   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
5511   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
5512
5513   /* Both of them must exist.  */
5514   gdb_assert (w1 != NULL);
5515   gdb_assert (w2 != NULL);
5516
5517   /* If the target can evaluate the condition expression in hardware,
5518      then we we need to insert both watchpoints even if they are at
5519      the same place.  Otherwise the watchpoint will only trigger when
5520      the condition of whichever watchpoint was inserted evaluates to
5521      true, not giving a chance for GDB to check the condition of the
5522      other watchpoint.  */
5523   if ((w1->cond_exp
5524        && target_can_accel_watchpoint_condition (loc1->address, 
5525                                                  loc1->length,
5526                                                  loc1->watchpoint_type,
5527                                                  w1->cond_exp))
5528       || (w2->cond_exp
5529           && target_can_accel_watchpoint_condition (loc2->address, 
5530                                                     loc2->length,
5531                                                     loc2->watchpoint_type,
5532                                                     w2->cond_exp)))
5533     return 0;
5534
5535   /* Note that this checks the owner's type, not the location's.  In
5536      case the target does not support read watchpoints, but does
5537      support access watchpoints, we'll have bp_read_watchpoint
5538      watchpoints with hw_access locations.  Those should be considered
5539      duplicates of hw_read locations.  The hw_read locations will
5540      become hw_access locations later.  */
5541   return (loc1->owner->type == loc2->owner->type
5542           && loc1->pspace->aspace == loc2->pspace->aspace
5543           && loc1->address == loc2->address
5544           && loc1->length == loc2->length);
5545 }
5546
5547 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
5548    same breakpoint location.  In most targets, this can only be true
5549    if ASPACE1 matches ASPACE2.  On targets that have global
5550    breakpoints, the address space doesn't really matter.  */
5551
5552 static int
5553 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
5554                           struct address_space *aspace2, CORE_ADDR addr2)
5555 {
5556   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5557            || aspace1 == aspace2)
5558           && addr1 == addr2);
5559 }
5560
5561 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
5562    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
5563    matches ASPACE2.  On targets that have global breakpoints, the address
5564    space doesn't really matter.  */
5565
5566 static int
5567 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
5568                                 int len1, struct address_space *aspace2,
5569                                 CORE_ADDR addr2)
5570 {
5571   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5572            || aspace1 == aspace2)
5573           && addr2 >= addr1 && addr2 < addr1 + len1);
5574 }
5575
5576 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
5577    a ranged breakpoint.  In most targets, a match happens only if ASPACE
5578    matches the breakpoint's address space.  On targets that have global
5579    breakpoints, the address space doesn't really matter.  */
5580
5581 static int
5582 breakpoint_location_address_match (struct bp_location *bl,
5583                                    struct address_space *aspace,
5584                                    CORE_ADDR addr)
5585 {
5586   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
5587                                     aspace, addr)
5588           || (bl->length
5589               && breakpoint_address_match_range (bl->pspace->aspace,
5590                                                  bl->address, bl->length,
5591                                                  aspace, addr)));
5592 }
5593
5594 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
5595    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
5596    true, otherwise returns false.  */
5597
5598 static int
5599 tracepoint_locations_match (struct bp_location *loc1,
5600                             struct bp_location *loc2)
5601 {
5602   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
5603     /* Since tracepoint locations are never duplicated with others', tracepoint
5604        locations at the same address of different tracepoints are regarded as
5605        different locations.  */
5606     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
5607   else
5608     return 0;
5609 }
5610
5611 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
5612    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
5613    represent the same location.  */
5614
5615 static int
5616 breakpoint_locations_match (struct bp_location *loc1, 
5617                             struct bp_location *loc2)
5618 {
5619   int hw_point1, hw_point2;
5620
5621   /* Both of them must not be in moribund_locations.  */
5622   gdb_assert (loc1->owner != NULL);
5623   gdb_assert (loc2->owner != NULL);
5624
5625   hw_point1 = is_hardware_watchpoint (loc1->owner);
5626   hw_point2 = is_hardware_watchpoint (loc2->owner);
5627
5628   if (hw_point1 != hw_point2)
5629     return 0;
5630   else if (hw_point1)
5631     return watchpoint_locations_match (loc1, loc2);
5632   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
5633     return tracepoint_locations_match (loc1, loc2);
5634   else
5635     /* We compare bp_location.length in order to cover ranged breakpoints.  */
5636     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
5637                                      loc2->pspace->aspace, loc2->address)
5638             && loc1->length == loc2->length);
5639 }
5640
5641 static void
5642 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
5643                                int bnum, int have_bnum)
5644 {
5645   /* The longest string possibly returned by hex_string_custom
5646      is 50 chars.  These must be at least that big for safety.  */
5647   char astr1[64];
5648   char astr2[64];
5649
5650   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
5651   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
5652   if (have_bnum)
5653     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
5654              bnum, astr1, astr2);
5655   else
5656     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
5657 }
5658
5659 /* Adjust a breakpoint's address to account for architectural
5660    constraints on breakpoint placement.  Return the adjusted address.
5661    Note: Very few targets require this kind of adjustment.  For most
5662    targets, this function is simply the identity function.  */
5663
5664 static CORE_ADDR
5665 adjust_breakpoint_address (struct gdbarch *gdbarch,
5666                            CORE_ADDR bpaddr, enum bptype bptype)
5667 {
5668   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
5669     {
5670       /* Very few targets need any kind of breakpoint adjustment.  */
5671       return bpaddr;
5672     }
5673   else if (bptype == bp_watchpoint
5674            || bptype == bp_hardware_watchpoint
5675            || bptype == bp_read_watchpoint
5676            || bptype == bp_access_watchpoint
5677            || bptype == bp_catchpoint)
5678     {
5679       /* Watchpoints and the various bp_catch_* eventpoints should not
5680          have their addresses modified.  */
5681       return bpaddr;
5682     }
5683   else
5684     {
5685       CORE_ADDR adjusted_bpaddr;
5686
5687       /* Some targets have architectural constraints on the placement
5688          of breakpoint instructions.  Obtain the adjusted address.  */
5689       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
5690
5691       /* An adjusted breakpoint address can significantly alter
5692          a user's expectations.  Print a warning if an adjustment
5693          is required.  */
5694       if (adjusted_bpaddr != bpaddr)
5695         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
5696
5697       return adjusted_bpaddr;
5698     }
5699 }
5700
5701 void
5702 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
5703                   struct breakpoint *owner)
5704 {
5705   memset (loc, 0, sizeof (*loc));
5706
5707   gdb_assert (ops != NULL);
5708
5709   loc->ops = ops;
5710   loc->owner = owner;
5711   loc->cond = NULL;
5712   loc->shlib_disabled = 0;
5713   loc->enabled = 1;
5714
5715   switch (owner->type)
5716     {
5717     case bp_breakpoint:
5718     case bp_until:
5719     case bp_finish:
5720     case bp_longjmp:
5721     case bp_longjmp_resume:
5722     case bp_exception:
5723     case bp_exception_resume:
5724     case bp_step_resume:
5725     case bp_hp_step_resume:
5726     case bp_watchpoint_scope:
5727     case bp_call_dummy:
5728     case bp_std_terminate:
5729     case bp_shlib_event:
5730     case bp_thread_event:
5731     case bp_overlay_event:
5732     case bp_jit_event:
5733     case bp_longjmp_master:
5734     case bp_std_terminate_master:
5735     case bp_exception_master:
5736     case bp_gnu_ifunc_resolver:
5737     case bp_gnu_ifunc_resolver_return:
5738       loc->loc_type = bp_loc_software_breakpoint;
5739       break;
5740     case bp_hardware_breakpoint:
5741       loc->loc_type = bp_loc_hardware_breakpoint;
5742       break;
5743     case bp_hardware_watchpoint:
5744     case bp_read_watchpoint:
5745     case bp_access_watchpoint:
5746       loc->loc_type = bp_loc_hardware_watchpoint;
5747       break;
5748     case bp_watchpoint:
5749     case bp_catchpoint:
5750     case bp_tracepoint:
5751     case bp_fast_tracepoint:
5752     case bp_static_tracepoint:
5753       loc->loc_type = bp_loc_other;
5754       break;
5755     default:
5756       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
5757     }
5758
5759   loc->refc = 1;
5760 }
5761
5762 /* Allocate a struct bp_location.  */
5763
5764 static struct bp_location *
5765 allocate_bp_location (struct breakpoint *bpt)
5766 {
5767   return bpt->ops->allocate_location (bpt);
5768 }
5769
5770 static void
5771 free_bp_location (struct bp_location *loc)
5772 {
5773   loc->ops->dtor (loc);
5774   xfree (loc);
5775 }
5776
5777 /* Increment reference count.  */
5778
5779 static void
5780 incref_bp_location (struct bp_location *bl)
5781 {
5782   ++bl->refc;
5783 }
5784
5785 /* Decrement reference count.  If the reference count reaches 0,
5786    destroy the bp_location.  Sets *BLP to NULL.  */
5787
5788 static void
5789 decref_bp_location (struct bp_location **blp)
5790 {
5791   gdb_assert ((*blp)->refc > 0);
5792
5793   if (--(*blp)->refc == 0)
5794     free_bp_location (*blp);
5795   *blp = NULL;
5796 }
5797
5798 /* Add breakpoint B at the end of the global breakpoint chain.  */
5799
5800 static void
5801 add_to_breakpoint_chain (struct breakpoint *b)
5802 {
5803   struct breakpoint *b1;
5804
5805   /* Add this breakpoint to the end of the chain so that a list of
5806      breakpoints will come out in order of increasing numbers.  */
5807
5808   b1 = breakpoint_chain;
5809   if (b1 == 0)
5810     breakpoint_chain = b;
5811   else
5812     {
5813       while (b1->next)
5814         b1 = b1->next;
5815       b1->next = b;
5816     }
5817 }
5818
5819 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
5820
5821 static void
5822 init_raw_breakpoint_without_location (struct breakpoint *b,
5823                                       struct gdbarch *gdbarch,
5824                                       enum bptype bptype,
5825                                       const struct breakpoint_ops *ops)
5826 {
5827   memset (b, 0, sizeof (*b));
5828
5829   gdb_assert (ops != NULL);
5830
5831   b->ops = ops;
5832   b->type = bptype;
5833   b->gdbarch = gdbarch;
5834   b->language = current_language->la_language;
5835   b->input_radix = input_radix;
5836   b->thread = -1;
5837   b->enable_state = bp_enabled;
5838   b->next = 0;
5839   b->silent = 0;
5840   b->ignore_count = 0;
5841   b->commands = NULL;
5842   b->frame_id = null_frame_id;
5843   b->condition_not_parsed = 0;
5844   b->py_bp_object = NULL;
5845   b->related_breakpoint = b;
5846 }
5847
5848 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
5849    that has type BPTYPE and has no locations as yet.  */
5850
5851 static struct breakpoint *
5852 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
5853                                      enum bptype bptype,
5854                                      const struct breakpoint_ops *ops)
5855 {
5856   struct breakpoint *b = XNEW (struct breakpoint);
5857
5858   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
5859   add_to_breakpoint_chain (b);
5860   return b;
5861 }
5862
5863 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
5864    resolutions should be made as the user specified the location explicitly
5865    enough.  */
5866
5867 static void
5868 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
5869 {
5870   gdb_assert (loc->owner != NULL);
5871
5872   if (loc->owner->type == bp_breakpoint
5873       || loc->owner->type == bp_hardware_breakpoint
5874       || is_tracepoint (loc->owner))
5875     {
5876       int is_gnu_ifunc;
5877       const char *function_name;
5878
5879       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
5880                                           NULL, NULL, &is_gnu_ifunc);
5881
5882       if (is_gnu_ifunc && !explicit_loc)
5883         {
5884           struct breakpoint *b = loc->owner;
5885
5886           gdb_assert (loc->pspace == current_program_space);
5887           if (gnu_ifunc_resolve_name (function_name,
5888                                       &loc->requested_address))
5889             {
5890               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
5891               loc->address = adjust_breakpoint_address (loc->gdbarch,
5892                                                         loc->requested_address,
5893                                                         b->type);
5894             }
5895           else if (b->type == bp_breakpoint && b->loc == loc
5896                    && loc->next == NULL && b->related_breakpoint == b)
5897             {
5898               /* Create only the whole new breakpoint of this type but do not
5899                  mess more complicated breakpoints with multiple locations.  */
5900               b->type = bp_gnu_ifunc_resolver;
5901             }
5902         }
5903
5904       if (function_name)
5905         loc->function_name = xstrdup (function_name);
5906     }
5907 }
5908
5909 /* Attempt to determine architecture of location identified by SAL.  */
5910 struct gdbarch *
5911 get_sal_arch (struct symtab_and_line sal)
5912 {
5913   if (sal.section)
5914     return get_objfile_arch (sal.section->objfile);
5915   if (sal.symtab)
5916     return get_objfile_arch (sal.symtab->objfile);
5917
5918   return NULL;
5919 }
5920
5921 /* Low level routine for partially initializing a breakpoint of type
5922    BPTYPE.  The newly created breakpoint's address, section, source
5923    file name, and line number are provided by SAL.
5924
5925    It is expected that the caller will complete the initialization of
5926    the newly created breakpoint struct as well as output any status
5927    information regarding the creation of a new breakpoint.  */
5928
5929 static void
5930 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
5931                      struct symtab_and_line sal, enum bptype bptype,
5932                      const struct breakpoint_ops *ops)
5933 {
5934   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
5935
5936   add_location_to_breakpoint (b, &sal);
5937
5938   if (bptype != bp_catchpoint)
5939     gdb_assert (sal.pspace != NULL);
5940
5941   /* Store the program space that was used to set the breakpoint,
5942      except for ordinary breakpoints, which are independent of the
5943      program space.  */
5944   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
5945     b->pspace = sal.pspace;
5946
5947   breakpoints_changed ();
5948 }
5949
5950 /* set_raw_breakpoint is a low level routine for allocating and
5951    partially initializing a breakpoint of type BPTYPE.  The newly
5952    created breakpoint's address, section, source file name, and line
5953    number are provided by SAL.  The newly created and partially
5954    initialized breakpoint is added to the breakpoint chain and
5955    is also returned as the value of this function.
5956
5957    It is expected that the caller will complete the initialization of
5958    the newly created breakpoint struct as well as output any status
5959    information regarding the creation of a new breakpoint.  In
5960    particular, set_raw_breakpoint does NOT set the breakpoint
5961    number!  Care should be taken to not allow an error to occur
5962    prior to completing the initialization of the breakpoint.  If this
5963    should happen, a bogus breakpoint will be left on the chain.  */
5964
5965 struct breakpoint *
5966 set_raw_breakpoint (struct gdbarch *gdbarch,
5967                     struct symtab_and_line sal, enum bptype bptype,
5968                     const struct breakpoint_ops *ops)
5969 {
5970   struct breakpoint *b = XNEW (struct breakpoint);
5971
5972   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
5973   add_to_breakpoint_chain (b);
5974   return b;
5975 }
5976
5977
5978 /* Note that the breakpoint object B describes a permanent breakpoint
5979    instruction, hard-wired into the inferior's code.  */
5980 void
5981 make_breakpoint_permanent (struct breakpoint *b)
5982 {
5983   struct bp_location *bl;
5984
5985   b->enable_state = bp_permanent;
5986
5987   /* By definition, permanent breakpoints are already present in the
5988      code.  Mark all locations as inserted.  For now,
5989      make_breakpoint_permanent is called in just one place, so it's
5990      hard to say if it's reasonable to have permanent breakpoint with
5991      multiple locations or not, but it's easy to implement.  */
5992   for (bl = b->loc; bl; bl = bl->next)
5993     bl->inserted = 1;
5994 }
5995
5996 /* Call this routine when stepping and nexting to enable a breakpoint
5997    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
5998    initiated the operation.  */
5999
6000 void
6001 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6002 {
6003   struct breakpoint *b, *b_tmp;
6004   int thread = tp->num;
6005
6006   /* To avoid having to rescan all objfile symbols at every step,
6007      we maintain a list of continually-inserted but always disabled
6008      longjmp "master" breakpoints.  Here, we simply create momentary
6009      clones of those and enable them for the requested thread.  */
6010   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6011     if (b->pspace == current_program_space
6012         && (b->type == bp_longjmp_master
6013             || b->type == bp_exception_master))
6014       {
6015         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6016         struct breakpoint *clone;
6017
6018         clone = momentary_breakpoint_from_master (b, type,
6019                                                   &momentary_breakpoint_ops);
6020         clone->thread = thread;
6021       }
6022
6023   tp->initiating_frame = frame;
6024 }
6025
6026 /* Delete all longjmp breakpoints from THREAD.  */
6027 void
6028 delete_longjmp_breakpoint (int thread)
6029 {
6030   struct breakpoint *b, *b_tmp;
6031
6032   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6033     if (b->type == bp_longjmp || b->type == bp_exception)
6034       {
6035         if (b->thread == thread)
6036           delete_breakpoint (b);
6037       }
6038 }
6039
6040 void
6041 enable_overlay_breakpoints (void)
6042 {
6043   struct breakpoint *b;
6044
6045   ALL_BREAKPOINTS (b)
6046     if (b->type == bp_overlay_event)
6047     {
6048       b->enable_state = bp_enabled;
6049       update_global_location_list (1);
6050       overlay_events_enabled = 1;
6051     }
6052 }
6053
6054 void
6055 disable_overlay_breakpoints (void)
6056 {
6057   struct breakpoint *b;
6058
6059   ALL_BREAKPOINTS (b)
6060     if (b->type == bp_overlay_event)
6061     {
6062       b->enable_state = bp_disabled;
6063       update_global_location_list (0);
6064       overlay_events_enabled = 0;
6065     }
6066 }
6067
6068 /* Set an active std::terminate breakpoint for each std::terminate
6069    master breakpoint.  */
6070 void
6071 set_std_terminate_breakpoint (void)
6072 {
6073   struct breakpoint *b, *b_tmp;
6074
6075   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6076     if (b->pspace == current_program_space
6077         && b->type == bp_std_terminate_master)
6078       {
6079         momentary_breakpoint_from_master (b, bp_std_terminate,
6080                                           &momentary_breakpoint_ops);
6081       }
6082 }
6083
6084 /* Delete all the std::terminate breakpoints.  */
6085 void
6086 delete_std_terminate_breakpoint (void)
6087 {
6088   struct breakpoint *b, *b_tmp;
6089
6090   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6091     if (b->type == bp_std_terminate)
6092       delete_breakpoint (b);
6093 }
6094
6095 struct breakpoint *
6096 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6097 {
6098   struct breakpoint *b;
6099
6100   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6101                                   &internal_breakpoint_ops);
6102
6103   b->enable_state = bp_enabled;
6104   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6105   b->addr_string
6106     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6107
6108   update_global_location_list_nothrow (1);
6109
6110   return b;
6111 }
6112
6113 void
6114 remove_thread_event_breakpoints (void)
6115 {
6116   struct breakpoint *b, *b_tmp;
6117
6118   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6119     if (b->type == bp_thread_event
6120         && b->loc->pspace == current_program_space)
6121       delete_breakpoint (b);
6122 }
6123
6124 struct lang_and_radix
6125   {
6126     enum language lang;
6127     int radix;
6128   };
6129
6130 /* Create a breakpoint for JIT code registration and unregistration.  */
6131
6132 struct breakpoint *
6133 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6134 {
6135   struct breakpoint *b;
6136
6137   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6138                                   &internal_breakpoint_ops);
6139   update_global_location_list_nothrow (1);
6140   return b;
6141 }
6142
6143 /* Remove JIT code registration and unregistration breakpoint(s).  */
6144
6145 void
6146 remove_jit_event_breakpoints (void)
6147 {
6148   struct breakpoint *b, *b_tmp;
6149
6150   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6151     if (b->type == bp_jit_event
6152         && b->loc->pspace == current_program_space)
6153       delete_breakpoint (b);
6154 }
6155
6156 void
6157 remove_solib_event_breakpoints (void)
6158 {
6159   struct breakpoint *b, *b_tmp;
6160
6161   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6162     if (b->type == bp_shlib_event
6163         && b->loc->pspace == current_program_space)
6164       delete_breakpoint (b);
6165 }
6166
6167 struct breakpoint *
6168 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6169 {
6170   struct breakpoint *b;
6171
6172   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6173                                   &internal_breakpoint_ops);
6174   update_global_location_list_nothrow (1);
6175   return b;
6176 }
6177
6178 /* Disable any breakpoints that are on code in shared libraries.  Only
6179    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6180
6181 void
6182 disable_breakpoints_in_shlibs (void)
6183 {
6184   struct bp_location *loc, **locp_tmp;
6185
6186   ALL_BP_LOCATIONS (loc, locp_tmp)
6187   {
6188     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6189     struct breakpoint *b = loc->owner;
6190
6191     /* We apply the check to all breakpoints, including disabled for
6192        those with loc->duplicate set.  This is so that when breakpoint
6193        becomes enabled, or the duplicate is removed, gdb will try to
6194        insert all breakpoints.  If we don't set shlib_disabled here,
6195        we'll try to insert those breakpoints and fail.  */
6196     if (((b->type == bp_breakpoint)
6197          || (b->type == bp_jit_event)
6198          || (b->type == bp_hardware_breakpoint)
6199          || (is_tracepoint (b)))
6200         && loc->pspace == current_program_space
6201         && !loc->shlib_disabled
6202 #ifdef PC_SOLIB
6203         && PC_SOLIB (loc->address)
6204 #else
6205         && solib_name_from_address (loc->pspace, loc->address)
6206 #endif
6207         )
6208       {
6209         loc->shlib_disabled = 1;
6210       }
6211   }
6212 }
6213
6214 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6215    library.  Only apply to enabled breakpoints, disabled ones can just stay
6216    disabled.  */
6217
6218 static void
6219 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6220 {
6221   struct bp_location *loc, **locp_tmp;
6222   int disabled_shlib_breaks = 0;
6223
6224   /* SunOS a.out shared libraries are always mapped, so do not
6225      disable breakpoints; they will only be reported as unloaded
6226      through clear_solib when GDB discards its shared library
6227      list.  See clear_solib for more information.  */
6228   if (exec_bfd != NULL
6229       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6230     return;
6231
6232   ALL_BP_LOCATIONS (loc, locp_tmp)
6233   {
6234     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6235     struct breakpoint *b = loc->owner;
6236
6237     if (solib->pspace == loc->pspace
6238         && !loc->shlib_disabled
6239         && (((b->type == bp_breakpoint
6240               || b->type == bp_jit_event
6241               || b->type == bp_hardware_breakpoint)
6242              && (loc->loc_type == bp_loc_hardware_breakpoint
6243                  || loc->loc_type == bp_loc_software_breakpoint))
6244             || is_tracepoint (b))
6245         && solib_contains_address_p (solib, loc->address))
6246       {
6247         loc->shlib_disabled = 1;
6248         /* At this point, we cannot rely on remove_breakpoint
6249            succeeding so we must mark the breakpoint as not inserted
6250            to prevent future errors occurring in remove_breakpoints.  */
6251         loc->inserted = 0;
6252
6253         /* This may cause duplicate notifications for the same breakpoint.  */
6254         observer_notify_breakpoint_modified (b);
6255
6256         if (!disabled_shlib_breaks)
6257           {
6258             target_terminal_ours_for_output ();
6259             warning (_("Temporarily disabling breakpoints "
6260                        "for unloaded shared library \"%s\""),
6261                      solib->so_name);
6262           }
6263         disabled_shlib_breaks = 1;
6264       }
6265   }
6266 }
6267
6268 /* FORK & VFORK catchpoints.  */
6269
6270 /* An instance of this type is used to represent a fork or vfork
6271    catchpoint.  It includes a "struct breakpoint" as a kind of base
6272    class; users downcast to "struct breakpoint *" when needed.  A
6273    breakpoint is really of this type iff its ops pointer points to
6274    CATCH_FORK_BREAKPOINT_OPS.  */
6275
6276 struct fork_catchpoint
6277 {
6278   /* The base class.  */
6279   struct breakpoint base;
6280
6281   /* Process id of a child process whose forking triggered this
6282      catchpoint.  This field is only valid immediately after this
6283      catchpoint has triggered.  */
6284   ptid_t forked_inferior_pid;
6285 };
6286
6287 /* Implement the "insert" breakpoint_ops method for fork
6288    catchpoints.  */
6289
6290 static int
6291 insert_catch_fork (struct bp_location *bl)
6292 {
6293   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6294 }
6295
6296 /* Implement the "remove" breakpoint_ops method for fork
6297    catchpoints.  */
6298
6299 static int
6300 remove_catch_fork (struct bp_location *bl)
6301 {
6302   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6303 }
6304
6305 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6306    catchpoints.  */
6307
6308 static int
6309 breakpoint_hit_catch_fork (const struct bp_location *bl,
6310                            struct address_space *aspace, CORE_ADDR bp_addr,
6311                            const struct target_waitstatus *ws)
6312 {
6313   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6314
6315   if (ws->kind != TARGET_WAITKIND_FORKED)
6316     return 0;
6317
6318   c->forked_inferior_pid = ws->value.related_pid;
6319   return 1;
6320 }
6321
6322 /* Implement the "print_it" breakpoint_ops method for fork
6323    catchpoints.  */
6324
6325 static enum print_stop_action
6326 print_it_catch_fork (bpstat bs)
6327 {
6328   struct ui_out *uiout = current_uiout;
6329   struct breakpoint *b = bs->breakpoint_at;
6330   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6331
6332   annotate_catchpoint (b->number);
6333   if (b->disposition == disp_del)
6334     ui_out_text (uiout, "\nTemporary catchpoint ");
6335   else
6336     ui_out_text (uiout, "\nCatchpoint ");
6337   if (ui_out_is_mi_like_p (uiout))
6338     {
6339       ui_out_field_string (uiout, "reason",
6340                            async_reason_lookup (EXEC_ASYNC_FORK));
6341       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6342     }
6343   ui_out_field_int (uiout, "bkptno", b->number);
6344   ui_out_text (uiout, " (forked process ");
6345   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6346   ui_out_text (uiout, "), ");
6347   return PRINT_SRC_AND_LOC;
6348 }
6349
6350 /* Implement the "print_one" breakpoint_ops method for fork
6351    catchpoints.  */
6352
6353 static void
6354 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6355 {
6356   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6357   struct value_print_options opts;
6358   struct ui_out *uiout = current_uiout;
6359
6360   get_user_print_options (&opts);
6361
6362   /* Field 4, the address, is omitted (which makes the columns not
6363      line up too nicely with the headers, but the effect is relatively
6364      readable).  */
6365   if (opts.addressprint)
6366     ui_out_field_skip (uiout, "addr");
6367   annotate_field (5);
6368   ui_out_text (uiout, "fork");
6369   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6370     {
6371       ui_out_text (uiout, ", process ");
6372       ui_out_field_int (uiout, "what",
6373                         ptid_get_pid (c->forked_inferior_pid));
6374       ui_out_spaces (uiout, 1);
6375     }
6376 }
6377
6378 /* Implement the "print_mention" breakpoint_ops method for fork
6379    catchpoints.  */
6380
6381 static void
6382 print_mention_catch_fork (struct breakpoint *b)
6383 {
6384   printf_filtered (_("Catchpoint %d (fork)"), b->number);
6385 }
6386
6387 /* Implement the "print_recreate" breakpoint_ops method for fork
6388    catchpoints.  */
6389
6390 static void
6391 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
6392 {
6393   fprintf_unfiltered (fp, "catch fork");
6394   print_recreate_thread (b, fp);
6395 }
6396
6397 /* The breakpoint_ops structure to be used in fork catchpoints.  */
6398
6399 static struct breakpoint_ops catch_fork_breakpoint_ops;
6400
6401 /* Implement the "insert" breakpoint_ops method for vfork
6402    catchpoints.  */
6403
6404 static int
6405 insert_catch_vfork (struct bp_location *bl)
6406 {
6407   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
6408 }
6409
6410 /* Implement the "remove" breakpoint_ops method for vfork
6411    catchpoints.  */
6412
6413 static int
6414 remove_catch_vfork (struct bp_location *bl)
6415 {
6416   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
6417 }
6418
6419 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
6420    catchpoints.  */
6421
6422 static int
6423 breakpoint_hit_catch_vfork (const struct bp_location *bl,
6424                             struct address_space *aspace, CORE_ADDR bp_addr,
6425                             const struct target_waitstatus *ws)
6426 {
6427   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6428
6429   if (ws->kind != TARGET_WAITKIND_VFORKED)
6430     return 0;
6431
6432   c->forked_inferior_pid = ws->value.related_pid;
6433   return 1;
6434 }
6435
6436 /* Implement the "print_it" breakpoint_ops method for vfork
6437    catchpoints.  */
6438
6439 static enum print_stop_action
6440 print_it_catch_vfork (bpstat bs)
6441 {
6442   struct ui_out *uiout = current_uiout;
6443   struct breakpoint *b = bs->breakpoint_at;
6444   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6445
6446   annotate_catchpoint (b->number);
6447   if (b->disposition == disp_del)
6448     ui_out_text (uiout, "\nTemporary catchpoint ");
6449   else
6450     ui_out_text (uiout, "\nCatchpoint ");
6451   if (ui_out_is_mi_like_p (uiout))
6452     {
6453       ui_out_field_string (uiout, "reason",
6454                            async_reason_lookup (EXEC_ASYNC_VFORK));
6455       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6456     }
6457   ui_out_field_int (uiout, "bkptno", b->number);
6458   ui_out_text (uiout, " (vforked process ");
6459   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6460   ui_out_text (uiout, "), ");
6461   return PRINT_SRC_AND_LOC;
6462 }
6463
6464 /* Implement the "print_one" breakpoint_ops method for vfork
6465    catchpoints.  */
6466
6467 static void
6468 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
6469 {
6470   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6471   struct value_print_options opts;
6472   struct ui_out *uiout = current_uiout;
6473
6474   get_user_print_options (&opts);
6475   /* Field 4, the address, is omitted (which makes the columns not
6476      line up too nicely with the headers, but the effect is relatively
6477      readable).  */
6478   if (opts.addressprint)
6479     ui_out_field_skip (uiout, "addr");
6480   annotate_field (5);
6481   ui_out_text (uiout, "vfork");
6482   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6483     {
6484       ui_out_text (uiout, ", process ");
6485       ui_out_field_int (uiout, "what",
6486                         ptid_get_pid (c->forked_inferior_pid));
6487       ui_out_spaces (uiout, 1);
6488     }
6489 }
6490
6491 /* Implement the "print_mention" breakpoint_ops method for vfork
6492    catchpoints.  */
6493
6494 static void
6495 print_mention_catch_vfork (struct breakpoint *b)
6496 {
6497   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
6498 }
6499
6500 /* Implement the "print_recreate" breakpoint_ops method for vfork
6501    catchpoints.  */
6502
6503 static void
6504 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
6505 {
6506   fprintf_unfiltered (fp, "catch vfork");
6507   print_recreate_thread (b, fp);
6508 }
6509
6510 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
6511
6512 static struct breakpoint_ops catch_vfork_breakpoint_ops;
6513
6514 /* An instance of this type is used to represent an solib catchpoint.
6515    It includes a "struct breakpoint" as a kind of base class; users
6516    downcast to "struct breakpoint *" when needed.  A breakpoint is
6517    really of this type iff its ops pointer points to
6518    CATCH_SOLIB_BREAKPOINT_OPS.  */
6519
6520 struct solib_catchpoint
6521 {
6522   /* The base class.  */
6523   struct breakpoint base;
6524
6525   /* True for "catch load", false for "catch unload".  */
6526   unsigned char is_load;
6527
6528   /* Regular expression to match, if any.  COMPILED is only valid when
6529      REGEX is non-NULL.  */
6530   char *regex;
6531   regex_t compiled;
6532 };
6533
6534 static void
6535 dtor_catch_solib (struct breakpoint *b)
6536 {
6537   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
6538
6539   if (self->regex)
6540     regfree (&self->compiled);
6541   xfree (self->regex);
6542
6543   base_breakpoint_ops.dtor (b);
6544 }
6545
6546 static int
6547 insert_catch_solib (struct bp_location *ignore)
6548 {
6549   return 0;
6550 }
6551
6552 static int
6553 remove_catch_solib (struct bp_location *ignore)
6554 {
6555   return 0;
6556 }
6557
6558 static int
6559 breakpoint_hit_catch_solib (const struct bp_location *bl,
6560                             struct address_space *aspace,
6561                             CORE_ADDR bp_addr,
6562                             const struct target_waitstatus *ws)
6563 {
6564   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
6565   struct breakpoint *other;
6566
6567   if (ws->kind == TARGET_WAITKIND_LOADED)
6568     return 1;
6569
6570   ALL_BREAKPOINTS (other)
6571   {
6572     struct bp_location *other_bl;
6573
6574     if (other == bl->owner)
6575       continue;
6576
6577     if (other->type != bp_shlib_event)
6578       continue;
6579
6580     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
6581       continue;
6582
6583     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
6584       {
6585         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
6586           return 1;
6587       }
6588   }
6589
6590   return 0;
6591 }
6592
6593 static void
6594 check_status_catch_solib (struct bpstats *bs)
6595 {
6596   struct solib_catchpoint *self
6597     = (struct solib_catchpoint *) bs->breakpoint_at;
6598   int ix;
6599
6600   if (self->is_load)
6601     {
6602       struct so_list *iter;
6603
6604       for (ix = 0;
6605            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
6606                         ix, iter);
6607            ++ix)
6608         {
6609           if (!self->regex
6610               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
6611             return;
6612         }
6613     }
6614   else
6615     {
6616       char *iter;
6617
6618       for (ix = 0;
6619            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
6620                         ix, iter);
6621            ++ix)
6622         {
6623           if (!self->regex
6624               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
6625             return;
6626         }
6627     }
6628
6629   bs->stop = 0;
6630   bs->print_it = print_it_noop;
6631 }
6632
6633 static enum print_stop_action
6634 print_it_catch_solib (bpstat bs)
6635 {
6636   struct breakpoint *b = bs->breakpoint_at;
6637   struct ui_out *uiout = current_uiout;
6638
6639   annotate_catchpoint (b->number);
6640   if (b->disposition == disp_del)
6641     ui_out_text (uiout, "\nTemporary catchpoint ");
6642   else
6643     ui_out_text (uiout, "\nCatchpoint ");
6644   ui_out_field_int (uiout, "bkptno", b->number);
6645   ui_out_text (uiout, "\n");
6646   if (ui_out_is_mi_like_p (uiout))
6647     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6648   print_solib_event (1);
6649   return PRINT_SRC_AND_LOC;
6650 }
6651
6652 static void
6653 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
6654 {
6655   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
6656   struct value_print_options opts;
6657   struct ui_out *uiout = current_uiout;
6658   char *msg;
6659
6660   get_user_print_options (&opts);
6661   /* Field 4, the address, is omitted (which makes the columns not
6662      line up too nicely with the headers, but the effect is relatively
6663      readable).  */
6664   if (opts.addressprint)
6665     {
6666       annotate_field (4);
6667       ui_out_field_skip (uiout, "addr");
6668     }
6669
6670   annotate_field (5);
6671   if (self->is_load)
6672     {
6673       if (self->regex)
6674         msg = xstrprintf (_("load of library matching %s"), self->regex);
6675       else
6676         msg = xstrdup (_("load of library"));
6677     }
6678   else
6679     {
6680       if (self->regex)
6681         msg = xstrprintf (_("unload of library matching %s"), self->regex);
6682       else
6683         msg = xstrdup (_("unload of library"));
6684     }
6685   ui_out_field_string (uiout, "what", msg);
6686   xfree (msg);
6687 }
6688
6689 static void
6690 print_mention_catch_solib (struct breakpoint *b)
6691 {
6692   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
6693
6694   printf_filtered (_("Catchpoint %d (%s)"), b->number,
6695                    self->is_load ? "load" : "unload");
6696 }
6697
6698 static void
6699 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
6700 {
6701   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
6702
6703   fprintf_unfiltered (fp, "%s %s",
6704                       b->disposition == disp_del ? "tcatch" : "catch",
6705                       self->is_load ? "load" : "unload");
6706   if (self->regex)
6707     fprintf_unfiltered (fp, " %s", self->regex);
6708   fprintf_unfiltered (fp, "\n");
6709 }
6710
6711 static struct breakpoint_ops catch_solib_breakpoint_ops;
6712
6713 /* A helper function that does all the work for "catch load" and
6714    "catch unload".  */
6715
6716 static void
6717 catch_load_or_unload (char *arg, int from_tty, int is_load,
6718                       struct cmd_list_element *command)
6719 {
6720   struct solib_catchpoint *c;
6721   struct gdbarch *gdbarch = get_current_arch ();
6722   int tempflag;
6723   regex_t compiled;
6724   struct cleanup *cleanup;
6725
6726   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
6727
6728   if (!arg)
6729     arg = "";
6730   arg = skip_spaces (arg);
6731
6732   c = XCNEW (struct solib_catchpoint);
6733   cleanup = make_cleanup (xfree, c);
6734
6735   if (*arg != '\0')
6736     {
6737       int errcode;
6738
6739       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
6740       if (errcode != 0)
6741         {
6742           char *err = get_regcomp_error (errcode, &c->compiled);
6743
6744           make_cleanup (xfree, err);
6745           error (_("Invalid regexp (%s): %s"), err, arg);
6746         }
6747       c->regex = xstrdup (arg);
6748     }
6749
6750   c->is_load = is_load;
6751   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
6752                    &catch_solib_breakpoint_ops);
6753
6754   discard_cleanups (cleanup);
6755   install_breakpoint (0, &c->base, 1);
6756 }
6757
6758 static void
6759 catch_load_command_1 (char *arg, int from_tty,
6760                       struct cmd_list_element *command)
6761 {
6762   catch_load_or_unload (arg, from_tty, 1, command);
6763 }
6764
6765 static void
6766 catch_unload_command_1 (char *arg, int from_tty,
6767                         struct cmd_list_element *command)
6768 {
6769   catch_load_or_unload (arg, from_tty, 0, command);
6770 }
6771
6772 /* An instance of this type is used to represent a syscall catchpoint.
6773    It includes a "struct breakpoint" as a kind of base class; users
6774    downcast to "struct breakpoint *" when needed.  A breakpoint is
6775    really of this type iff its ops pointer points to
6776    CATCH_SYSCALL_BREAKPOINT_OPS.  */
6777
6778 struct syscall_catchpoint
6779 {
6780   /* The base class.  */
6781   struct breakpoint base;
6782
6783   /* Syscall numbers used for the 'catch syscall' feature.  If no
6784      syscall has been specified for filtering, its value is NULL.
6785      Otherwise, it holds a list of all syscalls to be caught.  The
6786      list elements are allocated with xmalloc.  */
6787   VEC(int) *syscalls_to_be_caught;
6788 };
6789
6790 /* Implement the "dtor" breakpoint_ops method for syscall
6791    catchpoints.  */
6792
6793 static void
6794 dtor_catch_syscall (struct breakpoint *b)
6795 {
6796   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6797
6798   VEC_free (int, c->syscalls_to_be_caught);
6799
6800   base_breakpoint_ops.dtor (b);
6801 }
6802
6803 /* Implement the "insert" breakpoint_ops method for syscall
6804    catchpoints.  */
6805
6806 static int
6807 insert_catch_syscall (struct bp_location *bl)
6808 {
6809   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
6810   struct inferior *inf = current_inferior ();
6811
6812   ++inf->total_syscalls_count;
6813   if (!c->syscalls_to_be_caught)
6814     ++inf->any_syscall_count;
6815   else
6816     {
6817       int i, iter;
6818
6819       for (i = 0;
6820            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6821            i++)
6822         {
6823           int elem;
6824
6825           if (iter >= VEC_length (int, inf->syscalls_counts))
6826             {
6827               int old_size = VEC_length (int, inf->syscalls_counts);
6828               uintptr_t vec_addr_offset
6829                 = old_size * ((uintptr_t) sizeof (int));
6830               uintptr_t vec_addr;
6831               VEC_safe_grow (int, inf->syscalls_counts, iter + 1);
6832               vec_addr = (uintptr_t) VEC_address (int, inf->syscalls_counts) +
6833                 vec_addr_offset;
6834               memset ((void *) vec_addr, 0,
6835                       (iter + 1 - old_size) * sizeof (int));
6836             }
6837           elem = VEC_index (int, inf->syscalls_counts, iter);
6838           VEC_replace (int, inf->syscalls_counts, iter, ++elem);
6839         }
6840     }
6841
6842   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6843                                         inf->total_syscalls_count != 0,
6844                                         inf->any_syscall_count,
6845                                         VEC_length (int, inf->syscalls_counts),
6846                                         VEC_address (int, inf->syscalls_counts));
6847 }
6848
6849 /* Implement the "remove" breakpoint_ops method for syscall
6850    catchpoints.  */
6851
6852 static int
6853 remove_catch_syscall (struct bp_location *bl)
6854 {
6855   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
6856   struct inferior *inf = current_inferior ();
6857
6858   --inf->total_syscalls_count;
6859   if (!c->syscalls_to_be_caught)
6860     --inf->any_syscall_count;
6861   else
6862     {
6863       int i, iter;
6864
6865       for (i = 0;
6866            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6867            i++)
6868         {
6869           int elem;
6870           if (iter >= VEC_length (int, inf->syscalls_counts))
6871             /* Shouldn't happen.  */
6872             continue;
6873           elem = VEC_index (int, inf->syscalls_counts, iter);
6874           VEC_replace (int, inf->syscalls_counts, iter, --elem);
6875         }
6876     }
6877
6878   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6879                                         inf->total_syscalls_count != 0,
6880                                         inf->any_syscall_count,
6881                                         VEC_length (int, inf->syscalls_counts),
6882                                         VEC_address (int,
6883                                                      inf->syscalls_counts));
6884 }
6885
6886 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
6887    catchpoints.  */
6888
6889 static int
6890 breakpoint_hit_catch_syscall (const struct bp_location *bl,
6891                               struct address_space *aspace, CORE_ADDR bp_addr,
6892                               const struct target_waitstatus *ws)
6893 {
6894   /* We must check if we are catching specific syscalls in this
6895      breakpoint.  If we are, then we must guarantee that the called
6896      syscall is the same syscall we are catching.  */
6897   int syscall_number = 0;
6898   const struct syscall_catchpoint *c
6899     = (const struct syscall_catchpoint *) bl->owner;
6900
6901   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
6902       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
6903     return 0;
6904
6905   syscall_number = ws->value.syscall_number;
6906
6907   /* Now, checking if the syscall is the same.  */
6908   if (c->syscalls_to_be_caught)
6909     {
6910       int i, iter;
6911
6912       for (i = 0;
6913            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6914            i++)
6915         if (syscall_number == iter)
6916           break;
6917       /* Not the same.  */
6918       if (!iter)
6919         return 0;
6920     }
6921
6922   return 1;
6923 }
6924
6925 /* Implement the "print_it" breakpoint_ops method for syscall
6926    catchpoints.  */
6927
6928 static enum print_stop_action
6929 print_it_catch_syscall (bpstat bs)
6930 {
6931   struct ui_out *uiout = current_uiout;
6932   struct breakpoint *b = bs->breakpoint_at;
6933   /* These are needed because we want to know in which state a
6934      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
6935      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
6936      must print "called syscall" or "returned from syscall".  */
6937   ptid_t ptid;
6938   struct target_waitstatus last;
6939   struct syscall s;
6940   char *syscall_id;
6941
6942   get_last_target_status (&ptid, &last);
6943
6944   get_syscall_by_number (last.value.syscall_number, &s);
6945
6946   annotate_catchpoint (b->number);
6947
6948   if (b->disposition == disp_del)
6949     ui_out_text (uiout, "\nTemporary catchpoint ");
6950   else
6951     ui_out_text (uiout, "\nCatchpoint ");
6952   if (ui_out_is_mi_like_p (uiout))
6953     {
6954       ui_out_field_string (uiout, "reason",
6955                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
6956                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
6957                                                 : EXEC_ASYNC_SYSCALL_RETURN));
6958       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6959     }
6960   ui_out_field_int (uiout, "bkptno", b->number);
6961
6962   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
6963     ui_out_text (uiout, " (call to syscall ");
6964   else
6965     ui_out_text (uiout, " (returned from syscall ");
6966
6967   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
6968     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
6969   if (s.name != NULL)
6970     ui_out_field_string (uiout, "syscall-name", s.name);
6971
6972   ui_out_text (uiout, "), ");
6973
6974   return PRINT_SRC_AND_LOC;
6975 }
6976
6977 /* Implement the "print_one" breakpoint_ops method for syscall
6978    catchpoints.  */
6979
6980 static void
6981 print_one_catch_syscall (struct breakpoint *b,
6982                          struct bp_location **last_loc)
6983 {
6984   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6985   struct value_print_options opts;
6986   struct ui_out *uiout = current_uiout;
6987
6988   get_user_print_options (&opts);
6989   /* Field 4, the address, is omitted (which makes the columns not
6990      line up too nicely with the headers, but the effect is relatively
6991      readable).  */
6992   if (opts.addressprint)
6993     ui_out_field_skip (uiout, "addr");
6994   annotate_field (5);
6995
6996   if (c->syscalls_to_be_caught
6997       && VEC_length (int, c->syscalls_to_be_caught) > 1)
6998     ui_out_text (uiout, "syscalls \"");
6999   else
7000     ui_out_text (uiout, "syscall \"");
7001
7002   if (c->syscalls_to_be_caught)
7003     {
7004       int i, iter;
7005       char *text = xstrprintf ("%s", "");
7006
7007       for (i = 0;
7008            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7009            i++)
7010         {
7011           char *x = text;
7012           struct syscall s;
7013           get_syscall_by_number (iter, &s);
7014
7015           if (s.name != NULL)
7016             text = xstrprintf ("%s%s, ", text, s.name);
7017           else
7018             text = xstrprintf ("%s%d, ", text, iter);
7019
7020           /* We have to xfree the last 'text' (now stored at 'x')
7021              because xstrprintf dynamically allocates new space for it
7022              on every call.  */
7023           xfree (x);
7024         }
7025       /* Remove the last comma.  */
7026       text[strlen (text) - 2] = '\0';
7027       ui_out_field_string (uiout, "what", text);
7028     }
7029   else
7030     ui_out_field_string (uiout, "what", "<any syscall>");
7031   ui_out_text (uiout, "\" ");
7032 }
7033
7034 /* Implement the "print_mention" breakpoint_ops method for syscall
7035    catchpoints.  */
7036
7037 static void
7038 print_mention_catch_syscall (struct breakpoint *b)
7039 {
7040   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7041
7042   if (c->syscalls_to_be_caught)
7043     {
7044       int i, iter;
7045
7046       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7047         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7048       else
7049         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7050
7051       for (i = 0;
7052            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7053            i++)
7054         {
7055           struct syscall s;
7056           get_syscall_by_number (iter, &s);
7057
7058           if (s.name)
7059             printf_filtered (" '%s' [%d]", s.name, s.number);
7060           else
7061             printf_filtered (" %d", s.number);
7062         }
7063       printf_filtered (")");
7064     }
7065   else
7066     printf_filtered (_("Catchpoint %d (any syscall)"),
7067                      b->number);
7068 }
7069
7070 /* Implement the "print_recreate" breakpoint_ops method for syscall
7071    catchpoints.  */
7072
7073 static void
7074 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7075 {
7076   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7077
7078   fprintf_unfiltered (fp, "catch syscall");
7079
7080   if (c->syscalls_to_be_caught)
7081     {
7082       int i, iter;
7083
7084       for (i = 0;
7085            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7086            i++)
7087         {
7088           struct syscall s;
7089
7090           get_syscall_by_number (iter, &s);
7091           if (s.name)
7092             fprintf_unfiltered (fp, " %s", s.name);
7093           else
7094             fprintf_unfiltered (fp, " %d", s.number);
7095         }
7096     }
7097   print_recreate_thread (b, fp);
7098 }
7099
7100 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
7101
7102 static struct breakpoint_ops catch_syscall_breakpoint_ops;
7103
7104 /* Returns non-zero if 'b' is a syscall catchpoint.  */
7105
7106 static int
7107 syscall_catchpoint_p (struct breakpoint *b)
7108 {
7109   return (b->ops == &catch_syscall_breakpoint_ops);
7110 }
7111
7112 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
7113    is non-zero, then make the breakpoint temporary.  If COND_STRING is
7114    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
7115    the breakpoint_ops structure associated to the catchpoint.  */
7116
7117 static void
7118 init_catchpoint (struct breakpoint *b,
7119                  struct gdbarch *gdbarch, int tempflag,
7120                  char *cond_string,
7121                  const struct breakpoint_ops *ops)
7122 {
7123   struct symtab_and_line sal;
7124
7125   init_sal (&sal);
7126   sal.pspace = current_program_space;
7127
7128   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7129
7130   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
7131   b->disposition = tempflag ? disp_del : disp_donttouch;
7132 }
7133
7134 void
7135 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
7136 {
7137   add_to_breakpoint_chain (b);
7138   set_breakpoint_number (internal, b);
7139   if (!internal)
7140     mention (b);
7141   observer_notify_breakpoint_created (b);
7142
7143   if (update_gll)
7144     update_global_location_list (1);
7145 }
7146
7147 static void
7148 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
7149                                     int tempflag, char *cond_string,
7150                                     const struct breakpoint_ops *ops)
7151 {
7152   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
7153
7154   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
7155
7156   c->forked_inferior_pid = null_ptid;
7157
7158   install_breakpoint (0, &c->base, 1);
7159 }
7160
7161 /* Exec catchpoints.  */
7162
7163 /* An instance of this type is used to represent an exec catchpoint.
7164    It includes a "struct breakpoint" as a kind of base class; users
7165    downcast to "struct breakpoint *" when needed.  A breakpoint is
7166    really of this type iff its ops pointer points to
7167    CATCH_EXEC_BREAKPOINT_OPS.  */
7168
7169 struct exec_catchpoint
7170 {
7171   /* The base class.  */
7172   struct breakpoint base;
7173
7174   /* Filename of a program whose exec triggered this catchpoint.
7175      This field is only valid immediately after this catchpoint has
7176      triggered.  */
7177   char *exec_pathname;
7178 };
7179
7180 /* Implement the "dtor" breakpoint_ops method for exec
7181    catchpoints.  */
7182
7183 static void
7184 dtor_catch_exec (struct breakpoint *b)
7185 {
7186   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7187
7188   xfree (c->exec_pathname);
7189
7190   base_breakpoint_ops.dtor (b);
7191 }
7192
7193 static int
7194 insert_catch_exec (struct bp_location *bl)
7195 {
7196   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
7197 }
7198
7199 static int
7200 remove_catch_exec (struct bp_location *bl)
7201 {
7202   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
7203 }
7204
7205 static int
7206 breakpoint_hit_catch_exec (const struct bp_location *bl,
7207                            struct address_space *aspace, CORE_ADDR bp_addr,
7208                            const struct target_waitstatus *ws)
7209 {
7210   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
7211
7212   if (ws->kind != TARGET_WAITKIND_EXECD)
7213     return 0;
7214
7215   c->exec_pathname = xstrdup (ws->value.execd_pathname);
7216   return 1;
7217 }
7218
7219 static enum print_stop_action
7220 print_it_catch_exec (bpstat bs)
7221 {
7222   struct ui_out *uiout = current_uiout;
7223   struct breakpoint *b = bs->breakpoint_at;
7224   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7225
7226   annotate_catchpoint (b->number);
7227   if (b->disposition == disp_del)
7228     ui_out_text (uiout, "\nTemporary catchpoint ");
7229   else
7230     ui_out_text (uiout, "\nCatchpoint ");
7231   if (ui_out_is_mi_like_p (uiout))
7232     {
7233       ui_out_field_string (uiout, "reason",
7234                            async_reason_lookup (EXEC_ASYNC_EXEC));
7235       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7236     }
7237   ui_out_field_int (uiout, "bkptno", b->number);
7238   ui_out_text (uiout, " (exec'd ");
7239   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
7240   ui_out_text (uiout, "), ");
7241
7242   return PRINT_SRC_AND_LOC;
7243 }
7244
7245 static void
7246 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
7247 {
7248   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7249   struct value_print_options opts;
7250   struct ui_out *uiout = current_uiout;
7251
7252   get_user_print_options (&opts);
7253
7254   /* Field 4, the address, is omitted (which makes the columns
7255      not line up too nicely with the headers, but the effect
7256      is relatively readable).  */
7257   if (opts.addressprint)
7258     ui_out_field_skip (uiout, "addr");
7259   annotate_field (5);
7260   ui_out_text (uiout, "exec");
7261   if (c->exec_pathname != NULL)
7262     {
7263       ui_out_text (uiout, ", program \"");
7264       ui_out_field_string (uiout, "what", c->exec_pathname);
7265       ui_out_text (uiout, "\" ");
7266     }
7267 }
7268
7269 static void
7270 print_mention_catch_exec (struct breakpoint *b)
7271 {
7272   printf_filtered (_("Catchpoint %d (exec)"), b->number);
7273 }
7274
7275 /* Implement the "print_recreate" breakpoint_ops method for exec
7276    catchpoints.  */
7277
7278 static void
7279 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
7280 {
7281   fprintf_unfiltered (fp, "catch exec");
7282   print_recreate_thread (b, fp);
7283 }
7284
7285 static struct breakpoint_ops catch_exec_breakpoint_ops;
7286
7287 static void
7288 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
7289                                  const struct breakpoint_ops *ops)
7290 {
7291   struct syscall_catchpoint *c;
7292   struct gdbarch *gdbarch = get_current_arch ();
7293
7294   c = XNEW (struct syscall_catchpoint);
7295   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
7296   c->syscalls_to_be_caught = filter;
7297
7298   install_breakpoint (0, &c->base, 1);
7299 }
7300
7301 static int
7302 hw_breakpoint_used_count (void)
7303 {
7304   int i = 0;
7305   struct breakpoint *b;
7306   struct bp_location *bl;
7307
7308   ALL_BREAKPOINTS (b)
7309   {
7310     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
7311       for (bl = b->loc; bl; bl = bl->next)
7312         {
7313           /* Special types of hardware breakpoints may use more than
7314              one register.  */
7315           i += b->ops->resources_needed (bl);
7316         }
7317   }
7318
7319   return i;
7320 }
7321
7322 /* Returns the resources B would use if it were a hardware
7323    watchpoint.  */
7324
7325 static int
7326 hw_watchpoint_use_count (struct breakpoint *b)
7327 {
7328   int i = 0;
7329   struct bp_location *bl;
7330
7331   if (!breakpoint_enabled (b))
7332     return 0;
7333
7334   for (bl = b->loc; bl; bl = bl->next)
7335     {
7336       /* Special types of hardware watchpoints may use more than
7337          one register.  */
7338       i += b->ops->resources_needed (bl);
7339     }
7340
7341   return i;
7342 }
7343
7344 /* Returns the sum the used resources of all hardware watchpoints of
7345    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
7346    the sum of the used resources of all hardware watchpoints of other
7347    types _not_ TYPE.  */
7348
7349 static int
7350 hw_watchpoint_used_count_others (struct breakpoint *except,
7351                                  enum bptype type, int *other_type_used)
7352 {
7353   int i = 0;
7354   struct breakpoint *b;
7355
7356   *other_type_used = 0;
7357   ALL_BREAKPOINTS (b)
7358     {
7359       if (b == except)
7360         continue;
7361       if (!breakpoint_enabled (b))
7362         continue;
7363
7364       if (b->type == type)
7365         i += hw_watchpoint_use_count (b);
7366       else if (is_hardware_watchpoint (b))
7367         *other_type_used = 1;
7368     }
7369
7370   return i;
7371 }
7372
7373 void
7374 disable_watchpoints_before_interactive_call_start (void)
7375 {
7376   struct breakpoint *b;
7377
7378   ALL_BREAKPOINTS (b)
7379   {
7380     if (is_watchpoint (b) && breakpoint_enabled (b))
7381       {
7382         b->enable_state = bp_call_disabled;
7383         update_global_location_list (0);
7384       }
7385   }
7386 }
7387
7388 void
7389 enable_watchpoints_after_interactive_call_stop (void)
7390 {
7391   struct breakpoint *b;
7392
7393   ALL_BREAKPOINTS (b)
7394   {
7395     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
7396       {
7397         b->enable_state = bp_enabled;
7398         update_global_location_list (1);
7399       }
7400   }
7401 }
7402
7403 void
7404 disable_breakpoints_before_startup (void)
7405 {
7406   current_program_space->executing_startup = 1;
7407   update_global_location_list (0);
7408 }
7409
7410 void
7411 enable_breakpoints_after_startup (void)
7412 {
7413   current_program_space->executing_startup = 0;
7414   breakpoint_re_set ();
7415 }
7416
7417
7418 /* Set a breakpoint that will evaporate an end of command
7419    at address specified by SAL.
7420    Restrict it to frame FRAME if FRAME is nonzero.  */
7421
7422 struct breakpoint *
7423 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
7424                           struct frame_id frame_id, enum bptype type)
7425 {
7426   struct breakpoint *b;
7427
7428   /* If FRAME_ID is valid, it should be a real frame, not an inlined
7429      one.  */
7430   gdb_assert (!frame_id_inlined_p (frame_id));
7431
7432   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
7433   b->enable_state = bp_enabled;
7434   b->disposition = disp_donttouch;
7435   b->frame_id = frame_id;
7436
7437   /* If we're debugging a multi-threaded program, then we want
7438      momentary breakpoints to be active in only a single thread of
7439      control.  */
7440   if (in_thread_list (inferior_ptid))
7441     b->thread = pid_to_thread_id (inferior_ptid);
7442
7443   update_global_location_list_nothrow (1);
7444
7445   return b;
7446 }
7447
7448 /* Make a momentary breakpoint based on the master breakpoint ORIG.
7449    The new breakpoint will have type TYPE, and use OPS as it
7450    breakpoint_ops.  */
7451
7452 static struct breakpoint *
7453 momentary_breakpoint_from_master (struct breakpoint *orig,
7454                                   enum bptype type,
7455                                   const struct breakpoint_ops *ops)
7456 {
7457   struct breakpoint *copy;
7458
7459   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
7460   copy->loc = allocate_bp_location (copy);
7461   set_breakpoint_location_function (copy->loc, 1);
7462
7463   copy->loc->gdbarch = orig->loc->gdbarch;
7464   copy->loc->requested_address = orig->loc->requested_address;
7465   copy->loc->address = orig->loc->address;
7466   copy->loc->section = orig->loc->section;
7467   copy->loc->pspace = orig->loc->pspace;
7468
7469   if (orig->loc->source_file != NULL)
7470     copy->loc->source_file = xstrdup (orig->loc->source_file);
7471
7472   copy->loc->line_number = orig->loc->line_number;
7473   copy->frame_id = orig->frame_id;
7474   copy->thread = orig->thread;
7475   copy->pspace = orig->pspace;
7476
7477   copy->enable_state = bp_enabled;
7478   copy->disposition = disp_donttouch;
7479   copy->number = internal_breakpoint_number--;
7480
7481   update_global_location_list_nothrow (0);
7482   return copy;
7483 }
7484
7485 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
7486    ORIG is NULL.  */
7487
7488 struct breakpoint *
7489 clone_momentary_breakpoint (struct breakpoint *orig)
7490 {
7491   /* If there's nothing to clone, then return nothing.  */
7492   if (orig == NULL)
7493     return NULL;
7494
7495   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
7496 }
7497
7498 struct breakpoint *
7499 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
7500                                 enum bptype type)
7501 {
7502   struct symtab_and_line sal;
7503
7504   sal = find_pc_line (pc, 0);
7505   sal.pc = pc;
7506   sal.section = find_pc_overlay (pc);
7507   sal.explicit_pc = 1;
7508
7509   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
7510 }
7511 \f
7512
7513 /* Tell the user we have just set a breakpoint B.  */
7514
7515 static void
7516 mention (struct breakpoint *b)
7517 {
7518   b->ops->print_mention (b);
7519   if (ui_out_is_mi_like_p (current_uiout))
7520     return;
7521   printf_filtered ("\n");
7522 }
7523 \f
7524
7525 static struct bp_location *
7526 add_location_to_breakpoint (struct breakpoint *b,
7527                             const struct symtab_and_line *sal)
7528 {
7529   struct bp_location *loc, **tmp;
7530   CORE_ADDR adjusted_address;
7531   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
7532
7533   if (loc_gdbarch == NULL)
7534     loc_gdbarch = b->gdbarch;
7535
7536   /* Adjust the breakpoint's address prior to allocating a location.
7537      Once we call allocate_bp_location(), that mostly uninitialized
7538      location will be placed on the location chain.  Adjustment of the
7539      breakpoint may cause target_read_memory() to be called and we do
7540      not want its scan of the location chain to find a breakpoint and
7541      location that's only been partially initialized.  */
7542   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
7543                                                 sal->pc, b->type);
7544
7545   loc = allocate_bp_location (b);
7546   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
7547     ;
7548   *tmp = loc;
7549
7550   loc->requested_address = sal->pc;
7551   loc->address = adjusted_address;
7552   loc->pspace = sal->pspace;
7553   gdb_assert (loc->pspace != NULL);
7554   loc->section = sal->section;
7555   loc->gdbarch = loc_gdbarch;
7556
7557   if (sal->symtab != NULL)
7558     loc->source_file = xstrdup (sal->symtab->filename);
7559   loc->line_number = sal->line;
7560
7561   set_breakpoint_location_function (loc,
7562                                     sal->explicit_pc || sal->explicit_line);
7563   return loc;
7564 }
7565 \f
7566
7567 /* Return 1 if LOC is pointing to a permanent breakpoint, 
7568    return 0 otherwise.  */
7569
7570 static int
7571 bp_loc_is_permanent (struct bp_location *loc)
7572 {
7573   int len;
7574   CORE_ADDR addr;
7575   const gdb_byte *bpoint;
7576   gdb_byte *target_mem;
7577   struct cleanup *cleanup;
7578   int retval = 0;
7579
7580   gdb_assert (loc != NULL);
7581
7582   addr = loc->address;
7583   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
7584
7585   /* Software breakpoints unsupported?  */
7586   if (bpoint == NULL)
7587     return 0;
7588
7589   target_mem = alloca (len);
7590
7591   /* Enable the automatic memory restoration from breakpoints while
7592      we read the memory.  Otherwise we could say about our temporary
7593      breakpoints they are permanent.  */
7594   cleanup = save_current_space_and_thread ();
7595
7596   switch_to_program_space_and_thread (loc->pspace);
7597   make_show_memory_breakpoints_cleanup (0);
7598
7599   if (target_read_memory (loc->address, target_mem, len) == 0
7600       && memcmp (target_mem, bpoint, len) == 0)
7601     retval = 1;
7602
7603   do_cleanups (cleanup);
7604
7605   return retval;
7606 }
7607
7608
7609
7610 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
7611    as textual description of the location, and COND_STRING
7612    as condition expression.  */
7613
7614 static void
7615 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
7616                      struct symtabs_and_lines sals, char *addr_string,
7617                      char *filter, char *cond_string,
7618                      enum bptype type, enum bpdisp disposition,
7619                      int thread, int task, int ignore_count,
7620                      const struct breakpoint_ops *ops, int from_tty,
7621                      int enabled, int internal, int display_canonical)
7622 {
7623   int i;
7624
7625   if (type == bp_hardware_breakpoint)
7626     {
7627       int target_resources_ok;
7628
7629       i = hw_breakpoint_used_count ();
7630       target_resources_ok =
7631         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
7632                                             i + 1, 0);
7633       if (target_resources_ok == 0)
7634         error (_("No hardware breakpoint support in the target."));
7635       else if (target_resources_ok < 0)
7636         error (_("Hardware breakpoints used exceeds limit."));
7637     }
7638
7639   gdb_assert (sals.nelts > 0);
7640
7641   for (i = 0; i < sals.nelts; ++i)
7642     {
7643       struct symtab_and_line sal = sals.sals[i];
7644       struct bp_location *loc;
7645
7646       if (from_tty)
7647         {
7648           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
7649           if (!loc_gdbarch)
7650             loc_gdbarch = gdbarch;
7651
7652           describe_other_breakpoints (loc_gdbarch,
7653                                       sal.pspace, sal.pc, sal.section, thread);
7654         }
7655
7656       if (i == 0)
7657         {
7658           init_raw_breakpoint (b, gdbarch, sal, type, ops);
7659           b->thread = thread;
7660           b->task = task;
7661   
7662           b->cond_string = cond_string;
7663           b->ignore_count = ignore_count;
7664           b->enable_state = enabled ? bp_enabled : bp_disabled;
7665           b->disposition = disposition;
7666
7667           if (type == bp_static_tracepoint)
7668             {
7669               struct tracepoint *t = (struct tracepoint *) b;
7670               struct static_tracepoint_marker marker;
7671
7672               if (strace_marker_p (b))
7673                 {
7674                   /* We already know the marker exists, otherwise, we
7675                      wouldn't see a sal for it.  */
7676                   char *p = &addr_string[3];
7677                   char *endp;
7678                   char *marker_str;
7679
7680                   p = skip_spaces (p);
7681
7682                   endp = skip_to_space (p);
7683
7684                   marker_str = savestring (p, endp - p);
7685                   t->static_trace_marker_id = marker_str;
7686
7687                   printf_filtered (_("Probed static tracepoint "
7688                                      "marker \"%s\"\n"),
7689                                    t->static_trace_marker_id);
7690                 }
7691               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
7692                 {
7693                   t->static_trace_marker_id = xstrdup (marker.str_id);
7694                   release_static_tracepoint_marker (&marker);
7695
7696                   printf_filtered (_("Probed static tracepoint "
7697                                      "marker \"%s\"\n"),
7698                                    t->static_trace_marker_id);
7699                 }
7700               else
7701                 warning (_("Couldn't determine the static "
7702                            "tracepoint marker to probe"));
7703             }
7704
7705           loc = b->loc;
7706         }
7707       else
7708         {
7709           loc = add_location_to_breakpoint (b, &sal);
7710         }
7711
7712       if (bp_loc_is_permanent (loc))
7713         make_breakpoint_permanent (b);
7714
7715       if (b->cond_string)
7716         {
7717           char *arg = b->cond_string;
7718           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
7719           if (*arg)
7720               error (_("Garbage %s follows condition"), arg);
7721         }
7722     }   
7723
7724   b->display_canonical = display_canonical;
7725   if (addr_string)
7726     b->addr_string = addr_string;
7727   else
7728     /* addr_string has to be used or breakpoint_re_set will delete
7729        me.  */
7730     b->addr_string
7731       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7732   b->filter = filter;
7733 }
7734
7735 static void
7736 create_breakpoint_sal (struct gdbarch *gdbarch,
7737                        struct symtabs_and_lines sals, char *addr_string,
7738                        char *filter, char *cond_string,
7739                        enum bptype type, enum bpdisp disposition,
7740                        int thread, int task, int ignore_count,
7741                        const struct breakpoint_ops *ops, int from_tty,
7742                        int enabled, int internal, int display_canonical)
7743 {
7744   struct breakpoint *b;
7745   struct cleanup *old_chain;
7746
7747   if (is_tracepoint_type (type))
7748     {
7749       struct tracepoint *t;
7750
7751       t = XCNEW (struct tracepoint);
7752       b = &t->base;
7753     }
7754   else
7755     b = XNEW (struct breakpoint);
7756
7757   old_chain = make_cleanup (xfree, b);
7758
7759   init_breakpoint_sal (b, gdbarch,
7760                        sals, addr_string,
7761                        filter, cond_string,
7762                        type, disposition,
7763                        thread, task, ignore_count,
7764                        ops, from_tty,
7765                        enabled, internal, display_canonical);
7766   discard_cleanups (old_chain);
7767
7768   install_breakpoint (internal, b, 0);
7769 }
7770
7771 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
7772    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
7773    value.  COND_STRING, if not NULL, specified the condition to be
7774    used for all breakpoints.  Essentially the only case where
7775    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
7776    function.  In that case, it's still not possible to specify
7777    separate conditions for different overloaded functions, so
7778    we take just a single condition string.
7779    
7780    NOTE: If the function succeeds, the caller is expected to cleanup
7781    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
7782    array contents).  If the function fails (error() is called), the
7783    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
7784    COND and SALS arrays and each of those arrays contents.  */
7785
7786 static void
7787 create_breakpoints_sal (struct gdbarch *gdbarch,
7788                         struct linespec_result *canonical,
7789                         char *cond_string,
7790                         enum bptype type, enum bpdisp disposition,
7791                         int thread, int task, int ignore_count,
7792                         const struct breakpoint_ops *ops, int from_tty,
7793                         int enabled, int internal)
7794 {
7795   int i;
7796   struct linespec_sals *lsal;
7797
7798   if (canonical->pre_expanded)
7799     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
7800
7801   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
7802     {
7803       /* Note that 'addr_string' can be NULL in the case of a plain
7804          'break', without arguments.  */
7805       char *addr_string = (canonical->addr_string
7806                            ? xstrdup (canonical->addr_string)
7807                            : NULL);
7808       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
7809       struct cleanup *inner = make_cleanup (xfree, addr_string);
7810
7811       make_cleanup (xfree, filter_string);
7812       create_breakpoint_sal (gdbarch, lsal->sals,
7813                              addr_string,
7814                              filter_string,
7815                              cond_string, type, disposition,
7816                              thread, task, ignore_count, ops,
7817                              from_tty, enabled, internal,
7818                              canonical->special_display);
7819       discard_cleanups (inner);
7820     }
7821 }
7822
7823 /* Parse ADDRESS which is assumed to be a SAL specification possibly
7824    followed by conditionals.  On return, SALS contains an array of SAL
7825    addresses found.  ADDR_STRING contains a vector of (canonical)
7826    address strings.  ADDRESS points to the end of the SAL.
7827
7828    The array and the line spec strings are allocated on the heap, it is
7829    the caller's responsibility to free them.  */
7830
7831 static void
7832 parse_breakpoint_sals (char **address,
7833                        struct linespec_result *canonical)
7834 {
7835   char *addr_start = *address;
7836
7837   /* If no arg given, or if first arg is 'if ', use the default
7838      breakpoint.  */
7839   if ((*address) == NULL
7840       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
7841     {
7842       /* The last displayed codepoint, if it's valid, is our default breakpoint
7843          address.  */
7844       if (last_displayed_sal_is_valid ())
7845         {
7846           struct linespec_sals lsal;
7847           struct symtab_and_line sal;
7848
7849           init_sal (&sal);              /* Initialize to zeroes.  */
7850           lsal.sals.sals = (struct symtab_and_line *)
7851             xmalloc (sizeof (struct symtab_and_line));
7852
7853           /* Set sal's pspace, pc, symtab, and line to the values
7854              corresponding to the last call to print_frame_info.  */
7855           get_last_displayed_sal (&sal);
7856           sal.section = find_pc_overlay (sal.pc);
7857
7858           /* "break" without arguments is equivalent to "break *PC"
7859              where PC is the last displayed codepoint's address.  So
7860              make sure to set sal.explicit_pc to prevent GDB from
7861              trying to expand the list of sals to include all other
7862              instances with the same symtab and line.  */
7863           sal.explicit_pc = 1;
7864
7865           lsal.sals.sals[0] = sal;
7866           lsal.sals.nelts = 1;
7867           lsal.canonical = NULL;
7868
7869           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
7870         }
7871       else
7872         error (_("No default breakpoint address now."));
7873     }
7874   else
7875     {
7876       /* Force almost all breakpoints to be in terms of the
7877          current_source_symtab (which is decode_line_1's default).
7878          This should produce the results we want almost all of the
7879          time while leaving default_breakpoint_* alone.  */
7880       if (last_displayed_sal_is_valid ())
7881         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
7882                           get_last_displayed_symtab (),
7883                           get_last_displayed_line (),
7884                           canonical, NULL, NULL);
7885       else
7886         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
7887                           (struct symtab *) NULL, 0,
7888                           canonical, NULL, NULL);
7889     }
7890 }
7891
7892
7893 /* Convert each SAL into a real PC.  Verify that the PC can be
7894    inserted as a breakpoint.  If it can't throw an error.  */
7895
7896 static void
7897 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
7898 {    
7899   int i;
7900
7901   for (i = 0; i < sals->nelts; i++)
7902     resolve_sal_pc (&sals->sals[i]);
7903 }
7904
7905 /* Fast tracepoints may have restrictions on valid locations.  For
7906    instance, a fast tracepoint using a jump instead of a trap will
7907    likely have to overwrite more bytes than a trap would, and so can
7908    only be placed where the instruction is longer than the jump, or a
7909    multi-instruction sequence does not have a jump into the middle of
7910    it, etc.  */
7911
7912 static void
7913 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
7914                             struct symtabs_and_lines *sals)
7915 {
7916   int i, rslt;
7917   struct symtab_and_line *sal;
7918   char *msg;
7919   struct cleanup *old_chain;
7920
7921   for (i = 0; i < sals->nelts; i++)
7922     {
7923       struct gdbarch *sarch;
7924
7925       sal = &sals->sals[i];
7926
7927       sarch = get_sal_arch (*sal);
7928       /* We fall back to GDBARCH if there is no architecture
7929          associated with SAL.  */
7930       if (sarch == NULL)
7931         sarch = gdbarch;
7932       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
7933                                                NULL, &msg);
7934       old_chain = make_cleanup (xfree, msg);
7935
7936       if (!rslt)
7937         error (_("May not have a fast tracepoint at 0x%s%s"),
7938                paddress (sarch, sal->pc), (msg ? msg : ""));
7939
7940       do_cleanups (old_chain);
7941     }
7942 }
7943
7944 /* Given TOK, a string specification of condition and thread, as
7945    accepted by the 'break' command, extract the condition
7946    string and thread number and set *COND_STRING and *THREAD.
7947    PC identifies the context at which the condition should be parsed.
7948    If no condition is found, *COND_STRING is set to NULL.
7949    If no thread is found, *THREAD is set to -1.  */
7950 static void 
7951 find_condition_and_thread (char *tok, CORE_ADDR pc, 
7952                            char **cond_string, int *thread, int *task)
7953 {
7954   *cond_string = NULL;
7955   *thread = -1;
7956   while (tok && *tok)
7957     {
7958       char *end_tok;
7959       int toklen;
7960       char *cond_start = NULL;
7961       char *cond_end = NULL;
7962
7963       tok = skip_spaces (tok);
7964       
7965       end_tok = skip_to_space (tok);
7966       
7967       toklen = end_tok - tok;
7968       
7969       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
7970         {
7971           struct expression *expr;
7972
7973           tok = cond_start = end_tok + 1;
7974           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
7975           xfree (expr);
7976           cond_end = tok;
7977           *cond_string = savestring (cond_start, 
7978                                      cond_end - cond_start);
7979         }
7980       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
7981         {
7982           char *tmptok;
7983           
7984           tok = end_tok + 1;
7985           tmptok = tok;
7986           *thread = strtol (tok, &tok, 0);
7987           if (tok == tmptok)
7988             error (_("Junk after thread keyword."));
7989           if (!valid_thread_id (*thread))
7990             error (_("Unknown thread %d."), *thread);
7991         }
7992       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
7993         {
7994           char *tmptok;
7995
7996           tok = end_tok + 1;
7997           tmptok = tok;
7998           *task = strtol (tok, &tok, 0);
7999           if (tok == tmptok)
8000             error (_("Junk after task keyword."));
8001           if (!valid_task_id (*task))
8002             error (_("Unknown task %d."), *task);
8003         }
8004       else
8005         error (_("Junk at end of arguments."));
8006     }
8007 }
8008
8009 /* Decode a static tracepoint marker spec.  */
8010
8011 static struct symtabs_and_lines
8012 decode_static_tracepoint_spec (char **arg_p)
8013 {
8014   VEC(static_tracepoint_marker_p) *markers = NULL;
8015   struct symtabs_and_lines sals;
8016   struct symtab_and_line sal;
8017   struct symbol *sym;
8018   struct cleanup *old_chain;
8019   char *p = &(*arg_p)[3];
8020   char *endp;
8021   char *marker_str;
8022   int i;
8023
8024   p = skip_spaces (p);
8025
8026   endp = skip_to_space (p);
8027
8028   marker_str = savestring (p, endp - p);
8029   old_chain = make_cleanup (xfree, marker_str);
8030
8031   markers = target_static_tracepoint_markers_by_strid (marker_str);
8032   if (VEC_empty(static_tracepoint_marker_p, markers))
8033     error (_("No known static tracepoint marker named %s"), marker_str);
8034
8035   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
8036   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
8037
8038   for (i = 0; i < sals.nelts; i++)
8039     {
8040       struct static_tracepoint_marker *marker;
8041
8042       marker = VEC_index (static_tracepoint_marker_p, markers, i);
8043
8044       init_sal (&sals.sals[i]);
8045
8046       sals.sals[i] = find_pc_line (marker->address, 0);
8047       sals.sals[i].pc = marker->address;
8048
8049       release_static_tracepoint_marker (marker);
8050     }
8051
8052   do_cleanups (old_chain);
8053
8054   *arg_p = endp;
8055   return sals;
8056 }
8057
8058 /* Set a breakpoint.  This function is shared between CLI and MI
8059    functions for setting a breakpoint.  This function has two major
8060    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
8061    parameter.  If non-zero, the function will parse arg, extracting
8062    breakpoint location, address and thread.  Otherwise, ARG is just
8063    the location of breakpoint, with condition and thread specified by
8064    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
8065    the breakpoint number will be allocated from the internal
8066    breakpoint count.  Returns true if any breakpoint was created;
8067    false otherwise.  */
8068
8069 int
8070 create_breakpoint (struct gdbarch *gdbarch,
8071                    char *arg, char *cond_string, int thread,
8072                    int parse_condition_and_thread,
8073                    int tempflag, enum bptype type_wanted,
8074                    int ignore_count,
8075                    enum auto_boolean pending_break_support,
8076                    const struct breakpoint_ops *ops,
8077                    int from_tty, int enabled, int internal)
8078 {
8079   volatile struct gdb_exception e;
8080   char *copy_arg = NULL;
8081   char *addr_start = arg;
8082   struct linespec_result canonical;
8083   struct cleanup *old_chain;
8084   struct cleanup *bkpt_chain = NULL;
8085   int i;
8086   int pending = 0;
8087   int task = 0;
8088   int prev_bkpt_count = breakpoint_count;
8089
8090   gdb_assert (ops != NULL);
8091
8092   init_linespec_result (&canonical);
8093
8094   TRY_CATCH (e, RETURN_MASK_ALL)
8095     {
8096       ops->create_sals_from_address (&arg, &canonical, type_wanted,
8097                                      addr_start, &copy_arg);
8098     }
8099
8100   /* If caller is interested in rc value from parse, set value.  */
8101   switch (e.reason)
8102     {
8103     case GDB_NO_ERROR:
8104       if (VEC_empty (linespec_sals, canonical.sals))
8105         return 0;
8106       break;
8107     case RETURN_ERROR:
8108       switch (e.error)
8109         {
8110         case NOT_FOUND_ERROR:
8111
8112           /* If pending breakpoint support is turned off, throw
8113              error.  */
8114
8115           if (pending_break_support == AUTO_BOOLEAN_FALSE)
8116             throw_exception (e);
8117
8118           exception_print (gdb_stderr, e);
8119
8120           /* If pending breakpoint support is auto query and the user
8121              selects no, then simply return the error code.  */
8122           if (pending_break_support == AUTO_BOOLEAN_AUTO
8123               && !nquery (_("Make %s pending on future shared library load? "),
8124                           bptype_string (type_wanted)))
8125             return 0;
8126
8127           /* At this point, either the user was queried about setting
8128              a pending breakpoint and selected yes, or pending
8129              breakpoint behavior is on and thus a pending breakpoint
8130              is defaulted on behalf of the user.  */
8131           {
8132             struct linespec_sals lsal;
8133
8134             copy_arg = xstrdup (addr_start);
8135             lsal.canonical = xstrdup (copy_arg);
8136             lsal.sals.nelts = 1;
8137             lsal.sals.sals = XNEW (struct symtab_and_line);
8138             init_sal (&lsal.sals.sals[0]);
8139             pending = 1;
8140             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
8141           }
8142           break;
8143         default:
8144           throw_exception (e);
8145         }
8146       break;
8147     default:
8148       throw_exception (e);
8149     }
8150
8151   /* Create a chain of things that always need to be cleaned up.  */
8152   old_chain = make_cleanup_destroy_linespec_result (&canonical);
8153
8154   /* ----------------------------- SNIP -----------------------------
8155      Anything added to the cleanup chain beyond this point is assumed
8156      to be part of a breakpoint.  If the breakpoint create succeeds
8157      then the memory is not reclaimed.  */
8158   bkpt_chain = make_cleanup (null_cleanup, 0);
8159
8160   /* Resolve all line numbers to PC's and verify that the addresses
8161      are ok for the target.  */
8162   if (!pending)
8163     {
8164       int ix;
8165       struct linespec_sals *iter;
8166
8167       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8168         breakpoint_sals_to_pc (&iter->sals);
8169     }
8170
8171   /* Fast tracepoints may have additional restrictions on location.  */
8172   if (!pending && type_wanted == bp_fast_tracepoint)
8173     {
8174       int ix;
8175       struct linespec_sals *iter;
8176
8177       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8178         check_fast_tracepoint_sals (gdbarch, &iter->sals);
8179     }
8180
8181   /* Verify that condition can be parsed, before setting any
8182      breakpoints.  Allocate a separate condition expression for each
8183      breakpoint.  */
8184   if (!pending)
8185     {
8186       struct linespec_sals *lsal;
8187
8188       lsal = VEC_index (linespec_sals, canonical.sals, 0);
8189
8190       if (parse_condition_and_thread)
8191         {
8192             /* Here we only parse 'arg' to separate condition
8193                from thread number, so parsing in context of first
8194                sal is OK.  When setting the breakpoint we'll 
8195                re-parse it in context of each sal.  */
8196             cond_string = NULL;
8197             thread = -1;
8198             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
8199                                        &thread, &task);
8200             if (cond_string)
8201                 make_cleanup (xfree, cond_string);
8202         }
8203       else
8204         {
8205             /* Create a private copy of condition string.  */
8206             if (cond_string)
8207             {
8208                 cond_string = xstrdup (cond_string);
8209                 make_cleanup (xfree, cond_string);
8210             }
8211         }
8212
8213       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
8214                                    cond_string, type_wanted,
8215                                    tempflag ? disp_del : disp_donttouch,
8216                                    thread, task, ignore_count, ops,
8217                                    from_tty, enabled, internal);
8218     }
8219   else
8220     {
8221       struct breakpoint *b;
8222
8223       make_cleanup (xfree, copy_arg);
8224
8225       if (is_tracepoint_type (type_wanted))
8226         {
8227           struct tracepoint *t;
8228
8229           t = XCNEW (struct tracepoint);
8230           b = &t->base;
8231         }
8232       else
8233         b = XNEW (struct breakpoint);
8234
8235       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
8236
8237       b->addr_string = copy_arg;
8238       b->cond_string = NULL;
8239       b->ignore_count = ignore_count;
8240       b->disposition = tempflag ? disp_del : disp_donttouch;
8241       b->condition_not_parsed = 1;
8242       b->enable_state = enabled ? bp_enabled : bp_disabled;
8243       if ((type_wanted != bp_breakpoint
8244            && type_wanted != bp_hardware_breakpoint) || thread != -1)
8245         b->pspace = current_program_space;
8246
8247       install_breakpoint (internal, b, 0);
8248     }
8249   
8250   if (VEC_length (linespec_sals, canonical.sals) > 1)
8251     {
8252       warning (_("Multiple breakpoints were set.\nUse the "
8253                  "\"delete\" command to delete unwanted breakpoints."));
8254       prev_breakpoint_count = prev_bkpt_count;
8255     }
8256
8257   /* That's it.  Discard the cleanups for data inserted into the
8258      breakpoint.  */
8259   discard_cleanups (bkpt_chain);
8260   /* But cleanup everything else.  */
8261   do_cleanups (old_chain);
8262
8263   /* error call may happen here - have BKPT_CHAIN already discarded.  */
8264   update_global_location_list (1);
8265
8266   return 1;
8267 }
8268
8269 /* Set a breakpoint.
8270    ARG is a string describing breakpoint address,
8271    condition, and thread.
8272    FLAG specifies if a breakpoint is hardware on,
8273    and if breakpoint is temporary, using BP_HARDWARE_FLAG
8274    and BP_TEMPFLAG.  */
8275
8276 static void
8277 break_command_1 (char *arg, int flag, int from_tty)
8278 {
8279   int tempflag = flag & BP_TEMPFLAG;
8280   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
8281                              ? bp_hardware_breakpoint
8282                              : bp_breakpoint);
8283
8284   create_breakpoint (get_current_arch (),
8285                      arg,
8286                      NULL, 0, 1 /* parse arg */,
8287                      tempflag, type_wanted,
8288                      0 /* Ignore count */,
8289                      pending_break_support,
8290                      &bkpt_breakpoint_ops,
8291                      from_tty,
8292                      1 /* enabled */,
8293                      0 /* internal */);
8294 }
8295
8296 /* Helper function for break_command_1 and disassemble_command.  */
8297
8298 void
8299 resolve_sal_pc (struct symtab_and_line *sal)
8300 {
8301   CORE_ADDR pc;
8302
8303   if (sal->pc == 0 && sal->symtab != NULL)
8304     {
8305       if (!find_line_pc (sal->symtab, sal->line, &pc))
8306         error (_("No line %d in file \"%s\"."),
8307                sal->line, sal->symtab->filename);
8308       sal->pc = pc;
8309
8310       /* If this SAL corresponds to a breakpoint inserted using a line
8311          number, then skip the function prologue if necessary.  */
8312       if (sal->explicit_line)
8313         skip_prologue_sal (sal);
8314     }
8315
8316   if (sal->section == 0 && sal->symtab != NULL)
8317     {
8318       struct blockvector *bv;
8319       struct block *b;
8320       struct symbol *sym;
8321
8322       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
8323       if (bv != NULL)
8324         {
8325           sym = block_linkage_function (b);
8326           if (sym != NULL)
8327             {
8328               fixup_symbol_section (sym, sal->symtab->objfile);
8329               sal->section = SYMBOL_OBJ_SECTION (sym);
8330             }
8331           else
8332             {
8333               /* It really is worthwhile to have the section, so we'll
8334                  just have to look harder. This case can be executed
8335                  if we have line numbers but no functions (as can
8336                  happen in assembly source).  */
8337
8338               struct minimal_symbol *msym;
8339               struct cleanup *old_chain = save_current_space_and_thread ();
8340
8341               switch_to_program_space_and_thread (sal->pspace);
8342
8343               msym = lookup_minimal_symbol_by_pc (sal->pc);
8344               if (msym)
8345                 sal->section = SYMBOL_OBJ_SECTION (msym);
8346
8347               do_cleanups (old_chain);
8348             }
8349         }
8350     }
8351 }
8352
8353 void
8354 break_command (char *arg, int from_tty)
8355 {
8356   break_command_1 (arg, 0, from_tty);
8357 }
8358
8359 void
8360 tbreak_command (char *arg, int from_tty)
8361 {
8362   break_command_1 (arg, BP_TEMPFLAG, from_tty);
8363 }
8364
8365 static void
8366 hbreak_command (char *arg, int from_tty)
8367 {
8368   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
8369 }
8370
8371 static void
8372 thbreak_command (char *arg, int from_tty)
8373 {
8374   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
8375 }
8376
8377 static void
8378 stop_command (char *arg, int from_tty)
8379 {
8380   printf_filtered (_("Specify the type of breakpoint to set.\n\
8381 Usage: stop in <function | address>\n\
8382        stop at <line>\n"));
8383 }
8384
8385 static void
8386 stopin_command (char *arg, int from_tty)
8387 {
8388   int badInput = 0;
8389
8390   if (arg == (char *) NULL)
8391     badInput = 1;
8392   else if (*arg != '*')
8393     {
8394       char *argptr = arg;
8395       int hasColon = 0;
8396
8397       /* Look for a ':'.  If this is a line number specification, then
8398          say it is bad, otherwise, it should be an address or
8399          function/method name.  */
8400       while (*argptr && !hasColon)
8401         {
8402           hasColon = (*argptr == ':');
8403           argptr++;
8404         }
8405
8406       if (hasColon)
8407         badInput = (*argptr != ':');    /* Not a class::method */
8408       else
8409         badInput = isdigit (*arg);      /* a simple line number */
8410     }
8411
8412   if (badInput)
8413     printf_filtered (_("Usage: stop in <function | address>\n"));
8414   else
8415     break_command_1 (arg, 0, from_tty);
8416 }
8417
8418 static void
8419 stopat_command (char *arg, int from_tty)
8420 {
8421   int badInput = 0;
8422
8423   if (arg == (char *) NULL || *arg == '*')      /* no line number */
8424     badInput = 1;
8425   else
8426     {
8427       char *argptr = arg;
8428       int hasColon = 0;
8429
8430       /* Look for a ':'.  If there is a '::' then get out, otherwise
8431          it is probably a line number.  */
8432       while (*argptr && !hasColon)
8433         {
8434           hasColon = (*argptr == ':');
8435           argptr++;
8436         }
8437
8438       if (hasColon)
8439         badInput = (*argptr == ':');    /* we have class::method */
8440       else
8441         badInput = !isdigit (*arg);     /* not a line number */
8442     }
8443
8444   if (badInput)
8445     printf_filtered (_("Usage: stop at <line>\n"));
8446   else
8447     break_command_1 (arg, 0, from_tty);
8448 }
8449
8450 /* Implement the "breakpoint_hit" breakpoint_ops method for
8451    ranged breakpoints.  */
8452
8453 static int
8454 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
8455                                   struct address_space *aspace,
8456                                   CORE_ADDR bp_addr,
8457                                   const struct target_waitstatus *ws)
8458 {
8459   if (ws->kind != TARGET_WAITKIND_STOPPED
8460       || ws->value.sig != TARGET_SIGNAL_TRAP)
8461     return 0;
8462
8463   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
8464                                          bl->length, aspace, bp_addr);
8465 }
8466
8467 /* Implement the "resources_needed" breakpoint_ops method for
8468    ranged breakpoints.  */
8469
8470 static int
8471 resources_needed_ranged_breakpoint (const struct bp_location *bl)
8472 {
8473   return target_ranged_break_num_registers ();
8474 }
8475
8476 /* Implement the "print_it" breakpoint_ops method for
8477    ranged breakpoints.  */
8478
8479 static enum print_stop_action
8480 print_it_ranged_breakpoint (bpstat bs)
8481 {
8482   struct breakpoint *b = bs->breakpoint_at;
8483   struct bp_location *bl = b->loc;
8484   struct ui_out *uiout = current_uiout;
8485
8486   gdb_assert (b->type == bp_hardware_breakpoint);
8487
8488   /* Ranged breakpoints have only one location.  */
8489   gdb_assert (bl && bl->next == NULL);
8490
8491   annotate_breakpoint (b->number);
8492   if (b->disposition == disp_del)
8493     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
8494   else
8495     ui_out_text (uiout, "\nRanged breakpoint ");
8496   if (ui_out_is_mi_like_p (uiout))
8497     {
8498       ui_out_field_string (uiout, "reason",
8499                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
8500       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8501     }
8502   ui_out_field_int (uiout, "bkptno", b->number);
8503   ui_out_text (uiout, ", ");
8504
8505   return PRINT_SRC_AND_LOC;
8506 }
8507
8508 /* Implement the "print_one" breakpoint_ops method for
8509    ranged breakpoints.  */
8510
8511 static void
8512 print_one_ranged_breakpoint (struct breakpoint *b,
8513                              struct bp_location **last_loc)
8514 {
8515   struct bp_location *bl = b->loc;
8516   struct value_print_options opts;
8517   struct ui_out *uiout = current_uiout;
8518
8519   /* Ranged breakpoints have only one location.  */
8520   gdb_assert (bl && bl->next == NULL);
8521
8522   get_user_print_options (&opts);
8523
8524   if (opts.addressprint)
8525     /* We don't print the address range here, it will be printed later
8526        by print_one_detail_ranged_breakpoint.  */
8527     ui_out_field_skip (uiout, "addr");
8528   annotate_field (5);
8529   print_breakpoint_location (b, bl);
8530   *last_loc = bl;
8531 }
8532
8533 /* Implement the "print_one_detail" breakpoint_ops method for
8534    ranged breakpoints.  */
8535
8536 static void
8537 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
8538                                     struct ui_out *uiout)
8539 {
8540   CORE_ADDR address_start, address_end;
8541   struct bp_location *bl = b->loc;
8542   struct ui_stream *stb = ui_out_stream_new (uiout);
8543   struct cleanup *cleanup = make_cleanup_ui_out_stream_delete (stb);
8544
8545   gdb_assert (bl);
8546
8547   address_start = bl->address;
8548   address_end = address_start + bl->length - 1;
8549
8550   ui_out_text (uiout, "\taddress range: ");
8551   fprintf_unfiltered (stb->stream, "[%s, %s]",
8552                       print_core_address (bl->gdbarch, address_start),
8553                       print_core_address (bl->gdbarch, address_end));
8554   ui_out_field_stream (uiout, "addr", stb);
8555   ui_out_text (uiout, "\n");
8556
8557   do_cleanups (cleanup);
8558 }
8559
8560 /* Implement the "print_mention" breakpoint_ops method for
8561    ranged breakpoints.  */
8562
8563 static void
8564 print_mention_ranged_breakpoint (struct breakpoint *b)
8565 {
8566   struct bp_location *bl = b->loc;
8567   struct ui_out *uiout = current_uiout;
8568
8569   gdb_assert (bl);
8570   gdb_assert (b->type == bp_hardware_breakpoint);
8571
8572   if (ui_out_is_mi_like_p (uiout))
8573     return;
8574
8575   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
8576                    b->number, paddress (bl->gdbarch, bl->address),
8577                    paddress (bl->gdbarch, bl->address + bl->length - 1));
8578 }
8579
8580 /* Implement the "print_recreate" breakpoint_ops method for
8581    ranged breakpoints.  */
8582
8583 static void
8584 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
8585 {
8586   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
8587                       b->addr_string_range_end);
8588   print_recreate_thread (b, fp);
8589 }
8590
8591 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
8592
8593 static struct breakpoint_ops ranged_breakpoint_ops;
8594
8595 /* Find the address where the end of the breakpoint range should be
8596    placed, given the SAL of the end of the range.  This is so that if
8597    the user provides a line number, the end of the range is set to the
8598    last instruction of the given line.  */
8599
8600 static CORE_ADDR
8601 find_breakpoint_range_end (struct symtab_and_line sal)
8602 {
8603   CORE_ADDR end;
8604
8605   /* If the user provided a PC value, use it.  Otherwise,
8606      find the address of the end of the given location.  */
8607   if (sal.explicit_pc)
8608     end = sal.pc;
8609   else
8610     {
8611       int ret;
8612       CORE_ADDR start;
8613
8614       ret = find_line_pc_range (sal, &start, &end);
8615       if (!ret)
8616         error (_("Could not find location of the end of the range."));
8617
8618       /* find_line_pc_range returns the start of the next line.  */
8619       end--;
8620     }
8621
8622   return end;
8623 }
8624
8625 /* Implement the "break-range" CLI command.  */
8626
8627 static void
8628 break_range_command (char *arg, int from_tty)
8629 {
8630   char *arg_start, *addr_string_start, *addr_string_end;
8631   struct linespec_result canonical_start, canonical_end;
8632   int bp_count, can_use_bp, length;
8633   CORE_ADDR end;
8634   struct breakpoint *b;
8635   struct symtab_and_line sal_start, sal_end;
8636   struct cleanup *cleanup_bkpt;
8637   struct linespec_sals *lsal_start, *lsal_end;
8638
8639   /* We don't support software ranged breakpoints.  */
8640   if (target_ranged_break_num_registers () < 0)
8641     error (_("This target does not support hardware ranged breakpoints."));
8642
8643   bp_count = hw_breakpoint_used_count ();
8644   bp_count += target_ranged_break_num_registers ();
8645   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8646                                                    bp_count, 0);
8647   if (can_use_bp < 0)
8648     error (_("Hardware breakpoints used exceeds limit."));
8649
8650   arg = skip_spaces (arg);
8651   if (arg == NULL || arg[0] == '\0')
8652     error(_("No address range specified."));
8653
8654   init_linespec_result (&canonical_start);
8655
8656   arg_start = arg;
8657   parse_breakpoint_sals (&arg, &canonical_start);
8658
8659   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
8660
8661   if (arg[0] != ',')
8662     error (_("Too few arguments."));
8663   else if (VEC_empty (linespec_sals, canonical_start.sals))
8664     error (_("Could not find location of the beginning of the range."));
8665
8666   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
8667
8668   if (VEC_length (linespec_sals, canonical_start.sals) > 1
8669       || lsal_start->sals.nelts != 1)
8670     error (_("Cannot create a ranged breakpoint with multiple locations."));
8671
8672   sal_start = lsal_start->sals.sals[0];
8673   addr_string_start = savestring (arg_start, arg - arg_start);
8674   make_cleanup (xfree, addr_string_start);
8675
8676   arg++;        /* Skip the comma.  */
8677   arg = skip_spaces (arg);
8678
8679   /* Parse the end location.  */
8680
8681   init_linespec_result (&canonical_end);
8682   arg_start = arg;
8683
8684   /* We call decode_line_full directly here instead of using
8685      parse_breakpoint_sals because we need to specify the start location's
8686      symtab and line as the default symtab and line for the end of the
8687      range.  This makes it possible to have ranges like "foo.c:27, +14",
8688      where +14 means 14 lines from the start location.  */
8689   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
8690                     sal_start.symtab, sal_start.line,
8691                     &canonical_end, NULL, NULL);
8692
8693   make_cleanup_destroy_linespec_result (&canonical_end);
8694
8695   if (VEC_empty (linespec_sals, canonical_end.sals))
8696     error (_("Could not find location of the end of the range."));
8697
8698   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
8699   if (VEC_length (linespec_sals, canonical_end.sals) > 1
8700       || lsal_end->sals.nelts != 1)
8701     error (_("Cannot create a ranged breakpoint with multiple locations."));
8702
8703   sal_end = lsal_end->sals.sals[0];
8704   addr_string_end = savestring (arg_start, arg - arg_start);
8705   make_cleanup (xfree, addr_string_end);
8706
8707   end = find_breakpoint_range_end (sal_end);
8708   if (sal_start.pc > end)
8709     error (_("Invalid address range, end precedes start."));
8710
8711   length = end - sal_start.pc + 1;
8712   if (length < 0)
8713     /* Length overflowed.  */
8714     error (_("Address range too large."));
8715   else if (length == 1)
8716     {
8717       /* This range is simple enough to be handled by
8718          the `hbreak' command.  */
8719       hbreak_command (addr_string_start, 1);
8720
8721       do_cleanups (cleanup_bkpt);
8722
8723       return;
8724     }
8725
8726   /* Now set up the breakpoint.  */
8727   b = set_raw_breakpoint (get_current_arch (), sal_start,
8728                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
8729   set_breakpoint_count (breakpoint_count + 1);
8730   b->number = breakpoint_count;
8731   b->disposition = disp_donttouch;
8732   b->addr_string = xstrdup (addr_string_start);
8733   b->addr_string_range_end = xstrdup (addr_string_end);
8734   b->loc->length = length;
8735
8736   do_cleanups (cleanup_bkpt);
8737
8738   mention (b);
8739   observer_notify_breakpoint_created (b);
8740   update_global_location_list (1);
8741 }
8742
8743 /*  Return non-zero if EXP is verified as constant.  Returned zero
8744     means EXP is variable.  Also the constant detection may fail for
8745     some constant expressions and in such case still falsely return
8746     zero.  */
8747 static int
8748 watchpoint_exp_is_const (const struct expression *exp)
8749 {
8750   int i = exp->nelts;
8751
8752   while (i > 0)
8753     {
8754       int oplenp, argsp;
8755
8756       /* We are only interested in the descriptor of each element.  */
8757       operator_length (exp, i, &oplenp, &argsp);
8758       i -= oplenp;
8759
8760       switch (exp->elts[i].opcode)
8761         {
8762         case BINOP_ADD:
8763         case BINOP_SUB:
8764         case BINOP_MUL:
8765         case BINOP_DIV:
8766         case BINOP_REM:
8767         case BINOP_MOD:
8768         case BINOP_LSH:
8769         case BINOP_RSH:
8770         case BINOP_LOGICAL_AND:
8771         case BINOP_LOGICAL_OR:
8772         case BINOP_BITWISE_AND:
8773         case BINOP_BITWISE_IOR:
8774         case BINOP_BITWISE_XOR:
8775         case BINOP_EQUAL:
8776         case BINOP_NOTEQUAL:
8777         case BINOP_LESS:
8778         case BINOP_GTR:
8779         case BINOP_LEQ:
8780         case BINOP_GEQ:
8781         case BINOP_REPEAT:
8782         case BINOP_COMMA:
8783         case BINOP_EXP:
8784         case BINOP_MIN:
8785         case BINOP_MAX:
8786         case BINOP_INTDIV:
8787         case BINOP_CONCAT:
8788         case BINOP_IN:
8789         case BINOP_RANGE:
8790         case TERNOP_COND:
8791         case TERNOP_SLICE:
8792         case TERNOP_SLICE_COUNT:
8793
8794         case OP_LONG:
8795         case OP_DOUBLE:
8796         case OP_DECFLOAT:
8797         case OP_LAST:
8798         case OP_COMPLEX:
8799         case OP_STRING:
8800         case OP_BITSTRING:
8801         case OP_ARRAY:
8802         case OP_TYPE:
8803         case OP_NAME:
8804         case OP_OBJC_NSSTRING:
8805
8806         case UNOP_NEG:
8807         case UNOP_LOGICAL_NOT:
8808         case UNOP_COMPLEMENT:
8809         case UNOP_ADDR:
8810         case UNOP_HIGH:
8811           /* Unary, binary and ternary operators: We have to check
8812              their operands.  If they are constant, then so is the
8813              result of that operation.  For instance, if A and B are
8814              determined to be constants, then so is "A + B".
8815
8816              UNOP_IND is one exception to the rule above, because the
8817              value of *ADDR is not necessarily a constant, even when
8818              ADDR is.  */
8819           break;
8820
8821         case OP_VAR_VALUE:
8822           /* Check whether the associated symbol is a constant.
8823
8824              We use SYMBOL_CLASS rather than TYPE_CONST because it's
8825              possible that a buggy compiler could mark a variable as
8826              constant even when it is not, and TYPE_CONST would return
8827              true in this case, while SYMBOL_CLASS wouldn't.
8828
8829              We also have to check for function symbols because they
8830              are always constant.  */
8831           {
8832             struct symbol *s = exp->elts[i + 2].symbol;
8833
8834             if (SYMBOL_CLASS (s) != LOC_BLOCK
8835                 && SYMBOL_CLASS (s) != LOC_CONST
8836                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
8837               return 0;
8838             break;
8839           }
8840
8841         /* The default action is to return 0 because we are using
8842            the optimistic approach here: If we don't know something,
8843            then it is not a constant.  */
8844         default:
8845           return 0;
8846         }
8847     }
8848
8849   return 1;
8850 }
8851
8852 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
8853
8854 static void
8855 dtor_watchpoint (struct breakpoint *self)
8856 {
8857   struct watchpoint *w = (struct watchpoint *) self;
8858
8859   xfree (w->cond_exp);
8860   xfree (w->exp);
8861   xfree (w->exp_string);
8862   xfree (w->exp_string_reparse);
8863   value_free (w->val);
8864
8865   base_breakpoint_ops.dtor (self);
8866 }
8867
8868 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
8869
8870 static void
8871 re_set_watchpoint (struct breakpoint *b)
8872 {
8873   struct watchpoint *w = (struct watchpoint *) b;
8874
8875   /* Watchpoint can be either on expression using entirely global
8876      variables, or it can be on local variables.
8877
8878      Watchpoints of the first kind are never auto-deleted, and even
8879      persist across program restarts.  Since they can use variables
8880      from shared libraries, we need to reparse expression as libraries
8881      are loaded and unloaded.
8882
8883      Watchpoints on local variables can also change meaning as result
8884      of solib event.  For example, if a watchpoint uses both a local
8885      and a global variables in expression, it's a local watchpoint,
8886      but unloading of a shared library will make the expression
8887      invalid.  This is not a very common use case, but we still
8888      re-evaluate expression, to avoid surprises to the user.
8889
8890      Note that for local watchpoints, we re-evaluate it only if
8891      watchpoints frame id is still valid.  If it's not, it means the
8892      watchpoint is out of scope and will be deleted soon.  In fact,
8893      I'm not sure we'll ever be called in this case.
8894
8895      If a local watchpoint's frame id is still valid, then
8896      w->exp_valid_block is likewise valid, and we can safely use it.
8897
8898      Don't do anything about disabled watchpoints, since they will be
8899      reevaluated again when enabled.  */
8900   update_watchpoint (w, 1 /* reparse */);
8901 }
8902
8903 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
8904
8905 static int
8906 insert_watchpoint (struct bp_location *bl)
8907 {
8908   struct watchpoint *w = (struct watchpoint *) bl->owner;
8909   int length = w->exact ? 1 : bl->length;
8910
8911   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
8912                                    w->cond_exp);
8913 }
8914
8915 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
8916
8917 static int
8918 remove_watchpoint (struct bp_location *bl)
8919 {
8920   struct watchpoint *w = (struct watchpoint *) bl->owner;
8921   int length = w->exact ? 1 : bl->length;
8922
8923   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
8924                                    w->cond_exp);
8925 }
8926
8927 static int
8928 breakpoint_hit_watchpoint (const struct bp_location *bl,
8929                            struct address_space *aspace, CORE_ADDR bp_addr,
8930                            const struct target_waitstatus *ws)
8931 {
8932   struct breakpoint *b = bl->owner;
8933   struct watchpoint *w = (struct watchpoint *) b;
8934
8935   /* Continuable hardware watchpoints are treated as non-existent if the
8936      reason we stopped wasn't a hardware watchpoint (we didn't stop on
8937      some data address).  Otherwise gdb won't stop on a break instruction
8938      in the code (not from a breakpoint) when a hardware watchpoint has
8939      been defined.  Also skip watchpoints which we know did not trigger
8940      (did not match the data address).  */
8941   if (is_hardware_watchpoint (b)
8942       && w->watchpoint_triggered == watch_triggered_no)
8943     return 0;
8944
8945   return 1;
8946 }
8947
8948 static void
8949 check_status_watchpoint (bpstat bs)
8950 {
8951   gdb_assert (is_watchpoint (bs->breakpoint_at));
8952
8953   bpstat_check_watchpoint (bs);
8954 }
8955
8956 /* Implement the "resources_needed" breakpoint_ops method for
8957    hardware watchpoints.  */
8958
8959 static int
8960 resources_needed_watchpoint (const struct bp_location *bl)
8961 {
8962   struct watchpoint *w = (struct watchpoint *) bl->owner;
8963   int length = w->exact? 1 : bl->length;
8964
8965   return target_region_ok_for_hw_watchpoint (bl->address, length);
8966 }
8967
8968 /* Implement the "works_in_software_mode" breakpoint_ops method for
8969    hardware watchpoints.  */
8970
8971 static int
8972 works_in_software_mode_watchpoint (const struct breakpoint *b)
8973 {
8974   /* Read and access watchpoints only work with hardware support.  */
8975   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
8976 }
8977
8978 static enum print_stop_action
8979 print_it_watchpoint (bpstat bs)
8980 {
8981   struct cleanup *old_chain;
8982   struct breakpoint *b;
8983   const struct bp_location *bl;
8984   struct ui_stream *stb;
8985   enum print_stop_action result;
8986   struct watchpoint *w;
8987   struct ui_out *uiout = current_uiout;
8988
8989   gdb_assert (bs->bp_location_at != NULL);
8990
8991   bl = bs->bp_location_at;
8992   b = bs->breakpoint_at;
8993   w = (struct watchpoint *) b;
8994
8995   stb = ui_out_stream_new (uiout);
8996   old_chain = make_cleanup_ui_out_stream_delete (stb);
8997
8998   switch (b->type)
8999     {
9000     case bp_watchpoint:
9001     case bp_hardware_watchpoint:
9002       annotate_watchpoint (b->number);
9003       if (ui_out_is_mi_like_p (uiout))
9004         ui_out_field_string
9005           (uiout, "reason",
9006            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9007       mention (b);
9008       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9009       ui_out_text (uiout, "\nOld value = ");
9010       watchpoint_value_print (bs->old_val, stb->stream);
9011       ui_out_field_stream (uiout, "old", stb);
9012       ui_out_text (uiout, "\nNew value = ");
9013       watchpoint_value_print (w->val, stb->stream);
9014       ui_out_field_stream (uiout, "new", stb);
9015       ui_out_text (uiout, "\n");
9016       /* More than one watchpoint may have been triggered.  */
9017       result = PRINT_UNKNOWN;
9018       break;
9019
9020     case bp_read_watchpoint:
9021       if (ui_out_is_mi_like_p (uiout))
9022         ui_out_field_string
9023           (uiout, "reason",
9024            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9025       mention (b);
9026       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9027       ui_out_text (uiout, "\nValue = ");
9028       watchpoint_value_print (w->val, stb->stream);
9029       ui_out_field_stream (uiout, "value", stb);
9030       ui_out_text (uiout, "\n");
9031       result = PRINT_UNKNOWN;
9032       break;
9033
9034     case bp_access_watchpoint:
9035       if (bs->old_val != NULL)
9036         {
9037           annotate_watchpoint (b->number);
9038           if (ui_out_is_mi_like_p (uiout))
9039             ui_out_field_string
9040               (uiout, "reason",
9041                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9042           mention (b);
9043           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9044           ui_out_text (uiout, "\nOld value = ");
9045           watchpoint_value_print (bs->old_val, stb->stream);
9046           ui_out_field_stream (uiout, "old", stb);
9047           ui_out_text (uiout, "\nNew value = ");
9048         }
9049       else
9050         {
9051           mention (b);
9052           if (ui_out_is_mi_like_p (uiout))
9053             ui_out_field_string
9054               (uiout, "reason",
9055                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9056           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9057           ui_out_text (uiout, "\nValue = ");
9058         }
9059       watchpoint_value_print (w->val, stb->stream);
9060       ui_out_field_stream (uiout, "new", stb);
9061       ui_out_text (uiout, "\n");
9062       result = PRINT_UNKNOWN;
9063       break;
9064     default:
9065       result = PRINT_UNKNOWN;
9066     }
9067
9068   do_cleanups (old_chain);
9069   return result;
9070 }
9071
9072 /* Implement the "print_mention" breakpoint_ops method for hardware
9073    watchpoints.  */
9074
9075 static void
9076 print_mention_watchpoint (struct breakpoint *b)
9077 {
9078   struct cleanup *ui_out_chain;
9079   struct watchpoint *w = (struct watchpoint *) b;
9080   struct ui_out *uiout = current_uiout;
9081
9082   switch (b->type)
9083     {
9084     case bp_watchpoint:
9085       ui_out_text (uiout, "Watchpoint ");
9086       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9087       break;
9088     case bp_hardware_watchpoint:
9089       ui_out_text (uiout, "Hardware watchpoint ");
9090       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9091       break;
9092     case bp_read_watchpoint:
9093       ui_out_text (uiout, "Hardware read watchpoint ");
9094       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9095       break;
9096     case bp_access_watchpoint:
9097       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
9098       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9099       break;
9100     default:
9101       internal_error (__FILE__, __LINE__,
9102                       _("Invalid hardware watchpoint type."));
9103     }
9104
9105   ui_out_field_int (uiout, "number", b->number);
9106   ui_out_text (uiout, ": ");
9107   ui_out_field_string (uiout, "exp", w->exp_string);
9108   do_cleanups (ui_out_chain);
9109 }
9110
9111 /* Implement the "print_recreate" breakpoint_ops method for
9112    watchpoints.  */
9113
9114 static void
9115 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
9116 {
9117   struct watchpoint *w = (struct watchpoint *) b;
9118
9119   switch (b->type)
9120     {
9121     case bp_watchpoint:
9122     case bp_hardware_watchpoint:
9123       fprintf_unfiltered (fp, "watch");
9124       break;
9125     case bp_read_watchpoint:
9126       fprintf_unfiltered (fp, "rwatch");
9127       break;
9128     case bp_access_watchpoint:
9129       fprintf_unfiltered (fp, "awatch");
9130       break;
9131     default:
9132       internal_error (__FILE__, __LINE__,
9133                       _("Invalid watchpoint type."));
9134     }
9135
9136   fprintf_unfiltered (fp, " %s", w->exp_string);
9137   print_recreate_thread (b, fp);
9138 }
9139
9140 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
9141
9142 static struct breakpoint_ops watchpoint_breakpoint_ops;
9143
9144 /* Implement the "insert" breakpoint_ops method for
9145    masked hardware watchpoints.  */
9146
9147 static int
9148 insert_masked_watchpoint (struct bp_location *bl)
9149 {
9150   struct watchpoint *w = (struct watchpoint *) bl->owner;
9151
9152   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
9153                                         bl->watchpoint_type);
9154 }
9155
9156 /* Implement the "remove" breakpoint_ops method for
9157    masked hardware watchpoints.  */
9158
9159 static int
9160 remove_masked_watchpoint (struct bp_location *bl)
9161 {
9162   struct watchpoint *w = (struct watchpoint *) bl->owner;
9163
9164   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
9165                                         bl->watchpoint_type);
9166 }
9167
9168 /* Implement the "resources_needed" breakpoint_ops method for
9169    masked hardware watchpoints.  */
9170
9171 static int
9172 resources_needed_masked_watchpoint (const struct bp_location *bl)
9173 {
9174   struct watchpoint *w = (struct watchpoint *) bl->owner;
9175
9176   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
9177 }
9178
9179 /* Implement the "works_in_software_mode" breakpoint_ops method for
9180    masked hardware watchpoints.  */
9181
9182 static int
9183 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
9184 {
9185   return 0;
9186 }
9187
9188 /* Implement the "print_it" breakpoint_ops method for
9189    masked hardware watchpoints.  */
9190
9191 static enum print_stop_action
9192 print_it_masked_watchpoint (bpstat bs)
9193 {
9194   struct breakpoint *b = bs->breakpoint_at;
9195   struct ui_out *uiout = current_uiout;
9196
9197   /* Masked watchpoints have only one location.  */
9198   gdb_assert (b->loc && b->loc->next == NULL);
9199
9200   switch (b->type)
9201     {
9202     case bp_hardware_watchpoint:
9203       annotate_watchpoint (b->number);
9204       if (ui_out_is_mi_like_p (uiout))
9205         ui_out_field_string
9206           (uiout, "reason",
9207            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9208       break;
9209
9210     case bp_read_watchpoint:
9211       if (ui_out_is_mi_like_p (uiout))
9212         ui_out_field_string
9213           (uiout, "reason",
9214            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9215       break;
9216
9217     case bp_access_watchpoint:
9218       if (ui_out_is_mi_like_p (uiout))
9219         ui_out_field_string
9220           (uiout, "reason",
9221            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9222       break;
9223     default:
9224       internal_error (__FILE__, __LINE__,
9225                       _("Invalid hardware watchpoint type."));
9226     }
9227
9228   mention (b);
9229   ui_out_text (uiout, _("\n\
9230 Check the underlying instruction at PC for the memory\n\
9231 address and value which triggered this watchpoint.\n"));
9232   ui_out_text (uiout, "\n");
9233
9234   /* More than one watchpoint may have been triggered.  */
9235   return PRINT_UNKNOWN;
9236 }
9237
9238 /* Implement the "print_one_detail" breakpoint_ops method for
9239    masked hardware watchpoints.  */
9240
9241 static void
9242 print_one_detail_masked_watchpoint (const struct breakpoint *b,
9243                                     struct ui_out *uiout)
9244 {
9245   struct watchpoint *w = (struct watchpoint *) b;
9246
9247   /* Masked watchpoints have only one location.  */
9248   gdb_assert (b->loc && b->loc->next == NULL);
9249
9250   ui_out_text (uiout, "\tmask ");
9251   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
9252   ui_out_text (uiout, "\n");
9253 }
9254
9255 /* Implement the "print_mention" breakpoint_ops method for
9256    masked hardware watchpoints.  */
9257
9258 static void
9259 print_mention_masked_watchpoint (struct breakpoint *b)
9260 {
9261   struct watchpoint *w = (struct watchpoint *) b;
9262   struct ui_out *uiout = current_uiout;
9263   struct cleanup *ui_out_chain;
9264
9265   switch (b->type)
9266     {
9267     case bp_hardware_watchpoint:
9268       ui_out_text (uiout, "Masked hardware watchpoint ");
9269       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9270       break;
9271     case bp_read_watchpoint:
9272       ui_out_text (uiout, "Masked hardware read watchpoint ");
9273       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9274       break;
9275     case bp_access_watchpoint:
9276       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
9277       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9278       break;
9279     default:
9280       internal_error (__FILE__, __LINE__,
9281                       _("Invalid hardware watchpoint type."));
9282     }
9283
9284   ui_out_field_int (uiout, "number", b->number);
9285   ui_out_text (uiout, ": ");
9286   ui_out_field_string (uiout, "exp", w->exp_string);
9287   do_cleanups (ui_out_chain);
9288 }
9289
9290 /* Implement the "print_recreate" breakpoint_ops method for
9291    masked hardware watchpoints.  */
9292
9293 static void
9294 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
9295 {
9296   struct watchpoint *w = (struct watchpoint *) b;
9297   char tmp[40];
9298
9299   switch (b->type)
9300     {
9301     case bp_hardware_watchpoint:
9302       fprintf_unfiltered (fp, "watch");
9303       break;
9304     case bp_read_watchpoint:
9305       fprintf_unfiltered (fp, "rwatch");
9306       break;
9307     case bp_access_watchpoint:
9308       fprintf_unfiltered (fp, "awatch");
9309       break;
9310     default:
9311       internal_error (__FILE__, __LINE__,
9312                       _("Invalid hardware watchpoint type."));
9313     }
9314
9315   sprintf_vma (tmp, w->hw_wp_mask);
9316   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
9317   print_recreate_thread (b, fp);
9318 }
9319
9320 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
9321
9322 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
9323
9324 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
9325
9326 static int
9327 is_masked_watchpoint (const struct breakpoint *b)
9328 {
9329   return b->ops == &masked_watchpoint_breakpoint_ops;
9330 }
9331
9332 /* accessflag:  hw_write:  watch write, 
9333                 hw_read:   watch read, 
9334                 hw_access: watch access (read or write) */
9335 static void
9336 watch_command_1 (char *arg, int accessflag, int from_tty,
9337                  int just_location, int internal)
9338 {
9339   volatile struct gdb_exception e;
9340   struct breakpoint *b, *scope_breakpoint = NULL;
9341   struct expression *exp;
9342   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
9343   struct value *val, *mark, *result;
9344   struct frame_info *frame;
9345   char *exp_start = NULL;
9346   char *exp_end = NULL;
9347   char *tok, *end_tok;
9348   int toklen = -1;
9349   char *cond_start = NULL;
9350   char *cond_end = NULL;
9351   enum bptype bp_type;
9352   int thread = -1;
9353   int pc = 0;
9354   /* Flag to indicate whether we are going to use masks for
9355      the hardware watchpoint.  */
9356   int use_mask = 0;
9357   CORE_ADDR mask = 0;
9358   struct watchpoint *w;
9359
9360   /* Make sure that we actually have parameters to parse.  */
9361   if (arg != NULL && arg[0] != '\0')
9362     {
9363       char *value_start;
9364
9365       /* Look for "parameter value" pairs at the end
9366          of the arguments string.  */
9367       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
9368         {
9369           /* Skip whitespace at the end of the argument list.  */
9370           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9371             tok--;
9372
9373           /* Find the beginning of the last token.
9374              This is the value of the parameter.  */
9375           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9376             tok--;
9377           value_start = tok + 1;
9378
9379           /* Skip whitespace.  */
9380           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9381             tok--;
9382
9383           end_tok = tok;
9384
9385           /* Find the beginning of the second to last token.
9386              This is the parameter itself.  */
9387           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9388             tok--;
9389           tok++;
9390           toklen = end_tok - tok + 1;
9391
9392           if (toklen == 6 && !strncmp (tok, "thread", 6))
9393             {
9394               /* At this point we've found a "thread" token, which means
9395                  the user is trying to set a watchpoint that triggers
9396                  only in a specific thread.  */
9397               char *endp;
9398
9399               if (thread != -1)
9400                 error(_("You can specify only one thread."));
9401
9402               /* Extract the thread ID from the next token.  */
9403               thread = strtol (value_start, &endp, 0);
9404
9405               /* Check if the user provided a valid numeric value for the
9406                  thread ID.  */
9407               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
9408                 error (_("Invalid thread ID specification %s."), value_start);
9409
9410               /* Check if the thread actually exists.  */
9411               if (!valid_thread_id (thread))
9412                 error (_("Unknown thread %d."), thread);
9413             }
9414           else if (toklen == 4 && !strncmp (tok, "mask", 4))
9415             {
9416               /* We've found a "mask" token, which means the user wants to
9417                  create a hardware watchpoint that is going to have the mask
9418                  facility.  */
9419               struct value *mask_value, *mark;
9420
9421               if (use_mask)
9422                 error(_("You can specify only one mask."));
9423
9424               use_mask = just_location = 1;
9425
9426               mark = value_mark ();
9427               mask_value = parse_to_comma_and_eval (&value_start);
9428               mask = value_as_address (mask_value);
9429               value_free_to_mark (mark);
9430             }
9431           else
9432             /* We didn't recognize what we found.  We should stop here.  */
9433             break;
9434
9435           /* Truncate the string and get rid of the "parameter value" pair before
9436              the arguments string is parsed by the parse_exp_1 function.  */
9437           *tok = '\0';
9438         }
9439     }
9440
9441   /* Parse the rest of the arguments.  */
9442   innermost_block = NULL;
9443   exp_start = arg;
9444   exp = parse_exp_1 (&arg, 0, 0);
9445   exp_end = arg;
9446   /* Remove trailing whitespace from the expression before saving it.
9447      This makes the eventual display of the expression string a bit
9448      prettier.  */
9449   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
9450     --exp_end;
9451
9452   /* Checking if the expression is not constant.  */
9453   if (watchpoint_exp_is_const (exp))
9454     {
9455       int len;
9456
9457       len = exp_end - exp_start;
9458       while (len > 0 && isspace (exp_start[len - 1]))
9459         len--;
9460       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
9461     }
9462
9463   exp_valid_block = innermost_block;
9464   mark = value_mark ();
9465   fetch_subexp_value (exp, &pc, &val, &result, NULL);
9466
9467   if (just_location)
9468     {
9469       int ret;
9470
9471       exp_valid_block = NULL;
9472       val = value_addr (result);
9473       release_value (val);
9474       value_free_to_mark (mark);
9475
9476       if (use_mask)
9477         {
9478           ret = target_masked_watch_num_registers (value_as_address (val),
9479                                                    mask);
9480           if (ret == -1)
9481             error (_("This target does not support masked watchpoints."));
9482           else if (ret == -2)
9483             error (_("Invalid mask or memory region."));
9484         }
9485     }
9486   else if (val != NULL)
9487     release_value (val);
9488
9489   tok = skip_spaces (arg);
9490   end_tok = skip_to_space (tok);
9491
9492   toklen = end_tok - tok;
9493   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9494     {
9495       struct expression *cond;
9496
9497       innermost_block = NULL;
9498       tok = cond_start = end_tok + 1;
9499       cond = parse_exp_1 (&tok, 0, 0);
9500
9501       /* The watchpoint expression may not be local, but the condition
9502          may still be.  E.g.: `watch global if local > 0'.  */
9503       cond_exp_valid_block = innermost_block;
9504
9505       xfree (cond);
9506       cond_end = tok;
9507     }
9508   if (*tok)
9509     error (_("Junk at end of command."));
9510
9511   if (accessflag == hw_read)
9512     bp_type = bp_read_watchpoint;
9513   else if (accessflag == hw_access)
9514     bp_type = bp_access_watchpoint;
9515   else
9516     bp_type = bp_hardware_watchpoint;
9517
9518   frame = block_innermost_frame (exp_valid_block);
9519
9520   /* If the expression is "local", then set up a "watchpoint scope"
9521      breakpoint at the point where we've left the scope of the watchpoint
9522      expression.  Create the scope breakpoint before the watchpoint, so
9523      that we will encounter it first in bpstat_stop_status.  */
9524   if (exp_valid_block && frame)
9525     {
9526       if (frame_id_p (frame_unwind_caller_id (frame)))
9527         {
9528           scope_breakpoint
9529             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
9530                                           frame_unwind_caller_pc (frame),
9531                                           bp_watchpoint_scope,
9532                                           &momentary_breakpoint_ops);
9533
9534           scope_breakpoint->enable_state = bp_enabled;
9535
9536           /* Automatically delete the breakpoint when it hits.  */
9537           scope_breakpoint->disposition = disp_del;
9538
9539           /* Only break in the proper frame (help with recursion).  */
9540           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
9541
9542           /* Set the address at which we will stop.  */
9543           scope_breakpoint->loc->gdbarch
9544             = frame_unwind_caller_arch (frame);
9545           scope_breakpoint->loc->requested_address
9546             = frame_unwind_caller_pc (frame);
9547           scope_breakpoint->loc->address
9548             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
9549                                          scope_breakpoint->loc->requested_address,
9550                                          scope_breakpoint->type);
9551         }
9552     }
9553
9554   /* Now set up the breakpoint.  */
9555
9556   w = XCNEW (struct watchpoint);
9557   b = &w->base;
9558   if (use_mask)
9559     init_raw_breakpoint_without_location (b, NULL, bp_type,
9560                                           &masked_watchpoint_breakpoint_ops);
9561   else
9562     init_raw_breakpoint_without_location (b, NULL, bp_type,
9563                                           &watchpoint_breakpoint_ops);
9564   b->thread = thread;
9565   b->disposition = disp_donttouch;
9566   b->pspace = current_program_space;
9567   w->exp = exp;
9568   w->exp_valid_block = exp_valid_block;
9569   w->cond_exp_valid_block = cond_exp_valid_block;
9570   if (just_location)
9571     {
9572       struct type *t = value_type (val);
9573       CORE_ADDR addr = value_as_address (val);
9574       char *name;
9575
9576       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
9577       name = type_to_string (t);
9578
9579       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
9580                                           core_addr_to_string (addr));
9581       xfree (name);
9582
9583       w->exp_string = xstrprintf ("-location %.*s",
9584                                   (int) (exp_end - exp_start), exp_start);
9585
9586       /* The above expression is in C.  */
9587       b->language = language_c;
9588     }
9589   else
9590     w->exp_string = savestring (exp_start, exp_end - exp_start);
9591
9592   if (use_mask)
9593     {
9594       w->hw_wp_mask = mask;
9595     }
9596   else
9597     {
9598       w->val = val;
9599       w->val_valid = 1;
9600     }
9601
9602   if (cond_start)
9603     b->cond_string = savestring (cond_start, cond_end - cond_start);
9604   else
9605     b->cond_string = 0;
9606
9607   if (frame)
9608     {
9609       w->watchpoint_frame = get_frame_id (frame);
9610       w->watchpoint_thread = inferior_ptid;
9611     }
9612   else
9613     {
9614       w->watchpoint_frame = null_frame_id;
9615       w->watchpoint_thread = null_ptid;
9616     }
9617
9618   if (scope_breakpoint != NULL)
9619     {
9620       /* The scope breakpoint is related to the watchpoint.  We will
9621          need to act on them together.  */
9622       b->related_breakpoint = scope_breakpoint;
9623       scope_breakpoint->related_breakpoint = b;
9624     }
9625
9626   if (!just_location)
9627     value_free_to_mark (mark);
9628
9629   TRY_CATCH (e, RETURN_MASK_ALL)
9630     {
9631       /* Finally update the new watchpoint.  This creates the locations
9632          that should be inserted.  */
9633       update_watchpoint (w, 1);
9634     }
9635   if (e.reason < 0)
9636     {
9637       delete_breakpoint (b);
9638       throw_exception (e);
9639     }
9640
9641   install_breakpoint (internal, b, 1);
9642 }
9643
9644 /* Return count of debug registers needed to watch the given expression.
9645    If the watchpoint cannot be handled in hardware return zero.  */
9646
9647 static int
9648 can_use_hardware_watchpoint (struct value *v)
9649 {
9650   int found_memory_cnt = 0;
9651   struct value *head = v;
9652
9653   /* Did the user specifically forbid us to use hardware watchpoints? */
9654   if (!can_use_hw_watchpoints)
9655     return 0;
9656
9657   /* Make sure that the value of the expression depends only upon
9658      memory contents, and values computed from them within GDB.  If we
9659      find any register references or function calls, we can't use a
9660      hardware watchpoint.
9661
9662      The idea here is that evaluating an expression generates a series
9663      of values, one holding the value of every subexpression.  (The
9664      expression a*b+c has five subexpressions: a, b, a*b, c, and
9665      a*b+c.)  GDB's values hold almost enough information to establish
9666      the criteria given above --- they identify memory lvalues,
9667      register lvalues, computed values, etcetera.  So we can evaluate
9668      the expression, and then scan the chain of values that leaves
9669      behind to decide whether we can detect any possible change to the
9670      expression's final value using only hardware watchpoints.
9671
9672      However, I don't think that the values returned by inferior
9673      function calls are special in any way.  So this function may not
9674      notice that an expression involving an inferior function call
9675      can't be watched with hardware watchpoints.  FIXME.  */
9676   for (; v; v = value_next (v))
9677     {
9678       if (VALUE_LVAL (v) == lval_memory)
9679         {
9680           if (v != head && value_lazy (v))
9681             /* A lazy memory lvalue in the chain is one that GDB never
9682                needed to fetch; we either just used its address (e.g.,
9683                `a' in `a.b') or we never needed it at all (e.g., `a'
9684                in `a,b').  This doesn't apply to HEAD; if that is
9685                lazy then it was not readable, but watch it anyway.  */
9686             ;
9687           else
9688             {
9689               /* Ahh, memory we actually used!  Check if we can cover
9690                  it with hardware watchpoints.  */
9691               struct type *vtype = check_typedef (value_type (v));
9692
9693               /* We only watch structs and arrays if user asked for it
9694                  explicitly, never if they just happen to appear in a
9695                  middle of some value chain.  */
9696               if (v == head
9697                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
9698                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
9699                 {
9700                   CORE_ADDR vaddr = value_address (v);
9701                   int len;
9702                   int num_regs;
9703
9704                   len = (target_exact_watchpoints
9705                          && is_scalar_type_recursive (vtype))?
9706                     1 : TYPE_LENGTH (value_type (v));
9707
9708                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
9709                   if (!num_regs)
9710                     return 0;
9711                   else
9712                     found_memory_cnt += num_regs;
9713                 }
9714             }
9715         }
9716       else if (VALUE_LVAL (v) != not_lval
9717                && deprecated_value_modifiable (v) == 0)
9718         return 0;       /* These are values from the history (e.g., $1).  */
9719       else if (VALUE_LVAL (v) == lval_register)
9720         return 0;       /* Cannot watch a register with a HW watchpoint.  */
9721     }
9722
9723   /* The expression itself looks suitable for using a hardware
9724      watchpoint, but give the target machine a chance to reject it.  */
9725   return found_memory_cnt;
9726 }
9727
9728 void
9729 watch_command_wrapper (char *arg, int from_tty, int internal)
9730 {
9731   watch_command_1 (arg, hw_write, from_tty, 0, internal);
9732 }
9733
9734 /* A helper function that looks for an argument at the start of a
9735    string.  The argument must also either be at the end of the string,
9736    or be followed by whitespace.  Returns 1 if it finds the argument,
9737    0 otherwise.  If the argument is found, it updates *STR.  */
9738
9739 static int
9740 check_for_argument (char **str, char *arg, int arg_len)
9741 {
9742   if (strncmp (*str, arg, arg_len) == 0
9743       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
9744     {
9745       *str += arg_len;
9746       return 1;
9747     }
9748   return 0;
9749 }
9750
9751 /* A helper function that looks for the "-location" argument and then
9752    calls watch_command_1.  */
9753
9754 static void
9755 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
9756 {
9757   int just_location = 0;
9758
9759   if (arg
9760       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
9761           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
9762     {
9763       arg = skip_spaces (arg);
9764       just_location = 1;
9765     }
9766
9767   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
9768 }
9769
9770 static void
9771 watch_command (char *arg, int from_tty)
9772 {
9773   watch_maybe_just_location (arg, hw_write, from_tty);
9774 }
9775
9776 void
9777 rwatch_command_wrapper (char *arg, int from_tty, int internal)
9778 {
9779   watch_command_1 (arg, hw_read, from_tty, 0, internal);
9780 }
9781
9782 static void
9783 rwatch_command (char *arg, int from_tty)
9784 {
9785   watch_maybe_just_location (arg, hw_read, from_tty);
9786 }
9787
9788 void
9789 awatch_command_wrapper (char *arg, int from_tty, int internal)
9790 {
9791   watch_command_1 (arg, hw_access, from_tty, 0, internal);
9792 }
9793
9794 static void
9795 awatch_command (char *arg, int from_tty)
9796 {
9797   watch_maybe_just_location (arg, hw_access, from_tty);
9798 }
9799 \f
9800
9801 /* Helper routines for the until_command routine in infcmd.c.  Here
9802    because it uses the mechanisms of breakpoints.  */
9803
9804 struct until_break_command_continuation_args
9805 {
9806   struct breakpoint *breakpoint;
9807   struct breakpoint *breakpoint2;
9808   int thread_num;
9809 };
9810
9811 /* This function is called by fetch_inferior_event via the
9812    cmd_continuation pointer, to complete the until command.  It takes
9813    care of cleaning up the temporary breakpoints set up by the until
9814    command.  */
9815 static void
9816 until_break_command_continuation (void *arg, int err)
9817 {
9818   struct until_break_command_continuation_args *a = arg;
9819
9820   delete_breakpoint (a->breakpoint);
9821   if (a->breakpoint2)
9822     delete_breakpoint (a->breakpoint2);
9823   delete_longjmp_breakpoint (a->thread_num);
9824 }
9825
9826 void
9827 until_break_command (char *arg, int from_tty, int anywhere)
9828 {
9829   struct symtabs_and_lines sals;
9830   struct symtab_and_line sal;
9831   struct frame_info *frame = get_selected_frame (NULL);
9832   struct breakpoint *breakpoint;
9833   struct breakpoint *breakpoint2 = NULL;
9834   struct cleanup *old_chain;
9835   int thread;
9836   struct thread_info *tp;
9837
9838   clear_proceed_status ();
9839
9840   /* Set a breakpoint where the user wants it and at return from
9841      this function.  */
9842
9843   if (last_displayed_sal_is_valid ())
9844     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
9845                           get_last_displayed_symtab (),
9846                           get_last_displayed_line ());
9847   else
9848     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
9849                           (struct symtab *) NULL, 0);
9850
9851   if (sals.nelts != 1)
9852     error (_("Couldn't get information on specified line."));
9853
9854   sal = sals.sals[0];
9855   xfree (sals.sals);    /* malloc'd, so freed.  */
9856
9857   if (*arg)
9858     error (_("Junk at end of arguments."));
9859
9860   resolve_sal_pc (&sal);
9861
9862   if (anywhere)
9863     /* If the user told us to continue until a specified location,
9864        we don't specify a frame at which we need to stop.  */
9865     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
9866                                            null_frame_id, bp_until);
9867   else
9868     /* Otherwise, specify the selected frame, because we want to stop
9869        only at the very same frame.  */
9870     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
9871                                            get_stack_frame_id (frame),
9872                                            bp_until);
9873
9874   old_chain = make_cleanup_delete_breakpoint (breakpoint);
9875
9876   tp = inferior_thread ();
9877   thread = tp->num;
9878
9879   /* Keep within the current frame, or in frames called by the current
9880      one.  */
9881
9882   if (frame_id_p (frame_unwind_caller_id (frame)))
9883     {
9884       sal = find_pc_line (frame_unwind_caller_pc (frame), 0);
9885       sal.pc = frame_unwind_caller_pc (frame);
9886       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
9887                                               sal,
9888                                               frame_unwind_caller_id (frame),
9889                                               bp_until);
9890       make_cleanup_delete_breakpoint (breakpoint2);
9891
9892       set_longjmp_breakpoint (tp, frame_unwind_caller_id (frame));
9893       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
9894     }
9895
9896   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
9897
9898   /* If we are running asynchronously, and proceed call above has
9899      actually managed to start the target, arrange for breakpoints to
9900      be deleted when the target stops.  Otherwise, we're already
9901      stopped and delete breakpoints via cleanup chain.  */
9902
9903   if (target_can_async_p () && is_running (inferior_ptid))
9904     {
9905       struct until_break_command_continuation_args *args;
9906       args = xmalloc (sizeof (*args));
9907
9908       args->breakpoint = breakpoint;
9909       args->breakpoint2 = breakpoint2;
9910       args->thread_num = thread;
9911
9912       discard_cleanups (old_chain);
9913       add_continuation (inferior_thread (),
9914                         until_break_command_continuation, args,
9915                         xfree);
9916     }
9917   else
9918     do_cleanups (old_chain);
9919 }
9920
9921 /* This function attempts to parse an optional "if <cond>" clause
9922    from the arg string.  If one is not found, it returns NULL.
9923
9924    Else, it returns a pointer to the condition string.  (It does not
9925    attempt to evaluate the string against a particular block.)  And,
9926    it updates arg to point to the first character following the parsed
9927    if clause in the arg string.  */
9928
9929 static char *
9930 ep_parse_optional_if_clause (char **arg)
9931 {
9932   char *cond_string;
9933
9934   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
9935     return NULL;
9936
9937   /* Skip the "if" keyword.  */
9938   (*arg) += 2;
9939
9940   /* Skip any extra leading whitespace, and record the start of the
9941      condition string.  */
9942   *arg = skip_spaces (*arg);
9943   cond_string = *arg;
9944
9945   /* Assume that the condition occupies the remainder of the arg
9946      string.  */
9947   (*arg) += strlen (cond_string);
9948
9949   return cond_string;
9950 }
9951
9952 /* Commands to deal with catching events, such as signals, exceptions,
9953    process start/exit, etc.  */
9954
9955 typedef enum
9956 {
9957   catch_fork_temporary, catch_vfork_temporary,
9958   catch_fork_permanent, catch_vfork_permanent
9959 }
9960 catch_fork_kind;
9961
9962 static void
9963 catch_fork_command_1 (char *arg, int from_tty, 
9964                       struct cmd_list_element *command)
9965 {
9966   struct gdbarch *gdbarch = get_current_arch ();
9967   char *cond_string = NULL;
9968   catch_fork_kind fork_kind;
9969   int tempflag;
9970
9971   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
9972   tempflag = (fork_kind == catch_fork_temporary
9973               || fork_kind == catch_vfork_temporary);
9974
9975   if (!arg)
9976     arg = "";
9977   arg = skip_spaces (arg);
9978
9979   /* The allowed syntax is:
9980      catch [v]fork
9981      catch [v]fork if <cond>
9982
9983      First, check if there's an if clause.  */
9984   cond_string = ep_parse_optional_if_clause (&arg);
9985
9986   if ((*arg != '\0') && !isspace (*arg))
9987     error (_("Junk at end of arguments."));
9988
9989   /* If this target supports it, create a fork or vfork catchpoint
9990      and enable reporting of such events.  */
9991   switch (fork_kind)
9992     {
9993     case catch_fork_temporary:
9994     case catch_fork_permanent:
9995       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
9996                                           &catch_fork_breakpoint_ops);
9997       break;
9998     case catch_vfork_temporary:
9999     case catch_vfork_permanent:
10000       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10001                                           &catch_vfork_breakpoint_ops);
10002       break;
10003     default:
10004       error (_("unsupported or unknown fork kind; cannot catch it"));
10005       break;
10006     }
10007 }
10008
10009 static void
10010 catch_exec_command_1 (char *arg, int from_tty, 
10011                       struct cmd_list_element *command)
10012 {
10013   struct exec_catchpoint *c;
10014   struct gdbarch *gdbarch = get_current_arch ();
10015   int tempflag;
10016   char *cond_string = NULL;
10017
10018   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10019
10020   if (!arg)
10021     arg = "";
10022   arg = skip_spaces (arg);
10023
10024   /* The allowed syntax is:
10025      catch exec
10026      catch exec if <cond>
10027
10028      First, check if there's an if clause.  */
10029   cond_string = ep_parse_optional_if_clause (&arg);
10030
10031   if ((*arg != '\0') && !isspace (*arg))
10032     error (_("Junk at end of arguments."));
10033
10034   c = XNEW (struct exec_catchpoint);
10035   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
10036                    &catch_exec_breakpoint_ops);
10037   c->exec_pathname = NULL;
10038
10039   install_breakpoint (0, &c->base, 1);
10040 }
10041
10042 static enum print_stop_action
10043 print_it_exception_catchpoint (bpstat bs)
10044 {
10045   struct ui_out *uiout = current_uiout;
10046   struct breakpoint *b = bs->breakpoint_at;
10047   int bp_temp, bp_throw;
10048
10049   annotate_catchpoint (b->number);
10050
10051   bp_throw = strstr (b->addr_string, "throw") != NULL;
10052   if (b->loc->address != b->loc->requested_address)
10053     breakpoint_adjustment_warning (b->loc->requested_address,
10054                                    b->loc->address,
10055                                    b->number, 1);
10056   bp_temp = b->disposition == disp_del;
10057   ui_out_text (uiout, 
10058                bp_temp ? "Temporary catchpoint "
10059                        : "Catchpoint ");
10060   if (!ui_out_is_mi_like_p (uiout))
10061     ui_out_field_int (uiout, "bkptno", b->number);
10062   ui_out_text (uiout,
10063                bp_throw ? " (exception thrown), "
10064                         : " (exception caught), ");
10065   if (ui_out_is_mi_like_p (uiout))
10066     {
10067       ui_out_field_string (uiout, "reason", 
10068                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10069       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10070       ui_out_field_int (uiout, "bkptno", b->number);
10071     }
10072   return PRINT_SRC_AND_LOC;
10073 }
10074
10075 static void
10076 print_one_exception_catchpoint (struct breakpoint *b, 
10077                                 struct bp_location **last_loc)
10078 {
10079   struct value_print_options opts;
10080   struct ui_out *uiout = current_uiout;
10081
10082   get_user_print_options (&opts);
10083   if (opts.addressprint)
10084     {
10085       annotate_field (4);
10086       if (b->loc == NULL || b->loc->shlib_disabled)
10087         ui_out_field_string (uiout, "addr", "<PENDING>");
10088       else
10089         ui_out_field_core_addr (uiout, "addr",
10090                                 b->loc->gdbarch, b->loc->address);
10091     }
10092   annotate_field (5);
10093   if (b->loc)
10094     *last_loc = b->loc;
10095   if (strstr (b->addr_string, "throw") != NULL)
10096     ui_out_field_string (uiout, "what", "exception throw");
10097   else
10098     ui_out_field_string (uiout, "what", "exception catch");
10099 }
10100
10101 static void
10102 print_mention_exception_catchpoint (struct breakpoint *b)
10103 {
10104   struct ui_out *uiout = current_uiout;
10105   int bp_temp;
10106   int bp_throw;
10107
10108   bp_temp = b->disposition == disp_del;
10109   bp_throw = strstr (b->addr_string, "throw") != NULL;
10110   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
10111                               : _("Catchpoint "));
10112   ui_out_field_int (uiout, "bkptno", b->number);
10113   ui_out_text (uiout, bp_throw ? _(" (throw)")
10114                                : _(" (catch)"));
10115 }
10116
10117 /* Implement the "print_recreate" breakpoint_ops method for throw and
10118    catch catchpoints.  */
10119
10120 static void
10121 print_recreate_exception_catchpoint (struct breakpoint *b, 
10122                                      struct ui_file *fp)
10123 {
10124   int bp_temp;
10125   int bp_throw;
10126
10127   bp_temp = b->disposition == disp_del;
10128   bp_throw = strstr (b->addr_string, "throw") != NULL;
10129   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
10130   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
10131   print_recreate_thread (b, fp);
10132 }
10133
10134 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
10135
10136 static int
10137 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
10138                           enum exception_event_kind ex_event, int from_tty)
10139 {
10140   char *trigger_func_name;
10141  
10142   if (ex_event == EX_EVENT_CATCH)
10143     trigger_func_name = "__cxa_begin_catch";
10144   else
10145     trigger_func_name = "__cxa_throw";
10146
10147   create_breakpoint (get_current_arch (),
10148                      trigger_func_name, cond_string, -1,
10149                      0 /* condition and thread are valid.  */,
10150                      tempflag, bp_breakpoint,
10151                      0,
10152                      AUTO_BOOLEAN_TRUE /* pending */,
10153                      &gnu_v3_exception_catchpoint_ops, from_tty,
10154                      1 /* enabled */,
10155                      0 /* internal */);
10156
10157   return 1;
10158 }
10159
10160 /* Deal with "catch catch" and "catch throw" commands.  */
10161
10162 static void
10163 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
10164                            int tempflag, int from_tty)
10165 {
10166   char *cond_string = NULL;
10167
10168   if (!arg)
10169     arg = "";
10170   arg = skip_spaces (arg);
10171
10172   cond_string = ep_parse_optional_if_clause (&arg);
10173
10174   if ((*arg != '\0') && !isspace (*arg))
10175     error (_("Junk at end of arguments."));
10176
10177   if (ex_event != EX_EVENT_THROW
10178       && ex_event != EX_EVENT_CATCH)
10179     error (_("Unsupported or unknown exception event; cannot catch it"));
10180
10181   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
10182     return;
10183
10184   warning (_("Unsupported with this platform/compiler combination."));
10185 }
10186
10187 /* Implementation of "catch catch" command.  */
10188
10189 static void
10190 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
10191 {
10192   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10193
10194   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
10195 }
10196
10197 /* Implementation of "catch throw" command.  */
10198
10199 static void
10200 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
10201 {
10202   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10203
10204   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
10205 }
10206
10207 void
10208 init_ada_exception_breakpoint (struct breakpoint *b,
10209                                struct gdbarch *gdbarch,
10210                                struct symtab_and_line sal,
10211                                char *addr_string,
10212                                const struct breakpoint_ops *ops,
10213                                int tempflag,
10214                                int from_tty)
10215 {
10216   if (from_tty)
10217     {
10218       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
10219       if (!loc_gdbarch)
10220         loc_gdbarch = gdbarch;
10221
10222       describe_other_breakpoints (loc_gdbarch,
10223                                   sal.pspace, sal.pc, sal.section, -1);
10224       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
10225          version for exception catchpoints, because two catchpoints
10226          used for different exception names will use the same address.
10227          In this case, a "breakpoint ... also set at..." warning is
10228          unproductive.  Besides, the warning phrasing is also a bit
10229          inappropriate, we should use the word catchpoint, and tell
10230          the user what type of catchpoint it is.  The above is good
10231          enough for now, though.  */
10232     }
10233
10234   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
10235
10236   b->enable_state = bp_enabled;
10237   b->disposition = tempflag ? disp_del : disp_donttouch;
10238   b->addr_string = addr_string;
10239   b->language = language_ada;
10240 }
10241
10242 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
10243    filter list, or NULL if no filtering is required.  */
10244 static VEC(int) *
10245 catch_syscall_split_args (char *arg)
10246 {
10247   VEC(int) *result = NULL;
10248   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
10249
10250   while (*arg != '\0')
10251     {
10252       int i, syscall_number;
10253       char *endptr;
10254       char cur_name[128];
10255       struct syscall s;
10256
10257       /* Skip whitespace.  */
10258       while (isspace (*arg))
10259         arg++;
10260
10261       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
10262         cur_name[i] = arg[i];
10263       cur_name[i] = '\0';
10264       arg += i;
10265
10266       /* Check if the user provided a syscall name or a number.  */
10267       syscall_number = (int) strtol (cur_name, &endptr, 0);
10268       if (*endptr == '\0')
10269         get_syscall_by_number (syscall_number, &s);
10270       else
10271         {
10272           /* We have a name.  Let's check if it's valid and convert it
10273              to a number.  */
10274           get_syscall_by_name (cur_name, &s);
10275
10276           if (s.number == UNKNOWN_SYSCALL)
10277             /* Here we have to issue an error instead of a warning,
10278                because GDB cannot do anything useful if there's no
10279                syscall number to be caught.  */
10280             error (_("Unknown syscall name '%s'."), cur_name);
10281         }
10282
10283       /* Ok, it's valid.  */
10284       VEC_safe_push (int, result, s.number);
10285     }
10286
10287   discard_cleanups (cleanup);
10288   return result;
10289 }
10290
10291 /* Implement the "catch syscall" command.  */
10292
10293 static void
10294 catch_syscall_command_1 (char *arg, int from_tty, 
10295                          struct cmd_list_element *command)
10296 {
10297   int tempflag;
10298   VEC(int) *filter;
10299   struct syscall s;
10300   struct gdbarch *gdbarch = get_current_arch ();
10301
10302   /* Checking if the feature if supported.  */
10303   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
10304     error (_("The feature 'catch syscall' is not supported on \
10305 this architecture yet."));
10306
10307   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10308
10309   arg = skip_spaces (arg);
10310
10311   /* We need to do this first "dummy" translation in order
10312      to get the syscall XML file loaded or, most important,
10313      to display a warning to the user if there's no XML file
10314      for his/her architecture.  */
10315   get_syscall_by_number (0, &s);
10316
10317   /* The allowed syntax is:
10318      catch syscall
10319      catch syscall <name | number> [<name | number> ... <name | number>]
10320
10321      Let's check if there's a syscall name.  */
10322
10323   if (arg != NULL)
10324     filter = catch_syscall_split_args (arg);
10325   else
10326     filter = NULL;
10327
10328   create_syscall_event_catchpoint (tempflag, filter,
10329                                    &catch_syscall_breakpoint_ops);
10330 }
10331
10332 static void
10333 catch_command (char *arg, int from_tty)
10334 {
10335   error (_("Catch requires an event name."));
10336 }
10337 \f
10338
10339 static void
10340 tcatch_command (char *arg, int from_tty)
10341 {
10342   error (_("Catch requires an event name."));
10343 }
10344
10345 /* A qsort comparison function that sorts breakpoints in order.  */
10346
10347 static int
10348 compare_breakpoints (const void *a, const void *b)
10349 {
10350   const breakpoint_p *ba = a;
10351   uintptr_t ua = (uintptr_t) *ba;
10352   const breakpoint_p *bb = b;
10353   uintptr_t ub = (uintptr_t) *bb;
10354
10355   if ((*ba)->number < (*bb)->number)
10356     return -1;
10357   else if ((*ba)->number > (*bb)->number)
10358     return 1;
10359
10360   /* Now sort by address, in case we see, e..g, two breakpoints with
10361      the number 0.  */
10362   if (ua < ub)
10363     return -1;
10364   return ub > ub ? 1 : 0;
10365 }
10366
10367 /* Delete breakpoints by address or line.  */
10368
10369 static void
10370 clear_command (char *arg, int from_tty)
10371 {
10372   struct breakpoint *b, *prev;
10373   VEC(breakpoint_p) *found = 0;
10374   int ix;
10375   int default_match;
10376   struct symtabs_and_lines sals;
10377   struct symtab_and_line sal;
10378   int i;
10379   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
10380
10381   if (arg)
10382     {
10383       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
10384                                      | DECODE_LINE_LIST_MODE));
10385       default_match = 0;
10386     }
10387   else
10388     {
10389       sals.sals = (struct symtab_and_line *)
10390         xmalloc (sizeof (struct symtab_and_line));
10391       make_cleanup (xfree, sals.sals);
10392       init_sal (&sal);          /* Initialize to zeroes.  */
10393
10394       /* Set sal's line, symtab, pc, and pspace to the values
10395          corresponding to the last call to print_frame_info.  If the
10396          codepoint is not valid, this will set all the fields to 0.  */
10397       get_last_displayed_sal (&sal);
10398       if (sal.symtab == 0)
10399         error (_("No source file specified."));
10400
10401       sals.sals[0] = sal;
10402       sals.nelts = 1;
10403
10404       default_match = 1;
10405     }
10406
10407   /* We don't call resolve_sal_pc here.  That's not as bad as it
10408      seems, because all existing breakpoints typically have both
10409      file/line and pc set.  So, if clear is given file/line, we can
10410      match this to existing breakpoint without obtaining pc at all.
10411
10412      We only support clearing given the address explicitly 
10413      present in breakpoint table.  Say, we've set breakpoint 
10414      at file:line.  There were several PC values for that file:line,
10415      due to optimization, all in one block.
10416
10417      We've picked one PC value.  If "clear" is issued with another
10418      PC corresponding to the same file:line, the breakpoint won't
10419      be cleared.  We probably can still clear the breakpoint, but 
10420      since the other PC value is never presented to user, user
10421      can only find it by guessing, and it does not seem important
10422      to support that.  */
10423
10424   /* For each line spec given, delete bps which correspond to it.  Do
10425      it in two passes, solely to preserve the current behavior that
10426      from_tty is forced true if we delete more than one
10427      breakpoint.  */
10428
10429   found = NULL;
10430   make_cleanup (VEC_cleanup (breakpoint_p), &found);
10431   for (i = 0; i < sals.nelts; i++)
10432     {
10433       int is_abs, sal_name_len;
10434
10435       /* If exact pc given, clear bpts at that pc.
10436          If line given (pc == 0), clear all bpts on specified line.
10437          If defaulting, clear all bpts on default line
10438          or at default pc.
10439
10440          defaulting    sal.pc != 0    tests to do
10441
10442          0              1             pc
10443          1              1             pc _and_ line
10444          0              0             line
10445          1              0             <can't happen> */
10446
10447       sal = sals.sals[i];
10448       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
10449       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
10450
10451       /* Find all matching breakpoints and add them to 'found'.  */
10452       ALL_BREAKPOINTS (b)
10453         {
10454           int match = 0;
10455           /* Are we going to delete b?  */
10456           if (b->type != bp_none && !is_watchpoint (b))
10457             {
10458               struct bp_location *loc = b->loc;
10459               for (; loc; loc = loc->next)
10460                 {
10461                   /* If the user specified file:line, don't allow a PC
10462                      match.  This matches historical gdb behavior.  */
10463                   int pc_match = (!sal.explicit_line
10464                                   && sal.pc
10465                                   && (loc->pspace == sal.pspace)
10466                                   && (loc->address == sal.pc)
10467                                   && (!section_is_overlay (loc->section)
10468                                       || loc->section == sal.section));
10469                   int line_match = 0;
10470
10471                   if ((default_match || sal.explicit_line)
10472                       && loc->source_file != NULL
10473                       && sal.symtab != NULL
10474                       && sal.pspace == loc->pspace
10475                       && loc->line_number == sal.line)
10476                     {
10477                       if (filename_cmp (loc->source_file,
10478                                         sal.symtab->filename) == 0)
10479                         line_match = 1;
10480                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
10481                                && compare_filenames_for_search (loc->source_file,
10482                                                                 sal.symtab->filename,
10483                                                                 sal_name_len))
10484                         line_match = 1;
10485                     }
10486
10487                   if (pc_match || line_match)
10488                     {
10489                       match = 1;
10490                       break;
10491                     }
10492                 }
10493             }
10494
10495           if (match)
10496             VEC_safe_push(breakpoint_p, found, b);
10497         }
10498     }
10499
10500   /* Now go thru the 'found' chain and delete them.  */
10501   if (VEC_empty(breakpoint_p, found))
10502     {
10503       if (arg)
10504         error (_("No breakpoint at %s."), arg);
10505       else
10506         error (_("No breakpoint at this line."));
10507     }
10508
10509   /* Remove duplicates from the vec.  */
10510   qsort (VEC_address (breakpoint_p, found),
10511          VEC_length (breakpoint_p, found),
10512          sizeof (breakpoint_p),
10513          compare_breakpoints);
10514   prev = VEC_index (breakpoint_p, found, 0);
10515   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
10516     {
10517       if (b == prev)
10518         {
10519           VEC_ordered_remove (breakpoint_p, found, ix);
10520           --ix;
10521         }
10522     }
10523
10524   if (VEC_length(breakpoint_p, found) > 1)
10525     from_tty = 1;       /* Always report if deleted more than one.  */
10526   if (from_tty)
10527     {
10528       if (VEC_length(breakpoint_p, found) == 1)
10529         printf_unfiltered (_("Deleted breakpoint "));
10530       else
10531         printf_unfiltered (_("Deleted breakpoints "));
10532     }
10533   breakpoints_changed ();
10534
10535   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
10536     {
10537       if (from_tty)
10538         printf_unfiltered ("%d ", b->number);
10539       delete_breakpoint (b);
10540     }
10541   if (from_tty)
10542     putchar_unfiltered ('\n');
10543
10544   do_cleanups (cleanups);
10545 }
10546 \f
10547 /* Delete breakpoint in BS if they are `delete' breakpoints and
10548    all breakpoints that are marked for deletion, whether hit or not.
10549    This is called after any breakpoint is hit, or after errors.  */
10550
10551 void
10552 breakpoint_auto_delete (bpstat bs)
10553 {
10554   struct breakpoint *b, *b_tmp;
10555
10556   for (; bs; bs = bs->next)
10557     if (bs->breakpoint_at
10558         && bs->breakpoint_at->disposition == disp_del
10559         && bs->stop)
10560       delete_breakpoint (bs->breakpoint_at);
10561
10562   ALL_BREAKPOINTS_SAFE (b, b_tmp)
10563   {
10564     if (b->disposition == disp_del_at_next_stop)
10565       delete_breakpoint (b);
10566   }
10567 }
10568
10569 /* A comparison function for bp_location AP and BP being interfaced to
10570    qsort.  Sort elements primarily by their ADDRESS (no matter what
10571    does breakpoint_address_is_meaningful say for its OWNER),
10572    secondarily by ordering first bp_permanent OWNERed elements and
10573    terciarily just ensuring the array is sorted stable way despite
10574    qsort being an unstable algorithm.  */
10575
10576 static int
10577 bp_location_compare (const void *ap, const void *bp)
10578 {
10579   struct bp_location *a = *(void **) ap;
10580   struct bp_location *b = *(void **) bp;
10581   /* A and B come from existing breakpoints having non-NULL OWNER.  */
10582   int a_perm = a->owner->enable_state == bp_permanent;
10583   int b_perm = b->owner->enable_state == bp_permanent;
10584
10585   if (a->address != b->address)
10586     return (a->address > b->address) - (a->address < b->address);
10587
10588   /* Sort permanent breakpoints first.  */
10589   if (a_perm != b_perm)
10590     return (a_perm < b_perm) - (a_perm > b_perm);
10591
10592   /* Make the user-visible order stable across GDB runs.  Locations of
10593      the same breakpoint can be sorted in arbitrary order.  */
10594
10595   if (a->owner->number != b->owner->number)
10596     return (a->owner->number > b->owner->number)
10597            - (a->owner->number < b->owner->number);
10598
10599   return (a > b) - (a < b);
10600 }
10601
10602 /* Set bp_location_placed_address_before_address_max and
10603    bp_location_shadow_len_after_address_max according to the current
10604    content of the bp_location array.  */
10605
10606 static void
10607 bp_location_target_extensions_update (void)
10608 {
10609   struct bp_location *bl, **blp_tmp;
10610
10611   bp_location_placed_address_before_address_max = 0;
10612   bp_location_shadow_len_after_address_max = 0;
10613
10614   ALL_BP_LOCATIONS (bl, blp_tmp)
10615     {
10616       CORE_ADDR start, end, addr;
10617
10618       if (!bp_location_has_shadow (bl))
10619         continue;
10620
10621       start = bl->target_info.placed_address;
10622       end = start + bl->target_info.shadow_len;
10623
10624       gdb_assert (bl->address >= start);
10625       addr = bl->address - start;
10626       if (addr > bp_location_placed_address_before_address_max)
10627         bp_location_placed_address_before_address_max = addr;
10628
10629       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
10630
10631       gdb_assert (bl->address < end);
10632       addr = end - bl->address;
10633       if (addr > bp_location_shadow_len_after_address_max)
10634         bp_location_shadow_len_after_address_max = addr;
10635     }
10636 }
10637
10638 /* Download tracepoint locations if they haven't been.  */
10639
10640 static void
10641 download_tracepoint_locations (void)
10642 {
10643   struct bp_location *bl, **blp_tmp;
10644   struct cleanup *old_chain;
10645
10646   if (!target_can_download_tracepoint ())
10647     return;
10648
10649   old_chain = save_current_space_and_thread ();
10650
10651   ALL_BP_LOCATIONS (bl, blp_tmp)
10652     {
10653       struct tracepoint *t;
10654
10655       if (!is_tracepoint (bl->owner))
10656         continue;
10657
10658       if ((bl->owner->type == bp_fast_tracepoint
10659            ? !may_insert_fast_tracepoints
10660            : !may_insert_tracepoints))
10661         continue;
10662
10663       /* In tracepoint, locations are _never_ duplicated, so
10664          should_be_inserted is equivalent to
10665          unduplicated_should_be_inserted.  */
10666       if (!should_be_inserted (bl) || bl->inserted)
10667         continue;
10668
10669       switch_to_program_space_and_thread (bl->pspace);
10670
10671       target_download_tracepoint (bl);
10672
10673       bl->inserted = 1;
10674       t = (struct tracepoint *) bl->owner;
10675       t->number_on_target = bl->owner->number;
10676     }
10677
10678   do_cleanups (old_chain);
10679 }
10680
10681 /* Swap the insertion/duplication state between two locations.  */
10682
10683 static void
10684 swap_insertion (struct bp_location *left, struct bp_location *right)
10685 {
10686   const int left_inserted = left->inserted;
10687   const int left_duplicate = left->duplicate;
10688   const struct bp_target_info left_target_info = left->target_info;
10689
10690   /* Locations of tracepoints can never be duplicated.  */
10691   if (is_tracepoint (left->owner))
10692     gdb_assert (!left->duplicate);
10693   if (is_tracepoint (right->owner))
10694     gdb_assert (!right->duplicate);
10695
10696   left->inserted = right->inserted;
10697   left->duplicate = right->duplicate;
10698   left->target_info = right->target_info;
10699   right->inserted = left_inserted;
10700   right->duplicate = left_duplicate;
10701   right->target_info = left_target_info;
10702 }
10703
10704 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
10705    into the inferior, only remove already-inserted locations that no
10706    longer should be inserted.  Functions that delete a breakpoint or
10707    breakpoints should pass false, so that deleting a breakpoint
10708    doesn't have the side effect of inserting the locations of other
10709    breakpoints that are marked not-inserted, but should_be_inserted
10710    returns true on them.
10711
10712    This behaviour is useful is situations close to tear-down -- e.g.,
10713    after an exec, while the target still has execution, but breakpoint
10714    shadows of the previous executable image should *NOT* be restored
10715    to the new image; or before detaching, where the target still has
10716    execution and wants to delete breakpoints from GDB's lists, and all
10717    breakpoints had already been removed from the inferior.  */
10718
10719 static void
10720 update_global_location_list (int should_insert)
10721 {
10722   struct breakpoint *b;
10723   struct bp_location **locp, *loc;
10724   struct cleanup *cleanups;
10725
10726   /* Used in the duplicates detection below.  When iterating over all
10727      bp_locations, points to the first bp_location of a given address.
10728      Breakpoints and watchpoints of different types are never
10729      duplicates of each other.  Keep one pointer for each type of
10730      breakpoint/watchpoint, so we only need to loop over all locations
10731      once.  */
10732   struct bp_location *bp_loc_first;  /* breakpoint */
10733   struct bp_location *wp_loc_first;  /* hardware watchpoint */
10734   struct bp_location *awp_loc_first; /* access watchpoint */
10735   struct bp_location *rwp_loc_first; /* read watchpoint */
10736
10737   /* Saved former bp_location array which we compare against the newly
10738      built bp_location from the current state of ALL_BREAKPOINTS.  */
10739   struct bp_location **old_location, **old_locp;
10740   unsigned old_location_count;
10741
10742   old_location = bp_location;
10743   old_location_count = bp_location_count;
10744   bp_location = NULL;
10745   bp_location_count = 0;
10746   cleanups = make_cleanup (xfree, old_location);
10747
10748   ALL_BREAKPOINTS (b)
10749     for (loc = b->loc; loc; loc = loc->next)
10750       bp_location_count++;
10751
10752   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
10753   locp = bp_location;
10754   ALL_BREAKPOINTS (b)
10755     for (loc = b->loc; loc; loc = loc->next)
10756       *locp++ = loc;
10757   qsort (bp_location, bp_location_count, sizeof (*bp_location),
10758          bp_location_compare);
10759
10760   bp_location_target_extensions_update ();
10761
10762   /* Identify bp_location instances that are no longer present in the
10763      new list, and therefore should be freed.  Note that it's not
10764      necessary that those locations should be removed from inferior --
10765      if there's another location at the same address (previously
10766      marked as duplicate), we don't need to remove/insert the
10767      location.
10768      
10769      LOCP is kept in sync with OLD_LOCP, each pointing to the current
10770      and former bp_location array state respectively.  */
10771
10772   locp = bp_location;
10773   for (old_locp = old_location; old_locp < old_location + old_location_count;
10774        old_locp++)
10775     {
10776       struct bp_location *old_loc = *old_locp;
10777       struct bp_location **loc2p;
10778
10779       /* Tells if 'old_loc' is found among the new locations.  If
10780          not, we have to free it.  */
10781       int found_object = 0;
10782       /* Tells if the location should remain inserted in the target.  */
10783       int keep_in_target = 0;
10784       int removed = 0;
10785
10786       /* Skip LOCP entries which will definitely never be needed.
10787          Stop either at or being the one matching OLD_LOC.  */
10788       while (locp < bp_location + bp_location_count
10789              && (*locp)->address < old_loc->address)
10790         locp++;
10791
10792       for (loc2p = locp;
10793            (loc2p < bp_location + bp_location_count
10794             && (*loc2p)->address == old_loc->address);
10795            loc2p++)
10796         {
10797           if (*loc2p == old_loc)
10798             {
10799               found_object = 1;
10800               break;
10801             }
10802         }
10803
10804       /* If this location is no longer present, and inserted, look if
10805          there's maybe a new location at the same address.  If so,
10806          mark that one inserted, and don't remove this one.  This is
10807          needed so that we don't have a time window where a breakpoint
10808          at certain location is not inserted.  */
10809
10810       if (old_loc->inserted)
10811         {
10812           /* If the location is inserted now, we might have to remove
10813              it.  */
10814
10815           if (found_object && should_be_inserted (old_loc))
10816             {
10817               /* The location is still present in the location list,
10818                  and still should be inserted.  Don't do anything.  */
10819               keep_in_target = 1;
10820             }
10821           else
10822             {
10823               /* The location is either no longer present, or got
10824                  disabled.  See if there's another location at the
10825                  same address, in which case we don't need to remove
10826                  this one from the target.  */
10827
10828               /* OLD_LOC comes from existing struct breakpoint.  */
10829               if (breakpoint_address_is_meaningful (old_loc->owner))
10830                 {
10831                   for (loc2p = locp;
10832                        (loc2p < bp_location + bp_location_count
10833                         && (*loc2p)->address == old_loc->address);
10834                        loc2p++)
10835                     {
10836                       struct bp_location *loc2 = *loc2p;
10837
10838                       if (breakpoint_locations_match (loc2, old_loc))
10839                         {
10840                           /* Read watchpoint locations are switched to
10841                              access watchpoints, if the former are not
10842                              supported, but the latter are.  */
10843                           if (is_hardware_watchpoint (old_loc->owner))
10844                             {
10845                               gdb_assert (is_hardware_watchpoint (loc2->owner));
10846                               loc2->watchpoint_type = old_loc->watchpoint_type;
10847                             }
10848
10849                           /* loc2 is a duplicated location. We need to check
10850                              if it should be inserted in case it will be
10851                              unduplicated.  */
10852                           if (loc2 != old_loc
10853                               && unduplicated_should_be_inserted (loc2))
10854                             {
10855                               swap_insertion (old_loc, loc2);
10856                               keep_in_target = 1;
10857                               break;
10858                             }
10859                         }
10860                     }
10861                 }
10862             }
10863
10864           if (!keep_in_target)
10865             {
10866               if (remove_breakpoint (old_loc, mark_uninserted))
10867                 {
10868                   /* This is just about all we can do.  We could keep
10869                      this location on the global list, and try to
10870                      remove it next time, but there's no particular
10871                      reason why we will succeed next time.
10872                      
10873                      Note that at this point, old_loc->owner is still
10874                      valid, as delete_breakpoint frees the breakpoint
10875                      only after calling us.  */
10876                   printf_filtered (_("warning: Error removing "
10877                                      "breakpoint %d\n"), 
10878                                    old_loc->owner->number);
10879                 }
10880               removed = 1;
10881             }
10882         }
10883
10884       if (!found_object)
10885         {
10886           if (removed && non_stop
10887               && breakpoint_address_is_meaningful (old_loc->owner)
10888               && !is_hardware_watchpoint (old_loc->owner))
10889             {
10890               /* This location was removed from the target.  In
10891                  non-stop mode, a race condition is possible where
10892                  we've removed a breakpoint, but stop events for that
10893                  breakpoint are already queued and will arrive later.
10894                  We apply an heuristic to be able to distinguish such
10895                  SIGTRAPs from other random SIGTRAPs: we keep this
10896                  breakpoint location for a bit, and will retire it
10897                  after we see some number of events.  The theory here
10898                  is that reporting of events should, "on the average",
10899                  be fair, so after a while we'll see events from all
10900                  threads that have anything of interest, and no longer
10901                  need to keep this breakpoint location around.  We
10902                  don't hold locations forever so to reduce chances of
10903                  mistaking a non-breakpoint SIGTRAP for a breakpoint
10904                  SIGTRAP.
10905
10906                  The heuristic failing can be disastrous on
10907                  decr_pc_after_break targets.
10908
10909                  On decr_pc_after_break targets, like e.g., x86-linux,
10910                  if we fail to recognize a late breakpoint SIGTRAP,
10911                  because events_till_retirement has reached 0 too
10912                  soon, we'll fail to do the PC adjustment, and report
10913                  a random SIGTRAP to the user.  When the user resumes
10914                  the inferior, it will most likely immediately crash
10915                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
10916                  corrupted, because of being resumed e.g., in the
10917                  middle of a multi-byte instruction, or skipped a
10918                  one-byte instruction.  This was actually seen happen
10919                  on native x86-linux, and should be less rare on
10920                  targets that do not support new thread events, like
10921                  remote, due to the heuristic depending on
10922                  thread_count.
10923
10924                  Mistaking a random SIGTRAP for a breakpoint trap
10925                  causes similar symptoms (PC adjustment applied when
10926                  it shouldn't), but then again, playing with SIGTRAPs
10927                  behind the debugger's back is asking for trouble.
10928
10929                  Since hardware watchpoint traps are always
10930                  distinguishable from other traps, so we don't need to
10931                  apply keep hardware watchpoint moribund locations
10932                  around.  We simply always ignore hardware watchpoint
10933                  traps we can no longer explain.  */
10934
10935               old_loc->events_till_retirement = 3 * (thread_count () + 1);
10936               old_loc->owner = NULL;
10937
10938               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
10939             }
10940           else
10941             {
10942               old_loc->owner = NULL;
10943               decref_bp_location (&old_loc);
10944             }
10945         }
10946     }
10947
10948   /* Rescan breakpoints at the same address and section, marking the
10949      first one as "first" and any others as "duplicates".  This is so
10950      that the bpt instruction is only inserted once.  If we have a
10951      permanent breakpoint at the same place as BPT, make that one the
10952      official one, and the rest as duplicates.  Permanent breakpoints
10953      are sorted first for the same address.
10954
10955      Do the same for hardware watchpoints, but also considering the
10956      watchpoint's type (regular/access/read) and length.  */
10957
10958   bp_loc_first = NULL;
10959   wp_loc_first = NULL;
10960   awp_loc_first = NULL;
10961   rwp_loc_first = NULL;
10962   ALL_BP_LOCATIONS (loc, locp)
10963     {
10964       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
10965          non-NULL.  */
10966       struct bp_location **loc_first_p;
10967       b = loc->owner;
10968
10969       if (!should_be_inserted (loc)
10970           || !breakpoint_address_is_meaningful (b)
10971           /* Don't detect duplicate for tracepoint locations because they are
10972            never duplicated.  See the comments in field `duplicate' of
10973            `struct bp_location'.  */
10974           || is_tracepoint (b))
10975         continue;
10976
10977       /* Permanent breakpoint should always be inserted.  */
10978       if (b->enable_state == bp_permanent && ! loc->inserted)
10979         internal_error (__FILE__, __LINE__,
10980                         _("allegedly permanent breakpoint is not "
10981                         "actually inserted"));
10982
10983       if (b->type == bp_hardware_watchpoint)
10984         loc_first_p = &wp_loc_first;
10985       else if (b->type == bp_read_watchpoint)
10986         loc_first_p = &rwp_loc_first;
10987       else if (b->type == bp_access_watchpoint)
10988         loc_first_p = &awp_loc_first;
10989       else
10990         loc_first_p = &bp_loc_first;
10991
10992       if (*loc_first_p == NULL
10993           || (overlay_debugging && loc->section != (*loc_first_p)->section)
10994           || !breakpoint_locations_match (loc, *loc_first_p))
10995         {
10996           *loc_first_p = loc;
10997           loc->duplicate = 0;
10998           continue;
10999         }
11000
11001
11002       /* This and the above ensure the invariant that the first location
11003          is not duplicated, and is the inserted one.
11004          All following are marked as duplicated, and are not inserted.  */
11005       if (loc->inserted)
11006         swap_insertion (loc, *loc_first_p);
11007       loc->duplicate = 1;
11008
11009       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
11010           && b->enable_state != bp_permanent)
11011         internal_error (__FILE__, __LINE__,
11012                         _("another breakpoint was inserted on top of "
11013                         "a permanent breakpoint"));
11014     }
11015
11016   if (breakpoints_always_inserted_mode () && should_insert
11017       && (have_live_inferiors ()
11018           || (gdbarch_has_global_breakpoints (target_gdbarch))))
11019     insert_breakpoint_locations ();
11020
11021   if (should_insert)
11022     download_tracepoint_locations ();
11023
11024   do_cleanups (cleanups);
11025 }
11026
11027 void
11028 breakpoint_retire_moribund (void)
11029 {
11030   struct bp_location *loc;
11031   int ix;
11032
11033   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
11034     if (--(loc->events_till_retirement) == 0)
11035       {
11036         decref_bp_location (&loc);
11037         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
11038         --ix;
11039       }
11040 }
11041
11042 static void
11043 update_global_location_list_nothrow (int inserting)
11044 {
11045   volatile struct gdb_exception e;
11046
11047   TRY_CATCH (e, RETURN_MASK_ERROR)
11048     update_global_location_list (inserting);
11049 }
11050
11051 /* Clear BKP from a BPS.  */
11052
11053 static void
11054 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
11055 {
11056   bpstat bs;
11057
11058   for (bs = bps; bs; bs = bs->next)
11059     if (bs->breakpoint_at == bpt)
11060       {
11061         bs->breakpoint_at = NULL;
11062         bs->old_val = NULL;
11063         /* bs->commands will be freed later.  */
11064       }
11065 }
11066
11067 /* Callback for iterate_over_threads.  */
11068 static int
11069 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11070 {
11071   struct breakpoint *bpt = data;
11072
11073   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11074   return 0;
11075 }
11076
11077 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
11078    callbacks.  */
11079
11080 static void
11081 say_where (struct breakpoint *b)
11082 {
11083   struct ui_out *uiout = current_uiout;
11084   struct value_print_options opts;
11085
11086   get_user_print_options (&opts);
11087
11088   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11089      single string.  */
11090   if (b->loc == NULL)
11091     {
11092       printf_filtered (_(" (%s) pending."), b->addr_string);
11093     }
11094   else
11095     {
11096       if (opts.addressprint || b->loc->source_file == NULL)
11097         {
11098           printf_filtered (" at ");
11099           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
11100                           gdb_stdout);
11101         }
11102       if (b->loc->source_file)
11103         {
11104           /* If there is a single location, we can print the location
11105              more nicely.  */
11106           if (b->loc->next == NULL)
11107             printf_filtered (": file %s, line %d.",
11108                              b->loc->source_file, b->loc->line_number);
11109           else
11110             /* This is not ideal, but each location may have a
11111                different file name, and this at least reflects the
11112                real situation somewhat.  */
11113             printf_filtered (": %s.", b->addr_string);
11114         }
11115
11116       if (b->loc->next)
11117         {
11118           struct bp_location *loc = b->loc;
11119           int n = 0;
11120           for (; loc; loc = loc->next)
11121             ++n;
11122           printf_filtered (" (%d locations)", n);
11123         }
11124     }
11125 }
11126
11127 /* Default bp_location_ops methods.  */
11128
11129 static void
11130 bp_location_dtor (struct bp_location *self)
11131 {
11132   xfree (self->cond);
11133   xfree (self->function_name);
11134   xfree (self->source_file);
11135 }
11136
11137 static const struct bp_location_ops bp_location_ops =
11138 {
11139   bp_location_dtor
11140 };
11141
11142 /* Default breakpoint_ops methods all breakpoint_ops ultimately
11143    inherit from.  */
11144
11145 static void
11146 base_breakpoint_dtor (struct breakpoint *self)
11147 {
11148   decref_counted_command_line (&self->commands);
11149   xfree (self->cond_string);
11150   xfree (self->addr_string);
11151   xfree (self->filter);
11152   xfree (self->addr_string_range_end);
11153 }
11154
11155 static struct bp_location *
11156 base_breakpoint_allocate_location (struct breakpoint *self)
11157 {
11158   struct bp_location *loc;
11159
11160   loc = XNEW (struct bp_location);
11161   init_bp_location (loc, &bp_location_ops, self);
11162   return loc;
11163 }
11164
11165 static void
11166 base_breakpoint_re_set (struct breakpoint *b)
11167 {
11168   /* Nothing to re-set. */
11169 }
11170
11171 #define internal_error_pure_virtual_called() \
11172   gdb_assert_not_reached ("pure virtual function called")
11173
11174 static int
11175 base_breakpoint_insert_location (struct bp_location *bl)
11176 {
11177   internal_error_pure_virtual_called ();
11178 }
11179
11180 static int
11181 base_breakpoint_remove_location (struct bp_location *bl)
11182 {
11183   internal_error_pure_virtual_called ();
11184 }
11185
11186 static int
11187 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
11188                                 struct address_space *aspace,
11189                                 CORE_ADDR bp_addr,
11190                                 const struct target_waitstatus *ws)
11191 {
11192   internal_error_pure_virtual_called ();
11193 }
11194
11195 static void
11196 base_breakpoint_check_status (bpstat bs)
11197 {
11198   /* Always stop.   */
11199 }
11200
11201 /* A "works_in_software_mode" breakpoint_ops method that just internal
11202    errors.  */
11203
11204 static int
11205 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
11206 {
11207   internal_error_pure_virtual_called ();
11208 }
11209
11210 /* A "resources_needed" breakpoint_ops method that just internal
11211    errors.  */
11212
11213 static int
11214 base_breakpoint_resources_needed (const struct bp_location *bl)
11215 {
11216   internal_error_pure_virtual_called ();
11217 }
11218
11219 static enum print_stop_action
11220 base_breakpoint_print_it (bpstat bs)
11221 {
11222   internal_error_pure_virtual_called ();
11223 }
11224
11225 static void
11226 base_breakpoint_print_one_detail (const struct breakpoint *self,
11227                                   struct ui_out *uiout)
11228 {
11229   /* nothing */
11230 }
11231
11232 static void
11233 base_breakpoint_print_mention (struct breakpoint *b)
11234 {
11235   internal_error_pure_virtual_called ();
11236 }
11237
11238 static void
11239 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
11240 {
11241   internal_error_pure_virtual_called ();
11242 }
11243
11244 static void
11245 base_breakpoint_create_sals_from_address (char **arg,
11246                                           struct linespec_result *canonical,
11247                                           enum bptype type_wanted,
11248                                           char *addr_start,
11249                                           char **copy_arg)
11250 {
11251   internal_error_pure_virtual_called ();
11252 }
11253
11254 static void
11255 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
11256                                         struct linespec_result *c,
11257                                         struct linespec_sals *lsal,
11258                                         char *cond_string,
11259                                         enum bptype type_wanted,
11260                                         enum bpdisp disposition,
11261                                         int thread,
11262                                         int task, int ignore_count,
11263                                         const struct breakpoint_ops *o,
11264                                         int from_tty, int enabled,
11265                                         int internal)
11266 {
11267   internal_error_pure_virtual_called ();
11268 }
11269
11270 static void
11271 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
11272                                  struct symtabs_and_lines *sals)
11273 {
11274   internal_error_pure_virtual_called ();
11275 }
11276
11277 static struct breakpoint_ops base_breakpoint_ops =
11278 {
11279   base_breakpoint_dtor,
11280   base_breakpoint_allocate_location,
11281   base_breakpoint_re_set,
11282   base_breakpoint_insert_location,
11283   base_breakpoint_remove_location,
11284   base_breakpoint_breakpoint_hit,
11285   base_breakpoint_check_status,
11286   base_breakpoint_resources_needed,
11287   base_breakpoint_works_in_software_mode,
11288   base_breakpoint_print_it,
11289   NULL,
11290   base_breakpoint_print_one_detail,
11291   base_breakpoint_print_mention,
11292   base_breakpoint_print_recreate,
11293   base_breakpoint_create_sals_from_address,
11294   base_breakpoint_create_breakpoints_sal,
11295   base_breakpoint_decode_linespec,
11296 };
11297
11298 /* Default breakpoint_ops methods.  */
11299
11300 static void
11301 bkpt_re_set (struct breakpoint *b)
11302 {
11303   /* FIXME: is this still reachable?  */
11304   if (b->addr_string == NULL)
11305     {
11306       /* Anything without a string can't be re-set.  */
11307       delete_breakpoint (b);
11308       return;
11309     }
11310
11311   breakpoint_re_set_default (b);
11312 }
11313
11314 static int
11315 bkpt_insert_location (struct bp_location *bl)
11316 {
11317   if (bl->loc_type == bp_loc_hardware_breakpoint)
11318     return target_insert_hw_breakpoint (bl->gdbarch,
11319                                         &bl->target_info);
11320   else
11321     return target_insert_breakpoint (bl->gdbarch,
11322                                      &bl->target_info);
11323 }
11324
11325 static int
11326 bkpt_remove_location (struct bp_location *bl)
11327 {
11328   if (bl->loc_type == bp_loc_hardware_breakpoint)
11329     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
11330   else
11331     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
11332 }
11333
11334 static int
11335 bkpt_breakpoint_hit (const struct bp_location *bl,
11336                      struct address_space *aspace, CORE_ADDR bp_addr,
11337                      const struct target_waitstatus *ws)
11338 {
11339   struct breakpoint *b = bl->owner;
11340
11341   if (ws->kind != TARGET_WAITKIND_STOPPED
11342       || ws->value.sig != TARGET_SIGNAL_TRAP)
11343     return 0;
11344
11345   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
11346                                  aspace, bp_addr))
11347     return 0;
11348
11349   if (overlay_debugging         /* unmapped overlay section */
11350       && section_is_overlay (bl->section)
11351       && !section_is_mapped (bl->section))
11352     return 0;
11353
11354   return 1;
11355 }
11356
11357 static int
11358 bkpt_resources_needed (const struct bp_location *bl)
11359 {
11360   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
11361
11362   return 1;
11363 }
11364
11365 static enum print_stop_action
11366 bkpt_print_it (bpstat bs)
11367 {
11368   struct breakpoint *b;
11369   const struct bp_location *bl;
11370   int bp_temp;
11371   struct ui_out *uiout = current_uiout;
11372
11373   gdb_assert (bs->bp_location_at != NULL);
11374
11375   bl = bs->bp_location_at;
11376   b = bs->breakpoint_at;
11377
11378   bp_temp = b->disposition == disp_del;
11379   if (bl->address != bl->requested_address)
11380     breakpoint_adjustment_warning (bl->requested_address,
11381                                    bl->address,
11382                                    b->number, 1);
11383   annotate_breakpoint (b->number);
11384   if (bp_temp)
11385     ui_out_text (uiout, "\nTemporary breakpoint ");
11386   else
11387     ui_out_text (uiout, "\nBreakpoint ");
11388   if (ui_out_is_mi_like_p (uiout))
11389     {
11390       ui_out_field_string (uiout, "reason",
11391                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11392       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11393     }
11394   ui_out_field_int (uiout, "bkptno", b->number);
11395   ui_out_text (uiout, ", ");
11396
11397   return PRINT_SRC_AND_LOC;
11398 }
11399
11400 static void
11401 bkpt_print_mention (struct breakpoint *b)
11402 {
11403   if (ui_out_is_mi_like_p (current_uiout))
11404     return;
11405
11406   switch (b->type)
11407     {
11408     case bp_breakpoint:
11409     case bp_gnu_ifunc_resolver:
11410       if (b->disposition == disp_del)
11411         printf_filtered (_("Temporary breakpoint"));
11412       else
11413         printf_filtered (_("Breakpoint"));
11414       printf_filtered (_(" %d"), b->number);
11415       if (b->type == bp_gnu_ifunc_resolver)
11416         printf_filtered (_(" at gnu-indirect-function resolver"));
11417       break;
11418     case bp_hardware_breakpoint:
11419       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
11420       break;
11421     }
11422
11423   say_where (b);
11424 }
11425
11426 static void
11427 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
11428 {
11429   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
11430     fprintf_unfiltered (fp, "tbreak");
11431   else if (tp->type == bp_breakpoint)
11432     fprintf_unfiltered (fp, "break");
11433   else if (tp->type == bp_hardware_breakpoint
11434            && tp->disposition == disp_del)
11435     fprintf_unfiltered (fp, "thbreak");
11436   else if (tp->type == bp_hardware_breakpoint)
11437     fprintf_unfiltered (fp, "hbreak");
11438   else
11439     internal_error (__FILE__, __LINE__,
11440                     _("unhandled breakpoint type %d"), (int) tp->type);
11441
11442   fprintf_unfiltered (fp, " %s", tp->addr_string);
11443   print_recreate_thread (tp, fp);
11444 }
11445
11446 static void
11447 bkpt_create_sals_from_address (char **arg,
11448                                struct linespec_result *canonical,
11449                                enum bptype type_wanted,
11450                                char *addr_start, char **copy_arg)
11451 {
11452   create_sals_from_address_default (arg, canonical, type_wanted,
11453                                     addr_start, copy_arg);
11454 }
11455
11456 static void
11457 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
11458                              struct linespec_result *canonical,
11459                              struct linespec_sals *lsal,
11460                              char *cond_string,
11461                              enum bptype type_wanted,
11462                              enum bpdisp disposition,
11463                              int thread,
11464                              int task, int ignore_count,
11465                              const struct breakpoint_ops *ops,
11466                              int from_tty, int enabled,
11467                              int internal)
11468 {
11469   create_breakpoints_sal_default (gdbarch, canonical, lsal,
11470                                   cond_string, type_wanted,
11471                                   disposition, thread, task,
11472                                   ignore_count, ops, from_tty,
11473                                   enabled, internal);
11474 }
11475
11476 static void
11477 bkpt_decode_linespec (struct breakpoint *b, char **s,
11478                       struct symtabs_and_lines *sals)
11479 {
11480   decode_linespec_default (b, s, sals);
11481 }
11482
11483 /* Virtual table for internal breakpoints.  */
11484
11485 static void
11486 internal_bkpt_re_set (struct breakpoint *b)
11487 {
11488   switch (b->type)
11489     {
11490       /* Delete overlay event and longjmp master breakpoints; they
11491          will be reset later by breakpoint_re_set.  */
11492     case bp_overlay_event:
11493     case bp_longjmp_master:
11494     case bp_std_terminate_master:
11495     case bp_exception_master:
11496       delete_breakpoint (b);
11497       break;
11498
11499       /* This breakpoint is special, it's set up when the inferior
11500          starts and we really don't want to touch it.  */
11501     case bp_shlib_event:
11502
11503       /* Like bp_shlib_event, this breakpoint type is special.  Once
11504          it is set up, we do not want to touch it.  */
11505     case bp_thread_event:
11506       break;
11507     }
11508 }
11509
11510 static void
11511 internal_bkpt_check_status (bpstat bs)
11512 {
11513   if (bs->breakpoint_at->type == bp_shlib_event)
11514     {
11515       /* If requested, stop when the dynamic linker notifies GDB of
11516          events.  This allows the user to get control and place
11517          breakpoints in initializer routines for dynamically loaded
11518          objects (among other things).  */
11519       bs->stop = stop_on_solib_events;
11520       bs->print = stop_on_solib_events;
11521     }
11522   else
11523     bs->stop = 0;
11524 }
11525
11526 static enum print_stop_action
11527 internal_bkpt_print_it (bpstat bs)
11528 {
11529   struct ui_out *uiout = current_uiout;
11530   struct breakpoint *b;
11531
11532   b = bs->breakpoint_at;
11533
11534   switch (b->type)
11535     {
11536     case bp_shlib_event:
11537       /* Did we stop because the user set the stop_on_solib_events
11538          variable?  (If so, we report this as a generic, "Stopped due
11539          to shlib event" message.) */
11540       print_solib_event (0);
11541       break;
11542
11543     case bp_thread_event:
11544       /* Not sure how we will get here.
11545          GDB should not stop for these breakpoints.  */
11546       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
11547       break;
11548
11549     case bp_overlay_event:
11550       /* By analogy with the thread event, GDB should not stop for these.  */
11551       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
11552       break;
11553
11554     case bp_longjmp_master:
11555       /* These should never be enabled.  */
11556       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
11557       break;
11558
11559     case bp_std_terminate_master:
11560       /* These should never be enabled.  */
11561       printf_filtered (_("std::terminate Master Breakpoint: "
11562                          "gdb should not stop!\n"));
11563       break;
11564
11565     case bp_exception_master:
11566       /* These should never be enabled.  */
11567       printf_filtered (_("Exception Master Breakpoint: "
11568                          "gdb should not stop!\n"));
11569       break;
11570     }
11571
11572   return PRINT_NOTHING;
11573 }
11574
11575 static void
11576 internal_bkpt_print_mention (struct breakpoint *b)
11577 {
11578   /* Nothing to mention.  These breakpoints are internal.  */
11579 }
11580
11581 /* Virtual table for momentary breakpoints  */
11582
11583 static void
11584 momentary_bkpt_re_set (struct breakpoint *b)
11585 {
11586   /* Keep temporary breakpoints, which can be encountered when we step
11587      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
11588      Otherwise these should have been blown away via the cleanup chain
11589      or by breakpoint_init_inferior when we rerun the executable.  */
11590 }
11591
11592 static void
11593 momentary_bkpt_check_status (bpstat bs)
11594 {
11595   /* Nothing.  The point of these breakpoints is causing a stop.  */
11596 }
11597
11598 static enum print_stop_action
11599 momentary_bkpt_print_it (bpstat bs)
11600 {
11601   struct ui_out *uiout = current_uiout;
11602
11603   if (ui_out_is_mi_like_p (uiout))
11604     {
11605       struct breakpoint *b = bs->breakpoint_at;
11606
11607       switch (b->type)
11608         {
11609         case bp_finish:
11610           ui_out_field_string
11611             (uiout, "reason",
11612              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
11613           break;
11614
11615         case bp_until:
11616           ui_out_field_string
11617             (uiout, "reason",
11618              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
11619           break;
11620         }
11621     }
11622
11623   return PRINT_UNKNOWN;
11624 }
11625
11626 static void
11627 momentary_bkpt_print_mention (struct breakpoint *b)
11628 {
11629   /* Nothing to mention.  These breakpoints are internal.  */
11630 }
11631
11632 /* The breakpoint_ops structure to be used in tracepoints.  */
11633
11634 static void
11635 tracepoint_re_set (struct breakpoint *b)
11636 {
11637   breakpoint_re_set_default (b);
11638 }
11639
11640 static int
11641 tracepoint_breakpoint_hit (const struct bp_location *bl,
11642                            struct address_space *aspace, CORE_ADDR bp_addr,
11643                            const struct target_waitstatus *ws)
11644 {
11645   /* By definition, the inferior does not report stops at
11646      tracepoints.  */
11647   return 0;
11648 }
11649
11650 static void
11651 tracepoint_print_one_detail (const struct breakpoint *self,
11652                              struct ui_out *uiout)
11653 {
11654   struct tracepoint *tp = (struct tracepoint *) self;
11655   if (tp->static_trace_marker_id)
11656     {
11657       gdb_assert (self->type == bp_static_tracepoint);
11658
11659       ui_out_text (uiout, "\tmarker id is ");
11660       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
11661                            tp->static_trace_marker_id);
11662       ui_out_text (uiout, "\n");
11663     }
11664 }
11665
11666 static void
11667 tracepoint_print_mention (struct breakpoint *b)
11668 {
11669   if (ui_out_is_mi_like_p (current_uiout))
11670     return;
11671
11672   switch (b->type)
11673     {
11674     case bp_tracepoint:
11675       printf_filtered (_("Tracepoint"));
11676       printf_filtered (_(" %d"), b->number);
11677       break;
11678     case bp_fast_tracepoint:
11679       printf_filtered (_("Fast tracepoint"));
11680       printf_filtered (_(" %d"), b->number);
11681       break;
11682     case bp_static_tracepoint:
11683       printf_filtered (_("Static tracepoint"));
11684       printf_filtered (_(" %d"), b->number);
11685       break;
11686     default:
11687       internal_error (__FILE__, __LINE__,
11688                       _("unhandled tracepoint type %d"), (int) b->type);
11689     }
11690
11691   say_where (b);
11692 }
11693
11694 static void
11695 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
11696 {
11697   struct tracepoint *tp = (struct tracepoint *) self;
11698
11699   if (self->type == bp_fast_tracepoint)
11700     fprintf_unfiltered (fp, "ftrace");
11701   if (self->type == bp_static_tracepoint)
11702     fprintf_unfiltered (fp, "strace");
11703   else if (self->type == bp_tracepoint)
11704     fprintf_unfiltered (fp, "trace");
11705   else
11706     internal_error (__FILE__, __LINE__,
11707                     _("unhandled tracepoint type %d"), (int) self->type);
11708
11709   fprintf_unfiltered (fp, " %s", self->addr_string);
11710   print_recreate_thread (self, fp);
11711
11712   if (tp->pass_count)
11713     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
11714 }
11715
11716 static void
11717 tracepoint_create_sals_from_address (char **arg,
11718                                      struct linespec_result *canonical,
11719                                      enum bptype type_wanted,
11720                                      char *addr_start, char **copy_arg)
11721 {
11722   create_sals_from_address_default (arg, canonical, type_wanted,
11723                                     addr_start, copy_arg);
11724 }
11725
11726 static void
11727 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
11728                                    struct linespec_result *canonical,
11729                                    struct linespec_sals *lsal,
11730                                    char *cond_string,
11731                                    enum bptype type_wanted,
11732                                    enum bpdisp disposition,
11733                                    int thread,
11734                                    int task, int ignore_count,
11735                                    const struct breakpoint_ops *ops,
11736                                    int from_tty, int enabled,
11737                                    int internal)
11738 {
11739   create_breakpoints_sal_default (gdbarch, canonical, lsal,
11740                                   cond_string, type_wanted,
11741                                   disposition, thread, task,
11742                                   ignore_count, ops, from_tty,
11743                                   enabled, internal);
11744 }
11745
11746 static void
11747 tracepoint_decode_linespec (struct breakpoint *b, char **s,
11748                             struct symtabs_and_lines *sals)
11749 {
11750   decode_linespec_default (b, s, sals);
11751 }
11752
11753 struct breakpoint_ops tracepoint_breakpoint_ops;
11754
11755 /* The breakpoint_ops structure to be used on static tracepoints with
11756    markers (`-m').  */
11757
11758 static void
11759 strace_marker_create_sals_from_address (char **arg,
11760                                         struct linespec_result *canonical,
11761                                         enum bptype type_wanted,
11762                                         char *addr_start, char **copy_arg)
11763 {
11764   struct linespec_sals lsal;
11765
11766   lsal.sals = decode_static_tracepoint_spec (arg);
11767
11768   *copy_arg = savestring (addr_start, *arg - addr_start);
11769
11770   canonical->addr_string = xstrdup (*copy_arg);
11771   lsal.canonical = xstrdup (*copy_arg);
11772   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
11773 }
11774
11775 static void
11776 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
11777                                       struct linespec_result *canonical,
11778                                       struct linespec_sals *lsal,
11779                                       char *cond_string,
11780                                       enum bptype type_wanted,
11781                                       enum bpdisp disposition,
11782                                       int thread,
11783                                       int task, int ignore_count,
11784                                       const struct breakpoint_ops *ops,
11785                                       int from_tty, int enabled,
11786                                       int internal)
11787 {
11788   int i;
11789
11790   /* If the user is creating a static tracepoint by marker id
11791      (strace -m MARKER_ID), then store the sals index, so that
11792      breakpoint_re_set can try to match up which of the newly
11793      found markers corresponds to this one, and, don't try to
11794      expand multiple locations for each sal, given than SALS
11795      already should contain all sals for MARKER_ID.  */
11796
11797   for (i = 0; i < lsal->sals.nelts; ++i)
11798     {
11799       struct symtabs_and_lines expanded;
11800       struct tracepoint *tp;
11801       struct cleanup *old_chain;
11802       char *addr_string;
11803
11804       expanded.nelts = 1;
11805       expanded.sals = &lsal->sals.sals[i];
11806
11807       addr_string = xstrdup (canonical->addr_string);
11808       old_chain = make_cleanup (xfree, addr_string);
11809
11810       tp = XCNEW (struct tracepoint);
11811       init_breakpoint_sal (&tp->base, gdbarch, expanded,
11812                            addr_string, NULL,
11813                            cond_string, type_wanted, disposition,
11814                            thread, task, ignore_count, ops,
11815                            from_tty, enabled, internal,
11816                            canonical->special_display);
11817       /* Given that its possible to have multiple markers with
11818          the same string id, if the user is creating a static
11819          tracepoint by marker id ("strace -m MARKER_ID"), then
11820          store the sals index, so that breakpoint_re_set can
11821          try to match up which of the newly found markers
11822          corresponds to this one  */
11823       tp->static_trace_marker_id_idx = i;
11824
11825       install_breakpoint (internal, &tp->base, 0);
11826
11827       discard_cleanups (old_chain);
11828     }
11829 }
11830
11831 static void
11832 strace_marker_decode_linespec (struct breakpoint *b, char **s,
11833                                struct symtabs_and_lines *sals)
11834 {
11835   struct tracepoint *tp = (struct tracepoint *) b;
11836
11837   *sals = decode_static_tracepoint_spec (s);
11838   if (sals->nelts > tp->static_trace_marker_id_idx)
11839     {
11840       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
11841       sals->nelts = 1;
11842     }
11843   else
11844     error (_("marker %s not found"), tp->static_trace_marker_id);
11845 }
11846
11847 static struct breakpoint_ops strace_marker_breakpoint_ops;
11848
11849 static int
11850 strace_marker_p (struct breakpoint *b)
11851 {
11852   return b->ops == &strace_marker_breakpoint_ops;
11853 }
11854
11855 /* Delete a breakpoint and clean up all traces of it in the data
11856    structures.  */
11857
11858 void
11859 delete_breakpoint (struct breakpoint *bpt)
11860 {
11861   struct breakpoint *b;
11862
11863   gdb_assert (bpt != NULL);
11864
11865   /* Has this bp already been deleted?  This can happen because
11866      multiple lists can hold pointers to bp's.  bpstat lists are
11867      especial culprits.
11868
11869      One example of this happening is a watchpoint's scope bp.  When
11870      the scope bp triggers, we notice that the watchpoint is out of
11871      scope, and delete it.  We also delete its scope bp.  But the
11872      scope bp is marked "auto-deleting", and is already on a bpstat.
11873      That bpstat is then checked for auto-deleting bp's, which are
11874      deleted.
11875
11876      A real solution to this problem might involve reference counts in
11877      bp's, and/or giving them pointers back to their referencing
11878      bpstat's, and teaching delete_breakpoint to only free a bp's
11879      storage when no more references were extent.  A cheaper bandaid
11880      was chosen.  */
11881   if (bpt->type == bp_none)
11882     return;
11883
11884   /* At least avoid this stale reference until the reference counting
11885      of breakpoints gets resolved.  */
11886   if (bpt->related_breakpoint != bpt)
11887     {
11888       struct breakpoint *related;
11889       struct watchpoint *w;
11890
11891       if (bpt->type == bp_watchpoint_scope)
11892         w = (struct watchpoint *) bpt->related_breakpoint;
11893       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
11894         w = (struct watchpoint *) bpt;
11895       else
11896         w = NULL;
11897       if (w != NULL)
11898         watchpoint_del_at_next_stop (w);
11899
11900       /* Unlink bpt from the bpt->related_breakpoint ring.  */
11901       for (related = bpt; related->related_breakpoint != bpt;
11902            related = related->related_breakpoint);
11903       related->related_breakpoint = bpt->related_breakpoint;
11904       bpt->related_breakpoint = bpt;
11905     }
11906
11907   /* watch_command_1 creates a watchpoint but only sets its number if
11908      update_watchpoint succeeds in creating its bp_locations.  If there's
11909      a problem in that process, we'll be asked to delete the half-created
11910      watchpoint.  In that case, don't announce the deletion.  */
11911   if (bpt->number)
11912     observer_notify_breakpoint_deleted (bpt);
11913
11914   if (breakpoint_chain == bpt)
11915     breakpoint_chain = bpt->next;
11916
11917   ALL_BREAKPOINTS (b)
11918     if (b->next == bpt)
11919     {
11920       b->next = bpt->next;
11921       break;
11922     }
11923
11924   /* Be sure no bpstat's are pointing at the breakpoint after it's
11925      been freed.  */
11926   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
11927      in all threads for now.  Note that we cannot just remove bpstats
11928      pointing at bpt from the stop_bpstat list entirely, as breakpoint
11929      commands are associated with the bpstat; if we remove it here,
11930      then the later call to bpstat_do_actions (&stop_bpstat); in
11931      event-top.c won't do anything, and temporary breakpoints with
11932      commands won't work.  */
11933
11934   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
11935
11936   /* Now that breakpoint is removed from breakpoint list, update the
11937      global location list.  This will remove locations that used to
11938      belong to this breakpoint.  Do this before freeing the breakpoint
11939      itself, since remove_breakpoint looks at location's owner.  It
11940      might be better design to have location completely
11941      self-contained, but it's not the case now.  */
11942   update_global_location_list (0);
11943
11944   bpt->ops->dtor (bpt);
11945   /* On the chance that someone will soon try again to delete this
11946      same bp, we mark it as deleted before freeing its storage.  */
11947   bpt->type = bp_none;
11948   xfree (bpt);
11949 }
11950
11951 static void
11952 do_delete_breakpoint_cleanup (void *b)
11953 {
11954   delete_breakpoint (b);
11955 }
11956
11957 struct cleanup *
11958 make_cleanup_delete_breakpoint (struct breakpoint *b)
11959 {
11960   return make_cleanup (do_delete_breakpoint_cleanup, b);
11961 }
11962
11963 /* Iterator function to call a user-provided callback function once
11964    for each of B and its related breakpoints.  */
11965
11966 static void
11967 iterate_over_related_breakpoints (struct breakpoint *b,
11968                                   void (*function) (struct breakpoint *,
11969                                                     void *),
11970                                   void *data)
11971 {
11972   struct breakpoint *related;
11973
11974   related = b;
11975   do
11976     {
11977       struct breakpoint *next;
11978
11979       /* FUNCTION may delete RELATED.  */
11980       next = related->related_breakpoint;
11981
11982       if (next == related)
11983         {
11984           /* RELATED is the last ring entry.  */
11985           function (related, data);
11986
11987           /* FUNCTION may have deleted it, so we'd never reach back to
11988              B.  There's nothing left to do anyway, so just break
11989              out.  */
11990           break;
11991         }
11992       else
11993         function (related, data);
11994
11995       related = next;
11996     }
11997   while (related != b);
11998 }
11999
12000 static void
12001 do_delete_breakpoint (struct breakpoint *b, void *ignore)
12002 {
12003   delete_breakpoint (b);
12004 }
12005
12006 /* A callback for map_breakpoint_numbers that calls
12007    delete_breakpoint.  */
12008
12009 static void
12010 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
12011 {
12012   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
12013 }
12014
12015 void
12016 delete_command (char *arg, int from_tty)
12017 {
12018   struct breakpoint *b, *b_tmp;
12019
12020   dont_repeat ();
12021
12022   if (arg == 0)
12023     {
12024       int breaks_to_delete = 0;
12025
12026       /* Delete all breakpoints if no argument.  Do not delete
12027          internal breakpoints, these have to be deleted with an
12028          explicit breakpoint number argument.  */
12029       ALL_BREAKPOINTS (b)
12030         if (user_breakpoint_p (b))
12031           {
12032             breaks_to_delete = 1;
12033             break;
12034           }
12035
12036       /* Ask user only if there are some breakpoints to delete.  */
12037       if (!from_tty
12038           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12039         {
12040           ALL_BREAKPOINTS_SAFE (b, b_tmp)
12041             if (user_breakpoint_p (b))
12042               delete_breakpoint (b);
12043         }
12044     }
12045   else
12046     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
12047 }
12048
12049 static int
12050 all_locations_are_pending (struct bp_location *loc)
12051 {
12052   for (; loc; loc = loc->next)
12053     if (!loc->shlib_disabled
12054         && !loc->pspace->executing_startup)
12055       return 0;
12056   return 1;
12057 }
12058
12059 /* Subroutine of update_breakpoint_locations to simplify it.
12060    Return non-zero if multiple fns in list LOC have the same name.
12061    Null names are ignored.  */
12062
12063 static int
12064 ambiguous_names_p (struct bp_location *loc)
12065 {
12066   struct bp_location *l;
12067   htab_t htab = htab_create_alloc (13, htab_hash_string,
12068                                    (int (*) (const void *, 
12069                                              const void *)) streq,
12070                                    NULL, xcalloc, xfree);
12071
12072   for (l = loc; l != NULL; l = l->next)
12073     {
12074       const char **slot;
12075       const char *name = l->function_name;
12076
12077       /* Allow for some names to be NULL, ignore them.  */
12078       if (name == NULL)
12079         continue;
12080
12081       slot = (const char **) htab_find_slot (htab, (const void *) name,
12082                                              INSERT);
12083       /* NOTE: We can assume slot != NULL here because xcalloc never
12084          returns NULL.  */
12085       if (*slot != NULL)
12086         {
12087           htab_delete (htab);
12088           return 1;
12089         }
12090       *slot = name;
12091     }
12092
12093   htab_delete (htab);
12094   return 0;
12095 }
12096
12097 /* When symbols change, it probably means the sources changed as well,
12098    and it might mean the static tracepoint markers are no longer at
12099    the same address or line numbers they used to be at last we
12100    checked.  Losing your static tracepoints whenever you rebuild is
12101    undesirable.  This function tries to resync/rematch gdb static
12102    tracepoints with the markers on the target, for static tracepoints
12103    that have not been set by marker id.  Static tracepoint that have
12104    been set by marker id are reset by marker id in breakpoint_re_set.
12105    The heuristic is:
12106
12107    1) For a tracepoint set at a specific address, look for a marker at
12108    the old PC.  If one is found there, assume to be the same marker.
12109    If the name / string id of the marker found is different from the
12110    previous known name, assume that means the user renamed the marker
12111    in the sources, and output a warning.
12112
12113    2) For a tracepoint set at a given line number, look for a marker
12114    at the new address of the old line number.  If one is found there,
12115    assume to be the same marker.  If the name / string id of the
12116    marker found is different from the previous known name, assume that
12117    means the user renamed the marker in the sources, and output a
12118    warning.
12119
12120    3) If a marker is no longer found at the same address or line, it
12121    may mean the marker no longer exists.  But it may also just mean
12122    the code changed a bit.  Maybe the user added a few lines of code
12123    that made the marker move up or down (in line number terms).  Ask
12124    the target for info about the marker with the string id as we knew
12125    it.  If found, update line number and address in the matching
12126    static tracepoint.  This will get confused if there's more than one
12127    marker with the same ID (possible in UST, although unadvised
12128    precisely because it confuses tools).  */
12129
12130 static struct symtab_and_line
12131 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12132 {
12133   struct tracepoint *tp = (struct tracepoint *) b;
12134   struct static_tracepoint_marker marker;
12135   CORE_ADDR pc;
12136   int i;
12137
12138   pc = sal.pc;
12139   if (sal.line)
12140     find_line_pc (sal.symtab, sal.line, &pc);
12141
12142   if (target_static_tracepoint_marker_at (pc, &marker))
12143     {
12144       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
12145         warning (_("static tracepoint %d changed probed marker from %s to %s"),
12146                  b->number,
12147                  tp->static_trace_marker_id, marker.str_id);
12148
12149       xfree (tp->static_trace_marker_id);
12150       tp->static_trace_marker_id = xstrdup (marker.str_id);
12151       release_static_tracepoint_marker (&marker);
12152
12153       return sal;
12154     }
12155
12156   /* Old marker wasn't found on target at lineno.  Try looking it up
12157      by string ID.  */
12158   if (!sal.explicit_pc
12159       && sal.line != 0
12160       && sal.symtab != NULL
12161       && tp->static_trace_marker_id != NULL)
12162     {
12163       VEC(static_tracepoint_marker_p) *markers;
12164
12165       markers
12166         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
12167
12168       if (!VEC_empty(static_tracepoint_marker_p, markers))
12169         {
12170           struct symtab_and_line sal2;
12171           struct symbol *sym;
12172           struct static_tracepoint_marker *tpmarker;
12173           struct ui_out *uiout = current_uiout;
12174
12175           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
12176
12177           xfree (tp->static_trace_marker_id);
12178           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
12179
12180           warning (_("marker for static tracepoint %d (%s) not "
12181                      "found at previous line number"),
12182                    b->number, tp->static_trace_marker_id);
12183
12184           init_sal (&sal2);
12185
12186           sal2.pc = tpmarker->address;
12187
12188           sal2 = find_pc_line (tpmarker->address, 0);
12189           sym = find_pc_sect_function (tpmarker->address, NULL);
12190           ui_out_text (uiout, "Now in ");
12191           if (sym)
12192             {
12193               ui_out_field_string (uiout, "func",
12194                                    SYMBOL_PRINT_NAME (sym));
12195               ui_out_text (uiout, " at ");
12196             }
12197           ui_out_field_string (uiout, "file", sal2.symtab->filename);
12198           ui_out_text (uiout, ":");
12199
12200           if (ui_out_is_mi_like_p (uiout))
12201             {
12202               char *fullname = symtab_to_fullname (sal2.symtab);
12203
12204               if (fullname)
12205                 ui_out_field_string (uiout, "fullname", fullname);
12206             }
12207
12208           ui_out_field_int (uiout, "line", sal2.line);
12209           ui_out_text (uiout, "\n");
12210
12211           b->loc->line_number = sal2.line;
12212
12213           xfree (b->loc->source_file);
12214           if (sym)
12215             b->loc->source_file = xstrdup (sal2.symtab->filename);
12216           else
12217             b->loc->source_file = NULL;
12218
12219           xfree (b->addr_string);
12220           b->addr_string = xstrprintf ("%s:%d",
12221                                        sal2.symtab->filename,
12222                                        b->loc->line_number);
12223
12224           /* Might be nice to check if function changed, and warn if
12225              so.  */
12226
12227           release_static_tracepoint_marker (tpmarker);
12228         }
12229     }
12230   return sal;
12231 }
12232
12233 /* Returns 1 iff locations A and B are sufficiently same that
12234    we don't need to report breakpoint as changed.  */
12235
12236 static int
12237 locations_are_equal (struct bp_location *a, struct bp_location *b)
12238 {
12239   while (a && b)
12240     {
12241       if (a->address != b->address)
12242         return 0;
12243
12244       if (a->shlib_disabled != b->shlib_disabled)
12245         return 0;
12246
12247       if (a->enabled != b->enabled)
12248         return 0;
12249
12250       a = a->next;
12251       b = b->next;
12252     }
12253
12254   if ((a == NULL) != (b == NULL))
12255     return 0;
12256
12257   return 1;
12258 }
12259
12260 /* Create new breakpoint locations for B (a hardware or software breakpoint)
12261    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
12262    a ranged breakpoint.  */
12263
12264 void
12265 update_breakpoint_locations (struct breakpoint *b,
12266                              struct symtabs_and_lines sals,
12267                              struct symtabs_and_lines sals_end)
12268 {
12269   int i;
12270   struct bp_location *existing_locations = b->loc;
12271
12272   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
12273     {
12274       /* Ranged breakpoints have only one start location and one end
12275          location.  */
12276       b->enable_state = bp_disabled;
12277       update_global_location_list (1);
12278       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
12279                            "multiple locations found\n"),
12280                          b->number);
12281       return;
12282     }
12283
12284   /* If there's no new locations, and all existing locations are
12285      pending, don't do anything.  This optimizes the common case where
12286      all locations are in the same shared library, that was unloaded.
12287      We'd like to retain the location, so that when the library is
12288      loaded again, we don't loose the enabled/disabled status of the
12289      individual locations.  */
12290   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
12291     return;
12292
12293   b->loc = NULL;
12294
12295   for (i = 0; i < sals.nelts; ++i)
12296     {
12297       struct bp_location *new_loc;
12298
12299       switch_to_program_space_and_thread (sals.sals[i].pspace);
12300
12301       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
12302
12303       /* Reparse conditions, they might contain references to the
12304          old symtab.  */
12305       if (b->cond_string != NULL)
12306         {
12307           char *s;
12308           volatile struct gdb_exception e;
12309
12310           s = b->cond_string;
12311           TRY_CATCH (e, RETURN_MASK_ERROR)
12312             {
12313               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
12314                                            0);
12315             }
12316           if (e.reason < 0)
12317             {
12318               warning (_("failed to reevaluate condition "
12319                          "for breakpoint %d: %s"), 
12320                        b->number, e.message);
12321               new_loc->enabled = 0;
12322             }
12323         }
12324
12325       if (sals_end.nelts)
12326         {
12327           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
12328
12329           new_loc->length = end - sals.sals[0].pc + 1;
12330         }
12331     }
12332
12333   /* Update locations of permanent breakpoints.  */
12334   if (b->enable_state == bp_permanent)
12335     make_breakpoint_permanent (b);
12336
12337   /* If possible, carry over 'disable' status from existing
12338      breakpoints.  */
12339   {
12340     struct bp_location *e = existing_locations;
12341     /* If there are multiple breakpoints with the same function name,
12342        e.g. for inline functions, comparing function names won't work.
12343        Instead compare pc addresses; this is just a heuristic as things
12344        may have moved, but in practice it gives the correct answer
12345        often enough until a better solution is found.  */
12346     int have_ambiguous_names = ambiguous_names_p (b->loc);
12347
12348     for (; e; e = e->next)
12349       {
12350         if (!e->enabled && e->function_name)
12351           {
12352             struct bp_location *l = b->loc;
12353             if (have_ambiguous_names)
12354               {
12355                 for (; l; l = l->next)
12356                   if (breakpoint_locations_match (e, l))
12357                     {
12358                       l->enabled = 0;
12359                       break;
12360                     }
12361               }
12362             else
12363               {
12364                 for (; l; l = l->next)
12365                   if (l->function_name
12366                       && strcmp (e->function_name, l->function_name) == 0)
12367                     {
12368                       l->enabled = 0;
12369                       break;
12370                     }
12371               }
12372           }
12373       }
12374   }
12375
12376   if (!locations_are_equal (existing_locations, b->loc))
12377     observer_notify_breakpoint_modified (b);
12378
12379   update_global_location_list (1);
12380 }
12381
12382 /* Find the SaL locations corresponding to the given ADDR_STRING.
12383    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
12384
12385 static struct symtabs_and_lines
12386 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
12387 {
12388   char *s;
12389   struct symtabs_and_lines sals = {0};
12390   volatile struct gdb_exception e;
12391
12392   gdb_assert (b->ops != NULL);
12393   s = addr_string;
12394
12395   TRY_CATCH (e, RETURN_MASK_ERROR)
12396     {
12397       b->ops->decode_linespec (b, &s, &sals);
12398     }
12399   if (e.reason < 0)
12400     {
12401       int not_found_and_ok = 0;
12402       /* For pending breakpoints, it's expected that parsing will
12403          fail until the right shared library is loaded.  User has
12404          already told to create pending breakpoints and don't need
12405          extra messages.  If breakpoint is in bp_shlib_disabled
12406          state, then user already saw the message about that
12407          breakpoint being disabled, and don't want to see more
12408          errors.  */
12409       if (e.error == NOT_FOUND_ERROR
12410           && (b->condition_not_parsed 
12411               || (b->loc && b->loc->shlib_disabled)
12412               || (b->loc && b->loc->pspace->executing_startup)
12413               || b->enable_state == bp_disabled))
12414         not_found_and_ok = 1;
12415
12416       if (!not_found_and_ok)
12417         {
12418           /* We surely don't want to warn about the same breakpoint
12419              10 times.  One solution, implemented here, is disable
12420              the breakpoint on error.  Another solution would be to
12421              have separate 'warning emitted' flag.  Since this
12422              happens only when a binary has changed, I don't know
12423              which approach is better.  */
12424           b->enable_state = bp_disabled;
12425           throw_exception (e);
12426         }
12427     }
12428
12429   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
12430     {
12431       int i;
12432
12433       for (i = 0; i < sals.nelts; ++i)
12434         resolve_sal_pc (&sals.sals[i]);
12435       if (b->condition_not_parsed && s && s[0])
12436         {
12437           char *cond_string = 0;
12438           int thread = -1;
12439           int task = 0;
12440
12441           find_condition_and_thread (s, sals.sals[0].pc,
12442                                      &cond_string, &thread, &task);
12443           if (cond_string)
12444             b->cond_string = cond_string;
12445           b->thread = thread;
12446           b->task = task;
12447           b->condition_not_parsed = 0;
12448         }
12449
12450       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
12451         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
12452
12453       *found = 1;
12454     }
12455   else
12456     *found = 0;
12457
12458   return sals;
12459 }
12460
12461 /* The default re_set method, for typical hardware or software
12462    breakpoints.  Reevaluate the breakpoint and recreate its
12463    locations.  */
12464
12465 static void
12466 breakpoint_re_set_default (struct breakpoint *b)
12467 {
12468   int found;
12469   struct symtabs_and_lines sals, sals_end;
12470   struct symtabs_and_lines expanded = {0};
12471   struct symtabs_and_lines expanded_end = {0};
12472
12473   sals = addr_string_to_sals (b, b->addr_string, &found);
12474   if (found)
12475     {
12476       make_cleanup (xfree, sals.sals);
12477       expanded = sals;
12478     }
12479
12480   if (b->addr_string_range_end)
12481     {
12482       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
12483       if (found)
12484         {
12485           make_cleanup (xfree, sals_end.sals);
12486           expanded_end = sals_end;
12487         }
12488     }
12489
12490   update_breakpoint_locations (b, expanded, expanded_end);
12491 }
12492
12493 /* Default method for creating SALs from an address string.  It basically
12494    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
12495
12496 static void
12497 create_sals_from_address_default (char **arg,
12498                                   struct linespec_result *canonical,
12499                                   enum bptype type_wanted,
12500                                   char *addr_start, char **copy_arg)
12501 {
12502   parse_breakpoint_sals (arg, canonical);
12503 }
12504
12505 /* Call create_breakpoints_sal for the given arguments.  This is the default
12506    function for the `create_breakpoints_sal' method of
12507    breakpoint_ops.  */
12508
12509 static void
12510 create_breakpoints_sal_default (struct gdbarch *gdbarch,
12511                                 struct linespec_result *canonical,
12512                                 struct linespec_sals *lsal,
12513                                 char *cond_string,
12514                                 enum bptype type_wanted,
12515                                 enum bpdisp disposition,
12516                                 int thread,
12517                                 int task, int ignore_count,
12518                                 const struct breakpoint_ops *ops,
12519                                 int from_tty, int enabled,
12520                                 int internal)
12521 {
12522   create_breakpoints_sal (gdbarch, canonical, cond_string,
12523                           type_wanted, disposition,
12524                           thread, task, ignore_count, ops, from_tty,
12525                           enabled, internal);
12526 }
12527
12528 /* Decode the line represented by S by calling decode_line_full.  This is the
12529    default function for the `decode_linespec' method of breakpoint_ops.  */
12530
12531 static void
12532 decode_linespec_default (struct breakpoint *b, char **s,
12533                          struct symtabs_and_lines *sals)
12534 {
12535   struct linespec_result canonical;
12536
12537   init_linespec_result (&canonical);
12538   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
12539                     (struct symtab *) NULL, 0,
12540                     &canonical, multiple_symbols_all,
12541                     b->filter);
12542
12543   /* We should get 0 or 1 resulting SALs.  */
12544   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
12545
12546   if (VEC_length (linespec_sals, canonical.sals) > 0)
12547     {
12548       struct linespec_sals *lsal;
12549
12550       lsal = VEC_index (linespec_sals, canonical.sals, 0);
12551       *sals = lsal->sals;
12552       /* Arrange it so the destructor does not free the
12553          contents.  */
12554       lsal->sals.sals = NULL;
12555     }
12556
12557   destroy_linespec_result (&canonical);
12558 }
12559
12560 /* Prepare the global context for a re-set of breakpoint B.  */
12561
12562 static struct cleanup *
12563 prepare_re_set_context (struct breakpoint *b)
12564 {
12565   struct cleanup *cleanups;
12566
12567   input_radix = b->input_radix;
12568   cleanups = save_current_space_and_thread ();
12569   if (b->pspace != NULL)
12570     switch_to_program_space_and_thread (b->pspace);
12571   set_language (b->language);
12572
12573   return cleanups;
12574 }
12575
12576 /* Reset a breakpoint given it's struct breakpoint * BINT.
12577    The value we return ends up being the return value from catch_errors.
12578    Unused in this case.  */
12579
12580 static int
12581 breakpoint_re_set_one (void *bint)
12582 {
12583   /* Get past catch_errs.  */
12584   struct breakpoint *b = (struct breakpoint *) bint;
12585   struct cleanup *cleanups;
12586
12587   cleanups = prepare_re_set_context (b);
12588   b->ops->re_set (b);
12589   do_cleanups (cleanups);
12590   return 0;
12591 }
12592
12593 /* Re-set all breakpoints after symbols have been re-loaded.  */
12594 void
12595 breakpoint_re_set (void)
12596 {
12597   struct breakpoint *b, *b_tmp;
12598   enum language save_language;
12599   int save_input_radix;
12600   struct cleanup *old_chain;
12601
12602   save_language = current_language->la_language;
12603   save_input_radix = input_radix;
12604   old_chain = save_current_program_space ();
12605
12606   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12607   {
12608     /* Format possible error msg.  */
12609     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
12610                                 b->number);
12611     struct cleanup *cleanups = make_cleanup (xfree, message);
12612     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
12613     do_cleanups (cleanups);
12614   }
12615   set_language (save_language);
12616   input_radix = save_input_radix;
12617
12618   jit_breakpoint_re_set ();
12619
12620   do_cleanups (old_chain);
12621
12622   create_overlay_event_breakpoint ();
12623   create_longjmp_master_breakpoint ();
12624   create_std_terminate_master_breakpoint ();
12625   create_exception_master_breakpoint ();
12626
12627   /* While we're at it, reset the skip list too.  */
12628   skip_re_set ();
12629 }
12630 \f
12631 /* Reset the thread number of this breakpoint:
12632
12633    - If the breakpoint is for all threads, leave it as-is.
12634    - Else, reset it to the current thread for inferior_ptid.  */
12635 void
12636 breakpoint_re_set_thread (struct breakpoint *b)
12637 {
12638   if (b->thread != -1)
12639     {
12640       if (in_thread_list (inferior_ptid))
12641         b->thread = pid_to_thread_id (inferior_ptid);
12642
12643       /* We're being called after following a fork.  The new fork is
12644          selected as current, and unless this was a vfork will have a
12645          different program space from the original thread.  Reset that
12646          as well.  */
12647       b->loc->pspace = current_program_space;
12648     }
12649 }
12650
12651 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12652    If from_tty is nonzero, it prints a message to that effect,
12653    which ends with a period (no newline).  */
12654
12655 void
12656 set_ignore_count (int bptnum, int count, int from_tty)
12657 {
12658   struct breakpoint *b;
12659
12660   if (count < 0)
12661     count = 0;
12662
12663   ALL_BREAKPOINTS (b)
12664     if (b->number == bptnum)
12665     {
12666       if (is_tracepoint (b))
12667         {
12668           if (from_tty && count != 0)
12669             printf_filtered (_("Ignore count ignored for tracepoint %d."),
12670                              bptnum);
12671           return;
12672         }
12673       
12674       b->ignore_count = count;
12675       if (from_tty)
12676         {
12677           if (count == 0)
12678             printf_filtered (_("Will stop next time "
12679                                "breakpoint %d is reached."),
12680                              bptnum);
12681           else if (count == 1)
12682             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
12683                              bptnum);
12684           else
12685             printf_filtered (_("Will ignore next %d "
12686                                "crossings of breakpoint %d."),
12687                              count, bptnum);
12688         }
12689       breakpoints_changed ();
12690       observer_notify_breakpoint_modified (b);
12691       return;
12692     }
12693
12694   error (_("No breakpoint number %d."), bptnum);
12695 }
12696
12697 /* Command to set ignore-count of breakpoint N to COUNT.  */
12698
12699 static void
12700 ignore_command (char *args, int from_tty)
12701 {
12702   char *p = args;
12703   int num;
12704
12705   if (p == 0)
12706     error_no_arg (_("a breakpoint number"));
12707
12708   num = get_number (&p);
12709   if (num == 0)
12710     error (_("bad breakpoint number: '%s'"), args);
12711   if (*p == 0)
12712     error (_("Second argument (specified ignore-count) is missing."));
12713
12714   set_ignore_count (num,
12715                     longest_to_int (value_as_long (parse_and_eval (p))),
12716                     from_tty);
12717   if (from_tty)
12718     printf_filtered ("\n");
12719 }
12720 \f
12721 /* Call FUNCTION on each of the breakpoints
12722    whose numbers are given in ARGS.  */
12723
12724 static void
12725 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
12726                                                       void *),
12727                         void *data)
12728 {
12729   int num;
12730   struct breakpoint *b, *tmp;
12731   int match;
12732   struct get_number_or_range_state state;
12733
12734   if (args == 0)
12735     error_no_arg (_("one or more breakpoint numbers"));
12736
12737   init_number_or_range (&state, args);
12738
12739   while (!state.finished)
12740     {
12741       char *p = state.string;
12742
12743       match = 0;
12744
12745       num = get_number_or_range (&state);
12746       if (num == 0)
12747         {
12748           warning (_("bad breakpoint number at or near '%s'"), p);
12749         }
12750       else
12751         {
12752           ALL_BREAKPOINTS_SAFE (b, tmp)
12753             if (b->number == num)
12754               {
12755                 match = 1;
12756                 function (b, data);
12757                 break;
12758               }
12759           if (match == 0)
12760             printf_unfiltered (_("No breakpoint number %d.\n"), num);
12761         }
12762     }
12763 }
12764
12765 static struct bp_location *
12766 find_location_by_number (char *number)
12767 {
12768   char *dot = strchr (number, '.');
12769   char *p1;
12770   int bp_num;
12771   int loc_num;
12772   struct breakpoint *b;
12773   struct bp_location *loc;  
12774
12775   *dot = '\0';
12776
12777   p1 = number;
12778   bp_num = get_number (&p1);
12779   if (bp_num == 0)
12780     error (_("Bad breakpoint number '%s'"), number);
12781
12782   ALL_BREAKPOINTS (b)
12783     if (b->number == bp_num)
12784       {
12785         break;
12786       }
12787
12788   if (!b || b->number != bp_num)
12789     error (_("Bad breakpoint number '%s'"), number);
12790   
12791   p1 = dot+1;
12792   loc_num = get_number (&p1);
12793   if (loc_num == 0)
12794     error (_("Bad breakpoint location number '%s'"), number);
12795
12796   --loc_num;
12797   loc = b->loc;
12798   for (;loc_num && loc; --loc_num, loc = loc->next)
12799     ;
12800   if (!loc)
12801     error (_("Bad breakpoint location number '%s'"), dot+1);
12802     
12803   return loc;  
12804 }
12805
12806
12807 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12808    If from_tty is nonzero, it prints a message to that effect,
12809    which ends with a period (no newline).  */
12810
12811 void
12812 disable_breakpoint (struct breakpoint *bpt)
12813 {
12814   /* Never disable a watchpoint scope breakpoint; we want to
12815      hit them when we leave scope so we can delete both the
12816      watchpoint and its scope breakpoint at that time.  */
12817   if (bpt->type == bp_watchpoint_scope)
12818     return;
12819
12820   /* You can't disable permanent breakpoints.  */
12821   if (bpt->enable_state == bp_permanent)
12822     return;
12823
12824   bpt->enable_state = bp_disabled;
12825
12826   if (target_supports_enable_disable_tracepoint ()
12827       && current_trace_status ()->running && is_tracepoint (bpt))
12828     {
12829       struct bp_location *location;
12830      
12831       for (location = bpt->loc; location; location = location->next)
12832         target_disable_tracepoint (location);
12833     }
12834
12835   update_global_location_list (0);
12836
12837   observer_notify_breakpoint_modified (bpt);
12838 }
12839
12840 /* A callback for iterate_over_related_breakpoints.  */
12841
12842 static void
12843 do_disable_breakpoint (struct breakpoint *b, void *ignore)
12844 {
12845   disable_breakpoint (b);
12846 }
12847
12848 /* A callback for map_breakpoint_numbers that calls
12849    disable_breakpoint.  */
12850
12851 static void
12852 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
12853 {
12854   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
12855 }
12856
12857 static void
12858 disable_command (char *args, int from_tty)
12859 {
12860   if (args == 0)
12861     {
12862       struct breakpoint *bpt;
12863
12864       ALL_BREAKPOINTS (bpt)
12865         if (user_breakpoint_p (bpt))
12866           disable_breakpoint (bpt);
12867     }
12868   else if (strchr (args, '.'))
12869     {
12870       struct bp_location *loc = find_location_by_number (args);
12871       if (loc)
12872         {
12873           loc->enabled = 0;
12874           if (target_supports_enable_disable_tracepoint ()
12875               && current_trace_status ()->running && loc->owner
12876               && is_tracepoint (loc->owner))
12877             target_disable_tracepoint (loc);
12878         }
12879       update_global_location_list (0);
12880     }
12881   else
12882     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
12883 }
12884
12885 static void
12886 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition)
12887 {
12888   int target_resources_ok;
12889
12890   if (bpt->type == bp_hardware_breakpoint)
12891     {
12892       int i;
12893       i = hw_breakpoint_used_count ();
12894       target_resources_ok = 
12895         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
12896                                             i + 1, 0);
12897       if (target_resources_ok == 0)
12898         error (_("No hardware breakpoint support in the target."));
12899       else if (target_resources_ok < 0)
12900         error (_("Hardware breakpoints used exceeds limit."));
12901     }
12902
12903   if (is_watchpoint (bpt))
12904     {
12905       /* Initialize it just to avoid a GCC false warning.  */
12906       enum enable_state orig_enable_state = 0;
12907       volatile struct gdb_exception e;
12908
12909       TRY_CATCH (e, RETURN_MASK_ALL)
12910         {
12911           struct watchpoint *w = (struct watchpoint *) bpt;
12912
12913           orig_enable_state = bpt->enable_state;
12914           bpt->enable_state = bp_enabled;
12915           update_watchpoint (w, 1 /* reparse */);
12916         }
12917       if (e.reason < 0)
12918         {
12919           bpt->enable_state = orig_enable_state;
12920           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
12921                              bpt->number);
12922           return;
12923         }
12924     }
12925
12926   if (bpt->enable_state != bp_permanent)
12927     bpt->enable_state = bp_enabled;
12928
12929   if (target_supports_enable_disable_tracepoint ()
12930       && current_trace_status ()->running && is_tracepoint (bpt))
12931     {
12932       struct bp_location *location;
12933
12934       for (location = bpt->loc; location; location = location->next)
12935         target_enable_tracepoint (location);
12936     }
12937
12938   bpt->disposition = disposition;
12939   update_global_location_list (1);
12940   breakpoints_changed ();
12941   
12942   observer_notify_breakpoint_modified (bpt);
12943 }
12944
12945
12946 void
12947 enable_breakpoint (struct breakpoint *bpt)
12948 {
12949   enable_breakpoint_disp (bpt, bpt->disposition);
12950 }
12951
12952 static void
12953 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
12954 {
12955   enable_breakpoint (bpt);
12956 }
12957
12958 /* A callback for map_breakpoint_numbers that calls
12959    enable_breakpoint.  */
12960
12961 static void
12962 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
12963 {
12964   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
12965 }
12966
12967 /* The enable command enables the specified breakpoints (or all defined
12968    breakpoints) so they once again become (or continue to be) effective
12969    in stopping the inferior.  */
12970
12971 static void
12972 enable_command (char *args, int from_tty)
12973 {
12974   if (args == 0)
12975     {
12976       struct breakpoint *bpt;
12977
12978       ALL_BREAKPOINTS (bpt)
12979         if (user_breakpoint_p (bpt))
12980           enable_breakpoint (bpt);
12981     }
12982   else if (strchr (args, '.'))
12983     {
12984       struct bp_location *loc = find_location_by_number (args);
12985       if (loc)
12986         {
12987           loc->enabled = 1;
12988           if (target_supports_enable_disable_tracepoint ()
12989               && current_trace_status ()->running && loc->owner
12990               && is_tracepoint (loc->owner))
12991             target_enable_tracepoint (loc);
12992         }
12993       update_global_location_list (1);
12994     }
12995   else
12996     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
12997 }
12998
12999 static void
13000 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
13001 {
13002   enum bpdisp disp = *(enum bpdisp *) arg;
13003
13004   enable_breakpoint_disp (bpt, disp);
13005 }
13006
13007 static void
13008 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
13009 {
13010   enum bpdisp disp = disp_disable;
13011
13012   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13013 }
13014
13015 static void
13016 enable_once_command (char *args, int from_tty)
13017 {
13018   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
13019 }
13020
13021 static void
13022 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
13023 {
13024   enum bpdisp disp = disp_del;
13025
13026   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13027 }
13028
13029 static void
13030 enable_delete_command (char *args, int from_tty)
13031 {
13032   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
13033 }
13034 \f
13035 static void
13036 set_breakpoint_cmd (char *args, int from_tty)
13037 {
13038 }
13039
13040 static void
13041 show_breakpoint_cmd (char *args, int from_tty)
13042 {
13043 }
13044
13045 /* Invalidate last known value of any hardware watchpoint if
13046    the memory which that value represents has been written to by
13047    GDB itself.  */
13048
13049 static void
13050 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
13051                                       const bfd_byte *data)
13052 {
13053   struct breakpoint *bp;
13054
13055   ALL_BREAKPOINTS (bp)
13056     if (bp->enable_state == bp_enabled
13057         && bp->type == bp_hardware_watchpoint)
13058       {
13059         struct watchpoint *wp = (struct watchpoint *) bp;
13060
13061         if (wp->val_valid && wp->val)
13062           {
13063             struct bp_location *loc;
13064
13065             for (loc = bp->loc; loc != NULL; loc = loc->next)
13066               if (loc->loc_type == bp_loc_hardware_watchpoint
13067                   && loc->address + loc->length > addr
13068                   && addr + len > loc->address)
13069                 {
13070                   value_free (wp->val);
13071                   wp->val = NULL;
13072                   wp->val_valid = 0;
13073                 }
13074           }
13075       }
13076 }
13077
13078 /* Use the last displayed codepoint's values, or nothing
13079    if they aren't valid.  */
13080
13081 struct symtabs_and_lines
13082 decode_line_spec_1 (char *string, int flags)
13083 {
13084   struct symtabs_and_lines sals;
13085
13086   if (string == 0)
13087     error (_("Empty line specification."));
13088   if (last_displayed_sal_is_valid ())
13089     sals = decode_line_1 (&string, flags,
13090                           get_last_displayed_symtab (),
13091                           get_last_displayed_line ());
13092   else
13093     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
13094   if (*string)
13095     error (_("Junk at end of line specification: %s"), string);
13096   return sals;
13097 }
13098
13099 /* Create and insert a raw software breakpoint at PC.  Return an
13100    identifier, which should be used to remove the breakpoint later.
13101    In general, places which call this should be using something on the
13102    breakpoint chain instead; this function should be eliminated
13103    someday.  */
13104
13105 void *
13106 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
13107                                   struct address_space *aspace, CORE_ADDR pc)
13108 {
13109   struct bp_target_info *bp_tgt;
13110
13111   bp_tgt = XZALLOC (struct bp_target_info);
13112
13113   bp_tgt->placed_address_space = aspace;
13114   bp_tgt->placed_address = pc;
13115
13116   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
13117     {
13118       /* Could not insert the breakpoint.  */
13119       xfree (bp_tgt);
13120       return NULL;
13121     }
13122
13123   return bp_tgt;
13124 }
13125
13126 /* Remove a breakpoint BP inserted by
13127    deprecated_insert_raw_breakpoint.  */
13128
13129 int
13130 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
13131 {
13132   struct bp_target_info *bp_tgt = bp;
13133   int ret;
13134
13135   ret = target_remove_breakpoint (gdbarch, bp_tgt);
13136   xfree (bp_tgt);
13137
13138   return ret;
13139 }
13140
13141 /* One (or perhaps two) breakpoints used for software single
13142    stepping.  */
13143
13144 static void *single_step_breakpoints[2];
13145 static struct gdbarch *single_step_gdbarch[2];
13146
13147 /* Create and insert a breakpoint for software single step.  */
13148
13149 void
13150 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13151                                struct address_space *aspace, 
13152                                CORE_ADDR next_pc)
13153 {
13154   void **bpt_p;
13155
13156   if (single_step_breakpoints[0] == NULL)
13157     {
13158       bpt_p = &single_step_breakpoints[0];
13159       single_step_gdbarch[0] = gdbarch;
13160     }
13161   else
13162     {
13163       gdb_assert (single_step_breakpoints[1] == NULL);
13164       bpt_p = &single_step_breakpoints[1];
13165       single_step_gdbarch[1] = gdbarch;
13166     }
13167
13168   /* NOTE drow/2006-04-11: A future improvement to this function would
13169      be to only create the breakpoints once, and actually put them on
13170      the breakpoint chain.  That would let us use set_raw_breakpoint.
13171      We could adjust the addresses each time they were needed.  Doing
13172      this requires corresponding changes elsewhere where single step
13173      breakpoints are handled, however.  So, for now, we use this.  */
13174
13175   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
13176   if (*bpt_p == NULL)
13177     error (_("Could not insert single-step breakpoint at %s"),
13178              paddress (gdbarch, next_pc));
13179 }
13180
13181 /* Check if the breakpoints used for software single stepping
13182    were inserted or not.  */
13183
13184 int
13185 single_step_breakpoints_inserted (void)
13186 {
13187   return (single_step_breakpoints[0] != NULL
13188           || single_step_breakpoints[1] != NULL);
13189 }
13190
13191 /* Remove and delete any breakpoints used for software single step.  */
13192
13193 void
13194 remove_single_step_breakpoints (void)
13195 {
13196   gdb_assert (single_step_breakpoints[0] != NULL);
13197
13198   /* See insert_single_step_breakpoint for more about this deprecated
13199      call.  */
13200   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
13201                                     single_step_breakpoints[0]);
13202   single_step_gdbarch[0] = NULL;
13203   single_step_breakpoints[0] = NULL;
13204
13205   if (single_step_breakpoints[1] != NULL)
13206     {
13207       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
13208                                         single_step_breakpoints[1]);
13209       single_step_gdbarch[1] = NULL;
13210       single_step_breakpoints[1] = NULL;
13211     }
13212 }
13213
13214 /* Delete software single step breakpoints without removing them from
13215    the inferior.  This is intended to be used if the inferior's address
13216    space where they were inserted is already gone, e.g. after exit or
13217    exec.  */
13218
13219 void
13220 cancel_single_step_breakpoints (void)
13221 {
13222   int i;
13223
13224   for (i = 0; i < 2; i++)
13225     if (single_step_breakpoints[i])
13226       {
13227         xfree (single_step_breakpoints[i]);
13228         single_step_breakpoints[i] = NULL;
13229         single_step_gdbarch[i] = NULL;
13230       }
13231 }
13232
13233 /* Detach software single-step breakpoints from INFERIOR_PTID without
13234    removing them.  */
13235
13236 static void
13237 detach_single_step_breakpoints (void)
13238 {
13239   int i;
13240
13241   for (i = 0; i < 2; i++)
13242     if (single_step_breakpoints[i])
13243       target_remove_breakpoint (single_step_gdbarch[i],
13244                                 single_step_breakpoints[i]);
13245 }
13246
13247 /* Check whether a software single-step breakpoint is inserted at
13248    PC.  */
13249
13250 static int
13251 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
13252                                         CORE_ADDR pc)
13253 {
13254   int i;
13255
13256   for (i = 0; i < 2; i++)
13257     {
13258       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
13259       if (bp_tgt
13260           && breakpoint_address_match (bp_tgt->placed_address_space,
13261                                        bp_tgt->placed_address,
13262                                        aspace, pc))
13263         return 1;
13264     }
13265
13266   return 0;
13267 }
13268
13269 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
13270    non-zero otherwise.  */
13271 static int
13272 is_syscall_catchpoint_enabled (struct breakpoint *bp)
13273 {
13274   if (syscall_catchpoint_p (bp)
13275       && bp->enable_state != bp_disabled
13276       && bp->enable_state != bp_call_disabled)
13277     return 1;
13278   else
13279     return 0;
13280 }
13281
13282 int
13283 catch_syscall_enabled (void)
13284 {
13285   struct inferior *inf = current_inferior ();
13286
13287   return inf->total_syscalls_count != 0;
13288 }
13289
13290 int
13291 catching_syscall_number (int syscall_number)
13292 {
13293   struct breakpoint *bp;
13294
13295   ALL_BREAKPOINTS (bp)
13296     if (is_syscall_catchpoint_enabled (bp))
13297       {
13298         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
13299
13300         if (c->syscalls_to_be_caught)
13301           {
13302             int i, iter;
13303             for (i = 0;
13304                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
13305                  i++)
13306               if (syscall_number == iter)
13307                 return 1;
13308           }
13309         else
13310           return 1;
13311       }
13312
13313   return 0;
13314 }
13315
13316 /* Complete syscall names.  Used by "catch syscall".  */
13317 static char **
13318 catch_syscall_completer (struct cmd_list_element *cmd,
13319                          char *text, char *word)
13320 {
13321   const char **list = get_syscall_names ();
13322   char **retlist
13323     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
13324
13325   xfree (list);
13326   return retlist;
13327 }
13328
13329 /* Tracepoint-specific operations.  */
13330
13331 /* Set tracepoint count to NUM.  */
13332 static void
13333 set_tracepoint_count (int num)
13334 {
13335   tracepoint_count = num;
13336   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
13337 }
13338
13339 void
13340 trace_command (char *arg, int from_tty)
13341 {
13342   if (create_breakpoint (get_current_arch (),
13343                          arg,
13344                          NULL, 0, 1 /* parse arg */,
13345                          0 /* tempflag */,
13346                          bp_tracepoint /* type_wanted */,
13347                          0 /* Ignore count */,
13348                          pending_break_support,
13349                          &tracepoint_breakpoint_ops,
13350                          from_tty,
13351                          1 /* enabled */,
13352                          0 /* internal */))
13353     set_tracepoint_count (breakpoint_count);
13354 }
13355
13356 void
13357 ftrace_command (char *arg, int from_tty)
13358 {
13359   if (create_breakpoint (get_current_arch (),
13360                          arg,
13361                          NULL, 0, 1 /* parse arg */,
13362                          0 /* tempflag */,
13363                          bp_fast_tracepoint /* type_wanted */,
13364                          0 /* Ignore count */,
13365                          pending_break_support,
13366                          &tracepoint_breakpoint_ops,
13367                          from_tty,
13368                          1 /* enabled */,
13369                          0 /* internal */))
13370     set_tracepoint_count (breakpoint_count);
13371 }
13372
13373 /* strace command implementation.  Creates a static tracepoint.  */
13374
13375 void
13376 strace_command (char *arg, int from_tty)
13377 {
13378   struct breakpoint_ops *ops;
13379
13380   /* Decide if we are dealing with a static tracepoint marker (`-m'),
13381      or with a normal static tracepoint.  */
13382   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
13383     ops = &strace_marker_breakpoint_ops;
13384   else
13385     ops = &tracepoint_breakpoint_ops;
13386
13387   if (create_breakpoint (get_current_arch (),
13388                          arg,
13389                          NULL, 0, 1 /* parse arg */,
13390                          0 /* tempflag */,
13391                          bp_static_tracepoint /* type_wanted */,
13392                          0 /* Ignore count */,
13393                          pending_break_support,
13394                          ops,
13395                          from_tty,
13396                          1 /* enabled */,
13397                          0 /* internal */))
13398     set_tracepoint_count (breakpoint_count);
13399 }
13400
13401 /* Set up a fake reader function that gets command lines from a linked
13402    list that was acquired during tracepoint uploading.  */
13403
13404 static struct uploaded_tp *this_utp;
13405 static int next_cmd;
13406
13407 static char *
13408 read_uploaded_action (void)
13409 {
13410   char *rslt;
13411
13412   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
13413
13414   next_cmd++;
13415
13416   return rslt;
13417 }
13418
13419 /* Given information about a tracepoint as recorded on a target (which
13420    can be either a live system or a trace file), attempt to create an
13421    equivalent GDB tracepoint.  This is not a reliable process, since
13422    the target does not necessarily have all the information used when
13423    the tracepoint was originally defined.  */
13424   
13425 struct tracepoint *
13426 create_tracepoint_from_upload (struct uploaded_tp *utp)
13427 {
13428   char *addr_str, small_buf[100];
13429   struct tracepoint *tp;
13430
13431   if (utp->at_string)
13432     addr_str = utp->at_string;
13433   else
13434     {
13435       /* In the absence of a source location, fall back to raw
13436          address.  Since there is no way to confirm that the address
13437          means the same thing as when the trace was started, warn the
13438          user.  */
13439       warning (_("Uploaded tracepoint %d has no "
13440                  "source location, using raw address"),
13441                utp->number);
13442       sprintf (small_buf, "*%s", hex_string (utp->addr));
13443       addr_str = small_buf;
13444     }
13445
13446   /* There's not much we can do with a sequence of bytecodes.  */
13447   if (utp->cond && !utp->cond_string)
13448     warning (_("Uploaded tracepoint %d condition "
13449                "has no source form, ignoring it"),
13450              utp->number);
13451
13452   if (!create_breakpoint (get_current_arch (),
13453                           addr_str,
13454                           utp->cond_string, -1, 0 /* parse cond/thread */,
13455                           0 /* tempflag */,
13456                           utp->type /* type_wanted */,
13457                           0 /* Ignore count */,
13458                           pending_break_support,
13459                           &tracepoint_breakpoint_ops,
13460                           0 /* from_tty */,
13461                           utp->enabled /* enabled */,
13462                           0 /* internal */))
13463     return NULL;
13464
13465   set_tracepoint_count (breakpoint_count);
13466   
13467   /* Get the tracepoint we just created.  */
13468   tp = get_tracepoint (tracepoint_count);
13469   gdb_assert (tp != NULL);
13470
13471   if (utp->pass > 0)
13472     {
13473       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
13474
13475       trace_pass_command (small_buf, 0);
13476     }
13477
13478   /* If we have uploaded versions of the original commands, set up a
13479      special-purpose "reader" function and call the usual command line
13480      reader, then pass the result to the breakpoint command-setting
13481      function.  */
13482   if (!VEC_empty (char_ptr, utp->cmd_strings))
13483     {
13484       struct command_line *cmd_list;
13485
13486       this_utp = utp;
13487       next_cmd = 0;
13488
13489       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
13490
13491       breakpoint_set_commands (&tp->base, cmd_list);
13492     }
13493   else if (!VEC_empty (char_ptr, utp->actions)
13494            || !VEC_empty (char_ptr, utp->step_actions))
13495     warning (_("Uploaded tracepoint %d actions "
13496                "have no source form, ignoring them"),
13497              utp->number);
13498
13499   /* Copy any status information that might be available.  */
13500   tp->base.hit_count = utp->hit_count;
13501   tp->traceframe_usage = utp->traceframe_usage;
13502
13503   return tp;
13504 }
13505   
13506 /* Print information on tracepoint number TPNUM_EXP, or all if
13507    omitted.  */
13508
13509 static void
13510 tracepoints_info (char *args, int from_tty)
13511 {
13512   struct ui_out *uiout = current_uiout;
13513   int num_printed;
13514
13515   num_printed = breakpoint_1 (args, 0, is_tracepoint);
13516
13517   if (num_printed == 0)
13518     {
13519       if (args == NULL || *args == '\0')
13520         ui_out_message (uiout, 0, "No tracepoints.\n");
13521       else
13522         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
13523     }
13524
13525   default_collect_info ();
13526 }
13527
13528 /* The 'enable trace' command enables tracepoints.
13529    Not supported by all targets.  */
13530 static void
13531 enable_trace_command (char *args, int from_tty)
13532 {
13533   enable_command (args, from_tty);
13534 }
13535
13536 /* The 'disable trace' command disables tracepoints.
13537    Not supported by all targets.  */
13538 static void
13539 disable_trace_command (char *args, int from_tty)
13540 {
13541   disable_command (args, from_tty);
13542 }
13543
13544 /* Remove a tracepoint (or all if no argument).  */
13545 static void
13546 delete_trace_command (char *arg, int from_tty)
13547 {
13548   struct breakpoint *b, *b_tmp;
13549
13550   dont_repeat ();
13551
13552   if (arg == 0)
13553     {
13554       int breaks_to_delete = 0;
13555
13556       /* Delete all breakpoints if no argument.
13557          Do not delete internal or call-dummy breakpoints, these
13558          have to be deleted with an explicit breakpoint number 
13559          argument.  */
13560       ALL_TRACEPOINTS (b)
13561         if (is_tracepoint (b) && user_breakpoint_p (b))
13562           {
13563             breaks_to_delete = 1;
13564             break;
13565           }
13566
13567       /* Ask user only if there are some breakpoints to delete.  */
13568       if (!from_tty
13569           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
13570         {
13571           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13572             if (is_tracepoint (b) && user_breakpoint_p (b))
13573               delete_breakpoint (b);
13574         }
13575     }
13576   else
13577     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13578 }
13579
13580 /* Helper function for trace_pass_command.  */
13581
13582 static void
13583 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
13584 {
13585   tp->pass_count = count;
13586   observer_notify_tracepoint_modified (tp->base.number);
13587   if (from_tty)
13588     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
13589                      tp->base.number, count);
13590 }
13591
13592 /* Set passcount for tracepoint.
13593
13594    First command argument is passcount, second is tracepoint number.
13595    If tracepoint number omitted, apply to most recently defined.
13596    Also accepts special argument "all".  */
13597
13598 static void
13599 trace_pass_command (char *args, int from_tty)
13600 {
13601   struct tracepoint *t1;
13602   unsigned int count;
13603
13604   if (args == 0 || *args == 0)
13605     error (_("passcount command requires an "
13606              "argument (count + optional TP num)"));
13607
13608   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
13609
13610   while (*args && isspace ((int) *args))
13611     args++;
13612
13613   if (*args && strncasecmp (args, "all", 3) == 0)
13614     {
13615       struct breakpoint *b;
13616
13617       args += 3;                        /* Skip special argument "all".  */
13618       if (*args)
13619         error (_("Junk at end of arguments."));
13620
13621       ALL_TRACEPOINTS (b)
13622       {
13623         t1 = (struct tracepoint *) b;
13624         trace_pass_set_count (t1, count, from_tty);
13625       }
13626     }
13627   else if (*args == '\0')
13628     {
13629       t1 = get_tracepoint_by_number (&args, NULL, 1);
13630       if (t1)
13631         trace_pass_set_count (t1, count, from_tty);
13632     }
13633   else
13634     {
13635       struct get_number_or_range_state state;
13636
13637       init_number_or_range (&state, args);
13638       while (!state.finished)
13639         {
13640           t1 = get_tracepoint_by_number (&args, &state, 1);
13641           if (t1)
13642             trace_pass_set_count (t1, count, from_tty);
13643         }
13644     }
13645 }
13646
13647 struct tracepoint *
13648 get_tracepoint (int num)
13649 {
13650   struct breakpoint *t;
13651
13652   ALL_TRACEPOINTS (t)
13653     if (t->number == num)
13654       return (struct tracepoint *) t;
13655
13656   return NULL;
13657 }
13658
13659 /* Find the tracepoint with the given target-side number (which may be
13660    different from the tracepoint number after disconnecting and
13661    reconnecting).  */
13662
13663 struct tracepoint *
13664 get_tracepoint_by_number_on_target (int num)
13665 {
13666   struct breakpoint *b;
13667
13668   ALL_TRACEPOINTS (b)
13669     {
13670       struct tracepoint *t = (struct tracepoint *) b;
13671
13672       if (t->number_on_target == num)
13673         return t;
13674     }
13675
13676   return NULL;
13677 }
13678
13679 /* Utility: parse a tracepoint number and look it up in the list.
13680    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
13681    If OPTIONAL_P is true, then if the argument is missing, the most
13682    recent tracepoint (tracepoint_count) is returned.  */
13683 struct tracepoint *
13684 get_tracepoint_by_number (char **arg,
13685                           struct get_number_or_range_state *state,
13686                           int optional_p)
13687 {
13688   extern int tracepoint_count;
13689   struct breakpoint *t;
13690   int tpnum;
13691   char *instring = arg == NULL ? NULL : *arg;
13692
13693   if (state)
13694     {
13695       gdb_assert (!state->finished);
13696       tpnum = get_number_or_range (state);
13697     }
13698   else if (arg == NULL || *arg == NULL || ! **arg)
13699     {
13700       if (optional_p)
13701         tpnum = tracepoint_count;
13702       else
13703         error_no_arg (_("tracepoint number"));
13704     }
13705   else
13706     tpnum = get_number (arg);
13707
13708   if (tpnum <= 0)
13709     {
13710       if (instring && *instring)
13711         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
13712                          instring);
13713       else
13714         printf_filtered (_("Tracepoint argument missing "
13715                            "and no previous tracepoint\n"));
13716       return NULL;
13717     }
13718
13719   ALL_TRACEPOINTS (t)
13720     if (t->number == tpnum)
13721     {
13722       return (struct tracepoint *) t;
13723     }
13724
13725   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
13726   return NULL;
13727 }
13728
13729 void
13730 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
13731 {
13732   if (b->thread != -1)
13733     fprintf_unfiltered (fp, " thread %d", b->thread);
13734
13735   if (b->task != 0)
13736     fprintf_unfiltered (fp, " task %d", b->task);
13737
13738   fprintf_unfiltered (fp, "\n");
13739 }
13740
13741 /* Save information on user settable breakpoints (watchpoints, etc) to
13742    a new script file named FILENAME.  If FILTER is non-NULL, call it
13743    on each breakpoint and only include the ones for which it returns
13744    non-zero.  */
13745
13746 static void
13747 save_breakpoints (char *filename, int from_tty,
13748                   int (*filter) (const struct breakpoint *))
13749 {
13750   struct breakpoint *tp;
13751   int any = 0;
13752   char *pathname;
13753   struct cleanup *cleanup;
13754   struct ui_file *fp;
13755   int extra_trace_bits = 0;
13756
13757   if (filename == 0 || *filename == 0)
13758     error (_("Argument required (file name in which to save)"));
13759
13760   /* See if we have anything to save.  */
13761   ALL_BREAKPOINTS (tp)
13762   {
13763     /* Skip internal and momentary breakpoints.  */
13764     if (!user_breakpoint_p (tp))
13765       continue;
13766
13767     /* If we have a filter, only save the breakpoints it accepts.  */
13768     if (filter && !filter (tp))
13769       continue;
13770
13771     any = 1;
13772
13773     if (is_tracepoint (tp))
13774       {
13775         extra_trace_bits = 1;
13776
13777         /* We can stop searching.  */
13778         break;
13779       }
13780   }
13781
13782   if (!any)
13783     {
13784       warning (_("Nothing to save."));
13785       return;
13786     }
13787
13788   pathname = tilde_expand (filename);
13789   cleanup = make_cleanup (xfree, pathname);
13790   fp = gdb_fopen (pathname, "w");
13791   if (!fp)
13792     error (_("Unable to open file '%s' for saving (%s)"),
13793            filename, safe_strerror (errno));
13794   make_cleanup_ui_file_delete (fp);
13795
13796   if (extra_trace_bits)
13797     save_trace_state_variables (fp);
13798
13799   ALL_BREAKPOINTS (tp)
13800   {
13801     /* Skip internal and momentary breakpoints.  */
13802     if (!user_breakpoint_p (tp))
13803       continue;
13804
13805     /* If we have a filter, only save the breakpoints it accepts.  */
13806     if (filter && !filter (tp))
13807       continue;
13808
13809     tp->ops->print_recreate (tp, fp);
13810
13811     /* Note, we can't rely on tp->number for anything, as we can't
13812        assume the recreated breakpoint numbers will match.  Use $bpnum
13813        instead.  */
13814
13815     if (tp->cond_string)
13816       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
13817
13818     if (tp->ignore_count)
13819       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
13820
13821     if (tp->commands)
13822       {
13823         volatile struct gdb_exception ex;       
13824
13825         fprintf_unfiltered (fp, "  commands\n");
13826         
13827         ui_out_redirect (current_uiout, fp);
13828         TRY_CATCH (ex, RETURN_MASK_ALL)
13829           {
13830             print_command_lines (current_uiout, tp->commands->commands, 2);
13831           }
13832         ui_out_redirect (current_uiout, NULL);
13833
13834         if (ex.reason < 0)
13835           throw_exception (ex);
13836
13837         fprintf_unfiltered (fp, "  end\n");
13838       }
13839
13840     if (tp->enable_state == bp_disabled)
13841       fprintf_unfiltered (fp, "disable\n");
13842
13843     /* If this is a multi-location breakpoint, check if the locations
13844        should be individually disabled.  Watchpoint locations are
13845        special, and not user visible.  */
13846     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
13847       {
13848         struct bp_location *loc;
13849         int n = 1;
13850
13851         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
13852           if (!loc->enabled)
13853             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
13854       }
13855   }
13856
13857   if (extra_trace_bits && *default_collect)
13858     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
13859
13860   do_cleanups (cleanup);
13861   if (from_tty)
13862     printf_filtered (_("Saved to file '%s'.\n"), filename);
13863 }
13864
13865 /* The `save breakpoints' command.  */
13866
13867 static void
13868 save_breakpoints_command (char *args, int from_tty)
13869 {
13870   save_breakpoints (args, from_tty, NULL);
13871 }
13872
13873 /* The `save tracepoints' command.  */
13874
13875 static void
13876 save_tracepoints_command (char *args, int from_tty)
13877 {
13878   save_breakpoints (args, from_tty, is_tracepoint);
13879 }
13880
13881 /* Create a vector of all tracepoints.  */
13882
13883 VEC(breakpoint_p) *
13884 all_tracepoints (void)
13885 {
13886   VEC(breakpoint_p) *tp_vec = 0;
13887   struct breakpoint *tp;
13888
13889   ALL_TRACEPOINTS (tp)
13890   {
13891     VEC_safe_push (breakpoint_p, tp_vec, tp);
13892   }
13893
13894   return tp_vec;
13895 }
13896
13897 \f
13898 /* This help string is used for the break, hbreak, tbreak and thbreak
13899    commands.  It is defined as a macro to prevent duplication.
13900    COMMAND should be a string constant containing the name of the
13901    command.  */
13902 #define BREAK_ARGS_HELP(command) \
13903 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
13904 LOCATION may be a line number, function name, or \"*\" and an address.\n\
13905 If a line number is specified, break at start of code for that line.\n\
13906 If a function is specified, break at start of code for that function.\n\
13907 If an address is specified, break at that exact address.\n\
13908 With no LOCATION, uses current execution address of the selected\n\
13909 stack frame.  This is useful for breaking on return to a stack frame.\n\
13910 \n\
13911 THREADNUM is the number from \"info threads\".\n\
13912 CONDITION is a boolean expression.\n\
13913 \n\
13914 Multiple breakpoints at one place are permitted, and useful if their\n\
13915 conditions are different.\n\
13916 \n\
13917 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
13918
13919 /* List of subcommands for "catch".  */
13920 static struct cmd_list_element *catch_cmdlist;
13921
13922 /* List of subcommands for "tcatch".  */
13923 static struct cmd_list_element *tcatch_cmdlist;
13924
13925 void
13926 add_catch_command (char *name, char *docstring,
13927                    void (*sfunc) (char *args, int from_tty,
13928                                   struct cmd_list_element *command),
13929                    char **(*completer) (struct cmd_list_element *cmd,
13930                                          char *text, char *word),
13931                    void *user_data_catch,
13932                    void *user_data_tcatch)
13933 {
13934   struct cmd_list_element *command;
13935
13936   command = add_cmd (name, class_breakpoint, NULL, docstring,
13937                      &catch_cmdlist);
13938   set_cmd_sfunc (command, sfunc);
13939   set_cmd_context (command, user_data_catch);
13940   set_cmd_completer (command, completer);
13941
13942   command = add_cmd (name, class_breakpoint, NULL, docstring,
13943                      &tcatch_cmdlist);
13944   set_cmd_sfunc (command, sfunc);
13945   set_cmd_context (command, user_data_tcatch);
13946   set_cmd_completer (command, completer);
13947 }
13948
13949 static void
13950 clear_syscall_counts (struct inferior *inf)
13951 {
13952   inf->total_syscalls_count = 0;
13953   inf->any_syscall_count = 0;
13954   VEC_free (int, inf->syscalls_counts);
13955 }
13956
13957 static void
13958 save_command (char *arg, int from_tty)
13959 {
13960   printf_unfiltered (_("\"save\" must be followed by "
13961                        "the name of a save subcommand.\n"));
13962   help_list (save_cmdlist, "save ", -1, gdb_stdout);
13963 }
13964
13965 struct breakpoint *
13966 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
13967                           void *data)
13968 {
13969   struct breakpoint *b, *b_tmp;
13970
13971   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13972     {
13973       if ((*callback) (b, data))
13974         return b;
13975     }
13976
13977   return NULL;
13978 }
13979
13980 /* Zero if any of the breakpoint's locations could be a location where
13981    functions have been inlined, nonzero otherwise.  */
13982
13983 static int
13984 is_non_inline_function (struct breakpoint *b)
13985 {
13986   /* The shared library event breakpoint is set on the address of a
13987      non-inline function.  */
13988   if (b->type == bp_shlib_event)
13989     return 1;
13990
13991   return 0;
13992 }
13993
13994 /* Nonzero if the specified PC cannot be a location where functions
13995    have been inlined.  */
13996
13997 int
13998 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
13999                            const struct target_waitstatus *ws)
14000 {
14001   struct breakpoint *b;
14002   struct bp_location *bl;
14003
14004   ALL_BREAKPOINTS (b)
14005     {
14006       if (!is_non_inline_function (b))
14007         continue;
14008
14009       for (bl = b->loc; bl != NULL; bl = bl->next)
14010         {
14011           if (!bl->shlib_disabled
14012               && bpstat_check_location (bl, aspace, pc, ws))
14013             return 1;
14014         }
14015     }
14016
14017   return 0;
14018 }
14019
14020 void
14021 initialize_breakpoint_ops (void)
14022 {
14023   static int initialized = 0;
14024
14025   struct breakpoint_ops *ops;
14026
14027   if (initialized)
14028     return;
14029   initialized = 1;
14030
14031   /* The breakpoint_ops structure to be inherit by all kinds of
14032      breakpoints (real breakpoints, i.e., user "break" breakpoints,
14033      internal and momentary breakpoints, etc.).  */
14034   ops = &bkpt_base_breakpoint_ops;
14035   *ops = base_breakpoint_ops;
14036   ops->re_set = bkpt_re_set;
14037   ops->insert_location = bkpt_insert_location;
14038   ops->remove_location = bkpt_remove_location;
14039   ops->breakpoint_hit = bkpt_breakpoint_hit;
14040   ops->create_sals_from_address = bkpt_create_sals_from_address;
14041   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
14042   ops->decode_linespec = bkpt_decode_linespec;
14043
14044   /* The breakpoint_ops structure to be used in regular breakpoints.  */
14045   ops = &bkpt_breakpoint_ops;
14046   *ops = bkpt_base_breakpoint_ops;
14047   ops->re_set = bkpt_re_set;
14048   ops->resources_needed = bkpt_resources_needed;
14049   ops->print_it = bkpt_print_it;
14050   ops->print_mention = bkpt_print_mention;
14051   ops->print_recreate = bkpt_print_recreate;
14052
14053   /* Ranged breakpoints.  */
14054   ops = &ranged_breakpoint_ops;
14055   *ops = bkpt_breakpoint_ops;
14056   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
14057   ops->resources_needed = resources_needed_ranged_breakpoint;
14058   ops->print_it = print_it_ranged_breakpoint;
14059   ops->print_one = print_one_ranged_breakpoint;
14060   ops->print_one_detail = print_one_detail_ranged_breakpoint;
14061   ops->print_mention = print_mention_ranged_breakpoint;
14062   ops->print_recreate = print_recreate_ranged_breakpoint;
14063
14064   /* Internal breakpoints.  */
14065   ops = &internal_breakpoint_ops;
14066   *ops = bkpt_base_breakpoint_ops;
14067   ops->re_set = internal_bkpt_re_set;
14068   ops->check_status = internal_bkpt_check_status;
14069   ops->print_it = internal_bkpt_print_it;
14070   ops->print_mention = internal_bkpt_print_mention;
14071
14072   /* Momentary breakpoints.  */
14073   ops = &momentary_breakpoint_ops;
14074   *ops = bkpt_base_breakpoint_ops;
14075   ops->re_set = momentary_bkpt_re_set;
14076   ops->check_status = momentary_bkpt_check_status;
14077   ops->print_it = momentary_bkpt_print_it;
14078   ops->print_mention = momentary_bkpt_print_mention;
14079
14080   /* GNU v3 exception catchpoints.  */
14081   ops = &gnu_v3_exception_catchpoint_ops;
14082   *ops = bkpt_breakpoint_ops;
14083   ops->print_it = print_it_exception_catchpoint;
14084   ops->print_one = print_one_exception_catchpoint;
14085   ops->print_mention = print_mention_exception_catchpoint;
14086   ops->print_recreate = print_recreate_exception_catchpoint;
14087
14088   /* Watchpoints.  */
14089   ops = &watchpoint_breakpoint_ops;
14090   *ops = base_breakpoint_ops;
14091   ops->dtor = dtor_watchpoint;
14092   ops->re_set = re_set_watchpoint;
14093   ops->insert_location = insert_watchpoint;
14094   ops->remove_location = remove_watchpoint;
14095   ops->breakpoint_hit = breakpoint_hit_watchpoint;
14096   ops->check_status = check_status_watchpoint;
14097   ops->resources_needed = resources_needed_watchpoint;
14098   ops->works_in_software_mode = works_in_software_mode_watchpoint;
14099   ops->print_it = print_it_watchpoint;
14100   ops->print_mention = print_mention_watchpoint;
14101   ops->print_recreate = print_recreate_watchpoint;
14102
14103   /* Masked watchpoints.  */
14104   ops = &masked_watchpoint_breakpoint_ops;
14105   *ops = watchpoint_breakpoint_ops;
14106   ops->insert_location = insert_masked_watchpoint;
14107   ops->remove_location = remove_masked_watchpoint;
14108   ops->resources_needed = resources_needed_masked_watchpoint;
14109   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
14110   ops->print_it = print_it_masked_watchpoint;
14111   ops->print_one_detail = print_one_detail_masked_watchpoint;
14112   ops->print_mention = print_mention_masked_watchpoint;
14113   ops->print_recreate = print_recreate_masked_watchpoint;
14114
14115   /* Tracepoints.  */
14116   ops = &tracepoint_breakpoint_ops;
14117   *ops = base_breakpoint_ops;
14118   ops->re_set = tracepoint_re_set;
14119   ops->breakpoint_hit = tracepoint_breakpoint_hit;
14120   ops->print_one_detail = tracepoint_print_one_detail;
14121   ops->print_mention = tracepoint_print_mention;
14122   ops->print_recreate = tracepoint_print_recreate;
14123   ops->create_sals_from_address = tracepoint_create_sals_from_address;
14124   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
14125   ops->decode_linespec = tracepoint_decode_linespec;
14126
14127   /* Static tracepoints with marker (`-m').  */
14128   ops = &strace_marker_breakpoint_ops;
14129   *ops = tracepoint_breakpoint_ops;
14130   ops->create_sals_from_address = strace_marker_create_sals_from_address;
14131   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
14132   ops->decode_linespec = strace_marker_decode_linespec;
14133
14134   /* Fork catchpoints.  */
14135   ops = &catch_fork_breakpoint_ops;
14136   *ops = base_breakpoint_ops;
14137   ops->insert_location = insert_catch_fork;
14138   ops->remove_location = remove_catch_fork;
14139   ops->breakpoint_hit = breakpoint_hit_catch_fork;
14140   ops->print_it = print_it_catch_fork;
14141   ops->print_one = print_one_catch_fork;
14142   ops->print_mention = print_mention_catch_fork;
14143   ops->print_recreate = print_recreate_catch_fork;
14144
14145   /* Vfork catchpoints.  */
14146   ops = &catch_vfork_breakpoint_ops;
14147   *ops = base_breakpoint_ops;
14148   ops->insert_location = insert_catch_vfork;
14149   ops->remove_location = remove_catch_vfork;
14150   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
14151   ops->print_it = print_it_catch_vfork;
14152   ops->print_one = print_one_catch_vfork;
14153   ops->print_mention = print_mention_catch_vfork;
14154   ops->print_recreate = print_recreate_catch_vfork;
14155
14156   /* Exec catchpoints.  */
14157   ops = &catch_exec_breakpoint_ops;
14158   *ops = base_breakpoint_ops;
14159   ops->dtor = dtor_catch_exec;
14160   ops->insert_location = insert_catch_exec;
14161   ops->remove_location = remove_catch_exec;
14162   ops->breakpoint_hit = breakpoint_hit_catch_exec;
14163   ops->print_it = print_it_catch_exec;
14164   ops->print_one = print_one_catch_exec;
14165   ops->print_mention = print_mention_catch_exec;
14166   ops->print_recreate = print_recreate_catch_exec;
14167
14168   /* Syscall catchpoints.  */
14169   ops = &catch_syscall_breakpoint_ops;
14170   *ops = base_breakpoint_ops;
14171   ops->dtor = dtor_catch_syscall;
14172   ops->insert_location = insert_catch_syscall;
14173   ops->remove_location = remove_catch_syscall;
14174   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
14175   ops->print_it = print_it_catch_syscall;
14176   ops->print_one = print_one_catch_syscall;
14177   ops->print_mention = print_mention_catch_syscall;
14178   ops->print_recreate = print_recreate_catch_syscall;
14179
14180   /* Solib-related catchpoints.  */
14181   ops = &catch_solib_breakpoint_ops;
14182   *ops = base_breakpoint_ops;
14183   ops->dtor = dtor_catch_solib;
14184   ops->insert_location = insert_catch_solib;
14185   ops->remove_location = remove_catch_solib;
14186   ops->breakpoint_hit = breakpoint_hit_catch_solib;
14187   ops->check_status = check_status_catch_solib;
14188   ops->print_it = print_it_catch_solib;
14189   ops->print_one = print_one_catch_solib;
14190   ops->print_mention = print_mention_catch_solib;
14191   ops->print_recreate = print_recreate_catch_solib;
14192 }
14193
14194 void
14195 _initialize_breakpoint (void)
14196 {
14197   struct cmd_list_element *c;
14198
14199   initialize_breakpoint_ops ();
14200
14201   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
14202   observer_attach_inferior_exit (clear_syscall_counts);
14203   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
14204
14205   breakpoint_objfile_key = register_objfile_data ();
14206
14207   breakpoint_chain = 0;
14208   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
14209      before a breakpoint is set.  */
14210   breakpoint_count = 0;
14211
14212   tracepoint_count = 0;
14213
14214   add_com ("ignore", class_breakpoint, ignore_command, _("\
14215 Set ignore-count of breakpoint number N to COUNT.\n\
14216 Usage is `ignore N COUNT'."));
14217   if (xdb_commands)
14218     add_com_alias ("bc", "ignore", class_breakpoint, 1);
14219
14220   add_com ("commands", class_breakpoint, commands_command, _("\
14221 Set commands to be executed when a breakpoint is hit.\n\
14222 Give breakpoint number as argument after \"commands\".\n\
14223 With no argument, the targeted breakpoint is the last one set.\n\
14224 The commands themselves follow starting on the next line.\n\
14225 Type a line containing \"end\" to indicate the end of them.\n\
14226 Give \"silent\" as the first line to make the breakpoint silent;\n\
14227 then no output is printed when it is hit, except what the commands print."));
14228
14229   add_com ("condition", class_breakpoint, condition_command, _("\
14230 Specify breakpoint number N to break only if COND is true.\n\
14231 Usage is `condition N COND', where N is an integer and COND is an\n\
14232 expression to be evaluated whenever breakpoint N is reached."));
14233
14234   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14235 Set a temporary breakpoint.\n\
14236 Like \"break\" except the breakpoint is only temporary,\n\
14237 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
14238 by using \"enable delete\" on the breakpoint number.\n\
14239 \n"
14240 BREAK_ARGS_HELP ("tbreak")));
14241   set_cmd_completer (c, location_completer);
14242
14243   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
14244 Set a hardware assisted breakpoint.\n\
14245 Like \"break\" except the breakpoint requires hardware support,\n\
14246 some target hardware may not have this support.\n\
14247 \n"
14248 BREAK_ARGS_HELP ("hbreak")));
14249   set_cmd_completer (c, location_completer);
14250
14251   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
14252 Set a temporary hardware assisted breakpoint.\n\
14253 Like \"hbreak\" except the breakpoint is only temporary,\n\
14254 so it will be deleted when hit.\n\
14255 \n"
14256 BREAK_ARGS_HELP ("thbreak")));
14257   set_cmd_completer (c, location_completer);
14258
14259   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
14260 Enable some breakpoints.\n\
14261 Give breakpoint numbers (separated by spaces) as arguments.\n\
14262 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14263 This is used to cancel the effect of the \"disable\" command.\n\
14264 With a subcommand you can enable temporarily."),
14265                   &enablelist, "enable ", 1, &cmdlist);
14266   if (xdb_commands)
14267     add_com ("ab", class_breakpoint, enable_command, _("\
14268 Enable some breakpoints.\n\
14269 Give breakpoint numbers (separated by spaces) as arguments.\n\
14270 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14271 This is used to cancel the effect of the \"disable\" command.\n\
14272 With a subcommand you can enable temporarily."));
14273
14274   add_com_alias ("en", "enable", class_breakpoint, 1);
14275
14276   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
14277 Enable some breakpoints.\n\
14278 Give breakpoint numbers (separated by spaces) as arguments.\n\
14279 This is used to cancel the effect of the \"disable\" command.\n\
14280 May be abbreviated to simply \"enable\".\n"),
14281                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
14282
14283   add_cmd ("once", no_class, enable_once_command, _("\
14284 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
14285 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14286            &enablebreaklist);
14287
14288   add_cmd ("delete", no_class, enable_delete_command, _("\
14289 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
14290 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14291            &enablebreaklist);
14292
14293   add_cmd ("delete", no_class, enable_delete_command, _("\
14294 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
14295 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14296            &enablelist);
14297
14298   add_cmd ("once", no_class, enable_once_command, _("\
14299 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
14300 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14301            &enablelist);
14302
14303   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
14304 Disable some breakpoints.\n\
14305 Arguments are breakpoint numbers with spaces in between.\n\
14306 To disable all breakpoints, give no argument.\n\
14307 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
14308                   &disablelist, "disable ", 1, &cmdlist);
14309   add_com_alias ("dis", "disable", class_breakpoint, 1);
14310   add_com_alias ("disa", "disable", class_breakpoint, 1);
14311   if (xdb_commands)
14312     add_com ("sb", class_breakpoint, disable_command, _("\
14313 Disable some breakpoints.\n\
14314 Arguments are breakpoint numbers with spaces in between.\n\
14315 To disable all breakpoints, give no argument.\n\
14316 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
14317
14318   add_cmd ("breakpoints", class_alias, disable_command, _("\
14319 Disable some breakpoints.\n\
14320 Arguments are breakpoint numbers with spaces in between.\n\
14321 To disable all breakpoints, give no argument.\n\
14322 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
14323 This command may be abbreviated \"disable\"."),
14324            &disablelist);
14325
14326   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
14327 Delete some breakpoints or auto-display expressions.\n\
14328 Arguments are breakpoint numbers with spaces in between.\n\
14329 To delete all breakpoints, give no argument.\n\
14330 \n\
14331 Also a prefix command for deletion of other GDB objects.\n\
14332 The \"unset\" command is also an alias for \"delete\"."),
14333                   &deletelist, "delete ", 1, &cmdlist);
14334   add_com_alias ("d", "delete", class_breakpoint, 1);
14335   add_com_alias ("del", "delete", class_breakpoint, 1);
14336   if (xdb_commands)
14337     add_com ("db", class_breakpoint, delete_command, _("\
14338 Delete some breakpoints.\n\
14339 Arguments are breakpoint numbers with spaces in between.\n\
14340 To delete all breakpoints, give no argument.\n"));
14341
14342   add_cmd ("breakpoints", class_alias, delete_command, _("\
14343 Delete some breakpoints or auto-display expressions.\n\
14344 Arguments are breakpoint numbers with spaces in between.\n\
14345 To delete all breakpoints, give no argument.\n\
14346 This command may be abbreviated \"delete\"."),
14347            &deletelist);
14348
14349   add_com ("clear", class_breakpoint, clear_command, _("\
14350 Clear breakpoint at specified line or function.\n\
14351 Argument may be line number, function name, or \"*\" and an address.\n\
14352 If line number is specified, all breakpoints in that line are cleared.\n\
14353 If function is specified, breakpoints at beginning of function are cleared.\n\
14354 If an address is specified, breakpoints at that address are cleared.\n\
14355 \n\
14356 With no argument, clears all breakpoints in the line that the selected frame\n\
14357 is executing in.\n\
14358 \n\
14359 See also the \"delete\" command which clears breakpoints by number."));
14360   add_com_alias ("cl", "clear", class_breakpoint, 1);
14361
14362   c = add_com ("break", class_breakpoint, break_command, _("\
14363 Set breakpoint at specified line or function.\n"
14364 BREAK_ARGS_HELP ("break")));
14365   set_cmd_completer (c, location_completer);
14366
14367   add_com_alias ("b", "break", class_run, 1);
14368   add_com_alias ("br", "break", class_run, 1);
14369   add_com_alias ("bre", "break", class_run, 1);
14370   add_com_alias ("brea", "break", class_run, 1);
14371
14372   if (xdb_commands)
14373    add_com_alias ("ba", "break", class_breakpoint, 1);
14374
14375   if (dbx_commands)
14376     {
14377       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
14378 Break in function/address or break at a line in the current file."),
14379                              &stoplist, "stop ", 1, &cmdlist);
14380       add_cmd ("in", class_breakpoint, stopin_command,
14381                _("Break in function or address."), &stoplist);
14382       add_cmd ("at", class_breakpoint, stopat_command,
14383                _("Break at a line in the current file."), &stoplist);
14384       add_com ("status", class_info, breakpoints_info, _("\
14385 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
14386 The \"Type\" column indicates one of:\n\
14387 \tbreakpoint     - normal breakpoint\n\
14388 \twatchpoint     - watchpoint\n\
14389 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14390 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14391 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14392 address and file/line number respectively.\n\
14393 \n\
14394 Convenience variable \"$_\" and default examine address for \"x\"\n\
14395 are set to the address of the last breakpoint listed unless the command\n\
14396 is prefixed with \"server \".\n\n\
14397 Convenience variable \"$bpnum\" contains the number of the last\n\
14398 breakpoint set."));
14399     }
14400
14401   add_info ("breakpoints", breakpoints_info, _("\
14402 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14403 The \"Type\" column indicates one of:\n\
14404 \tbreakpoint     - normal breakpoint\n\
14405 \twatchpoint     - watchpoint\n\
14406 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14407 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14408 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14409 address and file/line number respectively.\n\
14410 \n\
14411 Convenience variable \"$_\" and default examine address for \"x\"\n\
14412 are set to the address of the last breakpoint listed unless the command\n\
14413 is prefixed with \"server \".\n\n\
14414 Convenience variable \"$bpnum\" contains the number of the last\n\
14415 breakpoint set."));
14416
14417   add_info_alias ("b", "breakpoints", 1);
14418
14419   if (xdb_commands)
14420     add_com ("lb", class_breakpoint, breakpoints_info, _("\
14421 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
14422 The \"Type\" column indicates one of:\n\
14423 \tbreakpoint     - normal breakpoint\n\
14424 \twatchpoint     - watchpoint\n\
14425 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14426 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14427 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14428 address and file/line number respectively.\n\
14429 \n\
14430 Convenience variable \"$_\" and default examine address for \"x\"\n\
14431 are set to the address of the last breakpoint listed unless the command\n\
14432 is prefixed with \"server \".\n\n\
14433 Convenience variable \"$bpnum\" contains the number of the last\n\
14434 breakpoint set."));
14435
14436   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14437 Status of all breakpoints, or breakpoint number NUMBER.\n\
14438 The \"Type\" column indicates one of:\n\
14439 \tbreakpoint     - normal breakpoint\n\
14440 \twatchpoint     - watchpoint\n\
14441 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
14442 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14443 \tuntil          - internal breakpoint used by the \"until\" command\n\
14444 \tfinish         - internal breakpoint used by the \"finish\" command\n\
14445 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14446 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14447 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14448 address and file/line number respectively.\n\
14449 \n\
14450 Convenience variable \"$_\" and default examine address for \"x\"\n\
14451 are set to the address of the last breakpoint listed unless the command\n\
14452 is prefixed with \"server \".\n\n\
14453 Convenience variable \"$bpnum\" contains the number of the last\n\
14454 breakpoint set."),
14455            &maintenanceinfolist);
14456
14457   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
14458 Set catchpoints to catch events."),
14459                   &catch_cmdlist, "catch ",
14460                   0/*allow-unknown*/, &cmdlist);
14461
14462   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
14463 Set temporary catchpoints to catch events."),
14464                   &tcatch_cmdlist, "tcatch ",
14465                   0/*allow-unknown*/, &cmdlist);
14466
14467   /* Add catch and tcatch sub-commands.  */
14468   add_catch_command ("catch", _("\
14469 Catch an exception, when caught."),
14470                      catch_catch_command,
14471                      NULL,
14472                      CATCH_PERMANENT,
14473                      CATCH_TEMPORARY);
14474   add_catch_command ("throw", _("\
14475 Catch an exception, when thrown."),
14476                      catch_throw_command,
14477                      NULL,
14478                      CATCH_PERMANENT,
14479                      CATCH_TEMPORARY);
14480   add_catch_command ("fork", _("Catch calls to fork."),
14481                      catch_fork_command_1,
14482                      NULL,
14483                      (void *) (uintptr_t) catch_fork_permanent,
14484                      (void *) (uintptr_t) catch_fork_temporary);
14485   add_catch_command ("vfork", _("Catch calls to vfork."),
14486                      catch_fork_command_1,
14487                      NULL,
14488                      (void *) (uintptr_t) catch_vfork_permanent,
14489                      (void *) (uintptr_t) catch_vfork_temporary);
14490   add_catch_command ("exec", _("Catch calls to exec."),
14491                      catch_exec_command_1,
14492                      NULL,
14493                      CATCH_PERMANENT,
14494                      CATCH_TEMPORARY);
14495   add_catch_command ("load", _("Catch loads of shared libraries.\n\
14496 Usage: catch load [REGEX]\n\
14497 If REGEX is given, only stop for libraries matching the regular expression."),
14498                      catch_load_command_1,
14499                      NULL,
14500                      CATCH_PERMANENT,
14501                      CATCH_TEMPORARY);
14502   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
14503 Usage: catch unload [REGEX]\n\
14504 If REGEX is given, only stop for libraries matching the regular expression."),
14505                      catch_unload_command_1,
14506                      NULL,
14507                      CATCH_PERMANENT,
14508                      CATCH_TEMPORARY);
14509   add_catch_command ("syscall", _("\
14510 Catch system calls by their names and/or numbers.\n\
14511 Arguments say which system calls to catch.  If no arguments\n\
14512 are given, every system call will be caught.\n\
14513 Arguments, if given, should be one or more system call names\n\
14514 (if your system supports that), or system call numbers."),
14515                      catch_syscall_command_1,
14516                      catch_syscall_completer,
14517                      CATCH_PERMANENT,
14518                      CATCH_TEMPORARY);
14519
14520   c = add_com ("watch", class_breakpoint, watch_command, _("\
14521 Set a watchpoint for an expression.\n\
14522 Usage: watch [-l|-location] EXPRESSION\n\
14523 A watchpoint stops execution of your program whenever the value of\n\
14524 an expression changes.\n\
14525 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14526 the memory to which it refers."));
14527   set_cmd_completer (c, expression_completer);
14528
14529   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
14530 Set a read watchpoint for an expression.\n\
14531 Usage: rwatch [-l|-location] EXPRESSION\n\
14532 A watchpoint stops execution of your program whenever the value of\n\
14533 an expression is read.\n\
14534 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14535 the memory to which it refers."));
14536   set_cmd_completer (c, expression_completer);
14537
14538   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
14539 Set a watchpoint for an expression.\n\
14540 Usage: awatch [-l|-location] EXPRESSION\n\
14541 A watchpoint stops execution of your program whenever the value of\n\
14542 an expression is either read or written.\n\
14543 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14544 the memory to which it refers."));
14545   set_cmd_completer (c, expression_completer);
14546
14547   add_info ("watchpoints", watchpoints_info, _("\
14548 Status of specified watchpoints (all watchpoints if no argument)."));
14549
14550   /* XXX: cagney/2005-02-23: This should be a boolean, and should
14551      respond to changes - contrary to the description.  */
14552   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
14553                             &can_use_hw_watchpoints, _("\
14554 Set debugger's willingness to use watchpoint hardware."), _("\
14555 Show debugger's willingness to use watchpoint hardware."), _("\
14556 If zero, gdb will not use hardware for new watchpoints, even if\n\
14557 such is available.  (However, any hardware watchpoints that were\n\
14558 created before setting this to nonzero, will continue to use watchpoint\n\
14559 hardware.)"),
14560                             NULL,
14561                             show_can_use_hw_watchpoints,
14562                             &setlist, &showlist);
14563
14564   can_use_hw_watchpoints = 1;
14565
14566   /* Tracepoint manipulation commands.  */
14567
14568   c = add_com ("trace", class_breakpoint, trace_command, _("\
14569 Set a tracepoint at specified line or function.\n\
14570 \n"
14571 BREAK_ARGS_HELP ("trace") "\n\
14572 Do \"help tracepoints\" for info on other tracepoint commands."));
14573   set_cmd_completer (c, location_completer);
14574
14575   add_com_alias ("tp", "trace", class_alias, 0);
14576   add_com_alias ("tr", "trace", class_alias, 1);
14577   add_com_alias ("tra", "trace", class_alias, 1);
14578   add_com_alias ("trac", "trace", class_alias, 1);
14579
14580   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
14581 Set a fast tracepoint at specified line or function.\n\
14582 \n"
14583 BREAK_ARGS_HELP ("ftrace") "\n\
14584 Do \"help tracepoints\" for info on other tracepoint commands."));
14585   set_cmd_completer (c, location_completer);
14586
14587   c = add_com ("strace", class_breakpoint, strace_command, _("\
14588 Set a static tracepoint at specified line, function or marker.\n\
14589 \n\
14590 strace [LOCATION] [if CONDITION]\n\
14591 LOCATION may be a line number, function name, \"*\" and an address,\n\
14592 or -m MARKER_ID.\n\
14593 If a line number is specified, probe the marker at start of code\n\
14594 for that line.  If a function is specified, probe the marker at start\n\
14595 of code for that function.  If an address is specified, probe the marker\n\
14596 at that exact address.  If a marker id is specified, probe the marker\n\
14597 with that name.  With no LOCATION, uses current execution address of\n\
14598 the selected stack frame.\n\
14599 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
14600 This collects arbitrary user data passed in the probe point call to the\n\
14601 tracing library.  You can inspect it when analyzing the trace buffer,\n\
14602 by printing the $_sdata variable like any other convenience variable.\n\
14603 \n\
14604 CONDITION is a boolean expression.\n\
14605 \n\
14606 Multiple tracepoints at one place are permitted, and useful if their\n\
14607 conditions are different.\n\
14608 \n\
14609 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
14610 Do \"help tracepoints\" for info on other tracepoint commands."));
14611   set_cmd_completer (c, location_completer);
14612
14613   add_info ("tracepoints", tracepoints_info, _("\
14614 Status of specified tracepoints (all tracepoints if no argument).\n\
14615 Convenience variable \"$tpnum\" contains the number of the\n\
14616 last tracepoint set."));
14617
14618   add_info_alias ("tp", "tracepoints", 1);
14619
14620   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
14621 Delete specified tracepoints.\n\
14622 Arguments are tracepoint numbers, separated by spaces.\n\
14623 No argument means delete all tracepoints."),
14624            &deletelist);
14625
14626   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
14627 Disable specified tracepoints.\n\
14628 Arguments are tracepoint numbers, separated by spaces.\n\
14629 No argument means disable all tracepoints."),
14630            &disablelist);
14631   deprecate_cmd (c, "disable");
14632
14633   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
14634 Enable specified tracepoints.\n\
14635 Arguments are tracepoint numbers, separated by spaces.\n\
14636 No argument means enable all tracepoints."),
14637            &enablelist);
14638   deprecate_cmd (c, "enable");
14639
14640   add_com ("passcount", class_trace, trace_pass_command, _("\
14641 Set the passcount for a tracepoint.\n\
14642 The trace will end when the tracepoint has been passed 'count' times.\n\
14643 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
14644 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
14645
14646   add_prefix_cmd ("save", class_breakpoint, save_command,
14647                   _("Save breakpoint definitions as a script."),
14648                   &save_cmdlist, "save ",
14649                   0/*allow-unknown*/, &cmdlist);
14650
14651   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
14652 Save current breakpoint definitions as a script.\n\
14653 This includes all types of breakpoints (breakpoints, watchpoints,\n\
14654 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
14655 session to restore them."),
14656                &save_cmdlist);
14657   set_cmd_completer (c, filename_completer);
14658
14659   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
14660 Save current tracepoint definitions as a script.\n\
14661 Use the 'source' command in another debug session to restore them."),
14662                &save_cmdlist);
14663   set_cmd_completer (c, filename_completer);
14664
14665   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
14666   deprecate_cmd (c, "save tracepoints");
14667
14668   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
14669 Breakpoint specific settings\n\
14670 Configure various breakpoint-specific variables such as\n\
14671 pending breakpoint behavior"),
14672                   &breakpoint_set_cmdlist, "set breakpoint ",
14673                   0/*allow-unknown*/, &setlist);
14674   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
14675 Breakpoint specific settings\n\
14676 Configure various breakpoint-specific variables such as\n\
14677 pending breakpoint behavior"),
14678                   &breakpoint_show_cmdlist, "show breakpoint ",
14679                   0/*allow-unknown*/, &showlist);
14680
14681   add_setshow_auto_boolean_cmd ("pending", no_class,
14682                                 &pending_break_support, _("\
14683 Set debugger's behavior regarding pending breakpoints."), _("\
14684 Show debugger's behavior regarding pending breakpoints."), _("\
14685 If on, an unrecognized breakpoint location will cause gdb to create a\n\
14686 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
14687 an error.  If auto, an unrecognized breakpoint location results in a\n\
14688 user-query to see if a pending breakpoint should be created."),
14689                                 NULL,
14690                                 show_pending_break_support,
14691                                 &breakpoint_set_cmdlist,
14692                                 &breakpoint_show_cmdlist);
14693
14694   pending_break_support = AUTO_BOOLEAN_AUTO;
14695
14696   add_setshow_boolean_cmd ("auto-hw", no_class,
14697                            &automatic_hardware_breakpoints, _("\
14698 Set automatic usage of hardware breakpoints."), _("\
14699 Show automatic usage of hardware breakpoints."), _("\
14700 If set, the debugger will automatically use hardware breakpoints for\n\
14701 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
14702 a warning will be emitted for such breakpoints."),
14703                            NULL,
14704                            show_automatic_hardware_breakpoints,
14705                            &breakpoint_set_cmdlist,
14706                            &breakpoint_show_cmdlist);
14707
14708   add_setshow_enum_cmd ("always-inserted", class_support,
14709                         always_inserted_enums, &always_inserted_mode, _("\
14710 Set mode for inserting breakpoints."), _("\
14711 Show mode for inserting breakpoints."), _("\
14712 When this mode is off, breakpoints are inserted in inferior when it is\n\
14713 resumed, and removed when execution stops.  When this mode is on,\n\
14714 breakpoints are inserted immediately and removed only when the user\n\
14715 deletes the breakpoint.  When this mode is auto (which is the default),\n\
14716 the behaviour depends on the non-stop setting (see help set non-stop).\n\
14717 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
14718 behaves as if always-inserted mode is on; if gdb is controlling the\n\
14719 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
14720                            NULL,
14721                            &show_always_inserted_mode,
14722                            &breakpoint_set_cmdlist,
14723                            &breakpoint_show_cmdlist);
14724
14725   add_com ("break-range", class_breakpoint, break_range_command, _("\
14726 Set a breakpoint for an address range.\n\
14727 break-range START-LOCATION, END-LOCATION\n\
14728 where START-LOCATION and END-LOCATION can be one of the following:\n\
14729   LINENUM, for that line in the current file,\n\
14730   FILE:LINENUM, for that line in that file,\n\
14731   +OFFSET, for that number of lines after the current line\n\
14732            or the start of the range\n\
14733   FUNCTION, for the first line in that function,\n\
14734   FILE:FUNCTION, to distinguish among like-named static functions.\n\
14735   *ADDRESS, for the instruction at that address.\n\
14736 \n\
14737 The breakpoint will stop execution of the inferior whenever it executes\n\
14738 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
14739 range (including START-LOCATION and END-LOCATION)."));
14740
14741   automatic_hardware_breakpoints = 1;
14742
14743   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
14744 }