Constify add_info
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2017 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 "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.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 "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observer.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "continuations.h"
63 #include "stack.h"
64 #include "skip.h"
65 #include "ax-gdb.h"
66 #include "dummy-frame.h"
67 #include "interps.h"
68 #include "format.h"
69 #include "thread-fsm.h"
70 #include "tid-parse.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "extension.h"
81 #include <algorithm>
82 #include "progspace-and-thread.h"
83 #include "common/array-view.h"
84 #include "common/gdb_optional.h"
85
86 /* Enums for exception-handling support.  */
87 enum exception_event_kind
88 {
89   EX_EVENT_THROW,
90   EX_EVENT_RETHROW,
91   EX_EVENT_CATCH
92 };
93
94 /* Prototypes for local functions.  */
95
96 static void map_breakpoint_numbers (const char *,
97                                     gdb::function_view<void (breakpoint *)>);
98
99 static void breakpoint_re_set_default (struct breakpoint *);
100
101 static void
102   create_sals_from_location_default (const struct event_location *location,
103                                      struct linespec_result *canonical,
104                                      enum bptype type_wanted);
105
106 static void create_breakpoints_sal_default (struct gdbarch *,
107                                             struct linespec_result *,
108                                             gdb::unique_xmalloc_ptr<char>,
109                                             gdb::unique_xmalloc_ptr<char>,
110                                             enum bptype,
111                                             enum bpdisp, int, int,
112                                             int,
113                                             const struct breakpoint_ops *,
114                                             int, int, int, unsigned);
115
116 static std::vector<symtab_and_line> decode_location_default
117   (struct breakpoint *b, const struct event_location *location,
118    struct program_space *search_pspace);
119
120 static int can_use_hardware_watchpoint (struct value *);
121
122 static void mention (struct breakpoint *);
123
124 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
125                                                                enum bptype,
126                                                                const struct breakpoint_ops *);
127 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
128                                                        const struct symtab_and_line *);
129
130 /* This function is used in gdbtk sources and thus can not be made
131    static.  */
132 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
133                                        struct symtab_and_line,
134                                        enum bptype,
135                                        const struct breakpoint_ops *);
136
137 static struct breakpoint *
138   momentary_breakpoint_from_master (struct breakpoint *orig,
139                                     enum bptype type,
140                                     const struct breakpoint_ops *ops,
141                                     int loc_enabled);
142
143 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
144
145 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
146                                             CORE_ADDR bpaddr,
147                                             enum bptype bptype);
148
149 static void describe_other_breakpoints (struct gdbarch *,
150                                         struct program_space *, CORE_ADDR,
151                                         struct obj_section *, int);
152
153 static int watchpoint_locations_match (struct bp_location *loc1,
154                                        struct bp_location *loc2);
155
156 static int breakpoint_location_address_match (struct bp_location *bl,
157                                               const struct address_space *aspace,
158                                               CORE_ADDR addr);
159
160 static int breakpoint_location_address_range_overlap (struct bp_location *,
161                                                       const address_space *,
162                                                       CORE_ADDR, int);
163
164 static int remove_breakpoint (struct bp_location *);
165 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
166
167 static enum print_stop_action print_bp_stop_message (bpstat bs);
168
169 static int hw_breakpoint_used_count (void);
170
171 static int hw_watchpoint_use_count (struct breakpoint *);
172
173 static int hw_watchpoint_used_count_others (struct breakpoint *except,
174                                             enum bptype type,
175                                             int *other_type_used);
176
177 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
178                                     int count);
179
180 static void free_bp_location (struct bp_location *loc);
181 static void incref_bp_location (struct bp_location *loc);
182 static void decref_bp_location (struct bp_location **loc);
183
184 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
185
186 /* update_global_location_list's modes of operation wrt to whether to
187    insert locations now.  */
188 enum ugll_insert_mode
189 {
190   /* Don't insert any breakpoint locations into the inferior, only
191      remove already-inserted locations that no longer should be
192      inserted.  Functions that delete a breakpoint or breakpoints
193      should specify this mode, so that deleting a breakpoint doesn't
194      have the side effect of inserting the locations of other
195      breakpoints that are marked not-inserted, but should_be_inserted
196      returns true on them.
197
198      This behavior is useful is situations close to tear-down -- e.g.,
199      after an exec, while the target still has execution, but
200      breakpoint shadows of the previous executable image should *NOT*
201      be restored to the new image; or before detaching, where the
202      target still has execution and wants to delete breakpoints from
203      GDB's lists, and all breakpoints had already been removed from
204      the inferior.  */
205   UGLL_DONT_INSERT,
206
207   /* May insert breakpoints iff breakpoints_should_be_inserted_now
208      claims breakpoints should be inserted now.  */
209   UGLL_MAY_INSERT,
210
211   /* Insert locations now, irrespective of
212      breakpoints_should_be_inserted_now.  E.g., say all threads are
213      stopped right now, and the user did "continue".  We need to
214      insert breakpoints _before_ resuming the target, but
215      UGLL_MAY_INSERT wouldn't insert them, because
216      breakpoints_should_be_inserted_now returns false at that point,
217      as no thread is running yet.  */
218   UGLL_INSERT
219 };
220
221 static void update_global_location_list (enum ugll_insert_mode);
222
223 static void update_global_location_list_nothrow (enum ugll_insert_mode);
224
225 static int is_hardware_watchpoint (const struct breakpoint *bpt);
226
227 static void insert_breakpoint_locations (void);
228
229 static void enable_trace_command (char *, int);
230
231 static void disable_trace_command (char *, int);
232
233 static void trace_pass_command (const char *, int);
234
235 static void set_tracepoint_count (int num);
236
237 static int is_masked_watchpoint (const struct breakpoint *b);
238
239 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
240
241 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
242    otherwise.  */
243
244 static int strace_marker_p (struct breakpoint *b);
245
246 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
247    that are implemented on top of software or hardware breakpoints
248    (user breakpoints, internal and momentary breakpoints, etc.).  */
249 static struct breakpoint_ops bkpt_base_breakpoint_ops;
250
251 /* Internal breakpoints class type.  */
252 static struct breakpoint_ops internal_breakpoint_ops;
253
254 /* Momentary breakpoints class type.  */
255 static struct breakpoint_ops momentary_breakpoint_ops;
256
257 /* The breakpoint_ops structure to be used in regular user created
258    breakpoints.  */
259 struct breakpoint_ops bkpt_breakpoint_ops;
260
261 /* Breakpoints set on probes.  */
262 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
263
264 /* Dynamic printf class type.  */
265 struct breakpoint_ops dprintf_breakpoint_ops;
266
267 /* The style in which to perform a dynamic printf.  This is a user
268    option because different output options have different tradeoffs;
269    if GDB does the printing, there is better error handling if there
270    is a problem with any of the arguments, but using an inferior
271    function lets you have special-purpose printers and sending of
272    output to the same place as compiled-in print functions.  */
273
274 static const char dprintf_style_gdb[] = "gdb";
275 static const char dprintf_style_call[] = "call";
276 static const char dprintf_style_agent[] = "agent";
277 static const char *const dprintf_style_enums[] = {
278   dprintf_style_gdb,
279   dprintf_style_call,
280   dprintf_style_agent,
281   NULL
282 };
283 static const char *dprintf_style = dprintf_style_gdb;
284
285 /* The function to use for dynamic printf if the preferred style is to
286    call into the inferior.  The value is simply a string that is
287    copied into the command, so it can be anything that GDB can
288    evaluate to a callable address, not necessarily a function name.  */
289
290 static char *dprintf_function;
291
292 /* The channel to use for dynamic printf if the preferred style is to
293    call into the inferior; if a nonempty string, it will be passed to
294    the call as the first argument, with the format string as the
295    second.  As with the dprintf function, this can be anything that
296    GDB knows how to evaluate, so in addition to common choices like
297    "stderr", this could be an app-specific expression like
298    "mystreams[curlogger]".  */
299
300 static char *dprintf_channel;
301
302 /* True if dprintf commands should continue to operate even if GDB
303    has disconnected.  */
304 static int disconnected_dprintf = 1;
305
306 struct command_line *
307 breakpoint_commands (struct breakpoint *b)
308 {
309   return b->commands ? b->commands.get () : NULL;
310 }
311
312 /* Flag indicating that a command has proceeded the inferior past the
313    current breakpoint.  */
314
315 static int breakpoint_proceeded;
316
317 const char *
318 bpdisp_text (enum bpdisp disp)
319 {
320   /* NOTE: the following values are a part of MI protocol and
321      represent values of 'disp' field returned when inferior stops at
322      a breakpoint.  */
323   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
324
325   return bpdisps[(int) disp];
326 }
327
328 /* Prototypes for exported functions.  */
329 /* If FALSE, gdb will not use hardware support for watchpoints, even
330    if such is available.  */
331 static int can_use_hw_watchpoints;
332
333 static void
334 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
335                              struct cmd_list_element *c,
336                              const char *value)
337 {
338   fprintf_filtered (file,
339                     _("Debugger's willingness to use "
340                       "watchpoint hardware is %s.\n"),
341                     value);
342 }
343
344 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
345    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
346    for unrecognized breakpoint locations.
347    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
348 static enum auto_boolean pending_break_support;
349 static void
350 show_pending_break_support (struct ui_file *file, int from_tty,
351                             struct cmd_list_element *c,
352                             const char *value)
353 {
354   fprintf_filtered (file,
355                     _("Debugger's behavior regarding "
356                       "pending breakpoints is %s.\n"),
357                     value);
358 }
359
360 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
361    set with "break" but falling in read-only memory.
362    If 0, gdb will warn about such breakpoints, but won't automatically
363    use hardware breakpoints.  */
364 static int automatic_hardware_breakpoints;
365 static void
366 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
367                                      struct cmd_list_element *c,
368                                      const char *value)
369 {
370   fprintf_filtered (file,
371                     _("Automatic usage of hardware breakpoints is %s.\n"),
372                     value);
373 }
374
375 /* If on, GDB keeps breakpoints inserted even if the inferior is
376    stopped, and immediately inserts any new breakpoints as soon as
377    they're created.  If off (default), GDB keeps breakpoints off of
378    the target as long as possible.  That is, it delays inserting
379    breakpoints until the next resume, and removes them again when the
380    target fully stops.  This is a bit safer in case GDB crashes while
381    processing user input.  */
382 static int always_inserted_mode = 0;
383
384 static void
385 show_always_inserted_mode (struct ui_file *file, int from_tty,
386                      struct cmd_list_element *c, const char *value)
387 {
388   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
389                     value);
390 }
391
392 /* See breakpoint.h.  */
393
394 int
395 breakpoints_should_be_inserted_now (void)
396 {
397   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
398     {
399       /* If breakpoints are global, they should be inserted even if no
400          thread under gdb's control is running, or even if there are
401          no threads under GDB's control yet.  */
402       return 1;
403     }
404   else if (target_has_execution)
405     {
406       struct thread_info *tp;
407
408       if (always_inserted_mode)
409         {
410           /* The user wants breakpoints inserted even if all threads
411              are stopped.  */
412           return 1;
413         }
414
415       if (threads_are_executing ())
416         return 1;
417
418       /* Don't remove breakpoints yet if, even though all threads are
419          stopped, we still have events to process.  */
420       ALL_NON_EXITED_THREADS (tp)
421         if (tp->resumed
422             && tp->suspend.waitstatus_pending_p)
423           return 1;
424     }
425   return 0;
426 }
427
428 static const char condition_evaluation_both[] = "host or target";
429
430 /* Modes for breakpoint condition evaluation.  */
431 static const char condition_evaluation_auto[] = "auto";
432 static const char condition_evaluation_host[] = "host";
433 static const char condition_evaluation_target[] = "target";
434 static const char *const condition_evaluation_enums[] = {
435   condition_evaluation_auto,
436   condition_evaluation_host,
437   condition_evaluation_target,
438   NULL
439 };
440
441 /* Global that holds the current mode for breakpoint condition evaluation.  */
442 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
443
444 /* Global that we use to display information to the user (gets its value from
445    condition_evaluation_mode_1.  */
446 static const char *condition_evaluation_mode = condition_evaluation_auto;
447
448 /* Translate a condition evaluation mode MODE into either "host"
449    or "target".  This is used mostly to translate from "auto" to the
450    real setting that is being used.  It returns the translated
451    evaluation mode.  */
452
453 static const char *
454 translate_condition_evaluation_mode (const char *mode)
455 {
456   if (mode == condition_evaluation_auto)
457     {
458       if (target_supports_evaluation_of_breakpoint_conditions ())
459         return condition_evaluation_target;
460       else
461         return condition_evaluation_host;
462     }
463   else
464     return mode;
465 }
466
467 /* Discovers what condition_evaluation_auto translates to.  */
468
469 static const char *
470 breakpoint_condition_evaluation_mode (void)
471 {
472   return translate_condition_evaluation_mode (condition_evaluation_mode);
473 }
474
475 /* Return true if GDB should evaluate breakpoint conditions or false
476    otherwise.  */
477
478 static int
479 gdb_evaluates_breakpoint_condition_p (void)
480 {
481   const char *mode = breakpoint_condition_evaluation_mode ();
482
483   return (mode == condition_evaluation_host);
484 }
485
486 /* Are we executing breakpoint commands?  */
487 static int executing_breakpoint_commands;
488
489 /* Are overlay event breakpoints enabled? */
490 static int overlay_events_enabled;
491
492 /* See description in breakpoint.h. */
493 int target_exact_watchpoints = 0;
494
495 /* Walk the following statement or block through all breakpoints.
496    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
497    current breakpoint.  */
498
499 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
500
501 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
502         for (B = breakpoint_chain;      \
503              B ? (TMP=B->next, 1): 0;   \
504              B = TMP)
505
506 /* Similar iterator for the low-level breakpoints.  SAFE variant is
507    not provided so update_global_location_list must not be called
508    while executing the block of ALL_BP_LOCATIONS.  */
509
510 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
511         for (BP_TMP = bp_locations;                                     \
512              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
513              BP_TMP++)
514
515 /* Iterates through locations with address ADDRESS for the currently selected
516    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
517    to where the loop should start from.
518    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
519    appropriate location to start with.  */
520
521 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
522         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
523              BP_LOCP_TMP = BP_LOCP_START;                               \
524              BP_LOCP_START                                              \
525              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
526              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
527              BP_LOCP_TMP++)
528
529 /* Iterator for tracepoints only.  */
530
531 #define ALL_TRACEPOINTS(B)  \
532   for (B = breakpoint_chain; B; B = B->next)  \
533     if (is_tracepoint (B))
534
535 /* Chains of all breakpoints defined.  */
536
537 struct breakpoint *breakpoint_chain;
538
539 /* Array is sorted by bp_locations_compare - primarily by the ADDRESS.  */
540
541 static struct bp_location **bp_locations;
542
543 /* Number of elements of BP_LOCATIONS.  */
544
545 static unsigned bp_locations_count;
546
547 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
548    ADDRESS for the current elements of BP_LOCATIONS which get a valid
549    result from bp_location_has_shadow.  You can use it for roughly
550    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
551    an address you need to read.  */
552
553 static CORE_ADDR bp_locations_placed_address_before_address_max;
554
555 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
556    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
557    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
558    You can use it for roughly limiting the subrange of BP_LOCATIONS to
559    scan for shadow bytes for an address you need to read.  */
560
561 static CORE_ADDR bp_locations_shadow_len_after_address_max;
562
563 /* The locations that no longer correspond to any breakpoint, unlinked
564    from the bp_locations array, but for which a hit may still be
565    reported by a target.  */
566 VEC(bp_location_p) *moribund_locations = NULL;
567
568 /* Number of last breakpoint made.  */
569
570 static int breakpoint_count;
571
572 /* The value of `breakpoint_count' before the last command that
573    created breakpoints.  If the last (break-like) command created more
574    than one breakpoint, then the difference between BREAKPOINT_COUNT
575    and PREV_BREAKPOINT_COUNT is more than one.  */
576 static int prev_breakpoint_count;
577
578 /* Number of last tracepoint made.  */
579
580 static int tracepoint_count;
581
582 static struct cmd_list_element *breakpoint_set_cmdlist;
583 static struct cmd_list_element *breakpoint_show_cmdlist;
584 struct cmd_list_element *save_cmdlist;
585
586 /* See declaration at breakpoint.h.  */
587
588 struct breakpoint *
589 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
590                     void *user_data)
591 {
592   struct breakpoint *b = NULL;
593
594   ALL_BREAKPOINTS (b)
595     {
596       if (func (b, user_data) != 0)
597         break;
598     }
599
600   return b;
601 }
602
603 /* Return whether a breakpoint is an active enabled breakpoint.  */
604 static int
605 breakpoint_enabled (struct breakpoint *b)
606 {
607   return (b->enable_state == bp_enabled);
608 }
609
610 /* Set breakpoint count to NUM.  */
611
612 static void
613 set_breakpoint_count (int num)
614 {
615   prev_breakpoint_count = breakpoint_count;
616   breakpoint_count = num;
617   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
618 }
619
620 /* Used by `start_rbreak_breakpoints' below, to record the current
621    breakpoint count before "rbreak" creates any breakpoint.  */
622 static int rbreak_start_breakpoint_count;
623
624 /* Called at the start an "rbreak" command to record the first
625    breakpoint made.  */
626
627 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
628 {
629   rbreak_start_breakpoint_count = breakpoint_count;
630 }
631
632 /* Called at the end of an "rbreak" command to record the last
633    breakpoint made.  */
634
635 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
636 {
637   prev_breakpoint_count = rbreak_start_breakpoint_count;
638 }
639
640 /* Used in run_command to zero the hit count when a new run starts.  */
641
642 void
643 clear_breakpoint_hit_counts (void)
644 {
645   struct breakpoint *b;
646
647   ALL_BREAKPOINTS (b)
648     b->hit_count = 0;
649 }
650
651 \f
652 /* Return the breakpoint with the specified number, or NULL
653    if the number does not refer to an existing breakpoint.  */
654
655 struct breakpoint *
656 get_breakpoint (int num)
657 {
658   struct breakpoint *b;
659
660   ALL_BREAKPOINTS (b)
661     if (b->number == num)
662       return b;
663   
664   return NULL;
665 }
666
667 \f
668
669 /* Mark locations as "conditions have changed" in case the target supports
670    evaluating conditions on its side.  */
671
672 static void
673 mark_breakpoint_modified (struct breakpoint *b)
674 {
675   struct bp_location *loc;
676
677   /* This is only meaningful if the target is
678      evaluating conditions and if the user has
679      opted for condition evaluation on the target's
680      side.  */
681   if (gdb_evaluates_breakpoint_condition_p ()
682       || !target_supports_evaluation_of_breakpoint_conditions ())
683     return;
684
685   if (!is_breakpoint (b))
686     return;
687
688   for (loc = b->loc; loc; loc = loc->next)
689     loc->condition_changed = condition_modified;
690 }
691
692 /* Mark location as "conditions have changed" in case the target supports
693    evaluating conditions on its side.  */
694
695 static void
696 mark_breakpoint_location_modified (struct bp_location *loc)
697 {
698   /* This is only meaningful if the target is
699      evaluating conditions and if the user has
700      opted for condition evaluation on the target's
701      side.  */
702   if (gdb_evaluates_breakpoint_condition_p ()
703       || !target_supports_evaluation_of_breakpoint_conditions ())
704
705     return;
706
707   if (!is_breakpoint (loc->owner))
708     return;
709
710   loc->condition_changed = condition_modified;
711 }
712
713 /* Sets the condition-evaluation mode using the static global
714    condition_evaluation_mode.  */
715
716 static void
717 set_condition_evaluation_mode (char *args, int from_tty,
718                                struct cmd_list_element *c)
719 {
720   const char *old_mode, *new_mode;
721
722   if ((condition_evaluation_mode_1 == condition_evaluation_target)
723       && !target_supports_evaluation_of_breakpoint_conditions ())
724     {
725       condition_evaluation_mode_1 = condition_evaluation_mode;
726       warning (_("Target does not support breakpoint condition evaluation.\n"
727                  "Using host evaluation mode instead."));
728       return;
729     }
730
731   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
732   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
733
734   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
735      settings was "auto".  */
736   condition_evaluation_mode = condition_evaluation_mode_1;
737
738   /* Only update the mode if the user picked a different one.  */
739   if (new_mode != old_mode)
740     {
741       struct bp_location *loc, **loc_tmp;
742       /* If the user switched to a different evaluation mode, we
743          need to synch the changes with the target as follows:
744
745          "host" -> "target": Send all (valid) conditions to the target.
746          "target" -> "host": Remove all the conditions from the target.
747       */
748
749       if (new_mode == condition_evaluation_target)
750         {
751           /* Mark everything modified and synch conditions with the
752              target.  */
753           ALL_BP_LOCATIONS (loc, loc_tmp)
754             mark_breakpoint_location_modified (loc);
755         }
756       else
757         {
758           /* Manually mark non-duplicate locations to synch conditions
759              with the target.  We do this to remove all the conditions the
760              target knows about.  */
761           ALL_BP_LOCATIONS (loc, loc_tmp)
762             if (is_breakpoint (loc->owner) && loc->inserted)
763               loc->needs_update = 1;
764         }
765
766       /* Do the update.  */
767       update_global_location_list (UGLL_MAY_INSERT);
768     }
769
770   return;
771 }
772
773 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
774    what "auto" is translating to.  */
775
776 static void
777 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
778                                 struct cmd_list_element *c, const char *value)
779 {
780   if (condition_evaluation_mode == condition_evaluation_auto)
781     fprintf_filtered (file,
782                       _("Breakpoint condition evaluation "
783                         "mode is %s (currently %s).\n"),
784                       value,
785                       breakpoint_condition_evaluation_mode ());
786   else
787     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
788                       value);
789 }
790
791 /* A comparison function for bp_location AP and BP that is used by
792    bsearch.  This comparison function only cares about addresses, unlike
793    the more general bp_locations_compare function.  */
794
795 static int
796 bp_locations_compare_addrs (const void *ap, const void *bp)
797 {
798   const struct bp_location *a = *(const struct bp_location **) ap;
799   const struct bp_location *b = *(const struct bp_location **) bp;
800
801   if (a->address == b->address)
802     return 0;
803   else
804     return ((a->address > b->address) - (a->address < b->address));
805 }
806
807 /* Helper function to skip all bp_locations with addresses
808    less than ADDRESS.  It returns the first bp_location that
809    is greater than or equal to ADDRESS.  If none is found, just
810    return NULL.  */
811
812 static struct bp_location **
813 get_first_locp_gte_addr (CORE_ADDR address)
814 {
815   struct bp_location dummy_loc;
816   struct bp_location *dummy_locp = &dummy_loc;
817   struct bp_location **locp_found = NULL;
818
819   /* Initialize the dummy location's address field.  */
820   dummy_loc.address = address;
821
822   /* Find a close match to the first location at ADDRESS.  */
823   locp_found = ((struct bp_location **)
824                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
825                          sizeof (struct bp_location **),
826                          bp_locations_compare_addrs));
827
828   /* Nothing was found, nothing left to do.  */
829   if (locp_found == NULL)
830     return NULL;
831
832   /* We may have found a location that is at ADDRESS but is not the first in the
833      location's list.  Go backwards (if possible) and locate the first one.  */
834   while ((locp_found - 1) >= bp_locations
835          && (*(locp_found - 1))->address == address)
836     locp_found--;
837
838   return locp_found;
839 }
840
841 void
842 set_breakpoint_condition (struct breakpoint *b, const char *exp,
843                           int from_tty)
844 {
845   xfree (b->cond_string);
846   b->cond_string = NULL;
847
848   if (is_watchpoint (b))
849     {
850       struct watchpoint *w = (struct watchpoint *) b;
851
852       w->cond_exp.reset ();
853     }
854   else
855     {
856       struct bp_location *loc;
857
858       for (loc = b->loc; loc; loc = loc->next)
859         {
860           loc->cond.reset ();
861
862           /* No need to free the condition agent expression
863              bytecode (if we have one).  We will handle this
864              when we go through update_global_location_list.  */
865         }
866     }
867
868   if (*exp == 0)
869     {
870       if (from_tty)
871         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
872     }
873   else
874     {
875       const char *arg = exp;
876
877       /* I don't know if it matters whether this is the string the user
878          typed in or the decompiled expression.  */
879       b->cond_string = xstrdup (arg);
880       b->condition_not_parsed = 0;
881
882       if (is_watchpoint (b))
883         {
884           struct watchpoint *w = (struct watchpoint *) b;
885
886           innermost_block = NULL;
887           arg = exp;
888           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
889           if (*arg)
890             error (_("Junk at end of expression"));
891           w->cond_exp_valid_block = innermost_block;
892         }
893       else
894         {
895           struct bp_location *loc;
896
897           for (loc = b->loc; loc; loc = loc->next)
898             {
899               arg = exp;
900               loc->cond =
901                 parse_exp_1 (&arg, loc->address,
902                              block_for_pc (loc->address), 0);
903               if (*arg)
904                 error (_("Junk at end of expression"));
905             }
906         }
907     }
908   mark_breakpoint_modified (b);
909
910   observer_notify_breakpoint_modified (b);
911 }
912
913 /* Completion for the "condition" command.  */
914
915 static void
916 condition_completer (struct cmd_list_element *cmd,
917                      completion_tracker &tracker,
918                      const char *text, const char *word)
919 {
920   const char *space;
921
922   text = skip_spaces (text);
923   space = skip_to_space (text);
924   if (*space == '\0')
925     {
926       int len;
927       struct breakpoint *b;
928       VEC (char_ptr) *result = NULL;
929
930       if (text[0] == '$')
931         {
932           /* We don't support completion of history indices.  */
933           if (!isdigit (text[1]))
934             complete_internalvar (tracker, &text[1]);
935           return;
936         }
937
938       /* We're completing the breakpoint number.  */
939       len = strlen (text);
940
941       ALL_BREAKPOINTS (b)
942         {
943           char number[50];
944
945           xsnprintf (number, sizeof (number), "%d", b->number);
946
947           if (strncmp (number, text, len) == 0)
948             {
949               gdb::unique_xmalloc_ptr<char> copy (xstrdup (number));
950               tracker.add_completion (std::move (copy));
951             }
952         }
953
954       return;
955     }
956
957   /* We're completing the expression part.  */
958   text = skip_spaces (space);
959   expression_completer (cmd, tracker, text, word);
960 }
961
962 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
963
964 static void
965 condition_command (const char *arg, int from_tty)
966 {
967   struct breakpoint *b;
968   const char *p;
969   int bnum;
970
971   if (arg == 0)
972     error_no_arg (_("breakpoint number"));
973
974   p = arg;
975   bnum = get_number (&p);
976   if (bnum == 0)
977     error (_("Bad breakpoint argument: '%s'"), arg);
978
979   ALL_BREAKPOINTS (b)
980     if (b->number == bnum)
981       {
982         /* Check if this breakpoint has a "stop" method implemented in an
983            extension language.  This method and conditions entered into GDB
984            from the CLI are mutually exclusive.  */
985         const struct extension_language_defn *extlang
986           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
987
988         if (extlang != NULL)
989           {
990             error (_("Only one stop condition allowed.  There is currently"
991                      " a %s stop condition defined for this breakpoint."),
992                    ext_lang_capitalized_name (extlang));
993           }
994         set_breakpoint_condition (b, p, from_tty);
995
996         if (is_breakpoint (b))
997           update_global_location_list (UGLL_MAY_INSERT);
998
999         return;
1000       }
1001
1002   error (_("No breakpoint number %d."), bnum);
1003 }
1004
1005 /* Check that COMMAND do not contain commands that are suitable
1006    only for tracepoints and not suitable for ordinary breakpoints.
1007    Throw if any such commands is found.  */
1008
1009 static void
1010 check_no_tracepoint_commands (struct command_line *commands)
1011 {
1012   struct command_line *c;
1013
1014   for (c = commands; c; c = c->next)
1015     {
1016       int i;
1017
1018       if (c->control_type == while_stepping_control)
1019         error (_("The 'while-stepping' command can "
1020                  "only be used for tracepoints"));
1021
1022       for (i = 0; i < c->body_count; ++i)
1023         check_no_tracepoint_commands ((c->body_list)[i]);
1024
1025       /* Not that command parsing removes leading whitespace and comment
1026          lines and also empty lines.  So, we only need to check for
1027          command directly.  */
1028       if (strstr (c->line, "collect ") == c->line)
1029         error (_("The 'collect' command can only be used for tracepoints"));
1030
1031       if (strstr (c->line, "teval ") == c->line)
1032         error (_("The 'teval' command can only be used for tracepoints"));
1033     }
1034 }
1035
1036 struct longjmp_breakpoint : public breakpoint
1037 {
1038   ~longjmp_breakpoint () override;
1039 };
1040
1041 /* Encapsulate tests for different types of tracepoints.  */
1042
1043 static bool
1044 is_tracepoint_type (bptype type)
1045 {
1046   return (type == bp_tracepoint
1047           || type == bp_fast_tracepoint
1048           || type == bp_static_tracepoint);
1049 }
1050
1051 static bool
1052 is_longjmp_type (bptype type)
1053 {
1054   return type == bp_longjmp || type == bp_exception;
1055 }
1056
1057 int
1058 is_tracepoint (const struct breakpoint *b)
1059 {
1060   return is_tracepoint_type (b->type);
1061 }
1062
1063 /* Factory function to create an appropriate instance of breakpoint given
1064    TYPE.  */
1065
1066 static std::unique_ptr<breakpoint>
1067 new_breakpoint_from_type (bptype type)
1068 {
1069   breakpoint *b;
1070
1071   if (is_tracepoint_type (type))
1072     b = new tracepoint ();
1073   else if (is_longjmp_type (type))
1074     b = new longjmp_breakpoint ();
1075   else
1076     b = new breakpoint ();
1077
1078   return std::unique_ptr<breakpoint> (b);
1079 }
1080
1081 /* A helper function that validates that COMMANDS are valid for a
1082    breakpoint.  This function will throw an exception if a problem is
1083    found.  */
1084
1085 static void
1086 validate_commands_for_breakpoint (struct breakpoint *b,
1087                                   struct command_line *commands)
1088 {
1089   if (is_tracepoint (b))
1090     {
1091       struct tracepoint *t = (struct tracepoint *) b;
1092       struct command_line *c;
1093       struct command_line *while_stepping = 0;
1094
1095       /* Reset the while-stepping step count.  The previous commands
1096          might have included a while-stepping action, while the new
1097          ones might not.  */
1098       t->step_count = 0;
1099
1100       /* We need to verify that each top-level element of commands is
1101          valid for tracepoints, that there's at most one
1102          while-stepping element, and that the while-stepping's body
1103          has valid tracing commands excluding nested while-stepping.
1104          We also need to validate the tracepoint action line in the
1105          context of the tracepoint --- validate_actionline actually
1106          has side effects, like setting the tracepoint's
1107          while-stepping STEP_COUNT, in addition to checking if the
1108          collect/teval actions parse and make sense in the
1109          tracepoint's context.  */
1110       for (c = commands; c; c = c->next)
1111         {
1112           if (c->control_type == while_stepping_control)
1113             {
1114               if (b->type == bp_fast_tracepoint)
1115                 error (_("The 'while-stepping' command "
1116                          "cannot be used for fast tracepoint"));
1117               else if (b->type == bp_static_tracepoint)
1118                 error (_("The 'while-stepping' command "
1119                          "cannot be used for static tracepoint"));
1120
1121               if (while_stepping)
1122                 error (_("The 'while-stepping' command "
1123                          "can be used only once"));
1124               else
1125                 while_stepping = c;
1126             }
1127
1128           validate_actionline (c->line, b);
1129         }
1130       if (while_stepping)
1131         {
1132           struct command_line *c2;
1133
1134           gdb_assert (while_stepping->body_count == 1);
1135           c2 = while_stepping->body_list[0];
1136           for (; c2; c2 = c2->next)
1137             {
1138               if (c2->control_type == while_stepping_control)
1139                 error (_("The 'while-stepping' command cannot be nested"));
1140             }
1141         }
1142     }
1143   else
1144     {
1145       check_no_tracepoint_commands (commands);
1146     }
1147 }
1148
1149 /* Return a vector of all the static tracepoints set at ADDR.  The
1150    caller is responsible for releasing the vector.  */
1151
1152 VEC(breakpoint_p) *
1153 static_tracepoints_here (CORE_ADDR addr)
1154 {
1155   struct breakpoint *b;
1156   VEC(breakpoint_p) *found = 0;
1157   struct bp_location *loc;
1158
1159   ALL_BREAKPOINTS (b)
1160     if (b->type == bp_static_tracepoint)
1161       {
1162         for (loc = b->loc; loc; loc = loc->next)
1163           if (loc->address == addr)
1164             VEC_safe_push(breakpoint_p, found, b);
1165       }
1166
1167   return found;
1168 }
1169
1170 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1171    validate that only allowed commands are included.  */
1172
1173 void
1174 breakpoint_set_commands (struct breakpoint *b, 
1175                          command_line_up &&commands)
1176 {
1177   validate_commands_for_breakpoint (b, commands.get ());
1178
1179   b->commands = std::move (commands);
1180   observer_notify_breakpoint_modified (b);
1181 }
1182
1183 /* Set the internal `silent' flag on the breakpoint.  Note that this
1184    is not the same as the "silent" that may appear in the breakpoint's
1185    commands.  */
1186
1187 void
1188 breakpoint_set_silent (struct breakpoint *b, int silent)
1189 {
1190   int old_silent = b->silent;
1191
1192   b->silent = silent;
1193   if (old_silent != silent)
1194     observer_notify_breakpoint_modified (b);
1195 }
1196
1197 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1198    breakpoint work for any thread.  */
1199
1200 void
1201 breakpoint_set_thread (struct breakpoint *b, int thread)
1202 {
1203   int old_thread = b->thread;
1204
1205   b->thread = thread;
1206   if (old_thread != thread)
1207     observer_notify_breakpoint_modified (b);
1208 }
1209
1210 /* Set the task for this breakpoint.  If TASK is 0, make the
1211    breakpoint work for any task.  */
1212
1213 void
1214 breakpoint_set_task (struct breakpoint *b, int task)
1215 {
1216   int old_task = b->task;
1217
1218   b->task = task;
1219   if (old_task != task)
1220     observer_notify_breakpoint_modified (b);
1221 }
1222
1223 void
1224 check_tracepoint_command (char *line, void *closure)
1225 {
1226   struct breakpoint *b = (struct breakpoint *) closure;
1227
1228   validate_actionline (line, b);
1229 }
1230
1231 static void
1232 commands_command_1 (const char *arg, int from_tty,
1233                     struct command_line *control)
1234 {
1235   counted_command_line cmd;
1236
1237   std::string new_arg;
1238
1239   if (arg == NULL || !*arg)
1240     {
1241       if (breakpoint_count - prev_breakpoint_count > 1)
1242         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1243                                  breakpoint_count);
1244       else if (breakpoint_count > 0)
1245         new_arg = string_printf ("%d", breakpoint_count);
1246       arg = new_arg.c_str ();
1247     }
1248
1249   map_breakpoint_numbers
1250     (arg, [&] (breakpoint *b)
1251      {
1252        if (cmd == NULL)
1253          {
1254            if (control != NULL)
1255              cmd = copy_command_lines (control->body_list[0]);
1256            else
1257              {
1258                std::string str
1259                  = string_printf (_("Type commands for breakpoint(s) "
1260                                     "%s, one per line."),
1261                                   arg);
1262
1263                cmd = read_command_lines (&str[0],
1264                                          from_tty, 1,
1265                                          (is_tracepoint (b)
1266                                           ? check_tracepoint_command : 0),
1267                                          b);
1268              }
1269          }
1270
1271        /* If a breakpoint was on the list more than once, we don't need to
1272           do anything.  */
1273        if (b->commands != cmd)
1274          {
1275            validate_commands_for_breakpoint (b, cmd.get ());
1276            b->commands = cmd;
1277            observer_notify_breakpoint_modified (b);
1278          }
1279      });
1280
1281   if (cmd == NULL)
1282     error (_("No breakpoints specified."));
1283 }
1284
1285 static void
1286 commands_command (const char *arg, int from_tty)
1287 {
1288   commands_command_1 (arg, from_tty, NULL);
1289 }
1290
1291 /* Like commands_command, but instead of reading the commands from
1292    input stream, takes them from an already parsed command structure.
1293
1294    This is used by cli-script.c to DTRT with breakpoint commands
1295    that are part of if and while bodies.  */
1296 enum command_control_type
1297 commands_from_control_command (const char *arg, struct command_line *cmd)
1298 {
1299   commands_command_1 (arg, 0, cmd);
1300   return simple_control;
1301 }
1302
1303 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1304
1305 static int
1306 bp_location_has_shadow (struct bp_location *bl)
1307 {
1308   if (bl->loc_type != bp_loc_software_breakpoint)
1309     return 0;
1310   if (!bl->inserted)
1311     return 0;
1312   if (bl->target_info.shadow_len == 0)
1313     /* BL isn't valid, or doesn't shadow memory.  */
1314     return 0;
1315   return 1;
1316 }
1317
1318 /* Update BUF, which is LEN bytes read from the target address
1319    MEMADDR, by replacing a memory breakpoint with its shadowed
1320    contents.
1321
1322    If READBUF is not NULL, this buffer must not overlap with the of
1323    the breakpoint location's shadow_contents buffer.  Otherwise, a
1324    failed assertion internal error will be raised.  */
1325
1326 static void
1327 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1328                             const gdb_byte *writebuf_org,
1329                             ULONGEST memaddr, LONGEST len,
1330                             struct bp_target_info *target_info,
1331                             struct gdbarch *gdbarch)
1332 {
1333   /* Now do full processing of the found relevant range of elements.  */
1334   CORE_ADDR bp_addr = 0;
1335   int bp_size = 0;
1336   int bptoffset = 0;
1337
1338   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1339                                  current_program_space->aspace, 0))
1340     {
1341       /* The breakpoint is inserted in a different address space.  */
1342       return;
1343     }
1344
1345   /* Addresses and length of the part of the breakpoint that
1346      we need to copy.  */
1347   bp_addr = target_info->placed_address;
1348   bp_size = target_info->shadow_len;
1349
1350   if (bp_addr + bp_size <= memaddr)
1351     {
1352       /* The breakpoint is entirely before the chunk of memory we are
1353          reading.  */
1354       return;
1355     }
1356
1357   if (bp_addr >= memaddr + len)
1358     {
1359       /* The breakpoint is entirely after the chunk of memory we are
1360          reading.  */
1361       return;
1362     }
1363
1364   /* Offset within shadow_contents.  */
1365   if (bp_addr < memaddr)
1366     {
1367       /* Only copy the second part of the breakpoint.  */
1368       bp_size -= memaddr - bp_addr;
1369       bptoffset = memaddr - bp_addr;
1370       bp_addr = memaddr;
1371     }
1372
1373   if (bp_addr + bp_size > memaddr + len)
1374     {
1375       /* Only copy the first part of the breakpoint.  */
1376       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1377     }
1378
1379   if (readbuf != NULL)
1380     {
1381       /* Verify that the readbuf buffer does not overlap with the
1382          shadow_contents buffer.  */
1383       gdb_assert (target_info->shadow_contents >= readbuf + len
1384                   || readbuf >= (target_info->shadow_contents
1385                                  + target_info->shadow_len));
1386
1387       /* Update the read buffer with this inserted breakpoint's
1388          shadow.  */
1389       memcpy (readbuf + bp_addr - memaddr,
1390               target_info->shadow_contents + bptoffset, bp_size);
1391     }
1392   else
1393     {
1394       const unsigned char *bp;
1395       CORE_ADDR addr = target_info->reqstd_address;
1396       int placed_size;
1397
1398       /* Update the shadow with what we want to write to memory.  */
1399       memcpy (target_info->shadow_contents + bptoffset,
1400               writebuf_org + bp_addr - memaddr, bp_size);
1401
1402       /* Determine appropriate breakpoint contents and size for this
1403          address.  */
1404       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1405
1406       /* Update the final write buffer with this inserted
1407          breakpoint's INSN.  */
1408       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1409     }
1410 }
1411
1412 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1413    by replacing any memory breakpoints with their shadowed contents.
1414
1415    If READBUF is not NULL, this buffer must not overlap with any of
1416    the breakpoint location's shadow_contents buffers.  Otherwise,
1417    a failed assertion internal error will be raised.
1418
1419    The range of shadowed area by each bp_location is:
1420      bl->address - bp_locations_placed_address_before_address_max
1421      up to bl->address + bp_locations_shadow_len_after_address_max
1422    The range we were requested to resolve shadows for is:
1423      memaddr ... memaddr + len
1424    Thus the safe cutoff boundaries for performance optimization are
1425      memaddr + len <= (bl->address
1426                        - bp_locations_placed_address_before_address_max)
1427    and:
1428      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1429
1430 void
1431 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1432                         const gdb_byte *writebuf_org,
1433                         ULONGEST memaddr, LONGEST len)
1434 {
1435   /* Left boundary, right boundary and median element of our binary
1436      search.  */
1437   unsigned bc_l, bc_r, bc;
1438
1439   /* Find BC_L which is a leftmost element which may affect BUF
1440      content.  It is safe to report lower value but a failure to
1441      report higher one.  */
1442
1443   bc_l = 0;
1444   bc_r = bp_locations_count;
1445   while (bc_l + 1 < bc_r)
1446     {
1447       struct bp_location *bl;
1448
1449       bc = (bc_l + bc_r) / 2;
1450       bl = bp_locations[bc];
1451
1452       /* Check first BL->ADDRESS will not overflow due to the added
1453          constant.  Then advance the left boundary only if we are sure
1454          the BC element can in no way affect the BUF content (MEMADDR
1455          to MEMADDR + LEN range).
1456
1457          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1458          offset so that we cannot miss a breakpoint with its shadow
1459          range tail still reaching MEMADDR.  */
1460
1461       if ((bl->address + bp_locations_shadow_len_after_address_max
1462            >= bl->address)
1463           && (bl->address + bp_locations_shadow_len_after_address_max
1464               <= memaddr))
1465         bc_l = bc;
1466       else
1467         bc_r = bc;
1468     }
1469
1470   /* Due to the binary search above, we need to make sure we pick the
1471      first location that's at BC_L's address.  E.g., if there are
1472      multiple locations at the same address, BC_L may end up pointing
1473      at a duplicate location, and miss the "master"/"inserted"
1474      location.  Say, given locations L1, L2 and L3 at addresses A and
1475      B:
1476
1477       L1@A, L2@A, L3@B, ...
1478
1479      BC_L could end up pointing at location L2, while the "master"
1480      location could be L1.  Since the `loc->inserted' flag is only set
1481      on "master" locations, we'd forget to restore the shadow of L1
1482      and L2.  */
1483   while (bc_l > 0
1484          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1485     bc_l--;
1486
1487   /* Now do full processing of the found relevant range of elements.  */
1488
1489   for (bc = bc_l; bc < bp_locations_count; bc++)
1490   {
1491     struct bp_location *bl = bp_locations[bc];
1492
1493     /* bp_location array has BL->OWNER always non-NULL.  */
1494     if (bl->owner->type == bp_none)
1495       warning (_("reading through apparently deleted breakpoint #%d?"),
1496                bl->owner->number);
1497
1498     /* Performance optimization: any further element can no longer affect BUF
1499        content.  */
1500
1501     if (bl->address >= bp_locations_placed_address_before_address_max
1502         && memaddr + len <= (bl->address
1503                              - bp_locations_placed_address_before_address_max))
1504       break;
1505
1506     if (!bp_location_has_shadow (bl))
1507       continue;
1508
1509     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1510                                 memaddr, len, &bl->target_info, bl->gdbarch);
1511   }
1512 }
1513
1514 \f
1515
1516 /* Return true if BPT is either a software breakpoint or a hardware
1517    breakpoint.  */
1518
1519 int
1520 is_breakpoint (const struct breakpoint *bpt)
1521 {
1522   return (bpt->type == bp_breakpoint
1523           || bpt->type == bp_hardware_breakpoint
1524           || bpt->type == bp_dprintf);
1525 }
1526
1527 /* Return true if BPT is of any hardware watchpoint kind.  */
1528
1529 static int
1530 is_hardware_watchpoint (const struct breakpoint *bpt)
1531 {
1532   return (bpt->type == bp_hardware_watchpoint
1533           || bpt->type == bp_read_watchpoint
1534           || bpt->type == bp_access_watchpoint);
1535 }
1536
1537 /* Return true if BPT is of any watchpoint kind, hardware or
1538    software.  */
1539
1540 int
1541 is_watchpoint (const struct breakpoint *bpt)
1542 {
1543   return (is_hardware_watchpoint (bpt)
1544           || bpt->type == bp_watchpoint);
1545 }
1546
1547 /* Returns true if the current thread and its running state are safe
1548    to evaluate or update watchpoint B.  Watchpoints on local
1549    expressions need to be evaluated in the context of the thread that
1550    was current when the watchpoint was created, and, that thread needs
1551    to be stopped to be able to select the correct frame context.
1552    Watchpoints on global expressions can be evaluated on any thread,
1553    and in any state.  It is presently left to the target allowing
1554    memory accesses when threads are running.  */
1555
1556 static int
1557 watchpoint_in_thread_scope (struct watchpoint *b)
1558 {
1559   return (b->pspace == current_program_space
1560           && (ptid_equal (b->watchpoint_thread, null_ptid)
1561               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1562                   && !is_executing (inferior_ptid))));
1563 }
1564
1565 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1566    associated bp_watchpoint_scope breakpoint.  */
1567
1568 static void
1569 watchpoint_del_at_next_stop (struct watchpoint *w)
1570 {
1571   if (w->related_breakpoint != w)
1572     {
1573       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1574       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1575       w->related_breakpoint->disposition = disp_del_at_next_stop;
1576       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1577       w->related_breakpoint = w;
1578     }
1579   w->disposition = disp_del_at_next_stop;
1580 }
1581
1582 /* Extract a bitfield value from value VAL using the bit parameters contained in
1583    watchpoint W.  */
1584
1585 static struct value *
1586 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1587 {
1588   struct value *bit_val;
1589
1590   if (val == NULL)
1591     return NULL;
1592
1593   bit_val = allocate_value (value_type (val));
1594
1595   unpack_value_bitfield (bit_val,
1596                          w->val_bitpos,
1597                          w->val_bitsize,
1598                          value_contents_for_printing (val),
1599                          value_offset (val),
1600                          val);
1601
1602   return bit_val;
1603 }
1604
1605 /* Allocate a dummy location and add it to B, which must be a software
1606    watchpoint.  This is required because even if a software watchpoint
1607    is not watching any memory, bpstat_stop_status requires a location
1608    to be able to report stops.  */
1609
1610 static void
1611 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1612                                             struct program_space *pspace)
1613 {
1614   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1615
1616   b->loc = allocate_bp_location (b);
1617   b->loc->pspace = pspace;
1618   b->loc->address = -1;
1619   b->loc->length = -1;
1620 }
1621
1622 /* Returns true if B is a software watchpoint that is not watching any
1623    memory (e.g., "watch $pc").  */
1624
1625 static int
1626 is_no_memory_software_watchpoint (struct breakpoint *b)
1627 {
1628   return (b->type == bp_watchpoint
1629           && b->loc != NULL
1630           && b->loc->next == NULL
1631           && b->loc->address == -1
1632           && b->loc->length == -1);
1633 }
1634
1635 /* Assuming that B is a watchpoint:
1636    - Reparse watchpoint expression, if REPARSE is non-zero
1637    - Evaluate expression and store the result in B->val
1638    - Evaluate the condition if there is one, and store the result
1639      in b->loc->cond.
1640    - Update the list of values that must be watched in B->loc.
1641
1642    If the watchpoint disposition is disp_del_at_next_stop, then do
1643    nothing.  If this is local watchpoint that is out of scope, delete
1644    it.
1645
1646    Even with `set breakpoint always-inserted on' the watchpoints are
1647    removed + inserted on each stop here.  Normal breakpoints must
1648    never be removed because they might be missed by a running thread
1649    when debugging in non-stop mode.  On the other hand, hardware
1650    watchpoints (is_hardware_watchpoint; processed here) are specific
1651    to each LWP since they are stored in each LWP's hardware debug
1652    registers.  Therefore, such LWP must be stopped first in order to
1653    be able to modify its hardware watchpoints.
1654
1655    Hardware watchpoints must be reset exactly once after being
1656    presented to the user.  It cannot be done sooner, because it would
1657    reset the data used to present the watchpoint hit to the user.  And
1658    it must not be done later because it could display the same single
1659    watchpoint hit during multiple GDB stops.  Note that the latter is
1660    relevant only to the hardware watchpoint types bp_read_watchpoint
1661    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1662    not user-visible - its hit is suppressed if the memory content has
1663    not changed.
1664
1665    The following constraints influence the location where we can reset
1666    hardware watchpoints:
1667
1668    * target_stopped_by_watchpoint and target_stopped_data_address are
1669      called several times when GDB stops.
1670
1671    [linux] 
1672    * Multiple hardware watchpoints can be hit at the same time,
1673      causing GDB to stop.  GDB only presents one hardware watchpoint
1674      hit at a time as the reason for stopping, and all the other hits
1675      are presented later, one after the other, each time the user
1676      requests the execution to be resumed.  Execution is not resumed
1677      for the threads still having pending hit event stored in
1678      LWP_INFO->STATUS.  While the watchpoint is already removed from
1679      the inferior on the first stop the thread hit event is kept being
1680      reported from its cached value by linux_nat_stopped_data_address
1681      until the real thread resume happens after the watchpoint gets
1682      presented and thus its LWP_INFO->STATUS gets reset.
1683
1684    Therefore the hardware watchpoint hit can get safely reset on the
1685    watchpoint removal from inferior.  */
1686
1687 static void
1688 update_watchpoint (struct watchpoint *b, int reparse)
1689 {
1690   int within_current_scope;
1691   struct frame_id saved_frame_id;
1692   int frame_saved;
1693
1694   /* If this is a local watchpoint, we only want to check if the
1695      watchpoint frame is in scope if the current thread is the thread
1696      that was used to create the watchpoint.  */
1697   if (!watchpoint_in_thread_scope (b))
1698     return;
1699
1700   if (b->disposition == disp_del_at_next_stop)
1701     return;
1702  
1703   frame_saved = 0;
1704
1705   /* Determine if the watchpoint is within scope.  */
1706   if (b->exp_valid_block == NULL)
1707     within_current_scope = 1;
1708   else
1709     {
1710       struct frame_info *fi = get_current_frame ();
1711       struct gdbarch *frame_arch = get_frame_arch (fi);
1712       CORE_ADDR frame_pc = get_frame_pc (fi);
1713
1714       /* If we're at a point where the stack has been destroyed
1715          (e.g. in a function epilogue), unwinding may not work
1716          properly. Do not attempt to recreate locations at this
1717          point.  See similar comments in watchpoint_check.  */
1718       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1719         return;
1720
1721       /* Save the current frame's ID so we can restore it after
1722          evaluating the watchpoint expression on its own frame.  */
1723       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1724          took a frame parameter, so that we didn't have to change the
1725          selected frame.  */
1726       frame_saved = 1;
1727       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1728
1729       fi = frame_find_by_id (b->watchpoint_frame);
1730       within_current_scope = (fi != NULL);
1731       if (within_current_scope)
1732         select_frame (fi);
1733     }
1734
1735   /* We don't free locations.  They are stored in the bp_location array
1736      and update_global_location_list will eventually delete them and
1737      remove breakpoints if needed.  */
1738   b->loc = NULL;
1739
1740   if (within_current_scope && reparse)
1741     {
1742       const char *s;
1743
1744       b->exp.reset ();
1745       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1746       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1747       /* If the meaning of expression itself changed, the old value is
1748          no longer relevant.  We don't want to report a watchpoint hit
1749          to the user when the old value and the new value may actually
1750          be completely different objects.  */
1751       value_free (b->val);
1752       b->val = NULL;
1753       b->val_valid = 0;
1754
1755       /* Note that unlike with breakpoints, the watchpoint's condition
1756          expression is stored in the breakpoint object, not in the
1757          locations (re)created below.  */
1758       if (b->cond_string != NULL)
1759         {
1760           b->cond_exp.reset ();
1761
1762           s = b->cond_string;
1763           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1764         }
1765     }
1766
1767   /* If we failed to parse the expression, for example because
1768      it refers to a global variable in a not-yet-loaded shared library,
1769      don't try to insert watchpoint.  We don't automatically delete
1770      such watchpoint, though, since failure to parse expression
1771      is different from out-of-scope watchpoint.  */
1772   if (!target_has_execution)
1773     {
1774       /* Without execution, memory can't change.  No use to try and
1775          set watchpoint locations.  The watchpoint will be reset when
1776          the target gains execution, through breakpoint_re_set.  */
1777       if (!can_use_hw_watchpoints)
1778         {
1779           if (b->ops->works_in_software_mode (b))
1780             b->type = bp_watchpoint;
1781           else
1782             error (_("Can't set read/access watchpoint when "
1783                      "hardware watchpoints are disabled."));
1784         }
1785     }
1786   else if (within_current_scope && b->exp)
1787     {
1788       int pc = 0;
1789       struct value *val_chain, *v, *result, *next;
1790       struct program_space *frame_pspace;
1791
1792       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, 0);
1793
1794       /* Avoid setting b->val if it's already set.  The meaning of
1795          b->val is 'the last value' user saw, and we should update
1796          it only if we reported that last value to user.  As it
1797          happens, the code that reports it updates b->val directly.
1798          We don't keep track of the memory value for masked
1799          watchpoints.  */
1800       if (!b->val_valid && !is_masked_watchpoint (b))
1801         {
1802           if (b->val_bitsize != 0)
1803             {
1804               v = extract_bitfield_from_watchpoint_value (b, v);
1805               if (v != NULL)
1806                 release_value (v);
1807             }
1808           b->val = v;
1809           b->val_valid = 1;
1810         }
1811
1812       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1813
1814       /* Look at each value on the value chain.  */
1815       for (v = val_chain; v; v = value_next (v))
1816         {
1817           /* If it's a memory location, and GDB actually needed
1818              its contents to evaluate the expression, then we
1819              must watch it.  If the first value returned is
1820              still lazy, that means an error occurred reading it;
1821              watch it anyway in case it becomes readable.  */
1822           if (VALUE_LVAL (v) == lval_memory
1823               && (v == val_chain || ! value_lazy (v)))
1824             {
1825               struct type *vtype = check_typedef (value_type (v));
1826
1827               /* We only watch structs and arrays if user asked
1828                  for it explicitly, never if they just happen to
1829                  appear in the middle of some value chain.  */
1830               if (v == result
1831                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1832                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1833                 {
1834                   CORE_ADDR addr;
1835                   enum target_hw_bp_type type;
1836                   struct bp_location *loc, **tmp;
1837                   int bitpos = 0, bitsize = 0;
1838
1839                   if (value_bitsize (v) != 0)
1840                     {
1841                       /* Extract the bit parameters out from the bitfield
1842                          sub-expression.  */
1843                       bitpos = value_bitpos (v);
1844                       bitsize = value_bitsize (v);
1845                     }
1846                   else if (v == result && b->val_bitsize != 0)
1847                     {
1848                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1849                         lvalue whose bit parameters are saved in the fields
1850                         VAL_BITPOS and VAL_BITSIZE.  */
1851                       bitpos = b->val_bitpos;
1852                       bitsize = b->val_bitsize;
1853                     }
1854
1855                   addr = value_address (v);
1856                   if (bitsize != 0)
1857                     {
1858                       /* Skip the bytes that don't contain the bitfield.  */
1859                       addr += bitpos / 8;
1860                     }
1861
1862                   type = hw_write;
1863                   if (b->type == bp_read_watchpoint)
1864                     type = hw_read;
1865                   else if (b->type == bp_access_watchpoint)
1866                     type = hw_access;
1867
1868                   loc = allocate_bp_location (b);
1869                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1870                     ;
1871                   *tmp = loc;
1872                   loc->gdbarch = get_type_arch (value_type (v));
1873
1874                   loc->pspace = frame_pspace;
1875                   loc->address = addr;
1876
1877                   if (bitsize != 0)
1878                     {
1879                       /* Just cover the bytes that make up the bitfield.  */
1880                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1881                     }
1882                   else
1883                     loc->length = TYPE_LENGTH (value_type (v));
1884
1885                   loc->watchpoint_type = type;
1886                 }
1887             }
1888         }
1889
1890       /* Change the type of breakpoint between hardware assisted or
1891          an ordinary watchpoint depending on the hardware support
1892          and free hardware slots.  REPARSE is set when the inferior
1893          is started.  */
1894       if (reparse)
1895         {
1896           int reg_cnt;
1897           enum bp_loc_type loc_type;
1898           struct bp_location *bl;
1899
1900           reg_cnt = can_use_hardware_watchpoint (val_chain);
1901
1902           if (reg_cnt)
1903             {
1904               int i, target_resources_ok, other_type_used;
1905               enum bptype type;
1906
1907               /* Use an exact watchpoint when there's only one memory region to be
1908                  watched, and only one debug register is needed to watch it.  */
1909               b->exact = target_exact_watchpoints && reg_cnt == 1;
1910
1911               /* We need to determine how many resources are already
1912                  used for all other hardware watchpoints plus this one
1913                  to see if we still have enough resources to also fit
1914                  this watchpoint in as well.  */
1915
1916               /* If this is a software watchpoint, we try to turn it
1917                  to a hardware one -- count resources as if B was of
1918                  hardware watchpoint type.  */
1919               type = b->type;
1920               if (type == bp_watchpoint)
1921                 type = bp_hardware_watchpoint;
1922
1923               /* This watchpoint may or may not have been placed on
1924                  the list yet at this point (it won't be in the list
1925                  if we're trying to create it for the first time,
1926                  through watch_command), so always account for it
1927                  manually.  */
1928
1929               /* Count resources used by all watchpoints except B.  */
1930               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
1931
1932               /* Add in the resources needed for B.  */
1933               i += hw_watchpoint_use_count (b);
1934
1935               target_resources_ok
1936                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1937               if (target_resources_ok <= 0)
1938                 {
1939                   int sw_mode = b->ops->works_in_software_mode (b);
1940
1941                   if (target_resources_ok == 0 && !sw_mode)
1942                     error (_("Target does not support this type of "
1943                              "hardware watchpoint."));
1944                   else if (target_resources_ok < 0 && !sw_mode)
1945                     error (_("There are not enough available hardware "
1946                              "resources for this watchpoint."));
1947
1948                   /* Downgrade to software watchpoint.  */
1949                   b->type = bp_watchpoint;
1950                 }
1951               else
1952                 {
1953                   /* If this was a software watchpoint, we've just
1954                      found we have enough resources to turn it to a
1955                      hardware watchpoint.  Otherwise, this is a
1956                      nop.  */
1957                   b->type = type;
1958                 }
1959             }
1960           else if (!b->ops->works_in_software_mode (b))
1961             {
1962               if (!can_use_hw_watchpoints)
1963                 error (_("Can't set read/access watchpoint when "
1964                          "hardware watchpoints are disabled."));
1965               else
1966                 error (_("Expression cannot be implemented with "
1967                          "read/access watchpoint."));
1968             }
1969           else
1970             b->type = bp_watchpoint;
1971
1972           loc_type = (b->type == bp_watchpoint? bp_loc_other
1973                       : bp_loc_hardware_watchpoint);
1974           for (bl = b->loc; bl; bl = bl->next)
1975             bl->loc_type = loc_type;
1976         }
1977
1978       for (v = val_chain; v; v = next)
1979         {
1980           next = value_next (v);
1981           if (v != b->val)
1982             value_free (v);
1983         }
1984
1985       /* If a software watchpoint is not watching any memory, then the
1986          above left it without any location set up.  But,
1987          bpstat_stop_status requires a location to be able to report
1988          stops, so make sure there's at least a dummy one.  */
1989       if (b->type == bp_watchpoint && b->loc == NULL)
1990         software_watchpoint_add_no_memory_location (b, frame_pspace);
1991     }
1992   else if (!within_current_scope)
1993     {
1994       printf_filtered (_("\
1995 Watchpoint %d deleted because the program has left the block\n\
1996 in which its expression is valid.\n"),
1997                        b->number);
1998       watchpoint_del_at_next_stop (b);
1999     }
2000
2001   /* Restore the selected frame.  */
2002   if (frame_saved)
2003     select_frame (frame_find_by_id (saved_frame_id));
2004 }
2005
2006
2007 /* Returns 1 iff breakpoint location should be
2008    inserted in the inferior.  We don't differentiate the type of BL's owner
2009    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2010    breakpoint_ops is not defined, because in insert_bp_location,
2011    tracepoint's insert_location will not be called.  */
2012 static int
2013 should_be_inserted (struct bp_location *bl)
2014 {
2015   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2016     return 0;
2017
2018   if (bl->owner->disposition == disp_del_at_next_stop)
2019     return 0;
2020
2021   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2022     return 0;
2023
2024   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2025     return 0;
2026
2027   /* This is set for example, when we're attached to the parent of a
2028      vfork, and have detached from the child.  The child is running
2029      free, and we expect it to do an exec or exit, at which point the
2030      OS makes the parent schedulable again (and the target reports
2031      that the vfork is done).  Until the child is done with the shared
2032      memory region, do not insert breakpoints in the parent, otherwise
2033      the child could still trip on the parent's breakpoints.  Since
2034      the parent is blocked anyway, it won't miss any breakpoint.  */
2035   if (bl->pspace->breakpoints_not_allowed)
2036     return 0;
2037
2038   /* Don't insert a breakpoint if we're trying to step past its
2039      location, except if the breakpoint is a single-step breakpoint,
2040      and the breakpoint's thread is the thread which is stepping past
2041      a breakpoint.  */
2042   if ((bl->loc_type == bp_loc_software_breakpoint
2043        || bl->loc_type == bp_loc_hardware_breakpoint)
2044       && stepping_past_instruction_at (bl->pspace->aspace,
2045                                        bl->address)
2046       /* The single-step breakpoint may be inserted at the location
2047          we're trying to step if the instruction branches to itself.
2048          However, the instruction won't be executed at all and it may
2049          break the semantics of the instruction, for example, the
2050          instruction is a conditional branch or updates some flags.
2051          We can't fix it unless GDB is able to emulate the instruction
2052          or switch to displaced stepping.  */
2053       && !(bl->owner->type == bp_single_step
2054            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2055     {
2056       if (debug_infrun)
2057         {
2058           fprintf_unfiltered (gdb_stdlog,
2059                               "infrun: skipping breakpoint: "
2060                               "stepping past insn at: %s\n",
2061                               paddress (bl->gdbarch, bl->address));
2062         }
2063       return 0;
2064     }
2065
2066   /* Don't insert watchpoints if we're trying to step past the
2067      instruction that triggered one.  */
2068   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2069       && stepping_past_nonsteppable_watchpoint ())
2070     {
2071       if (debug_infrun)
2072         {
2073           fprintf_unfiltered (gdb_stdlog,
2074                               "infrun: stepping past non-steppable watchpoint. "
2075                               "skipping watchpoint at %s:%d\n",
2076                               paddress (bl->gdbarch, bl->address),
2077                               bl->length);
2078         }
2079       return 0;
2080     }
2081
2082   return 1;
2083 }
2084
2085 /* Same as should_be_inserted but does the check assuming
2086    that the location is not duplicated.  */
2087
2088 static int
2089 unduplicated_should_be_inserted (struct bp_location *bl)
2090 {
2091   int result;
2092   const int save_duplicate = bl->duplicate;
2093
2094   bl->duplicate = 0;
2095   result = should_be_inserted (bl);
2096   bl->duplicate = save_duplicate;
2097   return result;
2098 }
2099
2100 /* Parses a conditional described by an expression COND into an
2101    agent expression bytecode suitable for evaluation
2102    by the bytecode interpreter.  Return NULL if there was
2103    any error during parsing.  */
2104
2105 static agent_expr_up
2106 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2107 {
2108   if (cond == NULL)
2109     return NULL;
2110
2111   agent_expr_up aexpr;
2112
2113   /* We don't want to stop processing, so catch any errors
2114      that may show up.  */
2115   TRY
2116     {
2117       aexpr = gen_eval_for_expr (scope, cond);
2118     }
2119
2120   CATCH (ex, RETURN_MASK_ERROR)
2121     {
2122       /* If we got here, it means the condition could not be parsed to a valid
2123          bytecode expression and thus can't be evaluated on the target's side.
2124          It's no use iterating through the conditions.  */
2125     }
2126   END_CATCH
2127
2128   /* We have a valid agent expression.  */
2129   return aexpr;
2130 }
2131
2132 /* Based on location BL, create a list of breakpoint conditions to be
2133    passed on to the target.  If we have duplicated locations with different
2134    conditions, we will add such conditions to the list.  The idea is that the
2135    target will evaluate the list of conditions and will only notify GDB when
2136    one of them is true.  */
2137
2138 static void
2139 build_target_condition_list (struct bp_location *bl)
2140 {
2141   struct bp_location **locp = NULL, **loc2p;
2142   int null_condition_or_parse_error = 0;
2143   int modified = bl->needs_update;
2144   struct bp_location *loc;
2145
2146   /* Release conditions left over from a previous insert.  */
2147   bl->target_info.conditions.clear ();
2148
2149   /* This is only meaningful if the target is
2150      evaluating conditions and if the user has
2151      opted for condition evaluation on the target's
2152      side.  */
2153   if (gdb_evaluates_breakpoint_condition_p ()
2154       || !target_supports_evaluation_of_breakpoint_conditions ())
2155     return;
2156
2157   /* Do a first pass to check for locations with no assigned
2158      conditions or conditions that fail to parse to a valid agent expression
2159      bytecode.  If any of these happen, then it's no use to send conditions
2160      to the target since this location will always trigger and generate a
2161      response back to GDB.  */
2162   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2163     {
2164       loc = (*loc2p);
2165       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2166         {
2167           if (modified)
2168             {
2169               /* Re-parse the conditions since something changed.  In that
2170                  case we already freed the condition bytecodes (see
2171                  force_breakpoint_reinsertion).  We just
2172                  need to parse the condition to bytecodes again.  */
2173               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2174                                                         loc->cond.get ());
2175             }
2176
2177           /* If we have a NULL bytecode expression, it means something
2178              went wrong or we have a null condition expression.  */
2179           if (!loc->cond_bytecode)
2180             {
2181               null_condition_or_parse_error = 1;
2182               break;
2183             }
2184         }
2185     }
2186
2187   /* If any of these happened, it means we will have to evaluate the conditions
2188      for the location's address on gdb's side.  It is no use keeping bytecodes
2189      for all the other duplicate locations, thus we free all of them here.
2190
2191      This is so we have a finer control over which locations' conditions are
2192      being evaluated by GDB or the remote stub.  */
2193   if (null_condition_or_parse_error)
2194     {
2195       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2196         {
2197           loc = (*loc2p);
2198           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2199             {
2200               /* Only go as far as the first NULL bytecode is
2201                  located.  */
2202               if (!loc->cond_bytecode)
2203                 return;
2204
2205               loc->cond_bytecode.reset ();
2206             }
2207         }
2208     }
2209
2210   /* No NULL conditions or failed bytecode generation.  Build a condition list
2211      for this location's address.  */
2212   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2213     {
2214       loc = (*loc2p);
2215       if (loc->cond
2216           && is_breakpoint (loc->owner)
2217           && loc->pspace->num == bl->pspace->num
2218           && loc->owner->enable_state == bp_enabled
2219           && loc->enabled)
2220         {
2221           /* Add the condition to the vector.  This will be used later
2222              to send the conditions to the target.  */
2223           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2224         }
2225     }
2226
2227   return;
2228 }
2229
2230 /* Parses a command described by string CMD into an agent expression
2231    bytecode suitable for evaluation by the bytecode interpreter.
2232    Return NULL if there was any error during parsing.  */
2233
2234 static agent_expr_up
2235 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2236 {
2237   struct cleanup *old_cleanups = 0;
2238   struct expression **argvec;
2239   const char *cmdrest;
2240   const char *format_start, *format_end;
2241   struct format_piece *fpieces;
2242   int nargs;
2243   struct gdbarch *gdbarch = get_current_arch ();
2244
2245   if (cmd == NULL)
2246     return NULL;
2247
2248   cmdrest = cmd;
2249
2250   if (*cmdrest == ',')
2251     ++cmdrest;
2252   cmdrest = skip_spaces (cmdrest);
2253
2254   if (*cmdrest++ != '"')
2255     error (_("No format string following the location"));
2256
2257   format_start = cmdrest;
2258
2259   fpieces = parse_format_string (&cmdrest);
2260
2261   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2262
2263   format_end = cmdrest;
2264
2265   if (*cmdrest++ != '"')
2266     error (_("Bad format string, non-terminated '\"'."));
2267   
2268   cmdrest = skip_spaces (cmdrest);
2269
2270   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2271     error (_("Invalid argument syntax"));
2272
2273   if (*cmdrest == ',')
2274     cmdrest++;
2275   cmdrest = skip_spaces (cmdrest);
2276
2277   /* For each argument, make an expression.  */
2278
2279   argvec = (struct expression **) alloca (strlen (cmd)
2280                                          * sizeof (struct expression *));
2281
2282   nargs = 0;
2283   while (*cmdrest != '\0')
2284     {
2285       const char *cmd1;
2286
2287       cmd1 = cmdrest;
2288       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2289       argvec[nargs++] = expr.release ();
2290       cmdrest = cmd1;
2291       if (*cmdrest == ',')
2292         ++cmdrest;
2293     }
2294
2295   agent_expr_up aexpr;
2296
2297   /* We don't want to stop processing, so catch any errors
2298      that may show up.  */
2299   TRY
2300     {
2301       aexpr = gen_printf (scope, gdbarch, 0, 0,
2302                           format_start, format_end - format_start,
2303                           fpieces, nargs, argvec);
2304     }
2305   CATCH (ex, RETURN_MASK_ERROR)
2306     {
2307       /* If we got here, it means the command could not be parsed to a valid
2308          bytecode expression and thus can't be evaluated on the target's side.
2309          It's no use iterating through the other commands.  */
2310     }
2311   END_CATCH
2312
2313   do_cleanups (old_cleanups);
2314
2315   /* We have a valid agent expression, return it.  */
2316   return aexpr;
2317 }
2318
2319 /* Based on location BL, create a list of breakpoint commands to be
2320    passed on to the target.  If we have duplicated locations with
2321    different commands, we will add any such to the list.  */
2322
2323 static void
2324 build_target_command_list (struct bp_location *bl)
2325 {
2326   struct bp_location **locp = NULL, **loc2p;
2327   int null_command_or_parse_error = 0;
2328   int modified = bl->needs_update;
2329   struct bp_location *loc;
2330
2331   /* Clear commands left over from a previous insert.  */
2332   bl->target_info.tcommands.clear ();
2333
2334   if (!target_can_run_breakpoint_commands ())
2335     return;
2336
2337   /* For now, limit to agent-style dprintf breakpoints.  */
2338   if (dprintf_style != dprintf_style_agent)
2339     return;
2340
2341   /* For now, if we have any duplicate location that isn't a dprintf,
2342      don't install the target-side commands, as that would make the
2343      breakpoint not be reported to the core, and we'd lose
2344      control.  */
2345   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2346     {
2347       loc = (*loc2p);
2348       if (is_breakpoint (loc->owner)
2349           && loc->pspace->num == bl->pspace->num
2350           && loc->owner->type != bp_dprintf)
2351         return;
2352     }
2353
2354   /* Do a first pass to check for locations with no assigned
2355      conditions or conditions that fail to parse to a valid agent expression
2356      bytecode.  If any of these happen, then it's no use to send conditions
2357      to the target since this location will always trigger and generate a
2358      response back to GDB.  */
2359   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2360     {
2361       loc = (*loc2p);
2362       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2363         {
2364           if (modified)
2365             {
2366               /* Re-parse the commands since something changed.  In that
2367                  case we already freed the command bytecodes (see
2368                  force_breakpoint_reinsertion).  We just
2369                  need to parse the command to bytecodes again.  */
2370               loc->cmd_bytecode
2371                 = parse_cmd_to_aexpr (bl->address,
2372                                       loc->owner->extra_string);
2373             }
2374
2375           /* If we have a NULL bytecode expression, it means something
2376              went wrong or we have a null command expression.  */
2377           if (!loc->cmd_bytecode)
2378             {
2379               null_command_or_parse_error = 1;
2380               break;
2381             }
2382         }
2383     }
2384
2385   /* If anything failed, then we're not doing target-side commands,
2386      and so clean up.  */
2387   if (null_command_or_parse_error)
2388     {
2389       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2390         {
2391           loc = (*loc2p);
2392           if (is_breakpoint (loc->owner)
2393               && loc->pspace->num == bl->pspace->num)
2394             {
2395               /* Only go as far as the first NULL bytecode is
2396                  located.  */
2397               if (loc->cmd_bytecode == NULL)
2398                 return;
2399
2400               loc->cmd_bytecode.reset ();
2401             }
2402         }
2403     }
2404
2405   /* No NULL commands or failed bytecode generation.  Build a command list
2406      for this location's address.  */
2407   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2408     {
2409       loc = (*loc2p);
2410       if (loc->owner->extra_string
2411           && is_breakpoint (loc->owner)
2412           && loc->pspace->num == bl->pspace->num
2413           && loc->owner->enable_state == bp_enabled
2414           && loc->enabled)
2415         {
2416           /* Add the command to the vector.  This will be used later
2417              to send the commands to the target.  */
2418           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2419         }
2420     }
2421
2422   bl->target_info.persist = 0;
2423   /* Maybe flag this location as persistent.  */
2424   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2425     bl->target_info.persist = 1;
2426 }
2427
2428 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2429    of breakpoint according to ADDR except single-step breakpoint.
2430    Get the kind of single-step breakpoint according to the current
2431    registers state.  */
2432
2433 static int
2434 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2435 {
2436   if (bl->owner->type == bp_single_step)
2437     {
2438       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2439       struct regcache *regcache;
2440
2441       regcache = get_thread_regcache (thr->ptid);
2442
2443       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2444                                                          regcache, addr);
2445     }
2446   else
2447     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2448 }
2449
2450 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2451    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2452    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2453    Returns 0 for success, 1 if the bp_location type is not supported or
2454    -1 for failure.
2455
2456    NOTE drow/2003-09-09: This routine could be broken down to an
2457    object-style method for each breakpoint or catchpoint type.  */
2458 static int
2459 insert_bp_location (struct bp_location *bl,
2460                     struct ui_file *tmp_error_stream,
2461                     int *disabled_breaks,
2462                     int *hw_breakpoint_error,
2463                     int *hw_bp_error_explained_already)
2464 {
2465   enum errors bp_err = GDB_NO_ERROR;
2466   const char *bp_err_message = NULL;
2467
2468   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2469     return 0;
2470
2471   /* Note we don't initialize bl->target_info, as that wipes out
2472      the breakpoint location's shadow_contents if the breakpoint
2473      is still inserted at that location.  This in turn breaks
2474      target_read_memory which depends on these buffers when
2475      a memory read is requested at the breakpoint location:
2476      Once the target_info has been wiped, we fail to see that
2477      we have a breakpoint inserted at that address and thus
2478      read the breakpoint instead of returning the data saved in
2479      the breakpoint location's shadow contents.  */
2480   bl->target_info.reqstd_address = bl->address;
2481   bl->target_info.placed_address_space = bl->pspace->aspace;
2482   bl->target_info.length = bl->length;
2483
2484   /* When working with target-side conditions, we must pass all the conditions
2485      for the same breakpoint address down to the target since GDB will not
2486      insert those locations.  With a list of breakpoint conditions, the target
2487      can decide when to stop and notify GDB.  */
2488
2489   if (is_breakpoint (bl->owner))
2490     {
2491       build_target_condition_list (bl);
2492       build_target_command_list (bl);
2493       /* Reset the modification marker.  */
2494       bl->needs_update = 0;
2495     }
2496
2497   if (bl->loc_type == bp_loc_software_breakpoint
2498       || bl->loc_type == bp_loc_hardware_breakpoint)
2499     {
2500       if (bl->owner->type != bp_hardware_breakpoint)
2501         {
2502           /* If the explicitly specified breakpoint type
2503              is not hardware breakpoint, check the memory map to see
2504              if the breakpoint address is in read only memory or not.
2505
2506              Two important cases are:
2507              - location type is not hardware breakpoint, memory
2508              is readonly.  We change the type of the location to
2509              hardware breakpoint.
2510              - location type is hardware breakpoint, memory is
2511              read-write.  This means we've previously made the
2512              location hardware one, but then the memory map changed,
2513              so we undo.
2514              
2515              When breakpoints are removed, remove_breakpoints will use
2516              location types we've just set here, the only possible
2517              problem is that memory map has changed during running
2518              program, but it's not going to work anyway with current
2519              gdb.  */
2520           struct mem_region *mr 
2521             = lookup_mem_region (bl->target_info.reqstd_address);
2522           
2523           if (mr)
2524             {
2525               if (automatic_hardware_breakpoints)
2526                 {
2527                   enum bp_loc_type new_type;
2528                   
2529                   if (mr->attrib.mode != MEM_RW)
2530                     new_type = bp_loc_hardware_breakpoint;
2531                   else 
2532                     new_type = bp_loc_software_breakpoint;
2533                   
2534                   if (new_type != bl->loc_type)
2535                     {
2536                       static int said = 0;
2537
2538                       bl->loc_type = new_type;
2539                       if (!said)
2540                         {
2541                           fprintf_filtered (gdb_stdout,
2542                                             _("Note: automatically using "
2543                                               "hardware breakpoints for "
2544                                               "read-only addresses.\n"));
2545                           said = 1;
2546                         }
2547                     }
2548                 }
2549               else if (bl->loc_type == bp_loc_software_breakpoint
2550                        && mr->attrib.mode != MEM_RW)
2551                 {
2552                   fprintf_unfiltered (tmp_error_stream,
2553                                       _("Cannot insert breakpoint %d.\n"
2554                                         "Cannot set software breakpoint "
2555                                         "at read-only address %s\n"),
2556                                       bl->owner->number,
2557                                       paddress (bl->gdbarch, bl->address));
2558                   return 1;
2559                 }
2560             }
2561         }
2562         
2563       /* First check to see if we have to handle an overlay.  */
2564       if (overlay_debugging == ovly_off
2565           || bl->section == NULL
2566           || !(section_is_overlay (bl->section)))
2567         {
2568           /* No overlay handling: just set the breakpoint.  */
2569           TRY
2570             {
2571               int val;
2572
2573               val = bl->owner->ops->insert_location (bl);
2574               if (val)
2575                 bp_err = GENERIC_ERROR;
2576             }
2577           CATCH (e, RETURN_MASK_ALL)
2578             {
2579               bp_err = e.error;
2580               bp_err_message = e.message;
2581             }
2582           END_CATCH
2583         }
2584       else
2585         {
2586           /* This breakpoint is in an overlay section.
2587              Shall we set a breakpoint at the LMA?  */
2588           if (!overlay_events_enabled)
2589             {
2590               /* Yes -- overlay event support is not active, 
2591                  so we must try to set a breakpoint at the LMA.
2592                  This will not work for a hardware breakpoint.  */
2593               if (bl->loc_type == bp_loc_hardware_breakpoint)
2594                 warning (_("hardware breakpoint %d not supported in overlay!"),
2595                          bl->owner->number);
2596               else
2597                 {
2598                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2599                                                              bl->section);
2600                   /* Set a software (trap) breakpoint at the LMA.  */
2601                   bl->overlay_target_info = bl->target_info;
2602                   bl->overlay_target_info.reqstd_address = addr;
2603
2604                   /* No overlay handling: just set the breakpoint.  */
2605                   TRY
2606                     {
2607                       int val;
2608
2609                       bl->overlay_target_info.kind
2610                         = breakpoint_kind (bl, &addr);
2611                       bl->overlay_target_info.placed_address = addr;
2612                       val = target_insert_breakpoint (bl->gdbarch,
2613                                                       &bl->overlay_target_info);
2614                       if (val)
2615                         bp_err = GENERIC_ERROR;
2616                     }
2617                   CATCH (e, RETURN_MASK_ALL)
2618                     {
2619                       bp_err = e.error;
2620                       bp_err_message = e.message;
2621                     }
2622                   END_CATCH
2623
2624                   if (bp_err != GDB_NO_ERROR)
2625                     fprintf_unfiltered (tmp_error_stream,
2626                                         "Overlay breakpoint %d "
2627                                         "failed: in ROM?\n",
2628                                         bl->owner->number);
2629                 }
2630             }
2631           /* Shall we set a breakpoint at the VMA? */
2632           if (section_is_mapped (bl->section))
2633             {
2634               /* Yes.  This overlay section is mapped into memory.  */
2635               TRY
2636                 {
2637                   int val;
2638
2639                   val = bl->owner->ops->insert_location (bl);
2640                   if (val)
2641                     bp_err = GENERIC_ERROR;
2642                 }
2643               CATCH (e, RETURN_MASK_ALL)
2644                 {
2645                   bp_err = e.error;
2646                   bp_err_message = e.message;
2647                 }
2648               END_CATCH
2649             }
2650           else
2651             {
2652               /* No.  This breakpoint will not be inserted.  
2653                  No error, but do not mark the bp as 'inserted'.  */
2654               return 0;
2655             }
2656         }
2657
2658       if (bp_err != GDB_NO_ERROR)
2659         {
2660           /* Can't set the breakpoint.  */
2661
2662           /* In some cases, we might not be able to insert a
2663              breakpoint in a shared library that has already been
2664              removed, but we have not yet processed the shlib unload
2665              event.  Unfortunately, some targets that implement
2666              breakpoint insertion themselves can't tell why the
2667              breakpoint insertion failed (e.g., the remote target
2668              doesn't define error codes), so we must treat generic
2669              errors as memory errors.  */
2670           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2671               && bl->loc_type == bp_loc_software_breakpoint
2672               && (solib_name_from_address (bl->pspace, bl->address)
2673                   || shared_objfile_contains_address_p (bl->pspace,
2674                                                         bl->address)))
2675             {
2676               /* See also: disable_breakpoints_in_shlibs.  */
2677               bl->shlib_disabled = 1;
2678               observer_notify_breakpoint_modified (bl->owner);
2679               if (!*disabled_breaks)
2680                 {
2681                   fprintf_unfiltered (tmp_error_stream, 
2682                                       "Cannot insert breakpoint %d.\n", 
2683                                       bl->owner->number);
2684                   fprintf_unfiltered (tmp_error_stream, 
2685                                       "Temporarily disabling shared "
2686                                       "library breakpoints:\n");
2687                 }
2688               *disabled_breaks = 1;
2689               fprintf_unfiltered (tmp_error_stream,
2690                                   "breakpoint #%d\n", bl->owner->number);
2691               return 0;
2692             }
2693           else
2694             {
2695               if (bl->loc_type == bp_loc_hardware_breakpoint)
2696                 {
2697                   *hw_breakpoint_error = 1;
2698                   *hw_bp_error_explained_already = bp_err_message != NULL;
2699                   fprintf_unfiltered (tmp_error_stream,
2700                                       "Cannot insert hardware breakpoint %d%s",
2701                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2702                   if (bp_err_message != NULL)
2703                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2704                 }
2705               else
2706                 {
2707                   if (bp_err_message == NULL)
2708                     {
2709                       std::string message
2710                         = memory_error_message (TARGET_XFER_E_IO,
2711                                                 bl->gdbarch, bl->address);
2712
2713                       fprintf_unfiltered (tmp_error_stream,
2714                                           "Cannot insert breakpoint %d.\n"
2715                                           "%s\n",
2716                                           bl->owner->number, message.c_str ());
2717                     }
2718                   else
2719                     {
2720                       fprintf_unfiltered (tmp_error_stream,
2721                                           "Cannot insert breakpoint %d: %s\n",
2722                                           bl->owner->number,
2723                                           bp_err_message);
2724                     }
2725                 }
2726               return 1;
2727
2728             }
2729         }
2730       else
2731         bl->inserted = 1;
2732
2733       return 0;
2734     }
2735
2736   else if (bl->loc_type == bp_loc_hardware_watchpoint
2737            /* NOTE drow/2003-09-08: This state only exists for removing
2738               watchpoints.  It's not clear that it's necessary...  */
2739            && bl->owner->disposition != disp_del_at_next_stop)
2740     {
2741       int val;
2742
2743       gdb_assert (bl->owner->ops != NULL
2744                   && bl->owner->ops->insert_location != NULL);
2745
2746       val = bl->owner->ops->insert_location (bl);
2747
2748       /* If trying to set a read-watchpoint, and it turns out it's not
2749          supported, try emulating one with an access watchpoint.  */
2750       if (val == 1 && bl->watchpoint_type == hw_read)
2751         {
2752           struct bp_location *loc, **loc_temp;
2753
2754           /* But don't try to insert it, if there's already another
2755              hw_access location that would be considered a duplicate
2756              of this one.  */
2757           ALL_BP_LOCATIONS (loc, loc_temp)
2758             if (loc != bl
2759                 && loc->watchpoint_type == hw_access
2760                 && watchpoint_locations_match (bl, loc))
2761               {
2762                 bl->duplicate = 1;
2763                 bl->inserted = 1;
2764                 bl->target_info = loc->target_info;
2765                 bl->watchpoint_type = hw_access;
2766                 val = 0;
2767                 break;
2768               }
2769
2770           if (val == 1)
2771             {
2772               bl->watchpoint_type = hw_access;
2773               val = bl->owner->ops->insert_location (bl);
2774
2775               if (val)
2776                 /* Back to the original value.  */
2777                 bl->watchpoint_type = hw_read;
2778             }
2779         }
2780
2781       bl->inserted = (val == 0);
2782     }
2783
2784   else if (bl->owner->type == bp_catchpoint)
2785     {
2786       int val;
2787
2788       gdb_assert (bl->owner->ops != NULL
2789                   && bl->owner->ops->insert_location != NULL);
2790
2791       val = bl->owner->ops->insert_location (bl);
2792       if (val)
2793         {
2794           bl->owner->enable_state = bp_disabled;
2795
2796           if (val == 1)
2797             warning (_("\
2798 Error inserting catchpoint %d: Your system does not support this type\n\
2799 of catchpoint."), bl->owner->number);
2800           else
2801             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2802         }
2803
2804       bl->inserted = (val == 0);
2805
2806       /* We've already printed an error message if there was a problem
2807          inserting this catchpoint, and we've disabled the catchpoint,
2808          so just return success.  */
2809       return 0;
2810     }
2811
2812   return 0;
2813 }
2814
2815 /* This function is called when program space PSPACE is about to be
2816    deleted.  It takes care of updating breakpoints to not reference
2817    PSPACE anymore.  */
2818
2819 void
2820 breakpoint_program_space_exit (struct program_space *pspace)
2821 {
2822   struct breakpoint *b, *b_temp;
2823   struct bp_location *loc, **loc_temp;
2824
2825   /* Remove any breakpoint that was set through this program space.  */
2826   ALL_BREAKPOINTS_SAFE (b, b_temp)
2827     {
2828       if (b->pspace == pspace)
2829         delete_breakpoint (b);
2830     }
2831
2832   /* Breakpoints set through other program spaces could have locations
2833      bound to PSPACE as well.  Remove those.  */
2834   ALL_BP_LOCATIONS (loc, loc_temp)
2835     {
2836       struct bp_location *tmp;
2837
2838       if (loc->pspace == pspace)
2839         {
2840           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2841           if (loc->owner->loc == loc)
2842             loc->owner->loc = loc->next;
2843           else
2844             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2845               if (tmp->next == loc)
2846                 {
2847                   tmp->next = loc->next;
2848                   break;
2849                 }
2850         }
2851     }
2852
2853   /* Now update the global location list to permanently delete the
2854      removed locations above.  */
2855   update_global_location_list (UGLL_DONT_INSERT);
2856 }
2857
2858 /* Make sure all breakpoints are inserted in inferior.
2859    Throws exception on any error.
2860    A breakpoint that is already inserted won't be inserted
2861    again, so calling this function twice is safe.  */
2862 void
2863 insert_breakpoints (void)
2864 {
2865   struct breakpoint *bpt;
2866
2867   ALL_BREAKPOINTS (bpt)
2868     if (is_hardware_watchpoint (bpt))
2869       {
2870         struct watchpoint *w = (struct watchpoint *) bpt;
2871
2872         update_watchpoint (w, 0 /* don't reparse.  */);
2873       }
2874
2875   /* Updating watchpoints creates new locations, so update the global
2876      location list.  Explicitly tell ugll to insert locations and
2877      ignore breakpoints_always_inserted_mode.  */
2878   update_global_location_list (UGLL_INSERT);
2879 }
2880
2881 /* Invoke CALLBACK for each of bp_location.  */
2882
2883 void
2884 iterate_over_bp_locations (walk_bp_location_callback callback)
2885 {
2886   struct bp_location *loc, **loc_tmp;
2887
2888   ALL_BP_LOCATIONS (loc, loc_tmp)
2889     {
2890       callback (loc, NULL);
2891     }
2892 }
2893
2894 /* This is used when we need to synch breakpoint conditions between GDB and the
2895    target.  It is the case with deleting and disabling of breakpoints when using
2896    always-inserted mode.  */
2897
2898 static void
2899 update_inserted_breakpoint_locations (void)
2900 {
2901   struct bp_location *bl, **blp_tmp;
2902   int error_flag = 0;
2903   int val = 0;
2904   int disabled_breaks = 0;
2905   int hw_breakpoint_error = 0;
2906   int hw_bp_details_reported = 0;
2907
2908   string_file tmp_error_stream;
2909
2910   /* Explicitly mark the warning -- this will only be printed if
2911      there was an error.  */
2912   tmp_error_stream.puts ("Warning:\n");
2913
2914   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2915
2916   ALL_BP_LOCATIONS (bl, blp_tmp)
2917     {
2918       /* We only want to update software breakpoints and hardware
2919          breakpoints.  */
2920       if (!is_breakpoint (bl->owner))
2921         continue;
2922
2923       /* We only want to update locations that are already inserted
2924          and need updating.  This is to avoid unwanted insertion during
2925          deletion of breakpoints.  */
2926       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2927         continue;
2928
2929       switch_to_program_space_and_thread (bl->pspace);
2930
2931       /* For targets that support global breakpoints, there's no need
2932          to select an inferior to insert breakpoint to.  In fact, even
2933          if we aren't attached to any process yet, we should still
2934          insert breakpoints.  */
2935       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2936           && ptid_equal (inferior_ptid, null_ptid))
2937         continue;
2938
2939       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2940                                     &hw_breakpoint_error, &hw_bp_details_reported);
2941       if (val)
2942         error_flag = val;
2943     }
2944
2945   if (error_flag)
2946     {
2947       target_terminal::ours_for_output ();
2948       error_stream (tmp_error_stream);
2949     }
2950 }
2951
2952 /* Used when starting or continuing the program.  */
2953
2954 static void
2955 insert_breakpoint_locations (void)
2956 {
2957   struct breakpoint *bpt;
2958   struct bp_location *bl, **blp_tmp;
2959   int error_flag = 0;
2960   int val = 0;
2961   int disabled_breaks = 0;
2962   int hw_breakpoint_error = 0;
2963   int hw_bp_error_explained_already = 0;
2964
2965   string_file tmp_error_stream;
2966
2967   /* Explicitly mark the warning -- this will only be printed if
2968      there was an error.  */
2969   tmp_error_stream.puts ("Warning:\n");
2970
2971   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2972
2973   ALL_BP_LOCATIONS (bl, blp_tmp)
2974     {
2975       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2976         continue;
2977
2978       /* There is no point inserting thread-specific breakpoints if
2979          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2980          has BL->OWNER always non-NULL.  */
2981       if (bl->owner->thread != -1
2982           && !valid_global_thread_id (bl->owner->thread))
2983         continue;
2984
2985       switch_to_program_space_and_thread (bl->pspace);
2986
2987       /* For targets that support global breakpoints, there's no need
2988          to select an inferior to insert breakpoint to.  In fact, even
2989          if we aren't attached to any process yet, we should still
2990          insert breakpoints.  */
2991       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2992           && ptid_equal (inferior_ptid, null_ptid))
2993         continue;
2994
2995       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2996                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2997       if (val)
2998         error_flag = val;
2999     }
3000
3001   /* If we failed to insert all locations of a watchpoint, remove
3002      them, as half-inserted watchpoint is of limited use.  */
3003   ALL_BREAKPOINTS (bpt)  
3004     {
3005       int some_failed = 0;
3006       struct bp_location *loc;
3007
3008       if (!is_hardware_watchpoint (bpt))
3009         continue;
3010
3011       if (!breakpoint_enabled (bpt))
3012         continue;
3013
3014       if (bpt->disposition == disp_del_at_next_stop)
3015         continue;
3016       
3017       for (loc = bpt->loc; loc; loc = loc->next)
3018         if (!loc->inserted && should_be_inserted (loc))
3019           {
3020             some_failed = 1;
3021             break;
3022           }
3023       if (some_failed)
3024         {
3025           for (loc = bpt->loc; loc; loc = loc->next)
3026             if (loc->inserted)
3027               remove_breakpoint (loc);
3028
3029           hw_breakpoint_error = 1;
3030           tmp_error_stream.printf ("Could not insert "
3031                                    "hardware watchpoint %d.\n",
3032                                    bpt->number);
3033           error_flag = -1;
3034         }
3035     }
3036
3037   if (error_flag)
3038     {
3039       /* If a hardware breakpoint or watchpoint was inserted, add a
3040          message about possibly exhausted resources.  */
3041       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3042         {
3043           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3044 You may have requested too many hardware breakpoints/watchpoints.\n");
3045         }
3046       target_terminal::ours_for_output ();
3047       error_stream (tmp_error_stream);
3048     }
3049 }
3050
3051 /* Used when the program stops.
3052    Returns zero if successful, or non-zero if there was a problem
3053    removing a breakpoint location.  */
3054
3055 int
3056 remove_breakpoints (void)
3057 {
3058   struct bp_location *bl, **blp_tmp;
3059   int val = 0;
3060
3061   ALL_BP_LOCATIONS (bl, blp_tmp)
3062   {
3063     if (bl->inserted && !is_tracepoint (bl->owner))
3064       val |= remove_breakpoint (bl);
3065   }
3066   return val;
3067 }
3068
3069 /* When a thread exits, remove breakpoints that are related to
3070    that thread.  */
3071
3072 static void
3073 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3074 {
3075   struct breakpoint *b, *b_tmp;
3076
3077   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3078     {
3079       if (b->thread == tp->global_num && user_breakpoint_p (b))
3080         {
3081           b->disposition = disp_del_at_next_stop;
3082
3083           printf_filtered (_("\
3084 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3085                            b->number, print_thread_id (tp));
3086
3087           /* Hide it from the user.  */
3088           b->number = 0;
3089        }
3090     }
3091 }
3092
3093 /* Remove breakpoints of process PID.  */
3094
3095 int
3096 remove_breakpoints_pid (int pid)
3097 {
3098   struct bp_location *bl, **blp_tmp;
3099   int val;
3100   struct inferior *inf = find_inferior_pid (pid);
3101
3102   ALL_BP_LOCATIONS (bl, blp_tmp)
3103   {
3104     if (bl->pspace != inf->pspace)
3105       continue;
3106
3107     if (bl->inserted && !bl->target_info.persist)
3108       {
3109         val = remove_breakpoint (bl);
3110         if (val != 0)
3111           return val;
3112       }
3113   }
3114   return 0;
3115 }
3116
3117 static int internal_breakpoint_number = -1;
3118
3119 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3120    If INTERNAL is non-zero, the breakpoint number will be populated
3121    from internal_breakpoint_number and that variable decremented.
3122    Otherwise the breakpoint number will be populated from
3123    breakpoint_count and that value incremented.  Internal breakpoints
3124    do not set the internal var bpnum.  */
3125 static void
3126 set_breakpoint_number (int internal, struct breakpoint *b)
3127 {
3128   if (internal)
3129     b->number = internal_breakpoint_number--;
3130   else
3131     {
3132       set_breakpoint_count (breakpoint_count + 1);
3133       b->number = breakpoint_count;
3134     }
3135 }
3136
3137 static struct breakpoint *
3138 create_internal_breakpoint (struct gdbarch *gdbarch,
3139                             CORE_ADDR address, enum bptype type,
3140                             const struct breakpoint_ops *ops)
3141 {
3142   symtab_and_line sal;
3143   sal.pc = address;
3144   sal.section = find_pc_overlay (sal.pc);
3145   sal.pspace = current_program_space;
3146
3147   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3148   b->number = internal_breakpoint_number--;
3149   b->disposition = disp_donttouch;
3150
3151   return b;
3152 }
3153
3154 static const char *const longjmp_names[] =
3155   {
3156     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3157   };
3158 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3159
3160 /* Per-objfile data private to breakpoint.c.  */
3161 struct breakpoint_objfile_data
3162 {
3163   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3164   struct bound_minimal_symbol overlay_msym {};
3165
3166   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3167   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3168
3169   /* True if we have looked for longjmp probes.  */
3170   int longjmp_searched = 0;
3171
3172   /* SystemTap probe points for longjmp (if any).  These are non-owning
3173      references.  */
3174   std::vector<probe *> longjmp_probes;
3175
3176   /* Minimal symbol for "std::terminate()" (if any).  */
3177   struct bound_minimal_symbol terminate_msym {};
3178
3179   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3180   struct bound_minimal_symbol exception_msym {};
3181
3182   /* True if we have looked for exception probes.  */
3183   int exception_searched = 0;
3184
3185   /* SystemTap probe points for unwinding (if any).  These are non-owning
3186      references.  */
3187   std::vector<probe *> exception_probes;
3188 };
3189
3190 static const struct objfile_data *breakpoint_objfile_key;
3191
3192 /* Minimal symbol not found sentinel.  */
3193 static struct minimal_symbol msym_not_found;
3194
3195 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3196
3197 static int
3198 msym_not_found_p (const struct minimal_symbol *msym)
3199 {
3200   return msym == &msym_not_found;
3201 }
3202
3203 /* Return per-objfile data needed by breakpoint.c.
3204    Allocate the data if necessary.  */
3205
3206 static struct breakpoint_objfile_data *
3207 get_breakpoint_objfile_data (struct objfile *objfile)
3208 {
3209   struct breakpoint_objfile_data *bp_objfile_data;
3210
3211   bp_objfile_data = ((struct breakpoint_objfile_data *)
3212                      objfile_data (objfile, breakpoint_objfile_key));
3213   if (bp_objfile_data == NULL)
3214     {
3215       bp_objfile_data = new breakpoint_objfile_data ();
3216       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3217     }
3218   return bp_objfile_data;
3219 }
3220
3221 static void
3222 free_breakpoint_objfile_data (struct objfile *obj, void *data)
3223 {
3224   struct breakpoint_objfile_data *bp_objfile_data
3225     = (struct breakpoint_objfile_data *) data;
3226
3227   delete bp_objfile_data;
3228 }
3229
3230 static void
3231 create_overlay_event_breakpoint (void)
3232 {
3233   struct objfile *objfile;
3234   const char *const func_name = "_ovly_debug_event";
3235
3236   ALL_OBJFILES (objfile)
3237     {
3238       struct breakpoint *b;
3239       struct breakpoint_objfile_data *bp_objfile_data;
3240       CORE_ADDR addr;
3241       struct explicit_location explicit_loc;
3242
3243       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3244
3245       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3246         continue;
3247
3248       if (bp_objfile_data->overlay_msym.minsym == NULL)
3249         {
3250           struct bound_minimal_symbol m;
3251
3252           m = lookup_minimal_symbol_text (func_name, objfile);
3253           if (m.minsym == NULL)
3254             {
3255               /* Avoid future lookups in this objfile.  */
3256               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3257               continue;
3258             }
3259           bp_objfile_data->overlay_msym = m;
3260         }
3261
3262       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3263       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3264                                       bp_overlay_event,
3265                                       &internal_breakpoint_ops);
3266       initialize_explicit_location (&explicit_loc);
3267       explicit_loc.function_name = ASTRDUP (func_name);
3268       b->location = new_explicit_location (&explicit_loc);
3269
3270       if (overlay_debugging == ovly_auto)
3271         {
3272           b->enable_state = bp_enabled;
3273           overlay_events_enabled = 1;
3274         }
3275       else
3276        {
3277          b->enable_state = bp_disabled;
3278          overlay_events_enabled = 0;
3279        }
3280     }
3281 }
3282
3283 static void
3284 create_longjmp_master_breakpoint (void)
3285 {
3286   struct program_space *pspace;
3287
3288   scoped_restore_current_program_space restore_pspace;
3289
3290   ALL_PSPACES (pspace)
3291   {
3292     struct objfile *objfile;
3293
3294     set_current_program_space (pspace);
3295
3296     ALL_OBJFILES (objfile)
3297     {
3298       int i;
3299       struct gdbarch *gdbarch;
3300       struct breakpoint_objfile_data *bp_objfile_data;
3301
3302       gdbarch = get_objfile_arch (objfile);
3303
3304       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3305
3306       if (!bp_objfile_data->longjmp_searched)
3307         {
3308           std::vector<probe *> ret
3309             = find_probes_in_objfile (objfile, "libc", "longjmp");
3310
3311           if (!ret.empty ())
3312             {
3313               /* We are only interested in checking one element.  */
3314               probe *p = ret[0];
3315
3316               if (!can_evaluate_probe_arguments (p))
3317                 {
3318                   /* We cannot use the probe interface here, because it does
3319                      not know how to evaluate arguments.  */
3320                   ret.clear ();
3321                 }
3322             }
3323           bp_objfile_data->longjmp_probes = ret;
3324           bp_objfile_data->longjmp_searched = 1;
3325         }
3326
3327       if (!bp_objfile_data->longjmp_probes.empty ())
3328         {
3329           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3330
3331           for (probe *p : bp_objfile_data->longjmp_probes)
3332             {
3333               struct breakpoint *b;
3334
3335               b = create_internal_breakpoint (gdbarch,
3336                                               get_probe_address (p, objfile),
3337                                               bp_longjmp_master,
3338                                               &internal_breakpoint_ops);
3339               b->location = new_probe_location ("-probe-stap libc:longjmp");
3340               b->enable_state = bp_disabled;
3341             }
3342
3343           continue;
3344         }
3345
3346       if (!gdbarch_get_longjmp_target_p (gdbarch))
3347         continue;
3348
3349       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3350         {
3351           struct breakpoint *b;
3352           const char *func_name;
3353           CORE_ADDR addr;
3354           struct explicit_location explicit_loc;
3355
3356           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3357             continue;
3358
3359           func_name = longjmp_names[i];
3360           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3361             {
3362               struct bound_minimal_symbol m;
3363
3364               m = lookup_minimal_symbol_text (func_name, objfile);
3365               if (m.minsym == NULL)
3366                 {
3367                   /* Prevent future lookups in this objfile.  */
3368                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3369                   continue;
3370                 }
3371               bp_objfile_data->longjmp_msym[i] = m;
3372             }
3373
3374           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3375           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3376                                           &internal_breakpoint_ops);
3377           initialize_explicit_location (&explicit_loc);
3378           explicit_loc.function_name = ASTRDUP (func_name);
3379           b->location = new_explicit_location (&explicit_loc);
3380           b->enable_state = bp_disabled;
3381         }
3382     }
3383   }
3384 }
3385
3386 /* Create a master std::terminate breakpoint.  */
3387 static void
3388 create_std_terminate_master_breakpoint (void)
3389 {
3390   struct program_space *pspace;
3391   const char *const func_name = "std::terminate()";
3392
3393   scoped_restore_current_program_space restore_pspace;
3394
3395   ALL_PSPACES (pspace)
3396   {
3397     struct objfile *objfile;
3398     CORE_ADDR addr;
3399
3400     set_current_program_space (pspace);
3401
3402     ALL_OBJFILES (objfile)
3403     {
3404       struct breakpoint *b;
3405       struct breakpoint_objfile_data *bp_objfile_data;
3406       struct explicit_location explicit_loc;
3407
3408       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3409
3410       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3411         continue;
3412
3413       if (bp_objfile_data->terminate_msym.minsym == NULL)
3414         {
3415           struct bound_minimal_symbol m;
3416
3417           m = lookup_minimal_symbol (func_name, NULL, objfile);
3418           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3419                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3420             {
3421               /* Prevent future lookups in this objfile.  */
3422               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3423               continue;
3424             }
3425           bp_objfile_data->terminate_msym = m;
3426         }
3427
3428       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3429       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3430                                       bp_std_terminate_master,
3431                                       &internal_breakpoint_ops);
3432       initialize_explicit_location (&explicit_loc);
3433       explicit_loc.function_name = ASTRDUP (func_name);
3434       b->location = new_explicit_location (&explicit_loc);
3435       b->enable_state = bp_disabled;
3436     }
3437   }
3438 }
3439
3440 /* Install a master breakpoint on the unwinder's debug hook.  */
3441
3442 static void
3443 create_exception_master_breakpoint (void)
3444 {
3445   struct objfile *objfile;
3446   const char *const func_name = "_Unwind_DebugHook";
3447
3448   ALL_OBJFILES (objfile)
3449     {
3450       struct breakpoint *b;
3451       struct gdbarch *gdbarch;
3452       struct breakpoint_objfile_data *bp_objfile_data;
3453       CORE_ADDR addr;
3454       struct explicit_location explicit_loc;
3455
3456       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3457
3458       /* We prefer the SystemTap probe point if it exists.  */
3459       if (!bp_objfile_data->exception_searched)
3460         {
3461           std::vector<probe *> ret
3462             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3463
3464           if (!ret.empty ())
3465             {
3466               /* We are only interested in checking one element.  */
3467               probe *p = ret[0];
3468
3469               if (!can_evaluate_probe_arguments (p))
3470                 {
3471                   /* We cannot use the probe interface here, because it does
3472                      not know how to evaluate arguments.  */
3473                   ret.clear ();
3474                 }
3475             }
3476           bp_objfile_data->exception_probes = ret;
3477           bp_objfile_data->exception_searched = 1;
3478         }
3479
3480       if (!bp_objfile_data->exception_probes.empty ())
3481         {
3482           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3483
3484           for (probe *p : bp_objfile_data->exception_probes)
3485             {
3486               struct breakpoint *b;
3487
3488               b = create_internal_breakpoint (gdbarch,
3489                                               get_probe_address (p, objfile),
3490                                               bp_exception_master,
3491                                               &internal_breakpoint_ops);
3492               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3493               b->enable_state = bp_disabled;
3494             }
3495
3496           continue;
3497         }
3498
3499       /* Otherwise, try the hook function.  */
3500
3501       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3502         continue;
3503
3504       gdbarch = get_objfile_arch (objfile);
3505
3506       if (bp_objfile_data->exception_msym.minsym == NULL)
3507         {
3508           struct bound_minimal_symbol debug_hook;
3509
3510           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3511           if (debug_hook.minsym == NULL)
3512             {
3513               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3514               continue;
3515             }
3516
3517           bp_objfile_data->exception_msym = debug_hook;
3518         }
3519
3520       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3521       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3522                                                  &current_target);
3523       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3524                                       &internal_breakpoint_ops);
3525       initialize_explicit_location (&explicit_loc);
3526       explicit_loc.function_name = ASTRDUP (func_name);
3527       b->location = new_explicit_location (&explicit_loc);
3528       b->enable_state = bp_disabled;
3529     }
3530 }
3531
3532 /* Does B have a location spec?  */
3533
3534 static int
3535 breakpoint_event_location_empty_p (const struct breakpoint *b)
3536 {
3537   return b->location != NULL && event_location_empty_p (b->location.get ());
3538 }
3539
3540 void
3541 update_breakpoints_after_exec (void)
3542 {
3543   struct breakpoint *b, *b_tmp;
3544   struct bp_location *bploc, **bplocp_tmp;
3545
3546   /* We're about to delete breakpoints from GDB's lists.  If the
3547      INSERTED flag is true, GDB will try to lift the breakpoints by
3548      writing the breakpoints' "shadow contents" back into memory.  The
3549      "shadow contents" are NOT valid after an exec, so GDB should not
3550      do that.  Instead, the target is responsible from marking
3551      breakpoints out as soon as it detects an exec.  We don't do that
3552      here instead, because there may be other attempts to delete
3553      breakpoints after detecting an exec and before reaching here.  */
3554   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3555     if (bploc->pspace == current_program_space)
3556       gdb_assert (!bploc->inserted);
3557
3558   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3559   {
3560     if (b->pspace != current_program_space)
3561       continue;
3562
3563     /* Solib breakpoints must be explicitly reset after an exec().  */
3564     if (b->type == bp_shlib_event)
3565       {
3566         delete_breakpoint (b);
3567         continue;
3568       }
3569
3570     /* JIT breakpoints must be explicitly reset after an exec().  */
3571     if (b->type == bp_jit_event)
3572       {
3573         delete_breakpoint (b);
3574         continue;
3575       }
3576
3577     /* Thread event breakpoints must be set anew after an exec(),
3578        as must overlay event and longjmp master breakpoints.  */
3579     if (b->type == bp_thread_event || b->type == bp_overlay_event
3580         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3581         || b->type == bp_exception_master)
3582       {
3583         delete_breakpoint (b);
3584         continue;
3585       }
3586
3587     /* Step-resume breakpoints are meaningless after an exec().  */
3588     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3589       {
3590         delete_breakpoint (b);
3591         continue;
3592       }
3593
3594     /* Just like single-step breakpoints.  */
3595     if (b->type == bp_single_step)
3596       {
3597         delete_breakpoint (b);
3598         continue;
3599       }
3600
3601     /* Longjmp and longjmp-resume breakpoints are also meaningless
3602        after an exec.  */
3603     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3604         || b->type == bp_longjmp_call_dummy
3605         || b->type == bp_exception || b->type == bp_exception_resume)
3606       {
3607         delete_breakpoint (b);
3608         continue;
3609       }
3610
3611     if (b->type == bp_catchpoint)
3612       {
3613         /* For now, none of the bp_catchpoint breakpoints need to
3614            do anything at this point.  In the future, if some of
3615            the catchpoints need to something, we will need to add
3616            a new method, and call this method from here.  */
3617         continue;
3618       }
3619
3620     /* bp_finish is a special case.  The only way we ought to be able
3621        to see one of these when an exec() has happened, is if the user
3622        caught a vfork, and then said "finish".  Ordinarily a finish just
3623        carries them to the call-site of the current callee, by setting
3624        a temporary bp there and resuming.  But in this case, the finish
3625        will carry them entirely through the vfork & exec.
3626
3627        We don't want to allow a bp_finish to remain inserted now.  But
3628        we can't safely delete it, 'cause finish_command has a handle to
3629        the bp on a bpstat, and will later want to delete it.  There's a
3630        chance (and I've seen it happen) that if we delete the bp_finish
3631        here, that its storage will get reused by the time finish_command
3632        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3633        We really must allow finish_command to delete a bp_finish.
3634
3635        In the absence of a general solution for the "how do we know
3636        it's safe to delete something others may have handles to?"
3637        problem, what we'll do here is just uninsert the bp_finish, and
3638        let finish_command delete it.
3639
3640        (We know the bp_finish is "doomed" in the sense that it's
3641        momentary, and will be deleted as soon as finish_command sees
3642        the inferior stopped.  So it doesn't matter that the bp's
3643        address is probably bogus in the new a.out, unlike e.g., the
3644        solib breakpoints.)  */
3645
3646     if (b->type == bp_finish)
3647       {
3648         continue;
3649       }
3650
3651     /* Without a symbolic address, we have little hope of the
3652        pre-exec() address meaning the same thing in the post-exec()
3653        a.out.  */
3654     if (breakpoint_event_location_empty_p (b))
3655       {
3656         delete_breakpoint (b);
3657         continue;
3658       }
3659   }
3660 }
3661
3662 int
3663 detach_breakpoints (ptid_t ptid)
3664 {
3665   struct bp_location *bl, **blp_tmp;
3666   int val = 0;
3667   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3668   struct inferior *inf = current_inferior ();
3669
3670   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3671     error (_("Cannot detach breakpoints of inferior_ptid"));
3672
3673   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3674   inferior_ptid = ptid;
3675   ALL_BP_LOCATIONS (bl, blp_tmp)
3676   {
3677     if (bl->pspace != inf->pspace)
3678       continue;
3679
3680     /* This function must physically remove breakpoints locations
3681        from the specified ptid, without modifying the breakpoint
3682        package's state.  Locations of type bp_loc_other are only
3683        maintained at GDB side.  So, there is no need to remove
3684        these bp_loc_other locations.  Moreover, removing these
3685        would modify the breakpoint package's state.  */
3686     if (bl->loc_type == bp_loc_other)
3687       continue;
3688
3689     if (bl->inserted)
3690       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3691   }
3692
3693   return val;
3694 }
3695
3696 /* Remove the breakpoint location BL from the current address space.
3697    Note that this is used to detach breakpoints from a child fork.
3698    When we get here, the child isn't in the inferior list, and neither
3699    do we have objects to represent its address space --- we should
3700    *not* look at bl->pspace->aspace here.  */
3701
3702 static int
3703 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3704 {
3705   int val;
3706
3707   /* BL is never in moribund_locations by our callers.  */
3708   gdb_assert (bl->owner != NULL);
3709
3710   /* The type of none suggests that owner is actually deleted.
3711      This should not ever happen.  */
3712   gdb_assert (bl->owner->type != bp_none);
3713
3714   if (bl->loc_type == bp_loc_software_breakpoint
3715       || bl->loc_type == bp_loc_hardware_breakpoint)
3716     {
3717       /* "Normal" instruction breakpoint: either the standard
3718          trap-instruction bp (bp_breakpoint), or a
3719          bp_hardware_breakpoint.  */
3720
3721       /* First check to see if we have to handle an overlay.  */
3722       if (overlay_debugging == ovly_off
3723           || bl->section == NULL
3724           || !(section_is_overlay (bl->section)))
3725         {
3726           /* No overlay handling: just remove the breakpoint.  */
3727
3728           /* If we're trying to uninsert a memory breakpoint that we
3729              know is set in a dynamic object that is marked
3730              shlib_disabled, then either the dynamic object was
3731              removed with "remove-symbol-file" or with
3732              "nosharedlibrary".  In the former case, we don't know
3733              whether another dynamic object might have loaded over the
3734              breakpoint's address -- the user might well let us know
3735              about it next with add-symbol-file (the whole point of
3736              add-symbol-file is letting the user manually maintain a
3737              list of dynamically loaded objects).  If we have the
3738              breakpoint's shadow memory, that is, this is a software
3739              breakpoint managed by GDB, check whether the breakpoint
3740              is still inserted in memory, to avoid overwriting wrong
3741              code with stale saved shadow contents.  Note that HW
3742              breakpoints don't have shadow memory, as they're
3743              implemented using a mechanism that is not dependent on
3744              being able to modify the target's memory, and as such
3745              they should always be removed.  */
3746           if (bl->shlib_disabled
3747               && bl->target_info.shadow_len != 0
3748               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3749             val = 0;
3750           else
3751             val = bl->owner->ops->remove_location (bl, reason);
3752         }
3753       else
3754         {
3755           /* This breakpoint is in an overlay section.
3756              Did we set a breakpoint at the LMA?  */
3757           if (!overlay_events_enabled)
3758               {
3759                 /* Yes -- overlay event support is not active, so we
3760                    should have set a breakpoint at the LMA.  Remove it.  
3761                 */
3762                 /* Ignore any failures: if the LMA is in ROM, we will
3763                    have already warned when we failed to insert it.  */
3764                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3765                   target_remove_hw_breakpoint (bl->gdbarch,
3766                                                &bl->overlay_target_info);
3767                 else
3768                   target_remove_breakpoint (bl->gdbarch,
3769                                             &bl->overlay_target_info,
3770                                             reason);
3771               }
3772           /* Did we set a breakpoint at the VMA? 
3773              If so, we will have marked the breakpoint 'inserted'.  */
3774           if (bl->inserted)
3775             {
3776               /* Yes -- remove it.  Previously we did not bother to
3777                  remove the breakpoint if the section had been
3778                  unmapped, but let's not rely on that being safe.  We
3779                  don't know what the overlay manager might do.  */
3780
3781               /* However, we should remove *software* breakpoints only
3782                  if the section is still mapped, or else we overwrite
3783                  wrong code with the saved shadow contents.  */
3784               if (bl->loc_type == bp_loc_hardware_breakpoint
3785                   || section_is_mapped (bl->section))
3786                 val = bl->owner->ops->remove_location (bl, reason);
3787               else
3788                 val = 0;
3789             }
3790           else
3791             {
3792               /* No -- not inserted, so no need to remove.  No error.  */
3793               val = 0;
3794             }
3795         }
3796
3797       /* In some cases, we might not be able to remove a breakpoint in
3798          a shared library that has already been removed, but we have
3799          not yet processed the shlib unload event.  Similarly for an
3800          unloaded add-symbol-file object - the user might not yet have
3801          had the chance to remove-symbol-file it.  shlib_disabled will
3802          be set if the library/object has already been removed, but
3803          the breakpoint hasn't been uninserted yet, e.g., after
3804          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3805          always-inserted mode.  */
3806       if (val
3807           && (bl->loc_type == bp_loc_software_breakpoint
3808               && (bl->shlib_disabled
3809                   || solib_name_from_address (bl->pspace, bl->address)
3810                   || shared_objfile_contains_address_p (bl->pspace,
3811                                                         bl->address))))
3812         val = 0;
3813
3814       if (val)
3815         return val;
3816       bl->inserted = (reason == DETACH_BREAKPOINT);
3817     }
3818   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3819     {
3820       gdb_assert (bl->owner->ops != NULL
3821                   && bl->owner->ops->remove_location != NULL);
3822
3823       bl->inserted = (reason == DETACH_BREAKPOINT);
3824       bl->owner->ops->remove_location (bl, reason);
3825
3826       /* Failure to remove any of the hardware watchpoints comes here.  */
3827       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3828         warning (_("Could not remove hardware watchpoint %d."),
3829                  bl->owner->number);
3830     }
3831   else if (bl->owner->type == bp_catchpoint
3832            && breakpoint_enabled (bl->owner)
3833            && !bl->duplicate)
3834     {
3835       gdb_assert (bl->owner->ops != NULL
3836                   && bl->owner->ops->remove_location != NULL);
3837
3838       val = bl->owner->ops->remove_location (bl, reason);
3839       if (val)
3840         return val;
3841
3842       bl->inserted = (reason == DETACH_BREAKPOINT);
3843     }
3844
3845   return 0;
3846 }
3847
3848 static int
3849 remove_breakpoint (struct bp_location *bl)
3850 {
3851   /* BL is never in moribund_locations by our callers.  */
3852   gdb_assert (bl->owner != NULL);
3853
3854   /* The type of none suggests that owner is actually deleted.
3855      This should not ever happen.  */
3856   gdb_assert (bl->owner->type != bp_none);
3857
3858   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3859
3860   switch_to_program_space_and_thread (bl->pspace);
3861
3862   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3863 }
3864
3865 /* Clear the "inserted" flag in all breakpoints.  */
3866
3867 void
3868 mark_breakpoints_out (void)
3869 {
3870   struct bp_location *bl, **blp_tmp;
3871
3872   ALL_BP_LOCATIONS (bl, blp_tmp)
3873     if (bl->pspace == current_program_space)
3874       bl->inserted = 0;
3875 }
3876
3877 /* Clear the "inserted" flag in all breakpoints and delete any
3878    breakpoints which should go away between runs of the program.
3879
3880    Plus other such housekeeping that has to be done for breakpoints
3881    between runs.
3882
3883    Note: this function gets called at the end of a run (by
3884    generic_mourn_inferior) and when a run begins (by
3885    init_wait_for_inferior).  */
3886
3887
3888
3889 void
3890 breakpoint_init_inferior (enum inf_context context)
3891 {
3892   struct breakpoint *b, *b_tmp;
3893   struct bp_location *bl;
3894   int ix;
3895   struct program_space *pspace = current_program_space;
3896
3897   /* If breakpoint locations are shared across processes, then there's
3898      nothing to do.  */
3899   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3900     return;
3901
3902   mark_breakpoints_out ();
3903
3904   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3905   {
3906     if (b->loc && b->loc->pspace != pspace)
3907       continue;
3908
3909     switch (b->type)
3910       {
3911       case bp_call_dummy:
3912       case bp_longjmp_call_dummy:
3913
3914         /* If the call dummy breakpoint is at the entry point it will
3915            cause problems when the inferior is rerun, so we better get
3916            rid of it.  */
3917
3918       case bp_watchpoint_scope:
3919
3920         /* Also get rid of scope breakpoints.  */
3921
3922       case bp_shlib_event:
3923
3924         /* Also remove solib event breakpoints.  Their addresses may
3925            have changed since the last time we ran the program.
3926            Actually we may now be debugging against different target;
3927            and so the solib backend that installed this breakpoint may
3928            not be used in by the target.  E.g.,
3929
3930            (gdb) file prog-linux
3931            (gdb) run               # native linux target
3932            ...
3933            (gdb) kill
3934            (gdb) file prog-win.exe
3935            (gdb) tar rem :9999     # remote Windows gdbserver.
3936         */
3937
3938       case bp_step_resume:
3939
3940         /* Also remove step-resume breakpoints.  */
3941
3942       case bp_single_step:
3943
3944         /* Also remove single-step breakpoints.  */
3945
3946         delete_breakpoint (b);
3947         break;
3948
3949       case bp_watchpoint:
3950       case bp_hardware_watchpoint:
3951       case bp_read_watchpoint:
3952       case bp_access_watchpoint:
3953         {
3954           struct watchpoint *w = (struct watchpoint *) b;
3955
3956           /* Likewise for watchpoints on local expressions.  */
3957           if (w->exp_valid_block != NULL)
3958             delete_breakpoint (b);
3959           else
3960             {
3961               /* Get rid of existing locations, which are no longer
3962                  valid.  New ones will be created in
3963                  update_watchpoint, when the inferior is restarted.
3964                  The next update_global_location_list call will
3965                  garbage collect them.  */
3966               b->loc = NULL;
3967
3968               if (context == inf_starting)
3969                 {
3970                   /* Reset val field to force reread of starting value in
3971                      insert_breakpoints.  */
3972                   if (w->val)
3973                     value_free (w->val);
3974                   w->val = NULL;
3975                   w->val_valid = 0;
3976                 }
3977             }
3978         }
3979         break;
3980       default:
3981         break;
3982       }
3983   }
3984
3985   /* Get rid of the moribund locations.  */
3986   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3987     decref_bp_location (&bl);
3988   VEC_free (bp_location_p, moribund_locations);
3989 }
3990
3991 /* These functions concern about actual breakpoints inserted in the
3992    target --- to e.g. check if we need to do decr_pc adjustment or if
3993    we need to hop over the bkpt --- so we check for address space
3994    match, not program space.  */
3995
3996 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3997    exists at PC.  It returns ordinary_breakpoint_here if it's an
3998    ordinary breakpoint, or permanent_breakpoint_here if it's a
3999    permanent breakpoint.
4000    - When continuing from a location with an ordinary breakpoint, we
4001      actually single step once before calling insert_breakpoints.
4002    - When continuing from a location with a permanent breakpoint, we
4003      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4004      the target, to advance the PC past the breakpoint.  */
4005
4006 enum breakpoint_here
4007 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4008 {
4009   struct bp_location *bl, **blp_tmp;
4010   int any_breakpoint_here = 0;
4011
4012   ALL_BP_LOCATIONS (bl, blp_tmp)
4013     {
4014       if (bl->loc_type != bp_loc_software_breakpoint
4015           && bl->loc_type != bp_loc_hardware_breakpoint)
4016         continue;
4017
4018       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4019       if ((breakpoint_enabled (bl->owner)
4020            || bl->permanent)
4021           && breakpoint_location_address_match (bl, aspace, pc))
4022         {
4023           if (overlay_debugging 
4024               && section_is_overlay (bl->section)
4025               && !section_is_mapped (bl->section))
4026             continue;           /* unmapped overlay -- can't be a match */
4027           else if (bl->permanent)
4028             return permanent_breakpoint_here;
4029           else
4030             any_breakpoint_here = 1;
4031         }
4032     }
4033
4034   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4035 }
4036
4037 /* See breakpoint.h.  */
4038
4039 int
4040 breakpoint_in_range_p (const address_space *aspace,
4041                        CORE_ADDR addr, ULONGEST len)
4042 {
4043   struct bp_location *bl, **blp_tmp;
4044
4045   ALL_BP_LOCATIONS (bl, blp_tmp)
4046     {
4047       if (bl->loc_type != bp_loc_software_breakpoint
4048           && bl->loc_type != bp_loc_hardware_breakpoint)
4049         continue;
4050
4051       if ((breakpoint_enabled (bl->owner)
4052            || bl->permanent)
4053           && breakpoint_location_address_range_overlap (bl, aspace,
4054                                                         addr, len))
4055         {
4056           if (overlay_debugging
4057               && section_is_overlay (bl->section)
4058               && !section_is_mapped (bl->section))
4059             {
4060               /* Unmapped overlay -- can't be a match.  */
4061               continue;
4062             }
4063
4064           return 1;
4065         }
4066     }
4067
4068   return 0;
4069 }
4070
4071 /* Return true if there's a moribund breakpoint at PC.  */
4072
4073 int
4074 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4075 {
4076   struct bp_location *loc;
4077   int ix;
4078
4079   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4080     if (breakpoint_location_address_match (loc, aspace, pc))
4081       return 1;
4082
4083   return 0;
4084 }
4085
4086 /* Returns non-zero iff BL is inserted at PC, in address space
4087    ASPACE.  */
4088
4089 static int
4090 bp_location_inserted_here_p (struct bp_location *bl,
4091                              const address_space *aspace, CORE_ADDR pc)
4092 {
4093   if (bl->inserted
4094       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4095                                    aspace, pc))
4096     {
4097       if (overlay_debugging
4098           && section_is_overlay (bl->section)
4099           && !section_is_mapped (bl->section))
4100         return 0;               /* unmapped overlay -- can't be a match */
4101       else
4102         return 1;
4103     }
4104   return 0;
4105 }
4106
4107 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4108
4109 int
4110 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4111 {
4112   struct bp_location **blp, **blp_tmp = NULL;
4113
4114   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4115     {
4116       struct bp_location *bl = *blp;
4117
4118       if (bl->loc_type != bp_loc_software_breakpoint
4119           && bl->loc_type != bp_loc_hardware_breakpoint)
4120         continue;
4121
4122       if (bp_location_inserted_here_p (bl, aspace, pc))
4123         return 1;
4124     }
4125   return 0;
4126 }
4127
4128 /* This function returns non-zero iff there is a software breakpoint
4129    inserted at PC.  */
4130
4131 int
4132 software_breakpoint_inserted_here_p (const address_space *aspace,
4133                                      CORE_ADDR pc)
4134 {
4135   struct bp_location **blp, **blp_tmp = NULL;
4136
4137   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4138     {
4139       struct bp_location *bl = *blp;
4140
4141       if (bl->loc_type != bp_loc_software_breakpoint)
4142         continue;
4143
4144       if (bp_location_inserted_here_p (bl, aspace, pc))
4145         return 1;
4146     }
4147
4148   return 0;
4149 }
4150
4151 /* See breakpoint.h.  */
4152
4153 int
4154 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4155                                      CORE_ADDR pc)
4156 {
4157   struct bp_location **blp, **blp_tmp = NULL;
4158
4159   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4160     {
4161       struct bp_location *bl = *blp;
4162
4163       if (bl->loc_type != bp_loc_hardware_breakpoint)
4164         continue;
4165
4166       if (bp_location_inserted_here_p (bl, aspace, pc))
4167         return 1;
4168     }
4169
4170   return 0;
4171 }
4172
4173 int
4174 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4175                                        CORE_ADDR addr, ULONGEST len)
4176 {
4177   struct breakpoint *bpt;
4178
4179   ALL_BREAKPOINTS (bpt)
4180     {
4181       struct bp_location *loc;
4182
4183       if (bpt->type != bp_hardware_watchpoint
4184           && bpt->type != bp_access_watchpoint)
4185         continue;
4186
4187       if (!breakpoint_enabled (bpt))
4188         continue;
4189
4190       for (loc = bpt->loc; loc; loc = loc->next)
4191         if (loc->pspace->aspace == aspace && loc->inserted)
4192           {
4193             CORE_ADDR l, h;
4194
4195             /* Check for intersection.  */
4196             l = std::max<CORE_ADDR> (loc->address, addr);
4197             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4198             if (l < h)
4199               return 1;
4200           }
4201     }
4202   return 0;
4203 }
4204 \f
4205
4206 /* bpstat stuff.  External routines' interfaces are documented
4207    in breakpoint.h.  */
4208
4209 int
4210 is_catchpoint (struct breakpoint *ep)
4211 {
4212   return (ep->type == bp_catchpoint);
4213 }
4214
4215 /* Frees any storage that is part of a bpstat.  Does not walk the
4216    'next' chain.  */
4217
4218 bpstats::~bpstats ()
4219 {
4220   if (old_val != NULL)
4221     value_free (old_val);
4222   if (bp_location_at != NULL)
4223     decref_bp_location (&bp_location_at);
4224 }
4225
4226 /* Clear a bpstat so that it says we are not at any breakpoint.
4227    Also free any storage that is part of a bpstat.  */
4228
4229 void
4230 bpstat_clear (bpstat *bsp)
4231 {
4232   bpstat p;
4233   bpstat q;
4234
4235   if (bsp == 0)
4236     return;
4237   p = *bsp;
4238   while (p != NULL)
4239     {
4240       q = p->next;
4241       delete p;
4242       p = q;
4243     }
4244   *bsp = NULL;
4245 }
4246
4247 bpstats::bpstats (const bpstats &other)
4248   : next (NULL),
4249     bp_location_at (other.bp_location_at),
4250     breakpoint_at (other.breakpoint_at),
4251     commands (other.commands),
4252     old_val (other.old_val),
4253     print (other.print),
4254     stop (other.stop),
4255     print_it (other.print_it)
4256 {
4257   if (old_val != NULL)
4258     {
4259       old_val = value_copy (old_val);
4260       release_value (old_val);
4261     }
4262   incref_bp_location (bp_location_at);
4263 }
4264
4265 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4266    is part of the bpstat is copied as well.  */
4267
4268 bpstat
4269 bpstat_copy (bpstat bs)
4270 {
4271   bpstat p = NULL;
4272   bpstat tmp;
4273   bpstat retval = NULL;
4274
4275   if (bs == NULL)
4276     return bs;
4277
4278   for (; bs != NULL; bs = bs->next)
4279     {
4280       tmp = new bpstats (*bs);
4281
4282       if (p == NULL)
4283         /* This is the first thing in the chain.  */
4284         retval = tmp;
4285       else
4286         p->next = tmp;
4287       p = tmp;
4288     }
4289   p->next = NULL;
4290   return retval;
4291 }
4292
4293 /* Find the bpstat associated with this breakpoint.  */
4294
4295 bpstat
4296 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4297 {
4298   if (bsp == NULL)
4299     return NULL;
4300
4301   for (; bsp != NULL; bsp = bsp->next)
4302     {
4303       if (bsp->breakpoint_at == breakpoint)
4304         return bsp;
4305     }
4306   return NULL;
4307 }
4308
4309 /* See breakpoint.h.  */
4310
4311 int
4312 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4313 {
4314   for (; bsp != NULL; bsp = bsp->next)
4315     {
4316       if (bsp->breakpoint_at == NULL)
4317         {
4318           /* A moribund location can never explain a signal other than
4319              GDB_SIGNAL_TRAP.  */
4320           if (sig == GDB_SIGNAL_TRAP)
4321             return 1;
4322         }
4323       else
4324         {
4325           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4326                                                         sig))
4327             return 1;
4328         }
4329     }
4330
4331   return 0;
4332 }
4333
4334 /* Put in *NUM the breakpoint number of the first breakpoint we are
4335    stopped at.  *BSP upon return is a bpstat which points to the
4336    remaining breakpoints stopped at (but which is not guaranteed to be
4337    good for anything but further calls to bpstat_num).
4338
4339    Return 0 if passed a bpstat which does not indicate any breakpoints.
4340    Return -1 if stopped at a breakpoint that has been deleted since
4341    we set it.
4342    Return 1 otherwise.  */
4343
4344 int
4345 bpstat_num (bpstat *bsp, int *num)
4346 {
4347   struct breakpoint *b;
4348
4349   if ((*bsp) == NULL)
4350     return 0;                   /* No more breakpoint values */
4351
4352   /* We assume we'll never have several bpstats that correspond to a
4353      single breakpoint -- otherwise, this function might return the
4354      same number more than once and this will look ugly.  */
4355   b = (*bsp)->breakpoint_at;
4356   *bsp = (*bsp)->next;
4357   if (b == NULL)
4358     return -1;                  /* breakpoint that's been deleted since */
4359
4360   *num = b->number;             /* We have its number */
4361   return 1;
4362 }
4363
4364 /* See breakpoint.h.  */
4365
4366 void
4367 bpstat_clear_actions (void)
4368 {
4369   struct thread_info *tp;
4370   bpstat bs;
4371
4372   if (ptid_equal (inferior_ptid, null_ptid))
4373     return;
4374
4375   tp = find_thread_ptid (inferior_ptid);
4376   if (tp == NULL)
4377     return;
4378
4379   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4380     {
4381       bs->commands = NULL;
4382
4383       if (bs->old_val != NULL)
4384         {
4385           value_free (bs->old_val);
4386           bs->old_val = NULL;
4387         }
4388     }
4389 }
4390
4391 /* Called when a command is about to proceed the inferior.  */
4392
4393 static void
4394 breakpoint_about_to_proceed (void)
4395 {
4396   if (!ptid_equal (inferior_ptid, null_ptid))
4397     {
4398       struct thread_info *tp = inferior_thread ();
4399
4400       /* Allow inferior function calls in breakpoint commands to not
4401          interrupt the command list.  When the call finishes
4402          successfully, the inferior will be standing at the same
4403          breakpoint as if nothing happened.  */
4404       if (tp->control.in_infcall)
4405         return;
4406     }
4407
4408   breakpoint_proceeded = 1;
4409 }
4410
4411 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4412    or its equivalent.  */
4413
4414 static int
4415 command_line_is_silent (struct command_line *cmd)
4416 {
4417   return cmd && (strcmp ("silent", cmd->line) == 0);
4418 }
4419
4420 /* Execute all the commands associated with all the breakpoints at
4421    this location.  Any of these commands could cause the process to
4422    proceed beyond this point, etc.  We look out for such changes by
4423    checking the global "breakpoint_proceeded" after each command.
4424
4425    Returns true if a breakpoint command resumed the inferior.  In that
4426    case, it is the caller's responsibility to recall it again with the
4427    bpstat of the current thread.  */
4428
4429 static int
4430 bpstat_do_actions_1 (bpstat *bsp)
4431 {
4432   bpstat bs;
4433   int again = 0;
4434
4435   /* Avoid endless recursion if a `source' command is contained
4436      in bs->commands.  */
4437   if (executing_breakpoint_commands)
4438     return 0;
4439
4440   scoped_restore save_executing
4441     = make_scoped_restore (&executing_breakpoint_commands, 1);
4442
4443   scoped_restore preventer = prevent_dont_repeat ();
4444
4445   /* This pointer will iterate over the list of bpstat's.  */
4446   bs = *bsp;
4447
4448   breakpoint_proceeded = 0;
4449   for (; bs != NULL; bs = bs->next)
4450     {
4451       struct command_line *cmd = NULL;
4452
4453       /* Take ownership of the BSP's command tree, if it has one.
4454
4455          The command tree could legitimately contain commands like
4456          'step' and 'next', which call clear_proceed_status, which
4457          frees stop_bpstat's command tree.  To make sure this doesn't
4458          free the tree we're executing out from under us, we need to
4459          take ownership of the tree ourselves.  Since a given bpstat's
4460          commands are only executed once, we don't need to copy it; we
4461          can clear the pointer in the bpstat, and make sure we free
4462          the tree when we're done.  */
4463       counted_command_line ccmd = bs->commands;
4464       bs->commands = NULL;
4465       if (ccmd != NULL)
4466         cmd = ccmd.get ();
4467       if (command_line_is_silent (cmd))
4468         {
4469           /* The action has been already done by bpstat_stop_status.  */
4470           cmd = cmd->next;
4471         }
4472
4473       while (cmd != NULL)
4474         {
4475           execute_control_command (cmd);
4476
4477           if (breakpoint_proceeded)
4478             break;
4479           else
4480             cmd = cmd->next;
4481         }
4482
4483       if (breakpoint_proceeded)
4484         {
4485           if (current_ui->async)
4486             /* If we are in async mode, then the target might be still
4487                running, not stopped at any breakpoint, so nothing for
4488                us to do here -- just return to the event loop.  */
4489             ;
4490           else
4491             /* In sync mode, when execute_control_command returns
4492                we're already standing on the next breakpoint.
4493                Breakpoint commands for that stop were not run, since
4494                execute_command does not run breakpoint commands --
4495                only command_line_handler does, but that one is not
4496                involved in execution of breakpoint commands.  So, we
4497                can now execute breakpoint commands.  It should be
4498                noted that making execute_command do bpstat actions is
4499                not an option -- in this case we'll have recursive
4500                invocation of bpstat for each breakpoint with a
4501                command, and can easily blow up GDB stack.  Instead, we
4502                return true, which will trigger the caller to recall us
4503                with the new stop_bpstat.  */
4504             again = 1;
4505           break;
4506         }
4507     }
4508   return again;
4509 }
4510
4511 void
4512 bpstat_do_actions (void)
4513 {
4514   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4515
4516   /* Do any commands attached to breakpoint we are stopped at.  */
4517   while (!ptid_equal (inferior_ptid, null_ptid)
4518          && target_has_execution
4519          && !is_exited (inferior_ptid)
4520          && !is_executing (inferior_ptid))
4521     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4522        and only return when it is stopped at the next breakpoint, we
4523        keep doing breakpoint actions until it returns false to
4524        indicate the inferior was not resumed.  */
4525     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4526       break;
4527
4528   discard_cleanups (cleanup_if_error);
4529 }
4530
4531 /* Print out the (old or new) value associated with a watchpoint.  */
4532
4533 static void
4534 watchpoint_value_print (struct value *val, struct ui_file *stream)
4535 {
4536   if (val == NULL)
4537     fprintf_unfiltered (stream, _("<unreadable>"));
4538   else
4539     {
4540       struct value_print_options opts;
4541       get_user_print_options (&opts);
4542       value_print (val, stream, &opts);
4543     }
4544 }
4545
4546 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4547    debugging multiple threads.  */
4548
4549 void
4550 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4551 {
4552   if (uiout->is_mi_like_p ())
4553     return;
4554
4555   uiout->text ("\n");
4556
4557   if (show_thread_that_caused_stop ())
4558     {
4559       const char *name;
4560       struct thread_info *thr = inferior_thread ();
4561
4562       uiout->text ("Thread ");
4563       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
4564
4565       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4566       if (name != NULL)
4567         {
4568           uiout->text (" \"");
4569           uiout->field_fmt ("name", "%s", name);
4570           uiout->text ("\"");
4571         }
4572
4573       uiout->text (" hit ");
4574     }
4575 }
4576
4577 /* Generic routine for printing messages indicating why we
4578    stopped.  The behavior of this function depends on the value
4579    'print_it' in the bpstat structure.  Under some circumstances we
4580    may decide not to print anything here and delegate the task to
4581    normal_stop().  */
4582
4583 static enum print_stop_action
4584 print_bp_stop_message (bpstat bs)
4585 {
4586   switch (bs->print_it)
4587     {
4588     case print_it_noop:
4589       /* Nothing should be printed for this bpstat entry.  */
4590       return PRINT_UNKNOWN;
4591       break;
4592
4593     case print_it_done:
4594       /* We still want to print the frame, but we already printed the
4595          relevant messages.  */
4596       return PRINT_SRC_AND_LOC;
4597       break;
4598
4599     case print_it_normal:
4600       {
4601         struct breakpoint *b = bs->breakpoint_at;
4602
4603         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4604            which has since been deleted.  */
4605         if (b == NULL)
4606           return PRINT_UNKNOWN;
4607
4608         /* Normal case.  Call the breakpoint's print_it method.  */
4609         return b->ops->print_it (bs);
4610       }
4611       break;
4612
4613     default:
4614       internal_error (__FILE__, __LINE__,
4615                       _("print_bp_stop_message: unrecognized enum value"));
4616       break;
4617     }
4618 }
4619
4620 /* A helper function that prints a shared library stopped event.  */
4621
4622 static void
4623 print_solib_event (int is_catchpoint)
4624 {
4625   int any_deleted
4626     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4627   int any_added
4628     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4629
4630   if (!is_catchpoint)
4631     {
4632       if (any_added || any_deleted)
4633         current_uiout->text (_("Stopped due to shared library event:\n"));
4634       else
4635         current_uiout->text (_("Stopped due to shared library event (no "
4636                                "libraries added or removed)\n"));
4637     }
4638
4639   if (current_uiout->is_mi_like_p ())
4640     current_uiout->field_string ("reason",
4641                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4642
4643   if (any_deleted)
4644     {
4645       char *name;
4646       int ix;
4647
4648       current_uiout->text (_("  Inferior unloaded "));
4649       ui_out_emit_list list_emitter (current_uiout, "removed");
4650       for (ix = 0;
4651            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4652                         ix, name);
4653            ++ix)
4654         {
4655           if (ix > 0)
4656             current_uiout->text ("    ");
4657           current_uiout->field_string ("library", name);
4658           current_uiout->text ("\n");
4659         }
4660     }
4661
4662   if (any_added)
4663     {
4664       struct so_list *iter;
4665       int ix;
4666
4667       current_uiout->text (_("  Inferior loaded "));
4668       ui_out_emit_list list_emitter (current_uiout, "added");
4669       for (ix = 0;
4670            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4671                         ix, iter);
4672            ++ix)
4673         {
4674           if (ix > 0)
4675             current_uiout->text ("    ");
4676           current_uiout->field_string ("library", iter->so_name);
4677           current_uiout->text ("\n");
4678         }
4679     }
4680 }
4681
4682 /* Print a message indicating what happened.  This is called from
4683    normal_stop().  The input to this routine is the head of the bpstat
4684    list - a list of the eventpoints that caused this stop.  KIND is
4685    the target_waitkind for the stopping event.  This
4686    routine calls the generic print routine for printing a message
4687    about reasons for stopping.  This will print (for example) the
4688    "Breakpoint n," part of the output.  The return value of this
4689    routine is one of:
4690
4691    PRINT_UNKNOWN: Means we printed nothing.
4692    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4693    code to print the location.  An example is 
4694    "Breakpoint 1, " which should be followed by
4695    the location.
4696    PRINT_SRC_ONLY: Means we printed something, but there is no need
4697    to also print the location part of the message.
4698    An example is the catch/throw messages, which
4699    don't require a location appended to the end.
4700    PRINT_NOTHING: We have done some printing and we don't need any 
4701    further info to be printed.  */
4702
4703 enum print_stop_action
4704 bpstat_print (bpstat bs, int kind)
4705 {
4706   enum print_stop_action val;
4707
4708   /* Maybe another breakpoint in the chain caused us to stop.
4709      (Currently all watchpoints go on the bpstat whether hit or not.
4710      That probably could (should) be changed, provided care is taken
4711      with respect to bpstat_explains_signal).  */
4712   for (; bs; bs = bs->next)
4713     {
4714       val = print_bp_stop_message (bs);
4715       if (val == PRINT_SRC_ONLY 
4716           || val == PRINT_SRC_AND_LOC 
4717           || val == PRINT_NOTHING)
4718         return val;
4719     }
4720
4721   /* If we had hit a shared library event breakpoint,
4722      print_bp_stop_message would print out this message.  If we hit an
4723      OS-level shared library event, do the same thing.  */
4724   if (kind == TARGET_WAITKIND_LOADED)
4725     {
4726       print_solib_event (0);
4727       return PRINT_NOTHING;
4728     }
4729
4730   /* We reached the end of the chain, or we got a null BS to start
4731      with and nothing was printed.  */
4732   return PRINT_UNKNOWN;
4733 }
4734
4735 /* Evaluate the boolean expression EXP and return the result.  */
4736
4737 static bool
4738 breakpoint_cond_eval (expression *exp)
4739 {
4740   struct value *mark = value_mark ();
4741   bool res = value_true (evaluate_expression (exp));
4742
4743   value_free_to_mark (mark);
4744   return res;
4745 }
4746
4747 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4748
4749 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4750   : next (NULL),
4751     bp_location_at (bl),
4752     breakpoint_at (bl->owner),
4753     commands (NULL),
4754     old_val (NULL),
4755     print (0),
4756     stop (0),
4757     print_it (print_it_normal)
4758 {
4759   incref_bp_location (bl);
4760   **bs_link_pointer = this;
4761   *bs_link_pointer = &next;
4762 }
4763
4764 bpstats::bpstats ()
4765   : next (NULL),
4766     bp_location_at (NULL),
4767     breakpoint_at (NULL),
4768     commands (NULL),
4769     old_val (NULL),
4770     print (0),
4771     stop (0),
4772     print_it (print_it_normal)
4773 {
4774 }
4775 \f
4776 /* The target has stopped with waitstatus WS.  Check if any hardware
4777    watchpoints have triggered, according to the target.  */
4778
4779 int
4780 watchpoints_triggered (struct target_waitstatus *ws)
4781 {
4782   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4783   CORE_ADDR addr;
4784   struct breakpoint *b;
4785
4786   if (!stopped_by_watchpoint)
4787     {
4788       /* We were not stopped by a watchpoint.  Mark all watchpoints
4789          as not triggered.  */
4790       ALL_BREAKPOINTS (b)
4791         if (is_hardware_watchpoint (b))
4792           {
4793             struct watchpoint *w = (struct watchpoint *) b;
4794
4795             w->watchpoint_triggered = watch_triggered_no;
4796           }
4797
4798       return 0;
4799     }
4800
4801   if (!target_stopped_data_address (&current_target, &addr))
4802     {
4803       /* We were stopped by a watchpoint, but we don't know where.
4804          Mark all watchpoints as unknown.  */
4805       ALL_BREAKPOINTS (b)
4806         if (is_hardware_watchpoint (b))
4807           {
4808             struct watchpoint *w = (struct watchpoint *) b;
4809
4810             w->watchpoint_triggered = watch_triggered_unknown;
4811           }
4812
4813       return 1;
4814     }
4815
4816   /* The target could report the data address.  Mark watchpoints
4817      affected by this data address as triggered, and all others as not
4818      triggered.  */
4819
4820   ALL_BREAKPOINTS (b)
4821     if (is_hardware_watchpoint (b))
4822       {
4823         struct watchpoint *w = (struct watchpoint *) b;
4824         struct bp_location *loc;
4825
4826         w->watchpoint_triggered = watch_triggered_no;
4827         for (loc = b->loc; loc; loc = loc->next)
4828           {
4829             if (is_masked_watchpoint (b))
4830               {
4831                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4832                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4833
4834                 if (newaddr == start)
4835                   {
4836                     w->watchpoint_triggered = watch_triggered_yes;
4837                     break;
4838                   }
4839               }
4840             /* Exact match not required.  Within range is sufficient.  */
4841             else if (target_watchpoint_addr_within_range (&current_target,
4842                                                          addr, loc->address,
4843                                                          loc->length))
4844               {
4845                 w->watchpoint_triggered = watch_triggered_yes;
4846                 break;
4847               }
4848           }
4849       }
4850
4851   return 1;
4852 }
4853
4854 /* Possible return values for watchpoint_check.  */
4855 enum wp_check_result
4856   {
4857     /* The watchpoint has been deleted.  */
4858     WP_DELETED = 1,
4859
4860     /* The value has changed.  */
4861     WP_VALUE_CHANGED = 2,
4862
4863     /* The value has not changed.  */
4864     WP_VALUE_NOT_CHANGED = 3,
4865
4866     /* Ignore this watchpoint, no matter if the value changed or not.  */
4867     WP_IGNORE = 4,
4868   };
4869
4870 #define BP_TEMPFLAG 1
4871 #define BP_HARDWAREFLAG 2
4872
4873 /* Evaluate watchpoint condition expression and check if its value
4874    changed.  */
4875
4876 static wp_check_result
4877 watchpoint_check (bpstat bs)
4878 {
4879   struct watchpoint *b;
4880   struct frame_info *fr;
4881   int within_current_scope;
4882
4883   /* BS is built from an existing struct breakpoint.  */
4884   gdb_assert (bs->breakpoint_at != NULL);
4885   b = (struct watchpoint *) bs->breakpoint_at;
4886
4887   /* If this is a local watchpoint, we only want to check if the
4888      watchpoint frame is in scope if the current thread is the thread
4889      that was used to create the watchpoint.  */
4890   if (!watchpoint_in_thread_scope (b))
4891     return WP_IGNORE;
4892
4893   if (b->exp_valid_block == NULL)
4894     within_current_scope = 1;
4895   else
4896     {
4897       struct frame_info *frame = get_current_frame ();
4898       struct gdbarch *frame_arch = get_frame_arch (frame);
4899       CORE_ADDR frame_pc = get_frame_pc (frame);
4900
4901       /* stack_frame_destroyed_p() returns a non-zero value if we're
4902          still in the function but the stack frame has already been
4903          invalidated.  Since we can't rely on the values of local
4904          variables after the stack has been destroyed, we are treating
4905          the watchpoint in that state as `not changed' without further
4906          checking.  Don't mark watchpoints as changed if the current
4907          frame is in an epilogue - even if they are in some other
4908          frame, our view of the stack is likely to be wrong and
4909          frame_find_by_id could error out.  */
4910       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4911         return WP_IGNORE;
4912
4913       fr = frame_find_by_id (b->watchpoint_frame);
4914       within_current_scope = (fr != NULL);
4915
4916       /* If we've gotten confused in the unwinder, we might have
4917          returned a frame that can't describe this variable.  */
4918       if (within_current_scope)
4919         {
4920           struct symbol *function;
4921
4922           function = get_frame_function (fr);
4923           if (function == NULL
4924               || !contained_in (b->exp_valid_block,
4925                                 SYMBOL_BLOCK_VALUE (function)))
4926             within_current_scope = 0;
4927         }
4928
4929       if (within_current_scope)
4930         /* If we end up stopping, the current frame will get selected
4931            in normal_stop.  So this call to select_frame won't affect
4932            the user.  */
4933         select_frame (fr);
4934     }
4935
4936   if (within_current_scope)
4937     {
4938       /* We use value_{,free_to_}mark because it could be a *long*
4939          time before we return to the command level and call
4940          free_all_values.  We can't call free_all_values because we
4941          might be in the middle of evaluating a function call.  */
4942
4943       int pc = 0;
4944       struct value *mark;
4945       struct value *new_val;
4946
4947       if (is_masked_watchpoint (b))
4948         /* Since we don't know the exact trigger address (from
4949            stopped_data_address), just tell the user we've triggered
4950            a mask watchpoint.  */
4951         return WP_VALUE_CHANGED;
4952
4953       mark = value_mark ();
4954       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, 0);
4955
4956       if (b->val_bitsize != 0)
4957         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4958
4959       /* We use value_equal_contents instead of value_equal because
4960          the latter coerces an array to a pointer, thus comparing just
4961          the address of the array instead of its contents.  This is
4962          not what we want.  */
4963       if ((b->val != NULL) != (new_val != NULL)
4964           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4965         {
4966           if (new_val != NULL)
4967             {
4968               release_value (new_val);
4969               value_free_to_mark (mark);
4970             }
4971           bs->old_val = b->val;
4972           b->val = new_val;
4973           b->val_valid = 1;
4974           return WP_VALUE_CHANGED;
4975         }
4976       else
4977         {
4978           /* Nothing changed.  */
4979           value_free_to_mark (mark);
4980           return WP_VALUE_NOT_CHANGED;
4981         }
4982     }
4983   else
4984     {
4985       /* This seems like the only logical thing to do because
4986          if we temporarily ignored the watchpoint, then when
4987          we reenter the block in which it is valid it contains
4988          garbage (in the case of a function, it may have two
4989          garbage values, one before and one after the prologue).
4990          So we can't even detect the first assignment to it and
4991          watch after that (since the garbage may or may not equal
4992          the first value assigned).  */
4993       /* We print all the stop information in
4994          breakpoint_ops->print_it, but in this case, by the time we
4995          call breakpoint_ops->print_it this bp will be deleted
4996          already.  So we have no choice but print the information
4997          here.  */
4998
4999       SWITCH_THRU_ALL_UIS ()
5000         {
5001           struct ui_out *uiout = current_uiout;
5002
5003           if (uiout->is_mi_like_p ())
5004             uiout->field_string
5005               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5006           uiout->text ("\nWatchpoint ");
5007           uiout->field_int ("wpnum", b->number);
5008           uiout->text (" deleted because the program has left the block in\n"
5009                        "which its expression is valid.\n");
5010         }
5011
5012       /* Make sure the watchpoint's commands aren't executed.  */
5013       b->commands = NULL;
5014       watchpoint_del_at_next_stop (b);
5015
5016       return WP_DELETED;
5017     }
5018 }
5019
5020 /* Return true if it looks like target has stopped due to hitting
5021    breakpoint location BL.  This function does not check if we should
5022    stop, only if BL explains the stop.  */
5023
5024 static int
5025 bpstat_check_location (const struct bp_location *bl,
5026                        const address_space *aspace, CORE_ADDR bp_addr,
5027                        const struct target_waitstatus *ws)
5028 {
5029   struct breakpoint *b = bl->owner;
5030
5031   /* BL is from an existing breakpoint.  */
5032   gdb_assert (b != NULL);
5033
5034   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5035 }
5036
5037 /* Determine if the watched values have actually changed, and we
5038    should stop.  If not, set BS->stop to 0.  */
5039
5040 static void
5041 bpstat_check_watchpoint (bpstat bs)
5042 {
5043   const struct bp_location *bl;
5044   struct watchpoint *b;
5045
5046   /* BS is built for existing struct breakpoint.  */
5047   bl = bs->bp_location_at;
5048   gdb_assert (bl != NULL);
5049   b = (struct watchpoint *) bs->breakpoint_at;
5050   gdb_assert (b != NULL);
5051
5052     {
5053       int must_check_value = 0;
5054       
5055       if (b->type == bp_watchpoint)
5056         /* For a software watchpoint, we must always check the
5057            watched value.  */
5058         must_check_value = 1;
5059       else if (b->watchpoint_triggered == watch_triggered_yes)
5060         /* We have a hardware watchpoint (read, write, or access)
5061            and the target earlier reported an address watched by
5062            this watchpoint.  */
5063         must_check_value = 1;
5064       else if (b->watchpoint_triggered == watch_triggered_unknown
5065                && b->type == bp_hardware_watchpoint)
5066         /* We were stopped by a hardware watchpoint, but the target could
5067            not report the data address.  We must check the watchpoint's
5068            value.  Access and read watchpoints are out of luck; without
5069            a data address, we can't figure it out.  */
5070         must_check_value = 1;
5071
5072       if (must_check_value)
5073         {
5074           wp_check_result e;
5075
5076           TRY
5077             {
5078               e = watchpoint_check (bs);
5079             }
5080           CATCH (ex, RETURN_MASK_ALL)
5081             {
5082               exception_fprintf (gdb_stderr, ex,
5083                                  "Error evaluating expression "
5084                                  "for watchpoint %d\n",
5085                                  b->number);
5086
5087               SWITCH_THRU_ALL_UIS ()
5088                 {
5089                   printf_filtered (_("Watchpoint %d deleted.\n"),
5090                                    b->number);
5091                 }
5092               watchpoint_del_at_next_stop (b);
5093               e = WP_DELETED;
5094             }
5095           END_CATCH
5096
5097           switch (e)
5098             {
5099             case WP_DELETED:
5100               /* We've already printed what needs to be printed.  */
5101               bs->print_it = print_it_done;
5102               /* Stop.  */
5103               break;
5104             case WP_IGNORE:
5105               bs->print_it = print_it_noop;
5106               bs->stop = 0;
5107               break;
5108             case WP_VALUE_CHANGED:
5109               if (b->type == bp_read_watchpoint)
5110                 {
5111                   /* There are two cases to consider here:
5112
5113                      1. We're watching the triggered memory for reads.
5114                      In that case, trust the target, and always report
5115                      the watchpoint hit to the user.  Even though
5116                      reads don't cause value changes, the value may
5117                      have changed since the last time it was read, and
5118                      since we're not trapping writes, we will not see
5119                      those, and as such we should ignore our notion of
5120                      old value.
5121
5122                      2. We're watching the triggered memory for both
5123                      reads and writes.  There are two ways this may
5124                      happen:
5125
5126                      2.1. This is a target that can't break on data
5127                      reads only, but can break on accesses (reads or
5128                      writes), such as e.g., x86.  We detect this case
5129                      at the time we try to insert read watchpoints.
5130
5131                      2.2. Otherwise, the target supports read
5132                      watchpoints, but, the user set an access or write
5133                      watchpoint watching the same memory as this read
5134                      watchpoint.
5135
5136                      If we're watching memory writes as well as reads,
5137                      ignore watchpoint hits when we find that the
5138                      value hasn't changed, as reads don't cause
5139                      changes.  This still gives false positives when
5140                      the program writes the same value to memory as
5141                      what there was already in memory (we will confuse
5142                      it for a read), but it's much better than
5143                      nothing.  */
5144
5145                   int other_write_watchpoint = 0;
5146
5147                   if (bl->watchpoint_type == hw_read)
5148                     {
5149                       struct breakpoint *other_b;
5150
5151                       ALL_BREAKPOINTS (other_b)
5152                         if (other_b->type == bp_hardware_watchpoint
5153                             || other_b->type == bp_access_watchpoint)
5154                           {
5155                             struct watchpoint *other_w =
5156                               (struct watchpoint *) other_b;
5157
5158                             if (other_w->watchpoint_triggered
5159                                 == watch_triggered_yes)
5160                               {
5161                                 other_write_watchpoint = 1;
5162                                 break;
5163                               }
5164                           }
5165                     }
5166
5167                   if (other_write_watchpoint
5168                       || bl->watchpoint_type == hw_access)
5169                     {
5170                       /* We're watching the same memory for writes,
5171                          and the value changed since the last time we
5172                          updated it, so this trap must be for a write.
5173                          Ignore it.  */
5174                       bs->print_it = print_it_noop;
5175                       bs->stop = 0;
5176                     }
5177                 }
5178               break;
5179             case WP_VALUE_NOT_CHANGED:
5180               if (b->type == bp_hardware_watchpoint
5181                   || b->type == bp_watchpoint)
5182                 {
5183                   /* Don't stop: write watchpoints shouldn't fire if
5184                      the value hasn't changed.  */
5185                   bs->print_it = print_it_noop;
5186                   bs->stop = 0;
5187                 }
5188               /* Stop.  */
5189               break;
5190             default:
5191               /* Can't happen.  */
5192               break;
5193             }
5194         }
5195       else      /* must_check_value == 0 */
5196         {
5197           /* This is a case where some watchpoint(s) triggered, but
5198              not at the address of this watchpoint, or else no
5199              watchpoint triggered after all.  So don't print
5200              anything for this watchpoint.  */
5201           bs->print_it = print_it_noop;
5202           bs->stop = 0;
5203         }
5204     }
5205 }
5206
5207 /* For breakpoints that are currently marked as telling gdb to stop,
5208    check conditions (condition proper, frame, thread and ignore count)
5209    of breakpoint referred to by BS.  If we should not stop for this
5210    breakpoint, set BS->stop to 0.  */
5211
5212 static void
5213 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5214 {
5215   const struct bp_location *bl;
5216   struct breakpoint *b;
5217   /* Assume stop.  */
5218   bool condition_result = true;
5219   struct expression *cond;
5220
5221   gdb_assert (bs->stop);
5222
5223   /* BS is built for existing struct breakpoint.  */
5224   bl = bs->bp_location_at;
5225   gdb_assert (bl != NULL);
5226   b = bs->breakpoint_at;
5227   gdb_assert (b != NULL);
5228
5229   /* Even if the target evaluated the condition on its end and notified GDB, we
5230      need to do so again since GDB does not know if we stopped due to a
5231      breakpoint or a single step breakpoint.  */
5232
5233   if (frame_id_p (b->frame_id)
5234       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5235     {
5236       bs->stop = 0;
5237       return;
5238     }
5239
5240   /* If this is a thread/task-specific breakpoint, don't waste cpu
5241      evaluating the condition if this isn't the specified
5242      thread/task.  */
5243   if ((b->thread != -1 && b->thread != ptid_to_global_thread_id (ptid))
5244       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5245
5246     {
5247       bs->stop = 0;
5248       return;
5249     }
5250
5251   /* Evaluate extension language breakpoints that have a "stop" method
5252      implemented.  */
5253   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5254
5255   if (is_watchpoint (b))
5256     {
5257       struct watchpoint *w = (struct watchpoint *) b;
5258
5259       cond = w->cond_exp.get ();
5260     }
5261   else
5262     cond = bl->cond.get ();
5263
5264   if (cond && b->disposition != disp_del_at_next_stop)
5265     {
5266       int within_current_scope = 1;
5267       struct watchpoint * w;
5268
5269       /* We use value_mark and value_free_to_mark because it could
5270          be a long time before we return to the command level and
5271          call free_all_values.  We can't call free_all_values
5272          because we might be in the middle of evaluating a
5273          function call.  */
5274       struct value *mark = value_mark ();
5275
5276       if (is_watchpoint (b))
5277         w = (struct watchpoint *) b;
5278       else
5279         w = NULL;
5280
5281       /* Need to select the frame, with all that implies so that
5282          the conditions will have the right context.  Because we
5283          use the frame, we will not see an inlined function's
5284          variables when we arrive at a breakpoint at the start
5285          of the inlined function; the current frame will be the
5286          call site.  */
5287       if (w == NULL || w->cond_exp_valid_block == NULL)
5288         select_frame (get_current_frame ());
5289       else
5290         {
5291           struct frame_info *frame;
5292
5293           /* For local watchpoint expressions, which particular
5294              instance of a local is being watched matters, so we
5295              keep track of the frame to evaluate the expression
5296              in.  To evaluate the condition however, it doesn't
5297              really matter which instantiation of the function
5298              where the condition makes sense triggers the
5299              watchpoint.  This allows an expression like "watch
5300              global if q > 10" set in `func', catch writes to
5301              global on all threads that call `func', or catch
5302              writes on all recursive calls of `func' by a single
5303              thread.  We simply always evaluate the condition in
5304              the innermost frame that's executing where it makes
5305              sense to evaluate the condition.  It seems
5306              intuitive.  */
5307           frame = block_innermost_frame (w->cond_exp_valid_block);
5308           if (frame != NULL)
5309             select_frame (frame);
5310           else
5311             within_current_scope = 0;
5312         }
5313       if (within_current_scope)
5314         {
5315           TRY
5316             {
5317               condition_result = breakpoint_cond_eval (cond);
5318             }
5319           CATCH (ex, RETURN_MASK_ALL)
5320             {
5321               exception_fprintf (gdb_stderr, ex,
5322                                  "Error in testing breakpoint condition:\n");
5323             }
5324           END_CATCH
5325         }
5326       else
5327         {
5328           warning (_("Watchpoint condition cannot be tested "
5329                      "in the current scope"));
5330           /* If we failed to set the right context for this
5331              watchpoint, unconditionally report it.  */
5332         }
5333       /* FIXME-someday, should give breakpoint #.  */
5334       value_free_to_mark (mark);
5335     }
5336
5337   if (cond && !condition_result)
5338     {
5339       bs->stop = 0;
5340     }
5341   else if (b->ignore_count > 0)
5342     {
5343       b->ignore_count--;
5344       bs->stop = 0;
5345       /* Increase the hit count even though we don't stop.  */
5346       ++(b->hit_count);
5347       observer_notify_breakpoint_modified (b);
5348     }   
5349 }
5350
5351 /* Returns true if we need to track moribund locations of LOC's type
5352    on the current target.  */
5353
5354 static int
5355 need_moribund_for_location_type (struct bp_location *loc)
5356 {
5357   return ((loc->loc_type == bp_loc_software_breakpoint
5358            && !target_supports_stopped_by_sw_breakpoint ())
5359           || (loc->loc_type == bp_loc_hardware_breakpoint
5360               && !target_supports_stopped_by_hw_breakpoint ()));
5361 }
5362
5363
5364 /* Get a bpstat associated with having just stopped at address
5365    BP_ADDR in thread PTID.
5366
5367    Determine whether we stopped at a breakpoint, etc, or whether we
5368    don't understand this stop.  Result is a chain of bpstat's such
5369    that:
5370
5371    if we don't understand the stop, the result is a null pointer.
5372
5373    if we understand why we stopped, the result is not null.
5374
5375    Each element of the chain refers to a particular breakpoint or
5376    watchpoint at which we have stopped.  (We may have stopped for
5377    several reasons concurrently.)
5378
5379    Each element of the chain has valid next, breakpoint_at,
5380    commands, FIXME??? fields.  */
5381
5382 bpstat
5383 bpstat_stop_status (const address_space *aspace,
5384                     CORE_ADDR bp_addr, ptid_t ptid,
5385                     const struct target_waitstatus *ws)
5386 {
5387   struct breakpoint *b = NULL;
5388   struct bp_location *bl;
5389   struct bp_location *loc;
5390   /* First item of allocated bpstat's.  */
5391   bpstat bs_head = NULL, *bs_link = &bs_head;
5392   /* Pointer to the last thing in the chain currently.  */
5393   bpstat bs;
5394   int ix;
5395   int need_remove_insert;
5396   int removed_any;
5397
5398   /* First, build the bpstat chain with locations that explain a
5399      target stop, while being careful to not set the target running,
5400      as that may invalidate locations (in particular watchpoint
5401      locations are recreated).  Resuming will happen here with
5402      breakpoint conditions or watchpoint expressions that include
5403      inferior function calls.  */
5404
5405   ALL_BREAKPOINTS (b)
5406     {
5407       if (!breakpoint_enabled (b))
5408         continue;
5409
5410       for (bl = b->loc; bl != NULL; bl = bl->next)
5411         {
5412           /* For hardware watchpoints, we look only at the first
5413              location.  The watchpoint_check function will work on the
5414              entire expression, not the individual locations.  For
5415              read watchpoints, the watchpoints_triggered function has
5416              checked all locations already.  */
5417           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5418             break;
5419
5420           if (!bl->enabled || bl->shlib_disabled)
5421             continue;
5422
5423           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5424             continue;
5425
5426           /* Come here if it's a watchpoint, or if the break address
5427              matches.  */
5428
5429           bs = new bpstats (bl, &bs_link);      /* Alloc a bpstat to
5430                                                    explain stop.  */
5431
5432           /* Assume we stop.  Should we find a watchpoint that is not
5433              actually triggered, or if the condition of the breakpoint
5434              evaluates as false, we'll reset 'stop' to 0.  */
5435           bs->stop = 1;
5436           bs->print = 1;
5437
5438           /* If this is a scope breakpoint, mark the associated
5439              watchpoint as triggered so that we will handle the
5440              out-of-scope event.  We'll get to the watchpoint next
5441              iteration.  */
5442           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5443             {
5444               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5445
5446               w->watchpoint_triggered = watch_triggered_yes;
5447             }
5448         }
5449     }
5450
5451   /* Check if a moribund breakpoint explains the stop.  */
5452   if (!target_supports_stopped_by_sw_breakpoint ()
5453       || !target_supports_stopped_by_hw_breakpoint ())
5454     {
5455       for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5456         {
5457           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5458               && need_moribund_for_location_type (loc))
5459             {
5460               bs = new bpstats (loc, &bs_link);
5461               /* For hits of moribund locations, we should just proceed.  */
5462               bs->stop = 0;
5463               bs->print = 0;
5464               bs->print_it = print_it_noop;
5465             }
5466         }
5467     }
5468
5469   /* A bit of special processing for shlib breakpoints.  We need to
5470      process solib loading here, so that the lists of loaded and
5471      unloaded libraries are correct before we handle "catch load" and
5472      "catch unload".  */
5473   for (bs = bs_head; bs != NULL; bs = bs->next)
5474     {
5475       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5476         {
5477           handle_solib_event ();
5478           break;
5479         }
5480     }
5481
5482   /* Now go through the locations that caused the target to stop, and
5483      check whether we're interested in reporting this stop to higher
5484      layers, or whether we should resume the target transparently.  */
5485
5486   removed_any = 0;
5487
5488   for (bs = bs_head; bs != NULL; bs = bs->next)
5489     {
5490       if (!bs->stop)
5491         continue;
5492
5493       b = bs->breakpoint_at;
5494       b->ops->check_status (bs);
5495       if (bs->stop)
5496         {
5497           bpstat_check_breakpoint_conditions (bs, ptid);
5498
5499           if (bs->stop)
5500             {
5501               ++(b->hit_count);
5502               observer_notify_breakpoint_modified (b);
5503
5504               /* We will stop here.  */
5505               if (b->disposition == disp_disable)
5506                 {
5507                   --(b->enable_count);
5508                   if (b->enable_count <= 0)
5509                     b->enable_state = bp_disabled;
5510                   removed_any = 1;
5511                 }
5512               if (b->silent)
5513                 bs->print = 0;
5514               bs->commands = b->commands;
5515               if (command_line_is_silent (bs->commands
5516                                           ? bs->commands.get () : NULL))
5517                 bs->print = 0;
5518
5519               b->ops->after_condition_true (bs);
5520             }
5521
5522         }
5523
5524       /* Print nothing for this entry if we don't stop or don't
5525          print.  */
5526       if (!bs->stop || !bs->print)
5527         bs->print_it = print_it_noop;
5528     }
5529
5530   /* If we aren't stopping, the value of some hardware watchpoint may
5531      not have changed, but the intermediate memory locations we are
5532      watching may have.  Don't bother if we're stopping; this will get
5533      done later.  */
5534   need_remove_insert = 0;
5535   if (! bpstat_causes_stop (bs_head))
5536     for (bs = bs_head; bs != NULL; bs = bs->next)
5537       if (!bs->stop
5538           && bs->breakpoint_at
5539           && is_hardware_watchpoint (bs->breakpoint_at))
5540         {
5541           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5542
5543           update_watchpoint (w, 0 /* don't reparse.  */);
5544           need_remove_insert = 1;
5545         }
5546
5547   if (need_remove_insert)
5548     update_global_location_list (UGLL_MAY_INSERT);
5549   else if (removed_any)
5550     update_global_location_list (UGLL_DONT_INSERT);
5551
5552   return bs_head;
5553 }
5554
5555 static void
5556 handle_jit_event (void)
5557 {
5558   struct frame_info *frame;
5559   struct gdbarch *gdbarch;
5560
5561   if (debug_infrun)
5562     fprintf_unfiltered (gdb_stdlog, "handling bp_jit_event\n");
5563
5564   /* Switch terminal for any messages produced by
5565      breakpoint_re_set.  */
5566   target_terminal::ours_for_output ();
5567
5568   frame = get_current_frame ();
5569   gdbarch = get_frame_arch (frame);
5570
5571   jit_event_handler (gdbarch);
5572
5573   target_terminal::inferior ();
5574 }
5575
5576 /* Prepare WHAT final decision for infrun.  */
5577
5578 /* Decide what infrun needs to do with this bpstat.  */
5579
5580 struct bpstat_what
5581 bpstat_what (bpstat bs_head)
5582 {
5583   struct bpstat_what retval;
5584   bpstat bs;
5585
5586   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5587   retval.call_dummy = STOP_NONE;
5588   retval.is_longjmp = 0;
5589
5590   for (bs = bs_head; bs != NULL; bs = bs->next)
5591     {
5592       /* Extract this BS's action.  After processing each BS, we check
5593          if its action overrides all we've seem so far.  */
5594       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5595       enum bptype bptype;
5596
5597       if (bs->breakpoint_at == NULL)
5598         {
5599           /* I suspect this can happen if it was a momentary
5600              breakpoint which has since been deleted.  */
5601           bptype = bp_none;
5602         }
5603       else
5604         bptype = bs->breakpoint_at->type;
5605
5606       switch (bptype)
5607         {
5608         case bp_none:
5609           break;
5610         case bp_breakpoint:
5611         case bp_hardware_breakpoint:
5612         case bp_single_step:
5613         case bp_until:
5614         case bp_finish:
5615         case bp_shlib_event:
5616           if (bs->stop)
5617             {
5618               if (bs->print)
5619                 this_action = BPSTAT_WHAT_STOP_NOISY;
5620               else
5621                 this_action = BPSTAT_WHAT_STOP_SILENT;
5622             }
5623           else
5624             this_action = BPSTAT_WHAT_SINGLE;
5625           break;
5626         case bp_watchpoint:
5627         case bp_hardware_watchpoint:
5628         case bp_read_watchpoint:
5629         case bp_access_watchpoint:
5630           if (bs->stop)
5631             {
5632               if (bs->print)
5633                 this_action = BPSTAT_WHAT_STOP_NOISY;
5634               else
5635                 this_action = BPSTAT_WHAT_STOP_SILENT;
5636             }
5637           else
5638             {
5639               /* There was a watchpoint, but we're not stopping.
5640                  This requires no further action.  */
5641             }
5642           break;
5643         case bp_longjmp:
5644         case bp_longjmp_call_dummy:
5645         case bp_exception:
5646           if (bs->stop)
5647             {
5648               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5649               retval.is_longjmp = bptype != bp_exception;
5650             }
5651           else
5652             this_action = BPSTAT_WHAT_SINGLE;
5653           break;
5654         case bp_longjmp_resume:
5655         case bp_exception_resume:
5656           if (bs->stop)
5657             {
5658               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5659               retval.is_longjmp = bptype == bp_longjmp_resume;
5660             }
5661           else
5662             this_action = BPSTAT_WHAT_SINGLE;
5663           break;
5664         case bp_step_resume:
5665           if (bs->stop)
5666             this_action = BPSTAT_WHAT_STEP_RESUME;
5667           else
5668             {
5669               /* It is for the wrong frame.  */
5670               this_action = BPSTAT_WHAT_SINGLE;
5671             }
5672           break;
5673         case bp_hp_step_resume:
5674           if (bs->stop)
5675             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5676           else
5677             {
5678               /* It is for the wrong frame.  */
5679               this_action = BPSTAT_WHAT_SINGLE;
5680             }
5681           break;
5682         case bp_watchpoint_scope:
5683         case bp_thread_event:
5684         case bp_overlay_event:
5685         case bp_longjmp_master:
5686         case bp_std_terminate_master:
5687         case bp_exception_master:
5688           this_action = BPSTAT_WHAT_SINGLE;
5689           break;
5690         case bp_catchpoint:
5691           if (bs->stop)
5692             {
5693               if (bs->print)
5694                 this_action = BPSTAT_WHAT_STOP_NOISY;
5695               else
5696                 this_action = BPSTAT_WHAT_STOP_SILENT;
5697             }
5698           else
5699             {
5700               /* There was a catchpoint, but we're not stopping.
5701                  This requires no further action.  */
5702             }
5703           break;
5704         case bp_jit_event:
5705           this_action = BPSTAT_WHAT_SINGLE;
5706           break;
5707         case bp_call_dummy:
5708           /* Make sure the action is stop (silent or noisy),
5709              so infrun.c pops the dummy frame.  */
5710           retval.call_dummy = STOP_STACK_DUMMY;
5711           this_action = BPSTAT_WHAT_STOP_SILENT;
5712           break;
5713         case bp_std_terminate:
5714           /* Make sure the action is stop (silent or noisy),
5715              so infrun.c pops the dummy frame.  */
5716           retval.call_dummy = STOP_STD_TERMINATE;
5717           this_action = BPSTAT_WHAT_STOP_SILENT;
5718           break;
5719         case bp_tracepoint:
5720         case bp_fast_tracepoint:
5721         case bp_static_tracepoint:
5722           /* Tracepoint hits should not be reported back to GDB, and
5723              if one got through somehow, it should have been filtered
5724              out already.  */
5725           internal_error (__FILE__, __LINE__,
5726                           _("bpstat_what: tracepoint encountered"));
5727           break;
5728         case bp_gnu_ifunc_resolver:
5729           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5730           this_action = BPSTAT_WHAT_SINGLE;
5731           break;
5732         case bp_gnu_ifunc_resolver_return:
5733           /* The breakpoint will be removed, execution will restart from the
5734              PC of the former breakpoint.  */
5735           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5736           break;
5737
5738         case bp_dprintf:
5739           if (bs->stop)
5740             this_action = BPSTAT_WHAT_STOP_SILENT;
5741           else
5742             this_action = BPSTAT_WHAT_SINGLE;
5743           break;
5744
5745         default:
5746           internal_error (__FILE__, __LINE__,
5747                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5748         }
5749
5750       retval.main_action = std::max (retval.main_action, this_action);
5751     }
5752
5753   return retval;
5754 }
5755
5756 void
5757 bpstat_run_callbacks (bpstat bs_head)
5758 {
5759   bpstat bs;
5760
5761   for (bs = bs_head; bs != NULL; bs = bs->next)
5762     {
5763       struct breakpoint *b = bs->breakpoint_at;
5764
5765       if (b == NULL)
5766         continue;
5767       switch (b->type)
5768         {
5769         case bp_jit_event:
5770           handle_jit_event ();
5771           break;
5772         case bp_gnu_ifunc_resolver:
5773           gnu_ifunc_resolver_stop (b);
5774           break;
5775         case bp_gnu_ifunc_resolver_return:
5776           gnu_ifunc_resolver_return_stop (b);
5777           break;
5778         }
5779     }
5780 }
5781
5782 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5783    without hardware support).  This isn't related to a specific bpstat,
5784    just to things like whether watchpoints are set.  */
5785
5786 int
5787 bpstat_should_step (void)
5788 {
5789   struct breakpoint *b;
5790
5791   ALL_BREAKPOINTS (b)
5792     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5793       return 1;
5794   return 0;
5795 }
5796
5797 int
5798 bpstat_causes_stop (bpstat bs)
5799 {
5800   for (; bs != NULL; bs = bs->next)
5801     if (bs->stop)
5802       return 1;
5803
5804   return 0;
5805 }
5806
5807 \f
5808
5809 /* Compute a string of spaces suitable to indent the next line
5810    so it starts at the position corresponding to the table column
5811    named COL_NAME in the currently active table of UIOUT.  */
5812
5813 static char *
5814 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5815 {
5816   static char wrap_indent[80];
5817   int i, total_width, width, align;
5818   const char *text;
5819
5820   total_width = 0;
5821   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5822     {
5823       if (strcmp (text, col_name) == 0)
5824         {
5825           gdb_assert (total_width < sizeof wrap_indent);
5826           memset (wrap_indent, ' ', total_width);
5827           wrap_indent[total_width] = 0;
5828
5829           return wrap_indent;
5830         }
5831
5832       total_width += width + 1;
5833     }
5834
5835   return NULL;
5836 }
5837
5838 /* Determine if the locations of this breakpoint will have their conditions
5839    evaluated by the target, host or a mix of both.  Returns the following:
5840
5841     "host": Host evals condition.
5842     "host or target": Host or Target evals condition.
5843     "target": Target evals condition.
5844 */
5845
5846 static const char *
5847 bp_condition_evaluator (struct breakpoint *b)
5848 {
5849   struct bp_location *bl;
5850   char host_evals = 0;
5851   char target_evals = 0;
5852
5853   if (!b)
5854     return NULL;
5855
5856   if (!is_breakpoint (b))
5857     return NULL;
5858
5859   if (gdb_evaluates_breakpoint_condition_p ()
5860       || !target_supports_evaluation_of_breakpoint_conditions ())
5861     return condition_evaluation_host;
5862
5863   for (bl = b->loc; bl; bl = bl->next)
5864     {
5865       if (bl->cond_bytecode)
5866         target_evals++;
5867       else
5868         host_evals++;
5869     }
5870
5871   if (host_evals && target_evals)
5872     return condition_evaluation_both;
5873   else if (target_evals)
5874     return condition_evaluation_target;
5875   else
5876     return condition_evaluation_host;
5877 }
5878
5879 /* Determine the breakpoint location's condition evaluator.  This is
5880    similar to bp_condition_evaluator, but for locations.  */
5881
5882 static const char *
5883 bp_location_condition_evaluator (struct bp_location *bl)
5884 {
5885   if (bl && !is_breakpoint (bl->owner))
5886     return NULL;
5887
5888   if (gdb_evaluates_breakpoint_condition_p ()
5889       || !target_supports_evaluation_of_breakpoint_conditions ())
5890     return condition_evaluation_host;
5891
5892   if (bl && bl->cond_bytecode)
5893     return condition_evaluation_target;
5894   else
5895     return condition_evaluation_host;
5896 }
5897
5898 /* Print the LOC location out of the list of B->LOC locations.  */
5899
5900 static void
5901 print_breakpoint_location (struct breakpoint *b,
5902                            struct bp_location *loc)
5903 {
5904   struct ui_out *uiout = current_uiout;
5905
5906   scoped_restore_current_program_space restore_pspace;
5907
5908   if (loc != NULL && loc->shlib_disabled)
5909     loc = NULL;
5910
5911   if (loc != NULL)
5912     set_current_program_space (loc->pspace);
5913
5914   if (b->display_canonical)
5915     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5916   else if (loc && loc->symtab)
5917     {
5918       const struct symbol *sym = loc->symbol;
5919
5920       if (sym == NULL)
5921         sym = find_pc_sect_function (loc->address, loc->section);
5922
5923       if (sym)
5924         {
5925           uiout->text ("in ");
5926           uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
5927           uiout->text (" ");
5928           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5929           uiout->text ("at ");
5930         }
5931       uiout->field_string ("file",
5932                            symtab_to_filename_for_display (loc->symtab));
5933       uiout->text (":");
5934
5935       if (uiout->is_mi_like_p ())
5936         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5937       
5938       uiout->field_int ("line", loc->line_number);
5939     }
5940   else if (loc)
5941     {
5942       string_file stb;
5943
5944       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5945                               demangle, "");
5946       uiout->field_stream ("at", stb);
5947     }
5948   else
5949     {
5950       uiout->field_string ("pending",
5951                            event_location_to_string (b->location.get ()));
5952       /* If extra_string is available, it could be holding a condition
5953          or dprintf arguments.  In either case, make sure it is printed,
5954          too, but only for non-MI streams.  */
5955       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5956         {
5957           if (b->type == bp_dprintf)
5958             uiout->text (",");
5959           else
5960             uiout->text (" ");
5961           uiout->text (b->extra_string);
5962         }
5963     }
5964
5965   if (loc && is_breakpoint (b)
5966       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5967       && bp_condition_evaluator (b) == condition_evaluation_both)
5968     {
5969       uiout->text (" (");
5970       uiout->field_string ("evaluated-by",
5971                            bp_location_condition_evaluator (loc));
5972       uiout->text (")");
5973     }
5974 }
5975
5976 static const char *
5977 bptype_string (enum bptype type)
5978 {
5979   struct ep_type_description
5980     {
5981       enum bptype type;
5982       const char *description;
5983     };
5984   static struct ep_type_description bptypes[] =
5985   {
5986     {bp_none, "?deleted?"},
5987     {bp_breakpoint, "breakpoint"},
5988     {bp_hardware_breakpoint, "hw breakpoint"},
5989     {bp_single_step, "sw single-step"},
5990     {bp_until, "until"},
5991     {bp_finish, "finish"},
5992     {bp_watchpoint, "watchpoint"},
5993     {bp_hardware_watchpoint, "hw watchpoint"},
5994     {bp_read_watchpoint, "read watchpoint"},
5995     {bp_access_watchpoint, "acc watchpoint"},
5996     {bp_longjmp, "longjmp"},
5997     {bp_longjmp_resume, "longjmp resume"},
5998     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5999     {bp_exception, "exception"},
6000     {bp_exception_resume, "exception resume"},
6001     {bp_step_resume, "step resume"},
6002     {bp_hp_step_resume, "high-priority step resume"},
6003     {bp_watchpoint_scope, "watchpoint scope"},
6004     {bp_call_dummy, "call dummy"},
6005     {bp_std_terminate, "std::terminate"},
6006     {bp_shlib_event, "shlib events"},
6007     {bp_thread_event, "thread events"},
6008     {bp_overlay_event, "overlay events"},
6009     {bp_longjmp_master, "longjmp master"},
6010     {bp_std_terminate_master, "std::terminate master"},
6011     {bp_exception_master, "exception master"},
6012     {bp_catchpoint, "catchpoint"},
6013     {bp_tracepoint, "tracepoint"},
6014     {bp_fast_tracepoint, "fast tracepoint"},
6015     {bp_static_tracepoint, "static tracepoint"},
6016     {bp_dprintf, "dprintf"},
6017     {bp_jit_event, "jit events"},
6018     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6019     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6020   };
6021
6022   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6023       || ((int) type != bptypes[(int) type].type))
6024     internal_error (__FILE__, __LINE__,
6025                     _("bptypes table does not describe type #%d."),
6026                     (int) type);
6027
6028   return bptypes[(int) type].description;
6029 }
6030
6031 /* For MI, output a field named 'thread-groups' with a list as the value.
6032    For CLI, prefix the list with the string 'inf'. */
6033
6034 static void
6035 output_thread_groups (struct ui_out *uiout,
6036                       const char *field_name,
6037                       VEC(int) *inf_num,
6038                       int mi_only)
6039 {
6040   int is_mi = uiout->is_mi_like_p ();
6041   int inf;
6042   int i;
6043
6044   /* For backward compatibility, don't display inferiors in CLI unless
6045      there are several.  Always display them for MI. */
6046   if (!is_mi && mi_only)
6047     return;
6048
6049   ui_out_emit_list list_emitter (uiout, field_name);
6050
6051   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6052     {
6053       if (is_mi)
6054         {
6055           char mi_group[10];
6056
6057           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6058           uiout->field_string (NULL, mi_group);
6059         }
6060       else
6061         {
6062           if (i == 0)
6063             uiout->text (" inf ");
6064           else
6065             uiout->text (", ");
6066         
6067           uiout->text (plongest (inf));
6068         }
6069     }
6070 }
6071
6072 /* Print B to gdb_stdout.  */
6073
6074 static void
6075 print_one_breakpoint_location (struct breakpoint *b,
6076                                struct bp_location *loc,
6077                                int loc_number,
6078                                struct bp_location **last_loc,
6079                                int allflag)
6080 {
6081   struct command_line *l;
6082   static char bpenables[] = "nynny";
6083
6084   struct ui_out *uiout = current_uiout;
6085   int header_of_multiple = 0;
6086   int part_of_multiple = (loc != NULL);
6087   struct value_print_options opts;
6088
6089   get_user_print_options (&opts);
6090
6091   gdb_assert (!loc || loc_number != 0);
6092   /* See comment in print_one_breakpoint concerning treatment of
6093      breakpoints with single disabled location.  */
6094   if (loc == NULL 
6095       && (b->loc != NULL 
6096           && (b->loc->next != NULL || !b->loc->enabled)))
6097     header_of_multiple = 1;
6098   if (loc == NULL)
6099     loc = b->loc;
6100
6101   annotate_record ();
6102
6103   /* 1 */
6104   annotate_field (0);
6105   if (part_of_multiple)
6106     {
6107       char *formatted;
6108       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6109       uiout->field_string ("number", formatted);
6110       xfree (formatted);
6111     }
6112   else
6113     {
6114       uiout->field_int ("number", b->number);
6115     }
6116
6117   /* 2 */
6118   annotate_field (1);
6119   if (part_of_multiple)
6120     uiout->field_skip ("type");
6121   else
6122     uiout->field_string ("type", bptype_string (b->type));
6123
6124   /* 3 */
6125   annotate_field (2);
6126   if (part_of_multiple)
6127     uiout->field_skip ("disp");
6128   else
6129     uiout->field_string ("disp", bpdisp_text (b->disposition));
6130
6131
6132   /* 4 */
6133   annotate_field (3);
6134   if (part_of_multiple)
6135     uiout->field_string ("enabled", loc->enabled ? "y" : "n");
6136   else
6137     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6138   uiout->spaces (2);
6139
6140   
6141   /* 5 and 6 */
6142   if (b->ops != NULL && b->ops->print_one != NULL)
6143     {
6144       /* Although the print_one can possibly print all locations,
6145          calling it here is not likely to get any nice result.  So,
6146          make sure there's just one location.  */
6147       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6148       b->ops->print_one (b, last_loc);
6149     }
6150   else
6151     switch (b->type)
6152       {
6153       case bp_none:
6154         internal_error (__FILE__, __LINE__,
6155                         _("print_one_breakpoint: bp_none encountered\n"));
6156         break;
6157
6158       case bp_watchpoint:
6159       case bp_hardware_watchpoint:
6160       case bp_read_watchpoint:
6161       case bp_access_watchpoint:
6162         {
6163           struct watchpoint *w = (struct watchpoint *) b;
6164
6165           /* Field 4, the address, is omitted (which makes the columns
6166              not line up too nicely with the headers, but the effect
6167              is relatively readable).  */
6168           if (opts.addressprint)
6169             uiout->field_skip ("addr");
6170           annotate_field (5);
6171           uiout->field_string ("what", w->exp_string);
6172         }
6173         break;
6174
6175       case bp_breakpoint:
6176       case bp_hardware_breakpoint:
6177       case bp_single_step:
6178       case bp_until:
6179       case bp_finish:
6180       case bp_longjmp:
6181       case bp_longjmp_resume:
6182       case bp_longjmp_call_dummy:
6183       case bp_exception:
6184       case bp_exception_resume:
6185       case bp_step_resume:
6186       case bp_hp_step_resume:
6187       case bp_watchpoint_scope:
6188       case bp_call_dummy:
6189       case bp_std_terminate:
6190       case bp_shlib_event:
6191       case bp_thread_event:
6192       case bp_overlay_event:
6193       case bp_longjmp_master:
6194       case bp_std_terminate_master:
6195       case bp_exception_master:
6196       case bp_tracepoint:
6197       case bp_fast_tracepoint:
6198       case bp_static_tracepoint:
6199       case bp_dprintf:
6200       case bp_jit_event:
6201       case bp_gnu_ifunc_resolver:
6202       case bp_gnu_ifunc_resolver_return:
6203         if (opts.addressprint)
6204           {
6205             annotate_field (4);
6206             if (header_of_multiple)
6207               uiout->field_string ("addr", "<MULTIPLE>");
6208             else if (b->loc == NULL || loc->shlib_disabled)
6209               uiout->field_string ("addr", "<PENDING>");
6210             else
6211               uiout->field_core_addr ("addr",
6212                                       loc->gdbarch, loc->address);
6213           }
6214         annotate_field (5);
6215         if (!header_of_multiple)
6216           print_breakpoint_location (b, loc);
6217         if (b->loc)
6218           *last_loc = b->loc;
6219         break;
6220       }
6221
6222
6223   if (loc != NULL && !header_of_multiple)
6224     {
6225       struct inferior *inf;
6226       VEC(int) *inf_num = NULL;
6227       int mi_only = 1;
6228
6229       ALL_INFERIORS (inf)
6230         {
6231           if (inf->pspace == loc->pspace)
6232             VEC_safe_push (int, inf_num, inf->num);
6233         }
6234
6235         /* For backward compatibility, don't display inferiors in CLI unless
6236            there are several.  Always display for MI. */
6237         if (allflag
6238             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6239                 && (number_of_program_spaces () > 1
6240                     || number_of_inferiors () > 1)
6241                 /* LOC is for existing B, it cannot be in
6242                    moribund_locations and thus having NULL OWNER.  */
6243                 && loc->owner->type != bp_catchpoint))
6244         mi_only = 0;
6245       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6246       VEC_free (int, inf_num);
6247     }
6248
6249   if (!part_of_multiple)
6250     {
6251       if (b->thread != -1)
6252         {
6253           /* FIXME: This seems to be redundant and lost here; see the
6254              "stop only in" line a little further down.  */
6255           uiout->text (" thread ");
6256           uiout->field_int ("thread", b->thread);
6257         }
6258       else if (b->task != 0)
6259         {
6260           uiout->text (" task ");
6261           uiout->field_int ("task", b->task);
6262         }
6263     }
6264
6265   uiout->text ("\n");
6266
6267   if (!part_of_multiple)
6268     b->ops->print_one_detail (b, uiout);
6269
6270   if (part_of_multiple && frame_id_p (b->frame_id))
6271     {
6272       annotate_field (6);
6273       uiout->text ("\tstop only in stack frame at ");
6274       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6275          the frame ID.  */
6276       uiout->field_core_addr ("frame",
6277                               b->gdbarch, b->frame_id.stack_addr);
6278       uiout->text ("\n");
6279     }
6280   
6281   if (!part_of_multiple && b->cond_string)
6282     {
6283       annotate_field (7);
6284       if (is_tracepoint (b))
6285         uiout->text ("\ttrace only if ");
6286       else
6287         uiout->text ("\tstop only if ");
6288       uiout->field_string ("cond", b->cond_string);
6289
6290       /* Print whether the target is doing the breakpoint's condition
6291          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6292       if (is_breakpoint (b)
6293           && breakpoint_condition_evaluation_mode ()
6294           == condition_evaluation_target)
6295         {
6296           uiout->text (" (");
6297           uiout->field_string ("evaluated-by",
6298                                bp_condition_evaluator (b));
6299           uiout->text (" evals)");
6300         }
6301       uiout->text ("\n");
6302     }
6303
6304   if (!part_of_multiple && b->thread != -1)
6305     {
6306       /* FIXME should make an annotation for this.  */
6307       uiout->text ("\tstop only in thread ");
6308       if (uiout->is_mi_like_p ())
6309         uiout->field_int ("thread", b->thread);
6310       else
6311         {
6312           struct thread_info *thr = find_thread_global_id (b->thread);
6313
6314           uiout->field_string ("thread", print_thread_id (thr));
6315         }
6316       uiout->text ("\n");
6317     }
6318   
6319   if (!part_of_multiple)
6320     {
6321       if (b->hit_count)
6322         {
6323           /* FIXME should make an annotation for this.  */
6324           if (is_catchpoint (b))
6325             uiout->text ("\tcatchpoint");
6326           else if (is_tracepoint (b))
6327             uiout->text ("\ttracepoint");
6328           else
6329             uiout->text ("\tbreakpoint");
6330           uiout->text (" already hit ");
6331           uiout->field_int ("times", b->hit_count);
6332           if (b->hit_count == 1)
6333             uiout->text (" time\n");
6334           else
6335             uiout->text (" times\n");
6336         }
6337       else
6338         {
6339           /* Output the count also if it is zero, but only if this is mi.  */
6340           if (uiout->is_mi_like_p ())
6341             uiout->field_int ("times", b->hit_count);
6342         }
6343     }
6344
6345   if (!part_of_multiple && b->ignore_count)
6346     {
6347       annotate_field (8);
6348       uiout->text ("\tignore next ");
6349       uiout->field_int ("ignore", b->ignore_count);
6350       uiout->text (" hits\n");
6351     }
6352
6353   /* Note that an enable count of 1 corresponds to "enable once"
6354      behavior, which is reported by the combination of enablement and
6355      disposition, so we don't need to mention it here.  */
6356   if (!part_of_multiple && b->enable_count > 1)
6357     {
6358       annotate_field (8);
6359       uiout->text ("\tdisable after ");
6360       /* Tweak the wording to clarify that ignore and enable counts
6361          are distinct, and have additive effect.  */
6362       if (b->ignore_count)
6363         uiout->text ("additional ");
6364       else
6365         uiout->text ("next ");
6366       uiout->field_int ("enable", b->enable_count);
6367       uiout->text (" hits\n");
6368     }
6369
6370   if (!part_of_multiple && is_tracepoint (b))
6371     {
6372       struct tracepoint *tp = (struct tracepoint *) b;
6373
6374       if (tp->traceframe_usage)
6375         {
6376           uiout->text ("\ttrace buffer usage ");
6377           uiout->field_int ("traceframe-usage", tp->traceframe_usage);
6378           uiout->text (" bytes\n");
6379         }
6380     }
6381
6382   l = b->commands ? b->commands.get () : NULL;
6383   if (!part_of_multiple && l)
6384     {
6385       annotate_field (9);
6386       ui_out_emit_tuple tuple_emitter (uiout, "script");
6387       print_command_lines (uiout, l, 4);
6388     }
6389
6390   if (is_tracepoint (b))
6391     {
6392       struct tracepoint *t = (struct tracepoint *) b;
6393
6394       if (!part_of_multiple && t->pass_count)
6395         {
6396           annotate_field (10);
6397           uiout->text ("\tpass count ");
6398           uiout->field_int ("pass", t->pass_count);
6399           uiout->text (" \n");
6400         }
6401
6402       /* Don't display it when tracepoint or tracepoint location is
6403          pending.   */
6404       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6405         {
6406           annotate_field (11);
6407
6408           if (uiout->is_mi_like_p ())
6409             uiout->field_string ("installed",
6410                                  loc->inserted ? "y" : "n");
6411           else
6412             {
6413               if (loc->inserted)
6414                 uiout->text ("\t");
6415               else
6416                 uiout->text ("\tnot ");
6417               uiout->text ("installed on target\n");
6418             }
6419         }
6420     }
6421
6422   if (uiout->is_mi_like_p () && !part_of_multiple)
6423     {
6424       if (is_watchpoint (b))
6425         {
6426           struct watchpoint *w = (struct watchpoint *) b;
6427
6428           uiout->field_string ("original-location", w->exp_string);
6429         }
6430       else if (b->location != NULL
6431                && event_location_to_string (b->location.get ()) != NULL)
6432         uiout->field_string ("original-location",
6433                              event_location_to_string (b->location.get ()));
6434     }
6435 }
6436
6437 static void
6438 print_one_breakpoint (struct breakpoint *b,
6439                       struct bp_location **last_loc, 
6440                       int allflag)
6441 {
6442   struct ui_out *uiout = current_uiout;
6443
6444   {
6445     ui_out_emit_tuple tuple_emitter (uiout, "bkpt");
6446
6447     print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6448   }
6449
6450   /* If this breakpoint has custom print function,
6451      it's already printed.  Otherwise, print individual
6452      locations, if any.  */
6453   if (b->ops == NULL || b->ops->print_one == NULL)
6454     {
6455       /* If breakpoint has a single location that is disabled, we
6456          print it as if it had several locations, since otherwise it's
6457          hard to represent "breakpoint enabled, location disabled"
6458          situation.
6459
6460          Note that while hardware watchpoints have several locations
6461          internally, that's not a property exposed to user.  */
6462       if (b->loc 
6463           && !is_hardware_watchpoint (b)
6464           && (b->loc->next || !b->loc->enabled))
6465         {
6466           struct bp_location *loc;
6467           int n = 1;
6468
6469           for (loc = b->loc; loc; loc = loc->next, ++n)
6470             {
6471               ui_out_emit_tuple tuple_emitter (uiout, NULL);
6472               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6473             }
6474         }
6475     }
6476 }
6477
6478 static int
6479 breakpoint_address_bits (struct breakpoint *b)
6480 {
6481   int print_address_bits = 0;
6482   struct bp_location *loc;
6483
6484   /* Software watchpoints that aren't watching memory don't have an
6485      address to print.  */
6486   if (is_no_memory_software_watchpoint (b))
6487     return 0;
6488
6489   for (loc = b->loc; loc; loc = loc->next)
6490     {
6491       int addr_bit;
6492
6493       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6494       if (addr_bit > print_address_bits)
6495         print_address_bits = addr_bit;
6496     }
6497
6498   return print_address_bits;
6499 }
6500
6501 /* See breakpoint.h.  */
6502
6503 void
6504 print_breakpoint (breakpoint *b)
6505 {
6506   struct bp_location *dummy_loc = NULL;
6507   print_one_breakpoint (b, &dummy_loc, 0);
6508 }
6509
6510 /* Return true if this breakpoint was set by the user, false if it is
6511    internal or momentary.  */
6512
6513 int
6514 user_breakpoint_p (struct breakpoint *b)
6515 {
6516   return b->number > 0;
6517 }
6518
6519 /* See breakpoint.h.  */
6520
6521 int
6522 pending_breakpoint_p (struct breakpoint *b)
6523 {
6524   return b->loc == NULL;
6525 }
6526
6527 /* Print information on user settable breakpoint (watchpoint, etc)
6528    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6529    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6530    FILTER is non-NULL, call it on each breakpoint and only include the
6531    ones for which it returns non-zero.  Return the total number of
6532    breakpoints listed.  */
6533
6534 static int
6535 breakpoint_1 (const char *args, int allflag, 
6536               int (*filter) (const struct breakpoint *))
6537 {
6538   struct breakpoint *b;
6539   struct bp_location *last_loc = NULL;
6540   int nr_printable_breakpoints;
6541   struct value_print_options opts;
6542   int print_address_bits = 0;
6543   int print_type_col_width = 14;
6544   struct ui_out *uiout = current_uiout;
6545
6546   get_user_print_options (&opts);
6547
6548   /* Compute the number of rows in the table, as well as the size
6549      required for address fields.  */
6550   nr_printable_breakpoints = 0;
6551   ALL_BREAKPOINTS (b)
6552     {
6553       /* If we have a filter, only list the breakpoints it accepts.  */
6554       if (filter && !filter (b))
6555         continue;
6556
6557       /* If we have an "args" string, it is a list of breakpoints to 
6558          accept.  Skip the others.  */
6559       if (args != NULL && *args != '\0')
6560         {
6561           if (allflag && parse_and_eval_long (args) != b->number)
6562             continue;
6563           if (!allflag && !number_is_in_list (args, b->number))
6564             continue;
6565         }
6566
6567       if (allflag || user_breakpoint_p (b))
6568         {
6569           int addr_bit, type_len;
6570
6571           addr_bit = breakpoint_address_bits (b);
6572           if (addr_bit > print_address_bits)
6573             print_address_bits = addr_bit;
6574
6575           type_len = strlen (bptype_string (b->type));
6576           if (type_len > print_type_col_width)
6577             print_type_col_width = type_len;
6578
6579           nr_printable_breakpoints++;
6580         }
6581     }
6582
6583   {
6584     ui_out_emit_table table_emitter (uiout,
6585                                      opts.addressprint ? 6 : 5,
6586                                      nr_printable_breakpoints,
6587                                      "BreakpointTable");
6588
6589     if (nr_printable_breakpoints > 0)
6590       annotate_breakpoints_headers ();
6591     if (nr_printable_breakpoints > 0)
6592       annotate_field (0);
6593     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6594     if (nr_printable_breakpoints > 0)
6595       annotate_field (1);
6596     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6597     if (nr_printable_breakpoints > 0)
6598       annotate_field (2);
6599     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6600     if (nr_printable_breakpoints > 0)
6601       annotate_field (3);
6602     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6603     if (opts.addressprint)
6604       {
6605         if (nr_printable_breakpoints > 0)
6606           annotate_field (4);
6607         if (print_address_bits <= 32)
6608           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6609         else
6610           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6611       }
6612     if (nr_printable_breakpoints > 0)
6613       annotate_field (5);
6614     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6615     uiout->table_body ();
6616     if (nr_printable_breakpoints > 0)
6617       annotate_breakpoints_table ();
6618
6619     ALL_BREAKPOINTS (b)
6620       {
6621         QUIT;
6622         /* If we have a filter, only list the breakpoints it accepts.  */
6623         if (filter && !filter (b))
6624           continue;
6625
6626         /* If we have an "args" string, it is a list of breakpoints to 
6627            accept.  Skip the others.  */
6628
6629         if (args != NULL && *args != '\0')
6630           {
6631             if (allflag)        /* maintenance info breakpoint */
6632               {
6633                 if (parse_and_eval_long (args) != b->number)
6634                   continue;
6635               }
6636             else                /* all others */
6637               {
6638                 if (!number_is_in_list (args, b->number))
6639                   continue;
6640               }
6641           }
6642         /* We only print out user settable breakpoints unless the
6643            allflag is set.  */
6644         if (allflag || user_breakpoint_p (b))
6645           print_one_breakpoint (b, &last_loc, allflag);
6646       }
6647   }
6648
6649   if (nr_printable_breakpoints == 0)
6650     {
6651       /* If there's a filter, let the caller decide how to report
6652          empty list.  */
6653       if (!filter)
6654         {
6655           if (args == NULL || *args == '\0')
6656             uiout->message ("No breakpoints or watchpoints.\n");
6657           else
6658             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6659                             args);
6660         }
6661     }
6662   else
6663     {
6664       if (last_loc && !server_command)
6665         set_next_address (last_loc->gdbarch, last_loc->address);
6666     }
6667
6668   /* FIXME?  Should this be moved up so that it is only called when
6669      there have been breakpoints? */
6670   annotate_breakpoints_table_end ();
6671
6672   return nr_printable_breakpoints;
6673 }
6674
6675 /* Display the value of default-collect in a way that is generally
6676    compatible with the breakpoint list.  */
6677
6678 static void
6679 default_collect_info (void)
6680 {
6681   struct ui_out *uiout = current_uiout;
6682
6683   /* If it has no value (which is frequently the case), say nothing; a
6684      message like "No default-collect." gets in user's face when it's
6685      not wanted.  */
6686   if (!*default_collect)
6687     return;
6688
6689   /* The following phrase lines up nicely with per-tracepoint collect
6690      actions.  */
6691   uiout->text ("default collect ");
6692   uiout->field_string ("default-collect", default_collect);
6693   uiout->text (" \n");
6694 }
6695   
6696 static void
6697 info_breakpoints_command (const char *args, int from_tty)
6698 {
6699   breakpoint_1 (args, 0, NULL);
6700
6701   default_collect_info ();
6702 }
6703
6704 static void
6705 info_watchpoints_command (const char *args, int from_tty)
6706 {
6707   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6708   struct ui_out *uiout = current_uiout;
6709
6710   if (num_printed == 0)
6711     {
6712       if (args == NULL || *args == '\0')
6713         uiout->message ("No watchpoints.\n");
6714       else
6715         uiout->message ("No watchpoint matching '%s'.\n", args);
6716     }
6717 }
6718
6719 static void
6720 maintenance_info_breakpoints (const char *args, int from_tty)
6721 {
6722   breakpoint_1 (args, 1, NULL);
6723
6724   default_collect_info ();
6725 }
6726
6727 static int
6728 breakpoint_has_pc (struct breakpoint *b,
6729                    struct program_space *pspace,
6730                    CORE_ADDR pc, struct obj_section *section)
6731 {
6732   struct bp_location *bl = b->loc;
6733
6734   for (; bl; bl = bl->next)
6735     {
6736       if (bl->pspace == pspace
6737           && bl->address == pc
6738           && (!overlay_debugging || bl->section == section))
6739         return 1;         
6740     }
6741   return 0;
6742 }
6743
6744 /* Print a message describing any user-breakpoints set at PC.  This
6745    concerns with logical breakpoints, so we match program spaces, not
6746    address spaces.  */
6747
6748 static void
6749 describe_other_breakpoints (struct gdbarch *gdbarch,
6750                             struct program_space *pspace, CORE_ADDR pc,
6751                             struct obj_section *section, int thread)
6752 {
6753   int others = 0;
6754   struct breakpoint *b;
6755
6756   ALL_BREAKPOINTS (b)
6757     others += (user_breakpoint_p (b)
6758                && breakpoint_has_pc (b, pspace, pc, section));
6759   if (others > 0)
6760     {
6761       if (others == 1)
6762         printf_filtered (_("Note: breakpoint "));
6763       else /* if (others == ???) */
6764         printf_filtered (_("Note: breakpoints "));
6765       ALL_BREAKPOINTS (b)
6766         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6767           {
6768             others--;
6769             printf_filtered ("%d", b->number);
6770             if (b->thread == -1 && thread != -1)
6771               printf_filtered (" (all threads)");
6772             else if (b->thread != -1)
6773               printf_filtered (" (thread %d)", b->thread);
6774             printf_filtered ("%s%s ",
6775                              ((b->enable_state == bp_disabled
6776                                || b->enable_state == bp_call_disabled)
6777                               ? " (disabled)"
6778                               : ""),
6779                              (others > 1) ? "," 
6780                              : ((others == 1) ? " and" : ""));
6781           }
6782       printf_filtered (_("also set at pc "));
6783       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6784       printf_filtered (".\n");
6785     }
6786 }
6787 \f
6788
6789 /* Return true iff it is meaningful to use the address member of
6790    BPT locations.  For some breakpoint types, the locations' address members
6791    are irrelevant and it makes no sense to attempt to compare them to other
6792    addresses (or use them for any other purpose either).
6793
6794    More specifically, each of the following breakpoint types will
6795    always have a zero valued location address and we don't want to mark
6796    breakpoints of any of these types to be a duplicate of an actual
6797    breakpoint location at address zero:
6798
6799       bp_watchpoint
6800       bp_catchpoint
6801
6802 */
6803
6804 static int
6805 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6806 {
6807   enum bptype type = bpt->type;
6808
6809   return (type != bp_watchpoint && type != bp_catchpoint);
6810 }
6811
6812 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6813    true if LOC1 and LOC2 represent the same watchpoint location.  */
6814
6815 static int
6816 watchpoint_locations_match (struct bp_location *loc1, 
6817                             struct bp_location *loc2)
6818 {
6819   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6820   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6821
6822   /* Both of them must exist.  */
6823   gdb_assert (w1 != NULL);
6824   gdb_assert (w2 != NULL);
6825
6826   /* If the target can evaluate the condition expression in hardware,
6827      then we we need to insert both watchpoints even if they are at
6828      the same place.  Otherwise the watchpoint will only trigger when
6829      the condition of whichever watchpoint was inserted evaluates to
6830      true, not giving a chance for GDB to check the condition of the
6831      other watchpoint.  */
6832   if ((w1->cond_exp
6833        && target_can_accel_watchpoint_condition (loc1->address, 
6834                                                  loc1->length,
6835                                                  loc1->watchpoint_type,
6836                                                  w1->cond_exp.get ()))
6837       || (w2->cond_exp
6838           && target_can_accel_watchpoint_condition (loc2->address, 
6839                                                     loc2->length,
6840                                                     loc2->watchpoint_type,
6841                                                     w2->cond_exp.get ())))
6842     return 0;
6843
6844   /* Note that this checks the owner's type, not the location's.  In
6845      case the target does not support read watchpoints, but does
6846      support access watchpoints, we'll have bp_read_watchpoint
6847      watchpoints with hw_access locations.  Those should be considered
6848      duplicates of hw_read locations.  The hw_read locations will
6849      become hw_access locations later.  */
6850   return (loc1->owner->type == loc2->owner->type
6851           && loc1->pspace->aspace == loc2->pspace->aspace
6852           && loc1->address == loc2->address
6853           && loc1->length == loc2->length);
6854 }
6855
6856 /* See breakpoint.h.  */
6857
6858 int
6859 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6860                           const address_space *aspace2, CORE_ADDR addr2)
6861 {
6862   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6863            || aspace1 == aspace2)
6864           && addr1 == addr2);
6865 }
6866
6867 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6868    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6869    matches ASPACE2.  On targets that have global breakpoints, the address
6870    space doesn't really matter.  */
6871
6872 static int
6873 breakpoint_address_match_range (const address_space *aspace1,
6874                                 CORE_ADDR addr1,
6875                                 int len1, const address_space *aspace2,
6876                                 CORE_ADDR addr2)
6877 {
6878   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6879            || aspace1 == aspace2)
6880           && addr2 >= addr1 && addr2 < addr1 + len1);
6881 }
6882
6883 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6884    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6885    matches the breakpoint's address space.  On targets that have global
6886    breakpoints, the address space doesn't really matter.  */
6887
6888 static int
6889 breakpoint_location_address_match (struct bp_location *bl,
6890                                    const address_space *aspace,
6891                                    CORE_ADDR addr)
6892 {
6893   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6894                                     aspace, addr)
6895           || (bl->length
6896               && breakpoint_address_match_range (bl->pspace->aspace,
6897                                                  bl->address, bl->length,
6898                                                  aspace, addr)));
6899 }
6900
6901 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6902    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6903    match happens only if ASPACE matches the breakpoint's address
6904    space.  On targets that have global breakpoints, the address space
6905    doesn't really matter.  */
6906
6907 static int
6908 breakpoint_location_address_range_overlap (struct bp_location *bl,
6909                                            const address_space *aspace,
6910                                            CORE_ADDR addr, int len)
6911 {
6912   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6913       || bl->pspace->aspace == aspace)
6914     {
6915       int bl_len = bl->length != 0 ? bl->length : 1;
6916
6917       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6918         return 1;
6919     }
6920   return 0;
6921 }
6922
6923 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6924    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6925    true, otherwise returns false.  */
6926
6927 static int
6928 tracepoint_locations_match (struct bp_location *loc1,
6929                             struct bp_location *loc2)
6930 {
6931   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6932     /* Since tracepoint locations are never duplicated with others', tracepoint
6933        locations at the same address of different tracepoints are regarded as
6934        different locations.  */
6935     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6936   else
6937     return 0;
6938 }
6939
6940 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6941    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6942    represent the same location.  */
6943
6944 static int
6945 breakpoint_locations_match (struct bp_location *loc1, 
6946                             struct bp_location *loc2)
6947 {
6948   int hw_point1, hw_point2;
6949
6950   /* Both of them must not be in moribund_locations.  */
6951   gdb_assert (loc1->owner != NULL);
6952   gdb_assert (loc2->owner != NULL);
6953
6954   hw_point1 = is_hardware_watchpoint (loc1->owner);
6955   hw_point2 = is_hardware_watchpoint (loc2->owner);
6956
6957   if (hw_point1 != hw_point2)
6958     return 0;
6959   else if (hw_point1)
6960     return watchpoint_locations_match (loc1, loc2);
6961   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6962     return tracepoint_locations_match (loc1, loc2);
6963   else
6964     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6965     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6966                                      loc2->pspace->aspace, loc2->address)
6967             && loc1->length == loc2->length);
6968 }
6969
6970 static void
6971 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6972                                int bnum, int have_bnum)
6973 {
6974   /* The longest string possibly returned by hex_string_custom
6975      is 50 chars.  These must be at least that big for safety.  */
6976   char astr1[64];
6977   char astr2[64];
6978
6979   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6980   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6981   if (have_bnum)
6982     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6983              bnum, astr1, astr2);
6984   else
6985     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6986 }
6987
6988 /* Adjust a breakpoint's address to account for architectural
6989    constraints on breakpoint placement.  Return the adjusted address.
6990    Note: Very few targets require this kind of adjustment.  For most
6991    targets, this function is simply the identity function.  */
6992
6993 static CORE_ADDR
6994 adjust_breakpoint_address (struct gdbarch *gdbarch,
6995                            CORE_ADDR bpaddr, enum bptype bptype)
6996 {
6997   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6998     {
6999       /* Very few targets need any kind of breakpoint adjustment.  */
7000       return bpaddr;
7001     }
7002   else if (bptype == bp_watchpoint
7003            || bptype == bp_hardware_watchpoint
7004            || bptype == bp_read_watchpoint
7005            || bptype == bp_access_watchpoint
7006            || bptype == bp_catchpoint)
7007     {
7008       /* Watchpoints and the various bp_catch_* eventpoints should not
7009          have their addresses modified.  */
7010       return bpaddr;
7011     }
7012   else if (bptype == bp_single_step)
7013     {
7014       /* Single-step breakpoints should not have their addresses
7015          modified.  If there's any architectural constrain that
7016          applies to this address, then it should have already been
7017          taken into account when the breakpoint was created in the
7018          first place.  If we didn't do this, stepping through e.g.,
7019          Thumb-2 IT blocks would break.  */
7020       return bpaddr;
7021     }
7022   else
7023     {
7024       CORE_ADDR adjusted_bpaddr;
7025
7026       /* Some targets have architectural constraints on the placement
7027          of breakpoint instructions.  Obtain the adjusted address.  */
7028       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7029
7030       /* An adjusted breakpoint address can significantly alter
7031          a user's expectations.  Print a warning if an adjustment
7032          is required.  */
7033       if (adjusted_bpaddr != bpaddr)
7034         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7035
7036       return adjusted_bpaddr;
7037     }
7038 }
7039
7040 bp_location::bp_location (const bp_location_ops *ops, breakpoint *owner)
7041 {
7042   bp_location *loc = this;
7043
7044   gdb_assert (ops != NULL);
7045
7046   loc->ops = ops;
7047   loc->owner = owner;
7048   loc->cond_bytecode = NULL;
7049   loc->shlib_disabled = 0;
7050   loc->enabled = 1;
7051
7052   switch (owner->type)
7053     {
7054     case bp_breakpoint:
7055     case bp_single_step:
7056     case bp_until:
7057     case bp_finish:
7058     case bp_longjmp:
7059     case bp_longjmp_resume:
7060     case bp_longjmp_call_dummy:
7061     case bp_exception:
7062     case bp_exception_resume:
7063     case bp_step_resume:
7064     case bp_hp_step_resume:
7065     case bp_watchpoint_scope:
7066     case bp_call_dummy:
7067     case bp_std_terminate:
7068     case bp_shlib_event:
7069     case bp_thread_event:
7070     case bp_overlay_event:
7071     case bp_jit_event:
7072     case bp_longjmp_master:
7073     case bp_std_terminate_master:
7074     case bp_exception_master:
7075     case bp_gnu_ifunc_resolver:
7076     case bp_gnu_ifunc_resolver_return:
7077     case bp_dprintf:
7078       loc->loc_type = bp_loc_software_breakpoint;
7079       mark_breakpoint_location_modified (loc);
7080       break;
7081     case bp_hardware_breakpoint:
7082       loc->loc_type = bp_loc_hardware_breakpoint;
7083       mark_breakpoint_location_modified (loc);
7084       break;
7085     case bp_hardware_watchpoint:
7086     case bp_read_watchpoint:
7087     case bp_access_watchpoint:
7088       loc->loc_type = bp_loc_hardware_watchpoint;
7089       break;
7090     case bp_watchpoint:
7091     case bp_catchpoint:
7092     case bp_tracepoint:
7093     case bp_fast_tracepoint:
7094     case bp_static_tracepoint:
7095       loc->loc_type = bp_loc_other;
7096       break;
7097     default:
7098       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7099     }
7100
7101   loc->refc = 1;
7102 }
7103
7104 /* Allocate a struct bp_location.  */
7105
7106 static struct bp_location *
7107 allocate_bp_location (struct breakpoint *bpt)
7108 {
7109   return bpt->ops->allocate_location (bpt);
7110 }
7111
7112 static void
7113 free_bp_location (struct bp_location *loc)
7114 {
7115   loc->ops->dtor (loc);
7116   delete loc;
7117 }
7118
7119 /* Increment reference count.  */
7120
7121 static void
7122 incref_bp_location (struct bp_location *bl)
7123 {
7124   ++bl->refc;
7125 }
7126
7127 /* Decrement reference count.  If the reference count reaches 0,
7128    destroy the bp_location.  Sets *BLP to NULL.  */
7129
7130 static void
7131 decref_bp_location (struct bp_location **blp)
7132 {
7133   gdb_assert ((*blp)->refc > 0);
7134
7135   if (--(*blp)->refc == 0)
7136     free_bp_location (*blp);
7137   *blp = NULL;
7138 }
7139
7140 /* Add breakpoint B at the end of the global breakpoint chain.  */
7141
7142 static breakpoint *
7143 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7144 {
7145   struct breakpoint *b1;
7146   struct breakpoint *result = b.get ();
7147
7148   /* Add this breakpoint to the end of the chain so that a list of
7149      breakpoints will come out in order of increasing numbers.  */
7150
7151   b1 = breakpoint_chain;
7152   if (b1 == 0)
7153     breakpoint_chain = b.release ();
7154   else
7155     {
7156       while (b1->next)
7157         b1 = b1->next;
7158       b1->next = b.release ();
7159     }
7160
7161   return result;
7162 }
7163
7164 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7165
7166 static void
7167 init_raw_breakpoint_without_location (struct breakpoint *b,
7168                                       struct gdbarch *gdbarch,
7169                                       enum bptype bptype,
7170                                       const struct breakpoint_ops *ops)
7171 {
7172   gdb_assert (ops != NULL);
7173
7174   b->ops = ops;
7175   b->type = bptype;
7176   b->gdbarch = gdbarch;
7177   b->language = current_language->la_language;
7178   b->input_radix = input_radix;
7179   b->related_breakpoint = b;
7180 }
7181
7182 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7183    that has type BPTYPE and has no locations as yet.  */
7184
7185 static struct breakpoint *
7186 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7187                                      enum bptype bptype,
7188                                      const struct breakpoint_ops *ops)
7189 {
7190   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7191
7192   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7193   return add_to_breakpoint_chain (std::move (b));
7194 }
7195
7196 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7197    resolutions should be made as the user specified the location explicitly
7198    enough.  */
7199
7200 static void
7201 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7202 {
7203   gdb_assert (loc->owner != NULL);
7204
7205   if (loc->owner->type == bp_breakpoint
7206       || loc->owner->type == bp_hardware_breakpoint
7207       || is_tracepoint (loc->owner))
7208     {
7209       int is_gnu_ifunc;
7210       const char *function_name;
7211       CORE_ADDR func_addr;
7212
7213       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7214                                           &func_addr, NULL, &is_gnu_ifunc);
7215
7216       if (is_gnu_ifunc && !explicit_loc)
7217         {
7218           struct breakpoint *b = loc->owner;
7219
7220           gdb_assert (loc->pspace == current_program_space);
7221           if (gnu_ifunc_resolve_name (function_name,
7222                                       &loc->requested_address))
7223             {
7224               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7225               loc->address = adjust_breakpoint_address (loc->gdbarch,
7226                                                         loc->requested_address,
7227                                                         b->type);
7228             }
7229           else if (b->type == bp_breakpoint && b->loc == loc
7230                    && loc->next == NULL && b->related_breakpoint == b)
7231             {
7232               /* Create only the whole new breakpoint of this type but do not
7233                  mess more complicated breakpoints with multiple locations.  */
7234               b->type = bp_gnu_ifunc_resolver;
7235               /* Remember the resolver's address for use by the return
7236                  breakpoint.  */
7237               loc->related_address = func_addr;
7238             }
7239         }
7240
7241       if (function_name)
7242         loc->function_name = xstrdup (function_name);
7243     }
7244 }
7245
7246 /* Attempt to determine architecture of location identified by SAL.  */
7247 struct gdbarch *
7248 get_sal_arch (struct symtab_and_line sal)
7249 {
7250   if (sal.section)
7251     return get_objfile_arch (sal.section->objfile);
7252   if (sal.symtab)
7253     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7254
7255   return NULL;
7256 }
7257
7258 /* Low level routine for partially initializing a breakpoint of type
7259    BPTYPE.  The newly created breakpoint's address, section, source
7260    file name, and line number are provided by SAL.
7261
7262    It is expected that the caller will complete the initialization of
7263    the newly created breakpoint struct as well as output any status
7264    information regarding the creation of a new breakpoint.  */
7265
7266 static void
7267 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7268                      struct symtab_and_line sal, enum bptype bptype,
7269                      const struct breakpoint_ops *ops)
7270 {
7271   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7272
7273   add_location_to_breakpoint (b, &sal);
7274
7275   if (bptype != bp_catchpoint)
7276     gdb_assert (sal.pspace != NULL);
7277
7278   /* Store the program space that was used to set the breakpoint,
7279      except for ordinary breakpoints, which are independent of the
7280      program space.  */
7281   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7282     b->pspace = sal.pspace;
7283 }
7284
7285 /* set_raw_breakpoint is a low level routine for allocating and
7286    partially initializing a breakpoint of type BPTYPE.  The newly
7287    created breakpoint's address, section, source file name, and line
7288    number are provided by SAL.  The newly created and partially
7289    initialized breakpoint is added to the breakpoint chain and
7290    is also returned as the value of this function.
7291
7292    It is expected that the caller will complete the initialization of
7293    the newly created breakpoint struct as well as output any status
7294    information regarding the creation of a new breakpoint.  In
7295    particular, set_raw_breakpoint does NOT set the breakpoint
7296    number!  Care should be taken to not allow an error to occur
7297    prior to completing the initialization of the breakpoint.  If this
7298    should happen, a bogus breakpoint will be left on the chain.  */
7299
7300 struct breakpoint *
7301 set_raw_breakpoint (struct gdbarch *gdbarch,
7302                     struct symtab_and_line sal, enum bptype bptype,
7303                     const struct breakpoint_ops *ops)
7304 {
7305   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7306
7307   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7308   return add_to_breakpoint_chain (std::move (b));
7309 }
7310
7311 /* Call this routine when stepping and nexting to enable a breakpoint
7312    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7313    initiated the operation.  */
7314
7315 void
7316 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7317 {
7318   struct breakpoint *b, *b_tmp;
7319   int thread = tp->global_num;
7320
7321   /* To avoid having to rescan all objfile symbols at every step,
7322      we maintain a list of continually-inserted but always disabled
7323      longjmp "master" breakpoints.  Here, we simply create momentary
7324      clones of those and enable them for the requested thread.  */
7325   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7326     if (b->pspace == current_program_space
7327         && (b->type == bp_longjmp_master
7328             || b->type == bp_exception_master))
7329       {
7330         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7331         struct breakpoint *clone;
7332
7333         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7334            after their removal.  */
7335         clone = momentary_breakpoint_from_master (b, type,
7336                                                   &momentary_breakpoint_ops, 1);
7337         clone->thread = thread;
7338       }
7339
7340   tp->initiating_frame = frame;
7341 }
7342
7343 /* Delete all longjmp breakpoints from THREAD.  */
7344 void
7345 delete_longjmp_breakpoint (int thread)
7346 {
7347   struct breakpoint *b, *b_tmp;
7348
7349   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7350     if (b->type == bp_longjmp || b->type == bp_exception)
7351       {
7352         if (b->thread == thread)
7353           delete_breakpoint (b);
7354       }
7355 }
7356
7357 void
7358 delete_longjmp_breakpoint_at_next_stop (int thread)
7359 {
7360   struct breakpoint *b, *b_tmp;
7361
7362   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7363     if (b->type == bp_longjmp || b->type == bp_exception)
7364       {
7365         if (b->thread == thread)
7366           b->disposition = disp_del_at_next_stop;
7367       }
7368 }
7369
7370 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7371    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7372    pointer to any of them.  Return NULL if this system cannot place longjmp
7373    breakpoints.  */
7374
7375 struct breakpoint *
7376 set_longjmp_breakpoint_for_call_dummy (void)
7377 {
7378   struct breakpoint *b, *retval = NULL;
7379
7380   ALL_BREAKPOINTS (b)
7381     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7382       {
7383         struct breakpoint *new_b;
7384
7385         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7386                                                   &momentary_breakpoint_ops,
7387                                                   1);
7388         new_b->thread = ptid_to_global_thread_id (inferior_ptid);
7389
7390         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7391
7392         gdb_assert (new_b->related_breakpoint == new_b);
7393         if (retval == NULL)
7394           retval = new_b;
7395         new_b->related_breakpoint = retval;
7396         while (retval->related_breakpoint != new_b->related_breakpoint)
7397           retval = retval->related_breakpoint;
7398         retval->related_breakpoint = new_b;
7399       }
7400
7401   return retval;
7402 }
7403
7404 /* Verify all existing dummy frames and their associated breakpoints for
7405    TP.  Remove those which can no longer be found in the current frame
7406    stack.
7407
7408    You should call this function only at places where it is safe to currently
7409    unwind the whole stack.  Failed stack unwind would discard live dummy
7410    frames.  */
7411
7412 void
7413 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7414 {
7415   struct breakpoint *b, *b_tmp;
7416
7417   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7418     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7419       {
7420         struct breakpoint *dummy_b = b->related_breakpoint;
7421
7422         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7423           dummy_b = dummy_b->related_breakpoint;
7424         if (dummy_b->type != bp_call_dummy
7425             || frame_find_by_id (dummy_b->frame_id) != NULL)
7426           continue;
7427         
7428         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7429
7430         while (b->related_breakpoint != b)
7431           {
7432             if (b_tmp == b->related_breakpoint)
7433               b_tmp = b->related_breakpoint->next;
7434             delete_breakpoint (b->related_breakpoint);
7435           }
7436         delete_breakpoint (b);
7437       }
7438 }
7439
7440 void
7441 enable_overlay_breakpoints (void)
7442 {
7443   struct breakpoint *b;
7444
7445   ALL_BREAKPOINTS (b)
7446     if (b->type == bp_overlay_event)
7447     {
7448       b->enable_state = bp_enabled;
7449       update_global_location_list (UGLL_MAY_INSERT);
7450       overlay_events_enabled = 1;
7451     }
7452 }
7453
7454 void
7455 disable_overlay_breakpoints (void)
7456 {
7457   struct breakpoint *b;
7458
7459   ALL_BREAKPOINTS (b)
7460     if (b->type == bp_overlay_event)
7461     {
7462       b->enable_state = bp_disabled;
7463       update_global_location_list (UGLL_DONT_INSERT);
7464       overlay_events_enabled = 0;
7465     }
7466 }
7467
7468 /* Set an active std::terminate breakpoint for each std::terminate
7469    master breakpoint.  */
7470 void
7471 set_std_terminate_breakpoint (void)
7472 {
7473   struct breakpoint *b, *b_tmp;
7474
7475   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7476     if (b->pspace == current_program_space
7477         && b->type == bp_std_terminate_master)
7478       {
7479         momentary_breakpoint_from_master (b, bp_std_terminate,
7480                                           &momentary_breakpoint_ops, 1);
7481       }
7482 }
7483
7484 /* Delete all the std::terminate breakpoints.  */
7485 void
7486 delete_std_terminate_breakpoint (void)
7487 {
7488   struct breakpoint *b, *b_tmp;
7489
7490   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7491     if (b->type == bp_std_terminate)
7492       delete_breakpoint (b);
7493 }
7494
7495 struct breakpoint *
7496 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7497 {
7498   struct breakpoint *b;
7499
7500   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7501                                   &internal_breakpoint_ops);
7502
7503   b->enable_state = bp_enabled;
7504   /* location has to be used or breakpoint_re_set will delete me.  */
7505   b->location = new_address_location (b->loc->address, NULL, 0);
7506
7507   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7508
7509   return b;
7510 }
7511
7512 struct lang_and_radix
7513   {
7514     enum language lang;
7515     int radix;
7516   };
7517
7518 /* Create a breakpoint for JIT code registration and unregistration.  */
7519
7520 struct breakpoint *
7521 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7522 {
7523   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7524                                      &internal_breakpoint_ops);
7525 }
7526
7527 /* Remove JIT code registration and unregistration breakpoint(s).  */
7528
7529 void
7530 remove_jit_event_breakpoints (void)
7531 {
7532   struct breakpoint *b, *b_tmp;
7533
7534   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7535     if (b->type == bp_jit_event
7536         && b->loc->pspace == current_program_space)
7537       delete_breakpoint (b);
7538 }
7539
7540 void
7541 remove_solib_event_breakpoints (void)
7542 {
7543   struct breakpoint *b, *b_tmp;
7544
7545   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7546     if (b->type == bp_shlib_event
7547         && b->loc->pspace == current_program_space)
7548       delete_breakpoint (b);
7549 }
7550
7551 /* See breakpoint.h.  */
7552
7553 void
7554 remove_solib_event_breakpoints_at_next_stop (void)
7555 {
7556   struct breakpoint *b, *b_tmp;
7557
7558   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7559     if (b->type == bp_shlib_event
7560         && b->loc->pspace == current_program_space)
7561       b->disposition = disp_del_at_next_stop;
7562 }
7563
7564 /* Helper for create_solib_event_breakpoint /
7565    create_and_insert_solib_event_breakpoint.  Allows specifying which
7566    INSERT_MODE to pass through to update_global_location_list.  */
7567
7568 static struct breakpoint *
7569 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7570                                  enum ugll_insert_mode insert_mode)
7571 {
7572   struct breakpoint *b;
7573
7574   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7575                                   &internal_breakpoint_ops);
7576   update_global_location_list_nothrow (insert_mode);
7577   return b;
7578 }
7579
7580 struct breakpoint *
7581 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7582 {
7583   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7584 }
7585
7586 /* See breakpoint.h.  */
7587
7588 struct breakpoint *
7589 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7590 {
7591   struct breakpoint *b;
7592
7593   /* Explicitly tell update_global_location_list to insert
7594      locations.  */
7595   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7596   if (!b->loc->inserted)
7597     {
7598       delete_breakpoint (b);
7599       return NULL;
7600     }
7601   return b;
7602 }
7603
7604 /* Disable any breakpoints that are on code in shared libraries.  Only
7605    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7606
7607 void
7608 disable_breakpoints_in_shlibs (void)
7609 {
7610   struct bp_location *loc, **locp_tmp;
7611
7612   ALL_BP_LOCATIONS (loc, locp_tmp)
7613   {
7614     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7615     struct breakpoint *b = loc->owner;
7616
7617     /* We apply the check to all breakpoints, including disabled for
7618        those with loc->duplicate set.  This is so that when breakpoint
7619        becomes enabled, or the duplicate is removed, gdb will try to
7620        insert all breakpoints.  If we don't set shlib_disabled here,
7621        we'll try to insert those breakpoints and fail.  */
7622     if (((b->type == bp_breakpoint)
7623          || (b->type == bp_jit_event)
7624          || (b->type == bp_hardware_breakpoint)
7625          || (is_tracepoint (b)))
7626         && loc->pspace == current_program_space
7627         && !loc->shlib_disabled
7628         && solib_name_from_address (loc->pspace, loc->address)
7629         )
7630       {
7631         loc->shlib_disabled = 1;
7632       }
7633   }
7634 }
7635
7636 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7637    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7638    disabled ones can just stay disabled.  */
7639
7640 static void
7641 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7642 {
7643   struct bp_location *loc, **locp_tmp;
7644   int disabled_shlib_breaks = 0;
7645
7646   ALL_BP_LOCATIONS (loc, locp_tmp)
7647   {
7648     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7649     struct breakpoint *b = loc->owner;
7650
7651     if (solib->pspace == loc->pspace
7652         && !loc->shlib_disabled
7653         && (((b->type == bp_breakpoint
7654               || b->type == bp_jit_event
7655               || b->type == bp_hardware_breakpoint)
7656              && (loc->loc_type == bp_loc_hardware_breakpoint
7657                  || loc->loc_type == bp_loc_software_breakpoint))
7658             || is_tracepoint (b))
7659         && solib_contains_address_p (solib, loc->address))
7660       {
7661         loc->shlib_disabled = 1;
7662         /* At this point, we cannot rely on remove_breakpoint
7663            succeeding so we must mark the breakpoint as not inserted
7664            to prevent future errors occurring in remove_breakpoints.  */
7665         loc->inserted = 0;
7666
7667         /* This may cause duplicate notifications for the same breakpoint.  */
7668         observer_notify_breakpoint_modified (b);
7669
7670         if (!disabled_shlib_breaks)
7671           {
7672             target_terminal::ours_for_output ();
7673             warning (_("Temporarily disabling breakpoints "
7674                        "for unloaded shared library \"%s\""),
7675                      solib->so_name);
7676           }
7677         disabled_shlib_breaks = 1;
7678       }
7679   }
7680 }
7681
7682 /* Disable any breakpoints and tracepoints in OBJFILE upon
7683    notification of free_objfile.  Only apply to enabled breakpoints,
7684    disabled ones can just stay disabled.  */
7685
7686 static void
7687 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7688 {
7689   struct breakpoint *b;
7690
7691   if (objfile == NULL)
7692     return;
7693
7694   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7695      managed by the user with add-symbol-file/remove-symbol-file.
7696      Similarly to how breakpoints in shared libraries are handled in
7697      response to "nosharedlibrary", mark breakpoints in such modules
7698      shlib_disabled so they end up uninserted on the next global
7699      location list update.  Shared libraries not loaded by the user
7700      aren't handled here -- they're already handled in
7701      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7702      solib_unloaded observer.  We skip objfiles that are not
7703      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7704      main objfile).  */
7705   if ((objfile->flags & OBJF_SHARED) == 0
7706       || (objfile->flags & OBJF_USERLOADED) == 0)
7707     return;
7708
7709   ALL_BREAKPOINTS (b)
7710     {
7711       struct bp_location *loc;
7712       int bp_modified = 0;
7713
7714       if (!is_breakpoint (b) && !is_tracepoint (b))
7715         continue;
7716
7717       for (loc = b->loc; loc != NULL; loc = loc->next)
7718         {
7719           CORE_ADDR loc_addr = loc->address;
7720
7721           if (loc->loc_type != bp_loc_hardware_breakpoint
7722               && loc->loc_type != bp_loc_software_breakpoint)
7723             continue;
7724
7725           if (loc->shlib_disabled != 0)
7726             continue;
7727
7728           if (objfile->pspace != loc->pspace)
7729             continue;
7730
7731           if (loc->loc_type != bp_loc_hardware_breakpoint
7732               && loc->loc_type != bp_loc_software_breakpoint)
7733             continue;
7734
7735           if (is_addr_in_objfile (loc_addr, objfile))
7736             {
7737               loc->shlib_disabled = 1;
7738               /* At this point, we don't know whether the object was
7739                  unmapped from the inferior or not, so leave the
7740                  inserted flag alone.  We'll handle failure to
7741                  uninsert quietly, in case the object was indeed
7742                  unmapped.  */
7743
7744               mark_breakpoint_location_modified (loc);
7745
7746               bp_modified = 1;
7747             }
7748         }
7749
7750       if (bp_modified)
7751         observer_notify_breakpoint_modified (b);
7752     }
7753 }
7754
7755 /* FORK & VFORK catchpoints.  */
7756
7757 /* An instance of this type is used to represent a fork or vfork
7758    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7759    to CATCH_FORK_BREAKPOINT_OPS.  */
7760
7761 struct fork_catchpoint : public breakpoint
7762 {
7763   /* Process id of a child process whose forking triggered this
7764      catchpoint.  This field is only valid immediately after this
7765      catchpoint has triggered.  */
7766   ptid_t forked_inferior_pid;
7767 };
7768
7769 /* Implement the "insert" breakpoint_ops method for fork
7770    catchpoints.  */
7771
7772 static int
7773 insert_catch_fork (struct bp_location *bl)
7774 {
7775   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7776 }
7777
7778 /* Implement the "remove" breakpoint_ops method for fork
7779    catchpoints.  */
7780
7781 static int
7782 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7783 {
7784   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7785 }
7786
7787 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7788    catchpoints.  */
7789
7790 static int
7791 breakpoint_hit_catch_fork (const struct bp_location *bl,
7792                            const address_space *aspace, CORE_ADDR bp_addr,
7793                            const struct target_waitstatus *ws)
7794 {
7795   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7796
7797   if (ws->kind != TARGET_WAITKIND_FORKED)
7798     return 0;
7799
7800   c->forked_inferior_pid = ws->value.related_pid;
7801   return 1;
7802 }
7803
7804 /* Implement the "print_it" breakpoint_ops method for fork
7805    catchpoints.  */
7806
7807 static enum print_stop_action
7808 print_it_catch_fork (bpstat bs)
7809 {
7810   struct ui_out *uiout = current_uiout;
7811   struct breakpoint *b = bs->breakpoint_at;
7812   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7813
7814   annotate_catchpoint (b->number);
7815   maybe_print_thread_hit_breakpoint (uiout);
7816   if (b->disposition == disp_del)
7817     uiout->text ("Temporary catchpoint ");
7818   else
7819     uiout->text ("Catchpoint ");
7820   if (uiout->is_mi_like_p ())
7821     {
7822       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7823       uiout->field_string ("disp", bpdisp_text (b->disposition));
7824     }
7825   uiout->field_int ("bkptno", b->number);
7826   uiout->text (" (forked process ");
7827   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7828   uiout->text ("), ");
7829   return PRINT_SRC_AND_LOC;
7830 }
7831
7832 /* Implement the "print_one" breakpoint_ops method for fork
7833    catchpoints.  */
7834
7835 static void
7836 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7837 {
7838   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7839   struct value_print_options opts;
7840   struct ui_out *uiout = current_uiout;
7841
7842   get_user_print_options (&opts);
7843
7844   /* Field 4, the address, is omitted (which makes the columns not
7845      line up too nicely with the headers, but the effect is relatively
7846      readable).  */
7847   if (opts.addressprint)
7848     uiout->field_skip ("addr");
7849   annotate_field (5);
7850   uiout->text ("fork");
7851   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7852     {
7853       uiout->text (", process ");
7854       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7855       uiout->spaces (1);
7856     }
7857
7858   if (uiout->is_mi_like_p ())
7859     uiout->field_string ("catch-type", "fork");
7860 }
7861
7862 /* Implement the "print_mention" breakpoint_ops method for fork
7863    catchpoints.  */
7864
7865 static void
7866 print_mention_catch_fork (struct breakpoint *b)
7867 {
7868   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7869 }
7870
7871 /* Implement the "print_recreate" breakpoint_ops method for fork
7872    catchpoints.  */
7873
7874 static void
7875 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7876 {
7877   fprintf_unfiltered (fp, "catch fork");
7878   print_recreate_thread (b, fp);
7879 }
7880
7881 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7882
7883 static struct breakpoint_ops catch_fork_breakpoint_ops;
7884
7885 /* Implement the "insert" breakpoint_ops method for vfork
7886    catchpoints.  */
7887
7888 static int
7889 insert_catch_vfork (struct bp_location *bl)
7890 {
7891   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7892 }
7893
7894 /* Implement the "remove" breakpoint_ops method for vfork
7895    catchpoints.  */
7896
7897 static int
7898 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7899 {
7900   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7901 }
7902
7903 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7904    catchpoints.  */
7905
7906 static int
7907 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7908                             const address_space *aspace, CORE_ADDR bp_addr,
7909                             const struct target_waitstatus *ws)
7910 {
7911   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7912
7913   if (ws->kind != TARGET_WAITKIND_VFORKED)
7914     return 0;
7915
7916   c->forked_inferior_pid = ws->value.related_pid;
7917   return 1;
7918 }
7919
7920 /* Implement the "print_it" breakpoint_ops method for vfork
7921    catchpoints.  */
7922
7923 static enum print_stop_action
7924 print_it_catch_vfork (bpstat bs)
7925 {
7926   struct ui_out *uiout = current_uiout;
7927   struct breakpoint *b = bs->breakpoint_at;
7928   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7929
7930   annotate_catchpoint (b->number);
7931   maybe_print_thread_hit_breakpoint (uiout);
7932   if (b->disposition == disp_del)
7933     uiout->text ("Temporary catchpoint ");
7934   else
7935     uiout->text ("Catchpoint ");
7936   if (uiout->is_mi_like_p ())
7937     {
7938       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7939       uiout->field_string ("disp", bpdisp_text (b->disposition));
7940     }
7941   uiout->field_int ("bkptno", b->number);
7942   uiout->text (" (vforked process ");
7943   uiout->field_int ("newpid", ptid_get_pid (c->forked_inferior_pid));
7944   uiout->text ("), ");
7945   return PRINT_SRC_AND_LOC;
7946 }
7947
7948 /* Implement the "print_one" breakpoint_ops method for vfork
7949    catchpoints.  */
7950
7951 static void
7952 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7953 {
7954   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7955   struct value_print_options opts;
7956   struct ui_out *uiout = current_uiout;
7957
7958   get_user_print_options (&opts);
7959   /* Field 4, the address, is omitted (which makes the columns not
7960      line up too nicely with the headers, but the effect is relatively
7961      readable).  */
7962   if (opts.addressprint)
7963     uiout->field_skip ("addr");
7964   annotate_field (5);
7965   uiout->text ("vfork");
7966   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7967     {
7968       uiout->text (", process ");
7969       uiout->field_int ("what", ptid_get_pid (c->forked_inferior_pid));
7970       uiout->spaces (1);
7971     }
7972
7973   if (uiout->is_mi_like_p ())
7974     uiout->field_string ("catch-type", "vfork");
7975 }
7976
7977 /* Implement the "print_mention" breakpoint_ops method for vfork
7978    catchpoints.  */
7979
7980 static void
7981 print_mention_catch_vfork (struct breakpoint *b)
7982 {
7983   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7984 }
7985
7986 /* Implement the "print_recreate" breakpoint_ops method for vfork
7987    catchpoints.  */
7988
7989 static void
7990 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7991 {
7992   fprintf_unfiltered (fp, "catch vfork");
7993   print_recreate_thread (b, fp);
7994 }
7995
7996 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7997
7998 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7999
8000 /* An instance of this type is used to represent an solib catchpoint.
8001    A breakpoint is really of this type iff its ops pointer points to
8002    CATCH_SOLIB_BREAKPOINT_OPS.  */
8003
8004 struct solib_catchpoint : public breakpoint
8005 {
8006   ~solib_catchpoint () override;
8007
8008   /* True for "catch load", false for "catch unload".  */
8009   unsigned char is_load;
8010
8011   /* Regular expression to match, if any.  COMPILED is only valid when
8012      REGEX is non-NULL.  */
8013   char *regex;
8014   std::unique_ptr<compiled_regex> compiled;
8015 };
8016
8017 solib_catchpoint::~solib_catchpoint ()
8018 {
8019   xfree (this->regex);
8020 }
8021
8022 static int
8023 insert_catch_solib (struct bp_location *ignore)
8024 {
8025   return 0;
8026 }
8027
8028 static int
8029 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8030 {
8031   return 0;
8032 }
8033
8034 static int
8035 breakpoint_hit_catch_solib (const struct bp_location *bl,
8036                             const address_space *aspace,
8037                             CORE_ADDR bp_addr,
8038                             const struct target_waitstatus *ws)
8039 {
8040   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8041   struct breakpoint *other;
8042
8043   if (ws->kind == TARGET_WAITKIND_LOADED)
8044     return 1;
8045
8046   ALL_BREAKPOINTS (other)
8047   {
8048     struct bp_location *other_bl;
8049
8050     if (other == bl->owner)
8051       continue;
8052
8053     if (other->type != bp_shlib_event)
8054       continue;
8055
8056     if (self->pspace != NULL && other->pspace != self->pspace)
8057       continue;
8058
8059     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8060       {
8061         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8062           return 1;
8063       }
8064   }
8065
8066   return 0;
8067 }
8068
8069 static void
8070 check_status_catch_solib (struct bpstats *bs)
8071 {
8072   struct solib_catchpoint *self
8073     = (struct solib_catchpoint *) bs->breakpoint_at;
8074   int ix;
8075
8076   if (self->is_load)
8077     {
8078       struct so_list *iter;
8079
8080       for (ix = 0;
8081            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8082                         ix, iter);
8083            ++ix)
8084         {
8085           if (!self->regex
8086               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8087             return;
8088         }
8089     }
8090   else
8091     {
8092       char *iter;
8093
8094       for (ix = 0;
8095            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8096                         ix, iter);
8097            ++ix)
8098         {
8099           if (!self->regex
8100               || self->compiled->exec (iter, 0, NULL, 0) == 0)
8101             return;
8102         }
8103     }
8104
8105   bs->stop = 0;
8106   bs->print_it = print_it_noop;
8107 }
8108
8109 static enum print_stop_action
8110 print_it_catch_solib (bpstat bs)
8111 {
8112   struct breakpoint *b = bs->breakpoint_at;
8113   struct ui_out *uiout = current_uiout;
8114
8115   annotate_catchpoint (b->number);
8116   maybe_print_thread_hit_breakpoint (uiout);
8117   if (b->disposition == disp_del)
8118     uiout->text ("Temporary catchpoint ");
8119   else
8120     uiout->text ("Catchpoint ");
8121   uiout->field_int ("bkptno", b->number);
8122   uiout->text ("\n");
8123   if (uiout->is_mi_like_p ())
8124     uiout->field_string ("disp", bpdisp_text (b->disposition));
8125   print_solib_event (1);
8126   return PRINT_SRC_AND_LOC;
8127 }
8128
8129 static void
8130 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8131 {
8132   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8133   struct value_print_options opts;
8134   struct ui_out *uiout = current_uiout;
8135   char *msg;
8136
8137   get_user_print_options (&opts);
8138   /* Field 4, the address, is omitted (which makes the columns not
8139      line up too nicely with the headers, but the effect is relatively
8140      readable).  */
8141   if (opts.addressprint)
8142     {
8143       annotate_field (4);
8144       uiout->field_skip ("addr");
8145     }
8146
8147   annotate_field (5);
8148   if (self->is_load)
8149     {
8150       if (self->regex)
8151         msg = xstrprintf (_("load of library matching %s"), self->regex);
8152       else
8153         msg = xstrdup (_("load of library"));
8154     }
8155   else
8156     {
8157       if (self->regex)
8158         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8159       else
8160         msg = xstrdup (_("unload of library"));
8161     }
8162   uiout->field_string ("what", msg);
8163   xfree (msg);
8164
8165   if (uiout->is_mi_like_p ())
8166     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8167 }
8168
8169 static void
8170 print_mention_catch_solib (struct breakpoint *b)
8171 {
8172   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8173
8174   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8175                    self->is_load ? "load" : "unload");
8176 }
8177
8178 static void
8179 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8180 {
8181   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8182
8183   fprintf_unfiltered (fp, "%s %s",
8184                       b->disposition == disp_del ? "tcatch" : "catch",
8185                       self->is_load ? "load" : "unload");
8186   if (self->regex)
8187     fprintf_unfiltered (fp, " %s", self->regex);
8188   fprintf_unfiltered (fp, "\n");
8189 }
8190
8191 static struct breakpoint_ops catch_solib_breakpoint_ops;
8192
8193 /* Shared helper function (MI and CLI) for creating and installing
8194    a shared object event catchpoint.  If IS_LOAD is non-zero then
8195    the events to be caught are load events, otherwise they are
8196    unload events.  If IS_TEMP is non-zero the catchpoint is a
8197    temporary one.  If ENABLED is non-zero the catchpoint is
8198    created in an enabled state.  */
8199
8200 void
8201 add_solib_catchpoint (const char *arg, int is_load, int is_temp, int enabled)
8202 {
8203   struct gdbarch *gdbarch = get_current_arch ();
8204
8205   if (!arg)
8206     arg = "";
8207   arg = skip_spaces (arg);
8208
8209   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8210
8211   if (*arg != '\0')
8212     {
8213       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8214                                              _("Invalid regexp")));
8215       c->regex = xstrdup (arg);
8216     }
8217
8218   c->is_load = is_load;
8219   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8220                    &catch_solib_breakpoint_ops);
8221
8222   c->enable_state = enabled ? bp_enabled : bp_disabled;
8223
8224   install_breakpoint (0, std::move (c), 1);
8225 }
8226
8227 /* A helper function that does all the work for "catch load" and
8228    "catch unload".  */
8229
8230 static void
8231 catch_load_or_unload (char *arg, int from_tty, int is_load,
8232                       struct cmd_list_element *command)
8233 {
8234   int tempflag;
8235   const int enabled = 1;
8236
8237   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8238
8239   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8240 }
8241
8242 static void
8243 catch_load_command_1 (char *arg, int from_tty,
8244                       struct cmd_list_element *command)
8245 {
8246   catch_load_or_unload (arg, from_tty, 1, command);
8247 }
8248
8249 static void
8250 catch_unload_command_1 (char *arg, int from_tty,
8251                         struct cmd_list_element *command)
8252 {
8253   catch_load_or_unload (arg, from_tty, 0, command);
8254 }
8255
8256 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8257    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8258    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8259    the breakpoint_ops structure associated to the catchpoint.  */
8260
8261 void
8262 init_catchpoint (struct breakpoint *b,
8263                  struct gdbarch *gdbarch, int tempflag,
8264                  const char *cond_string,
8265                  const struct breakpoint_ops *ops)
8266 {
8267   symtab_and_line sal;
8268   sal.pspace = current_program_space;
8269
8270   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8271
8272   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8273   b->disposition = tempflag ? disp_del : disp_donttouch;
8274 }
8275
8276 void
8277 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8278 {
8279   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8280   set_breakpoint_number (internal, b);
8281   if (is_tracepoint (b))
8282     set_tracepoint_count (breakpoint_count);
8283   if (!internal)
8284     mention (b);
8285   observer_notify_breakpoint_created (b);
8286
8287   if (update_gll)
8288     update_global_location_list (UGLL_MAY_INSERT);
8289 }
8290
8291 static void
8292 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8293                                     int tempflag, const char *cond_string,
8294                                     const struct breakpoint_ops *ops)
8295 {
8296   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8297
8298   init_catchpoint (c.get (), gdbarch, tempflag, cond_string, ops);
8299
8300   c->forked_inferior_pid = null_ptid;
8301
8302   install_breakpoint (0, std::move (c), 1);
8303 }
8304
8305 /* Exec catchpoints.  */
8306
8307 /* An instance of this type is used to represent an exec catchpoint.
8308    A breakpoint is really of this type iff its ops pointer points to
8309    CATCH_EXEC_BREAKPOINT_OPS.  */
8310
8311 struct exec_catchpoint : public breakpoint
8312 {
8313   ~exec_catchpoint () override;
8314
8315   /* Filename of a program whose exec triggered this catchpoint.
8316      This field is only valid immediately after this catchpoint has
8317      triggered.  */
8318   char *exec_pathname;
8319 };
8320
8321 /* Exec catchpoint destructor.  */
8322
8323 exec_catchpoint::~exec_catchpoint ()
8324 {
8325   xfree (this->exec_pathname);
8326 }
8327
8328 static int
8329 insert_catch_exec (struct bp_location *bl)
8330 {
8331   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8332 }
8333
8334 static int
8335 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8336 {
8337   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8338 }
8339
8340 static int
8341 breakpoint_hit_catch_exec (const struct bp_location *bl,
8342                            const address_space *aspace, CORE_ADDR bp_addr,
8343                            const struct target_waitstatus *ws)
8344 {
8345   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8346
8347   if (ws->kind != TARGET_WAITKIND_EXECD)
8348     return 0;
8349
8350   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8351   return 1;
8352 }
8353
8354 static enum print_stop_action
8355 print_it_catch_exec (bpstat bs)
8356 {
8357   struct ui_out *uiout = current_uiout;
8358   struct breakpoint *b = bs->breakpoint_at;
8359   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8360
8361   annotate_catchpoint (b->number);
8362   maybe_print_thread_hit_breakpoint (uiout);
8363   if (b->disposition == disp_del)
8364     uiout->text ("Temporary catchpoint ");
8365   else
8366     uiout->text ("Catchpoint ");
8367   if (uiout->is_mi_like_p ())
8368     {
8369       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8370       uiout->field_string ("disp", bpdisp_text (b->disposition));
8371     }
8372   uiout->field_int ("bkptno", b->number);
8373   uiout->text (" (exec'd ");
8374   uiout->field_string ("new-exec", c->exec_pathname);
8375   uiout->text ("), ");
8376
8377   return PRINT_SRC_AND_LOC;
8378 }
8379
8380 static void
8381 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8382 {
8383   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8384   struct value_print_options opts;
8385   struct ui_out *uiout = current_uiout;
8386
8387   get_user_print_options (&opts);
8388
8389   /* Field 4, the address, is omitted (which makes the columns
8390      not line up too nicely with the headers, but the effect
8391      is relatively readable).  */
8392   if (opts.addressprint)
8393     uiout->field_skip ("addr");
8394   annotate_field (5);
8395   uiout->text ("exec");
8396   if (c->exec_pathname != NULL)
8397     {
8398       uiout->text (", program \"");
8399       uiout->field_string ("what", c->exec_pathname);
8400       uiout->text ("\" ");
8401     }
8402
8403   if (uiout->is_mi_like_p ())
8404     uiout->field_string ("catch-type", "exec");
8405 }
8406
8407 static void
8408 print_mention_catch_exec (struct breakpoint *b)
8409 {
8410   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8411 }
8412
8413 /* Implement the "print_recreate" breakpoint_ops method for exec
8414    catchpoints.  */
8415
8416 static void
8417 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8418 {
8419   fprintf_unfiltered (fp, "catch exec");
8420   print_recreate_thread (b, fp);
8421 }
8422
8423 static struct breakpoint_ops catch_exec_breakpoint_ops;
8424
8425 static int
8426 hw_breakpoint_used_count (void)
8427 {
8428   int i = 0;
8429   struct breakpoint *b;
8430   struct bp_location *bl;
8431
8432   ALL_BREAKPOINTS (b)
8433   {
8434     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8435       for (bl = b->loc; bl; bl = bl->next)
8436         {
8437           /* Special types of hardware breakpoints may use more than
8438              one register.  */
8439           i += b->ops->resources_needed (bl);
8440         }
8441   }
8442
8443   return i;
8444 }
8445
8446 /* Returns the resources B would use if it were a hardware
8447    watchpoint.  */
8448
8449 static int
8450 hw_watchpoint_use_count (struct breakpoint *b)
8451 {
8452   int i = 0;
8453   struct bp_location *bl;
8454
8455   if (!breakpoint_enabled (b))
8456     return 0;
8457
8458   for (bl = b->loc; bl; bl = bl->next)
8459     {
8460       /* Special types of hardware watchpoints may use more than
8461          one register.  */
8462       i += b->ops->resources_needed (bl);
8463     }
8464
8465   return i;
8466 }
8467
8468 /* Returns the sum the used resources of all hardware watchpoints of
8469    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8470    the sum of the used resources of all hardware watchpoints of other
8471    types _not_ TYPE.  */
8472
8473 static int
8474 hw_watchpoint_used_count_others (struct breakpoint *except,
8475                                  enum bptype type, int *other_type_used)
8476 {
8477   int i = 0;
8478   struct breakpoint *b;
8479
8480   *other_type_used = 0;
8481   ALL_BREAKPOINTS (b)
8482     {
8483       if (b == except)
8484         continue;
8485       if (!breakpoint_enabled (b))
8486         continue;
8487
8488       if (b->type == type)
8489         i += hw_watchpoint_use_count (b);
8490       else if (is_hardware_watchpoint (b))
8491         *other_type_used = 1;
8492     }
8493
8494   return i;
8495 }
8496
8497 void
8498 disable_watchpoints_before_interactive_call_start (void)
8499 {
8500   struct breakpoint *b;
8501
8502   ALL_BREAKPOINTS (b)
8503   {
8504     if (is_watchpoint (b) && breakpoint_enabled (b))
8505       {
8506         b->enable_state = bp_call_disabled;
8507         update_global_location_list (UGLL_DONT_INSERT);
8508       }
8509   }
8510 }
8511
8512 void
8513 enable_watchpoints_after_interactive_call_stop (void)
8514 {
8515   struct breakpoint *b;
8516
8517   ALL_BREAKPOINTS (b)
8518   {
8519     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8520       {
8521         b->enable_state = bp_enabled;
8522         update_global_location_list (UGLL_MAY_INSERT);
8523       }
8524   }
8525 }
8526
8527 void
8528 disable_breakpoints_before_startup (void)
8529 {
8530   current_program_space->executing_startup = 1;
8531   update_global_location_list (UGLL_DONT_INSERT);
8532 }
8533
8534 void
8535 enable_breakpoints_after_startup (void)
8536 {
8537   current_program_space->executing_startup = 0;
8538   breakpoint_re_set ();
8539 }
8540
8541 /* Create a new single-step breakpoint for thread THREAD, with no
8542    locations.  */
8543
8544 static struct breakpoint *
8545 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8546 {
8547   std::unique_ptr<breakpoint> b (new breakpoint ());
8548
8549   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8550                                         &momentary_breakpoint_ops);
8551
8552   b->disposition = disp_donttouch;
8553   b->frame_id = null_frame_id;
8554
8555   b->thread = thread;
8556   gdb_assert (b->thread != 0);
8557
8558   return add_to_breakpoint_chain (std::move (b));
8559 }
8560
8561 /* Set a momentary breakpoint of type TYPE at address specified by
8562    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8563    frame.  */
8564
8565 breakpoint_up
8566 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8567                           struct frame_id frame_id, enum bptype type)
8568 {
8569   struct breakpoint *b;
8570
8571   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8572      tail-called one.  */
8573   gdb_assert (!frame_id_artificial_p (frame_id));
8574
8575   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8576   b->enable_state = bp_enabled;
8577   b->disposition = disp_donttouch;
8578   b->frame_id = frame_id;
8579
8580   /* If we're debugging a multi-threaded program, then we want
8581      momentary breakpoints to be active in only a single thread of
8582      control.  */
8583   if (in_thread_list (inferior_ptid))
8584     b->thread = ptid_to_global_thread_id (inferior_ptid);
8585
8586   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8587
8588   return breakpoint_up (b);
8589 }
8590
8591 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8592    The new breakpoint will have type TYPE, use OPS as its
8593    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8594
8595 static struct breakpoint *
8596 momentary_breakpoint_from_master (struct breakpoint *orig,
8597                                   enum bptype type,
8598                                   const struct breakpoint_ops *ops,
8599                                   int loc_enabled)
8600 {
8601   struct breakpoint *copy;
8602
8603   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8604   copy->loc = allocate_bp_location (copy);
8605   set_breakpoint_location_function (copy->loc, 1);
8606
8607   copy->loc->gdbarch = orig->loc->gdbarch;
8608   copy->loc->requested_address = orig->loc->requested_address;
8609   copy->loc->address = orig->loc->address;
8610   copy->loc->section = orig->loc->section;
8611   copy->loc->pspace = orig->loc->pspace;
8612   copy->loc->probe = orig->loc->probe;
8613   copy->loc->line_number = orig->loc->line_number;
8614   copy->loc->symtab = orig->loc->symtab;
8615   copy->loc->enabled = loc_enabled;
8616   copy->frame_id = orig->frame_id;
8617   copy->thread = orig->thread;
8618   copy->pspace = orig->pspace;
8619
8620   copy->enable_state = bp_enabled;
8621   copy->disposition = disp_donttouch;
8622   copy->number = internal_breakpoint_number--;
8623
8624   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8625   return copy;
8626 }
8627
8628 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8629    ORIG is NULL.  */
8630
8631 struct breakpoint *
8632 clone_momentary_breakpoint (struct breakpoint *orig)
8633 {
8634   /* If there's nothing to clone, then return nothing.  */
8635   if (orig == NULL)
8636     return NULL;
8637
8638   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8639 }
8640
8641 breakpoint_up
8642 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8643                                 enum bptype type)
8644 {
8645   struct symtab_and_line sal;
8646
8647   sal = find_pc_line (pc, 0);
8648   sal.pc = pc;
8649   sal.section = find_pc_overlay (pc);
8650   sal.explicit_pc = 1;
8651
8652   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8653 }
8654 \f
8655
8656 /* Tell the user we have just set a breakpoint B.  */
8657
8658 static void
8659 mention (struct breakpoint *b)
8660 {
8661   b->ops->print_mention (b);
8662   if (current_uiout->is_mi_like_p ())
8663     return;
8664   printf_filtered ("\n");
8665 }
8666 \f
8667
8668 static int bp_loc_is_permanent (struct bp_location *loc);
8669
8670 static struct bp_location *
8671 add_location_to_breakpoint (struct breakpoint *b,
8672                             const struct symtab_and_line *sal)
8673 {
8674   struct bp_location *loc, **tmp;
8675   CORE_ADDR adjusted_address;
8676   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8677
8678   if (loc_gdbarch == NULL)
8679     loc_gdbarch = b->gdbarch;
8680
8681   /* Adjust the breakpoint's address prior to allocating a location.
8682      Once we call allocate_bp_location(), that mostly uninitialized
8683      location will be placed on the location chain.  Adjustment of the
8684      breakpoint may cause target_read_memory() to be called and we do
8685      not want its scan of the location chain to find a breakpoint and
8686      location that's only been partially initialized.  */
8687   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8688                                                 sal->pc, b->type);
8689
8690   /* Sort the locations by their ADDRESS.  */
8691   loc = allocate_bp_location (b);
8692   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8693        tmp = &((*tmp)->next))
8694     ;
8695   loc->next = *tmp;
8696   *tmp = loc;
8697
8698   loc->requested_address = sal->pc;
8699   loc->address = adjusted_address;
8700   loc->pspace = sal->pspace;
8701   loc->probe.probe = sal->probe;
8702   loc->probe.objfile = sal->objfile;
8703   gdb_assert (loc->pspace != NULL);
8704   loc->section = sal->section;
8705   loc->gdbarch = loc_gdbarch;
8706   loc->line_number = sal->line;
8707   loc->symtab = sal->symtab;
8708   loc->symbol = sal->symbol;
8709
8710   set_breakpoint_location_function (loc,
8711                                     sal->explicit_pc || sal->explicit_line);
8712
8713   /* While by definition, permanent breakpoints are already present in the
8714      code, we don't mark the location as inserted.  Normally one would expect
8715      that GDB could rely on that breakpoint instruction to stop the program,
8716      thus removing the need to insert its own breakpoint, except that executing
8717      the breakpoint instruction can kill the target instead of reporting a
8718      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8719      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8720      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8721      breakpoint be inserted normally results in QEMU knowing about the GDB
8722      breakpoint, and thus trap before the breakpoint instruction is executed.
8723      (If GDB later needs to continue execution past the permanent breakpoint,
8724      it manually increments the PC, thus avoiding executing the breakpoint
8725      instruction.)  */
8726   if (bp_loc_is_permanent (loc))
8727     loc->permanent = 1;
8728
8729   return loc;
8730 }
8731 \f
8732
8733 /* See breakpoint.h.  */
8734
8735 int
8736 program_breakpoint_here_p (struct gdbarch *gdbarch, CORE_ADDR address)
8737 {
8738   int len;
8739   CORE_ADDR addr;
8740   const gdb_byte *bpoint;
8741   gdb_byte *target_mem;
8742
8743   addr = address;
8744   bpoint = gdbarch_breakpoint_from_pc (gdbarch, &addr, &len);
8745
8746   /* Software breakpoints unsupported?  */
8747   if (bpoint == NULL)
8748     return 0;
8749
8750   target_mem = (gdb_byte *) alloca (len);
8751
8752   /* Enable the automatic memory restoration from breakpoints while
8753      we read the memory.  Otherwise we could say about our temporary
8754      breakpoints they are permanent.  */
8755   scoped_restore restore_memory
8756     = make_scoped_restore_show_memory_breakpoints (0);
8757
8758   if (target_read_memory (address, target_mem, len) == 0
8759       && memcmp (target_mem, bpoint, len) == 0)
8760     return 1;
8761
8762   return 0;
8763 }
8764
8765 /* Return 1 if LOC is pointing to a permanent breakpoint,
8766    return 0 otherwise.  */
8767
8768 static int
8769 bp_loc_is_permanent (struct bp_location *loc)
8770 {
8771   gdb_assert (loc != NULL);
8772
8773   /* If we have a catchpoint or a watchpoint, just return 0.  We should not
8774      attempt to read from the addresses the locations of these breakpoint types
8775      point to.  program_breakpoint_here_p, below, will attempt to read
8776      memory.  */
8777   if (!breakpoint_address_is_meaningful (loc->owner))
8778     return 0;
8779
8780   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8781   switch_to_program_space_and_thread (loc->pspace);
8782   return program_breakpoint_here_p (loc->gdbarch, loc->address);
8783 }
8784
8785 /* Build a command list for the dprintf corresponding to the current
8786    settings of the dprintf style options.  */
8787
8788 static void
8789 update_dprintf_command_list (struct breakpoint *b)
8790 {
8791   char *dprintf_args = b->extra_string;
8792   char *printf_line = NULL;
8793
8794   if (!dprintf_args)
8795     return;
8796
8797   dprintf_args = skip_spaces (dprintf_args);
8798
8799   /* Allow a comma, as it may have terminated a location, but don't
8800      insist on it.  */
8801   if (*dprintf_args == ',')
8802     ++dprintf_args;
8803   dprintf_args = skip_spaces (dprintf_args);
8804
8805   if (*dprintf_args != '"')
8806     error (_("Bad format string, missing '\"'."));
8807
8808   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8809     printf_line = xstrprintf ("printf %s", dprintf_args);
8810   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8811     {
8812       if (!dprintf_function)
8813         error (_("No function supplied for dprintf call"));
8814
8815       if (dprintf_channel && strlen (dprintf_channel) > 0)
8816         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8817                                   dprintf_function,
8818                                   dprintf_channel,
8819                                   dprintf_args);
8820       else
8821         printf_line = xstrprintf ("call (void) %s (%s)",
8822                                   dprintf_function,
8823                                   dprintf_args);
8824     }
8825   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8826     {
8827       if (target_can_run_breakpoint_commands ())
8828         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8829       else
8830         {
8831           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8832           printf_line = xstrprintf ("printf %s", dprintf_args);
8833         }
8834     }
8835   else
8836     internal_error (__FILE__, __LINE__,
8837                     _("Invalid dprintf style."));
8838
8839   gdb_assert (printf_line != NULL);
8840   /* Manufacture a printf sequence.  */
8841   {
8842     struct command_line *printf_cmd_line = XNEW (struct command_line);
8843
8844     printf_cmd_line->control_type = simple_control;
8845     printf_cmd_line->body_count = 0;
8846     printf_cmd_line->body_list = NULL;
8847     printf_cmd_line->next = NULL;
8848     printf_cmd_line->line = printf_line;
8849
8850     breakpoint_set_commands (b, command_line_up (printf_cmd_line));
8851   }
8852 }
8853
8854 /* Update all dprintf commands, making their command lists reflect
8855    current style settings.  */
8856
8857 static void
8858 update_dprintf_commands (char *args, int from_tty,
8859                          struct cmd_list_element *c)
8860 {
8861   struct breakpoint *b;
8862
8863   ALL_BREAKPOINTS (b)
8864     {
8865       if (b->type == bp_dprintf)
8866         update_dprintf_command_list (b);
8867     }
8868 }
8869
8870 /* Create a breakpoint with SAL as location.  Use LOCATION
8871    as a description of the location, and COND_STRING
8872    as condition expression.  If LOCATION is NULL then create an
8873    "address location" from the address in the SAL.  */
8874
8875 static void
8876 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8877                      gdb::array_view<const symtab_and_line> sals,
8878                      event_location_up &&location,
8879                      gdb::unique_xmalloc_ptr<char> filter,
8880                      gdb::unique_xmalloc_ptr<char> cond_string,
8881                      gdb::unique_xmalloc_ptr<char> extra_string,
8882                      enum bptype type, enum bpdisp disposition,
8883                      int thread, int task, int ignore_count,
8884                      const struct breakpoint_ops *ops, int from_tty,
8885                      int enabled, int internal, unsigned flags,
8886                      int display_canonical)
8887 {
8888   int i;
8889
8890   if (type == bp_hardware_breakpoint)
8891     {
8892       int target_resources_ok;
8893
8894       i = hw_breakpoint_used_count ();
8895       target_resources_ok =
8896         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8897                                             i + 1, 0);
8898       if (target_resources_ok == 0)
8899         error (_("No hardware breakpoint support in the target."));
8900       else if (target_resources_ok < 0)
8901         error (_("Hardware breakpoints used exceeds limit."));
8902     }
8903
8904   gdb_assert (!sals.empty ());
8905
8906   for (const auto &sal : sals)
8907     {
8908       struct bp_location *loc;
8909
8910       if (from_tty)
8911         {
8912           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8913           if (!loc_gdbarch)
8914             loc_gdbarch = gdbarch;
8915
8916           describe_other_breakpoints (loc_gdbarch,
8917                                       sal.pspace, sal.pc, sal.section, thread);
8918         }
8919
8920       if (&sal == &sals[0])
8921         {
8922           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8923           b->thread = thread;
8924           b->task = task;
8925
8926           b->cond_string = cond_string.release ();
8927           b->extra_string = extra_string.release ();
8928           b->ignore_count = ignore_count;
8929           b->enable_state = enabled ? bp_enabled : bp_disabled;
8930           b->disposition = disposition;
8931
8932           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8933             b->loc->inserted = 1;
8934
8935           if (type == bp_static_tracepoint)
8936             {
8937               struct tracepoint *t = (struct tracepoint *) b;
8938               struct static_tracepoint_marker marker;
8939
8940               if (strace_marker_p (b))
8941                 {
8942                   /* We already know the marker exists, otherwise, we
8943                      wouldn't see a sal for it.  */
8944                   const char *p
8945                     = &event_location_to_string (b->location.get ())[3];
8946                   const char *endp;
8947                   char *marker_str;
8948
8949                   p = skip_spaces (p);
8950
8951                   endp = skip_to_space (p);
8952
8953                   marker_str = savestring (p, endp - p);
8954                   t->static_trace_marker_id = marker_str;
8955
8956                   printf_filtered (_("Probed static tracepoint "
8957                                      "marker \"%s\"\n"),
8958                                    t->static_trace_marker_id);
8959                 }
8960               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8961                 {
8962                   t->static_trace_marker_id = xstrdup (marker.str_id);
8963                   release_static_tracepoint_marker (&marker);
8964
8965                   printf_filtered (_("Probed static tracepoint "
8966                                      "marker \"%s\"\n"),
8967                                    t->static_trace_marker_id);
8968                 }
8969               else
8970                 warning (_("Couldn't determine the static "
8971                            "tracepoint marker to probe"));
8972             }
8973
8974           loc = b->loc;
8975         }
8976       else
8977         {
8978           loc = add_location_to_breakpoint (b, &sal);
8979           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8980             loc->inserted = 1;
8981         }
8982
8983       if (b->cond_string)
8984         {
8985           const char *arg = b->cond_string;
8986
8987           loc->cond = parse_exp_1 (&arg, loc->address,
8988                                    block_for_pc (loc->address), 0);
8989           if (*arg)
8990               error (_("Garbage '%s' follows condition"), arg);
8991         }
8992
8993       /* Dynamic printf requires and uses additional arguments on the
8994          command line, otherwise it's an error.  */
8995       if (type == bp_dprintf)
8996         {
8997           if (b->extra_string)
8998             update_dprintf_command_list (b);
8999           else
9000             error (_("Format string required"));
9001         }
9002       else if (b->extra_string)
9003         error (_("Garbage '%s' at end of command"), b->extra_string);
9004     }
9005
9006   b->display_canonical = display_canonical;
9007   if (location != NULL)
9008     b->location = std::move (location);
9009   else
9010     b->location = new_address_location (b->loc->address, NULL, 0);
9011   b->filter = filter.release ();
9012 }
9013
9014 static void
9015 create_breakpoint_sal (struct gdbarch *gdbarch,
9016                        gdb::array_view<const symtab_and_line> sals,
9017                        event_location_up &&location,
9018                        gdb::unique_xmalloc_ptr<char> filter,
9019                        gdb::unique_xmalloc_ptr<char> cond_string,
9020                        gdb::unique_xmalloc_ptr<char> extra_string,
9021                        enum bptype type, enum bpdisp disposition,
9022                        int thread, int task, int ignore_count,
9023                        const struct breakpoint_ops *ops, int from_tty,
9024                        int enabled, int internal, unsigned flags,
9025                        int display_canonical)
9026 {
9027   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9028
9029   init_breakpoint_sal (b.get (), gdbarch,
9030                        sals, std::move (location),
9031                        std::move (filter),
9032                        std::move (cond_string),
9033                        std::move (extra_string),
9034                        type, disposition,
9035                        thread, task, ignore_count,
9036                        ops, from_tty,
9037                        enabled, internal, flags,
9038                        display_canonical);
9039
9040   install_breakpoint (internal, std::move (b), 0);
9041 }
9042
9043 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9044    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9045    value.  COND_STRING, if not NULL, specified the condition to be
9046    used for all breakpoints.  Essentially the only case where
9047    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9048    function.  In that case, it's still not possible to specify
9049    separate conditions for different overloaded functions, so
9050    we take just a single condition string.
9051    
9052    NOTE: If the function succeeds, the caller is expected to cleanup
9053    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9054    array contents).  If the function fails (error() is called), the
9055    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9056    COND and SALS arrays and each of those arrays contents.  */
9057
9058 static void
9059 create_breakpoints_sal (struct gdbarch *gdbarch,
9060                         struct linespec_result *canonical,
9061                         gdb::unique_xmalloc_ptr<char> cond_string,
9062                         gdb::unique_xmalloc_ptr<char> extra_string,
9063                         enum bptype type, enum bpdisp disposition,
9064                         int thread, int task, int ignore_count,
9065                         const struct breakpoint_ops *ops, int from_tty,
9066                         int enabled, int internal, unsigned flags)
9067 {
9068   if (canonical->pre_expanded)
9069     gdb_assert (canonical->lsals.size () == 1);
9070
9071   for (const auto &lsal : canonical->lsals)
9072     {
9073       /* Note that 'location' can be NULL in the case of a plain
9074          'break', without arguments.  */
9075       event_location_up location
9076         = (canonical->location != NULL
9077            ? copy_event_location (canonical->location.get ()) : NULL);
9078       gdb::unique_xmalloc_ptr<char> filter_string
9079         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9080
9081       create_breakpoint_sal (gdbarch, lsal.sals,
9082                              std::move (location),
9083                              std::move (filter_string),
9084                              std::move (cond_string),
9085                              std::move (extra_string),
9086                              type, disposition,
9087                              thread, task, ignore_count, ops,
9088                              from_tty, enabled, internal, flags,
9089                              canonical->special_display);
9090     }
9091 }
9092
9093 /* Parse LOCATION which is assumed to be a SAL specification possibly
9094    followed by conditionals.  On return, SALS contains an array of SAL
9095    addresses found.  LOCATION points to the end of the SAL (for
9096    linespec locations).
9097
9098    The array and the line spec strings are allocated on the heap, it is
9099    the caller's responsibility to free them.  */
9100
9101 static void
9102 parse_breakpoint_sals (const struct event_location *location,
9103                        struct linespec_result *canonical)
9104 {
9105   struct symtab_and_line cursal;
9106
9107   if (event_location_type (location) == LINESPEC_LOCATION)
9108     {
9109       const char *address = get_linespec_location (location);
9110
9111       if (address == NULL)
9112         {
9113           /* The last displayed codepoint, if it's valid, is our default
9114              breakpoint address.  */
9115           if (last_displayed_sal_is_valid ())
9116             {
9117               /* Set sal's pspace, pc, symtab, and line to the values
9118                  corresponding to the last call to print_frame_info.
9119                  Be sure to reinitialize LINE with NOTCURRENT == 0
9120                  as the breakpoint line number is inappropriate otherwise.
9121                  find_pc_line would adjust PC, re-set it back.  */
9122               symtab_and_line sal = get_last_displayed_sal ();
9123               CORE_ADDR pc = sal.pc;
9124
9125               sal = find_pc_line (pc, 0);
9126
9127               /* "break" without arguments is equivalent to "break *PC"
9128                  where PC is the last displayed codepoint's address.  So
9129                  make sure to set sal.explicit_pc to prevent GDB from
9130                  trying to expand the list of sals to include all other
9131                  instances with the same symtab and line.  */
9132               sal.pc = pc;
9133               sal.explicit_pc = 1;
9134
9135               struct linespec_sals lsal;
9136               lsal.sals = {sal};
9137               lsal.canonical = NULL;
9138
9139               canonical->lsals.push_back (std::move (lsal));
9140               return;
9141             }
9142           else
9143             error (_("No default breakpoint address now."));
9144         }
9145     }
9146
9147   /* Force almost all breakpoints to be in terms of the
9148      current_source_symtab (which is decode_line_1's default).
9149      This should produce the results we want almost all of the
9150      time while leaving default_breakpoint_* alone.
9151
9152      ObjC: However, don't match an Objective-C method name which
9153      may have a '+' or '-' succeeded by a '['.  */
9154   cursal = get_current_source_symtab_and_line ();
9155   if (last_displayed_sal_is_valid ())
9156     {
9157       const char *address = NULL;
9158
9159       if (event_location_type (location) == LINESPEC_LOCATION)
9160         address = get_linespec_location (location);
9161
9162       if (!cursal.symtab
9163           || (address != NULL
9164               && strchr ("+-", address[0]) != NULL
9165               && address[1] != '['))
9166         {
9167           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9168                             get_last_displayed_symtab (),
9169                             get_last_displayed_line (),
9170                             canonical, NULL, NULL);
9171           return;
9172         }
9173     }
9174
9175   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9176                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9177 }
9178
9179
9180 /* Convert each SAL into a real PC.  Verify that the PC can be
9181    inserted as a breakpoint.  If it can't throw an error.  */
9182
9183 static void
9184 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9185 {    
9186   for (auto &sal : sals)
9187     resolve_sal_pc (&sal);
9188 }
9189
9190 /* Fast tracepoints may have restrictions on valid locations.  For
9191    instance, a fast tracepoint using a jump instead of a trap will
9192    likely have to overwrite more bytes than a trap would, and so can
9193    only be placed where the instruction is longer than the jump, or a
9194    multi-instruction sequence does not have a jump into the middle of
9195    it, etc.  */
9196
9197 static void
9198 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9199                             gdb::array_view<const symtab_and_line> sals)
9200 {
9201   int rslt;
9202   char *msg;
9203   struct cleanup *old_chain;
9204
9205   for (const auto &sal : sals)
9206     {
9207       struct gdbarch *sarch;
9208
9209       sarch = get_sal_arch (sal);
9210       /* We fall back to GDBARCH if there is no architecture
9211          associated with SAL.  */
9212       if (sarch == NULL)
9213         sarch = gdbarch;
9214       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg);
9215       old_chain = make_cleanup (xfree, msg);
9216
9217       if (!rslt)
9218         error (_("May not have a fast tracepoint at %s%s"),
9219                paddress (sarch, sal.pc), (msg ? msg : ""));
9220
9221       do_cleanups (old_chain);
9222     }
9223 }
9224
9225 /* Given TOK, a string specification of condition and thread, as
9226    accepted by the 'break' command, extract the condition
9227    string and thread number and set *COND_STRING and *THREAD.
9228    PC identifies the context at which the condition should be parsed.
9229    If no condition is found, *COND_STRING is set to NULL.
9230    If no thread is found, *THREAD is set to -1.  */
9231
9232 static void
9233 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9234                            char **cond_string, int *thread, int *task,
9235                            char **rest)
9236 {
9237   *cond_string = NULL;
9238   *thread = -1;
9239   *task = 0;
9240   *rest = NULL;
9241
9242   while (tok && *tok)
9243     {
9244       const char *end_tok;
9245       int toklen;
9246       const char *cond_start = NULL;
9247       const char *cond_end = NULL;
9248
9249       tok = skip_spaces (tok);
9250
9251       if ((*tok == '"' || *tok == ',') && rest)
9252         {
9253           *rest = savestring (tok, strlen (tok));
9254           return;
9255         }
9256
9257       end_tok = skip_to_space (tok);
9258
9259       toklen = end_tok - tok;
9260
9261       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9262         {
9263           tok = cond_start = end_tok + 1;
9264           parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9265           cond_end = tok;
9266           *cond_string = savestring (cond_start, cond_end - cond_start);
9267         }
9268       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9269         {
9270           const char *tmptok;
9271           struct thread_info *thr;
9272
9273           tok = end_tok + 1;
9274           thr = parse_thread_id (tok, &tmptok);
9275           if (tok == tmptok)
9276             error (_("Junk after thread keyword."));
9277           *thread = thr->global_num;
9278           tok = tmptok;
9279         }
9280       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9281         {
9282           char *tmptok;
9283
9284           tok = end_tok + 1;
9285           *task = strtol (tok, &tmptok, 0);
9286           if (tok == tmptok)
9287             error (_("Junk after task keyword."));
9288           if (!valid_task_id (*task))
9289             error (_("Unknown task %d."), *task);
9290           tok = tmptok;
9291         }
9292       else if (rest)
9293         {
9294           *rest = savestring (tok, strlen (tok));
9295           return;
9296         }
9297       else
9298         error (_("Junk at end of arguments."));
9299     }
9300 }
9301
9302 /* Decode a static tracepoint marker spec.  */
9303
9304 static std::vector<symtab_and_line>
9305 decode_static_tracepoint_spec (const char **arg_p)
9306 {
9307   VEC(static_tracepoint_marker_p) *markers = NULL;
9308   const char *p = &(*arg_p)[3];
9309   const char *endp;
9310   int i;
9311
9312   p = skip_spaces (p);
9313
9314   endp = skip_to_space (p);
9315
9316   std::string marker_str (p, endp - p);
9317
9318   markers = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9319   if (VEC_empty(static_tracepoint_marker_p, markers))
9320     error (_("No known static tracepoint marker named %s"),
9321            marker_str.c_str ());
9322
9323   std::vector<symtab_and_line> sals;
9324   sals.reserve (VEC_length(static_tracepoint_marker_p, markers));
9325
9326   for (i = 0; i < VEC_length(static_tracepoint_marker_p, markers); i++)
9327     {
9328       struct static_tracepoint_marker *marker;
9329
9330       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9331
9332       symtab_and_line sal = find_pc_line (marker->address, 0);
9333       sal.pc = marker->address;
9334       sals.push_back (sal);
9335
9336       release_static_tracepoint_marker (marker);
9337     }
9338
9339   *arg_p = endp;
9340   return sals;
9341 }
9342
9343 /* See breakpoint.h.  */
9344
9345 int
9346 create_breakpoint (struct gdbarch *gdbarch,
9347                    const struct event_location *location,
9348                    const char *cond_string,
9349                    int thread, const char *extra_string,
9350                    int parse_extra,
9351                    int tempflag, enum bptype type_wanted,
9352                    int ignore_count,
9353                    enum auto_boolean pending_break_support,
9354                    const struct breakpoint_ops *ops,
9355                    int from_tty, int enabled, int internal,
9356                    unsigned flags)
9357 {
9358   struct linespec_result canonical;
9359   struct cleanup *bkpt_chain = NULL;
9360   int pending = 0;
9361   int task = 0;
9362   int prev_bkpt_count = breakpoint_count;
9363
9364   gdb_assert (ops != NULL);
9365
9366   /* If extra_string isn't useful, set it to NULL.  */
9367   if (extra_string != NULL && *extra_string == '\0')
9368     extra_string = NULL;
9369
9370   TRY
9371     {
9372       ops->create_sals_from_location (location, &canonical, type_wanted);
9373     }
9374   CATCH (e, RETURN_MASK_ERROR)
9375     {
9376       /* If caller is interested in rc value from parse, set
9377          value.  */
9378       if (e.error == NOT_FOUND_ERROR)
9379         {
9380           /* If pending breakpoint support is turned off, throw
9381              error.  */
9382
9383           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9384             throw_exception (e);
9385
9386           exception_print (gdb_stderr, e);
9387
9388           /* If pending breakpoint support is auto query and the user
9389              selects no, then simply return the error code.  */
9390           if (pending_break_support == AUTO_BOOLEAN_AUTO
9391               && !nquery (_("Make %s pending on future shared library load? "),
9392                           bptype_string (type_wanted)))
9393             return 0;
9394
9395           /* At this point, either the user was queried about setting
9396              a pending breakpoint and selected yes, or pending
9397              breakpoint behavior is on and thus a pending breakpoint
9398              is defaulted on behalf of the user.  */
9399           pending = 1;
9400         }
9401       else
9402         throw_exception (e);
9403     }
9404   END_CATCH
9405
9406   if (!pending && canonical.lsals.empty ())
9407     return 0;
9408
9409   /* ----------------------------- SNIP -----------------------------
9410      Anything added to the cleanup chain beyond this point is assumed
9411      to be part of a breakpoint.  If the breakpoint create succeeds
9412      then the memory is not reclaimed.  */
9413   bkpt_chain = make_cleanup (null_cleanup, 0);
9414
9415   /* Resolve all line numbers to PC's and verify that the addresses
9416      are ok for the target.  */
9417   if (!pending)
9418     {
9419       for (auto &lsal : canonical.lsals)
9420         breakpoint_sals_to_pc (lsal.sals);
9421     }
9422
9423   /* Fast tracepoints may have additional restrictions on location.  */
9424   if (!pending && type_wanted == bp_fast_tracepoint)
9425     {
9426       for (const auto &lsal : canonical.lsals)
9427         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9428     }
9429
9430   /* Verify that condition can be parsed, before setting any
9431      breakpoints.  Allocate a separate condition expression for each
9432      breakpoint.  */
9433   if (!pending)
9434     {
9435       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9436       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9437
9438       if (parse_extra)
9439         {
9440           char *rest;
9441           char *cond;
9442
9443           const linespec_sals &lsal = canonical.lsals[0];
9444
9445           /* Here we only parse 'arg' to separate condition
9446              from thread number, so parsing in context of first
9447              sal is OK.  When setting the breakpoint we'll
9448              re-parse it in context of each sal.  */
9449
9450           find_condition_and_thread (extra_string, lsal.sals[0].pc,
9451                                      &cond, &thread, &task, &rest);
9452           cond_string_copy.reset (cond);
9453           extra_string_copy.reset (rest);
9454         }
9455       else
9456         {
9457           if (type_wanted != bp_dprintf
9458               && extra_string != NULL && *extra_string != '\0')
9459                 error (_("Garbage '%s' at end of location"), extra_string);
9460
9461           /* Create a private copy of condition string.  */
9462           if (cond_string)
9463             cond_string_copy.reset (xstrdup (cond_string));
9464           /* Create a private copy of any extra string.  */
9465           if (extra_string)
9466             extra_string_copy.reset (xstrdup (extra_string));
9467         }
9468
9469       ops->create_breakpoints_sal (gdbarch, &canonical,
9470                                    std::move (cond_string_copy),
9471                                    std::move (extra_string_copy),
9472                                    type_wanted,
9473                                    tempflag ? disp_del : disp_donttouch,
9474                                    thread, task, ignore_count, ops,
9475                                    from_tty, enabled, internal, flags);
9476     }
9477   else
9478     {
9479       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9480
9481       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9482       b->location = copy_event_location (location);
9483
9484       if (parse_extra)
9485         b->cond_string = NULL;
9486       else
9487         {
9488           /* Create a private copy of condition string.  */
9489           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9490           b->thread = thread;
9491         }
9492
9493       /* Create a private copy of any extra string.  */
9494       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9495       b->ignore_count = ignore_count;
9496       b->disposition = tempflag ? disp_del : disp_donttouch;
9497       b->condition_not_parsed = 1;
9498       b->enable_state = enabled ? bp_enabled : bp_disabled;
9499       if ((type_wanted != bp_breakpoint
9500            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9501         b->pspace = current_program_space;
9502
9503       install_breakpoint (internal, std::move (b), 0);
9504     }
9505   
9506   if (canonical.lsals.size () > 1)
9507     {
9508       warning (_("Multiple breakpoints were set.\nUse the "
9509                  "\"delete\" command to delete unwanted breakpoints."));
9510       prev_breakpoint_count = prev_bkpt_count;
9511     }
9512
9513   /* That's it.  Discard the cleanups for data inserted into the
9514      breakpoint.  */
9515   discard_cleanups (bkpt_chain);
9516
9517   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9518   update_global_location_list (UGLL_MAY_INSERT);
9519
9520   return 1;
9521 }
9522
9523 /* Set a breakpoint.
9524    ARG is a string describing breakpoint address,
9525    condition, and thread.
9526    FLAG specifies if a breakpoint is hardware on,
9527    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9528    and BP_TEMPFLAG.  */
9529
9530 static void
9531 break_command_1 (const char *arg, int flag, int from_tty)
9532 {
9533   int tempflag = flag & BP_TEMPFLAG;
9534   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9535                              ? bp_hardware_breakpoint
9536                              : bp_breakpoint);
9537   struct breakpoint_ops *ops;
9538
9539   event_location_up location = string_to_event_location (&arg, current_language);
9540
9541   /* Matching breakpoints on probes.  */
9542   if (location != NULL
9543       && event_location_type (location.get ()) == PROBE_LOCATION)
9544     ops = &bkpt_probe_breakpoint_ops;
9545   else
9546     ops = &bkpt_breakpoint_ops;
9547
9548   create_breakpoint (get_current_arch (),
9549                      location.get (),
9550                      NULL, 0, arg, 1 /* parse arg */,
9551                      tempflag, type_wanted,
9552                      0 /* Ignore count */,
9553                      pending_break_support,
9554                      ops,
9555                      from_tty,
9556                      1 /* enabled */,
9557                      0 /* internal */,
9558                      0);
9559 }
9560
9561 /* Helper function for break_command_1 and disassemble_command.  */
9562
9563 void
9564 resolve_sal_pc (struct symtab_and_line *sal)
9565 {
9566   CORE_ADDR pc;
9567
9568   if (sal->pc == 0 && sal->symtab != NULL)
9569     {
9570       if (!find_line_pc (sal->symtab, sal->line, &pc))
9571         error (_("No line %d in file \"%s\"."),
9572                sal->line, symtab_to_filename_for_display (sal->symtab));
9573       sal->pc = pc;
9574
9575       /* If this SAL corresponds to a breakpoint inserted using a line
9576          number, then skip the function prologue if necessary.  */
9577       if (sal->explicit_line)
9578         skip_prologue_sal (sal);
9579     }
9580
9581   if (sal->section == 0 && sal->symtab != NULL)
9582     {
9583       const struct blockvector *bv;
9584       const struct block *b;
9585       struct symbol *sym;
9586
9587       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9588                                     SYMTAB_COMPUNIT (sal->symtab));
9589       if (bv != NULL)
9590         {
9591           sym = block_linkage_function (b);
9592           if (sym != NULL)
9593             {
9594               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9595               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9596                                                  sym);
9597             }
9598           else
9599             {
9600               /* It really is worthwhile to have the section, so we'll
9601                  just have to look harder. This case can be executed
9602                  if we have line numbers but no functions (as can
9603                  happen in assembly source).  */
9604
9605               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9606               switch_to_program_space_and_thread (sal->pspace);
9607
9608               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9609               if (msym.minsym)
9610                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9611             }
9612         }
9613     }
9614 }
9615
9616 void
9617 break_command (const char *arg, int from_tty)
9618 {
9619   break_command_1 (arg, 0, from_tty);
9620 }
9621
9622 void
9623 tbreak_command (const char *arg, int from_tty)
9624 {
9625   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9626 }
9627
9628 static void
9629 hbreak_command (const char *arg, int from_tty)
9630 {
9631   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9632 }
9633
9634 static void
9635 thbreak_command (const char *arg, int from_tty)
9636 {
9637   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9638 }
9639
9640 static void
9641 stop_command (const char *arg, int from_tty)
9642 {
9643   printf_filtered (_("Specify the type of breakpoint to set.\n\
9644 Usage: stop in <function | address>\n\
9645        stop at <line>\n"));
9646 }
9647
9648 static void
9649 stopin_command (const char *arg, int from_tty)
9650 {
9651   int badInput = 0;
9652
9653   if (arg == (char *) NULL)
9654     badInput = 1;
9655   else if (*arg != '*')
9656     {
9657       const char *argptr = arg;
9658       int hasColon = 0;
9659
9660       /* Look for a ':'.  If this is a line number specification, then
9661          say it is bad, otherwise, it should be an address or
9662          function/method name.  */
9663       while (*argptr && !hasColon)
9664         {
9665           hasColon = (*argptr == ':');
9666           argptr++;
9667         }
9668
9669       if (hasColon)
9670         badInput = (*argptr != ':');    /* Not a class::method */
9671       else
9672         badInput = isdigit (*arg);      /* a simple line number */
9673     }
9674
9675   if (badInput)
9676     printf_filtered (_("Usage: stop in <function | address>\n"));
9677   else
9678     break_command_1 (arg, 0, from_tty);
9679 }
9680
9681 static void
9682 stopat_command (const char *arg, int from_tty)
9683 {
9684   int badInput = 0;
9685
9686   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9687     badInput = 1;
9688   else
9689     {
9690       const char *argptr = arg;
9691       int hasColon = 0;
9692
9693       /* Look for a ':'.  If there is a '::' then get out, otherwise
9694          it is probably a line number.  */
9695       while (*argptr && !hasColon)
9696         {
9697           hasColon = (*argptr == ':');
9698           argptr++;
9699         }
9700
9701       if (hasColon)
9702         badInput = (*argptr == ':');    /* we have class::method */
9703       else
9704         badInput = !isdigit (*arg);     /* not a line number */
9705     }
9706
9707   if (badInput)
9708     printf_filtered (_("Usage: stop at <line>\n"));
9709   else
9710     break_command_1 (arg, 0, from_tty);
9711 }
9712
9713 /* The dynamic printf command is mostly like a regular breakpoint, but
9714    with a prewired command list consisting of a single output command,
9715    built from extra arguments supplied on the dprintf command
9716    line.  */
9717
9718 static void
9719 dprintf_command (const char *arg, int from_tty)
9720 {
9721   event_location_up location = string_to_event_location (&arg, current_language);
9722
9723   /* If non-NULL, ARG should have been advanced past the location;
9724      the next character must be ','.  */
9725   if (arg != NULL)
9726     {
9727       if (arg[0] != ',' || arg[1] == '\0')
9728         error (_("Format string required"));
9729       else
9730         {
9731           /* Skip the comma.  */
9732           ++arg;
9733         }
9734     }
9735
9736   create_breakpoint (get_current_arch (),
9737                      location.get (),
9738                      NULL, 0, arg, 1 /* parse arg */,
9739                      0, bp_dprintf,
9740                      0 /* Ignore count */,
9741                      pending_break_support,
9742                      &dprintf_breakpoint_ops,
9743                      from_tty,
9744                      1 /* enabled */,
9745                      0 /* internal */,
9746                      0);
9747 }
9748
9749 static void
9750 agent_printf_command (const char *arg, int from_tty)
9751 {
9752   error (_("May only run agent-printf on the target"));
9753 }
9754
9755 /* Implement the "breakpoint_hit" breakpoint_ops method for
9756    ranged breakpoints.  */
9757
9758 static int
9759 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9760                                   const address_space *aspace,
9761                                   CORE_ADDR bp_addr,
9762                                   const struct target_waitstatus *ws)
9763 {
9764   if (ws->kind != TARGET_WAITKIND_STOPPED
9765       || ws->value.sig != GDB_SIGNAL_TRAP)
9766     return 0;
9767
9768   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9769                                          bl->length, aspace, bp_addr);
9770 }
9771
9772 /* Implement the "resources_needed" breakpoint_ops method for
9773    ranged breakpoints.  */
9774
9775 static int
9776 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9777 {
9778   return target_ranged_break_num_registers ();
9779 }
9780
9781 /* Implement the "print_it" breakpoint_ops method for
9782    ranged breakpoints.  */
9783
9784 static enum print_stop_action
9785 print_it_ranged_breakpoint (bpstat bs)
9786 {
9787   struct breakpoint *b = bs->breakpoint_at;
9788   struct bp_location *bl = b->loc;
9789   struct ui_out *uiout = current_uiout;
9790
9791   gdb_assert (b->type == bp_hardware_breakpoint);
9792
9793   /* Ranged breakpoints have only one location.  */
9794   gdb_assert (bl && bl->next == NULL);
9795
9796   annotate_breakpoint (b->number);
9797
9798   maybe_print_thread_hit_breakpoint (uiout);
9799
9800   if (b->disposition == disp_del)
9801     uiout->text ("Temporary ranged breakpoint ");
9802   else
9803     uiout->text ("Ranged breakpoint ");
9804   if (uiout->is_mi_like_p ())
9805     {
9806       uiout->field_string ("reason",
9807                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9808       uiout->field_string ("disp", bpdisp_text (b->disposition));
9809     }
9810   uiout->field_int ("bkptno", b->number);
9811   uiout->text (", ");
9812
9813   return PRINT_SRC_AND_LOC;
9814 }
9815
9816 /* Implement the "print_one" breakpoint_ops method for
9817    ranged breakpoints.  */
9818
9819 static void
9820 print_one_ranged_breakpoint (struct breakpoint *b,
9821                              struct bp_location **last_loc)
9822 {
9823   struct bp_location *bl = b->loc;
9824   struct value_print_options opts;
9825   struct ui_out *uiout = current_uiout;
9826
9827   /* Ranged breakpoints have only one location.  */
9828   gdb_assert (bl && bl->next == NULL);
9829
9830   get_user_print_options (&opts);
9831
9832   if (opts.addressprint)
9833     /* We don't print the address range here, it will be printed later
9834        by print_one_detail_ranged_breakpoint.  */
9835     uiout->field_skip ("addr");
9836   annotate_field (5);
9837   print_breakpoint_location (b, bl);
9838   *last_loc = bl;
9839 }
9840
9841 /* Implement the "print_one_detail" breakpoint_ops method for
9842    ranged breakpoints.  */
9843
9844 static void
9845 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9846                                     struct ui_out *uiout)
9847 {
9848   CORE_ADDR address_start, address_end;
9849   struct bp_location *bl = b->loc;
9850   string_file stb;
9851
9852   gdb_assert (bl);
9853
9854   address_start = bl->address;
9855   address_end = address_start + bl->length - 1;
9856
9857   uiout->text ("\taddress range: ");
9858   stb.printf ("[%s, %s]",
9859               print_core_address (bl->gdbarch, address_start),
9860               print_core_address (bl->gdbarch, address_end));
9861   uiout->field_stream ("addr", stb);
9862   uiout->text ("\n");
9863 }
9864
9865 /* Implement the "print_mention" breakpoint_ops method for
9866    ranged breakpoints.  */
9867
9868 static void
9869 print_mention_ranged_breakpoint (struct breakpoint *b)
9870 {
9871   struct bp_location *bl = b->loc;
9872   struct ui_out *uiout = current_uiout;
9873
9874   gdb_assert (bl);
9875   gdb_assert (b->type == bp_hardware_breakpoint);
9876
9877   if (uiout->is_mi_like_p ())
9878     return;
9879
9880   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9881                    b->number, paddress (bl->gdbarch, bl->address),
9882                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9883 }
9884
9885 /* Implement the "print_recreate" breakpoint_ops method for
9886    ranged breakpoints.  */
9887
9888 static void
9889 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9890 {
9891   fprintf_unfiltered (fp, "break-range %s, %s",
9892                       event_location_to_string (b->location.get ()),
9893                       event_location_to_string (b->location_range_end.get ()));
9894   print_recreate_thread (b, fp);
9895 }
9896
9897 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9898
9899 static struct breakpoint_ops ranged_breakpoint_ops;
9900
9901 /* Find the address where the end of the breakpoint range should be
9902    placed, given the SAL of the end of the range.  This is so that if
9903    the user provides a line number, the end of the range is set to the
9904    last instruction of the given line.  */
9905
9906 static CORE_ADDR
9907 find_breakpoint_range_end (struct symtab_and_line sal)
9908 {
9909   CORE_ADDR end;
9910
9911   /* If the user provided a PC value, use it.  Otherwise,
9912      find the address of the end of the given location.  */
9913   if (sal.explicit_pc)
9914     end = sal.pc;
9915   else
9916     {
9917       int ret;
9918       CORE_ADDR start;
9919
9920       ret = find_line_pc_range (sal, &start, &end);
9921       if (!ret)
9922         error (_("Could not find location of the end of the range."));
9923
9924       /* find_line_pc_range returns the start of the next line.  */
9925       end--;
9926     }
9927
9928   return end;
9929 }
9930
9931 /* Implement the "break-range" CLI command.  */
9932
9933 static void
9934 break_range_command (const char *arg, int from_tty)
9935 {
9936   const char *arg_start;
9937   struct linespec_result canonical_start, canonical_end;
9938   int bp_count, can_use_bp, length;
9939   CORE_ADDR end;
9940   struct breakpoint *b;
9941
9942   /* We don't support software ranged breakpoints.  */
9943   if (target_ranged_break_num_registers () < 0)
9944     error (_("This target does not support hardware ranged breakpoints."));
9945
9946   bp_count = hw_breakpoint_used_count ();
9947   bp_count += target_ranged_break_num_registers ();
9948   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9949                                                    bp_count, 0);
9950   if (can_use_bp < 0)
9951     error (_("Hardware breakpoints used exceeds limit."));
9952
9953   arg = skip_spaces (arg);
9954   if (arg == NULL || arg[0] == '\0')
9955     error(_("No address range specified."));
9956
9957   arg_start = arg;
9958   event_location_up start_location = string_to_event_location (&arg,
9959                                                                current_language);
9960   parse_breakpoint_sals (start_location.get (), &canonical_start);
9961
9962   if (arg[0] != ',')
9963     error (_("Too few arguments."));
9964   else if (canonical_start.lsals.empty ())
9965     error (_("Could not find location of the beginning of the range."));
9966
9967   const linespec_sals &lsal_start = canonical_start.lsals[0];
9968
9969   if (canonical_start.lsals.size () > 1
9970       || lsal_start.sals.size () != 1)
9971     error (_("Cannot create a ranged breakpoint with multiple locations."));
9972
9973   const symtab_and_line &sal_start = lsal_start.sals[0];
9974   std::string addr_string_start (arg_start, arg - arg_start);
9975
9976   arg++;        /* Skip the comma.  */
9977   arg = skip_spaces (arg);
9978
9979   /* Parse the end location.  */
9980
9981   arg_start = arg;
9982
9983   /* We call decode_line_full directly here instead of using
9984      parse_breakpoint_sals because we need to specify the start location's
9985      symtab and line as the default symtab and line for the end of the
9986      range.  This makes it possible to have ranges like "foo.c:27, +14",
9987      where +14 means 14 lines from the start location.  */
9988   event_location_up end_location = string_to_event_location (&arg,
9989                                                              current_language);
9990   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9991                     sal_start.symtab, sal_start.line,
9992                     &canonical_end, NULL, NULL);
9993
9994   if (canonical_end.lsals.empty ())
9995     error (_("Could not find location of the end of the range."));
9996
9997   const linespec_sals &lsal_end = canonical_end.lsals[0];
9998   if (canonical_end.lsals.size () > 1
9999       || lsal_end.sals.size () != 1)
10000     error (_("Cannot create a ranged breakpoint with multiple locations."));
10001
10002   const symtab_and_line &sal_end = lsal_end.sals[0];
10003
10004   end = find_breakpoint_range_end (sal_end);
10005   if (sal_start.pc > end)
10006     error (_("Invalid address range, end precedes start."));
10007
10008   length = end - sal_start.pc + 1;
10009   if (length < 0)
10010     /* Length overflowed.  */
10011     error (_("Address range too large."));
10012   else if (length == 1)
10013     {
10014       /* This range is simple enough to be handled by
10015          the `hbreak' command.  */
10016       hbreak_command (&addr_string_start[0], 1);
10017
10018       return;
10019     }
10020
10021   /* Now set up the breakpoint.  */
10022   b = set_raw_breakpoint (get_current_arch (), sal_start,
10023                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10024   set_breakpoint_count (breakpoint_count + 1);
10025   b->number = breakpoint_count;
10026   b->disposition = disp_donttouch;
10027   b->location = std::move (start_location);
10028   b->location_range_end = std::move (end_location);
10029   b->loc->length = length;
10030
10031   mention (b);
10032   observer_notify_breakpoint_created (b);
10033   update_global_location_list (UGLL_MAY_INSERT);
10034 }
10035
10036 /*  Return non-zero if EXP is verified as constant.  Returned zero
10037     means EXP is variable.  Also the constant detection may fail for
10038     some constant expressions and in such case still falsely return
10039     zero.  */
10040
10041 static int
10042 watchpoint_exp_is_const (const struct expression *exp)
10043 {
10044   int i = exp->nelts;
10045
10046   while (i > 0)
10047     {
10048       int oplenp, argsp;
10049
10050       /* We are only interested in the descriptor of each element.  */
10051       operator_length (exp, i, &oplenp, &argsp);
10052       i -= oplenp;
10053
10054       switch (exp->elts[i].opcode)
10055         {
10056         case BINOP_ADD:
10057         case BINOP_SUB:
10058         case BINOP_MUL:
10059         case BINOP_DIV:
10060         case BINOP_REM:
10061         case BINOP_MOD:
10062         case BINOP_LSH:
10063         case BINOP_RSH:
10064         case BINOP_LOGICAL_AND:
10065         case BINOP_LOGICAL_OR:
10066         case BINOP_BITWISE_AND:
10067         case BINOP_BITWISE_IOR:
10068         case BINOP_BITWISE_XOR:
10069         case BINOP_EQUAL:
10070         case BINOP_NOTEQUAL:
10071         case BINOP_LESS:
10072         case BINOP_GTR:
10073         case BINOP_LEQ:
10074         case BINOP_GEQ:
10075         case BINOP_REPEAT:
10076         case BINOP_COMMA:
10077         case BINOP_EXP:
10078         case BINOP_MIN:
10079         case BINOP_MAX:
10080         case BINOP_INTDIV:
10081         case BINOP_CONCAT:
10082         case TERNOP_COND:
10083         case TERNOP_SLICE:
10084
10085         case OP_LONG:
10086         case OP_FLOAT:
10087         case OP_LAST:
10088         case OP_COMPLEX:
10089         case OP_STRING:
10090         case OP_ARRAY:
10091         case OP_TYPE:
10092         case OP_TYPEOF:
10093         case OP_DECLTYPE:
10094         case OP_TYPEID:
10095         case OP_NAME:
10096         case OP_OBJC_NSSTRING:
10097
10098         case UNOP_NEG:
10099         case UNOP_LOGICAL_NOT:
10100         case UNOP_COMPLEMENT:
10101         case UNOP_ADDR:
10102         case UNOP_HIGH:
10103         case UNOP_CAST:
10104
10105         case UNOP_CAST_TYPE:
10106         case UNOP_REINTERPRET_CAST:
10107         case UNOP_DYNAMIC_CAST:
10108           /* Unary, binary and ternary operators: We have to check
10109              their operands.  If they are constant, then so is the
10110              result of that operation.  For instance, if A and B are
10111              determined to be constants, then so is "A + B".
10112
10113              UNOP_IND is one exception to the rule above, because the
10114              value of *ADDR is not necessarily a constant, even when
10115              ADDR is.  */
10116           break;
10117
10118         case OP_VAR_VALUE:
10119           /* Check whether the associated symbol is a constant.
10120
10121              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10122              possible that a buggy compiler could mark a variable as
10123              constant even when it is not, and TYPE_CONST would return
10124              true in this case, while SYMBOL_CLASS wouldn't.
10125
10126              We also have to check for function symbols because they
10127              are always constant.  */
10128           {
10129             struct symbol *s = exp->elts[i + 2].symbol;
10130
10131             if (SYMBOL_CLASS (s) != LOC_BLOCK
10132                 && SYMBOL_CLASS (s) != LOC_CONST
10133                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10134               return 0;
10135             break;
10136           }
10137
10138         /* The default action is to return 0 because we are using
10139            the optimistic approach here: If we don't know something,
10140            then it is not a constant.  */
10141         default:
10142           return 0;
10143         }
10144     }
10145
10146   return 1;
10147 }
10148
10149 /* Watchpoint destructor.  */
10150
10151 watchpoint::~watchpoint ()
10152 {
10153   xfree (this->exp_string);
10154   xfree (this->exp_string_reparse);
10155   value_free (this->val);
10156 }
10157
10158 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10159
10160 static void
10161 re_set_watchpoint (struct breakpoint *b)
10162 {
10163   struct watchpoint *w = (struct watchpoint *) b;
10164
10165   /* Watchpoint can be either on expression using entirely global
10166      variables, or it can be on local variables.
10167
10168      Watchpoints of the first kind are never auto-deleted, and even
10169      persist across program restarts.  Since they can use variables
10170      from shared libraries, we need to reparse expression as libraries
10171      are loaded and unloaded.
10172
10173      Watchpoints on local variables can also change meaning as result
10174      of solib event.  For example, if a watchpoint uses both a local
10175      and a global variables in expression, it's a local watchpoint,
10176      but unloading of a shared library will make the expression
10177      invalid.  This is not a very common use case, but we still
10178      re-evaluate expression, to avoid surprises to the user.
10179
10180      Note that for local watchpoints, we re-evaluate it only if
10181      watchpoints frame id is still valid.  If it's not, it means the
10182      watchpoint is out of scope and will be deleted soon.  In fact,
10183      I'm not sure we'll ever be called in this case.
10184
10185      If a local watchpoint's frame id is still valid, then
10186      w->exp_valid_block is likewise valid, and we can safely use it.
10187
10188      Don't do anything about disabled watchpoints, since they will be
10189      reevaluated again when enabled.  */
10190   update_watchpoint (w, 1 /* reparse */);
10191 }
10192
10193 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10194
10195 static int
10196 insert_watchpoint (struct bp_location *bl)
10197 {
10198   struct watchpoint *w = (struct watchpoint *) bl->owner;
10199   int length = w->exact ? 1 : bl->length;
10200
10201   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10202                                    w->cond_exp.get ());
10203 }
10204
10205 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10206
10207 static int
10208 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10209 {
10210   struct watchpoint *w = (struct watchpoint *) bl->owner;
10211   int length = w->exact ? 1 : bl->length;
10212
10213   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10214                                    w->cond_exp.get ());
10215 }
10216
10217 static int
10218 breakpoint_hit_watchpoint (const struct bp_location *bl,
10219                            const address_space *aspace, CORE_ADDR bp_addr,
10220                            const struct target_waitstatus *ws)
10221 {
10222   struct breakpoint *b = bl->owner;
10223   struct watchpoint *w = (struct watchpoint *) b;
10224
10225   /* Continuable hardware watchpoints are treated as non-existent if the
10226      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10227      some data address).  Otherwise gdb won't stop on a break instruction
10228      in the code (not from a breakpoint) when a hardware watchpoint has
10229      been defined.  Also skip watchpoints which we know did not trigger
10230      (did not match the data address).  */
10231   if (is_hardware_watchpoint (b)
10232       && w->watchpoint_triggered == watch_triggered_no)
10233     return 0;
10234
10235   return 1;
10236 }
10237
10238 static void
10239 check_status_watchpoint (bpstat bs)
10240 {
10241   gdb_assert (is_watchpoint (bs->breakpoint_at));
10242
10243   bpstat_check_watchpoint (bs);
10244 }
10245
10246 /* Implement the "resources_needed" breakpoint_ops method for
10247    hardware watchpoints.  */
10248
10249 static int
10250 resources_needed_watchpoint (const struct bp_location *bl)
10251 {
10252   struct watchpoint *w = (struct watchpoint *) bl->owner;
10253   int length = w->exact? 1 : bl->length;
10254
10255   return target_region_ok_for_hw_watchpoint (bl->address, length);
10256 }
10257
10258 /* Implement the "works_in_software_mode" breakpoint_ops method for
10259    hardware watchpoints.  */
10260
10261 static int
10262 works_in_software_mode_watchpoint (const struct breakpoint *b)
10263 {
10264   /* Read and access watchpoints only work with hardware support.  */
10265   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10266 }
10267
10268 static enum print_stop_action
10269 print_it_watchpoint (bpstat bs)
10270 {
10271   struct breakpoint *b;
10272   enum print_stop_action result;
10273   struct watchpoint *w;
10274   struct ui_out *uiout = current_uiout;
10275
10276   gdb_assert (bs->bp_location_at != NULL);
10277
10278   b = bs->breakpoint_at;
10279   w = (struct watchpoint *) b;
10280
10281   annotate_watchpoint (b->number);
10282   maybe_print_thread_hit_breakpoint (uiout);
10283
10284   string_file stb;
10285
10286   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10287   switch (b->type)
10288     {
10289     case bp_watchpoint:
10290     case bp_hardware_watchpoint:
10291       if (uiout->is_mi_like_p ())
10292         uiout->field_string
10293           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10294       mention (b);
10295       tuple_emitter.emplace (uiout, "value");
10296       uiout->text ("\nOld value = ");
10297       watchpoint_value_print (bs->old_val, &stb);
10298       uiout->field_stream ("old", stb);
10299       uiout->text ("\nNew value = ");
10300       watchpoint_value_print (w->val, &stb);
10301       uiout->field_stream ("new", stb);
10302       uiout->text ("\n");
10303       /* More than one watchpoint may have been triggered.  */
10304       result = PRINT_UNKNOWN;
10305       break;
10306
10307     case bp_read_watchpoint:
10308       if (uiout->is_mi_like_p ())
10309         uiout->field_string
10310           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10311       mention (b);
10312       tuple_emitter.emplace (uiout, "value");
10313       uiout->text ("\nValue = ");
10314       watchpoint_value_print (w->val, &stb);
10315       uiout->field_stream ("value", stb);
10316       uiout->text ("\n");
10317       result = PRINT_UNKNOWN;
10318       break;
10319
10320     case bp_access_watchpoint:
10321       if (bs->old_val != NULL)
10322         {
10323           if (uiout->is_mi_like_p ())
10324             uiout->field_string
10325               ("reason",
10326                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10327           mention (b);
10328           tuple_emitter.emplace (uiout, "value");
10329           uiout->text ("\nOld value = ");
10330           watchpoint_value_print (bs->old_val, &stb);
10331           uiout->field_stream ("old", stb);
10332           uiout->text ("\nNew value = ");
10333         }
10334       else
10335         {
10336           mention (b);
10337           if (uiout->is_mi_like_p ())
10338             uiout->field_string
10339               ("reason",
10340                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10341           tuple_emitter.emplace (uiout, "value");
10342           uiout->text ("\nValue = ");
10343         }
10344       watchpoint_value_print (w->val, &stb);
10345       uiout->field_stream ("new", stb);
10346       uiout->text ("\n");
10347       result = PRINT_UNKNOWN;
10348       break;
10349     default:
10350       result = PRINT_UNKNOWN;
10351     }
10352
10353   return result;
10354 }
10355
10356 /* Implement the "print_mention" breakpoint_ops method for hardware
10357    watchpoints.  */
10358
10359 static void
10360 print_mention_watchpoint (struct breakpoint *b)
10361 {
10362   struct watchpoint *w = (struct watchpoint *) b;
10363   struct ui_out *uiout = current_uiout;
10364   const char *tuple_name;
10365
10366   switch (b->type)
10367     {
10368     case bp_watchpoint:
10369       uiout->text ("Watchpoint ");
10370       tuple_name = "wpt";
10371       break;
10372     case bp_hardware_watchpoint:
10373       uiout->text ("Hardware watchpoint ");
10374       tuple_name = "wpt";
10375       break;
10376     case bp_read_watchpoint:
10377       uiout->text ("Hardware read watchpoint ");
10378       tuple_name = "hw-rwpt";
10379       break;
10380     case bp_access_watchpoint:
10381       uiout->text ("Hardware access (read/write) watchpoint ");
10382       tuple_name = "hw-awpt";
10383       break;
10384     default:
10385       internal_error (__FILE__, __LINE__,
10386                       _("Invalid hardware watchpoint type."));
10387     }
10388
10389   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10390   uiout->field_int ("number", b->number);
10391   uiout->text (": ");
10392   uiout->field_string ("exp", w->exp_string);
10393 }
10394
10395 /* Implement the "print_recreate" breakpoint_ops method for
10396    watchpoints.  */
10397
10398 static void
10399 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10400 {
10401   struct watchpoint *w = (struct watchpoint *) b;
10402
10403   switch (b->type)
10404     {
10405     case bp_watchpoint:
10406     case bp_hardware_watchpoint:
10407       fprintf_unfiltered (fp, "watch");
10408       break;
10409     case bp_read_watchpoint:
10410       fprintf_unfiltered (fp, "rwatch");
10411       break;
10412     case bp_access_watchpoint:
10413       fprintf_unfiltered (fp, "awatch");
10414       break;
10415     default:
10416       internal_error (__FILE__, __LINE__,
10417                       _("Invalid watchpoint type."));
10418     }
10419
10420   fprintf_unfiltered (fp, " %s", w->exp_string);
10421   print_recreate_thread (b, fp);
10422 }
10423
10424 /* Implement the "explains_signal" breakpoint_ops method for
10425    watchpoints.  */
10426
10427 static int
10428 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10429 {
10430   /* A software watchpoint cannot cause a signal other than
10431      GDB_SIGNAL_TRAP.  */
10432   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10433     return 0;
10434
10435   return 1;
10436 }
10437
10438 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10439
10440 static struct breakpoint_ops watchpoint_breakpoint_ops;
10441
10442 /* Implement the "insert" breakpoint_ops method for
10443    masked hardware watchpoints.  */
10444
10445 static int
10446 insert_masked_watchpoint (struct bp_location *bl)
10447 {
10448   struct watchpoint *w = (struct watchpoint *) bl->owner;
10449
10450   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10451                                         bl->watchpoint_type);
10452 }
10453
10454 /* Implement the "remove" breakpoint_ops method for
10455    masked hardware watchpoints.  */
10456
10457 static int
10458 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10459 {
10460   struct watchpoint *w = (struct watchpoint *) bl->owner;
10461
10462   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10463                                         bl->watchpoint_type);
10464 }
10465
10466 /* Implement the "resources_needed" breakpoint_ops method for
10467    masked hardware watchpoints.  */
10468
10469 static int
10470 resources_needed_masked_watchpoint (const struct bp_location *bl)
10471 {
10472   struct watchpoint *w = (struct watchpoint *) bl->owner;
10473
10474   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10475 }
10476
10477 /* Implement the "works_in_software_mode" breakpoint_ops method for
10478    masked hardware watchpoints.  */
10479
10480 static int
10481 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10482 {
10483   return 0;
10484 }
10485
10486 /* Implement the "print_it" breakpoint_ops method for
10487    masked hardware watchpoints.  */
10488
10489 static enum print_stop_action
10490 print_it_masked_watchpoint (bpstat bs)
10491 {
10492   struct breakpoint *b = bs->breakpoint_at;
10493   struct ui_out *uiout = current_uiout;
10494
10495   /* Masked watchpoints have only one location.  */
10496   gdb_assert (b->loc && b->loc->next == NULL);
10497
10498   annotate_watchpoint (b->number);
10499   maybe_print_thread_hit_breakpoint (uiout);
10500
10501   switch (b->type)
10502     {
10503     case bp_hardware_watchpoint:
10504       if (uiout->is_mi_like_p ())
10505         uiout->field_string
10506           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10507       break;
10508
10509     case bp_read_watchpoint:
10510       if (uiout->is_mi_like_p ())
10511         uiout->field_string
10512           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10513       break;
10514
10515     case bp_access_watchpoint:
10516       if (uiout->is_mi_like_p ())
10517         uiout->field_string
10518           ("reason",
10519            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10520       break;
10521     default:
10522       internal_error (__FILE__, __LINE__,
10523                       _("Invalid hardware watchpoint type."));
10524     }
10525
10526   mention (b);
10527   uiout->text (_("\n\
10528 Check the underlying instruction at PC for the memory\n\
10529 address and value which triggered this watchpoint.\n"));
10530   uiout->text ("\n");
10531
10532   /* More than one watchpoint may have been triggered.  */
10533   return PRINT_UNKNOWN;
10534 }
10535
10536 /* Implement the "print_one_detail" breakpoint_ops method for
10537    masked hardware watchpoints.  */
10538
10539 static void
10540 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10541                                     struct ui_out *uiout)
10542 {
10543   struct watchpoint *w = (struct watchpoint *) b;
10544
10545   /* Masked watchpoints have only one location.  */
10546   gdb_assert (b->loc && b->loc->next == NULL);
10547
10548   uiout->text ("\tmask ");
10549   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10550   uiout->text ("\n");
10551 }
10552
10553 /* Implement the "print_mention" breakpoint_ops method for
10554    masked hardware watchpoints.  */
10555
10556 static void
10557 print_mention_masked_watchpoint (struct breakpoint *b)
10558 {
10559   struct watchpoint *w = (struct watchpoint *) b;
10560   struct ui_out *uiout = current_uiout;
10561   const char *tuple_name;
10562
10563   switch (b->type)
10564     {
10565     case bp_hardware_watchpoint:
10566       uiout->text ("Masked hardware watchpoint ");
10567       tuple_name = "wpt";
10568       break;
10569     case bp_read_watchpoint:
10570       uiout->text ("Masked hardware read watchpoint ");
10571       tuple_name = "hw-rwpt";
10572       break;
10573     case bp_access_watchpoint:
10574       uiout->text ("Masked hardware access (read/write) watchpoint ");
10575       tuple_name = "hw-awpt";
10576       break;
10577     default:
10578       internal_error (__FILE__, __LINE__,
10579                       _("Invalid hardware watchpoint type."));
10580     }
10581
10582   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10583   uiout->field_int ("number", b->number);
10584   uiout->text (": ");
10585   uiout->field_string ("exp", w->exp_string);
10586 }
10587
10588 /* Implement the "print_recreate" breakpoint_ops method for
10589    masked hardware watchpoints.  */
10590
10591 static void
10592 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10593 {
10594   struct watchpoint *w = (struct watchpoint *) b;
10595   char tmp[40];
10596
10597   switch (b->type)
10598     {
10599     case bp_hardware_watchpoint:
10600       fprintf_unfiltered (fp, "watch");
10601       break;
10602     case bp_read_watchpoint:
10603       fprintf_unfiltered (fp, "rwatch");
10604       break;
10605     case bp_access_watchpoint:
10606       fprintf_unfiltered (fp, "awatch");
10607       break;
10608     default:
10609       internal_error (__FILE__, __LINE__,
10610                       _("Invalid hardware watchpoint type."));
10611     }
10612
10613   sprintf_vma (tmp, w->hw_wp_mask);
10614   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10615   print_recreate_thread (b, fp);
10616 }
10617
10618 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10619
10620 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10621
10622 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10623
10624 static int
10625 is_masked_watchpoint (const struct breakpoint *b)
10626 {
10627   return b->ops == &masked_watchpoint_breakpoint_ops;
10628 }
10629
10630 /* accessflag:  hw_write:  watch write, 
10631                 hw_read:   watch read, 
10632                 hw_access: watch access (read or write) */
10633 static void
10634 watch_command_1 (const char *arg, int accessflag, int from_tty,
10635                  int just_location, int internal)
10636 {
10637   struct breakpoint *scope_breakpoint = NULL;
10638   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10639   struct value *val, *mark, *result;
10640   int saved_bitpos = 0, saved_bitsize = 0;
10641   const char *exp_start = NULL;
10642   const char *exp_end = NULL;
10643   const char *tok, *end_tok;
10644   int toklen = -1;
10645   const char *cond_start = NULL;
10646   const char *cond_end = NULL;
10647   enum bptype bp_type;
10648   int thread = -1;
10649   int pc = 0;
10650   /* Flag to indicate whether we are going to use masks for
10651      the hardware watchpoint.  */
10652   int use_mask = 0;
10653   CORE_ADDR mask = 0;
10654
10655   /* Make sure that we actually have parameters to parse.  */
10656   if (arg != NULL && arg[0] != '\0')
10657     {
10658       const char *value_start;
10659
10660       exp_end = arg + strlen (arg);
10661
10662       /* Look for "parameter value" pairs at the end
10663          of the arguments string.  */
10664       for (tok = exp_end - 1; tok > arg; tok--)
10665         {
10666           /* Skip whitespace at the end of the argument list.  */
10667           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10668             tok--;
10669
10670           /* Find the beginning of the last token.
10671              This is the value of the parameter.  */
10672           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10673             tok--;
10674           value_start = tok + 1;
10675
10676           /* Skip whitespace.  */
10677           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10678             tok--;
10679
10680           end_tok = tok;
10681
10682           /* Find the beginning of the second to last token.
10683              This is the parameter itself.  */
10684           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10685             tok--;
10686           tok++;
10687           toklen = end_tok - tok + 1;
10688
10689           if (toklen == 6 && startswith (tok, "thread"))
10690             {
10691               struct thread_info *thr;
10692               /* At this point we've found a "thread" token, which means
10693                  the user is trying to set a watchpoint that triggers
10694                  only in a specific thread.  */
10695               const char *endp;
10696
10697               if (thread != -1)
10698                 error(_("You can specify only one thread."));
10699
10700               /* Extract the thread ID from the next token.  */
10701               thr = parse_thread_id (value_start, &endp);
10702
10703               /* Check if the user provided a valid thread ID.  */
10704               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10705                 invalid_thread_id_error (value_start);
10706
10707               thread = thr->global_num;
10708             }
10709           else if (toklen == 4 && startswith (tok, "mask"))
10710             {
10711               /* We've found a "mask" token, which means the user wants to
10712                  create a hardware watchpoint that is going to have the mask
10713                  facility.  */
10714               struct value *mask_value, *mark;
10715
10716               if (use_mask)
10717                 error(_("You can specify only one mask."));
10718
10719               use_mask = just_location = 1;
10720
10721               mark = value_mark ();
10722               mask_value = parse_to_comma_and_eval (&value_start);
10723               mask = value_as_address (mask_value);
10724               value_free_to_mark (mark);
10725             }
10726           else
10727             /* We didn't recognize what we found.  We should stop here.  */
10728             break;
10729
10730           /* Truncate the string and get rid of the "parameter value" pair before
10731              the arguments string is parsed by the parse_exp_1 function.  */
10732           exp_end = tok;
10733         }
10734     }
10735   else
10736     exp_end = arg;
10737
10738   /* Parse the rest of the arguments.  From here on out, everything
10739      is in terms of a newly allocated string instead of the original
10740      ARG.  */
10741   innermost_block = NULL;
10742   std::string expression (arg, exp_end - arg);
10743   exp_start = arg = expression.c_str ();
10744   expression_up exp = parse_exp_1 (&arg, 0, 0, 0);
10745   exp_end = arg;
10746   /* Remove trailing whitespace from the expression before saving it.
10747      This makes the eventual display of the expression string a bit
10748      prettier.  */
10749   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10750     --exp_end;
10751
10752   /* Checking if the expression is not constant.  */
10753   if (watchpoint_exp_is_const (exp.get ()))
10754     {
10755       int len;
10756
10757       len = exp_end - exp_start;
10758       while (len > 0 && isspace (exp_start[len - 1]))
10759         len--;
10760       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10761     }
10762
10763   exp_valid_block = innermost_block;
10764   mark = value_mark ();
10765   fetch_subexp_value (exp.get (), &pc, &val, &result, NULL, just_location);
10766
10767   if (val != NULL && just_location)
10768     {
10769       saved_bitpos = value_bitpos (val);
10770       saved_bitsize = value_bitsize (val);
10771     }
10772
10773   if (just_location)
10774     {
10775       int ret;
10776
10777       exp_valid_block = NULL;
10778       val = value_addr (result);
10779       release_value (val);
10780       value_free_to_mark (mark);
10781
10782       if (use_mask)
10783         {
10784           ret = target_masked_watch_num_registers (value_as_address (val),
10785                                                    mask);
10786           if (ret == -1)
10787             error (_("This target does not support masked watchpoints."));
10788           else if (ret == -2)
10789             error (_("Invalid mask or memory region."));
10790         }
10791     }
10792   else if (val != NULL)
10793     release_value (val);
10794
10795   tok = skip_spaces (arg);
10796   end_tok = skip_to_space (tok);
10797
10798   toklen = end_tok - tok;
10799   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10800     {
10801       innermost_block = NULL;
10802       tok = cond_start = end_tok + 1;
10803       parse_exp_1 (&tok, 0, 0, 0);
10804
10805       /* The watchpoint expression may not be local, but the condition
10806          may still be.  E.g.: `watch global if local > 0'.  */
10807       cond_exp_valid_block = innermost_block;
10808
10809       cond_end = tok;
10810     }
10811   if (*tok)
10812     error (_("Junk at end of command."));
10813
10814   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10815
10816   /* Save this because create_internal_breakpoint below invalidates
10817      'wp_frame'.  */
10818   frame_id watchpoint_frame = get_frame_id (wp_frame);
10819
10820   /* If the expression is "local", then set up a "watchpoint scope"
10821      breakpoint at the point where we've left the scope of the watchpoint
10822      expression.  Create the scope breakpoint before the watchpoint, so
10823      that we will encounter it first in bpstat_stop_status.  */
10824   if (exp_valid_block != NULL && wp_frame != NULL)
10825     {
10826       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10827
10828       if (frame_id_p (caller_frame_id))
10829         {
10830           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10831           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10832
10833           scope_breakpoint
10834             = create_internal_breakpoint (caller_arch, caller_pc,
10835                                           bp_watchpoint_scope,
10836                                           &momentary_breakpoint_ops);
10837
10838           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10839           wp_frame = NULL;
10840
10841           scope_breakpoint->enable_state = bp_enabled;
10842
10843           /* Automatically delete the breakpoint when it hits.  */
10844           scope_breakpoint->disposition = disp_del;
10845
10846           /* Only break in the proper frame (help with recursion).  */
10847           scope_breakpoint->frame_id = caller_frame_id;
10848
10849           /* Set the address at which we will stop.  */
10850           scope_breakpoint->loc->gdbarch = caller_arch;
10851           scope_breakpoint->loc->requested_address = caller_pc;
10852           scope_breakpoint->loc->address
10853             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10854                                          scope_breakpoint->loc->requested_address,
10855                                          scope_breakpoint->type);
10856         }
10857     }
10858
10859   /* Now set up the breakpoint.  We create all watchpoints as hardware
10860      watchpoints here even if hardware watchpoints are turned off, a call
10861      to update_watchpoint later in this function will cause the type to
10862      drop back to bp_watchpoint (software watchpoint) if required.  */
10863
10864   if (accessflag == hw_read)
10865     bp_type = bp_read_watchpoint;
10866   else if (accessflag == hw_access)
10867     bp_type = bp_access_watchpoint;
10868   else
10869     bp_type = bp_hardware_watchpoint;
10870
10871   std::unique_ptr<watchpoint> w (new watchpoint ());
10872
10873   if (use_mask)
10874     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10875                                           &masked_watchpoint_breakpoint_ops);
10876   else
10877     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10878                                           &watchpoint_breakpoint_ops);
10879   w->thread = thread;
10880   w->disposition = disp_donttouch;
10881   w->pspace = current_program_space;
10882   w->exp = std::move (exp);
10883   w->exp_valid_block = exp_valid_block;
10884   w->cond_exp_valid_block = cond_exp_valid_block;
10885   if (just_location)
10886     {
10887       struct type *t = value_type (val);
10888       CORE_ADDR addr = value_as_address (val);
10889
10890       w->exp_string_reparse
10891         = current_language->la_watch_location_expression (t, addr).release ();
10892
10893       w->exp_string = xstrprintf ("-location %.*s",
10894                                   (int) (exp_end - exp_start), exp_start);
10895     }
10896   else
10897     w->exp_string = savestring (exp_start, exp_end - exp_start);
10898
10899   if (use_mask)
10900     {
10901       w->hw_wp_mask = mask;
10902     }
10903   else
10904     {
10905       w->val = val;
10906       w->val_bitpos = saved_bitpos;
10907       w->val_bitsize = saved_bitsize;
10908       w->val_valid = 1;
10909     }
10910
10911   if (cond_start)
10912     w->cond_string = savestring (cond_start, cond_end - cond_start);
10913   else
10914     w->cond_string = 0;
10915
10916   if (frame_id_p (watchpoint_frame))
10917     {
10918       w->watchpoint_frame = watchpoint_frame;
10919       w->watchpoint_thread = inferior_ptid;
10920     }
10921   else
10922     {
10923       w->watchpoint_frame = null_frame_id;
10924       w->watchpoint_thread = null_ptid;
10925     }
10926
10927   if (scope_breakpoint != NULL)
10928     {
10929       /* The scope breakpoint is related to the watchpoint.  We will
10930          need to act on them together.  */
10931       w->related_breakpoint = scope_breakpoint;
10932       scope_breakpoint->related_breakpoint = w.get ();
10933     }
10934
10935   if (!just_location)
10936     value_free_to_mark (mark);
10937
10938   /* Finally update the new watchpoint.  This creates the locations
10939      that should be inserted.  */
10940   update_watchpoint (w.get (), 1);
10941
10942   install_breakpoint (internal, std::move (w), 1);
10943 }
10944
10945 /* Return count of debug registers needed to watch the given expression.
10946    If the watchpoint cannot be handled in hardware return zero.  */
10947
10948 static int
10949 can_use_hardware_watchpoint (struct value *v)
10950 {
10951   int found_memory_cnt = 0;
10952   struct value *head = v;
10953
10954   /* Did the user specifically forbid us to use hardware watchpoints? */
10955   if (!can_use_hw_watchpoints)
10956     return 0;
10957
10958   /* Make sure that the value of the expression depends only upon
10959      memory contents, and values computed from them within GDB.  If we
10960      find any register references or function calls, we can't use a
10961      hardware watchpoint.
10962
10963      The idea here is that evaluating an expression generates a series
10964      of values, one holding the value of every subexpression.  (The
10965      expression a*b+c has five subexpressions: a, b, a*b, c, and
10966      a*b+c.)  GDB's values hold almost enough information to establish
10967      the criteria given above --- they identify memory lvalues,
10968      register lvalues, computed values, etcetera.  So we can evaluate
10969      the expression, and then scan the chain of values that leaves
10970      behind to decide whether we can detect any possible change to the
10971      expression's final value using only hardware watchpoints.
10972
10973      However, I don't think that the values returned by inferior
10974      function calls are special in any way.  So this function may not
10975      notice that an expression involving an inferior function call
10976      can't be watched with hardware watchpoints.  FIXME.  */
10977   for (; v; v = value_next (v))
10978     {
10979       if (VALUE_LVAL (v) == lval_memory)
10980         {
10981           if (v != head && value_lazy (v))
10982             /* A lazy memory lvalue in the chain is one that GDB never
10983                needed to fetch; we either just used its address (e.g.,
10984                `a' in `a.b') or we never needed it at all (e.g., `a'
10985                in `a,b').  This doesn't apply to HEAD; if that is
10986                lazy then it was not readable, but watch it anyway.  */
10987             ;
10988           else
10989             {
10990               /* Ahh, memory we actually used!  Check if we can cover
10991                  it with hardware watchpoints.  */
10992               struct type *vtype = check_typedef (value_type (v));
10993
10994               /* We only watch structs and arrays if user asked for it
10995                  explicitly, never if they just happen to appear in a
10996                  middle of some value chain.  */
10997               if (v == head
10998                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10999                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11000                 {
11001                   CORE_ADDR vaddr = value_address (v);
11002                   int len;
11003                   int num_regs;
11004
11005                   len = (target_exact_watchpoints
11006                          && is_scalar_type_recursive (vtype))?
11007                     1 : TYPE_LENGTH (value_type (v));
11008
11009                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11010                   if (!num_regs)
11011                     return 0;
11012                   else
11013                     found_memory_cnt += num_regs;
11014                 }
11015             }
11016         }
11017       else if (VALUE_LVAL (v) != not_lval
11018                && deprecated_value_modifiable (v) == 0)
11019         return 0;       /* These are values from the history (e.g., $1).  */
11020       else if (VALUE_LVAL (v) == lval_register)
11021         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11022     }
11023
11024   /* The expression itself looks suitable for using a hardware
11025      watchpoint, but give the target machine a chance to reject it.  */
11026   return found_memory_cnt;
11027 }
11028
11029 void
11030 watch_command_wrapper (const char *arg, int from_tty, int internal)
11031 {
11032   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11033 }
11034
11035 /* A helper function that looks for the "-location" argument and then
11036    calls watch_command_1.  */
11037
11038 static void
11039 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11040 {
11041   int just_location = 0;
11042
11043   if (arg
11044       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11045           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11046     {
11047       arg = skip_spaces (arg);
11048       just_location = 1;
11049     }
11050
11051   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11052 }
11053
11054 static void
11055 watch_command (const char *arg, int from_tty)
11056 {
11057   watch_maybe_just_location (arg, hw_write, from_tty);
11058 }
11059
11060 void
11061 rwatch_command_wrapper (const char *arg, int from_tty, int internal)
11062 {
11063   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11064 }
11065
11066 static void
11067 rwatch_command (const char *arg, int from_tty)
11068 {
11069   watch_maybe_just_location (arg, hw_read, from_tty);
11070 }
11071
11072 void
11073 awatch_command_wrapper (const char *arg, int from_tty, int internal)
11074 {
11075   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11076 }
11077
11078 static void
11079 awatch_command (const char *arg, int from_tty)
11080 {
11081   watch_maybe_just_location (arg, hw_access, from_tty);
11082 }
11083 \f
11084
11085 /* Data for the FSM that manages the until(location)/advance commands
11086    in infcmd.c.  Here because it uses the mechanisms of
11087    breakpoints.  */
11088
11089 struct until_break_fsm
11090 {
11091   /* The base class.  */
11092   struct thread_fsm thread_fsm;
11093
11094   /* The thread that as current when the command was executed.  */
11095   int thread;
11096
11097   /* The breakpoint set at the destination location.  */
11098   struct breakpoint *location_breakpoint;
11099
11100   /* Breakpoint set at the return address in the caller frame.  May be
11101      NULL.  */
11102   struct breakpoint *caller_breakpoint;
11103 };
11104
11105 static void until_break_fsm_clean_up (struct thread_fsm *self,
11106                                       struct thread_info *thread);
11107 static int until_break_fsm_should_stop (struct thread_fsm *self,
11108                                         struct thread_info *thread);
11109 static enum async_reply_reason
11110   until_break_fsm_async_reply_reason (struct thread_fsm *self);
11111
11112 /* until_break_fsm's vtable.  */
11113
11114 static struct thread_fsm_ops until_break_fsm_ops =
11115 {
11116   NULL, /* dtor */
11117   until_break_fsm_clean_up,
11118   until_break_fsm_should_stop,
11119   NULL, /* return_value */
11120   until_break_fsm_async_reply_reason,
11121 };
11122
11123 /* Allocate a new until_break_command_fsm.  */
11124
11125 static struct until_break_fsm *
11126 new_until_break_fsm (struct interp *cmd_interp, int thread,
11127                      breakpoint_up &&location_breakpoint,
11128                      breakpoint_up &&caller_breakpoint)
11129 {
11130   struct until_break_fsm *sm;
11131
11132   sm = XCNEW (struct until_break_fsm);
11133   thread_fsm_ctor (&sm->thread_fsm, &until_break_fsm_ops, cmd_interp);
11134
11135   sm->thread = thread;
11136   sm->location_breakpoint = location_breakpoint.release ();
11137   sm->caller_breakpoint = caller_breakpoint.release ();
11138
11139   return sm;
11140 }
11141
11142 /* Implementation of the 'should_stop' FSM method for the
11143    until(location)/advance commands.  */
11144
11145 static int
11146 until_break_fsm_should_stop (struct thread_fsm *self,
11147                              struct thread_info *tp)
11148 {
11149   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11150
11151   if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11152                               sm->location_breakpoint) != NULL
11153       || (sm->caller_breakpoint != NULL
11154           && bpstat_find_breakpoint (tp->control.stop_bpstat,
11155                                      sm->caller_breakpoint) != NULL))
11156     thread_fsm_set_finished (self);
11157
11158   return 1;
11159 }
11160
11161 /* Implementation of the 'clean_up' FSM method for the
11162    until(location)/advance commands.  */
11163
11164 static void
11165 until_break_fsm_clean_up (struct thread_fsm *self,
11166                           struct thread_info *thread)
11167 {
11168   struct until_break_fsm *sm = (struct until_break_fsm *) self;
11169
11170   /* Clean up our temporary breakpoints.  */
11171   if (sm->location_breakpoint != NULL)
11172     {
11173       delete_breakpoint (sm->location_breakpoint);
11174       sm->location_breakpoint = NULL;
11175     }
11176   if (sm->caller_breakpoint != NULL)
11177     {
11178       delete_breakpoint (sm->caller_breakpoint);
11179       sm->caller_breakpoint = NULL;
11180     }
11181   delete_longjmp_breakpoint (sm->thread);
11182 }
11183
11184 /* Implementation of the 'async_reply_reason' FSM method for the
11185    until(location)/advance commands.  */
11186
11187 static enum async_reply_reason
11188 until_break_fsm_async_reply_reason (struct thread_fsm *self)
11189 {
11190   return EXEC_ASYNC_LOCATION_REACHED;
11191 }
11192
11193 void
11194 until_break_command (const char *arg, int from_tty, int anywhere)
11195 {
11196   struct frame_info *frame;
11197   struct gdbarch *frame_gdbarch;
11198   struct frame_id stack_frame_id;
11199   struct frame_id caller_frame_id;
11200   struct cleanup *old_chain;
11201   int thread;
11202   struct thread_info *tp;
11203   struct until_break_fsm *sm;
11204
11205   clear_proceed_status (0);
11206
11207   /* Set a breakpoint where the user wants it and at return from
11208      this function.  */
11209
11210   event_location_up location = string_to_event_location (&arg, current_language);
11211
11212   std::vector<symtab_and_line> sals
11213     = (last_displayed_sal_is_valid ()
11214        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11215                         get_last_displayed_symtab (),
11216                         get_last_displayed_line ())
11217        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11218                         NULL, (struct symtab *) NULL, 0));
11219
11220   if (sals.size () != 1)
11221     error (_("Couldn't get information on specified line."));
11222
11223   symtab_and_line &sal = sals[0];
11224
11225   if (*arg)
11226     error (_("Junk at end of arguments."));
11227
11228   resolve_sal_pc (&sal);
11229
11230   tp = inferior_thread ();
11231   thread = tp->global_num;
11232
11233   old_chain = make_cleanup (null_cleanup, NULL);
11234
11235   /* Note linespec handling above invalidates the frame chain.
11236      Installing a breakpoint also invalidates the frame chain (as it
11237      may need to switch threads), so do any frame handling before
11238      that.  */
11239
11240   frame = get_selected_frame (NULL);
11241   frame_gdbarch = get_frame_arch (frame);
11242   stack_frame_id = get_stack_frame_id (frame);
11243   caller_frame_id = frame_unwind_caller_id (frame);
11244
11245   /* Keep within the current frame, or in frames called by the current
11246      one.  */
11247
11248   breakpoint_up caller_breakpoint;
11249   if (frame_id_p (caller_frame_id))
11250     {
11251       struct symtab_and_line sal2;
11252       struct gdbarch *caller_gdbarch;
11253
11254       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11255       sal2.pc = frame_unwind_caller_pc (frame);
11256       caller_gdbarch = frame_unwind_caller_arch (frame);
11257       caller_breakpoint = set_momentary_breakpoint (caller_gdbarch,
11258                                                     sal2,
11259                                                     caller_frame_id,
11260                                                     bp_until);
11261
11262       set_longjmp_breakpoint (tp, caller_frame_id);
11263       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11264     }
11265
11266   /* set_momentary_breakpoint could invalidate FRAME.  */
11267   frame = NULL;
11268
11269   breakpoint_up location_breakpoint;
11270   if (anywhere)
11271     /* If the user told us to continue until a specified location,
11272        we don't specify a frame at which we need to stop.  */
11273     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11274                                                     null_frame_id, bp_until);
11275   else
11276     /* Otherwise, specify the selected frame, because we want to stop
11277        only at the very same frame.  */
11278     location_breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11279                                                     stack_frame_id, bp_until);
11280
11281   sm = new_until_break_fsm (command_interp (), tp->global_num,
11282                             std::move (location_breakpoint),
11283                             std::move (caller_breakpoint));
11284   tp->thread_fsm = &sm->thread_fsm;
11285
11286   discard_cleanups (old_chain);
11287
11288   proceed (-1, GDB_SIGNAL_DEFAULT);
11289 }
11290
11291 /* This function attempts to parse an optional "if <cond>" clause
11292    from the arg string.  If one is not found, it returns NULL.
11293
11294    Else, it returns a pointer to the condition string.  (It does not
11295    attempt to evaluate the string against a particular block.)  And,
11296    it updates arg to point to the first character following the parsed
11297    if clause in the arg string.  */
11298
11299 const char *
11300 ep_parse_optional_if_clause (const char **arg)
11301 {
11302   const char *cond_string;
11303
11304   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11305     return NULL;
11306
11307   /* Skip the "if" keyword.  */
11308   (*arg) += 2;
11309
11310   /* Skip any extra leading whitespace, and record the start of the
11311      condition string.  */
11312   *arg = skip_spaces (*arg);
11313   cond_string = *arg;
11314
11315   /* Assume that the condition occupies the remainder of the arg
11316      string.  */
11317   (*arg) += strlen (cond_string);
11318
11319   return cond_string;
11320 }
11321
11322 /* Commands to deal with catching events, such as signals, exceptions,
11323    process start/exit, etc.  */
11324
11325 typedef enum
11326 {
11327   catch_fork_temporary, catch_vfork_temporary,
11328   catch_fork_permanent, catch_vfork_permanent
11329 }
11330 catch_fork_kind;
11331
11332 static void
11333 catch_fork_command_1 (char *arg_entry, int from_tty,
11334                       struct cmd_list_element *command)
11335 {
11336   const char *arg = arg_entry;
11337   struct gdbarch *gdbarch = get_current_arch ();
11338   const char *cond_string = NULL;
11339   catch_fork_kind fork_kind;
11340   int tempflag;
11341
11342   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11343   tempflag = (fork_kind == catch_fork_temporary
11344               || fork_kind == catch_vfork_temporary);
11345
11346   if (!arg)
11347     arg = "";
11348   arg = skip_spaces (arg);
11349
11350   /* The allowed syntax is:
11351      catch [v]fork
11352      catch [v]fork if <cond>
11353
11354      First, check if there's an if clause.  */
11355   cond_string = ep_parse_optional_if_clause (&arg);
11356
11357   if ((*arg != '\0') && !isspace (*arg))
11358     error (_("Junk at end of arguments."));
11359
11360   /* If this target supports it, create a fork or vfork catchpoint
11361      and enable reporting of such events.  */
11362   switch (fork_kind)
11363     {
11364     case catch_fork_temporary:
11365     case catch_fork_permanent:
11366       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11367                                           &catch_fork_breakpoint_ops);
11368       break;
11369     case catch_vfork_temporary:
11370     case catch_vfork_permanent:
11371       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11372                                           &catch_vfork_breakpoint_ops);
11373       break;
11374     default:
11375       error (_("unsupported or unknown fork kind; cannot catch it"));
11376       break;
11377     }
11378 }
11379
11380 static void
11381 catch_exec_command_1 (char *arg_entry, int from_tty,
11382                       struct cmd_list_element *command)
11383 {
11384   const char *arg = arg_entry;
11385   struct gdbarch *gdbarch = get_current_arch ();
11386   int tempflag;
11387   const char *cond_string = NULL;
11388
11389   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11390
11391   if (!arg)
11392     arg = "";
11393   arg = skip_spaces (arg);
11394
11395   /* The allowed syntax is:
11396      catch exec
11397      catch exec if <cond>
11398
11399      First, check if there's an if clause.  */
11400   cond_string = ep_parse_optional_if_clause (&arg);
11401
11402   if ((*arg != '\0') && !isspace (*arg))
11403     error (_("Junk at end of arguments."));
11404
11405   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11406   init_catchpoint (c.get (), gdbarch, tempflag, cond_string,
11407                    &catch_exec_breakpoint_ops);
11408   c->exec_pathname = NULL;
11409
11410   install_breakpoint (0, std::move (c), 1);
11411 }
11412
11413 void
11414 init_ada_exception_breakpoint (struct breakpoint *b,
11415                                struct gdbarch *gdbarch,
11416                                struct symtab_and_line sal,
11417                                const char *addr_string,
11418                                const struct breakpoint_ops *ops,
11419                                int tempflag,
11420                                int enabled,
11421                                int from_tty)
11422 {
11423   if (from_tty)
11424     {
11425       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11426       if (!loc_gdbarch)
11427         loc_gdbarch = gdbarch;
11428
11429       describe_other_breakpoints (loc_gdbarch,
11430                                   sal.pspace, sal.pc, sal.section, -1);
11431       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11432          version for exception catchpoints, because two catchpoints
11433          used for different exception names will use the same address.
11434          In this case, a "breakpoint ... also set at..." warning is
11435          unproductive.  Besides, the warning phrasing is also a bit
11436          inappropriate, we should use the word catchpoint, and tell
11437          the user what type of catchpoint it is.  The above is good
11438          enough for now, though.  */
11439     }
11440
11441   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11442
11443   b->enable_state = enabled ? bp_enabled : bp_disabled;
11444   b->disposition = tempflag ? disp_del : disp_donttouch;
11445   b->location = string_to_event_location (&addr_string,
11446                                           language_def (language_ada));
11447   b->language = language_ada;
11448 }
11449
11450 static void
11451 catch_command (const char *arg, int from_tty)
11452 {
11453   error (_("Catch requires an event name."));
11454 }
11455 \f
11456
11457 static void
11458 tcatch_command (const char *arg, int from_tty)
11459 {
11460   error (_("Catch requires an event name."));
11461 }
11462
11463 /* Compare two breakpoints and return a strcmp-like result.  */
11464
11465 static int
11466 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11467 {
11468   uintptr_t ua = (uintptr_t) a;
11469   uintptr_t ub = (uintptr_t) b;
11470
11471   if (a->number < b->number)
11472     return -1;
11473   else if (a->number > b->number)
11474     return 1;
11475
11476   /* Now sort by address, in case we see, e..g, two breakpoints with
11477      the number 0.  */
11478   if (ua < ub)
11479     return -1;
11480   return ua > ub ? 1 : 0;
11481 }
11482
11483 /* Delete breakpoints by address or line.  */
11484
11485 static void
11486 clear_command (const char *arg, int from_tty)
11487 {
11488   struct breakpoint *b;
11489   int default_match;
11490   int i;
11491
11492   std::vector<symtab_and_line> decoded_sals;
11493   symtab_and_line last_sal;
11494   gdb::array_view<symtab_and_line> sals;
11495   if (arg)
11496     {
11497       decoded_sals
11498         = decode_line_with_current_source (arg,
11499                                            (DECODE_LINE_FUNFIRSTLINE
11500                                             | DECODE_LINE_LIST_MODE));
11501       default_match = 0;
11502       sals = decoded_sals;
11503     }
11504   else
11505     {
11506       /* Set sal's line, symtab, pc, and pspace to the values
11507          corresponding to the last call to print_frame_info.  If the
11508          codepoint is not valid, this will set all the fields to 0.  */
11509       last_sal = get_last_displayed_sal ();
11510       if (last_sal.symtab == 0)
11511         error (_("No source file specified."));
11512
11513       default_match = 1;
11514       sals = last_sal;
11515     }
11516
11517   /* We don't call resolve_sal_pc here.  That's not as bad as it
11518      seems, because all existing breakpoints typically have both
11519      file/line and pc set.  So, if clear is given file/line, we can
11520      match this to existing breakpoint without obtaining pc at all.
11521
11522      We only support clearing given the address explicitly 
11523      present in breakpoint table.  Say, we've set breakpoint 
11524      at file:line.  There were several PC values for that file:line,
11525      due to optimization, all in one block.
11526
11527      We've picked one PC value.  If "clear" is issued with another
11528      PC corresponding to the same file:line, the breakpoint won't
11529      be cleared.  We probably can still clear the breakpoint, but 
11530      since the other PC value is never presented to user, user
11531      can only find it by guessing, and it does not seem important
11532      to support that.  */
11533
11534   /* For each line spec given, delete bps which correspond to it.  Do
11535      it in two passes, solely to preserve the current behavior that
11536      from_tty is forced true if we delete more than one
11537      breakpoint.  */
11538
11539   std::vector<struct breakpoint *> found;
11540   for (const auto &sal : sals)
11541     {
11542       const char *sal_fullname;
11543
11544       /* If exact pc given, clear bpts at that pc.
11545          If line given (pc == 0), clear all bpts on specified line.
11546          If defaulting, clear all bpts on default line
11547          or at default pc.
11548
11549          defaulting    sal.pc != 0    tests to do
11550
11551          0              1             pc
11552          1              1             pc _and_ line
11553          0              0             line
11554          1              0             <can't happen> */
11555
11556       sal_fullname = (sal.symtab == NULL
11557                       ? NULL : symtab_to_fullname (sal.symtab));
11558
11559       /* Find all matching breakpoints and add them to 'found'.  */
11560       ALL_BREAKPOINTS (b)
11561         {
11562           int match = 0;
11563           /* Are we going to delete b?  */
11564           if (b->type != bp_none && !is_watchpoint (b))
11565             {
11566               struct bp_location *loc = b->loc;
11567               for (; loc; loc = loc->next)
11568                 {
11569                   /* If the user specified file:line, don't allow a PC
11570                      match.  This matches historical gdb behavior.  */
11571                   int pc_match = (!sal.explicit_line
11572                                   && sal.pc
11573                                   && (loc->pspace == sal.pspace)
11574                                   && (loc->address == sal.pc)
11575                                   && (!section_is_overlay (loc->section)
11576                                       || loc->section == sal.section));
11577                   int line_match = 0;
11578
11579                   if ((default_match || sal.explicit_line)
11580                       && loc->symtab != NULL
11581                       && sal_fullname != NULL
11582                       && sal.pspace == loc->pspace
11583                       && loc->line_number == sal.line
11584                       && filename_cmp (symtab_to_fullname (loc->symtab),
11585                                        sal_fullname) == 0)
11586                     line_match = 1;
11587
11588                   if (pc_match || line_match)
11589                     {
11590                       match = 1;
11591                       break;
11592                     }
11593                 }
11594             }
11595
11596           if (match)
11597             found.push_back (b);
11598         }
11599     }
11600
11601   /* Now go thru the 'found' chain and delete them.  */
11602   if (found.empty ())
11603     {
11604       if (arg)
11605         error (_("No breakpoint at %s."), arg);
11606       else
11607         error (_("No breakpoint at this line."));
11608     }
11609
11610   /* Remove duplicates from the vec.  */
11611   std::sort (found.begin (), found.end (),
11612              [] (const breakpoint *a, const breakpoint *b)
11613              {
11614                return compare_breakpoints (a, b) < 0;
11615              });
11616   found.erase (std::unique (found.begin (), found.end (),
11617                             [] (const breakpoint *a, const breakpoint *b)
11618                             {
11619                               return compare_breakpoints (a, b) == 0;
11620                             }),
11621                found.end ());
11622
11623   if (found.size () > 1)
11624     from_tty = 1;       /* Always report if deleted more than one.  */
11625   if (from_tty)
11626     {
11627       if (found.size () == 1)
11628         printf_unfiltered (_("Deleted breakpoint "));
11629       else
11630         printf_unfiltered (_("Deleted breakpoints "));
11631     }
11632
11633   for (breakpoint *iter : found)
11634     {
11635       if (from_tty)
11636         printf_unfiltered ("%d ", iter->number);
11637       delete_breakpoint (iter);
11638     }
11639   if (from_tty)
11640     putchar_unfiltered ('\n');
11641 }
11642 \f
11643 /* Delete breakpoint in BS if they are `delete' breakpoints and
11644    all breakpoints that are marked for deletion, whether hit or not.
11645    This is called after any breakpoint is hit, or after errors.  */
11646
11647 void
11648 breakpoint_auto_delete (bpstat bs)
11649 {
11650   struct breakpoint *b, *b_tmp;
11651
11652   for (; bs; bs = bs->next)
11653     if (bs->breakpoint_at
11654         && bs->breakpoint_at->disposition == disp_del
11655         && bs->stop)
11656       delete_breakpoint (bs->breakpoint_at);
11657
11658   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11659   {
11660     if (b->disposition == disp_del_at_next_stop)
11661       delete_breakpoint (b);
11662   }
11663 }
11664
11665 /* A comparison function for bp_location AP and BP being interfaced to
11666    qsort.  Sort elements primarily by their ADDRESS (no matter what
11667    does breakpoint_address_is_meaningful say for its OWNER),
11668    secondarily by ordering first permanent elements and
11669    terciarily just ensuring the array is sorted stable way despite
11670    qsort being an unstable algorithm.  */
11671
11672 static int
11673 bp_locations_compare (const void *ap, const void *bp)
11674 {
11675   const struct bp_location *a = *(const struct bp_location **) ap;
11676   const struct bp_location *b = *(const struct bp_location **) bp;
11677
11678   if (a->address != b->address)
11679     return (a->address > b->address) - (a->address < b->address);
11680
11681   /* Sort locations at the same address by their pspace number, keeping
11682      locations of the same inferior (in a multi-inferior environment)
11683      grouped.  */
11684
11685   if (a->pspace->num != b->pspace->num)
11686     return ((a->pspace->num > b->pspace->num)
11687             - (a->pspace->num < b->pspace->num));
11688
11689   /* Sort permanent breakpoints first.  */
11690   if (a->permanent != b->permanent)
11691     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
11692
11693   /* Make the internal GDB representation stable across GDB runs
11694      where A and B memory inside GDB can differ.  Breakpoint locations of
11695      the same type at the same address can be sorted in arbitrary order.  */
11696
11697   if (a->owner->number != b->owner->number)
11698     return ((a->owner->number > b->owner->number)
11699             - (a->owner->number < b->owner->number));
11700
11701   return (a > b) - (a < b);
11702 }
11703
11704 /* Set bp_locations_placed_address_before_address_max and
11705    bp_locations_shadow_len_after_address_max according to the current
11706    content of the bp_locations array.  */
11707
11708 static void
11709 bp_locations_target_extensions_update (void)
11710 {
11711   struct bp_location *bl, **blp_tmp;
11712
11713   bp_locations_placed_address_before_address_max = 0;
11714   bp_locations_shadow_len_after_address_max = 0;
11715
11716   ALL_BP_LOCATIONS (bl, blp_tmp)
11717     {
11718       CORE_ADDR start, end, addr;
11719
11720       if (!bp_location_has_shadow (bl))
11721         continue;
11722
11723       start = bl->target_info.placed_address;
11724       end = start + bl->target_info.shadow_len;
11725
11726       gdb_assert (bl->address >= start);
11727       addr = bl->address - start;
11728       if (addr > bp_locations_placed_address_before_address_max)
11729         bp_locations_placed_address_before_address_max = addr;
11730
11731       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11732
11733       gdb_assert (bl->address < end);
11734       addr = end - bl->address;
11735       if (addr > bp_locations_shadow_len_after_address_max)
11736         bp_locations_shadow_len_after_address_max = addr;
11737     }
11738 }
11739
11740 /* Download tracepoint locations if they haven't been.  */
11741
11742 static void
11743 download_tracepoint_locations (void)
11744 {
11745   struct breakpoint *b;
11746   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11747
11748   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11749
11750   ALL_TRACEPOINTS (b)
11751     {
11752       struct bp_location *bl;
11753       struct tracepoint *t;
11754       int bp_location_downloaded = 0;
11755
11756       if ((b->type == bp_fast_tracepoint
11757            ? !may_insert_fast_tracepoints
11758            : !may_insert_tracepoints))
11759         continue;
11760
11761       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11762         {
11763           if (target_can_download_tracepoint ())
11764             can_download_tracepoint = TRIBOOL_TRUE;
11765           else
11766             can_download_tracepoint = TRIBOOL_FALSE;
11767         }
11768
11769       if (can_download_tracepoint == TRIBOOL_FALSE)
11770         break;
11771
11772       for (bl = b->loc; bl; bl = bl->next)
11773         {
11774           /* In tracepoint, locations are _never_ duplicated, so
11775              should_be_inserted is equivalent to
11776              unduplicated_should_be_inserted.  */
11777           if (!should_be_inserted (bl) || bl->inserted)
11778             continue;
11779
11780           switch_to_program_space_and_thread (bl->pspace);
11781
11782           target_download_tracepoint (bl);
11783
11784           bl->inserted = 1;
11785           bp_location_downloaded = 1;
11786         }
11787       t = (struct tracepoint *) b;
11788       t->number_on_target = b->number;
11789       if (bp_location_downloaded)
11790         observer_notify_breakpoint_modified (b);
11791     }
11792 }
11793
11794 /* Swap the insertion/duplication state between two locations.  */
11795
11796 static void
11797 swap_insertion (struct bp_location *left, struct bp_location *right)
11798 {
11799   const int left_inserted = left->inserted;
11800   const int left_duplicate = left->duplicate;
11801   const int left_needs_update = left->needs_update;
11802   const struct bp_target_info left_target_info = left->target_info;
11803
11804   /* Locations of tracepoints can never be duplicated.  */
11805   if (is_tracepoint (left->owner))
11806     gdb_assert (!left->duplicate);
11807   if (is_tracepoint (right->owner))
11808     gdb_assert (!right->duplicate);
11809
11810   left->inserted = right->inserted;
11811   left->duplicate = right->duplicate;
11812   left->needs_update = right->needs_update;
11813   left->target_info = right->target_info;
11814   right->inserted = left_inserted;
11815   right->duplicate = left_duplicate;
11816   right->needs_update = left_needs_update;
11817   right->target_info = left_target_info;
11818 }
11819
11820 /* Force the re-insertion of the locations at ADDRESS.  This is called
11821    once a new/deleted/modified duplicate location is found and we are evaluating
11822    conditions on the target's side.  Such conditions need to be updated on
11823    the target.  */
11824
11825 static void
11826 force_breakpoint_reinsertion (struct bp_location *bl)
11827 {
11828   struct bp_location **locp = NULL, **loc2p;
11829   struct bp_location *loc;
11830   CORE_ADDR address = 0;
11831   int pspace_num;
11832
11833   address = bl->address;
11834   pspace_num = bl->pspace->num;
11835
11836   /* This is only meaningful if the target is
11837      evaluating conditions and if the user has
11838      opted for condition evaluation on the target's
11839      side.  */
11840   if (gdb_evaluates_breakpoint_condition_p ()
11841       || !target_supports_evaluation_of_breakpoint_conditions ())
11842     return;
11843
11844   /* Flag all breakpoint locations with this address and
11845      the same program space as the location
11846      as "its condition has changed".  We need to
11847      update the conditions on the target's side.  */
11848   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11849     {
11850       loc = *loc2p;
11851
11852       if (!is_breakpoint (loc->owner)
11853           || pspace_num != loc->pspace->num)
11854         continue;
11855
11856       /* Flag the location appropriately.  We use a different state to
11857          let everyone know that we already updated the set of locations
11858          with addr bl->address and program space bl->pspace.  This is so
11859          we don't have to keep calling these functions just to mark locations
11860          that have already been marked.  */
11861       loc->condition_changed = condition_updated;
11862
11863       /* Free the agent expression bytecode as well.  We will compute
11864          it later on.  */
11865       loc->cond_bytecode.reset ();
11866     }
11867 }
11868 /* Called whether new breakpoints are created, or existing breakpoints
11869    deleted, to update the global location list and recompute which
11870    locations are duplicate of which.
11871
11872    The INSERT_MODE flag determines whether locations may not, may, or
11873    shall be inserted now.  See 'enum ugll_insert_mode' for more
11874    info.  */
11875
11876 static void
11877 update_global_location_list (enum ugll_insert_mode insert_mode)
11878 {
11879   struct breakpoint *b;
11880   struct bp_location **locp, *loc;
11881   /* Last breakpoint location address that was marked for update.  */
11882   CORE_ADDR last_addr = 0;
11883   /* Last breakpoint location program space that was marked for update.  */
11884   int last_pspace_num = -1;
11885
11886   /* Used in the duplicates detection below.  When iterating over all
11887      bp_locations, points to the first bp_location of a given address.
11888      Breakpoints and watchpoints of different types are never
11889      duplicates of each other.  Keep one pointer for each type of
11890      breakpoint/watchpoint, so we only need to loop over all locations
11891      once.  */
11892   struct bp_location *bp_loc_first;  /* breakpoint */
11893   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11894   struct bp_location *awp_loc_first; /* access watchpoint */
11895   struct bp_location *rwp_loc_first; /* read watchpoint */
11896
11897   /* Saved former bp_locations array which we compare against the newly
11898      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11899   struct bp_location **old_locp;
11900   unsigned old_locations_count;
11901   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11902
11903   old_locations_count = bp_locations_count;
11904   bp_locations = NULL;
11905   bp_locations_count = 0;
11906
11907   ALL_BREAKPOINTS (b)
11908     for (loc = b->loc; loc; loc = loc->next)
11909       bp_locations_count++;
11910
11911   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11912   locp = bp_locations;
11913   ALL_BREAKPOINTS (b)
11914     for (loc = b->loc; loc; loc = loc->next)
11915       *locp++ = loc;
11916   qsort (bp_locations, bp_locations_count, sizeof (*bp_locations),
11917          bp_locations_compare);
11918
11919   bp_locations_target_extensions_update ();
11920
11921   /* Identify bp_location instances that are no longer present in the
11922      new list, and therefore should be freed.  Note that it's not
11923      necessary that those locations should be removed from inferior --
11924      if there's another location at the same address (previously
11925      marked as duplicate), we don't need to remove/insert the
11926      location.
11927      
11928      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11929      and former bp_location array state respectively.  */
11930
11931   locp = bp_locations;
11932   for (old_locp = old_locations.get ();
11933        old_locp < old_locations.get () + old_locations_count;
11934        old_locp++)
11935     {
11936       struct bp_location *old_loc = *old_locp;
11937       struct bp_location **loc2p;
11938
11939       /* Tells if 'old_loc' is found among the new locations.  If
11940          not, we have to free it.  */
11941       int found_object = 0;
11942       /* Tells if the location should remain inserted in the target.  */
11943       int keep_in_target = 0;
11944       int removed = 0;
11945
11946       /* Skip LOCP entries which will definitely never be needed.
11947          Stop either at or being the one matching OLD_LOC.  */
11948       while (locp < bp_locations + bp_locations_count
11949              && (*locp)->address < old_loc->address)
11950         locp++;
11951
11952       for (loc2p = locp;
11953            (loc2p < bp_locations + bp_locations_count
11954             && (*loc2p)->address == old_loc->address);
11955            loc2p++)
11956         {
11957           /* Check if this is a new/duplicated location or a duplicated
11958              location that had its condition modified.  If so, we want to send
11959              its condition to the target if evaluation of conditions is taking
11960              place there.  */
11961           if ((*loc2p)->condition_changed == condition_modified
11962               && (last_addr != old_loc->address
11963                   || last_pspace_num != old_loc->pspace->num))
11964             {
11965               force_breakpoint_reinsertion (*loc2p);
11966               last_pspace_num = old_loc->pspace->num;
11967             }
11968
11969           if (*loc2p == old_loc)
11970             found_object = 1;
11971         }
11972
11973       /* We have already handled this address, update it so that we don't
11974          have to go through updates again.  */
11975       last_addr = old_loc->address;
11976
11977       /* Target-side condition evaluation: Handle deleted locations.  */
11978       if (!found_object)
11979         force_breakpoint_reinsertion (old_loc);
11980
11981       /* If this location is no longer present, and inserted, look if
11982          there's maybe a new location at the same address.  If so,
11983          mark that one inserted, and don't remove this one.  This is
11984          needed so that we don't have a time window where a breakpoint
11985          at certain location is not inserted.  */
11986
11987       if (old_loc->inserted)
11988         {
11989           /* If the location is inserted now, we might have to remove
11990              it.  */
11991
11992           if (found_object && should_be_inserted (old_loc))
11993             {
11994               /* The location is still present in the location list,
11995                  and still should be inserted.  Don't do anything.  */
11996               keep_in_target = 1;
11997             }
11998           else
11999             {
12000               /* This location still exists, but it won't be kept in the
12001                  target since it may have been disabled.  We proceed to
12002                  remove its target-side condition.  */
12003
12004               /* The location is either no longer present, or got
12005                  disabled.  See if there's another location at the
12006                  same address, in which case we don't need to remove
12007                  this one from the target.  */
12008
12009               /* OLD_LOC comes from existing struct breakpoint.  */
12010               if (breakpoint_address_is_meaningful (old_loc->owner))
12011                 {
12012                   for (loc2p = locp;
12013                        (loc2p < bp_locations + bp_locations_count
12014                         && (*loc2p)->address == old_loc->address);
12015                        loc2p++)
12016                     {
12017                       struct bp_location *loc2 = *loc2p;
12018
12019                       if (breakpoint_locations_match (loc2, old_loc))
12020                         {
12021                           /* Read watchpoint locations are switched to
12022                              access watchpoints, if the former are not
12023                              supported, but the latter are.  */
12024                           if (is_hardware_watchpoint (old_loc->owner))
12025                             {
12026                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12027                               loc2->watchpoint_type = old_loc->watchpoint_type;
12028                             }
12029
12030                           /* loc2 is a duplicated location. We need to check
12031                              if it should be inserted in case it will be
12032                              unduplicated.  */
12033                           if (loc2 != old_loc
12034                               && unduplicated_should_be_inserted (loc2))
12035                             {
12036                               swap_insertion (old_loc, loc2);
12037                               keep_in_target = 1;
12038                               break;
12039                             }
12040                         }
12041                     }
12042                 }
12043             }
12044
12045           if (!keep_in_target)
12046             {
12047               if (remove_breakpoint (old_loc))
12048                 {
12049                   /* This is just about all we can do.  We could keep
12050                      this location on the global list, and try to
12051                      remove it next time, but there's no particular
12052                      reason why we will succeed next time.
12053                      
12054                      Note that at this point, old_loc->owner is still
12055                      valid, as delete_breakpoint frees the breakpoint
12056                      only after calling us.  */
12057                   printf_filtered (_("warning: Error removing "
12058                                      "breakpoint %d\n"), 
12059                                    old_loc->owner->number);
12060                 }
12061               removed = 1;
12062             }
12063         }
12064
12065       if (!found_object)
12066         {
12067           if (removed && target_is_non_stop_p ()
12068               && need_moribund_for_location_type (old_loc))
12069             {
12070               /* This location was removed from the target.  In
12071                  non-stop mode, a race condition is possible where
12072                  we've removed a breakpoint, but stop events for that
12073                  breakpoint are already queued and will arrive later.
12074                  We apply an heuristic to be able to distinguish such
12075                  SIGTRAPs from other random SIGTRAPs: we keep this
12076                  breakpoint location for a bit, and will retire it
12077                  after we see some number of events.  The theory here
12078                  is that reporting of events should, "on the average",
12079                  be fair, so after a while we'll see events from all
12080                  threads that have anything of interest, and no longer
12081                  need to keep this breakpoint location around.  We
12082                  don't hold locations forever so to reduce chances of
12083                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12084                  SIGTRAP.
12085
12086                  The heuristic failing can be disastrous on
12087                  decr_pc_after_break targets.
12088
12089                  On decr_pc_after_break targets, like e.g., x86-linux,
12090                  if we fail to recognize a late breakpoint SIGTRAP,
12091                  because events_till_retirement has reached 0 too
12092                  soon, we'll fail to do the PC adjustment, and report
12093                  a random SIGTRAP to the user.  When the user resumes
12094                  the inferior, it will most likely immediately crash
12095                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12096                  corrupted, because of being resumed e.g., in the
12097                  middle of a multi-byte instruction, or skipped a
12098                  one-byte instruction.  This was actually seen happen
12099                  on native x86-linux, and should be less rare on
12100                  targets that do not support new thread events, like
12101                  remote, due to the heuristic depending on
12102                  thread_count.
12103
12104                  Mistaking a random SIGTRAP for a breakpoint trap
12105                  causes similar symptoms (PC adjustment applied when
12106                  it shouldn't), but then again, playing with SIGTRAPs
12107                  behind the debugger's back is asking for trouble.
12108
12109                  Since hardware watchpoint traps are always
12110                  distinguishable from other traps, so we don't need to
12111                  apply keep hardware watchpoint moribund locations
12112                  around.  We simply always ignore hardware watchpoint
12113                  traps we can no longer explain.  */
12114
12115               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12116               old_loc->owner = NULL;
12117
12118               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12119             }
12120           else
12121             {
12122               old_loc->owner = NULL;
12123               decref_bp_location (&old_loc);
12124             }
12125         }
12126     }
12127
12128   /* Rescan breakpoints at the same address and section, marking the
12129      first one as "first" and any others as "duplicates".  This is so
12130      that the bpt instruction is only inserted once.  If we have a
12131      permanent breakpoint at the same place as BPT, make that one the
12132      official one, and the rest as duplicates.  Permanent breakpoints
12133      are sorted first for the same address.
12134
12135      Do the same for hardware watchpoints, but also considering the
12136      watchpoint's type (regular/access/read) and length.  */
12137
12138   bp_loc_first = NULL;
12139   wp_loc_first = NULL;
12140   awp_loc_first = NULL;
12141   rwp_loc_first = NULL;
12142   ALL_BP_LOCATIONS (loc, locp)
12143     {
12144       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12145          non-NULL.  */
12146       struct bp_location **loc_first_p;
12147       b = loc->owner;
12148
12149       if (!unduplicated_should_be_inserted (loc)
12150           || !breakpoint_address_is_meaningful (b)
12151           /* Don't detect duplicate for tracepoint locations because they are
12152            never duplicated.  See the comments in field `duplicate' of
12153            `struct bp_location'.  */
12154           || is_tracepoint (b))
12155         {
12156           /* Clear the condition modification flag.  */
12157           loc->condition_changed = condition_unchanged;
12158           continue;
12159         }
12160
12161       if (b->type == bp_hardware_watchpoint)
12162         loc_first_p = &wp_loc_first;
12163       else if (b->type == bp_read_watchpoint)
12164         loc_first_p = &rwp_loc_first;
12165       else if (b->type == bp_access_watchpoint)
12166         loc_first_p = &awp_loc_first;
12167       else
12168         loc_first_p = &bp_loc_first;
12169
12170       if (*loc_first_p == NULL
12171           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12172           || !breakpoint_locations_match (loc, *loc_first_p))
12173         {
12174           *loc_first_p = loc;
12175           loc->duplicate = 0;
12176
12177           if (is_breakpoint (loc->owner) && loc->condition_changed)
12178             {
12179               loc->needs_update = 1;
12180               /* Clear the condition modification flag.  */
12181               loc->condition_changed = condition_unchanged;
12182             }
12183           continue;
12184         }
12185
12186
12187       /* This and the above ensure the invariant that the first location
12188          is not duplicated, and is the inserted one.
12189          All following are marked as duplicated, and are not inserted.  */
12190       if (loc->inserted)
12191         swap_insertion (loc, *loc_first_p);
12192       loc->duplicate = 1;
12193
12194       /* Clear the condition modification flag.  */
12195       loc->condition_changed = condition_unchanged;
12196     }
12197
12198   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12199     {
12200       if (insert_mode != UGLL_DONT_INSERT)
12201         insert_breakpoint_locations ();
12202       else
12203         {
12204           /* Even though the caller told us to not insert new
12205              locations, we may still need to update conditions on the
12206              target's side of breakpoints that were already inserted
12207              if the target is evaluating breakpoint conditions.  We
12208              only update conditions for locations that are marked
12209              "needs_update".  */
12210           update_inserted_breakpoint_locations ();
12211         }
12212     }
12213
12214   if (insert_mode != UGLL_DONT_INSERT)
12215     download_tracepoint_locations ();
12216 }
12217
12218 void
12219 breakpoint_retire_moribund (void)
12220 {
12221   struct bp_location *loc;
12222   int ix;
12223
12224   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12225     if (--(loc->events_till_retirement) == 0)
12226       {
12227         decref_bp_location (&loc);
12228         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12229         --ix;
12230       }
12231 }
12232
12233 static void
12234 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12235 {
12236
12237   TRY
12238     {
12239       update_global_location_list (insert_mode);
12240     }
12241   CATCH (e, RETURN_MASK_ERROR)
12242     {
12243     }
12244   END_CATCH
12245 }
12246
12247 /* Clear BKP from a BPS.  */
12248
12249 static void
12250 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12251 {
12252   bpstat bs;
12253
12254   for (bs = bps; bs; bs = bs->next)
12255     if (bs->breakpoint_at == bpt)
12256       {
12257         bs->breakpoint_at = NULL;
12258         bs->old_val = NULL;
12259         /* bs->commands will be freed later.  */
12260       }
12261 }
12262
12263 /* Callback for iterate_over_threads.  */
12264 static int
12265 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12266 {
12267   struct breakpoint *bpt = (struct breakpoint *) data;
12268
12269   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12270   return 0;
12271 }
12272
12273 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12274    callbacks.  */
12275
12276 static void
12277 say_where (struct breakpoint *b)
12278 {
12279   struct value_print_options opts;
12280
12281   get_user_print_options (&opts);
12282
12283   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12284      single string.  */
12285   if (b->loc == NULL)
12286     {
12287       /* For pending locations, the output differs slightly based
12288          on b->extra_string.  If this is non-NULL, it contains either
12289          a condition or dprintf arguments.  */
12290       if (b->extra_string == NULL)
12291         {
12292           printf_filtered (_(" (%s) pending."),
12293                            event_location_to_string (b->location.get ()));
12294         }
12295       else if (b->type == bp_dprintf)
12296         {
12297           printf_filtered (_(" (%s,%s) pending."),
12298                            event_location_to_string (b->location.get ()),
12299                            b->extra_string);
12300         }
12301       else
12302         {
12303           printf_filtered (_(" (%s %s) pending."),
12304                            event_location_to_string (b->location.get ()),
12305                            b->extra_string);
12306         }
12307     }
12308   else
12309     {
12310       if (opts.addressprint || b->loc->symtab == NULL)
12311         {
12312           printf_filtered (" at ");
12313           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12314                           gdb_stdout);
12315         }
12316       if (b->loc->symtab != NULL)
12317         {
12318           /* If there is a single location, we can print the location
12319              more nicely.  */
12320           if (b->loc->next == NULL)
12321             printf_filtered (": file %s, line %d.",
12322                              symtab_to_filename_for_display (b->loc->symtab),
12323                              b->loc->line_number);
12324           else
12325             /* This is not ideal, but each location may have a
12326                different file name, and this at least reflects the
12327                real situation somewhat.  */
12328             printf_filtered (": %s.",
12329                              event_location_to_string (b->location.get ()));
12330         }
12331
12332       if (b->loc->next)
12333         {
12334           struct bp_location *loc = b->loc;
12335           int n = 0;
12336           for (; loc; loc = loc->next)
12337             ++n;
12338           printf_filtered (" (%d locations)", n);
12339         }
12340     }
12341 }
12342
12343 /* Default bp_location_ops methods.  */
12344
12345 static void
12346 bp_location_dtor (struct bp_location *self)
12347 {
12348   xfree (self->function_name);
12349 }
12350
12351 static const struct bp_location_ops bp_location_ops =
12352 {
12353   bp_location_dtor
12354 };
12355
12356 /* Destructor for the breakpoint base class.  */
12357
12358 breakpoint::~breakpoint ()
12359 {
12360   xfree (this->cond_string);
12361   xfree (this->extra_string);
12362   xfree (this->filter);
12363 }
12364
12365 static struct bp_location *
12366 base_breakpoint_allocate_location (struct breakpoint *self)
12367 {
12368   return new bp_location (&bp_location_ops, self);
12369 }
12370
12371 static void
12372 base_breakpoint_re_set (struct breakpoint *b)
12373 {
12374   /* Nothing to re-set. */
12375 }
12376
12377 #define internal_error_pure_virtual_called() \
12378   gdb_assert_not_reached ("pure virtual function called")
12379
12380 static int
12381 base_breakpoint_insert_location (struct bp_location *bl)
12382 {
12383   internal_error_pure_virtual_called ();
12384 }
12385
12386 static int
12387 base_breakpoint_remove_location (struct bp_location *bl,
12388                                  enum remove_bp_reason reason)
12389 {
12390   internal_error_pure_virtual_called ();
12391 }
12392
12393 static int
12394 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12395                                 const address_space *aspace,
12396                                 CORE_ADDR bp_addr,
12397                                 const struct target_waitstatus *ws)
12398 {
12399   internal_error_pure_virtual_called ();
12400 }
12401
12402 static void
12403 base_breakpoint_check_status (bpstat bs)
12404 {
12405   /* Always stop.   */
12406 }
12407
12408 /* A "works_in_software_mode" breakpoint_ops method that just internal
12409    errors.  */
12410
12411 static int
12412 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12413 {
12414   internal_error_pure_virtual_called ();
12415 }
12416
12417 /* A "resources_needed" breakpoint_ops method that just internal
12418    errors.  */
12419
12420 static int
12421 base_breakpoint_resources_needed (const struct bp_location *bl)
12422 {
12423   internal_error_pure_virtual_called ();
12424 }
12425
12426 static enum print_stop_action
12427 base_breakpoint_print_it (bpstat bs)
12428 {
12429   internal_error_pure_virtual_called ();
12430 }
12431
12432 static void
12433 base_breakpoint_print_one_detail (const struct breakpoint *self,
12434                                   struct ui_out *uiout)
12435 {
12436   /* nothing */
12437 }
12438
12439 static void
12440 base_breakpoint_print_mention (struct breakpoint *b)
12441 {
12442   internal_error_pure_virtual_called ();
12443 }
12444
12445 static void
12446 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12447 {
12448   internal_error_pure_virtual_called ();
12449 }
12450
12451 static void
12452 base_breakpoint_create_sals_from_location
12453   (const struct event_location *location,
12454    struct linespec_result *canonical,
12455    enum bptype type_wanted)
12456 {
12457   internal_error_pure_virtual_called ();
12458 }
12459
12460 static void
12461 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12462                                         struct linespec_result *c,
12463                                         gdb::unique_xmalloc_ptr<char> cond_string,
12464                                         gdb::unique_xmalloc_ptr<char> extra_string,
12465                                         enum bptype type_wanted,
12466                                         enum bpdisp disposition,
12467                                         int thread,
12468                                         int task, int ignore_count,
12469                                         const struct breakpoint_ops *o,
12470                                         int from_tty, int enabled,
12471                                         int internal, unsigned flags)
12472 {
12473   internal_error_pure_virtual_called ();
12474 }
12475
12476 static std::vector<symtab_and_line>
12477 base_breakpoint_decode_location (struct breakpoint *b,
12478                                  const struct event_location *location,
12479                                  struct program_space *search_pspace)
12480 {
12481   internal_error_pure_virtual_called ();
12482 }
12483
12484 /* The default 'explains_signal' method.  */
12485
12486 static int
12487 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12488 {
12489   return 1;
12490 }
12491
12492 /* The default "after_condition_true" method.  */
12493
12494 static void
12495 base_breakpoint_after_condition_true (struct bpstats *bs)
12496 {
12497   /* Nothing to do.   */
12498 }
12499
12500 struct breakpoint_ops base_breakpoint_ops =
12501 {
12502   base_breakpoint_allocate_location,
12503   base_breakpoint_re_set,
12504   base_breakpoint_insert_location,
12505   base_breakpoint_remove_location,
12506   base_breakpoint_breakpoint_hit,
12507   base_breakpoint_check_status,
12508   base_breakpoint_resources_needed,
12509   base_breakpoint_works_in_software_mode,
12510   base_breakpoint_print_it,
12511   NULL,
12512   base_breakpoint_print_one_detail,
12513   base_breakpoint_print_mention,
12514   base_breakpoint_print_recreate,
12515   base_breakpoint_create_sals_from_location,
12516   base_breakpoint_create_breakpoints_sal,
12517   base_breakpoint_decode_location,
12518   base_breakpoint_explains_signal,
12519   base_breakpoint_after_condition_true,
12520 };
12521
12522 /* Default breakpoint_ops methods.  */
12523
12524 static void
12525 bkpt_re_set (struct breakpoint *b)
12526 {
12527   /* FIXME: is this still reachable?  */
12528   if (breakpoint_event_location_empty_p (b))
12529     {
12530       /* Anything without a location can't be re-set.  */
12531       delete_breakpoint (b);
12532       return;
12533     }
12534
12535   breakpoint_re_set_default (b);
12536 }
12537
12538 static int
12539 bkpt_insert_location (struct bp_location *bl)
12540 {
12541   CORE_ADDR addr = bl->target_info.reqstd_address;
12542
12543   bl->target_info.kind = breakpoint_kind (bl, &addr);
12544   bl->target_info.placed_address = addr;
12545
12546   if (bl->loc_type == bp_loc_hardware_breakpoint)
12547     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12548   else
12549     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12550 }
12551
12552 static int
12553 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12554 {
12555   if (bl->loc_type == bp_loc_hardware_breakpoint)
12556     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12557   else
12558     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12559 }
12560
12561 static int
12562 bkpt_breakpoint_hit (const struct bp_location *bl,
12563                      const address_space *aspace, CORE_ADDR bp_addr,
12564                      const struct target_waitstatus *ws)
12565 {
12566   if (ws->kind != TARGET_WAITKIND_STOPPED
12567       || ws->value.sig != GDB_SIGNAL_TRAP)
12568     return 0;
12569
12570   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12571                                  aspace, bp_addr))
12572     return 0;
12573
12574   if (overlay_debugging         /* unmapped overlay section */
12575       && section_is_overlay (bl->section)
12576       && !section_is_mapped (bl->section))
12577     return 0;
12578
12579   return 1;
12580 }
12581
12582 static int
12583 dprintf_breakpoint_hit (const struct bp_location *bl,
12584                         const address_space *aspace, CORE_ADDR bp_addr,
12585                         const struct target_waitstatus *ws)
12586 {
12587   if (dprintf_style == dprintf_style_agent
12588       && target_can_run_breakpoint_commands ())
12589     {
12590       /* An agent-style dprintf never causes a stop.  If we see a trap
12591          for this address it must be for a breakpoint that happens to
12592          be set at the same address.  */
12593       return 0;
12594     }
12595
12596   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12597 }
12598
12599 static int
12600 bkpt_resources_needed (const struct bp_location *bl)
12601 {
12602   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12603
12604   return 1;
12605 }
12606
12607 static enum print_stop_action
12608 bkpt_print_it (bpstat bs)
12609 {
12610   struct breakpoint *b;
12611   const struct bp_location *bl;
12612   int bp_temp;
12613   struct ui_out *uiout = current_uiout;
12614
12615   gdb_assert (bs->bp_location_at != NULL);
12616
12617   bl = bs->bp_location_at;
12618   b = bs->breakpoint_at;
12619
12620   bp_temp = b->disposition == disp_del;
12621   if (bl->address != bl->requested_address)
12622     breakpoint_adjustment_warning (bl->requested_address,
12623                                    bl->address,
12624                                    b->number, 1);
12625   annotate_breakpoint (b->number);
12626   maybe_print_thread_hit_breakpoint (uiout);
12627
12628   if (bp_temp)
12629     uiout->text ("Temporary breakpoint ");
12630   else
12631     uiout->text ("Breakpoint ");
12632   if (uiout->is_mi_like_p ())
12633     {
12634       uiout->field_string ("reason",
12635                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12636       uiout->field_string ("disp", bpdisp_text (b->disposition));
12637     }
12638   uiout->field_int ("bkptno", b->number);
12639   uiout->text (", ");
12640
12641   return PRINT_SRC_AND_LOC;
12642 }
12643
12644 static void
12645 bkpt_print_mention (struct breakpoint *b)
12646 {
12647   if (current_uiout->is_mi_like_p ())
12648     return;
12649
12650   switch (b->type)
12651     {
12652     case bp_breakpoint:
12653     case bp_gnu_ifunc_resolver:
12654       if (b->disposition == disp_del)
12655         printf_filtered (_("Temporary breakpoint"));
12656       else
12657         printf_filtered (_("Breakpoint"));
12658       printf_filtered (_(" %d"), b->number);
12659       if (b->type == bp_gnu_ifunc_resolver)
12660         printf_filtered (_(" at gnu-indirect-function resolver"));
12661       break;
12662     case bp_hardware_breakpoint:
12663       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12664       break;
12665     case bp_dprintf:
12666       printf_filtered (_("Dprintf %d"), b->number);
12667       break;
12668     }
12669
12670   say_where (b);
12671 }
12672
12673 static void
12674 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12675 {
12676   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12677     fprintf_unfiltered (fp, "tbreak");
12678   else if (tp->type == bp_breakpoint)
12679     fprintf_unfiltered (fp, "break");
12680   else if (tp->type == bp_hardware_breakpoint
12681            && tp->disposition == disp_del)
12682     fprintf_unfiltered (fp, "thbreak");
12683   else if (tp->type == bp_hardware_breakpoint)
12684     fprintf_unfiltered (fp, "hbreak");
12685   else
12686     internal_error (__FILE__, __LINE__,
12687                     _("unhandled breakpoint type %d"), (int) tp->type);
12688
12689   fprintf_unfiltered (fp, " %s",
12690                       event_location_to_string (tp->location.get ()));
12691
12692   /* Print out extra_string if this breakpoint is pending.  It might
12693      contain, for example, conditions that were set by the user.  */
12694   if (tp->loc == NULL && tp->extra_string != NULL)
12695     fprintf_unfiltered (fp, " %s", tp->extra_string);
12696
12697   print_recreate_thread (tp, fp);
12698 }
12699
12700 static void
12701 bkpt_create_sals_from_location (const struct event_location *location,
12702                                 struct linespec_result *canonical,
12703                                 enum bptype type_wanted)
12704 {
12705   create_sals_from_location_default (location, canonical, type_wanted);
12706 }
12707
12708 static void
12709 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12710                              struct linespec_result *canonical,
12711                              gdb::unique_xmalloc_ptr<char> cond_string,
12712                              gdb::unique_xmalloc_ptr<char> extra_string,
12713                              enum bptype type_wanted,
12714                              enum bpdisp disposition,
12715                              int thread,
12716                              int task, int ignore_count,
12717                              const struct breakpoint_ops *ops,
12718                              int from_tty, int enabled,
12719                              int internal, unsigned flags)
12720 {
12721   create_breakpoints_sal_default (gdbarch, canonical,
12722                                   std::move (cond_string),
12723                                   std::move (extra_string),
12724                                   type_wanted,
12725                                   disposition, thread, task,
12726                                   ignore_count, ops, from_tty,
12727                                   enabled, internal, flags);
12728 }
12729
12730 static std::vector<symtab_and_line>
12731 bkpt_decode_location (struct breakpoint *b,
12732                       const struct event_location *location,
12733                       struct program_space *search_pspace)
12734 {
12735   return decode_location_default (b, location, search_pspace);
12736 }
12737
12738 /* Virtual table for internal breakpoints.  */
12739
12740 static void
12741 internal_bkpt_re_set (struct breakpoint *b)
12742 {
12743   switch (b->type)
12744     {
12745       /* Delete overlay event and longjmp master breakpoints; they
12746          will be reset later by breakpoint_re_set.  */
12747     case bp_overlay_event:
12748     case bp_longjmp_master:
12749     case bp_std_terminate_master:
12750     case bp_exception_master:
12751       delete_breakpoint (b);
12752       break;
12753
12754       /* This breakpoint is special, it's set up when the inferior
12755          starts and we really don't want to touch it.  */
12756     case bp_shlib_event:
12757
12758       /* Like bp_shlib_event, this breakpoint type is special.  Once
12759          it is set up, we do not want to touch it.  */
12760     case bp_thread_event:
12761       break;
12762     }
12763 }
12764
12765 static void
12766 internal_bkpt_check_status (bpstat bs)
12767 {
12768   if (bs->breakpoint_at->type == bp_shlib_event)
12769     {
12770       /* If requested, stop when the dynamic linker notifies GDB of
12771          events.  This allows the user to get control and place
12772          breakpoints in initializer routines for dynamically loaded
12773          objects (among other things).  */
12774       bs->stop = stop_on_solib_events;
12775       bs->print = stop_on_solib_events;
12776     }
12777   else
12778     bs->stop = 0;
12779 }
12780
12781 static enum print_stop_action
12782 internal_bkpt_print_it (bpstat bs)
12783 {
12784   struct breakpoint *b;
12785
12786   b = bs->breakpoint_at;
12787
12788   switch (b->type)
12789     {
12790     case bp_shlib_event:
12791       /* Did we stop because the user set the stop_on_solib_events
12792          variable?  (If so, we report this as a generic, "Stopped due
12793          to shlib event" message.) */
12794       print_solib_event (0);
12795       break;
12796
12797     case bp_thread_event:
12798       /* Not sure how we will get here.
12799          GDB should not stop for these breakpoints.  */
12800       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12801       break;
12802
12803     case bp_overlay_event:
12804       /* By analogy with the thread event, GDB should not stop for these.  */
12805       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12806       break;
12807
12808     case bp_longjmp_master:
12809       /* These should never be enabled.  */
12810       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12811       break;
12812
12813     case bp_std_terminate_master:
12814       /* These should never be enabled.  */
12815       printf_filtered (_("std::terminate Master Breakpoint: "
12816                          "gdb should not stop!\n"));
12817       break;
12818
12819     case bp_exception_master:
12820       /* These should never be enabled.  */
12821       printf_filtered (_("Exception Master Breakpoint: "
12822                          "gdb should not stop!\n"));
12823       break;
12824     }
12825
12826   return PRINT_NOTHING;
12827 }
12828
12829 static void
12830 internal_bkpt_print_mention (struct breakpoint *b)
12831 {
12832   /* Nothing to mention.  These breakpoints are internal.  */
12833 }
12834
12835 /* Virtual table for momentary breakpoints  */
12836
12837 static void
12838 momentary_bkpt_re_set (struct breakpoint *b)
12839 {
12840   /* Keep temporary breakpoints, which can be encountered when we step
12841      over a dlopen call and solib_add is resetting the breakpoints.
12842      Otherwise these should have been blown away via the cleanup chain
12843      or by breakpoint_init_inferior when we rerun the executable.  */
12844 }
12845
12846 static void
12847 momentary_bkpt_check_status (bpstat bs)
12848 {
12849   /* Nothing.  The point of these breakpoints is causing a stop.  */
12850 }
12851
12852 static enum print_stop_action
12853 momentary_bkpt_print_it (bpstat bs)
12854 {
12855   return PRINT_UNKNOWN;
12856 }
12857
12858 static void
12859 momentary_bkpt_print_mention (struct breakpoint *b)
12860 {
12861   /* Nothing to mention.  These breakpoints are internal.  */
12862 }
12863
12864 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12865
12866    It gets cleared already on the removal of the first one of such placed
12867    breakpoints.  This is OK as they get all removed altogether.  */
12868
12869 longjmp_breakpoint::~longjmp_breakpoint ()
12870 {
12871   thread_info *tp = find_thread_global_id (this->thread);
12872
12873   if (tp != NULL)
12874     tp->initiating_frame = null_frame_id;
12875 }
12876
12877 /* Specific methods for probe breakpoints.  */
12878
12879 static int
12880 bkpt_probe_insert_location (struct bp_location *bl)
12881 {
12882   int v = bkpt_insert_location (bl);
12883
12884   if (v == 0)
12885     {
12886       /* The insertion was successful, now let's set the probe's semaphore
12887          if needed.  */
12888       if (bl->probe.probe->pops->set_semaphore != NULL)
12889         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
12890                                               bl->probe.objfile,
12891                                               bl->gdbarch);
12892     }
12893
12894   return v;
12895 }
12896
12897 static int
12898 bkpt_probe_remove_location (struct bp_location *bl,
12899                             enum remove_bp_reason reason)
12900 {
12901   /* Let's clear the semaphore before removing the location.  */
12902   if (bl->probe.probe->pops->clear_semaphore != NULL)
12903     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
12904                                             bl->probe.objfile,
12905                                             bl->gdbarch);
12906
12907   return bkpt_remove_location (bl, reason);
12908 }
12909
12910 static void
12911 bkpt_probe_create_sals_from_location (const struct event_location *location,
12912                                       struct linespec_result *canonical,
12913                                       enum bptype type_wanted)
12914 {
12915   struct linespec_sals lsal;
12916
12917   lsal.sals = parse_probes (location, NULL, canonical);
12918   lsal.canonical
12919     = xstrdup (event_location_to_string (canonical->location.get ()));
12920   canonical->lsals.push_back (std::move (lsal));
12921 }
12922
12923 static std::vector<symtab_and_line>
12924 bkpt_probe_decode_location (struct breakpoint *b,
12925                             const struct event_location *location,
12926                             struct program_space *search_pspace)
12927 {
12928   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12929   if (sals.empty ())
12930     error (_("probe not found"));
12931   return sals;
12932 }
12933
12934 /* The breakpoint_ops structure to be used in tracepoints.  */
12935
12936 static void
12937 tracepoint_re_set (struct breakpoint *b)
12938 {
12939   breakpoint_re_set_default (b);
12940 }
12941
12942 static int
12943 tracepoint_breakpoint_hit (const struct bp_location *bl,
12944                            const address_space *aspace, CORE_ADDR bp_addr,
12945                            const struct target_waitstatus *ws)
12946 {
12947   /* By definition, the inferior does not report stops at
12948      tracepoints.  */
12949   return 0;
12950 }
12951
12952 static void
12953 tracepoint_print_one_detail (const struct breakpoint *self,
12954                              struct ui_out *uiout)
12955 {
12956   struct tracepoint *tp = (struct tracepoint *) self;
12957   if (tp->static_trace_marker_id)
12958     {
12959       gdb_assert (self->type == bp_static_tracepoint);
12960
12961       uiout->text ("\tmarker id is ");
12962       uiout->field_string ("static-tracepoint-marker-string-id",
12963                            tp->static_trace_marker_id);
12964       uiout->text ("\n");
12965     }
12966 }
12967
12968 static void
12969 tracepoint_print_mention (struct breakpoint *b)
12970 {
12971   if (current_uiout->is_mi_like_p ())
12972     return;
12973
12974   switch (b->type)
12975     {
12976     case bp_tracepoint:
12977       printf_filtered (_("Tracepoint"));
12978       printf_filtered (_(" %d"), b->number);
12979       break;
12980     case bp_fast_tracepoint:
12981       printf_filtered (_("Fast tracepoint"));
12982       printf_filtered (_(" %d"), b->number);
12983       break;
12984     case bp_static_tracepoint:
12985       printf_filtered (_("Static tracepoint"));
12986       printf_filtered (_(" %d"), b->number);
12987       break;
12988     default:
12989       internal_error (__FILE__, __LINE__,
12990                       _("unhandled tracepoint type %d"), (int) b->type);
12991     }
12992
12993   say_where (b);
12994 }
12995
12996 static void
12997 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12998 {
12999   struct tracepoint *tp = (struct tracepoint *) self;
13000
13001   if (self->type == bp_fast_tracepoint)
13002     fprintf_unfiltered (fp, "ftrace");
13003   else if (self->type == bp_static_tracepoint)
13004     fprintf_unfiltered (fp, "strace");
13005   else if (self->type == bp_tracepoint)
13006     fprintf_unfiltered (fp, "trace");
13007   else
13008     internal_error (__FILE__, __LINE__,
13009                     _("unhandled tracepoint type %d"), (int) self->type);
13010
13011   fprintf_unfiltered (fp, " %s",
13012                       event_location_to_string (self->location.get ()));
13013   print_recreate_thread (self, fp);
13014
13015   if (tp->pass_count)
13016     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13017 }
13018
13019 static void
13020 tracepoint_create_sals_from_location (const struct event_location *location,
13021                                       struct linespec_result *canonical,
13022                                       enum bptype type_wanted)
13023 {
13024   create_sals_from_location_default (location, canonical, type_wanted);
13025 }
13026
13027 static void
13028 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13029                                    struct linespec_result *canonical,
13030                                    gdb::unique_xmalloc_ptr<char> cond_string,
13031                                    gdb::unique_xmalloc_ptr<char> extra_string,
13032                                    enum bptype type_wanted,
13033                                    enum bpdisp disposition,
13034                                    int thread,
13035                                    int task, int ignore_count,
13036                                    const struct breakpoint_ops *ops,
13037                                    int from_tty, int enabled,
13038                                    int internal, unsigned flags)
13039 {
13040   create_breakpoints_sal_default (gdbarch, canonical,
13041                                   std::move (cond_string),
13042                                   std::move (extra_string),
13043                                   type_wanted,
13044                                   disposition, thread, task,
13045                                   ignore_count, ops, from_tty,
13046                                   enabled, internal, flags);
13047 }
13048
13049 static std::vector<symtab_and_line>
13050 tracepoint_decode_location (struct breakpoint *b,
13051                             const struct event_location *location,
13052                             struct program_space *search_pspace)
13053 {
13054   return decode_location_default (b, location, search_pspace);
13055 }
13056
13057 struct breakpoint_ops tracepoint_breakpoint_ops;
13058
13059 /* The breakpoint_ops structure to be use on tracepoints placed in a
13060    static probe.  */
13061
13062 static void
13063 tracepoint_probe_create_sals_from_location
13064   (const struct event_location *location,
13065    struct linespec_result *canonical,
13066    enum bptype type_wanted)
13067 {
13068   /* We use the same method for breakpoint on probes.  */
13069   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13070 }
13071
13072 static std::vector<symtab_and_line>
13073 tracepoint_probe_decode_location (struct breakpoint *b,
13074                                   const struct event_location *location,
13075                                   struct program_space *search_pspace)
13076 {
13077   /* We use the same method for breakpoint on probes.  */
13078   return bkpt_probe_decode_location (b, location, search_pspace);
13079 }
13080
13081 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13082
13083 /* Dprintf breakpoint_ops methods.  */
13084
13085 static void
13086 dprintf_re_set (struct breakpoint *b)
13087 {
13088   breakpoint_re_set_default (b);
13089
13090   /* extra_string should never be non-NULL for dprintf.  */
13091   gdb_assert (b->extra_string != NULL);
13092
13093   /* 1 - connect to target 1, that can run breakpoint commands.
13094      2 - create a dprintf, which resolves fine.
13095      3 - disconnect from target 1
13096      4 - connect to target 2, that can NOT run breakpoint commands.
13097
13098      After steps #3/#4, you'll want the dprintf command list to
13099      be updated, because target 1 and 2 may well return different
13100      answers for target_can_run_breakpoint_commands().
13101      Given absence of finer grained resetting, we get to do
13102      it all the time.  */
13103   if (b->extra_string != NULL)
13104     update_dprintf_command_list (b);
13105 }
13106
13107 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13108
13109 static void
13110 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13111 {
13112   fprintf_unfiltered (fp, "dprintf %s,%s",
13113                       event_location_to_string (tp->location.get ()),
13114                       tp->extra_string);
13115   print_recreate_thread (tp, fp);
13116 }
13117
13118 /* Implement the "after_condition_true" breakpoint_ops method for
13119    dprintf.
13120
13121    dprintf's are implemented with regular commands in their command
13122    list, but we run the commands here instead of before presenting the
13123    stop to the user, as dprintf's don't actually cause a stop.  This
13124    also makes it so that the commands of multiple dprintfs at the same
13125    address are all handled.  */
13126
13127 static void
13128 dprintf_after_condition_true (struct bpstats *bs)
13129 {
13130   struct bpstats tmp_bs;
13131   struct bpstats *tmp_bs_p = &tmp_bs;
13132
13133   /* dprintf's never cause a stop.  This wasn't set in the
13134      check_status hook instead because that would make the dprintf's
13135      condition not be evaluated.  */
13136   bs->stop = 0;
13137
13138   /* Run the command list here.  Take ownership of it instead of
13139      copying.  We never want these commands to run later in
13140      bpstat_do_actions, if a breakpoint that causes a stop happens to
13141      be set at same address as this dprintf, or even if running the
13142      commands here throws.  */
13143   tmp_bs.commands = bs->commands;
13144   bs->commands = NULL;
13145
13146   bpstat_do_actions_1 (&tmp_bs_p);
13147
13148   /* 'tmp_bs.commands' will usually be NULL by now, but
13149      bpstat_do_actions_1 may return early without processing the whole
13150      list.  */
13151 }
13152
13153 /* The breakpoint_ops structure to be used on static tracepoints with
13154    markers (`-m').  */
13155
13156 static void
13157 strace_marker_create_sals_from_location (const struct event_location *location,
13158                                          struct linespec_result *canonical,
13159                                          enum bptype type_wanted)
13160 {
13161   struct linespec_sals lsal;
13162   const char *arg_start, *arg;
13163
13164   arg = arg_start = get_linespec_location (location);
13165   lsal.sals = decode_static_tracepoint_spec (&arg);
13166
13167   std::string str (arg_start, arg - arg_start);
13168   const char *ptr = str.c_str ();
13169   canonical->location = new_linespec_location (&ptr);
13170
13171   lsal.canonical
13172     = xstrdup (event_location_to_string (canonical->location.get ()));
13173   canonical->lsals.push_back (std::move (lsal));
13174 }
13175
13176 static void
13177 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13178                                       struct linespec_result *canonical,
13179                                       gdb::unique_xmalloc_ptr<char> cond_string,
13180                                       gdb::unique_xmalloc_ptr<char> extra_string,
13181                                       enum bptype type_wanted,
13182                                       enum bpdisp disposition,
13183                                       int thread,
13184                                       int task, int ignore_count,
13185                                       const struct breakpoint_ops *ops,
13186                                       int from_tty, int enabled,
13187                                       int internal, unsigned flags)
13188 {
13189   const linespec_sals &lsal = canonical->lsals[0];
13190
13191   /* If the user is creating a static tracepoint by marker id
13192      (strace -m MARKER_ID), then store the sals index, so that
13193      breakpoint_re_set can try to match up which of the newly
13194      found markers corresponds to this one, and, don't try to
13195      expand multiple locations for each sal, given than SALS
13196      already should contain all sals for MARKER_ID.  */
13197
13198   for (size_t i = 0; i < lsal.sals.size (); i++)
13199     {
13200       event_location_up location
13201         = copy_event_location (canonical->location.get ());
13202
13203       std::unique_ptr<tracepoint> tp (new tracepoint ());
13204       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13205                            std::move (location), NULL,
13206                            std::move (cond_string),
13207                            std::move (extra_string),
13208                            type_wanted, disposition,
13209                            thread, task, ignore_count, ops,
13210                            from_tty, enabled, internal, flags,
13211                            canonical->special_display);
13212       /* Given that its possible to have multiple markers with
13213          the same string id, if the user is creating a static
13214          tracepoint by marker id ("strace -m MARKER_ID"), then
13215          store the sals index, so that breakpoint_re_set can
13216          try to match up which of the newly found markers
13217          corresponds to this one  */
13218       tp->static_trace_marker_id_idx = i;
13219
13220       install_breakpoint (internal, std::move (tp), 0);
13221     }
13222 }
13223
13224 static std::vector<symtab_and_line>
13225 strace_marker_decode_location (struct breakpoint *b,
13226                                const struct event_location *location,
13227                                struct program_space *search_pspace)
13228 {
13229   struct tracepoint *tp = (struct tracepoint *) b;
13230   const char *s = get_linespec_location (location);
13231
13232   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13233   if (sals.size () > tp->static_trace_marker_id_idx)
13234     {
13235       sals[0] = sals[tp->static_trace_marker_id_idx];
13236       sals.resize (1);
13237       return sals;
13238     }
13239   else
13240     error (_("marker %s not found"), tp->static_trace_marker_id);
13241 }
13242
13243 static struct breakpoint_ops strace_marker_breakpoint_ops;
13244
13245 static int
13246 strace_marker_p (struct breakpoint *b)
13247 {
13248   return b->ops == &strace_marker_breakpoint_ops;
13249 }
13250
13251 /* Delete a breakpoint and clean up all traces of it in the data
13252    structures.  */
13253
13254 void
13255 delete_breakpoint (struct breakpoint *bpt)
13256 {
13257   struct breakpoint *b;
13258
13259   gdb_assert (bpt != NULL);
13260
13261   /* Has this bp already been deleted?  This can happen because
13262      multiple lists can hold pointers to bp's.  bpstat lists are
13263      especial culprits.
13264
13265      One example of this happening is a watchpoint's scope bp.  When
13266      the scope bp triggers, we notice that the watchpoint is out of
13267      scope, and delete it.  We also delete its scope bp.  But the
13268      scope bp is marked "auto-deleting", and is already on a bpstat.
13269      That bpstat is then checked for auto-deleting bp's, which are
13270      deleted.
13271
13272      A real solution to this problem might involve reference counts in
13273      bp's, and/or giving them pointers back to their referencing
13274      bpstat's, and teaching delete_breakpoint to only free a bp's
13275      storage when no more references were extent.  A cheaper bandaid
13276      was chosen.  */
13277   if (bpt->type == bp_none)
13278     return;
13279
13280   /* At least avoid this stale reference until the reference counting
13281      of breakpoints gets resolved.  */
13282   if (bpt->related_breakpoint != bpt)
13283     {
13284       struct breakpoint *related;
13285       struct watchpoint *w;
13286
13287       if (bpt->type == bp_watchpoint_scope)
13288         w = (struct watchpoint *) bpt->related_breakpoint;
13289       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13290         w = (struct watchpoint *) bpt;
13291       else
13292         w = NULL;
13293       if (w != NULL)
13294         watchpoint_del_at_next_stop (w);
13295
13296       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13297       for (related = bpt; related->related_breakpoint != bpt;
13298            related = related->related_breakpoint);
13299       related->related_breakpoint = bpt->related_breakpoint;
13300       bpt->related_breakpoint = bpt;
13301     }
13302
13303   /* watch_command_1 creates a watchpoint but only sets its number if
13304      update_watchpoint succeeds in creating its bp_locations.  If there's
13305      a problem in that process, we'll be asked to delete the half-created
13306      watchpoint.  In that case, don't announce the deletion.  */
13307   if (bpt->number)
13308     observer_notify_breakpoint_deleted (bpt);
13309
13310   if (breakpoint_chain == bpt)
13311     breakpoint_chain = bpt->next;
13312
13313   ALL_BREAKPOINTS (b)
13314     if (b->next == bpt)
13315     {
13316       b->next = bpt->next;
13317       break;
13318     }
13319
13320   /* Be sure no bpstat's are pointing at the breakpoint after it's
13321      been freed.  */
13322   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13323      in all threads for now.  Note that we cannot just remove bpstats
13324      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13325      commands are associated with the bpstat; if we remove it here,
13326      then the later call to bpstat_do_actions (&stop_bpstat); in
13327      event-top.c won't do anything, and temporary breakpoints with
13328      commands won't work.  */
13329
13330   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13331
13332   /* Now that breakpoint is removed from breakpoint list, update the
13333      global location list.  This will remove locations that used to
13334      belong to this breakpoint.  Do this before freeing the breakpoint
13335      itself, since remove_breakpoint looks at location's owner.  It
13336      might be better design to have location completely
13337      self-contained, but it's not the case now.  */
13338   update_global_location_list (UGLL_DONT_INSERT);
13339
13340   /* On the chance that someone will soon try again to delete this
13341      same bp, we mark it as deleted before freeing its storage.  */
13342   bpt->type = bp_none;
13343   delete bpt;
13344 }
13345
13346 /* Iterator function to call a user-provided callback function once
13347    for each of B and its related breakpoints.  */
13348
13349 static void
13350 iterate_over_related_breakpoints (struct breakpoint *b,
13351                                   gdb::function_view<void (breakpoint *)> function)
13352 {
13353   struct breakpoint *related;
13354
13355   related = b;
13356   do
13357     {
13358       struct breakpoint *next;
13359
13360       /* FUNCTION may delete RELATED.  */
13361       next = related->related_breakpoint;
13362
13363       if (next == related)
13364         {
13365           /* RELATED is the last ring entry.  */
13366           function (related);
13367
13368           /* FUNCTION may have deleted it, so we'd never reach back to
13369              B.  There's nothing left to do anyway, so just break
13370              out.  */
13371           break;
13372         }
13373       else
13374         function (related);
13375
13376       related = next;
13377     }
13378   while (related != b);
13379 }
13380
13381 static void
13382 delete_command (const char *arg, int from_tty)
13383 {
13384   struct breakpoint *b, *b_tmp;
13385
13386   dont_repeat ();
13387
13388   if (arg == 0)
13389     {
13390       int breaks_to_delete = 0;
13391
13392       /* Delete all breakpoints if no argument.  Do not delete
13393          internal breakpoints, these have to be deleted with an
13394          explicit breakpoint number argument.  */
13395       ALL_BREAKPOINTS (b)
13396         if (user_breakpoint_p (b))
13397           {
13398             breaks_to_delete = 1;
13399             break;
13400           }
13401
13402       /* Ask user only if there are some breakpoints to delete.  */
13403       if (!from_tty
13404           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13405         {
13406           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13407             if (user_breakpoint_p (b))
13408               delete_breakpoint (b);
13409         }
13410     }
13411   else
13412     map_breakpoint_numbers
13413       (arg, [&] (breakpoint *b)
13414        {
13415          iterate_over_related_breakpoints (b, delete_breakpoint);
13416        });
13417 }
13418
13419 /* Return true if all locations of B bound to PSPACE are pending.  If
13420    PSPACE is NULL, all locations of all program spaces are
13421    considered.  */
13422
13423 static int
13424 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13425 {
13426   struct bp_location *loc;
13427
13428   for (loc = b->loc; loc != NULL; loc = loc->next)
13429     if ((pspace == NULL
13430          || loc->pspace == pspace)
13431         && !loc->shlib_disabled
13432         && !loc->pspace->executing_startup)
13433       return 0;
13434   return 1;
13435 }
13436
13437 /* Subroutine of update_breakpoint_locations to simplify it.
13438    Return non-zero if multiple fns in list LOC have the same name.
13439    Null names are ignored.  */
13440
13441 static int
13442 ambiguous_names_p (struct bp_location *loc)
13443 {
13444   struct bp_location *l;
13445   htab_t htab = htab_create_alloc (13, htab_hash_string,
13446                                    (int (*) (const void *, 
13447                                              const void *)) streq,
13448                                    NULL, xcalloc, xfree);
13449
13450   for (l = loc; l != NULL; l = l->next)
13451     {
13452       const char **slot;
13453       const char *name = l->function_name;
13454
13455       /* Allow for some names to be NULL, ignore them.  */
13456       if (name == NULL)
13457         continue;
13458
13459       slot = (const char **) htab_find_slot (htab, (const void *) name,
13460                                              INSERT);
13461       /* NOTE: We can assume slot != NULL here because xcalloc never
13462          returns NULL.  */
13463       if (*slot != NULL)
13464         {
13465           htab_delete (htab);
13466           return 1;
13467         }
13468       *slot = name;
13469     }
13470
13471   htab_delete (htab);
13472   return 0;
13473 }
13474
13475 /* When symbols change, it probably means the sources changed as well,
13476    and it might mean the static tracepoint markers are no longer at
13477    the same address or line numbers they used to be at last we
13478    checked.  Losing your static tracepoints whenever you rebuild is
13479    undesirable.  This function tries to resync/rematch gdb static
13480    tracepoints with the markers on the target, for static tracepoints
13481    that have not been set by marker id.  Static tracepoint that have
13482    been set by marker id are reset by marker id in breakpoint_re_set.
13483    The heuristic is:
13484
13485    1) For a tracepoint set at a specific address, look for a marker at
13486    the old PC.  If one is found there, assume to be the same marker.
13487    If the name / string id of the marker found is different from the
13488    previous known name, assume that means the user renamed the marker
13489    in the sources, and output a warning.
13490
13491    2) For a tracepoint set at a given line number, look for a marker
13492    at the new address of the old line number.  If one is found there,
13493    assume to be the same marker.  If the name / string id of the
13494    marker found is different from the previous known name, assume that
13495    means the user renamed the marker in the sources, and output a
13496    warning.
13497
13498    3) If a marker is no longer found at the same address or line, it
13499    may mean the marker no longer exists.  But it may also just mean
13500    the code changed a bit.  Maybe the user added a few lines of code
13501    that made the marker move up or down (in line number terms).  Ask
13502    the target for info about the marker with the string id as we knew
13503    it.  If found, update line number and address in the matching
13504    static tracepoint.  This will get confused if there's more than one
13505    marker with the same ID (possible in UST, although unadvised
13506    precisely because it confuses tools).  */
13507
13508 static struct symtab_and_line
13509 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13510 {
13511   struct tracepoint *tp = (struct tracepoint *) b;
13512   struct static_tracepoint_marker marker;
13513   CORE_ADDR pc;
13514
13515   pc = sal.pc;
13516   if (sal.line)
13517     find_line_pc (sal.symtab, sal.line, &pc);
13518
13519   if (target_static_tracepoint_marker_at (pc, &marker))
13520     {
13521       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13522         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13523                  b->number,
13524                  tp->static_trace_marker_id, marker.str_id);
13525
13526       xfree (tp->static_trace_marker_id);
13527       tp->static_trace_marker_id = xstrdup (marker.str_id);
13528       release_static_tracepoint_marker (&marker);
13529
13530       return sal;
13531     }
13532
13533   /* Old marker wasn't found on target at lineno.  Try looking it up
13534      by string ID.  */
13535   if (!sal.explicit_pc
13536       && sal.line != 0
13537       && sal.symtab != NULL
13538       && tp->static_trace_marker_id != NULL)
13539     {
13540       VEC(static_tracepoint_marker_p) *markers;
13541
13542       markers
13543         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13544
13545       if (!VEC_empty(static_tracepoint_marker_p, markers))
13546         {
13547           struct symbol *sym;
13548           struct static_tracepoint_marker *tpmarker;
13549           struct ui_out *uiout = current_uiout;
13550           struct explicit_location explicit_loc;
13551
13552           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13553
13554           xfree (tp->static_trace_marker_id);
13555           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13556
13557           warning (_("marker for static tracepoint %d (%s) not "
13558                      "found at previous line number"),
13559                    b->number, tp->static_trace_marker_id);
13560
13561           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13562           sym = find_pc_sect_function (tpmarker->address, NULL);
13563           uiout->text ("Now in ");
13564           if (sym)
13565             {
13566               uiout->field_string ("func", SYMBOL_PRINT_NAME (sym));
13567               uiout->text (" at ");
13568             }
13569           uiout->field_string ("file",
13570                                symtab_to_filename_for_display (sal2.symtab));
13571           uiout->text (":");
13572
13573           if (uiout->is_mi_like_p ())
13574             {
13575               const char *fullname = symtab_to_fullname (sal2.symtab);
13576
13577               uiout->field_string ("fullname", fullname);
13578             }
13579
13580           uiout->field_int ("line", sal2.line);
13581           uiout->text ("\n");
13582
13583           b->loc->line_number = sal2.line;
13584           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13585
13586           b->location.reset (NULL);
13587           initialize_explicit_location (&explicit_loc);
13588           explicit_loc.source_filename
13589             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13590           explicit_loc.line_offset.offset = b->loc->line_number;
13591           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13592           b->location = new_explicit_location (&explicit_loc);
13593
13594           /* Might be nice to check if function changed, and warn if
13595              so.  */
13596
13597           release_static_tracepoint_marker (tpmarker);
13598         }
13599     }
13600   return sal;
13601 }
13602
13603 /* Returns 1 iff locations A and B are sufficiently same that
13604    we don't need to report breakpoint as changed.  */
13605
13606 static int
13607 locations_are_equal (struct bp_location *a, struct bp_location *b)
13608 {
13609   while (a && b)
13610     {
13611       if (a->address != b->address)
13612         return 0;
13613
13614       if (a->shlib_disabled != b->shlib_disabled)
13615         return 0;
13616
13617       if (a->enabled != b->enabled)
13618         return 0;
13619
13620       a = a->next;
13621       b = b->next;
13622     }
13623
13624   if ((a == NULL) != (b == NULL))
13625     return 0;
13626
13627   return 1;
13628 }
13629
13630 /* Split all locations of B that are bound to PSPACE out of B's
13631    location list to a separate list and return that list's head.  If
13632    PSPACE is NULL, hoist out all locations of B.  */
13633
13634 static struct bp_location *
13635 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13636 {
13637   struct bp_location head;
13638   struct bp_location *i = b->loc;
13639   struct bp_location **i_link = &b->loc;
13640   struct bp_location *hoisted = &head;
13641
13642   if (pspace == NULL)
13643     {
13644       i = b->loc;
13645       b->loc = NULL;
13646       return i;
13647     }
13648
13649   head.next = NULL;
13650
13651   while (i != NULL)
13652     {
13653       if (i->pspace == pspace)
13654         {
13655           *i_link = i->next;
13656           i->next = NULL;
13657           hoisted->next = i;
13658           hoisted = i;
13659         }
13660       else
13661         i_link = &i->next;
13662       i = *i_link;
13663     }
13664
13665   return head.next;
13666 }
13667
13668 /* Create new breakpoint locations for B (a hardware or software
13669    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13670    zero, then B is a ranged breakpoint.  Only recreates locations for
13671    FILTER_PSPACE.  Locations of other program spaces are left
13672    untouched.  */
13673
13674 void
13675 update_breakpoint_locations (struct breakpoint *b,
13676                              struct program_space *filter_pspace,
13677                              gdb::array_view<const symtab_and_line> sals,
13678                              gdb::array_view<const symtab_and_line> sals_end)
13679 {
13680   int i;
13681   struct bp_location *existing_locations;
13682
13683   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13684     {
13685       /* Ranged breakpoints have only one start location and one end
13686          location.  */
13687       b->enable_state = bp_disabled;
13688       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13689                            "multiple locations found\n"),
13690                          b->number);
13691       return;
13692     }
13693
13694   /* If there's no new locations, and all existing locations are
13695      pending, don't do anything.  This optimizes the common case where
13696      all locations are in the same shared library, that was unloaded.
13697      We'd like to retain the location, so that when the library is
13698      loaded again, we don't loose the enabled/disabled status of the
13699      individual locations.  */
13700   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13701     return;
13702
13703   existing_locations = hoist_existing_locations (b, filter_pspace);
13704
13705   for (const auto &sal : sals)
13706     {
13707       struct bp_location *new_loc;
13708
13709       switch_to_program_space_and_thread (sal.pspace);
13710
13711       new_loc = add_location_to_breakpoint (b, &sal);
13712
13713       /* Reparse conditions, they might contain references to the
13714          old symtab.  */
13715       if (b->cond_string != NULL)
13716         {
13717           const char *s;
13718
13719           s = b->cond_string;
13720           TRY
13721             {
13722               new_loc->cond = parse_exp_1 (&s, sal.pc,
13723                                            block_for_pc (sal.pc),
13724                                            0);
13725             }
13726           CATCH (e, RETURN_MASK_ERROR)
13727             {
13728               warning (_("failed to reevaluate condition "
13729                          "for breakpoint %d: %s"), 
13730                        b->number, e.message);
13731               new_loc->enabled = 0;
13732             }
13733           END_CATCH
13734         }
13735
13736       if (!sals_end.empty ())
13737         {
13738           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13739
13740           new_loc->length = end - sals[0].pc + 1;
13741         }
13742     }
13743
13744   /* If possible, carry over 'disable' status from existing
13745      breakpoints.  */
13746   {
13747     struct bp_location *e = existing_locations;
13748     /* If there are multiple breakpoints with the same function name,
13749        e.g. for inline functions, comparing function names won't work.
13750        Instead compare pc addresses; this is just a heuristic as things
13751        may have moved, but in practice it gives the correct answer
13752        often enough until a better solution is found.  */
13753     int have_ambiguous_names = ambiguous_names_p (b->loc);
13754
13755     for (; e; e = e->next)
13756       {
13757         if (!e->enabled && e->function_name)
13758           {
13759             struct bp_location *l = b->loc;
13760             if (have_ambiguous_names)
13761               {
13762                 for (; l; l = l->next)
13763                   if (breakpoint_locations_match (e, l))
13764                     {
13765                       l->enabled = 0;
13766                       break;
13767                     }
13768               }
13769             else
13770               {
13771                 for (; l; l = l->next)
13772                   if (l->function_name
13773                       && strcmp (e->function_name, l->function_name) == 0)
13774                     {
13775                       l->enabled = 0;
13776                       break;
13777                     }
13778               }
13779           }
13780       }
13781   }
13782
13783   if (!locations_are_equal (existing_locations, b->loc))
13784     observer_notify_breakpoint_modified (b);
13785 }
13786
13787 /* Find the SaL locations corresponding to the given LOCATION.
13788    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13789
13790 static std::vector<symtab_and_line>
13791 location_to_sals (struct breakpoint *b, struct event_location *location,
13792                   struct program_space *search_pspace, int *found)
13793 {
13794   struct gdb_exception exception = exception_none;
13795
13796   gdb_assert (b->ops != NULL);
13797
13798   std::vector<symtab_and_line> sals;
13799
13800   TRY
13801     {
13802       sals = b->ops->decode_location (b, location, search_pspace);
13803     }
13804   CATCH (e, RETURN_MASK_ERROR)
13805     {
13806       int not_found_and_ok = 0;
13807
13808       exception = e;
13809
13810       /* For pending breakpoints, it's expected that parsing will
13811          fail until the right shared library is loaded.  User has
13812          already told to create pending breakpoints and don't need
13813          extra messages.  If breakpoint is in bp_shlib_disabled
13814          state, then user already saw the message about that
13815          breakpoint being disabled, and don't want to see more
13816          errors.  */
13817       if (e.error == NOT_FOUND_ERROR
13818           && (b->condition_not_parsed
13819               || (b->loc != NULL
13820                   && search_pspace != NULL
13821                   && b->loc->pspace != search_pspace)
13822               || (b->loc && b->loc->shlib_disabled)
13823               || (b->loc && b->loc->pspace->executing_startup)
13824               || b->enable_state == bp_disabled))
13825         not_found_and_ok = 1;
13826
13827       if (!not_found_and_ok)
13828         {
13829           /* We surely don't want to warn about the same breakpoint
13830              10 times.  One solution, implemented here, is disable
13831              the breakpoint on error.  Another solution would be to
13832              have separate 'warning emitted' flag.  Since this
13833              happens only when a binary has changed, I don't know
13834              which approach is better.  */
13835           b->enable_state = bp_disabled;
13836           throw_exception (e);
13837         }
13838     }
13839   END_CATCH
13840
13841   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13842     {
13843       for (auto &sal : sals)
13844         resolve_sal_pc (&sal);
13845       if (b->condition_not_parsed && b->extra_string != NULL)
13846         {
13847           char *cond_string, *extra_string;
13848           int thread, task;
13849
13850           find_condition_and_thread (b->extra_string, sals[0].pc,
13851                                      &cond_string, &thread, &task,
13852                                      &extra_string);
13853           gdb_assert (b->cond_string == NULL);
13854           if (cond_string)
13855             b->cond_string = cond_string;
13856           b->thread = thread;
13857           b->task = task;
13858           if (extra_string)
13859             {
13860               xfree (b->extra_string);
13861               b->extra_string = extra_string;
13862             }
13863           b->condition_not_parsed = 0;
13864         }
13865
13866       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13867         sals[0] = update_static_tracepoint (b, sals[0]);
13868
13869       *found = 1;
13870     }
13871   else
13872     *found = 0;
13873
13874   return sals;
13875 }
13876
13877 /* The default re_set method, for typical hardware or software
13878    breakpoints.  Reevaluate the breakpoint and recreate its
13879    locations.  */
13880
13881 static void
13882 breakpoint_re_set_default (struct breakpoint *b)
13883 {
13884   struct program_space *filter_pspace = current_program_space;
13885   std::vector<symtab_and_line> expanded, expanded_end;
13886
13887   int found;
13888   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13889                                                         filter_pspace, &found);
13890   if (found)
13891     expanded = std::move (sals);
13892
13893   if (b->location_range_end != NULL)
13894     {
13895       std::vector<symtab_and_line> sals_end
13896         = location_to_sals (b, b->location_range_end.get (),
13897                             filter_pspace, &found);
13898       if (found)
13899         expanded_end = std::move (sals_end);
13900     }
13901
13902   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13903 }
13904
13905 /* Default method for creating SALs from an address string.  It basically
13906    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13907
13908 static void
13909 create_sals_from_location_default (const struct event_location *location,
13910                                    struct linespec_result *canonical,
13911                                    enum bptype type_wanted)
13912 {
13913   parse_breakpoint_sals (location, canonical);
13914 }
13915
13916 /* Call create_breakpoints_sal for the given arguments.  This is the default
13917    function for the `create_breakpoints_sal' method of
13918    breakpoint_ops.  */
13919
13920 static void
13921 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13922                                 struct linespec_result *canonical,
13923                                 gdb::unique_xmalloc_ptr<char> cond_string,
13924                                 gdb::unique_xmalloc_ptr<char> extra_string,
13925                                 enum bptype type_wanted,
13926                                 enum bpdisp disposition,
13927                                 int thread,
13928                                 int task, int ignore_count,
13929                                 const struct breakpoint_ops *ops,
13930                                 int from_tty, int enabled,
13931                                 int internal, unsigned flags)
13932 {
13933   create_breakpoints_sal (gdbarch, canonical,
13934                           std::move (cond_string),
13935                           std::move (extra_string),
13936                           type_wanted, disposition,
13937                           thread, task, ignore_count, ops, from_tty,
13938                           enabled, internal, flags);
13939 }
13940
13941 /* Decode the line represented by S by calling decode_line_full.  This is the
13942    default function for the `decode_location' method of breakpoint_ops.  */
13943
13944 static std::vector<symtab_and_line>
13945 decode_location_default (struct breakpoint *b,
13946                          const struct event_location *location,
13947                          struct program_space *search_pspace)
13948 {
13949   struct linespec_result canonical;
13950
13951   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13952                     (struct symtab *) NULL, 0,
13953                     &canonical, multiple_symbols_all,
13954                     b->filter);
13955
13956   /* We should get 0 or 1 resulting SALs.  */
13957   gdb_assert (canonical.lsals.size () < 2);
13958
13959   if (!canonical.lsals.empty ())
13960     {
13961       const linespec_sals &lsal = canonical.lsals[0];
13962       return std::move (lsal.sals);
13963     }
13964   return {};
13965 }
13966
13967 /* Reset a breakpoint.  */
13968
13969 static void
13970 breakpoint_re_set_one (breakpoint *b)
13971 {
13972   input_radix = b->input_radix;
13973   set_language (b->language);
13974
13975   b->ops->re_set (b);
13976 }
13977
13978 /* Re-set breakpoint locations for the current program space.
13979    Locations bound to other program spaces are left untouched.  */
13980
13981 void
13982 breakpoint_re_set (void)
13983 {
13984   struct breakpoint *b, *b_tmp;
13985
13986   {
13987     scoped_restore_current_language save_language;
13988     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13989     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13990
13991     /* Note: we must not try to insert locations until after all
13992        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13993        breakpoint 1, we'd insert the locations of breakpoint 2, which
13994        hadn't been re-set yet, and thus may have stale locations.  */
13995
13996     ALL_BREAKPOINTS_SAFE (b, b_tmp)
13997       {
13998         TRY
13999           {
14000             breakpoint_re_set_one (b);
14001           }
14002         CATCH (ex, RETURN_MASK_ALL)
14003           {
14004             exception_fprintf (gdb_stderr, ex,
14005                                "Error in re-setting breakpoint %d: ",
14006                                b->number);
14007           }
14008         END_CATCH
14009       }
14010
14011     jit_breakpoint_re_set ();
14012   }
14013
14014   create_overlay_event_breakpoint ();
14015   create_longjmp_master_breakpoint ();
14016   create_std_terminate_master_breakpoint ();
14017   create_exception_master_breakpoint ();
14018
14019   /* Now we can insert.  */
14020   update_global_location_list (UGLL_MAY_INSERT);
14021 }
14022 \f
14023 /* Reset the thread number of this breakpoint:
14024
14025    - If the breakpoint is for all threads, leave it as-is.
14026    - Else, reset it to the current thread for inferior_ptid.  */
14027 void
14028 breakpoint_re_set_thread (struct breakpoint *b)
14029 {
14030   if (b->thread != -1)
14031     {
14032       if (in_thread_list (inferior_ptid))
14033         b->thread = ptid_to_global_thread_id (inferior_ptid);
14034
14035       /* We're being called after following a fork.  The new fork is
14036          selected as current, and unless this was a vfork will have a
14037          different program space from the original thread.  Reset that
14038          as well.  */
14039       b->loc->pspace = current_program_space;
14040     }
14041 }
14042
14043 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14044    If from_tty is nonzero, it prints a message to that effect,
14045    which ends with a period (no newline).  */
14046
14047 void
14048 set_ignore_count (int bptnum, int count, int from_tty)
14049 {
14050   struct breakpoint *b;
14051
14052   if (count < 0)
14053     count = 0;
14054
14055   ALL_BREAKPOINTS (b)
14056     if (b->number == bptnum)
14057     {
14058       if (is_tracepoint (b))
14059         {
14060           if (from_tty && count != 0)
14061             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14062                              bptnum);
14063           return;
14064         }
14065       
14066       b->ignore_count = count;
14067       if (from_tty)
14068         {
14069           if (count == 0)
14070             printf_filtered (_("Will stop next time "
14071                                "breakpoint %d is reached."),
14072                              bptnum);
14073           else if (count == 1)
14074             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14075                              bptnum);
14076           else
14077             printf_filtered (_("Will ignore next %d "
14078                                "crossings of breakpoint %d."),
14079                              count, bptnum);
14080         }
14081       observer_notify_breakpoint_modified (b);
14082       return;
14083     }
14084
14085   error (_("No breakpoint number %d."), bptnum);
14086 }
14087
14088 /* Command to set ignore-count of breakpoint N to COUNT.  */
14089
14090 static void
14091 ignore_command (const char *args, int from_tty)
14092 {
14093   const char *p = args;
14094   int num;
14095
14096   if (p == 0)
14097     error_no_arg (_("a breakpoint number"));
14098
14099   num = get_number (&p);
14100   if (num == 0)
14101     error (_("bad breakpoint number: '%s'"), args);
14102   if (*p == 0)
14103     error (_("Second argument (specified ignore-count) is missing."));
14104
14105   set_ignore_count (num,
14106                     longest_to_int (value_as_long (parse_and_eval (p))),
14107                     from_tty);
14108   if (from_tty)
14109     printf_filtered ("\n");
14110 }
14111 \f
14112
14113 /* Call FUNCTION on each of the breakpoints with numbers in the range
14114    defined by BP_NUM_RANGE (an inclusive range).  */
14115
14116 static void
14117 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14118                              gdb::function_view<void (breakpoint *)> function)
14119 {
14120   if (bp_num_range.first == 0)
14121     {
14122       warning (_("bad breakpoint number at or near '%d'"),
14123                bp_num_range.first);
14124     }
14125   else
14126     {
14127       struct breakpoint *b, *tmp;
14128
14129       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14130         {
14131           bool match = false;
14132
14133           ALL_BREAKPOINTS_SAFE (b, tmp)
14134             if (b->number == i)
14135               {
14136                 match = true;
14137                 function (b);
14138                 break;
14139               }
14140           if (!match)
14141             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14142         }
14143     }
14144 }
14145
14146 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14147    ARGS.  */
14148
14149 static void
14150 map_breakpoint_numbers (const char *args,
14151                         gdb::function_view<void (breakpoint *)> function)
14152 {
14153   if (args == NULL || *args == '\0')
14154     error_no_arg (_("one or more breakpoint numbers"));
14155
14156   number_or_range_parser parser (args);
14157
14158   while (!parser.finished ())
14159     {
14160       int num = parser.get_number ();
14161       map_breakpoint_number_range (std::make_pair (num, num), function);
14162     }
14163 }
14164
14165 /* Return the breakpoint location structure corresponding to the
14166    BP_NUM and LOC_NUM values.  */
14167
14168 static struct bp_location *
14169 find_location_by_number (int bp_num, int loc_num)
14170 {
14171   struct breakpoint *b;
14172
14173   ALL_BREAKPOINTS (b)
14174     if (b->number == bp_num)
14175       {
14176         break;
14177       }
14178
14179   if (!b || b->number != bp_num)
14180     error (_("Bad breakpoint number '%d'"), bp_num);
14181   
14182   if (loc_num == 0)
14183     error (_("Bad breakpoint location number '%d'"), loc_num);
14184
14185   int n = 0;
14186   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14187     if (++n == loc_num)
14188       return loc;
14189
14190   error (_("Bad breakpoint location number '%d'"), loc_num);
14191 }
14192
14193 /* Modes of operation for extract_bp_num.  */
14194 enum class extract_bp_kind
14195 {
14196   /* Extracting a breakpoint number.  */
14197   bp,
14198
14199   /* Extracting a location number.  */
14200   loc,
14201 };
14202
14203 /* Extract a breakpoint or location number (as determined by KIND)
14204    from the string starting at START.  TRAILER is a character which
14205    can be found after the number.  If you don't want a trailer, use
14206    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14207    string.  This always returns a positive integer.  */
14208
14209 static int
14210 extract_bp_num (extract_bp_kind kind, const char *start,
14211                 int trailer, const char **end_out = NULL)
14212 {
14213   const char *end = start;
14214   int num = get_number_trailer (&end, trailer);
14215   if (num < 0)
14216     error (kind == extract_bp_kind::bp
14217            ? _("Negative breakpoint number '%.*s'")
14218            : _("Negative breakpoint location number '%.*s'"),
14219            int (end - start), start);
14220   if (num == 0)
14221     error (kind == extract_bp_kind::bp
14222            ? _("Bad breakpoint number '%.*s'")
14223            : _("Bad breakpoint location number '%.*s'"),
14224            int (end - start), start);
14225
14226   if (end_out != NULL)
14227     *end_out = end;
14228   return num;
14229 }
14230
14231 /* Extract a breakpoint or location range (as determined by KIND) in
14232    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14233    representing the (inclusive) range.  The returned pair's elements
14234    are always positive integers.  */
14235
14236 static std::pair<int, int>
14237 extract_bp_or_bp_range (extract_bp_kind kind,
14238                         const std::string &arg,
14239                         std::string::size_type arg_offset)
14240 {
14241   std::pair<int, int> range;
14242   const char *bp_loc = &arg[arg_offset];
14243   std::string::size_type dash = arg.find ('-', arg_offset);
14244   if (dash != std::string::npos)
14245     {
14246       /* bp_loc is a range (x-z).  */
14247       if (arg.length () == dash + 1)
14248         error (kind == extract_bp_kind::bp
14249                ? _("Bad breakpoint number at or near: '%s'")
14250                : _("Bad breakpoint location number at or near: '%s'"),
14251                bp_loc);
14252
14253       const char *end;
14254       const char *start_first = bp_loc;
14255       const char *start_second = &arg[dash + 1];
14256       range.first = extract_bp_num (kind, start_first, '-');
14257       range.second = extract_bp_num (kind, start_second, '\0', &end);
14258
14259       if (range.first > range.second)
14260         error (kind == extract_bp_kind::bp
14261                ? _("Inverted breakpoint range at '%.*s'")
14262                : _("Inverted breakpoint location range at '%.*s'"),
14263                int (end - start_first), start_first);
14264     }
14265   else
14266     {
14267       /* bp_loc is a single value.  */
14268       range.first = extract_bp_num (kind, bp_loc, '\0');
14269       range.second = range.first;
14270     }
14271   return range;
14272 }
14273
14274 /* Extract the breakpoint/location range specified by ARG.  Returns
14275    the breakpoint range in BP_NUM_RANGE, and the location range in
14276    BP_LOC_RANGE.
14277
14278    ARG may be in any of the following forms:
14279
14280    x     where 'x' is a breakpoint number.
14281    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14282    x.y   where 'x' is a breakpoint number and 'y' a location number.
14283    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14284          location number range.
14285 */
14286
14287 static void
14288 extract_bp_number_and_location (const std::string &arg,
14289                                 std::pair<int, int> &bp_num_range,
14290                                 std::pair<int, int> &bp_loc_range)
14291 {
14292   std::string::size_type dot = arg.find ('.');
14293
14294   if (dot != std::string::npos)
14295     {
14296       /* Handle 'x.y' and 'x.y-z' cases.  */
14297
14298       if (arg.length () == dot + 1 || dot == 0)
14299         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14300
14301       bp_num_range.first
14302         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14303       bp_num_range.second = bp_num_range.first;
14304
14305       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14306                                              arg, dot + 1);
14307     }
14308   else
14309     {
14310       /* Handle x and x-y cases.  */
14311
14312       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14313       bp_loc_range.first = 0;
14314       bp_loc_range.second = 0;
14315     }
14316 }
14317
14318 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14319    specifies whether to enable or disable.  */
14320
14321 static void
14322 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14323 {
14324   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14325   if (loc != NULL)
14326     {
14327       if (loc->enabled != enable)
14328         {
14329           loc->enabled = enable;
14330           mark_breakpoint_location_modified (loc);
14331         }
14332       if (target_supports_enable_disable_tracepoint ()
14333           && current_trace_status ()->running && loc->owner
14334           && is_tracepoint (loc->owner))
14335         target_disable_tracepoint (loc);
14336     }
14337   update_global_location_list (UGLL_DONT_INSERT);
14338 }
14339
14340 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14341    number of the breakpoint, and BP_LOC_RANGE specifies the
14342    (inclusive) range of location numbers of that breakpoint to
14343    enable/disable.  ENABLE specifies whether to enable or disable the
14344    location.  */
14345
14346 static void
14347 enable_disable_breakpoint_location_range (int bp_num,
14348                                           std::pair<int, int> &bp_loc_range,
14349                                           bool enable)
14350 {
14351   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14352     enable_disable_bp_num_loc (bp_num, i, enable);
14353 }
14354
14355 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14356    If from_tty is nonzero, it prints a message to that effect,
14357    which ends with a period (no newline).  */
14358
14359 void
14360 disable_breakpoint (struct breakpoint *bpt)
14361 {
14362   /* Never disable a watchpoint scope breakpoint; we want to
14363      hit them when we leave scope so we can delete both the
14364      watchpoint and its scope breakpoint at that time.  */
14365   if (bpt->type == bp_watchpoint_scope)
14366     return;
14367
14368   bpt->enable_state = bp_disabled;
14369
14370   /* Mark breakpoint locations modified.  */
14371   mark_breakpoint_modified (bpt);
14372
14373   if (target_supports_enable_disable_tracepoint ()
14374       && current_trace_status ()->running && is_tracepoint (bpt))
14375     {
14376       struct bp_location *location;
14377      
14378       for (location = bpt->loc; location; location = location->next)
14379         target_disable_tracepoint (location);
14380     }
14381
14382   update_global_location_list (UGLL_DONT_INSERT);
14383
14384   observer_notify_breakpoint_modified (bpt);
14385 }
14386
14387 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14388    specified in ARGS.  ARGS may be in any of the formats handled by
14389    extract_bp_number_and_location.  ENABLE specifies whether to enable
14390    or disable the breakpoints/locations.  */
14391
14392 static void
14393 enable_disable_command (const char *args, int from_tty, bool enable)
14394 {
14395   if (args == 0)
14396     {
14397       struct breakpoint *bpt;
14398
14399       ALL_BREAKPOINTS (bpt)
14400         if (user_breakpoint_p (bpt))
14401           {
14402             if (enable)
14403               enable_breakpoint (bpt);
14404             else
14405               disable_breakpoint (bpt);
14406           }
14407     }
14408   else
14409     {
14410       std::string num = extract_arg (&args);
14411
14412       while (!num.empty ())
14413         {
14414           std::pair<int, int> bp_num_range, bp_loc_range;
14415
14416           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14417
14418           if (bp_loc_range.first == bp_loc_range.second
14419               && bp_loc_range.first == 0)
14420             {
14421               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14422               map_breakpoint_number_range (bp_num_range,
14423                                            enable
14424                                            ? enable_breakpoint
14425                                            : disable_breakpoint);
14426             }
14427           else
14428             {
14429               /* Handle breakpoint ids with formats 'x.y' or
14430                  'x.y-z'.  */
14431               enable_disable_breakpoint_location_range
14432                 (bp_num_range.first, bp_loc_range, enable);
14433             }
14434           num = extract_arg (&args);
14435         }
14436     }
14437 }
14438
14439 /* The disable command disables the specified breakpoints/locations
14440    (or all defined breakpoints) so they're no longer effective in
14441    stopping the inferior.  ARGS may be in any of the forms defined in
14442    extract_bp_number_and_location.  */
14443
14444 static void
14445 disable_command (const char *args, int from_tty)
14446 {
14447   enable_disable_command (args, from_tty, false);
14448 }
14449
14450 static void
14451 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14452                         int count)
14453 {
14454   int target_resources_ok;
14455
14456   if (bpt->type == bp_hardware_breakpoint)
14457     {
14458       int i;
14459       i = hw_breakpoint_used_count ();
14460       target_resources_ok = 
14461         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14462                                             i + 1, 0);
14463       if (target_resources_ok == 0)
14464         error (_("No hardware breakpoint support in the target."));
14465       else if (target_resources_ok < 0)
14466         error (_("Hardware breakpoints used exceeds limit."));
14467     }
14468
14469   if (is_watchpoint (bpt))
14470     {
14471       /* Initialize it just to avoid a GCC false warning.  */
14472       enum enable_state orig_enable_state = bp_disabled;
14473
14474       TRY
14475         {
14476           struct watchpoint *w = (struct watchpoint *) bpt;
14477
14478           orig_enable_state = bpt->enable_state;
14479           bpt->enable_state = bp_enabled;
14480           update_watchpoint (w, 1 /* reparse */);
14481         }
14482       CATCH (e, RETURN_MASK_ALL)
14483         {
14484           bpt->enable_state = orig_enable_state;
14485           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14486                              bpt->number);
14487           return;
14488         }
14489       END_CATCH
14490     }
14491
14492   bpt->enable_state = bp_enabled;
14493
14494   /* Mark breakpoint locations modified.  */
14495   mark_breakpoint_modified (bpt);
14496
14497   if (target_supports_enable_disable_tracepoint ()
14498       && current_trace_status ()->running && is_tracepoint (bpt))
14499     {
14500       struct bp_location *location;
14501
14502       for (location = bpt->loc; location; location = location->next)
14503         target_enable_tracepoint (location);
14504     }
14505
14506   bpt->disposition = disposition;
14507   bpt->enable_count = count;
14508   update_global_location_list (UGLL_MAY_INSERT);
14509
14510   observer_notify_breakpoint_modified (bpt);
14511 }
14512
14513
14514 void
14515 enable_breakpoint (struct breakpoint *bpt)
14516 {
14517   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14518 }
14519
14520 /* The enable command enables the specified breakpoints/locations (or
14521    all defined breakpoints) so they once again become (or continue to
14522    be) effective in stopping the inferior.  ARGS may be in any of the
14523    forms defined in extract_bp_number_and_location.  */
14524
14525 static void
14526 enable_command (const char *args, int from_tty)
14527 {
14528   enable_disable_command (args, from_tty, true);
14529 }
14530
14531 static void
14532 enable_once_command (const char *args, int from_tty)
14533 {
14534   map_breakpoint_numbers
14535     (args, [&] (breakpoint *b)
14536      {
14537        iterate_over_related_breakpoints
14538          (b, [&] (breakpoint *bpt)
14539           {
14540             enable_breakpoint_disp (bpt, disp_disable, 1);
14541           });
14542      });
14543 }
14544
14545 static void
14546 enable_count_command (const char *args, int from_tty)
14547 {
14548   int count;
14549
14550   if (args == NULL)
14551     error_no_arg (_("hit count"));
14552
14553   count = get_number (&args);
14554
14555   map_breakpoint_numbers
14556     (args, [&] (breakpoint *b)
14557      {
14558        iterate_over_related_breakpoints
14559          (b, [&] (breakpoint *bpt)
14560           {
14561             enable_breakpoint_disp (bpt, disp_disable, count);
14562           });
14563      });
14564 }
14565
14566 static void
14567 enable_delete_command (const char *args, int from_tty)
14568 {
14569   map_breakpoint_numbers
14570     (args, [&] (breakpoint *b)
14571      {
14572        iterate_over_related_breakpoints
14573          (b, [&] (breakpoint *bpt)
14574           {
14575             enable_breakpoint_disp (bpt, disp_del, 1);
14576           });
14577      });
14578 }
14579 \f
14580 static void
14581 set_breakpoint_cmd (const char *args, int from_tty)
14582 {
14583 }
14584
14585 static void
14586 show_breakpoint_cmd (const char *args, int from_tty)
14587 {
14588 }
14589
14590 /* Invalidate last known value of any hardware watchpoint if
14591    the memory which that value represents has been written to by
14592    GDB itself.  */
14593
14594 static void
14595 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14596                                       CORE_ADDR addr, ssize_t len,
14597                                       const bfd_byte *data)
14598 {
14599   struct breakpoint *bp;
14600
14601   ALL_BREAKPOINTS (bp)
14602     if (bp->enable_state == bp_enabled
14603         && bp->type == bp_hardware_watchpoint)
14604       {
14605         struct watchpoint *wp = (struct watchpoint *) bp;
14606
14607         if (wp->val_valid && wp->val)
14608           {
14609             struct bp_location *loc;
14610
14611             for (loc = bp->loc; loc != NULL; loc = loc->next)
14612               if (loc->loc_type == bp_loc_hardware_watchpoint
14613                   && loc->address + loc->length > addr
14614                   && addr + len > loc->address)
14615                 {
14616                   value_free (wp->val);
14617                   wp->val = NULL;
14618                   wp->val_valid = 0;
14619                 }
14620           }
14621       }
14622 }
14623
14624 /* Create and insert a breakpoint for software single step.  */
14625
14626 void
14627 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14628                                const address_space *aspace,
14629                                CORE_ADDR next_pc)
14630 {
14631   struct thread_info *tp = inferior_thread ();
14632   struct symtab_and_line sal;
14633   CORE_ADDR pc = next_pc;
14634
14635   if (tp->control.single_step_breakpoints == NULL)
14636     {
14637       tp->control.single_step_breakpoints
14638         = new_single_step_breakpoint (tp->global_num, gdbarch);
14639     }
14640
14641   sal = find_pc_line (pc, 0);
14642   sal.pc = pc;
14643   sal.section = find_pc_overlay (pc);
14644   sal.explicit_pc = 1;
14645   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14646
14647   update_global_location_list (UGLL_INSERT);
14648 }
14649
14650 /* Insert single step breakpoints according to the current state.  */
14651
14652 int
14653 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14654 {
14655   struct regcache *regcache = get_current_regcache ();
14656   std::vector<CORE_ADDR> next_pcs;
14657
14658   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14659
14660   if (!next_pcs.empty ())
14661     {
14662       struct frame_info *frame = get_current_frame ();
14663       const address_space *aspace = get_frame_address_space (frame);
14664
14665       for (CORE_ADDR pc : next_pcs)
14666         insert_single_step_breakpoint (gdbarch, aspace, pc);
14667
14668       return 1;
14669     }
14670   else
14671     return 0;
14672 }
14673
14674 /* See breakpoint.h.  */
14675
14676 int
14677 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14678                                        const address_space *aspace,
14679                                        CORE_ADDR pc)
14680 {
14681   struct bp_location *loc;
14682
14683   for (loc = bp->loc; loc != NULL; loc = loc->next)
14684     if (loc->inserted
14685         && breakpoint_location_address_match (loc, aspace, pc))
14686       return 1;
14687
14688   return 0;
14689 }
14690
14691 /* Check whether a software single-step breakpoint is inserted at
14692    PC.  */
14693
14694 int
14695 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14696                                         CORE_ADDR pc)
14697 {
14698   struct breakpoint *bpt;
14699
14700   ALL_BREAKPOINTS (bpt)
14701     {
14702       if (bpt->type == bp_single_step
14703           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14704         return 1;
14705     }
14706   return 0;
14707 }
14708
14709 /* Tracepoint-specific operations.  */
14710
14711 /* Set tracepoint count to NUM.  */
14712 static void
14713 set_tracepoint_count (int num)
14714 {
14715   tracepoint_count = num;
14716   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14717 }
14718
14719 static void
14720 trace_command (const char *arg, int from_tty)
14721 {
14722   struct breakpoint_ops *ops;
14723
14724   event_location_up location = string_to_event_location (&arg,
14725                                                          current_language);
14726   if (location != NULL
14727       && event_location_type (location.get ()) == PROBE_LOCATION)
14728     ops = &tracepoint_probe_breakpoint_ops;
14729   else
14730     ops = &tracepoint_breakpoint_ops;
14731
14732   create_breakpoint (get_current_arch (),
14733                      location.get (),
14734                      NULL, 0, arg, 1 /* parse arg */,
14735                      0 /* tempflag */,
14736                      bp_tracepoint /* type_wanted */,
14737                      0 /* Ignore count */,
14738                      pending_break_support,
14739                      ops,
14740                      from_tty,
14741                      1 /* enabled */,
14742                      0 /* internal */, 0);
14743 }
14744
14745 static void
14746 ftrace_command (const char *arg, int from_tty)
14747 {
14748   event_location_up location = string_to_event_location (&arg,
14749                                                          current_language);
14750   create_breakpoint (get_current_arch (),
14751                      location.get (),
14752                      NULL, 0, arg, 1 /* parse arg */,
14753                      0 /* tempflag */,
14754                      bp_fast_tracepoint /* type_wanted */,
14755                      0 /* Ignore count */,
14756                      pending_break_support,
14757                      &tracepoint_breakpoint_ops,
14758                      from_tty,
14759                      1 /* enabled */,
14760                      0 /* internal */, 0);
14761 }
14762
14763 /* strace command implementation.  Creates a static tracepoint.  */
14764
14765 static void
14766 strace_command (const char *arg, int from_tty)
14767 {
14768   struct breakpoint_ops *ops;
14769   event_location_up location;
14770
14771   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14772      or with a normal static tracepoint.  */
14773   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14774     {
14775       ops = &strace_marker_breakpoint_ops;
14776       location = new_linespec_location (&arg);
14777     }
14778   else
14779     {
14780       ops = &tracepoint_breakpoint_ops;
14781       location = string_to_event_location (&arg, current_language);
14782     }
14783
14784   create_breakpoint (get_current_arch (),
14785                      location.get (),
14786                      NULL, 0, arg, 1 /* parse arg */,
14787                      0 /* tempflag */,
14788                      bp_static_tracepoint /* type_wanted */,
14789                      0 /* Ignore count */,
14790                      pending_break_support,
14791                      ops,
14792                      from_tty,
14793                      1 /* enabled */,
14794                      0 /* internal */, 0);
14795 }
14796
14797 /* Set up a fake reader function that gets command lines from a linked
14798    list that was acquired during tracepoint uploading.  */
14799
14800 static struct uploaded_tp *this_utp;
14801 static int next_cmd;
14802
14803 static char *
14804 read_uploaded_action (void)
14805 {
14806   char *rslt;
14807
14808   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14809
14810   next_cmd++;
14811
14812   return rslt;
14813 }
14814
14815 /* Given information about a tracepoint as recorded on a target (which
14816    can be either a live system or a trace file), attempt to create an
14817    equivalent GDB tracepoint.  This is not a reliable process, since
14818    the target does not necessarily have all the information used when
14819    the tracepoint was originally defined.  */
14820   
14821 struct tracepoint *
14822 create_tracepoint_from_upload (struct uploaded_tp *utp)
14823 {
14824   const char *addr_str;
14825   char small_buf[100];
14826   struct tracepoint *tp;
14827
14828   if (utp->at_string)
14829     addr_str = utp->at_string;
14830   else
14831     {
14832       /* In the absence of a source location, fall back to raw
14833          address.  Since there is no way to confirm that the address
14834          means the same thing as when the trace was started, warn the
14835          user.  */
14836       warning (_("Uploaded tracepoint %d has no "
14837                  "source location, using raw address"),
14838                utp->number);
14839       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14840       addr_str = small_buf;
14841     }
14842
14843   /* There's not much we can do with a sequence of bytecodes.  */
14844   if (utp->cond && !utp->cond_string)
14845     warning (_("Uploaded tracepoint %d condition "
14846                "has no source form, ignoring it"),
14847              utp->number);
14848
14849   event_location_up location = string_to_event_location (&addr_str,
14850                                                          current_language);
14851   if (!create_breakpoint (get_current_arch (),
14852                           location.get (),
14853                           utp->cond_string, -1, addr_str,
14854                           0 /* parse cond/thread */,
14855                           0 /* tempflag */,
14856                           utp->type /* type_wanted */,
14857                           0 /* Ignore count */,
14858                           pending_break_support,
14859                           &tracepoint_breakpoint_ops,
14860                           0 /* from_tty */,
14861                           utp->enabled /* enabled */,
14862                           0 /* internal */,
14863                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14864     return NULL;
14865
14866   /* Get the tracepoint we just created.  */
14867   tp = get_tracepoint (tracepoint_count);
14868   gdb_assert (tp != NULL);
14869
14870   if (utp->pass > 0)
14871     {
14872       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14873                  tp->number);
14874
14875       trace_pass_command (small_buf, 0);
14876     }
14877
14878   /* If we have uploaded versions of the original commands, set up a
14879      special-purpose "reader" function and call the usual command line
14880      reader, then pass the result to the breakpoint command-setting
14881      function.  */
14882   if (!VEC_empty (char_ptr, utp->cmd_strings))
14883     {
14884       command_line_up cmd_list;
14885
14886       this_utp = utp;
14887       next_cmd = 0;
14888
14889       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14890
14891       breakpoint_set_commands (tp, std::move (cmd_list));
14892     }
14893   else if (!VEC_empty (char_ptr, utp->actions)
14894            || !VEC_empty (char_ptr, utp->step_actions))
14895     warning (_("Uploaded tracepoint %d actions "
14896                "have no source form, ignoring them"),
14897              utp->number);
14898
14899   /* Copy any status information that might be available.  */
14900   tp->hit_count = utp->hit_count;
14901   tp->traceframe_usage = utp->traceframe_usage;
14902
14903   return tp;
14904 }
14905   
14906 /* Print information on tracepoint number TPNUM_EXP, or all if
14907    omitted.  */
14908
14909 static void
14910 info_tracepoints_command (const char *args, int from_tty)
14911 {
14912   struct ui_out *uiout = current_uiout;
14913   int num_printed;
14914
14915   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14916
14917   if (num_printed == 0)
14918     {
14919       if (args == NULL || *args == '\0')
14920         uiout->message ("No tracepoints.\n");
14921       else
14922         uiout->message ("No tracepoint matching '%s'.\n", args);
14923     }
14924
14925   default_collect_info ();
14926 }
14927
14928 /* The 'enable trace' command enables tracepoints.
14929    Not supported by all targets.  */
14930 static void
14931 enable_trace_command (char *args, int from_tty)
14932 {
14933   enable_command (args, from_tty);
14934 }
14935
14936 /* The 'disable trace' command disables tracepoints.
14937    Not supported by all targets.  */
14938 static void
14939 disable_trace_command (char *args, int from_tty)
14940 {
14941   disable_command (args, from_tty);
14942 }
14943
14944 /* Remove a tracepoint (or all if no argument).  */
14945 static void
14946 delete_trace_command (const char *arg, int from_tty)
14947 {
14948   struct breakpoint *b, *b_tmp;
14949
14950   dont_repeat ();
14951
14952   if (arg == 0)
14953     {
14954       int breaks_to_delete = 0;
14955
14956       /* Delete all breakpoints if no argument.
14957          Do not delete internal or call-dummy breakpoints, these
14958          have to be deleted with an explicit breakpoint number 
14959          argument.  */
14960       ALL_TRACEPOINTS (b)
14961         if (is_tracepoint (b) && user_breakpoint_p (b))
14962           {
14963             breaks_to_delete = 1;
14964             break;
14965           }
14966
14967       /* Ask user only if there are some breakpoints to delete.  */
14968       if (!from_tty
14969           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14970         {
14971           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14972             if (is_tracepoint (b) && user_breakpoint_p (b))
14973               delete_breakpoint (b);
14974         }
14975     }
14976   else
14977     map_breakpoint_numbers
14978       (arg, [&] (breakpoint *b)
14979        {
14980          iterate_over_related_breakpoints (b, delete_breakpoint);
14981        });
14982 }
14983
14984 /* Helper function for trace_pass_command.  */
14985
14986 static void
14987 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14988 {
14989   tp->pass_count = count;
14990   observer_notify_breakpoint_modified (tp);
14991   if (from_tty)
14992     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14993                      tp->number, count);
14994 }
14995
14996 /* Set passcount for tracepoint.
14997
14998    First command argument is passcount, second is tracepoint number.
14999    If tracepoint number omitted, apply to most recently defined.
15000    Also accepts special argument "all".  */
15001
15002 static void
15003 trace_pass_command (const char *args, int from_tty)
15004 {
15005   struct tracepoint *t1;
15006   ULONGEST count;
15007
15008   if (args == 0 || *args == 0)
15009     error (_("passcount command requires an "
15010              "argument (count + optional TP num)"));
15011
15012   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
15013
15014   args = skip_spaces (args);
15015   if (*args && strncasecmp (args, "all", 3) == 0)
15016     {
15017       struct breakpoint *b;
15018
15019       args += 3;                        /* Skip special argument "all".  */
15020       if (*args)
15021         error (_("Junk at end of arguments."));
15022
15023       ALL_TRACEPOINTS (b)
15024       {
15025         t1 = (struct tracepoint *) b;
15026         trace_pass_set_count (t1, count, from_tty);
15027       }
15028     }
15029   else if (*args == '\0')
15030     {
15031       t1 = get_tracepoint_by_number (&args, NULL);
15032       if (t1)
15033         trace_pass_set_count (t1, count, from_tty);
15034     }
15035   else
15036     {
15037       number_or_range_parser parser (args);
15038       while (!parser.finished ())
15039         {
15040           t1 = get_tracepoint_by_number (&args, &parser);
15041           if (t1)
15042             trace_pass_set_count (t1, count, from_tty);
15043         }
15044     }
15045 }
15046
15047 struct tracepoint *
15048 get_tracepoint (int num)
15049 {
15050   struct breakpoint *t;
15051
15052   ALL_TRACEPOINTS (t)
15053     if (t->number == num)
15054       return (struct tracepoint *) t;
15055
15056   return NULL;
15057 }
15058
15059 /* Find the tracepoint with the given target-side number (which may be
15060    different from the tracepoint number after disconnecting and
15061    reconnecting).  */
15062
15063 struct tracepoint *
15064 get_tracepoint_by_number_on_target (int num)
15065 {
15066   struct breakpoint *b;
15067
15068   ALL_TRACEPOINTS (b)
15069     {
15070       struct tracepoint *t = (struct tracepoint *) b;
15071
15072       if (t->number_on_target == num)
15073         return t;
15074     }
15075
15076   return NULL;
15077 }
15078
15079 /* Utility: parse a tracepoint number and look it up in the list.
15080    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15081    If the argument is missing, the most recent tracepoint
15082    (tracepoint_count) is returned.  */
15083
15084 struct tracepoint *
15085 get_tracepoint_by_number (const char **arg,
15086                           number_or_range_parser *parser)
15087 {
15088   struct breakpoint *t;
15089   int tpnum;
15090   const char *instring = arg == NULL ? NULL : *arg;
15091
15092   if (parser != NULL)
15093     {
15094       gdb_assert (!parser->finished ());
15095       tpnum = parser->get_number ();
15096     }
15097   else if (arg == NULL || *arg == NULL || ! **arg)
15098     tpnum = tracepoint_count;
15099   else
15100     tpnum = get_number (arg);
15101
15102   if (tpnum <= 0)
15103     {
15104       if (instring && *instring)
15105         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15106                          instring);
15107       else
15108         printf_filtered (_("No previous tracepoint\n"));
15109       return NULL;
15110     }
15111
15112   ALL_TRACEPOINTS (t)
15113     if (t->number == tpnum)
15114     {
15115       return (struct tracepoint *) t;
15116     }
15117
15118   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15119   return NULL;
15120 }
15121
15122 void
15123 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15124 {
15125   if (b->thread != -1)
15126     fprintf_unfiltered (fp, " thread %d", b->thread);
15127
15128   if (b->task != 0)
15129     fprintf_unfiltered (fp, " task %d", b->task);
15130
15131   fprintf_unfiltered (fp, "\n");
15132 }
15133
15134 /* Save information on user settable breakpoints (watchpoints, etc) to
15135    a new script file named FILENAME.  If FILTER is non-NULL, call it
15136    on each breakpoint and only include the ones for which it returns
15137    non-zero.  */
15138
15139 static void
15140 save_breakpoints (const char *filename, int from_tty,
15141                   int (*filter) (const struct breakpoint *))
15142 {
15143   struct breakpoint *tp;
15144   int any = 0;
15145   int extra_trace_bits = 0;
15146
15147   if (filename == 0 || *filename == 0)
15148     error (_("Argument required (file name in which to save)"));
15149
15150   /* See if we have anything to save.  */
15151   ALL_BREAKPOINTS (tp)
15152   {
15153     /* Skip internal and momentary breakpoints.  */
15154     if (!user_breakpoint_p (tp))
15155       continue;
15156
15157     /* If we have a filter, only save the breakpoints it accepts.  */
15158     if (filter && !filter (tp))
15159       continue;
15160
15161     any = 1;
15162
15163     if (is_tracepoint (tp))
15164       {
15165         extra_trace_bits = 1;
15166
15167         /* We can stop searching.  */
15168         break;
15169       }
15170   }
15171
15172   if (!any)
15173     {
15174       warning (_("Nothing to save."));
15175       return;
15176     }
15177
15178   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15179
15180   stdio_file fp;
15181
15182   if (!fp.open (expanded_filename.get (), "w"))
15183     error (_("Unable to open file '%s' for saving (%s)"),
15184            expanded_filename.get (), safe_strerror (errno));
15185
15186   if (extra_trace_bits)
15187     save_trace_state_variables (&fp);
15188
15189   ALL_BREAKPOINTS (tp)
15190   {
15191     /* Skip internal and momentary breakpoints.  */
15192     if (!user_breakpoint_p (tp))
15193       continue;
15194
15195     /* If we have a filter, only save the breakpoints it accepts.  */
15196     if (filter && !filter (tp))
15197       continue;
15198
15199     tp->ops->print_recreate (tp, &fp);
15200
15201     /* Note, we can't rely on tp->number for anything, as we can't
15202        assume the recreated breakpoint numbers will match.  Use $bpnum
15203        instead.  */
15204
15205     if (tp->cond_string)
15206       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15207
15208     if (tp->ignore_count)
15209       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15210
15211     if (tp->type != bp_dprintf && tp->commands)
15212       {
15213         fp.puts ("  commands\n");
15214         
15215         current_uiout->redirect (&fp);
15216         TRY
15217           {
15218             print_command_lines (current_uiout, tp->commands.get (), 2);
15219           }
15220         CATCH (ex, RETURN_MASK_ALL)
15221           {
15222           current_uiout->redirect (NULL);
15223             throw_exception (ex);
15224           }
15225         END_CATCH
15226
15227         current_uiout->redirect (NULL);
15228         fp.puts ("  end\n");
15229       }
15230
15231     if (tp->enable_state == bp_disabled)
15232       fp.puts ("disable $bpnum\n");
15233
15234     /* If this is a multi-location breakpoint, check if the locations
15235        should be individually disabled.  Watchpoint locations are
15236        special, and not user visible.  */
15237     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15238       {
15239         struct bp_location *loc;
15240         int n = 1;
15241
15242         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15243           if (!loc->enabled)
15244             fp.printf ("disable $bpnum.%d\n", n);
15245       }
15246   }
15247
15248   if (extra_trace_bits && *default_collect)
15249     fp.printf ("set default-collect %s\n", default_collect);
15250
15251   if (from_tty)
15252     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15253 }
15254
15255 /* The `save breakpoints' command.  */
15256
15257 static void
15258 save_breakpoints_command (const char *args, int from_tty)
15259 {
15260   save_breakpoints (args, from_tty, NULL);
15261 }
15262
15263 /* The `save tracepoints' command.  */
15264
15265 static void
15266 save_tracepoints_command (const char *args, int from_tty)
15267 {
15268   save_breakpoints (args, from_tty, is_tracepoint);
15269 }
15270
15271 /* Create a vector of all tracepoints.  */
15272
15273 VEC(breakpoint_p) *
15274 all_tracepoints (void)
15275 {
15276   VEC(breakpoint_p) *tp_vec = 0;
15277   struct breakpoint *tp;
15278
15279   ALL_TRACEPOINTS (tp)
15280   {
15281     VEC_safe_push (breakpoint_p, tp_vec, tp);
15282   }
15283
15284   return tp_vec;
15285 }
15286
15287 \f
15288 /* This help string is used to consolidate all the help string for specifying
15289    locations used by several commands.  */
15290
15291 #define LOCATION_HELP_STRING \
15292 "Linespecs are colon-separated lists of location parameters, such as\n\
15293 source filename, function name, label name, and line number.\n\
15294 Example: To specify the start of a label named \"the_top\" in the\n\
15295 function \"fact\" in the file \"factorial.c\", use\n\
15296 \"factorial.c:fact:the_top\".\n\
15297 \n\
15298 Address locations begin with \"*\" and specify an exact address in the\n\
15299 program.  Example: To specify the fourth byte past the start function\n\
15300 \"main\", use \"*main + 4\".\n\
15301 \n\
15302 Explicit locations are similar to linespecs but use an option/argument\n\
15303 syntax to specify location parameters.\n\
15304 Example: To specify the start of the label named \"the_top\" in the\n\
15305 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15306 -function fact -label the_top\".\n"
15307
15308 /* This help string is used for the break, hbreak, tbreak and thbreak
15309    commands.  It is defined as a macro to prevent duplication.
15310    COMMAND should be a string constant containing the name of the
15311    command.  */
15312
15313 #define BREAK_ARGS_HELP(command) \
15314 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15315 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15316 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15317 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15318 `-probe-dtrace' (for a DTrace probe).\n\
15319 LOCATION may be a linespec, address, or explicit location as described\n\
15320 below.\n\
15321 \n\
15322 With no LOCATION, uses current execution address of the selected\n\
15323 stack frame.  This is useful for breaking on return to a stack frame.\n\
15324 \n\
15325 THREADNUM is the number from \"info threads\".\n\
15326 CONDITION is a boolean expression.\n\
15327 \n" LOCATION_HELP_STRING "\n\
15328 Multiple breakpoints at one place are permitted, and useful if their\n\
15329 conditions are different.\n\
15330 \n\
15331 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15332
15333 /* List of subcommands for "catch".  */
15334 static struct cmd_list_element *catch_cmdlist;
15335
15336 /* List of subcommands for "tcatch".  */
15337 static struct cmd_list_element *tcatch_cmdlist;
15338
15339 void
15340 add_catch_command (const char *name, const char *docstring,
15341                    cmd_sfunc_ftype *sfunc,
15342                    completer_ftype *completer,
15343                    void *user_data_catch,
15344                    void *user_data_tcatch)
15345 {
15346   struct cmd_list_element *command;
15347
15348   command = add_cmd (name, class_breakpoint, docstring,
15349                      &catch_cmdlist);
15350   set_cmd_sfunc (command, sfunc);
15351   set_cmd_context (command, user_data_catch);
15352   set_cmd_completer (command, completer);
15353
15354   command = add_cmd (name, class_breakpoint, docstring,
15355                      &tcatch_cmdlist);
15356   set_cmd_sfunc (command, sfunc);
15357   set_cmd_context (command, user_data_tcatch);
15358   set_cmd_completer (command, completer);
15359 }
15360
15361 static void
15362 save_command (const char *arg, int from_tty)
15363 {
15364   printf_unfiltered (_("\"save\" must be followed by "
15365                        "the name of a save subcommand.\n"));
15366   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
15367 }
15368
15369 struct breakpoint *
15370 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15371                           void *data)
15372 {
15373   struct breakpoint *b, *b_tmp;
15374
15375   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15376     {
15377       if ((*callback) (b, data))
15378         return b;
15379     }
15380
15381   return NULL;
15382 }
15383
15384 /* Zero if any of the breakpoint's locations could be a location where
15385    functions have been inlined, nonzero otherwise.  */
15386
15387 static int
15388 is_non_inline_function (struct breakpoint *b)
15389 {
15390   /* The shared library event breakpoint is set on the address of a
15391      non-inline function.  */
15392   if (b->type == bp_shlib_event)
15393     return 1;
15394
15395   return 0;
15396 }
15397
15398 /* Nonzero if the specified PC cannot be a location where functions
15399    have been inlined.  */
15400
15401 int
15402 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15403                            const struct target_waitstatus *ws)
15404 {
15405   struct breakpoint *b;
15406   struct bp_location *bl;
15407
15408   ALL_BREAKPOINTS (b)
15409     {
15410       if (!is_non_inline_function (b))
15411         continue;
15412
15413       for (bl = b->loc; bl != NULL; bl = bl->next)
15414         {
15415           if (!bl->shlib_disabled
15416               && bpstat_check_location (bl, aspace, pc, ws))
15417             return 1;
15418         }
15419     }
15420
15421   return 0;
15422 }
15423
15424 /* Remove any references to OBJFILE which is going to be freed.  */
15425
15426 void
15427 breakpoint_free_objfile (struct objfile *objfile)
15428 {
15429   struct bp_location **locp, *loc;
15430
15431   ALL_BP_LOCATIONS (loc, locp)
15432     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15433       loc->symtab = NULL;
15434 }
15435
15436 void
15437 initialize_breakpoint_ops (void)
15438 {
15439   static int initialized = 0;
15440
15441   struct breakpoint_ops *ops;
15442
15443   if (initialized)
15444     return;
15445   initialized = 1;
15446
15447   /* The breakpoint_ops structure to be inherit by all kinds of
15448      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15449      internal and momentary breakpoints, etc.).  */
15450   ops = &bkpt_base_breakpoint_ops;
15451   *ops = base_breakpoint_ops;
15452   ops->re_set = bkpt_re_set;
15453   ops->insert_location = bkpt_insert_location;
15454   ops->remove_location = bkpt_remove_location;
15455   ops->breakpoint_hit = bkpt_breakpoint_hit;
15456   ops->create_sals_from_location = bkpt_create_sals_from_location;
15457   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15458   ops->decode_location = bkpt_decode_location;
15459
15460   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15461   ops = &bkpt_breakpoint_ops;
15462   *ops = bkpt_base_breakpoint_ops;
15463   ops->re_set = bkpt_re_set;
15464   ops->resources_needed = bkpt_resources_needed;
15465   ops->print_it = bkpt_print_it;
15466   ops->print_mention = bkpt_print_mention;
15467   ops->print_recreate = bkpt_print_recreate;
15468
15469   /* Ranged breakpoints.  */
15470   ops = &ranged_breakpoint_ops;
15471   *ops = bkpt_breakpoint_ops;
15472   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15473   ops->resources_needed = resources_needed_ranged_breakpoint;
15474   ops->print_it = print_it_ranged_breakpoint;
15475   ops->print_one = print_one_ranged_breakpoint;
15476   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15477   ops->print_mention = print_mention_ranged_breakpoint;
15478   ops->print_recreate = print_recreate_ranged_breakpoint;
15479
15480   /* Internal breakpoints.  */
15481   ops = &internal_breakpoint_ops;
15482   *ops = bkpt_base_breakpoint_ops;
15483   ops->re_set = internal_bkpt_re_set;
15484   ops->check_status = internal_bkpt_check_status;
15485   ops->print_it = internal_bkpt_print_it;
15486   ops->print_mention = internal_bkpt_print_mention;
15487
15488   /* Momentary breakpoints.  */
15489   ops = &momentary_breakpoint_ops;
15490   *ops = bkpt_base_breakpoint_ops;
15491   ops->re_set = momentary_bkpt_re_set;
15492   ops->check_status = momentary_bkpt_check_status;
15493   ops->print_it = momentary_bkpt_print_it;
15494   ops->print_mention = momentary_bkpt_print_mention;
15495
15496   /* Probe breakpoints.  */
15497   ops = &bkpt_probe_breakpoint_ops;
15498   *ops = bkpt_breakpoint_ops;
15499   ops->insert_location = bkpt_probe_insert_location;
15500   ops->remove_location = bkpt_probe_remove_location;
15501   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15502   ops->decode_location = bkpt_probe_decode_location;
15503
15504   /* Watchpoints.  */
15505   ops = &watchpoint_breakpoint_ops;
15506   *ops = base_breakpoint_ops;
15507   ops->re_set = re_set_watchpoint;
15508   ops->insert_location = insert_watchpoint;
15509   ops->remove_location = remove_watchpoint;
15510   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15511   ops->check_status = check_status_watchpoint;
15512   ops->resources_needed = resources_needed_watchpoint;
15513   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15514   ops->print_it = print_it_watchpoint;
15515   ops->print_mention = print_mention_watchpoint;
15516   ops->print_recreate = print_recreate_watchpoint;
15517   ops->explains_signal = explains_signal_watchpoint;
15518
15519   /* Masked watchpoints.  */
15520   ops = &masked_watchpoint_breakpoint_ops;
15521   *ops = watchpoint_breakpoint_ops;
15522   ops->insert_location = insert_masked_watchpoint;
15523   ops->remove_location = remove_masked_watchpoint;
15524   ops->resources_needed = resources_needed_masked_watchpoint;
15525   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15526   ops->print_it = print_it_masked_watchpoint;
15527   ops->print_one_detail = print_one_detail_masked_watchpoint;
15528   ops->print_mention = print_mention_masked_watchpoint;
15529   ops->print_recreate = print_recreate_masked_watchpoint;
15530
15531   /* Tracepoints.  */
15532   ops = &tracepoint_breakpoint_ops;
15533   *ops = base_breakpoint_ops;
15534   ops->re_set = tracepoint_re_set;
15535   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15536   ops->print_one_detail = tracepoint_print_one_detail;
15537   ops->print_mention = tracepoint_print_mention;
15538   ops->print_recreate = tracepoint_print_recreate;
15539   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15540   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15541   ops->decode_location = tracepoint_decode_location;
15542
15543   /* Probe tracepoints.  */
15544   ops = &tracepoint_probe_breakpoint_ops;
15545   *ops = tracepoint_breakpoint_ops;
15546   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15547   ops->decode_location = tracepoint_probe_decode_location;
15548
15549   /* Static tracepoints with marker (`-m').  */
15550   ops = &strace_marker_breakpoint_ops;
15551   *ops = tracepoint_breakpoint_ops;
15552   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15553   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15554   ops->decode_location = strace_marker_decode_location;
15555
15556   /* Fork catchpoints.  */
15557   ops = &catch_fork_breakpoint_ops;
15558   *ops = base_breakpoint_ops;
15559   ops->insert_location = insert_catch_fork;
15560   ops->remove_location = remove_catch_fork;
15561   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15562   ops->print_it = print_it_catch_fork;
15563   ops->print_one = print_one_catch_fork;
15564   ops->print_mention = print_mention_catch_fork;
15565   ops->print_recreate = print_recreate_catch_fork;
15566
15567   /* Vfork catchpoints.  */
15568   ops = &catch_vfork_breakpoint_ops;
15569   *ops = base_breakpoint_ops;
15570   ops->insert_location = insert_catch_vfork;
15571   ops->remove_location = remove_catch_vfork;
15572   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15573   ops->print_it = print_it_catch_vfork;
15574   ops->print_one = print_one_catch_vfork;
15575   ops->print_mention = print_mention_catch_vfork;
15576   ops->print_recreate = print_recreate_catch_vfork;
15577
15578   /* Exec catchpoints.  */
15579   ops = &catch_exec_breakpoint_ops;
15580   *ops = base_breakpoint_ops;
15581   ops->insert_location = insert_catch_exec;
15582   ops->remove_location = remove_catch_exec;
15583   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15584   ops->print_it = print_it_catch_exec;
15585   ops->print_one = print_one_catch_exec;
15586   ops->print_mention = print_mention_catch_exec;
15587   ops->print_recreate = print_recreate_catch_exec;
15588
15589   /* Solib-related catchpoints.  */
15590   ops = &catch_solib_breakpoint_ops;
15591   *ops = base_breakpoint_ops;
15592   ops->insert_location = insert_catch_solib;
15593   ops->remove_location = remove_catch_solib;
15594   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15595   ops->check_status = check_status_catch_solib;
15596   ops->print_it = print_it_catch_solib;
15597   ops->print_one = print_one_catch_solib;
15598   ops->print_mention = print_mention_catch_solib;
15599   ops->print_recreate = print_recreate_catch_solib;
15600
15601   ops = &dprintf_breakpoint_ops;
15602   *ops = bkpt_base_breakpoint_ops;
15603   ops->re_set = dprintf_re_set;
15604   ops->resources_needed = bkpt_resources_needed;
15605   ops->print_it = bkpt_print_it;
15606   ops->print_mention = bkpt_print_mention;
15607   ops->print_recreate = dprintf_print_recreate;
15608   ops->after_condition_true = dprintf_after_condition_true;
15609   ops->breakpoint_hit = dprintf_breakpoint_hit;
15610 }
15611
15612 /* Chain containing all defined "enable breakpoint" subcommands.  */
15613
15614 static struct cmd_list_element *enablebreaklist = NULL;
15615
15616 void
15617 _initialize_breakpoint (void)
15618 {
15619   struct cmd_list_element *c;
15620
15621   initialize_breakpoint_ops ();
15622
15623   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15624   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
15625   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15626
15627   breakpoint_objfile_key
15628     = register_objfile_data_with_cleanup (NULL, free_breakpoint_objfile_data);
15629
15630   breakpoint_chain = 0;
15631   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15632      before a breakpoint is set.  */
15633   breakpoint_count = 0;
15634
15635   tracepoint_count = 0;
15636
15637   add_com ("ignore", class_breakpoint, ignore_command, _("\
15638 Set ignore-count of breakpoint number N to COUNT.\n\
15639 Usage is `ignore N COUNT'."));
15640
15641   add_com ("commands", class_breakpoint, commands_command, _("\
15642 Set commands to be executed when the given breakpoints are hit.\n\
15643 Give a space-separated breakpoint list as argument after \"commands\".\n\
15644 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15645 (e.g. `5-7').\n\
15646 With no argument, the targeted breakpoint is the last one set.\n\
15647 The commands themselves follow starting on the next line.\n\
15648 Type a line containing \"end\" to indicate the end of them.\n\
15649 Give \"silent\" as the first line to make the breakpoint silent;\n\
15650 then no output is printed when it is hit, except what the commands print."));
15651
15652   c = add_com ("condition", class_breakpoint, condition_command, _("\
15653 Specify breakpoint number N to break only if COND is true.\n\
15654 Usage is `condition N COND', where N is an integer and COND is an\n\
15655 expression to be evaluated whenever breakpoint N is reached."));
15656   set_cmd_completer (c, condition_completer);
15657
15658   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15659 Set a temporary breakpoint.\n\
15660 Like \"break\" except the breakpoint is only temporary,\n\
15661 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15662 by using \"enable delete\" on the breakpoint number.\n\
15663 \n"
15664 BREAK_ARGS_HELP ("tbreak")));
15665   set_cmd_completer (c, location_completer);
15666
15667   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15668 Set a hardware assisted breakpoint.\n\
15669 Like \"break\" except the breakpoint requires hardware support,\n\
15670 some target hardware may not have this support.\n\
15671 \n"
15672 BREAK_ARGS_HELP ("hbreak")));
15673   set_cmd_completer (c, location_completer);
15674
15675   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15676 Set a temporary hardware assisted breakpoint.\n\
15677 Like \"hbreak\" except the breakpoint is only temporary,\n\
15678 so it will be deleted when hit.\n\
15679 \n"
15680 BREAK_ARGS_HELP ("thbreak")));
15681   set_cmd_completer (c, location_completer);
15682
15683   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15684 Enable some breakpoints.\n\
15685 Give breakpoint numbers (separated by spaces) as arguments.\n\
15686 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15687 This is used to cancel the effect of the \"disable\" command.\n\
15688 With a subcommand you can enable temporarily."),
15689                   &enablelist, "enable ", 1, &cmdlist);
15690
15691   add_com_alias ("en", "enable", class_breakpoint, 1);
15692
15693   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15694 Enable some breakpoints.\n\
15695 Give breakpoint numbers (separated by spaces) as arguments.\n\
15696 This is used to cancel the effect of the \"disable\" command.\n\
15697 May be abbreviated to simply \"enable\".\n"),
15698                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15699
15700   add_cmd ("once", no_class, enable_once_command, _("\
15701 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15702 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15703            &enablebreaklist);
15704
15705   add_cmd ("delete", no_class, enable_delete_command, _("\
15706 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15707 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15708            &enablebreaklist);
15709
15710   add_cmd ("count", no_class, enable_count_command, _("\
15711 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15712 If a breakpoint is hit while enabled in this fashion,\n\
15713 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15714            &enablebreaklist);
15715
15716   add_cmd ("delete", no_class, enable_delete_command, _("\
15717 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15718 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15719            &enablelist);
15720
15721   add_cmd ("once", no_class, enable_once_command, _("\
15722 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15723 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15724            &enablelist);
15725
15726   add_cmd ("count", no_class, enable_count_command, _("\
15727 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15728 If a breakpoint is hit while enabled in this fashion,\n\
15729 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15730            &enablelist);
15731
15732   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15733 Disable some breakpoints.\n\
15734 Arguments are breakpoint numbers with spaces in between.\n\
15735 To disable all breakpoints, give no argument.\n\
15736 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15737                   &disablelist, "disable ", 1, &cmdlist);
15738   add_com_alias ("dis", "disable", class_breakpoint, 1);
15739   add_com_alias ("disa", "disable", class_breakpoint, 1);
15740
15741   add_cmd ("breakpoints", class_alias, disable_command, _("\
15742 Disable some breakpoints.\n\
15743 Arguments are breakpoint numbers with spaces in between.\n\
15744 To disable all breakpoints, give no argument.\n\
15745 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15746 This command may be abbreviated \"disable\"."),
15747            &disablelist);
15748
15749   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15750 Delete some breakpoints or auto-display expressions.\n\
15751 Arguments are breakpoint numbers with spaces in between.\n\
15752 To delete all breakpoints, give no argument.\n\
15753 \n\
15754 Also a prefix command for deletion of other GDB objects.\n\
15755 The \"unset\" command is also an alias for \"delete\"."),
15756                   &deletelist, "delete ", 1, &cmdlist);
15757   add_com_alias ("d", "delete", class_breakpoint, 1);
15758   add_com_alias ("del", "delete", class_breakpoint, 1);
15759
15760   add_cmd ("breakpoints", class_alias, delete_command, _("\
15761 Delete some breakpoints or auto-display expressions.\n\
15762 Arguments are breakpoint numbers with spaces in between.\n\
15763 To delete all breakpoints, give no argument.\n\
15764 This command may be abbreviated \"delete\"."),
15765            &deletelist);
15766
15767   add_com ("clear", class_breakpoint, clear_command, _("\
15768 Clear breakpoint at specified location.\n\
15769 Argument may be a linespec, explicit, or address location as described below.\n\
15770 \n\
15771 With no argument, clears all breakpoints in the line that the selected frame\n\
15772 is executing in.\n"
15773 "\n" LOCATION_HELP_STRING "\n\
15774 See also the \"delete\" command which clears breakpoints by number."));
15775   add_com_alias ("cl", "clear", class_breakpoint, 1);
15776
15777   c = add_com ("break", class_breakpoint, break_command, _("\
15778 Set breakpoint at specified location.\n"
15779 BREAK_ARGS_HELP ("break")));
15780   set_cmd_completer (c, location_completer);
15781
15782   add_com_alias ("b", "break", class_run, 1);
15783   add_com_alias ("br", "break", class_run, 1);
15784   add_com_alias ("bre", "break", class_run, 1);
15785   add_com_alias ("brea", "break", class_run, 1);
15786
15787   if (dbx_commands)
15788     {
15789       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15790 Break in function/address or break at a line in the current file."),
15791                              &stoplist, "stop ", 1, &cmdlist);
15792       add_cmd ("in", class_breakpoint, stopin_command,
15793                _("Break in function or address."), &stoplist);
15794       add_cmd ("at", class_breakpoint, stopat_command,
15795                _("Break at a line in the current file."), &stoplist);
15796       add_com ("status", class_info, info_breakpoints_command, _("\
15797 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15798 The \"Type\" column indicates one of:\n\
15799 \tbreakpoint     - normal breakpoint\n\
15800 \twatchpoint     - watchpoint\n\
15801 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15802 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15803 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15804 address and file/line number respectively.\n\
15805 \n\
15806 Convenience variable \"$_\" and default examine address for \"x\"\n\
15807 are set to the address of the last breakpoint listed unless the command\n\
15808 is prefixed with \"server \".\n\n\
15809 Convenience variable \"$bpnum\" contains the number of the last\n\
15810 breakpoint set."));
15811     }
15812
15813   add_info ("breakpoints", info_breakpoints_command, _("\
15814 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15815 The \"Type\" column indicates one of:\n\
15816 \tbreakpoint     - normal breakpoint\n\
15817 \twatchpoint     - watchpoint\n\
15818 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15819 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15820 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15821 address and file/line number respectively.\n\
15822 \n\
15823 Convenience variable \"$_\" and default examine address for \"x\"\n\
15824 are set to the address of the last breakpoint listed unless the command\n\
15825 is prefixed with \"server \".\n\n\
15826 Convenience variable \"$bpnum\" contains the number of the last\n\
15827 breakpoint set."));
15828
15829   add_info_alias ("b", "breakpoints", 1);
15830
15831   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15832 Status of all breakpoints, or breakpoint number NUMBER.\n\
15833 The \"Type\" column indicates one of:\n\
15834 \tbreakpoint     - normal breakpoint\n\
15835 \twatchpoint     - watchpoint\n\
15836 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15837 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15838 \tuntil          - internal breakpoint used by the \"until\" command\n\
15839 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15840 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15841 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15842 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15843 address and file/line number respectively.\n\
15844 \n\
15845 Convenience variable \"$_\" and default examine address for \"x\"\n\
15846 are set to the address of the last breakpoint listed unless the command\n\
15847 is prefixed with \"server \".\n\n\
15848 Convenience variable \"$bpnum\" contains the number of the last\n\
15849 breakpoint set."),
15850            &maintenanceinfolist);
15851
15852   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15853 Set catchpoints to catch events."),
15854                   &catch_cmdlist, "catch ",
15855                   0/*allow-unknown*/, &cmdlist);
15856
15857   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15858 Set temporary catchpoints to catch events."),
15859                   &tcatch_cmdlist, "tcatch ",
15860                   0/*allow-unknown*/, &cmdlist);
15861
15862   add_catch_command ("fork", _("Catch calls to fork."),
15863                      catch_fork_command_1,
15864                      NULL,
15865                      (void *) (uintptr_t) catch_fork_permanent,
15866                      (void *) (uintptr_t) catch_fork_temporary);
15867   add_catch_command ("vfork", _("Catch calls to vfork."),
15868                      catch_fork_command_1,
15869                      NULL,
15870                      (void *) (uintptr_t) catch_vfork_permanent,
15871                      (void *) (uintptr_t) catch_vfork_temporary);
15872   add_catch_command ("exec", _("Catch calls to exec."),
15873                      catch_exec_command_1,
15874                      NULL,
15875                      CATCH_PERMANENT,
15876                      CATCH_TEMPORARY);
15877   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15878 Usage: catch load [REGEX]\n\
15879 If REGEX is given, only stop for libraries matching the regular expression."),
15880                      catch_load_command_1,
15881                      NULL,
15882                      CATCH_PERMANENT,
15883                      CATCH_TEMPORARY);
15884   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15885 Usage: catch unload [REGEX]\n\
15886 If REGEX is given, only stop for libraries matching the regular expression."),
15887                      catch_unload_command_1,
15888                      NULL,
15889                      CATCH_PERMANENT,
15890                      CATCH_TEMPORARY);
15891
15892   c = add_com ("watch", class_breakpoint, watch_command, _("\
15893 Set a watchpoint for an expression.\n\
15894 Usage: watch [-l|-location] EXPRESSION\n\
15895 A watchpoint stops execution of your program whenever the value of\n\
15896 an expression changes.\n\
15897 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15898 the memory to which it refers."));
15899   set_cmd_completer (c, expression_completer);
15900
15901   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15902 Set a read watchpoint for an expression.\n\
15903 Usage: rwatch [-l|-location] EXPRESSION\n\
15904 A watchpoint stops execution of your program whenever the value of\n\
15905 an expression is read.\n\
15906 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15907 the memory to which it refers."));
15908   set_cmd_completer (c, expression_completer);
15909
15910   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15911 Set a watchpoint for an expression.\n\
15912 Usage: awatch [-l|-location] EXPRESSION\n\
15913 A watchpoint stops execution of your program whenever the value of\n\
15914 an expression is either read or written.\n\
15915 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15916 the memory to which it refers."));
15917   set_cmd_completer (c, expression_completer);
15918
15919   add_info ("watchpoints", info_watchpoints_command, _("\
15920 Status of specified watchpoints (all watchpoints if no argument)."));
15921
15922   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15923      respond to changes - contrary to the description.  */
15924   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15925                             &can_use_hw_watchpoints, _("\
15926 Set debugger's willingness to use watchpoint hardware."), _("\
15927 Show debugger's willingness to use watchpoint hardware."), _("\
15928 If zero, gdb will not use hardware for new watchpoints, even if\n\
15929 such is available.  (However, any hardware watchpoints that were\n\
15930 created before setting this to nonzero, will continue to use watchpoint\n\
15931 hardware.)"),
15932                             NULL,
15933                             show_can_use_hw_watchpoints,
15934                             &setlist, &showlist);
15935
15936   can_use_hw_watchpoints = 1;
15937
15938   /* Tracepoint manipulation commands.  */
15939
15940   c = add_com ("trace", class_breakpoint, trace_command, _("\
15941 Set a tracepoint at specified location.\n\
15942 \n"
15943 BREAK_ARGS_HELP ("trace") "\n\
15944 Do \"help tracepoints\" for info on other tracepoint commands."));
15945   set_cmd_completer (c, location_completer);
15946
15947   add_com_alias ("tp", "trace", class_alias, 0);
15948   add_com_alias ("tr", "trace", class_alias, 1);
15949   add_com_alias ("tra", "trace", class_alias, 1);
15950   add_com_alias ("trac", "trace", class_alias, 1);
15951
15952   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15953 Set a fast tracepoint at specified location.\n\
15954 \n"
15955 BREAK_ARGS_HELP ("ftrace") "\n\
15956 Do \"help tracepoints\" for info on other tracepoint commands."));
15957   set_cmd_completer (c, location_completer);
15958
15959   c = add_com ("strace", class_breakpoint, strace_command, _("\
15960 Set a static tracepoint at location or marker.\n\
15961 \n\
15962 strace [LOCATION] [if CONDITION]\n\
15963 LOCATION may be a linespec, explicit, or address location (described below) \n\
15964 or -m MARKER_ID.\n\n\
15965 If a marker id is specified, probe the marker with that name.  With\n\
15966 no LOCATION, uses current execution address of the selected stack frame.\n\
15967 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15968 This collects arbitrary user data passed in the probe point call to the\n\
15969 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15970 by printing the $_sdata variable like any other convenience variable.\n\
15971 \n\
15972 CONDITION is a boolean expression.\n\
15973 \n" LOCATION_HELP_STRING "\n\
15974 Multiple tracepoints at one place are permitted, and useful if their\n\
15975 conditions are different.\n\
15976 \n\
15977 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15978 Do \"help tracepoints\" for info on other tracepoint commands."));
15979   set_cmd_completer (c, location_completer);
15980
15981   add_info ("tracepoints", info_tracepoints_command, _("\
15982 Status of specified tracepoints (all tracepoints if no argument).\n\
15983 Convenience variable \"$tpnum\" contains the number of the\n\
15984 last tracepoint set."));
15985
15986   add_info_alias ("tp", "tracepoints", 1);
15987
15988   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15989 Delete specified tracepoints.\n\
15990 Arguments are tracepoint numbers, separated by spaces.\n\
15991 No argument means delete all tracepoints."),
15992            &deletelist);
15993   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
15994
15995   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15996 Disable specified tracepoints.\n\
15997 Arguments are tracepoint numbers, separated by spaces.\n\
15998 No argument means disable all tracepoints."),
15999            &disablelist);
16000   deprecate_cmd (c, "disable");
16001
16002   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16003 Enable specified tracepoints.\n\
16004 Arguments are tracepoint numbers, separated by spaces.\n\
16005 No argument means enable all tracepoints."),
16006            &enablelist);
16007   deprecate_cmd (c, "enable");
16008
16009   add_com ("passcount", class_trace, trace_pass_command, _("\
16010 Set the passcount for a tracepoint.\n\
16011 The trace will end when the tracepoint has been passed 'count' times.\n\
16012 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16013 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16014
16015   add_prefix_cmd ("save", class_breakpoint, save_command,
16016                   _("Save breakpoint definitions as a script."),
16017                   &save_cmdlist, "save ",
16018                   0/*allow-unknown*/, &cmdlist);
16019
16020   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16021 Save current breakpoint definitions as a script.\n\
16022 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16023 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16024 session to restore them."),
16025                &save_cmdlist);
16026   set_cmd_completer (c, filename_completer);
16027
16028   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16029 Save current tracepoint definitions as a script.\n\
16030 Use the 'source' command in another debug session to restore them."),
16031                &save_cmdlist);
16032   set_cmd_completer (c, filename_completer);
16033
16034   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16035   deprecate_cmd (c, "save tracepoints");
16036
16037   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16038 Breakpoint specific settings\n\
16039 Configure various breakpoint-specific variables such as\n\
16040 pending breakpoint behavior"),
16041                   &breakpoint_set_cmdlist, "set breakpoint ",
16042                   0/*allow-unknown*/, &setlist);
16043   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16044 Breakpoint specific settings\n\
16045 Configure various breakpoint-specific variables such as\n\
16046 pending breakpoint behavior"),
16047                   &breakpoint_show_cmdlist, "show breakpoint ",
16048                   0/*allow-unknown*/, &showlist);
16049
16050   add_setshow_auto_boolean_cmd ("pending", no_class,
16051                                 &pending_break_support, _("\
16052 Set debugger's behavior regarding pending breakpoints."), _("\
16053 Show debugger's behavior regarding pending breakpoints."), _("\
16054 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16055 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16056 an error.  If auto, an unrecognized breakpoint location results in a\n\
16057 user-query to see if a pending breakpoint should be created."),
16058                                 NULL,
16059                                 show_pending_break_support,
16060                                 &breakpoint_set_cmdlist,
16061                                 &breakpoint_show_cmdlist);
16062
16063   pending_break_support = AUTO_BOOLEAN_AUTO;
16064
16065   add_setshow_boolean_cmd ("auto-hw", no_class,
16066                            &automatic_hardware_breakpoints, _("\
16067 Set automatic usage of hardware breakpoints."), _("\
16068 Show automatic usage of hardware breakpoints."), _("\
16069 If set, the debugger will automatically use hardware breakpoints for\n\
16070 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16071 a warning will be emitted for such breakpoints."),
16072                            NULL,
16073                            show_automatic_hardware_breakpoints,
16074                            &breakpoint_set_cmdlist,
16075                            &breakpoint_show_cmdlist);
16076
16077   add_setshow_boolean_cmd ("always-inserted", class_support,
16078                            &always_inserted_mode, _("\
16079 Set mode for inserting breakpoints."), _("\
16080 Show mode for inserting breakpoints."), _("\
16081 When this mode is on, breakpoints are inserted immediately as soon as\n\
16082 they're created, kept inserted even when execution stops, and removed\n\
16083 only when the user deletes them.  When this mode is off (the default),\n\
16084 breakpoints are inserted only when execution continues, and removed\n\
16085 when execution stops."),
16086                                 NULL,
16087                                 &show_always_inserted_mode,
16088                                 &breakpoint_set_cmdlist,
16089                                 &breakpoint_show_cmdlist);
16090
16091   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16092                         condition_evaluation_enums,
16093                         &condition_evaluation_mode_1, _("\
16094 Set mode of breakpoint condition evaluation."), _("\
16095 Show mode of breakpoint condition evaluation."), _("\
16096 When this is set to \"host\", breakpoint conditions will be\n\
16097 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16098 breakpoint conditions will be downloaded to the target (if the target\n\
16099 supports such feature) and conditions will be evaluated on the target's side.\n\
16100 If this is set to \"auto\" (default), this will be automatically set to\n\
16101 \"target\" if it supports condition evaluation, otherwise it will\n\
16102 be set to \"gdb\""),
16103                            &set_condition_evaluation_mode,
16104                            &show_condition_evaluation_mode,
16105                            &breakpoint_set_cmdlist,
16106                            &breakpoint_show_cmdlist);
16107
16108   add_com ("break-range", class_breakpoint, break_range_command, _("\
16109 Set a breakpoint for an address range.\n\
16110 break-range START-LOCATION, END-LOCATION\n\
16111 where START-LOCATION and END-LOCATION can be one of the following:\n\
16112   LINENUM, for that line in the current file,\n\
16113   FILE:LINENUM, for that line in that file,\n\
16114   +OFFSET, for that number of lines after the current line\n\
16115            or the start of the range\n\
16116   FUNCTION, for the first line in that function,\n\
16117   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16118   *ADDRESS, for the instruction at that address.\n\
16119 \n\
16120 The breakpoint will stop execution of the inferior whenever it executes\n\
16121 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16122 range (including START-LOCATION and END-LOCATION)."));
16123
16124   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16125 Set a dynamic printf at specified location.\n\
16126 dprintf location,format string,arg1,arg2,...\n\
16127 location may be a linespec, explicit, or address location.\n"
16128 "\n" LOCATION_HELP_STRING));
16129   set_cmd_completer (c, location_completer);
16130
16131   add_setshow_enum_cmd ("dprintf-style", class_support,
16132                         dprintf_style_enums, &dprintf_style, _("\
16133 Set the style of usage for dynamic printf."), _("\
16134 Show the style of usage for dynamic printf."), _("\
16135 This setting chooses how GDB will do a dynamic printf.\n\
16136 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16137 console, as with the \"printf\" command.\n\
16138 If the value is \"call\", the print is done by calling a function in your\n\
16139 program; by default printf(), but you can choose a different function or\n\
16140 output stream by setting dprintf-function and dprintf-channel."),
16141                         update_dprintf_commands, NULL,
16142                         &setlist, &showlist);
16143
16144   dprintf_function = xstrdup ("printf");
16145   add_setshow_string_cmd ("dprintf-function", class_support,
16146                           &dprintf_function, _("\
16147 Set the function to use for dynamic printf"), _("\
16148 Show the function to use for dynamic printf"), NULL,
16149                           update_dprintf_commands, NULL,
16150                           &setlist, &showlist);
16151
16152   dprintf_channel = xstrdup ("");
16153   add_setshow_string_cmd ("dprintf-channel", class_support,
16154                           &dprintf_channel, _("\
16155 Set the channel to use for dynamic printf"), _("\
16156 Show the channel to use for dynamic printf"), NULL,
16157                           update_dprintf_commands, NULL,
16158                           &setlist, &showlist);
16159
16160   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16161                            &disconnected_dprintf, _("\
16162 Set whether dprintf continues after GDB disconnects."), _("\
16163 Show whether dprintf continues after GDB disconnects."), _("\
16164 Use this to let dprintf commands continue to hit and produce output\n\
16165 even if GDB disconnects or detaches from the target."),
16166                            NULL,
16167                            NULL,
16168                            &setlist, &showlist);
16169
16170   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16171 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16172 (target agent only) This is useful for formatted output in user-defined commands."));
16173
16174   automatic_hardware_breakpoints = 1;
16175
16176   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16177   observer_attach_thread_exit (remove_threaded_breakpoints);
16178 }