]> Git Repo - binutils.git/blob - gdb/breakpoint.c
gdb: clear inferior displaced stepping state and in-line step-over info on exec
[binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2020 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 "observable.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 "stack.h"
63 #include "ax-gdb.h"
64 #include "dummy-frame.h"
65 #include "interps.h"
66 #include "gdbsupport/format.h"
67 #include "thread-fsm.h"
68 #include "tid-parse.h"
69 #include "cli/cli-style.h"
70
71 /* readline include files */
72 #include "readline/tilde.h"
73
74 /* readline defines this.  */
75 #undef savestring
76
77 #include "mi/mi-common.h"
78 #include "extension.h"
79 #include <algorithm>
80 #include "progspace-and-thread.h"
81 #include "gdbsupport/array-view.h"
82 #include "gdbsupport/gdb_optional.h"
83
84 /* Prototypes for local functions.  */
85
86 static void map_breakpoint_numbers (const char *,
87                                     gdb::function_view<void (breakpoint *)>);
88
89 static void breakpoint_re_set_default (struct breakpoint *);
90
91 static void
92   create_sals_from_location_default (struct event_location *location,
93                                      struct linespec_result *canonical,
94                                      enum bptype type_wanted);
95
96 static void create_breakpoints_sal_default (struct gdbarch *,
97                                             struct linespec_result *,
98                                             gdb::unique_xmalloc_ptr<char>,
99                                             gdb::unique_xmalloc_ptr<char>,
100                                             enum bptype,
101                                             enum bpdisp, int, int,
102                                             int,
103                                             const struct breakpoint_ops *,
104                                             int, int, int, unsigned);
105
106 static std::vector<symtab_and_line> decode_location_default
107   (struct breakpoint *b, struct event_location *location,
108    struct program_space *search_pspace);
109
110 static int can_use_hardware_watchpoint
111     (const std::vector<value_ref_ptr> &vals);
112
113 static void mention (struct breakpoint *);
114
115 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
116                                                                enum bptype,
117                                                                const struct breakpoint_ops *);
118 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
119                                                        const struct symtab_and_line *);
120
121 /* This function is used in gdbtk sources and thus can not be made
122    static.  */
123 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
124                                        struct symtab_and_line,
125                                        enum bptype,
126                                        const struct breakpoint_ops *);
127
128 static struct breakpoint *
129   momentary_breakpoint_from_master (struct breakpoint *orig,
130                                     enum bptype type,
131                                     const struct breakpoint_ops *ops,
132                                     int loc_enabled);
133
134 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
135
136 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
137                                             CORE_ADDR bpaddr,
138                                             enum bptype bptype);
139
140 static void describe_other_breakpoints (struct gdbarch *,
141                                         struct program_space *, CORE_ADDR,
142                                         struct obj_section *, int);
143
144 static int watchpoint_locations_match (struct bp_location *loc1,
145                                        struct bp_location *loc2);
146
147 static int breakpoint_locations_match (struct bp_location *loc1,
148                                        struct bp_location *loc2,
149                                        bool sw_hw_bps_match = false);
150
151 static int breakpoint_location_address_match (struct bp_location *bl,
152                                               const struct address_space *aspace,
153                                               CORE_ADDR addr);
154
155 static int breakpoint_location_address_range_overlap (struct bp_location *,
156                                                       const address_space *,
157                                                       CORE_ADDR, int);
158
159 static int remove_breakpoint (struct bp_location *);
160 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
161
162 static enum print_stop_action print_bp_stop_message (bpstat bs);
163
164 static int hw_breakpoint_used_count (void);
165
166 static int hw_watchpoint_use_count (struct breakpoint *);
167
168 static int hw_watchpoint_used_count_others (struct breakpoint *except,
169                                             enum bptype type,
170                                             int *other_type_used);
171
172 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
173                                     int count);
174
175 static void free_bp_location (struct bp_location *loc);
176 static void incref_bp_location (struct bp_location *loc);
177 static void decref_bp_location (struct bp_location **loc);
178
179 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
180
181 /* update_global_location_list's modes of operation wrt to whether to
182    insert locations now.  */
183 enum ugll_insert_mode
184 {
185   /* Don't insert any breakpoint locations into the inferior, only
186      remove already-inserted locations that no longer should be
187      inserted.  Functions that delete a breakpoint or breakpoints
188      should specify this mode, so that deleting a breakpoint doesn't
189      have the side effect of inserting the locations of other
190      breakpoints that are marked not-inserted, but should_be_inserted
191      returns true on them.
192
193      This behavior is useful is situations close to tear-down -- e.g.,
194      after an exec, while the target still has execution, but
195      breakpoint shadows of the previous executable image should *NOT*
196      be restored to the new image; or before detaching, where the
197      target still has execution and wants to delete breakpoints from
198      GDB's lists, and all breakpoints had already been removed from
199      the inferior.  */
200   UGLL_DONT_INSERT,
201
202   /* May insert breakpoints iff breakpoints_should_be_inserted_now
203      claims breakpoints should be inserted now.  */
204   UGLL_MAY_INSERT,
205
206   /* Insert locations now, irrespective of
207      breakpoints_should_be_inserted_now.  E.g., say all threads are
208      stopped right now, and the user did "continue".  We need to
209      insert breakpoints _before_ resuming the target, but
210      UGLL_MAY_INSERT wouldn't insert them, because
211      breakpoints_should_be_inserted_now returns false at that point,
212      as no thread is running yet.  */
213   UGLL_INSERT
214 };
215
216 static void update_global_location_list (enum ugll_insert_mode);
217
218 static void update_global_location_list_nothrow (enum ugll_insert_mode);
219
220 static void insert_breakpoint_locations (void);
221
222 static void trace_pass_command (const char *, int);
223
224 static void set_tracepoint_count (int num);
225
226 static bool is_masked_watchpoint (const struct breakpoint *b);
227
228 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
229
230 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
231    otherwise.  */
232
233 static int strace_marker_p (struct breakpoint *b);
234
235 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
236    that are implemented on top of software or hardware breakpoints
237    (user breakpoints, internal and momentary breakpoints, etc.).  */
238 static struct breakpoint_ops bkpt_base_breakpoint_ops;
239
240 /* Internal breakpoints class type.  */
241 static struct breakpoint_ops internal_breakpoint_ops;
242
243 /* Momentary breakpoints class type.  */
244 static struct breakpoint_ops momentary_breakpoint_ops;
245
246 /* The breakpoint_ops structure to be used in regular user created
247    breakpoints.  */
248 struct breakpoint_ops bkpt_breakpoint_ops;
249
250 /* Breakpoints set on probes.  */
251 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
252
253 /* Tracepoints set on probes.  */
254 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
255
256 /* Dynamic printf class type.  */
257 struct breakpoint_ops dprintf_breakpoint_ops;
258
259 /* The style in which to perform a dynamic printf.  This is a user
260    option because different output options have different tradeoffs;
261    if GDB does the printing, there is better error handling if there
262    is a problem with any of the arguments, but using an inferior
263    function lets you have special-purpose printers and sending of
264    output to the same place as compiled-in print functions.  */
265
266 static const char dprintf_style_gdb[] = "gdb";
267 static const char dprintf_style_call[] = "call";
268 static const char dprintf_style_agent[] = "agent";
269 static const char *const dprintf_style_enums[] = {
270   dprintf_style_gdb,
271   dprintf_style_call,
272   dprintf_style_agent,
273   NULL
274 };
275 static const char *dprintf_style = dprintf_style_gdb;
276
277 /* The function to use for dynamic printf if the preferred style is to
278    call into the inferior.  The value is simply a string that is
279    copied into the command, so it can be anything that GDB can
280    evaluate to a callable address, not necessarily a function name.  */
281
282 static char *dprintf_function;
283
284 /* The channel to use for dynamic printf if the preferred style is to
285    call into the inferior; if a nonempty string, it will be passed to
286    the call as the first argument, with the format string as the
287    second.  As with the dprintf function, this can be anything that
288    GDB knows how to evaluate, so in addition to common choices like
289    "stderr", this could be an app-specific expression like
290    "mystreams[curlogger]".  */
291
292 static char *dprintf_channel;
293
294 /* True if dprintf commands should continue to operate even if GDB
295    has disconnected.  */
296 static bool disconnected_dprintf = true;
297
298 struct command_line *
299 breakpoint_commands (struct breakpoint *b)
300 {
301   return b->commands ? b->commands.get () : NULL;
302 }
303
304 /* Flag indicating that a command has proceeded the inferior past the
305    current breakpoint.  */
306
307 static bool breakpoint_proceeded;
308
309 const char *
310 bpdisp_text (enum bpdisp disp)
311 {
312   /* NOTE: the following values are a part of MI protocol and
313      represent values of 'disp' field returned when inferior stops at
314      a breakpoint.  */
315   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
316
317   return bpdisps[(int) disp];
318 }
319
320 /* Prototypes for exported functions.  */
321 /* If FALSE, gdb will not use hardware support for watchpoints, even
322    if such is available.  */
323 static int can_use_hw_watchpoints;
324
325 static void
326 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
327                              struct cmd_list_element *c,
328                              const char *value)
329 {
330   fprintf_filtered (file,
331                     _("Debugger's willingness to use "
332                       "watchpoint hardware is %s.\n"),
333                     value);
334 }
335
336 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
337    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
338    for unrecognized breakpoint locations.
339    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
340 static enum auto_boolean pending_break_support;
341 static void
342 show_pending_break_support (struct ui_file *file, int from_tty,
343                             struct cmd_list_element *c,
344                             const char *value)
345 {
346   fprintf_filtered (file,
347                     _("Debugger's behavior regarding "
348                       "pending breakpoints is %s.\n"),
349                     value);
350 }
351
352 /* If true, gdb will automatically use hardware breakpoints for breakpoints
353    set with "break" but falling in read-only memory.
354    If false, gdb will warn about such breakpoints, but won't automatically
355    use hardware breakpoints.  */
356 static bool automatic_hardware_breakpoints;
357 static void
358 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
359                                      struct cmd_list_element *c,
360                                      const char *value)
361 {
362   fprintf_filtered (file,
363                     _("Automatic usage of hardware breakpoints is %s.\n"),
364                     value);
365 }
366
367 /* If on, GDB keeps breakpoints inserted even if the inferior is
368    stopped, and immediately inserts any new breakpoints as soon as
369    they're created.  If off (default), GDB keeps breakpoints off of
370    the target as long as possible.  That is, it delays inserting
371    breakpoints until the next resume, and removes them again when the
372    target fully stops.  This is a bit safer in case GDB crashes while
373    processing user input.  */
374 static bool always_inserted_mode = false;
375
376 static void
377 show_always_inserted_mode (struct ui_file *file, int from_tty,
378                      struct cmd_list_element *c, const char *value)
379 {
380   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
381                     value);
382 }
383
384 /* See breakpoint.h.  */
385
386 int
387 breakpoints_should_be_inserted_now (void)
388 {
389   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
390     {
391       /* If breakpoints are global, they should be inserted even if no
392          thread under gdb's control is running, or even if there are
393          no threads under GDB's control yet.  */
394       return 1;
395     }
396   else
397     {
398       if (always_inserted_mode)
399         {
400           /* The user wants breakpoints inserted even if all threads
401              are stopped.  */
402           return 1;
403         }
404
405       for (inferior *inf : all_inferiors ())
406         if (inf->has_execution ()
407             && threads_are_executing (inf->process_target ()))
408           return 1;
409
410       /* Don't remove breakpoints yet if, even though all threads are
411          stopped, we still have events to process.  */
412       for (thread_info *tp : all_non_exited_threads ())
413         if (tp->resumed
414             && tp->suspend.waitstatus_pending_p)
415           return 1;
416     }
417   return 0;
418 }
419
420 static const char condition_evaluation_both[] = "host or target";
421
422 /* Modes for breakpoint condition evaluation.  */
423 static const char condition_evaluation_auto[] = "auto";
424 static const char condition_evaluation_host[] = "host";
425 static const char condition_evaluation_target[] = "target";
426 static const char *const condition_evaluation_enums[] = {
427   condition_evaluation_auto,
428   condition_evaluation_host,
429   condition_evaluation_target,
430   NULL
431 };
432
433 /* Global that holds the current mode for breakpoint condition evaluation.  */
434 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
435
436 /* Global that we use to display information to the user (gets its value from
437    condition_evaluation_mode_1.  */
438 static const char *condition_evaluation_mode = condition_evaluation_auto;
439
440 /* Translate a condition evaluation mode MODE into either "host"
441    or "target".  This is used mostly to translate from "auto" to the
442    real setting that is being used.  It returns the translated
443    evaluation mode.  */
444
445 static const char *
446 translate_condition_evaluation_mode (const char *mode)
447 {
448   if (mode == condition_evaluation_auto)
449     {
450       if (target_supports_evaluation_of_breakpoint_conditions ())
451         return condition_evaluation_target;
452       else
453         return condition_evaluation_host;
454     }
455   else
456     return mode;
457 }
458
459 /* Discovers what condition_evaluation_auto translates to.  */
460
461 static const char *
462 breakpoint_condition_evaluation_mode (void)
463 {
464   return translate_condition_evaluation_mode (condition_evaluation_mode);
465 }
466
467 /* Return true if GDB should evaluate breakpoint conditions or false
468    otherwise.  */
469
470 static int
471 gdb_evaluates_breakpoint_condition_p (void)
472 {
473   const char *mode = breakpoint_condition_evaluation_mode ();
474
475   return (mode == condition_evaluation_host);
476 }
477
478 /* Are we executing breakpoint commands?  */
479 static int executing_breakpoint_commands;
480
481 /* Are overlay event breakpoints enabled? */
482 static int overlay_events_enabled;
483
484 /* See description in breakpoint.h. */
485 bool target_exact_watchpoints = false;
486
487 /* Walk the following statement or block through all breakpoints.
488    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
489    current breakpoint.  */
490
491 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
492
493 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
494         for (B = breakpoint_chain;      \
495              B ? (TMP=B->next, 1): 0;   \
496              B = TMP)
497
498 /* Similar iterator for the low-level breakpoints.  SAFE variant is
499    not provided so update_global_location_list must not be called
500    while executing the block of ALL_BP_LOCATIONS.  */
501
502 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
503         for (BP_TMP = bp_locations;                                     \
504              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
505              BP_TMP++)
506
507 /* Iterates through locations with address ADDRESS for the currently selected
508    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
509    to where the loop should start from.
510    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
511    appropriate location to start with.  */
512
513 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
514         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
515              BP_LOCP_TMP = BP_LOCP_START;                               \
516              BP_LOCP_START                                              \
517              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
518              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
519              BP_LOCP_TMP++)
520
521 /* Iterator for tracepoints only.  */
522
523 #define ALL_TRACEPOINTS(B)  \
524   for (B = breakpoint_chain; B; B = B->next)  \
525     if (is_tracepoint (B))
526
527 /* Chains of all breakpoints defined.  */
528
529 static struct breakpoint *breakpoint_chain;
530
531 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS.  */
532
533 static struct bp_location **bp_locations;
534
535 /* Number of elements of BP_LOCATIONS.  */
536
537 static unsigned bp_locations_count;
538
539 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
540    ADDRESS for the current elements of BP_LOCATIONS which get a valid
541    result from bp_location_has_shadow.  You can use it for roughly
542    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
543    an address you need to read.  */
544
545 static CORE_ADDR bp_locations_placed_address_before_address_max;
546
547 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
548    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
549    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
550    You can use it for roughly limiting the subrange of BP_LOCATIONS to
551    scan for shadow bytes for an address you need to read.  */
552
553 static CORE_ADDR bp_locations_shadow_len_after_address_max;
554
555 /* The locations that no longer correspond to any breakpoint, unlinked
556    from the bp_locations array, but for which a hit may still be
557    reported by a target.  */
558 static std::vector<bp_location *> moribund_locations;
559
560 /* Number of last breakpoint made.  */
561
562 static int breakpoint_count;
563
564 /* The value of `breakpoint_count' before the last command that
565    created breakpoints.  If the last (break-like) command created more
566    than one breakpoint, then the difference between BREAKPOINT_COUNT
567    and PREV_BREAKPOINT_COUNT is more than one.  */
568 static int prev_breakpoint_count;
569
570 /* Number of last tracepoint made.  */
571
572 static int tracepoint_count;
573
574 static struct cmd_list_element *breakpoint_set_cmdlist;
575 static struct cmd_list_element *breakpoint_show_cmdlist;
576 struct cmd_list_element *save_cmdlist;
577
578 /* See declaration at breakpoint.h.  */
579
580 struct breakpoint *
581 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
582                     void *user_data)
583 {
584   struct breakpoint *b = NULL;
585
586   ALL_BREAKPOINTS (b)
587     {
588       if (func (b, user_data) != 0)
589         break;
590     }
591
592   return b;
593 }
594
595 /* Return whether a breakpoint is an active enabled breakpoint.  */
596 static int
597 breakpoint_enabled (struct breakpoint *b)
598 {
599   return (b->enable_state == bp_enabled);
600 }
601
602 /* Set breakpoint count to NUM.  */
603
604 static void
605 set_breakpoint_count (int num)
606 {
607   prev_breakpoint_count = breakpoint_count;
608   breakpoint_count = num;
609   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
610 }
611
612 /* Used by `start_rbreak_breakpoints' below, to record the current
613    breakpoint count before "rbreak" creates any breakpoint.  */
614 static int rbreak_start_breakpoint_count;
615
616 /* Called at the start an "rbreak" command to record the first
617    breakpoint made.  */
618
619 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
620 {
621   rbreak_start_breakpoint_count = breakpoint_count;
622 }
623
624 /* Called at the end of an "rbreak" command to record the last
625    breakpoint made.  */
626
627 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
628 {
629   prev_breakpoint_count = rbreak_start_breakpoint_count;
630 }
631
632 /* Used in run_command to zero the hit count when a new run starts.  */
633
634 void
635 clear_breakpoint_hit_counts (void)
636 {
637   struct breakpoint *b;
638
639   ALL_BREAKPOINTS (b)
640     b->hit_count = 0;
641 }
642
643 \f
644 /* Return the breakpoint with the specified number, or NULL
645    if the number does not refer to an existing breakpoint.  */
646
647 struct breakpoint *
648 get_breakpoint (int num)
649 {
650   struct breakpoint *b;
651
652   ALL_BREAKPOINTS (b)
653     if (b->number == num)
654       return b;
655   
656   return NULL;
657 }
658
659 \f
660
661 /* Mark locations as "conditions have changed" in case the target supports
662    evaluating conditions on its side.  */
663
664 static void
665 mark_breakpoint_modified (struct breakpoint *b)
666 {
667   struct bp_location *loc;
668
669   /* This is only meaningful if the target is
670      evaluating conditions and if the user has
671      opted for condition evaluation on the target's
672      side.  */
673   if (gdb_evaluates_breakpoint_condition_p ()
674       || !target_supports_evaluation_of_breakpoint_conditions ())
675     return;
676
677   if (!is_breakpoint (b))
678     return;
679
680   for (loc = b->loc; loc; loc = loc->next)
681     loc->condition_changed = condition_modified;
682 }
683
684 /* Mark location as "conditions have changed" in case the target supports
685    evaluating conditions on its side.  */
686
687 static void
688 mark_breakpoint_location_modified (struct bp_location *loc)
689 {
690   /* This is only meaningful if the target is
691      evaluating conditions and if the user has
692      opted for condition evaluation on the target's
693      side.  */
694   if (gdb_evaluates_breakpoint_condition_p ()
695       || !target_supports_evaluation_of_breakpoint_conditions ())
696
697     return;
698
699   if (!is_breakpoint (loc->owner))
700     return;
701
702   loc->condition_changed = condition_modified;
703 }
704
705 /* Sets the condition-evaluation mode using the static global
706    condition_evaluation_mode.  */
707
708 static void
709 set_condition_evaluation_mode (const char *args, int from_tty,
710                                struct cmd_list_element *c)
711 {
712   const char *old_mode, *new_mode;
713
714   if ((condition_evaluation_mode_1 == condition_evaluation_target)
715       && !target_supports_evaluation_of_breakpoint_conditions ())
716     {
717       condition_evaluation_mode_1 = condition_evaluation_mode;
718       warning (_("Target does not support breakpoint condition evaluation.\n"
719                  "Using host evaluation mode instead."));
720       return;
721     }
722
723   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
724   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
725
726   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
727      settings was "auto".  */
728   condition_evaluation_mode = condition_evaluation_mode_1;
729
730   /* Only update the mode if the user picked a different one.  */
731   if (new_mode != old_mode)
732     {
733       struct bp_location *loc, **loc_tmp;
734       /* If the user switched to a different evaluation mode, we
735          need to synch the changes with the target as follows:
736
737          "host" -> "target": Send all (valid) conditions to the target.
738          "target" -> "host": Remove all the conditions from the target.
739       */
740
741       if (new_mode == condition_evaluation_target)
742         {
743           /* Mark everything modified and synch conditions with the
744              target.  */
745           ALL_BP_LOCATIONS (loc, loc_tmp)
746             mark_breakpoint_location_modified (loc);
747         }
748       else
749         {
750           /* Manually mark non-duplicate locations to synch conditions
751              with the target.  We do this to remove all the conditions the
752              target knows about.  */
753           ALL_BP_LOCATIONS (loc, loc_tmp)
754             if (is_breakpoint (loc->owner) && loc->inserted)
755               loc->needs_update = 1;
756         }
757
758       /* Do the update.  */
759       update_global_location_list (UGLL_MAY_INSERT);
760     }
761
762   return;
763 }
764
765 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
766    what "auto" is translating to.  */
767
768 static void
769 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
770                                 struct cmd_list_element *c, const char *value)
771 {
772   if (condition_evaluation_mode == condition_evaluation_auto)
773     fprintf_filtered (file,
774                       _("Breakpoint condition evaluation "
775                         "mode is %s (currently %s).\n"),
776                       value,
777                       breakpoint_condition_evaluation_mode ());
778   else
779     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
780                       value);
781 }
782
783 /* A comparison function for bp_location AP and BP that is used by
784    bsearch.  This comparison function only cares about addresses, unlike
785    the more general bp_location_is_less_than function.  */
786
787 static int
788 bp_locations_compare_addrs (const void *ap, const void *bp)
789 {
790   const struct bp_location *a = *(const struct bp_location **) ap;
791   const struct bp_location *b = *(const struct bp_location **) bp;
792
793   if (a->address == b->address)
794     return 0;
795   else
796     return ((a->address > b->address) - (a->address < b->address));
797 }
798
799 /* Helper function to skip all bp_locations with addresses
800    less than ADDRESS.  It returns the first bp_location that
801    is greater than or equal to ADDRESS.  If none is found, just
802    return NULL.  */
803
804 static struct bp_location **
805 get_first_locp_gte_addr (CORE_ADDR address)
806 {
807   struct bp_location dummy_loc;
808   struct bp_location *dummy_locp = &dummy_loc;
809   struct bp_location **locp_found = NULL;
810
811   /* Initialize the dummy location's address field.  */
812   dummy_loc.address = address;
813
814   /* Find a close match to the first location at ADDRESS.  */
815   locp_found = ((struct bp_location **)
816                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
817                          sizeof (struct bp_location **),
818                          bp_locations_compare_addrs));
819
820   /* Nothing was found, nothing left to do.  */
821   if (locp_found == NULL)
822     return NULL;
823
824   /* We may have found a location that is at ADDRESS but is not the first in the
825      location's list.  Go backwards (if possible) and locate the first one.  */
826   while ((locp_found - 1) >= bp_locations
827          && (*(locp_found - 1))->address == address)
828     locp_found--;
829
830   return locp_found;
831 }
832
833 /* Parse COND_STRING in the context of LOC and set as the condition
834    expression of LOC.  BP_NUM is the number of LOC's owner, LOC_NUM is
835    the number of LOC within its owner.  In case of parsing error, mark
836    LOC as DISABLED_BY_COND.  In case of success, unset DISABLED_BY_COND.  */
837
838 static void
839 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
840                                    int bp_num, int loc_num)
841 {
842   bool has_junk = false;
843   try
844     {
845       expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
846                                            block_for_pc (loc->address), 0);
847       if (*cond_string != 0)
848         has_junk = true;
849       else
850         {
851           loc->cond = std::move (new_exp);
852           if (loc->disabled_by_cond && loc->enabled)
853             printf_filtered (_("Breakpoint %d's condition is now valid at "
854                                "location %d, enabling.\n"),
855                              bp_num, loc_num);
856
857           loc->disabled_by_cond = false;
858         }
859     }
860   catch (const gdb_exception_error &e)
861     {
862       if (loc->enabled)
863         {
864           /* Warn if a user-enabled location is now becoming disabled-by-cond.
865              BP_NUM is 0 if the breakpoint is being defined for the first
866              time using the "break ... if ..." command, and non-zero if
867              already defined.  */
868           if (bp_num != 0)
869             warning (_("failed to validate condition at location %d.%d, "
870                        "disabling:\n  %s"), bp_num, loc_num, e.what ());
871           else
872             warning (_("failed to validate condition at location %d, "
873                        "disabling:\n  %s"), loc_num, e.what ());
874         }
875
876       loc->disabled_by_cond = true;
877     }
878
879   if (has_junk)
880     error (_("Garbage '%s' follows condition"), cond_string);
881 }
882
883 void
884 set_breakpoint_condition (struct breakpoint *b, const char *exp,
885                           int from_tty, bool force)
886 {
887   if (*exp == 0)
888     {
889       xfree (b->cond_string);
890       b->cond_string = nullptr;
891
892       if (is_watchpoint (b))
893         static_cast<watchpoint *> (b)->cond_exp.reset ();
894       else
895         {
896           int loc_num = 1;
897           for (bp_location *loc = b->loc; loc != nullptr; loc = loc->next)
898             {
899               loc->cond.reset ();
900               if (loc->disabled_by_cond && loc->enabled)
901                 printf_filtered (_("Breakpoint %d's condition is now valid at "
902                                    "location %d, enabling.\n"),
903                                  b->number, loc_num);
904               loc->disabled_by_cond = false;
905               loc_num++;
906
907               /* No need to free the condition agent expression
908                  bytecode (if we have one).  We will handle this
909                  when we go through update_global_location_list.  */
910             }
911         }
912
913       if (from_tty)
914         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
915     }
916   else
917     {
918       if (is_watchpoint (b))
919         {
920           innermost_block_tracker tracker;
921           const char *arg = exp;
922           expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
923           if (*arg != 0)
924             error (_("Junk at end of expression"));
925           watchpoint *w = static_cast<watchpoint *> (b);
926           w->cond_exp = std::move (new_exp);
927           w->cond_exp_valid_block = tracker.block ();
928         }
929       else
930         {
931           /* Parse and set condition expressions.  We make two passes.
932              In the first, we parse the condition string to see if it
933              is valid in at least one location.  If so, the condition
934              would be accepted.  So we go ahead and set the locations'
935              conditions.  In case no valid case is found, we throw
936              the error and the condition string will be rejected.
937              This two-pass approach is taken to avoid setting the
938              state of locations in case of a reject.  */
939           for (bp_location *loc = b->loc; loc != nullptr; loc = loc->next)
940             {
941               try
942                 {
943                   const char *arg = exp;
944                   parse_exp_1 (&arg, loc->address,
945                                block_for_pc (loc->address), 0);
946                   if (*arg != 0)
947                     error (_("Junk at end of expression"));
948                   break;
949                 }
950               catch (const gdb_exception_error &e)
951                 {
952                   /* Condition string is invalid.  If this happens to
953                      be the last loc, abandon (if not forced) or continue
954                      (if forced).  */
955                   if (loc->next == nullptr && !force)
956                     throw;
957                 }
958             }
959
960           /* If we reach here, the condition is valid at some locations.  */
961           int loc_num = 1;
962           for (bp_location *loc = b->loc; loc != nullptr;
963                loc = loc->next, loc_num++)
964             set_breakpoint_location_condition (exp, loc, b->number, loc_num);
965         }
966
967       /* We know that the new condition parsed successfully.  The
968          condition string of the breakpoint can be safely updated.  */
969       xfree (b->cond_string);
970       b->cond_string = xstrdup (exp);
971       b->condition_not_parsed = 0;
972     }
973   mark_breakpoint_modified (b);
974
975   gdb::observers::breakpoint_modified.notify (b);
976 }
977
978 /* The options for the "condition" command.  */
979
980 struct condition_command_opts
981 {
982   /* For "-force".  */
983   bool force_condition = false;
984 };
985
986 static const gdb::option::option_def condition_command_option_defs[] = {
987
988   gdb::option::flag_option_def<condition_command_opts> {
989     "force",
990     [] (condition_command_opts *opts) { return &opts->force_condition; },
991     N_("Set the condition even if it is invalid for all current locations."),
992   },
993
994 };
995
996 /* Create an option_def_group for the "condition" options, with
997    CC_OPTS as context.  */
998
999 static inline gdb::option::option_def_group
1000 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1001 {
1002   return {{condition_command_option_defs}, cc_opts};
1003 }
1004
1005 /* Completion for the "condition" command.  */
1006
1007 static void
1008 condition_completer (struct cmd_list_element *cmd,
1009                      completion_tracker &tracker,
1010                      const char *text, const char * /*word*/)
1011 {
1012   bool has_no_arguments = (*text == '\0');
1013   condition_command_opts cc_opts;
1014   const auto group = make_condition_command_options_def_group (&cc_opts);
1015   if (gdb::option::complete_options
1016       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1017     return;
1018
1019   text = skip_spaces (text);
1020   const char *space = skip_to_space (text);
1021   if (*space == '\0')
1022     {
1023       int len;
1024       struct breakpoint *b;
1025
1026       if (text[0] == '$')
1027         {
1028           tracker.advance_custom_word_point_by (1);
1029           /* We don't support completion of history indices.  */
1030           if (!isdigit (text[1]))
1031             complete_internalvar (tracker, &text[1]);
1032           return;
1033         }
1034
1035       /* Suggest the "-force" flag if no arguments are given.  If
1036          arguments were passed, they either already include the flag,
1037          or we are beyond the point of suggesting it because it's
1038          positionally the first argument.  */
1039       if (has_no_arguments)
1040         gdb::option::complete_on_all_options (tracker, group);
1041
1042       /* We're completing the breakpoint number.  */
1043       len = strlen (text);
1044
1045       ALL_BREAKPOINTS (b)
1046         {
1047           char number[50];
1048
1049           xsnprintf (number, sizeof (number), "%d", b->number);
1050
1051           if (strncmp (number, text, len) == 0)
1052             tracker.add_completion (make_unique_xstrdup (number));
1053         }
1054
1055       return;
1056     }
1057
1058   /* We're completing the expression part.  Skip the breakpoint num.  */
1059   const char *exp_start = skip_spaces (space);
1060   tracker.advance_custom_word_point_by (exp_start - text);
1061   text = exp_start;
1062   const char *word = advance_to_expression_complete_word_point (tracker, text);
1063   expression_completer (cmd, tracker, text, word);
1064 }
1065
1066 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1067
1068 static void
1069 condition_command (const char *arg, int from_tty)
1070 {
1071   struct breakpoint *b;
1072   const char *p;
1073   int bnum;
1074
1075   if (arg == 0)
1076     error_no_arg (_("breakpoint number"));
1077
1078   p = arg;
1079
1080   /* Check if the "-force" flag was passed.  */
1081   condition_command_opts cc_opts;
1082   const auto group = make_condition_command_options_def_group (&cc_opts);
1083   gdb::option::process_options
1084     (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1085
1086   bnum = get_number (&p);
1087   if (bnum == 0)
1088     error (_("Bad breakpoint argument: '%s'"), arg);
1089
1090   ALL_BREAKPOINTS (b)
1091     if (b->number == bnum)
1092       {
1093         /* Check if this breakpoint has a "stop" method implemented in an
1094            extension language.  This method and conditions entered into GDB
1095            from the CLI are mutually exclusive.  */
1096         const struct extension_language_defn *extlang
1097           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1098
1099         if (extlang != NULL)
1100           {
1101             error (_("Only one stop condition allowed.  There is currently"
1102                      " a %s stop condition defined for this breakpoint."),
1103                    ext_lang_capitalized_name (extlang));
1104           }
1105         set_breakpoint_condition (b, p, from_tty, cc_opts.force_condition);
1106
1107         if (is_breakpoint (b))
1108           update_global_location_list (UGLL_MAY_INSERT);
1109
1110         return;
1111       }
1112
1113   error (_("No breakpoint number %d."), bnum);
1114 }
1115
1116 /* Check that COMMAND do not contain commands that are suitable
1117    only for tracepoints and not suitable for ordinary breakpoints.
1118    Throw if any such commands is found.  */
1119
1120 static void
1121 check_no_tracepoint_commands (struct command_line *commands)
1122 {
1123   struct command_line *c;
1124
1125   for (c = commands; c; c = c->next)
1126     {
1127       if (c->control_type == while_stepping_control)
1128         error (_("The 'while-stepping' command can "
1129                  "only be used for tracepoints"));
1130
1131       check_no_tracepoint_commands (c->body_list_0.get ());
1132       check_no_tracepoint_commands (c->body_list_1.get ());
1133
1134       /* Not that command parsing removes leading whitespace and comment
1135          lines and also empty lines.  So, we only need to check for
1136          command directly.  */
1137       if (strstr (c->line, "collect ") == c->line)
1138         error (_("The 'collect' command can only be used for tracepoints"));
1139
1140       if (strstr (c->line, "teval ") == c->line)
1141         error (_("The 'teval' command can only be used for tracepoints"));
1142     }
1143 }
1144
1145 struct longjmp_breakpoint : public breakpoint
1146 {
1147   ~longjmp_breakpoint () override;
1148 };
1149
1150 /* Encapsulate tests for different types of tracepoints.  */
1151
1152 static bool
1153 is_tracepoint_type (bptype type)
1154 {
1155   return (type == bp_tracepoint
1156           || type == bp_fast_tracepoint
1157           || type == bp_static_tracepoint);
1158 }
1159
1160 static bool
1161 is_longjmp_type (bptype type)
1162 {
1163   return type == bp_longjmp || type == bp_exception;
1164 }
1165
1166 /* See breakpoint.h.  */
1167
1168 bool
1169 is_tracepoint (const struct breakpoint *b)
1170 {
1171   return is_tracepoint_type (b->type);
1172 }
1173
1174 /* Factory function to create an appropriate instance of breakpoint given
1175    TYPE.  */
1176
1177 static std::unique_ptr<breakpoint>
1178 new_breakpoint_from_type (bptype type)
1179 {
1180   breakpoint *b;
1181
1182   if (is_tracepoint_type (type))
1183     b = new tracepoint ();
1184   else if (is_longjmp_type (type))
1185     b = new longjmp_breakpoint ();
1186   else
1187     b = new breakpoint ();
1188
1189   return std::unique_ptr<breakpoint> (b);
1190 }
1191
1192 /* A helper function that validates that COMMANDS are valid for a
1193    breakpoint.  This function will throw an exception if a problem is
1194    found.  */
1195
1196 static void
1197 validate_commands_for_breakpoint (struct breakpoint *b,
1198                                   struct command_line *commands)
1199 {
1200   if (is_tracepoint (b))
1201     {
1202       struct tracepoint *t = (struct tracepoint *) b;
1203       struct command_line *c;
1204       struct command_line *while_stepping = 0;
1205
1206       /* Reset the while-stepping step count.  The previous commands
1207          might have included a while-stepping action, while the new
1208          ones might not.  */
1209       t->step_count = 0;
1210
1211       /* We need to verify that each top-level element of commands is
1212          valid for tracepoints, that there's at most one
1213          while-stepping element, and that the while-stepping's body
1214          has valid tracing commands excluding nested while-stepping.
1215          We also need to validate the tracepoint action line in the
1216          context of the tracepoint --- validate_actionline actually
1217          has side effects, like setting the tracepoint's
1218          while-stepping STEP_COUNT, in addition to checking if the
1219          collect/teval actions parse and make sense in the
1220          tracepoint's context.  */
1221       for (c = commands; c; c = c->next)
1222         {
1223           if (c->control_type == while_stepping_control)
1224             {
1225               if (b->type == bp_fast_tracepoint)
1226                 error (_("The 'while-stepping' command "
1227                          "cannot be used for fast tracepoint"));
1228               else if (b->type == bp_static_tracepoint)
1229                 error (_("The 'while-stepping' command "
1230                          "cannot be used for static tracepoint"));
1231
1232               if (while_stepping)
1233                 error (_("The 'while-stepping' command "
1234                          "can be used only once"));
1235               else
1236                 while_stepping = c;
1237             }
1238
1239           validate_actionline (c->line, b);
1240         }
1241       if (while_stepping)
1242         {
1243           struct command_line *c2;
1244
1245           gdb_assert (while_stepping->body_list_1 == nullptr);
1246           c2 = while_stepping->body_list_0.get ();
1247           for (; c2; c2 = c2->next)
1248             {
1249               if (c2->control_type == while_stepping_control)
1250                 error (_("The 'while-stepping' command cannot be nested"));
1251             }
1252         }
1253     }
1254   else
1255     {
1256       check_no_tracepoint_commands (commands);
1257     }
1258 }
1259
1260 /* Return a vector of all the static tracepoints set at ADDR.  The
1261    caller is responsible for releasing the vector.  */
1262
1263 std::vector<breakpoint *>
1264 static_tracepoints_here (CORE_ADDR addr)
1265 {
1266   struct breakpoint *b;
1267   std::vector<breakpoint *> found;
1268   struct bp_location *loc;
1269
1270   ALL_BREAKPOINTS (b)
1271     if (b->type == bp_static_tracepoint)
1272       {
1273         for (loc = b->loc; loc; loc = loc->next)
1274           if (loc->address == addr)
1275             found.push_back (b);
1276       }
1277
1278   return found;
1279 }
1280
1281 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1282    validate that only allowed commands are included.  */
1283
1284 void
1285 breakpoint_set_commands (struct breakpoint *b, 
1286                          counted_command_line &&commands)
1287 {
1288   validate_commands_for_breakpoint (b, commands.get ());
1289
1290   b->commands = std::move (commands);
1291   gdb::observers::breakpoint_modified.notify (b);
1292 }
1293
1294 /* Set the internal `silent' flag on the breakpoint.  Note that this
1295    is not the same as the "silent" that may appear in the breakpoint's
1296    commands.  */
1297
1298 void
1299 breakpoint_set_silent (struct breakpoint *b, int silent)
1300 {
1301   int old_silent = b->silent;
1302
1303   b->silent = silent;
1304   if (old_silent != silent)
1305     gdb::observers::breakpoint_modified.notify (b);
1306 }
1307
1308 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1309    breakpoint work for any thread.  */
1310
1311 void
1312 breakpoint_set_thread (struct breakpoint *b, int thread)
1313 {
1314   int old_thread = b->thread;
1315
1316   b->thread = thread;
1317   if (old_thread != thread)
1318     gdb::observers::breakpoint_modified.notify (b);
1319 }
1320
1321 /* Set the task for this breakpoint.  If TASK is 0, make the
1322    breakpoint work for any task.  */
1323
1324 void
1325 breakpoint_set_task (struct breakpoint *b, int task)
1326 {
1327   int old_task = b->task;
1328
1329   b->task = task;
1330   if (old_task != task)
1331     gdb::observers::breakpoint_modified.notify (b);
1332 }
1333
1334 static void
1335 commands_command_1 (const char *arg, int from_tty,
1336                     struct command_line *control)
1337 {
1338   counted_command_line cmd;
1339   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1340      NULL after the call to read_command_lines if the user provides an empty
1341      list of command by just typing "end".  */
1342   bool cmd_read = false;
1343
1344   std::string new_arg;
1345
1346   if (arg == NULL || !*arg)
1347     {
1348       /* Argument not explicitly given.  Synthesize it.  */
1349       if (breakpoint_count - prev_breakpoint_count > 1)
1350         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1351                                  breakpoint_count);
1352       else if (breakpoint_count > 0)
1353         new_arg = string_printf ("%d", breakpoint_count);
1354     }
1355   else
1356     {
1357       /* Create a copy of ARG.  This is needed because the "commands"
1358          command may be coming from a script.  In that case, the read
1359          line buffer is going to be overwritten in the lambda of
1360          'map_breakpoint_numbers' below when reading the next line
1361          before we are are done parsing the breakpoint numbers.  */
1362       new_arg = arg;
1363     }
1364   arg = new_arg.c_str ();
1365
1366   map_breakpoint_numbers
1367     (arg, [&] (breakpoint *b)
1368      {
1369        if (!cmd_read)
1370          {
1371            gdb_assert (cmd == NULL);
1372            if (control != NULL)
1373              cmd = control->body_list_0;
1374            else
1375              {
1376                std::string str
1377                  = string_printf (_("Type commands for breakpoint(s) "
1378                                     "%s, one per line."),
1379                                   arg);
1380
1381                auto do_validate = [=] (const char *line)
1382                                   {
1383                                     validate_actionline (line, b);
1384                                   };
1385                gdb::function_view<void (const char *)> validator;
1386                if (is_tracepoint (b))
1387                  validator = do_validate;
1388
1389                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1390              }
1391            cmd_read = true;
1392          }
1393
1394        /* If a breakpoint was on the list more than once, we don't need to
1395           do anything.  */
1396        if (b->commands != cmd)
1397          {
1398            validate_commands_for_breakpoint (b, cmd.get ());
1399            b->commands = cmd;
1400            gdb::observers::breakpoint_modified.notify (b);
1401          }
1402      });
1403 }
1404
1405 static void
1406 commands_command (const char *arg, int from_tty)
1407 {
1408   commands_command_1 (arg, from_tty, NULL);
1409 }
1410
1411 /* Like commands_command, but instead of reading the commands from
1412    input stream, takes them from an already parsed command structure.
1413
1414    This is used by cli-script.c to DTRT with breakpoint commands
1415    that are part of if and while bodies.  */
1416 enum command_control_type
1417 commands_from_control_command (const char *arg, struct command_line *cmd)
1418 {
1419   commands_command_1 (arg, 0, cmd);
1420   return simple_control;
1421 }
1422
1423 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1424
1425 static int
1426 bp_location_has_shadow (struct bp_location *bl)
1427 {
1428   if (bl->loc_type != bp_loc_software_breakpoint)
1429     return 0;
1430   if (!bl->inserted)
1431     return 0;
1432   if (bl->target_info.shadow_len == 0)
1433     /* BL isn't valid, or doesn't shadow memory.  */
1434     return 0;
1435   return 1;
1436 }
1437
1438 /* Update BUF, which is LEN bytes read from the target address
1439    MEMADDR, by replacing a memory breakpoint with its shadowed
1440    contents.
1441
1442    If READBUF is not NULL, this buffer must not overlap with the of
1443    the breakpoint location's shadow_contents buffer.  Otherwise, a
1444    failed assertion internal error will be raised.  */
1445
1446 static void
1447 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1448                             const gdb_byte *writebuf_org,
1449                             ULONGEST memaddr, LONGEST len,
1450                             struct bp_target_info *target_info,
1451                             struct gdbarch *gdbarch)
1452 {
1453   /* Now do full processing of the found relevant range of elements.  */
1454   CORE_ADDR bp_addr = 0;
1455   int bp_size = 0;
1456   int bptoffset = 0;
1457
1458   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1459                                  current_program_space->aspace, 0))
1460     {
1461       /* The breakpoint is inserted in a different address space.  */
1462       return;
1463     }
1464
1465   /* Addresses and length of the part of the breakpoint that
1466      we need to copy.  */
1467   bp_addr = target_info->placed_address;
1468   bp_size = target_info->shadow_len;
1469
1470   if (bp_addr + bp_size <= memaddr)
1471     {
1472       /* The breakpoint is entirely before the chunk of memory we are
1473          reading.  */
1474       return;
1475     }
1476
1477   if (bp_addr >= memaddr + len)
1478     {
1479       /* The breakpoint is entirely after the chunk of memory we are
1480          reading.  */
1481       return;
1482     }
1483
1484   /* Offset within shadow_contents.  */
1485   if (bp_addr < memaddr)
1486     {
1487       /* Only copy the second part of the breakpoint.  */
1488       bp_size -= memaddr - bp_addr;
1489       bptoffset = memaddr - bp_addr;
1490       bp_addr = memaddr;
1491     }
1492
1493   if (bp_addr + bp_size > memaddr + len)
1494     {
1495       /* Only copy the first part of the breakpoint.  */
1496       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1497     }
1498
1499   if (readbuf != NULL)
1500     {
1501       /* Verify that the readbuf buffer does not overlap with the
1502          shadow_contents buffer.  */
1503       gdb_assert (target_info->shadow_contents >= readbuf + len
1504                   || readbuf >= (target_info->shadow_contents
1505                                  + target_info->shadow_len));
1506
1507       /* Update the read buffer with this inserted breakpoint's
1508          shadow.  */
1509       memcpy (readbuf + bp_addr - memaddr,
1510               target_info->shadow_contents + bptoffset, bp_size);
1511     }
1512   else
1513     {
1514       const unsigned char *bp;
1515       CORE_ADDR addr = target_info->reqstd_address;
1516       int placed_size;
1517
1518       /* Update the shadow with what we want to write to memory.  */
1519       memcpy (target_info->shadow_contents + bptoffset,
1520               writebuf_org + bp_addr - memaddr, bp_size);
1521
1522       /* Determine appropriate breakpoint contents and size for this
1523          address.  */
1524       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1525
1526       /* Update the final write buffer with this inserted
1527          breakpoint's INSN.  */
1528       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1529     }
1530 }
1531
1532 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1533    by replacing any memory breakpoints with their shadowed contents.
1534
1535    If READBUF is not NULL, this buffer must not overlap with any of
1536    the breakpoint location's shadow_contents buffers.  Otherwise,
1537    a failed assertion internal error will be raised.
1538
1539    The range of shadowed area by each bp_location is:
1540      bl->address - bp_locations_placed_address_before_address_max
1541      up to bl->address + bp_locations_shadow_len_after_address_max
1542    The range we were requested to resolve shadows for is:
1543      memaddr ... memaddr + len
1544    Thus the safe cutoff boundaries for performance optimization are
1545      memaddr + len <= (bl->address
1546                        - bp_locations_placed_address_before_address_max)
1547    and:
1548      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1549
1550 void
1551 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1552                         const gdb_byte *writebuf_org,
1553                         ULONGEST memaddr, LONGEST len)
1554 {
1555   /* Left boundary, right boundary and median element of our binary
1556      search.  */
1557   unsigned bc_l, bc_r, bc;
1558
1559   /* Find BC_L which is a leftmost element which may affect BUF
1560      content.  It is safe to report lower value but a failure to
1561      report higher one.  */
1562
1563   bc_l = 0;
1564   bc_r = bp_locations_count;
1565   while (bc_l + 1 < bc_r)
1566     {
1567       struct bp_location *bl;
1568
1569       bc = (bc_l + bc_r) / 2;
1570       bl = bp_locations[bc];
1571
1572       /* Check first BL->ADDRESS will not overflow due to the added
1573          constant.  Then advance the left boundary only if we are sure
1574          the BC element can in no way affect the BUF content (MEMADDR
1575          to MEMADDR + LEN range).
1576
1577          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1578          offset so that we cannot miss a breakpoint with its shadow
1579          range tail still reaching MEMADDR.  */
1580
1581       if ((bl->address + bp_locations_shadow_len_after_address_max
1582            >= bl->address)
1583           && (bl->address + bp_locations_shadow_len_after_address_max
1584               <= memaddr))
1585         bc_l = bc;
1586       else
1587         bc_r = bc;
1588     }
1589
1590   /* Due to the binary search above, we need to make sure we pick the
1591      first location that's at BC_L's address.  E.g., if there are
1592      multiple locations at the same address, BC_L may end up pointing
1593      at a duplicate location, and miss the "master"/"inserted"
1594      location.  Say, given locations L1, L2 and L3 at addresses A and
1595      B:
1596
1597       L1@A, L2@A, L3@B, ...
1598
1599      BC_L could end up pointing at location L2, while the "master"
1600      location could be L1.  Since the `loc->inserted' flag is only set
1601      on "master" locations, we'd forget to restore the shadow of L1
1602      and L2.  */
1603   while (bc_l > 0
1604          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1605     bc_l--;
1606
1607   /* Now do full processing of the found relevant range of elements.  */
1608
1609   for (bc = bc_l; bc < bp_locations_count; bc++)
1610   {
1611     struct bp_location *bl = bp_locations[bc];
1612
1613     /* bp_location array has BL->OWNER always non-NULL.  */
1614     if (bl->owner->type == bp_none)
1615       warning (_("reading through apparently deleted breakpoint #%d?"),
1616                bl->owner->number);
1617
1618     /* Performance optimization: any further element can no longer affect BUF
1619        content.  */
1620
1621     if (bl->address >= bp_locations_placed_address_before_address_max
1622         && memaddr + len <= (bl->address
1623                              - bp_locations_placed_address_before_address_max))
1624       break;
1625
1626     if (!bp_location_has_shadow (bl))
1627       continue;
1628
1629     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1630                                 memaddr, len, &bl->target_info, bl->gdbarch);
1631   }
1632 }
1633
1634 /* See breakpoint.h.  */
1635
1636 bool
1637 is_breakpoint (const struct breakpoint *bpt)
1638 {
1639   return (bpt->type == bp_breakpoint
1640           || bpt->type == bp_hardware_breakpoint
1641           || bpt->type == bp_dprintf);
1642 }
1643
1644 /* Return true if BPT is of any hardware watchpoint kind.  */
1645
1646 static bool
1647 is_hardware_watchpoint (const struct breakpoint *bpt)
1648 {
1649   return (bpt->type == bp_hardware_watchpoint
1650           || bpt->type == bp_read_watchpoint
1651           || bpt->type == bp_access_watchpoint);
1652 }
1653
1654 /* See breakpoint.h.  */
1655
1656 bool
1657 is_watchpoint (const struct breakpoint *bpt)
1658 {
1659   return (is_hardware_watchpoint (bpt)
1660           || bpt->type == bp_watchpoint);
1661 }
1662
1663 /* Returns true if the current thread and its running state are safe
1664    to evaluate or update watchpoint B.  Watchpoints on local
1665    expressions need to be evaluated in the context of the thread that
1666    was current when the watchpoint was created, and, that thread needs
1667    to be stopped to be able to select the correct frame context.
1668    Watchpoints on global expressions can be evaluated on any thread,
1669    and in any state.  It is presently left to the target allowing
1670    memory accesses when threads are running.  */
1671
1672 static int
1673 watchpoint_in_thread_scope (struct watchpoint *b)
1674 {
1675   return (b->pspace == current_program_space
1676           && (b->watchpoint_thread == null_ptid
1677               || (inferior_ptid == b->watchpoint_thread
1678                   && !inferior_thread ()->executing)));
1679 }
1680
1681 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1682    associated bp_watchpoint_scope breakpoint.  */
1683
1684 static void
1685 watchpoint_del_at_next_stop (struct watchpoint *w)
1686 {
1687   if (w->related_breakpoint != w)
1688     {
1689       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1690       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1691       w->related_breakpoint->disposition = disp_del_at_next_stop;
1692       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1693       w->related_breakpoint = w;
1694     }
1695   w->disposition = disp_del_at_next_stop;
1696 }
1697
1698 /* Extract a bitfield value from value VAL using the bit parameters contained in
1699    watchpoint W.  */
1700
1701 static struct value *
1702 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1703 {
1704   struct value *bit_val;
1705
1706   if (val == NULL)
1707     return NULL;
1708
1709   bit_val = allocate_value (value_type (val));
1710
1711   unpack_value_bitfield (bit_val,
1712                          w->val_bitpos,
1713                          w->val_bitsize,
1714                          value_contents_for_printing (val),
1715                          value_offset (val),
1716                          val);
1717
1718   return bit_val;
1719 }
1720
1721 /* Allocate a dummy location and add it to B, which must be a software
1722    watchpoint.  This is required because even if a software watchpoint
1723    is not watching any memory, bpstat_stop_status requires a location
1724    to be able to report stops.  */
1725
1726 static void
1727 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1728                                             struct program_space *pspace)
1729 {
1730   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1731
1732   b->loc = allocate_bp_location (b);
1733   b->loc->pspace = pspace;
1734   b->loc->address = -1;
1735   b->loc->length = -1;
1736 }
1737
1738 /* Returns true if B is a software watchpoint that is not watching any
1739    memory (e.g., "watch $pc").  */
1740
1741 static bool
1742 is_no_memory_software_watchpoint (struct breakpoint *b)
1743 {
1744   return (b->type == bp_watchpoint
1745           && b->loc != NULL
1746           && b->loc->next == NULL
1747           && b->loc->address == -1
1748           && b->loc->length == -1);
1749 }
1750
1751 /* Assuming that B is a watchpoint:
1752    - Reparse watchpoint expression, if REPARSE is non-zero
1753    - Evaluate expression and store the result in B->val
1754    - Evaluate the condition if there is one, and store the result
1755      in b->loc->cond.
1756    - Update the list of values that must be watched in B->loc.
1757
1758    If the watchpoint disposition is disp_del_at_next_stop, then do
1759    nothing.  If this is local watchpoint that is out of scope, delete
1760    it.
1761
1762    Even with `set breakpoint always-inserted on' the watchpoints are
1763    removed + inserted on each stop here.  Normal breakpoints must
1764    never be removed because they might be missed by a running thread
1765    when debugging in non-stop mode.  On the other hand, hardware
1766    watchpoints (is_hardware_watchpoint; processed here) are specific
1767    to each LWP since they are stored in each LWP's hardware debug
1768    registers.  Therefore, such LWP must be stopped first in order to
1769    be able to modify its hardware watchpoints.
1770
1771    Hardware watchpoints must be reset exactly once after being
1772    presented to the user.  It cannot be done sooner, because it would
1773    reset the data used to present the watchpoint hit to the user.  And
1774    it must not be done later because it could display the same single
1775    watchpoint hit during multiple GDB stops.  Note that the latter is
1776    relevant only to the hardware watchpoint types bp_read_watchpoint
1777    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1778    not user-visible - its hit is suppressed if the memory content has
1779    not changed.
1780
1781    The following constraints influence the location where we can reset
1782    hardware watchpoints:
1783
1784    * target_stopped_by_watchpoint and target_stopped_data_address are
1785      called several times when GDB stops.
1786
1787    [linux] 
1788    * Multiple hardware watchpoints can be hit at the same time,
1789      causing GDB to stop.  GDB only presents one hardware watchpoint
1790      hit at a time as the reason for stopping, and all the other hits
1791      are presented later, one after the other, each time the user
1792      requests the execution to be resumed.  Execution is not resumed
1793      for the threads still having pending hit event stored in
1794      LWP_INFO->STATUS.  While the watchpoint is already removed from
1795      the inferior on the first stop the thread hit event is kept being
1796      reported from its cached value by linux_nat_stopped_data_address
1797      until the real thread resume happens after the watchpoint gets
1798      presented and thus its LWP_INFO->STATUS gets reset.
1799
1800    Therefore the hardware watchpoint hit can get safely reset on the
1801    watchpoint removal from inferior.  */
1802
1803 static void
1804 update_watchpoint (struct watchpoint *b, int reparse)
1805 {
1806   int within_current_scope;
1807   struct frame_id saved_frame_id;
1808   int frame_saved;
1809
1810   /* If this is a local watchpoint, we only want to check if the
1811      watchpoint frame is in scope if the current thread is the thread
1812      that was used to create the watchpoint.  */
1813   if (!watchpoint_in_thread_scope (b))
1814     return;
1815
1816   if (b->disposition == disp_del_at_next_stop)
1817     return;
1818  
1819   frame_saved = 0;
1820
1821   /* Determine if the watchpoint is within scope.  */
1822   if (b->exp_valid_block == NULL)
1823     within_current_scope = 1;
1824   else
1825     {
1826       struct frame_info *fi = get_current_frame ();
1827       struct gdbarch *frame_arch = get_frame_arch (fi);
1828       CORE_ADDR frame_pc = get_frame_pc (fi);
1829
1830       /* If we're at a point where the stack has been destroyed
1831          (e.g. in a function epilogue), unwinding may not work
1832          properly. Do not attempt to recreate locations at this
1833          point.  See similar comments in watchpoint_check.  */
1834       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1835         return;
1836
1837       /* Save the current frame's ID so we can restore it after
1838          evaluating the watchpoint expression on its own frame.  */
1839       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1840          took a frame parameter, so that we didn't have to change the
1841          selected frame.  */
1842       frame_saved = 1;
1843       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1844
1845       fi = frame_find_by_id (b->watchpoint_frame);
1846       within_current_scope = (fi != NULL);
1847       if (within_current_scope)
1848         select_frame (fi);
1849     }
1850
1851   /* We don't free locations.  They are stored in the bp_location array
1852      and update_global_location_list will eventually delete them and
1853      remove breakpoints if needed.  */
1854   b->loc = NULL;
1855
1856   if (within_current_scope && reparse)
1857     {
1858       const char *s;
1859
1860       b->exp.reset ();
1861       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1862       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1863       /* If the meaning of expression itself changed, the old value is
1864          no longer relevant.  We don't want to report a watchpoint hit
1865          to the user when the old value and the new value may actually
1866          be completely different objects.  */
1867       b->val = NULL;
1868       b->val_valid = false;
1869
1870       /* Note that unlike with breakpoints, the watchpoint's condition
1871          expression is stored in the breakpoint object, not in the
1872          locations (re)created below.  */
1873       if (b->cond_string != NULL)
1874         {
1875           b->cond_exp.reset ();
1876
1877           s = b->cond_string;
1878           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1879         }
1880     }
1881
1882   /* If we failed to parse the expression, for example because
1883      it refers to a global variable in a not-yet-loaded shared library,
1884      don't try to insert watchpoint.  We don't automatically delete
1885      such watchpoint, though, since failure to parse expression
1886      is different from out-of-scope watchpoint.  */
1887   if (!target_has_execution ())
1888     {
1889       /* Without execution, memory can't change.  No use to try and
1890          set watchpoint locations.  The watchpoint will be reset when
1891          the target gains execution, through breakpoint_re_set.  */
1892       if (!can_use_hw_watchpoints)
1893         {
1894           if (b->ops->works_in_software_mode (b))
1895             b->type = bp_watchpoint;
1896           else
1897             error (_("Can't set read/access watchpoint when "
1898                      "hardware watchpoints are disabled."));
1899         }
1900     }
1901   else if (within_current_scope && b->exp)
1902     {
1903       int pc = 0;
1904       std::vector<value_ref_ptr> val_chain;
1905       struct value *v, *result;
1906       struct program_space *frame_pspace;
1907
1908       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, false);
1909
1910       /* Avoid setting b->val if it's already set.  The meaning of
1911          b->val is 'the last value' user saw, and we should update
1912          it only if we reported that last value to user.  As it
1913          happens, the code that reports it updates b->val directly.
1914          We don't keep track of the memory value for masked
1915          watchpoints.  */
1916       if (!b->val_valid && !is_masked_watchpoint (b))
1917         {
1918           if (b->val_bitsize != 0)
1919             v = extract_bitfield_from_watchpoint_value (b, v);
1920           b->val = release_value (v);
1921           b->val_valid = true;
1922         }
1923
1924       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1925
1926       /* Look at each value on the value chain.  */
1927       gdb_assert (!val_chain.empty ());
1928       for (const value_ref_ptr &iter : val_chain)
1929         {
1930           v = iter.get ();
1931
1932           /* If it's a memory location, and GDB actually needed
1933              its contents to evaluate the expression, then we
1934              must watch it.  If the first value returned is
1935              still lazy, that means an error occurred reading it;
1936              watch it anyway in case it becomes readable.  */
1937           if (VALUE_LVAL (v) == lval_memory
1938               && (v == val_chain[0] || ! value_lazy (v)))
1939             {
1940               struct type *vtype = check_typedef (value_type (v));
1941
1942               /* We only watch structs and arrays if user asked
1943                  for it explicitly, never if they just happen to
1944                  appear in the middle of some value chain.  */
1945               if (v == result
1946                   || (vtype->code () != TYPE_CODE_STRUCT
1947                       && vtype->code () != TYPE_CODE_ARRAY))
1948                 {
1949                   CORE_ADDR addr;
1950                   enum target_hw_bp_type type;
1951                   struct bp_location *loc, **tmp;
1952                   int bitpos = 0, bitsize = 0;
1953
1954                   if (value_bitsize (v) != 0)
1955                     {
1956                       /* Extract the bit parameters out from the bitfield
1957                          sub-expression.  */
1958                       bitpos = value_bitpos (v);
1959                       bitsize = value_bitsize (v);
1960                     }
1961                   else if (v == result && b->val_bitsize != 0)
1962                     {
1963                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1964                         lvalue whose bit parameters are saved in the fields
1965                         VAL_BITPOS and VAL_BITSIZE.  */
1966                       bitpos = b->val_bitpos;
1967                       bitsize = b->val_bitsize;
1968                     }
1969
1970                   addr = value_address (v);
1971                   if (bitsize != 0)
1972                     {
1973                       /* Skip the bytes that don't contain the bitfield.  */
1974                       addr += bitpos / 8;
1975                     }
1976
1977                   type = hw_write;
1978                   if (b->type == bp_read_watchpoint)
1979                     type = hw_read;
1980                   else if (b->type == bp_access_watchpoint)
1981                     type = hw_access;
1982
1983                   loc = allocate_bp_location (b);
1984                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1985                     ;
1986                   *tmp = loc;
1987                   loc->gdbarch = get_type_arch (value_type (v));
1988
1989                   loc->pspace = frame_pspace;
1990                   loc->address = address_significant (loc->gdbarch, addr);
1991
1992                   if (bitsize != 0)
1993                     {
1994                       /* Just cover the bytes that make up the bitfield.  */
1995                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1996                     }
1997                   else
1998                     loc->length = TYPE_LENGTH (value_type (v));
1999
2000                   loc->watchpoint_type = type;
2001                 }
2002             }
2003         }
2004
2005       /* Change the type of breakpoint between hardware assisted or
2006          an ordinary watchpoint depending on the hardware support
2007          and free hardware slots.  REPARSE is set when the inferior
2008          is started.  */
2009       if (reparse)
2010         {
2011           int reg_cnt;
2012           enum bp_loc_type loc_type;
2013           struct bp_location *bl;
2014
2015           reg_cnt = can_use_hardware_watchpoint (val_chain);
2016
2017           if (reg_cnt)
2018             {
2019               int i, target_resources_ok, other_type_used;
2020               enum bptype type;
2021
2022               /* Use an exact watchpoint when there's only one memory region to be
2023                  watched, and only one debug register is needed to watch it.  */
2024               b->exact = target_exact_watchpoints && reg_cnt == 1;
2025
2026               /* We need to determine how many resources are already
2027                  used for all other hardware watchpoints plus this one
2028                  to see if we still have enough resources to also fit
2029                  this watchpoint in as well.  */
2030
2031               /* If this is a software watchpoint, we try to turn it
2032                  to a hardware one -- count resources as if B was of
2033                  hardware watchpoint type.  */
2034               type = b->type;
2035               if (type == bp_watchpoint)
2036                 type = bp_hardware_watchpoint;
2037
2038               /* This watchpoint may or may not have been placed on
2039                  the list yet at this point (it won't be in the list
2040                  if we're trying to create it for the first time,
2041                  through watch_command), so always account for it
2042                  manually.  */
2043
2044               /* Count resources used by all watchpoints except B.  */
2045               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2046
2047               /* Add in the resources needed for B.  */
2048               i += hw_watchpoint_use_count (b);
2049
2050               target_resources_ok
2051                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2052               if (target_resources_ok <= 0)
2053                 {
2054                   int sw_mode = b->ops->works_in_software_mode (b);
2055
2056                   if (target_resources_ok == 0 && !sw_mode)
2057                     error (_("Target does not support this type of "
2058                              "hardware watchpoint."));
2059                   else if (target_resources_ok < 0 && !sw_mode)
2060                     error (_("There are not enough available hardware "
2061                              "resources for this watchpoint."));
2062
2063                   /* Downgrade to software watchpoint.  */
2064                   b->type = bp_watchpoint;
2065                 }
2066               else
2067                 {
2068                   /* If this was a software watchpoint, we've just
2069                      found we have enough resources to turn it to a
2070                      hardware watchpoint.  Otherwise, this is a
2071                      nop.  */
2072                   b->type = type;
2073                 }
2074             }
2075           else if (!b->ops->works_in_software_mode (b))
2076             {
2077               if (!can_use_hw_watchpoints)
2078                 error (_("Can't set read/access watchpoint when "
2079                          "hardware watchpoints are disabled."));
2080               else
2081                 error (_("Expression cannot be implemented with "
2082                          "read/access watchpoint."));
2083             }
2084           else
2085             b->type = bp_watchpoint;
2086
2087           loc_type = (b->type == bp_watchpoint? bp_loc_other
2088                       : bp_loc_hardware_watchpoint);
2089           for (bl = b->loc; bl; bl = bl->next)
2090             bl->loc_type = loc_type;
2091         }
2092
2093       /* If a software watchpoint is not watching any memory, then the
2094          above left it without any location set up.  But,
2095          bpstat_stop_status requires a location to be able to report
2096          stops, so make sure there's at least a dummy one.  */
2097       if (b->type == bp_watchpoint && b->loc == NULL)
2098         software_watchpoint_add_no_memory_location (b, frame_pspace);
2099     }
2100   else if (!within_current_scope)
2101     {
2102       printf_filtered (_("\
2103 Watchpoint %d deleted because the program has left the block\n\
2104 in which its expression is valid.\n"),
2105                        b->number);
2106       watchpoint_del_at_next_stop (b);
2107     }
2108
2109   /* Restore the selected frame.  */
2110   if (frame_saved)
2111     select_frame (frame_find_by_id (saved_frame_id));
2112 }
2113
2114
2115 /* Returns 1 iff breakpoint location should be
2116    inserted in the inferior.  We don't differentiate the type of BL's owner
2117    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2118    breakpoint_ops is not defined, because in insert_bp_location,
2119    tracepoint's insert_location will not be called.  */
2120 static int
2121 should_be_inserted (struct bp_location *bl)
2122 {
2123   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2124     return 0;
2125
2126   if (bl->owner->disposition == disp_del_at_next_stop)
2127     return 0;
2128
2129   if (!bl->enabled || bl->disabled_by_cond
2130       || bl->shlib_disabled || bl->duplicate)
2131     return 0;
2132
2133   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2134     return 0;
2135
2136   /* This is set for example, when we're attached to the parent of a
2137      vfork, and have detached from the child.  The child is running
2138      free, and we expect it to do an exec or exit, at which point the
2139      OS makes the parent schedulable again (and the target reports
2140      that the vfork is done).  Until the child is done with the shared
2141      memory region, do not insert breakpoints in the parent, otherwise
2142      the child could still trip on the parent's breakpoints.  Since
2143      the parent is blocked anyway, it won't miss any breakpoint.  */
2144   if (bl->pspace->breakpoints_not_allowed)
2145     return 0;
2146
2147   /* Don't insert a breakpoint if we're trying to step past its
2148      location, except if the breakpoint is a single-step breakpoint,
2149      and the breakpoint's thread is the thread which is stepping past
2150      a breakpoint.  */
2151   if ((bl->loc_type == bp_loc_software_breakpoint
2152        || bl->loc_type == bp_loc_hardware_breakpoint)
2153       && stepping_past_instruction_at (bl->pspace->aspace,
2154                                        bl->address)
2155       /* The single-step breakpoint may be inserted at the location
2156          we're trying to step if the instruction branches to itself.
2157          However, the instruction won't be executed at all and it may
2158          break the semantics of the instruction, for example, the
2159          instruction is a conditional branch or updates some flags.
2160          We can't fix it unless GDB is able to emulate the instruction
2161          or switch to displaced stepping.  */
2162       && !(bl->owner->type == bp_single_step
2163            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2164     {
2165       infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2166                            paddress (bl->gdbarch, bl->address));
2167       return 0;
2168     }
2169
2170   /* Don't insert watchpoints if we're trying to step past the
2171      instruction that triggered one.  */
2172   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2173       && stepping_past_nonsteppable_watchpoint ())
2174     {
2175       infrun_debug_printf ("stepping past non-steppable watchpoint. "
2176                            "skipping watchpoint at %s:%d\n",
2177                            paddress (bl->gdbarch, bl->address), bl->length);
2178       return 0;
2179     }
2180
2181   return 1;
2182 }
2183
2184 /* Same as should_be_inserted but does the check assuming
2185    that the location is not duplicated.  */
2186
2187 static int
2188 unduplicated_should_be_inserted (struct bp_location *bl)
2189 {
2190   int result;
2191   const int save_duplicate = bl->duplicate;
2192
2193   bl->duplicate = 0;
2194   result = should_be_inserted (bl);
2195   bl->duplicate = save_duplicate;
2196   return result;
2197 }
2198
2199 /* Parses a conditional described by an expression COND into an
2200    agent expression bytecode suitable for evaluation
2201    by the bytecode interpreter.  Return NULL if there was
2202    any error during parsing.  */
2203
2204 static agent_expr_up
2205 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2206 {
2207   if (cond == NULL)
2208     return NULL;
2209
2210   agent_expr_up aexpr;
2211
2212   /* We don't want to stop processing, so catch any errors
2213      that may show up.  */
2214   try
2215     {
2216       aexpr = gen_eval_for_expr (scope, cond);
2217     }
2218
2219   catch (const gdb_exception_error &ex)
2220     {
2221       /* If we got here, it means the condition could not be parsed to a valid
2222          bytecode expression and thus can't be evaluated on the target's side.
2223          It's no use iterating through the conditions.  */
2224     }
2225
2226   /* We have a valid agent expression.  */
2227   return aexpr;
2228 }
2229
2230 /* Based on location BL, create a list of breakpoint conditions to be
2231    passed on to the target.  If we have duplicated locations with different
2232    conditions, we will add such conditions to the list.  The idea is that the
2233    target will evaluate the list of conditions and will only notify GDB when
2234    one of them is true.  */
2235
2236 static void
2237 build_target_condition_list (struct bp_location *bl)
2238 {
2239   struct bp_location **locp = NULL, **loc2p;
2240   int null_condition_or_parse_error = 0;
2241   int modified = bl->needs_update;
2242   struct bp_location *loc;
2243
2244   /* Release conditions left over from a previous insert.  */
2245   bl->target_info.conditions.clear ();
2246
2247   /* This is only meaningful if the target is
2248      evaluating conditions and if the user has
2249      opted for condition evaluation on the target's
2250      side.  */
2251   if (gdb_evaluates_breakpoint_condition_p ()
2252       || !target_supports_evaluation_of_breakpoint_conditions ())
2253     return;
2254
2255   /* Do a first pass to check for locations with no assigned
2256      conditions or conditions that fail to parse to a valid agent
2257      expression bytecode.  If any of these happen, then it's no use to
2258      send conditions to the target since this location will always
2259      trigger and generate a response back to GDB.  Note we consider
2260      all locations at the same address irrespective of type, i.e.,
2261      even if the locations aren't considered duplicates (e.g.,
2262      software breakpoint and hardware breakpoint at the same
2263      address).  */
2264   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2265     {
2266       loc = (*loc2p);
2267       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2268         {
2269           if (modified)
2270             {
2271               /* Re-parse the conditions since something changed.  In that
2272                  case we already freed the condition bytecodes (see
2273                  force_breakpoint_reinsertion).  We just
2274                  need to parse the condition to bytecodes again.  */
2275               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2276                                                         loc->cond.get ());
2277             }
2278
2279           /* If we have a NULL bytecode expression, it means something
2280              went wrong or we have a null condition expression.  */
2281           if (!loc->cond_bytecode)
2282             {
2283               null_condition_or_parse_error = 1;
2284               break;
2285             }
2286         }
2287     }
2288
2289   /* If any of these happened, it means we will have to evaluate the conditions
2290      for the location's address on gdb's side.  It is no use keeping bytecodes
2291      for all the other duplicate locations, thus we free all of them here.
2292
2293      This is so we have a finer control over which locations' conditions are
2294      being evaluated by GDB or the remote stub.  */
2295   if (null_condition_or_parse_error)
2296     {
2297       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2298         {
2299           loc = (*loc2p);
2300           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2301             {
2302               /* Only go as far as the first NULL bytecode is
2303                  located.  */
2304               if (!loc->cond_bytecode)
2305                 return;
2306
2307               loc->cond_bytecode.reset ();
2308             }
2309         }
2310     }
2311
2312   /* No NULL conditions or failed bytecode generation.  Build a
2313      condition list for this location's address.  If we have software
2314      and hardware locations at the same address, they aren't
2315      considered duplicates, but we still marge all the conditions
2316      anyway, as it's simpler, and doesn't really make a practical
2317      difference.  */
2318   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2319     {
2320       loc = (*loc2p);
2321       if (loc->cond
2322           && is_breakpoint (loc->owner)
2323           && loc->pspace->num == bl->pspace->num
2324           && loc->owner->enable_state == bp_enabled
2325           && loc->enabled
2326           && !loc->disabled_by_cond)
2327         {
2328           /* Add the condition to the vector.  This will be used later
2329              to send the conditions to the target.  */
2330           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2331         }
2332     }
2333
2334   return;
2335 }
2336
2337 /* Parses a command described by string CMD into an agent expression
2338    bytecode suitable for evaluation by the bytecode interpreter.
2339    Return NULL if there was any error during parsing.  */
2340
2341 static agent_expr_up
2342 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2343 {
2344   const char *cmdrest;
2345   const char *format_start, *format_end;
2346   struct gdbarch *gdbarch = get_current_arch ();
2347
2348   if (cmd == NULL)
2349     return NULL;
2350
2351   cmdrest = cmd;
2352
2353   if (*cmdrest == ',')
2354     ++cmdrest;
2355   cmdrest = skip_spaces (cmdrest);
2356
2357   if (*cmdrest++ != '"')
2358     error (_("No format string following the location"));
2359
2360   format_start = cmdrest;
2361
2362   format_pieces fpieces (&cmdrest);
2363
2364   format_end = cmdrest;
2365
2366   if (*cmdrest++ != '"')
2367     error (_("Bad format string, non-terminated '\"'."));
2368   
2369   cmdrest = skip_spaces (cmdrest);
2370
2371   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2372     error (_("Invalid argument syntax"));
2373
2374   if (*cmdrest == ',')
2375     cmdrest++;
2376   cmdrest = skip_spaces (cmdrest);
2377
2378   /* For each argument, make an expression.  */
2379
2380   std::vector<struct expression *> argvec;
2381   while (*cmdrest != '\0')
2382     {
2383       const char *cmd1;
2384
2385       cmd1 = cmdrest;
2386       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2387       argvec.push_back (expr.release ());
2388       cmdrest = cmd1;
2389       if (*cmdrest == ',')
2390         ++cmdrest;
2391     }
2392
2393   agent_expr_up aexpr;
2394
2395   /* We don't want to stop processing, so catch any errors
2396      that may show up.  */
2397   try
2398     {
2399       aexpr = gen_printf (scope, gdbarch, 0, 0,
2400                           format_start, format_end - format_start,
2401                           argvec.size (), argvec.data ());
2402     }
2403   catch (const gdb_exception_error &ex)
2404     {
2405       /* If we got here, it means the command could not be parsed to a valid
2406          bytecode expression and thus can't be evaluated on the target's side.
2407          It's no use iterating through the other commands.  */
2408     }
2409
2410   /* We have a valid agent expression, return it.  */
2411   return aexpr;
2412 }
2413
2414 /* Based on location BL, create a list of breakpoint commands to be
2415    passed on to the target.  If we have duplicated locations with
2416    different commands, we will add any such to the list.  */
2417
2418 static void
2419 build_target_command_list (struct bp_location *bl)
2420 {
2421   struct bp_location **locp = NULL, **loc2p;
2422   int null_command_or_parse_error = 0;
2423   int modified = bl->needs_update;
2424   struct bp_location *loc;
2425
2426   /* Clear commands left over from a previous insert.  */
2427   bl->target_info.tcommands.clear ();
2428
2429   if (!target_can_run_breakpoint_commands ())
2430     return;
2431
2432   /* For now, limit to agent-style dprintf breakpoints.  */
2433   if (dprintf_style != dprintf_style_agent)
2434     return;
2435
2436   /* For now, if we have any location at the same address that isn't a
2437      dprintf, don't install the target-side commands, as that would
2438      make the breakpoint not be reported to the core, and we'd lose
2439      control.  */
2440   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2441     {
2442       loc = (*loc2p);
2443       if (is_breakpoint (loc->owner)
2444           && loc->pspace->num == bl->pspace->num
2445           && loc->owner->type != bp_dprintf)
2446         return;
2447     }
2448
2449   /* Do a first pass to check for locations with no assigned
2450      conditions or conditions that fail to parse to a valid agent expression
2451      bytecode.  If any of these happen, then it's no use to send conditions
2452      to the target since this location will always trigger and generate a
2453      response back to GDB.  */
2454   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2455     {
2456       loc = (*loc2p);
2457       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2458         {
2459           if (modified)
2460             {
2461               /* Re-parse the commands since something changed.  In that
2462                  case we already freed the command bytecodes (see
2463                  force_breakpoint_reinsertion).  We just
2464                  need to parse the command to bytecodes again.  */
2465               loc->cmd_bytecode
2466                 = parse_cmd_to_aexpr (bl->address,
2467                                       loc->owner->extra_string);
2468             }
2469
2470           /* If we have a NULL bytecode expression, it means something
2471              went wrong or we have a null command expression.  */
2472           if (!loc->cmd_bytecode)
2473             {
2474               null_command_or_parse_error = 1;
2475               break;
2476             }
2477         }
2478     }
2479
2480   /* If anything failed, then we're not doing target-side commands,
2481      and so clean up.  */
2482   if (null_command_or_parse_error)
2483     {
2484       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2485         {
2486           loc = (*loc2p);
2487           if (is_breakpoint (loc->owner)
2488               && loc->pspace->num == bl->pspace->num)
2489             {
2490               /* Only go as far as the first NULL bytecode is
2491                  located.  */
2492               if (loc->cmd_bytecode == NULL)
2493                 return;
2494
2495               loc->cmd_bytecode.reset ();
2496             }
2497         }
2498     }
2499
2500   /* No NULL commands or failed bytecode generation.  Build a command
2501      list for all duplicate locations at this location's address.
2502      Note that here we must care for whether the breakpoint location
2503      types are considered duplicates, otherwise, say, if we have a
2504      software and hardware location at the same address, the target
2505      could end up running the commands twice.  For the moment, we only
2506      support targets-side commands with dprintf, but it doesn't hurt
2507      to be pedantically correct in case that changes.  */
2508   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2509     {
2510       loc = (*loc2p);
2511       if (breakpoint_locations_match (bl, loc)
2512           && loc->owner->extra_string
2513           && is_breakpoint (loc->owner)
2514           && loc->pspace->num == bl->pspace->num
2515           && loc->owner->enable_state == bp_enabled
2516           && loc->enabled
2517           && !loc->disabled_by_cond)
2518         {
2519           /* Add the command to the vector.  This will be used later
2520              to send the commands to the target.  */
2521           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2522         }
2523     }
2524
2525   bl->target_info.persist = 0;
2526   /* Maybe flag this location as persistent.  */
2527   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2528     bl->target_info.persist = 1;
2529 }
2530
2531 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2532    of breakpoint according to ADDR except single-step breakpoint.
2533    Get the kind of single-step breakpoint according to the current
2534    registers state.  */
2535
2536 static int
2537 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2538 {
2539   if (bl->owner->type == bp_single_step)
2540     {
2541       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2542       struct regcache *regcache;
2543
2544       regcache = get_thread_regcache (thr);
2545
2546       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2547                                                          regcache, addr);
2548     }
2549   else
2550     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2551 }
2552
2553 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2554    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2555    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2556    Returns 0 for success, 1 if the bp_location type is not supported or
2557    -1 for failure.
2558
2559    NOTE drow/2003-09-09: This routine could be broken down to an
2560    object-style method for each breakpoint or catchpoint type.  */
2561 static int
2562 insert_bp_location (struct bp_location *bl,
2563                     struct ui_file *tmp_error_stream,
2564                     int *disabled_breaks,
2565                     int *hw_breakpoint_error,
2566                     int *hw_bp_error_explained_already)
2567 {
2568   gdb_exception bp_excpt;
2569
2570   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2571     return 0;
2572
2573   /* Note we don't initialize bl->target_info, as that wipes out
2574      the breakpoint location's shadow_contents if the breakpoint
2575      is still inserted at that location.  This in turn breaks
2576      target_read_memory which depends on these buffers when
2577      a memory read is requested at the breakpoint location:
2578      Once the target_info has been wiped, we fail to see that
2579      we have a breakpoint inserted at that address and thus
2580      read the breakpoint instead of returning the data saved in
2581      the breakpoint location's shadow contents.  */
2582   bl->target_info.reqstd_address = bl->address;
2583   bl->target_info.placed_address_space = bl->pspace->aspace;
2584   bl->target_info.length = bl->length;
2585
2586   /* When working with target-side conditions, we must pass all the conditions
2587      for the same breakpoint address down to the target since GDB will not
2588      insert those locations.  With a list of breakpoint conditions, the target
2589      can decide when to stop and notify GDB.  */
2590
2591   if (is_breakpoint (bl->owner))
2592     {
2593       build_target_condition_list (bl);
2594       build_target_command_list (bl);
2595       /* Reset the modification marker.  */
2596       bl->needs_update = 0;
2597     }
2598
2599   /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2600      set at a read-only address, then a breakpoint location will have
2601      been changed to hardware breakpoint before we get here.  If it is
2602      "off" however, error out before actually trying to insert the
2603      breakpoint, with a nicer error message.  */
2604   if (bl->loc_type == bp_loc_software_breakpoint
2605       && !automatic_hardware_breakpoints)
2606     {
2607       mem_region *mr = lookup_mem_region (bl->address);
2608
2609       if (mr != nullptr && mr->attrib.mode != MEM_RW)
2610         {
2611           fprintf_unfiltered (tmp_error_stream,
2612                               _("Cannot insert breakpoint %d.\n"
2613                                 "Cannot set software breakpoint "
2614                                 "at read-only address %s\n"),
2615                               bl->owner->number,
2616                               paddress (bl->gdbarch, bl->address));
2617           return 1;
2618         }
2619     }
2620
2621   if (bl->loc_type == bp_loc_software_breakpoint
2622       || bl->loc_type == bp_loc_hardware_breakpoint)
2623     {
2624       /* First check to see if we have to handle an overlay.  */
2625       if (overlay_debugging == ovly_off
2626           || bl->section == NULL
2627           || !(section_is_overlay (bl->section)))
2628         {
2629           /* No overlay handling: just set the breakpoint.  */
2630           try
2631             {
2632               int val;
2633
2634               val = bl->owner->ops->insert_location (bl);
2635               if (val)
2636                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2637             }
2638           catch (gdb_exception &e)
2639             {
2640               bp_excpt = std::move (e);
2641             }
2642         }
2643       else
2644         {
2645           /* This breakpoint is in an overlay section.
2646              Shall we set a breakpoint at the LMA?  */
2647           if (!overlay_events_enabled)
2648             {
2649               /* Yes -- overlay event support is not active, 
2650                  so we must try to set a breakpoint at the LMA.
2651                  This will not work for a hardware breakpoint.  */
2652               if (bl->loc_type == bp_loc_hardware_breakpoint)
2653                 warning (_("hardware breakpoint %d not supported in overlay!"),
2654                          bl->owner->number);
2655               else
2656                 {
2657                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2658                                                              bl->section);
2659                   /* Set a software (trap) breakpoint at the LMA.  */
2660                   bl->overlay_target_info = bl->target_info;
2661                   bl->overlay_target_info.reqstd_address = addr;
2662
2663                   /* No overlay handling: just set the breakpoint.  */
2664                   try
2665                     {
2666                       int val;
2667
2668                       bl->overlay_target_info.kind
2669                         = breakpoint_kind (bl, &addr);
2670                       bl->overlay_target_info.placed_address = addr;
2671                       val = target_insert_breakpoint (bl->gdbarch,
2672                                                       &bl->overlay_target_info);
2673                       if (val)
2674                         bp_excpt
2675                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2676                     }
2677                   catch (gdb_exception &e)
2678                     {
2679                       bp_excpt = std::move (e);
2680                     }
2681
2682                   if (bp_excpt.reason != 0)
2683                     fprintf_unfiltered (tmp_error_stream,
2684                                         "Overlay breakpoint %d "
2685                                         "failed: in ROM?\n",
2686                                         bl->owner->number);
2687                 }
2688             }
2689           /* Shall we set a breakpoint at the VMA? */
2690           if (section_is_mapped (bl->section))
2691             {
2692               /* Yes.  This overlay section is mapped into memory.  */
2693               try
2694                 {
2695                   int val;
2696
2697                   val = bl->owner->ops->insert_location (bl);
2698                   if (val)
2699                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2700                 }
2701               catch (gdb_exception &e)
2702                 {
2703                   bp_excpt = std::move (e);
2704                 }
2705             }
2706           else
2707             {
2708               /* No.  This breakpoint will not be inserted.  
2709                  No error, but do not mark the bp as 'inserted'.  */
2710               return 0;
2711             }
2712         }
2713
2714       if (bp_excpt.reason != 0)
2715         {
2716           /* Can't set the breakpoint.  */
2717
2718           /* In some cases, we might not be able to insert a
2719              breakpoint in a shared library that has already been
2720              removed, but we have not yet processed the shlib unload
2721              event.  Unfortunately, some targets that implement
2722              breakpoint insertion themselves can't tell why the
2723              breakpoint insertion failed (e.g., the remote target
2724              doesn't define error codes), so we must treat generic
2725              errors as memory errors.  */
2726           if (bp_excpt.reason == RETURN_ERROR
2727               && (bp_excpt.error == GENERIC_ERROR
2728                   || bp_excpt.error == MEMORY_ERROR)
2729               && bl->loc_type == bp_loc_software_breakpoint
2730               && (solib_name_from_address (bl->pspace, bl->address)
2731                   || shared_objfile_contains_address_p (bl->pspace,
2732                                                         bl->address)))
2733             {
2734               /* See also: disable_breakpoints_in_shlibs.  */
2735               bl->shlib_disabled = 1;
2736               gdb::observers::breakpoint_modified.notify (bl->owner);
2737               if (!*disabled_breaks)
2738                 {
2739                   fprintf_unfiltered (tmp_error_stream, 
2740                                       "Cannot insert breakpoint %d.\n", 
2741                                       bl->owner->number);
2742                   fprintf_unfiltered (tmp_error_stream, 
2743                                       "Temporarily disabling shared "
2744                                       "library breakpoints:\n");
2745                 }
2746               *disabled_breaks = 1;
2747               fprintf_unfiltered (tmp_error_stream,
2748                                   "breakpoint #%d\n", bl->owner->number);
2749               return 0;
2750             }
2751           else
2752             {
2753               if (bl->loc_type == bp_loc_hardware_breakpoint)
2754                 {
2755                   *hw_breakpoint_error = 1;
2756                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2757                   fprintf_unfiltered (tmp_error_stream,
2758                                       "Cannot insert hardware breakpoint %d%s",
2759                                       bl->owner->number,
2760                                       bp_excpt.message ? ":" : ".\n");
2761                   if (bp_excpt.message != NULL)
2762                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2763                                         bp_excpt.what ());
2764                 }
2765               else
2766                 {
2767                   if (bp_excpt.message == NULL)
2768                     {
2769                       std::string message
2770                         = memory_error_message (TARGET_XFER_E_IO,
2771                                                 bl->gdbarch, bl->address);
2772
2773                       fprintf_unfiltered (tmp_error_stream,
2774                                           "Cannot insert breakpoint %d.\n"
2775                                           "%s\n",
2776                                           bl->owner->number, message.c_str ());
2777                     }
2778                   else
2779                     {
2780                       fprintf_unfiltered (tmp_error_stream,
2781                                           "Cannot insert breakpoint %d: %s\n",
2782                                           bl->owner->number,
2783                                           bp_excpt.what ());
2784                     }
2785                 }
2786               return 1;
2787
2788             }
2789         }
2790       else
2791         bl->inserted = 1;
2792
2793       return 0;
2794     }
2795
2796   else if (bl->loc_type == bp_loc_hardware_watchpoint
2797            /* NOTE drow/2003-09-08: This state only exists for removing
2798               watchpoints.  It's not clear that it's necessary...  */
2799            && bl->owner->disposition != disp_del_at_next_stop)
2800     {
2801       int val;
2802
2803       gdb_assert (bl->owner->ops != NULL
2804                   && bl->owner->ops->insert_location != NULL);
2805
2806       val = bl->owner->ops->insert_location (bl);
2807
2808       /* If trying to set a read-watchpoint, and it turns out it's not
2809          supported, try emulating one with an access watchpoint.  */
2810       if (val == 1 && bl->watchpoint_type == hw_read)
2811         {
2812           struct bp_location *loc, **loc_temp;
2813
2814           /* But don't try to insert it, if there's already another
2815              hw_access location that would be considered a duplicate
2816              of this one.  */
2817           ALL_BP_LOCATIONS (loc, loc_temp)
2818             if (loc != bl
2819                 && loc->watchpoint_type == hw_access
2820                 && watchpoint_locations_match (bl, loc))
2821               {
2822                 bl->duplicate = 1;
2823                 bl->inserted = 1;
2824                 bl->target_info = loc->target_info;
2825                 bl->watchpoint_type = hw_access;
2826                 val = 0;
2827                 break;
2828               }
2829
2830           if (val == 1)
2831             {
2832               bl->watchpoint_type = hw_access;
2833               val = bl->owner->ops->insert_location (bl);
2834
2835               if (val)
2836                 /* Back to the original value.  */
2837                 bl->watchpoint_type = hw_read;
2838             }
2839         }
2840
2841       bl->inserted = (val == 0);
2842     }
2843
2844   else if (bl->owner->type == bp_catchpoint)
2845     {
2846       int val;
2847
2848       gdb_assert (bl->owner->ops != NULL
2849                   && bl->owner->ops->insert_location != NULL);
2850
2851       val = bl->owner->ops->insert_location (bl);
2852       if (val)
2853         {
2854           bl->owner->enable_state = bp_disabled;
2855
2856           if (val == 1)
2857             warning (_("\
2858 Error inserting catchpoint %d: Your system does not support this type\n\
2859 of catchpoint."), bl->owner->number);
2860           else
2861             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2862         }
2863
2864       bl->inserted = (val == 0);
2865
2866       /* We've already printed an error message if there was a problem
2867          inserting this catchpoint, and we've disabled the catchpoint,
2868          so just return success.  */
2869       return 0;
2870     }
2871
2872   return 0;
2873 }
2874
2875 /* This function is called when program space PSPACE is about to be
2876    deleted.  It takes care of updating breakpoints to not reference
2877    PSPACE anymore.  */
2878
2879 void
2880 breakpoint_program_space_exit (struct program_space *pspace)
2881 {
2882   struct breakpoint *b, *b_temp;
2883   struct bp_location *loc, **loc_temp;
2884
2885   /* Remove any breakpoint that was set through this program space.  */
2886   ALL_BREAKPOINTS_SAFE (b, b_temp)
2887     {
2888       if (b->pspace == pspace)
2889         delete_breakpoint (b);
2890     }
2891
2892   /* Breakpoints set through other program spaces could have locations
2893      bound to PSPACE as well.  Remove those.  */
2894   ALL_BP_LOCATIONS (loc, loc_temp)
2895     {
2896       struct bp_location *tmp;
2897
2898       if (loc->pspace == pspace)
2899         {
2900           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2901           if (loc->owner->loc == loc)
2902             loc->owner->loc = loc->next;
2903           else
2904             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2905               if (tmp->next == loc)
2906                 {
2907                   tmp->next = loc->next;
2908                   break;
2909                 }
2910         }
2911     }
2912
2913   /* Now update the global location list to permanently delete the
2914      removed locations above.  */
2915   update_global_location_list (UGLL_DONT_INSERT);
2916 }
2917
2918 /* Make sure all breakpoints are inserted in inferior.
2919    Throws exception on any error.
2920    A breakpoint that is already inserted won't be inserted
2921    again, so calling this function twice is safe.  */
2922 void
2923 insert_breakpoints (void)
2924 {
2925   struct breakpoint *bpt;
2926
2927   ALL_BREAKPOINTS (bpt)
2928     if (is_hardware_watchpoint (bpt))
2929       {
2930         struct watchpoint *w = (struct watchpoint *) bpt;
2931
2932         update_watchpoint (w, 0 /* don't reparse.  */);
2933       }
2934
2935   /* Updating watchpoints creates new locations, so update the global
2936      location list.  Explicitly tell ugll to insert locations and
2937      ignore breakpoints_always_inserted_mode.  Also,
2938      update_global_location_list tries to "upgrade" software
2939      breakpoints to hardware breakpoints to handle "set breakpoint
2940      auto-hw", so we need to call it even if we don't have new
2941      locations.  */
2942   update_global_location_list (UGLL_INSERT);
2943 }
2944
2945 /* Invoke CALLBACK for each of bp_location.  */
2946
2947 void
2948 iterate_over_bp_locations (walk_bp_location_callback callback)
2949 {
2950   struct bp_location *loc, **loc_tmp;
2951
2952   ALL_BP_LOCATIONS (loc, loc_tmp)
2953     {
2954       callback (loc, NULL);
2955     }
2956 }
2957
2958 /* This is used when we need to synch breakpoint conditions between GDB and the
2959    target.  It is the case with deleting and disabling of breakpoints when using
2960    always-inserted mode.  */
2961
2962 static void
2963 update_inserted_breakpoint_locations (void)
2964 {
2965   struct bp_location *bl, **blp_tmp;
2966   int error_flag = 0;
2967   int val = 0;
2968   int disabled_breaks = 0;
2969   int hw_breakpoint_error = 0;
2970   int hw_bp_details_reported = 0;
2971
2972   string_file tmp_error_stream;
2973
2974   /* Explicitly mark the warning -- this will only be printed if
2975      there was an error.  */
2976   tmp_error_stream.puts ("Warning:\n");
2977
2978   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2979
2980   ALL_BP_LOCATIONS (bl, blp_tmp)
2981     {
2982       /* We only want to update software breakpoints and hardware
2983          breakpoints.  */
2984       if (!is_breakpoint (bl->owner))
2985         continue;
2986
2987       /* We only want to update locations that are already inserted
2988          and need updating.  This is to avoid unwanted insertion during
2989          deletion of breakpoints.  */
2990       if (!bl->inserted || !bl->needs_update)
2991         continue;
2992
2993       switch_to_program_space_and_thread (bl->pspace);
2994
2995       /* For targets that support global breakpoints, there's no need
2996          to select an inferior to insert breakpoint to.  In fact, even
2997          if we aren't attached to any process yet, we should still
2998          insert breakpoints.  */
2999       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3000           && (inferior_ptid == null_ptid || !target_has_execution ()))
3001         continue;
3002
3003       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3004                                     &hw_breakpoint_error, &hw_bp_details_reported);
3005       if (val)
3006         error_flag = val;
3007     }
3008
3009   if (error_flag)
3010     {
3011       target_terminal::ours_for_output ();
3012       error_stream (tmp_error_stream);
3013     }
3014 }
3015
3016 /* Used when starting or continuing the program.  */
3017
3018 static void
3019 insert_breakpoint_locations (void)
3020 {
3021   struct breakpoint *bpt;
3022   struct bp_location *bl, **blp_tmp;
3023   int error_flag = 0;
3024   int val = 0;
3025   int disabled_breaks = 0;
3026   int hw_breakpoint_error = 0;
3027   int hw_bp_error_explained_already = 0;
3028
3029   string_file tmp_error_stream;
3030
3031   /* Explicitly mark the warning -- this will only be printed if
3032      there was an error.  */
3033   tmp_error_stream.puts ("Warning:\n");
3034
3035   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3036
3037   ALL_BP_LOCATIONS (bl, blp_tmp)
3038     {
3039       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3040         continue;
3041
3042       /* There is no point inserting thread-specific breakpoints if
3043          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3044          has BL->OWNER always non-NULL.  */
3045       if (bl->owner->thread != -1
3046           && !valid_global_thread_id (bl->owner->thread))
3047         continue;
3048
3049       switch_to_program_space_and_thread (bl->pspace);
3050
3051       /* For targets that support global breakpoints, there's no need
3052          to select an inferior to insert breakpoint to.  In fact, even
3053          if we aren't attached to any process yet, we should still
3054          insert breakpoints.  */
3055       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3056           && (inferior_ptid == null_ptid || !target_has_execution ()))
3057         continue;
3058
3059       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3060                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3061       if (val)
3062         error_flag = val;
3063     }
3064
3065   /* If we failed to insert all locations of a watchpoint, remove
3066      them, as half-inserted watchpoint is of limited use.  */
3067   ALL_BREAKPOINTS (bpt)  
3068     {
3069       int some_failed = 0;
3070       struct bp_location *loc;
3071
3072       if (!is_hardware_watchpoint (bpt))
3073         continue;
3074
3075       if (!breakpoint_enabled (bpt))
3076         continue;
3077
3078       if (bpt->disposition == disp_del_at_next_stop)
3079         continue;
3080       
3081       for (loc = bpt->loc; loc; loc = loc->next)
3082         if (!loc->inserted && should_be_inserted (loc))
3083           {
3084             some_failed = 1;
3085             break;
3086           }
3087       if (some_failed)
3088         {
3089           for (loc = bpt->loc; loc; loc = loc->next)
3090             if (loc->inserted)
3091               remove_breakpoint (loc);
3092
3093           hw_breakpoint_error = 1;
3094           tmp_error_stream.printf ("Could not insert "
3095                                    "hardware watchpoint %d.\n",
3096                                    bpt->number);
3097           error_flag = -1;
3098         }
3099     }
3100
3101   if (error_flag)
3102     {
3103       /* If a hardware breakpoint or watchpoint was inserted, add a
3104          message about possibly exhausted resources.  */
3105       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3106         {
3107           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3108 You may have requested too many hardware breakpoints/watchpoints.\n");
3109         }
3110       target_terminal::ours_for_output ();
3111       error_stream (tmp_error_stream);
3112     }
3113 }
3114
3115 /* Used when the program stops.
3116    Returns zero if successful, or non-zero if there was a problem
3117    removing a breakpoint location.  */
3118
3119 int
3120 remove_breakpoints (void)
3121 {
3122   struct bp_location *bl, **blp_tmp;
3123   int val = 0;
3124
3125   ALL_BP_LOCATIONS (bl, blp_tmp)
3126   {
3127     if (bl->inserted && !is_tracepoint (bl->owner))
3128       val |= remove_breakpoint (bl);
3129   }
3130   return val;
3131 }
3132
3133 /* When a thread exits, remove breakpoints that are related to
3134    that thread.  */
3135
3136 static void
3137 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3138 {
3139   struct breakpoint *b, *b_tmp;
3140
3141   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3142     {
3143       if (b->thread == tp->global_num && user_breakpoint_p (b))
3144         {
3145           b->disposition = disp_del_at_next_stop;
3146
3147           printf_filtered (_("\
3148 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3149                            b->number, print_thread_id (tp));
3150
3151           /* Hide it from the user.  */
3152           b->number = 0;
3153        }
3154     }
3155 }
3156
3157 /* See breakpoint.h.  */
3158
3159 void
3160 remove_breakpoints_inf (inferior *inf)
3161 {
3162   struct bp_location *bl, **blp_tmp;
3163   int val;
3164
3165   ALL_BP_LOCATIONS (bl, blp_tmp)
3166   {
3167     if (bl->pspace != inf->pspace)
3168       continue;
3169
3170     if (bl->inserted && !bl->target_info.persist)
3171       {
3172         val = remove_breakpoint (bl);
3173         if (val != 0)
3174           return;
3175       }
3176   }
3177 }
3178
3179 static int internal_breakpoint_number = -1;
3180
3181 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3182    If INTERNAL is non-zero, the breakpoint number will be populated
3183    from internal_breakpoint_number and that variable decremented.
3184    Otherwise the breakpoint number will be populated from
3185    breakpoint_count and that value incremented.  Internal breakpoints
3186    do not set the internal var bpnum.  */
3187 static void
3188 set_breakpoint_number (int internal, struct breakpoint *b)
3189 {
3190   if (internal)
3191     b->number = internal_breakpoint_number--;
3192   else
3193     {
3194       set_breakpoint_count (breakpoint_count + 1);
3195       b->number = breakpoint_count;
3196     }
3197 }
3198
3199 static struct breakpoint *
3200 create_internal_breakpoint (struct gdbarch *gdbarch,
3201                             CORE_ADDR address, enum bptype type,
3202                             const struct breakpoint_ops *ops)
3203 {
3204   symtab_and_line sal;
3205   sal.pc = address;
3206   sal.section = find_pc_overlay (sal.pc);
3207   sal.pspace = current_program_space;
3208
3209   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3210   b->number = internal_breakpoint_number--;
3211   b->disposition = disp_donttouch;
3212
3213   return b;
3214 }
3215
3216 static const char *const longjmp_names[] =
3217   {
3218     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3219   };
3220 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3221
3222 /* Per-objfile data private to breakpoint.c.  */
3223 struct breakpoint_objfile_data
3224 {
3225   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3226   struct bound_minimal_symbol overlay_msym {};
3227
3228   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3229   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3230
3231   /* True if we have looked for longjmp probes.  */
3232   int longjmp_searched = 0;
3233
3234   /* SystemTap probe points for longjmp (if any).  These are non-owning
3235      references.  */
3236   std::vector<probe *> longjmp_probes;
3237
3238   /* Minimal symbol for "std::terminate()" (if any).  */
3239   struct bound_minimal_symbol terminate_msym {};
3240
3241   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3242   struct bound_minimal_symbol exception_msym {};
3243
3244   /* True if we have looked for exception probes.  */
3245   int exception_searched = 0;
3246
3247   /* SystemTap probe points for unwinding (if any).  These are non-owning
3248      references.  */
3249   std::vector<probe *> exception_probes;
3250 };
3251
3252 static const struct objfile_key<breakpoint_objfile_data>
3253   breakpoint_objfile_key;
3254
3255 /* Minimal symbol not found sentinel.  */
3256 static struct minimal_symbol msym_not_found;
3257
3258 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3259
3260 static int
3261 msym_not_found_p (const struct minimal_symbol *msym)
3262 {
3263   return msym == &msym_not_found;
3264 }
3265
3266 /* Return per-objfile data needed by breakpoint.c.
3267    Allocate the data if necessary.  */
3268
3269 static struct breakpoint_objfile_data *
3270 get_breakpoint_objfile_data (struct objfile *objfile)
3271 {
3272   struct breakpoint_objfile_data *bp_objfile_data;
3273
3274   bp_objfile_data = breakpoint_objfile_key.get (objfile);
3275   if (bp_objfile_data == NULL)
3276     bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3277   return bp_objfile_data;
3278 }
3279
3280 static void
3281 create_overlay_event_breakpoint (void)
3282 {
3283   const char *const func_name = "_ovly_debug_event";
3284
3285   for (objfile *objfile : current_program_space->objfiles ())
3286     {
3287       struct breakpoint *b;
3288       struct breakpoint_objfile_data *bp_objfile_data;
3289       CORE_ADDR addr;
3290       struct explicit_location explicit_loc;
3291
3292       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3293
3294       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3295         continue;
3296
3297       if (bp_objfile_data->overlay_msym.minsym == NULL)
3298         {
3299           struct bound_minimal_symbol m;
3300
3301           m = lookup_minimal_symbol_text (func_name, objfile);
3302           if (m.minsym == NULL)
3303             {
3304               /* Avoid future lookups in this objfile.  */
3305               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3306               continue;
3307             }
3308           bp_objfile_data->overlay_msym = m;
3309         }
3310
3311       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3312       b = create_internal_breakpoint (objfile->arch (), addr,
3313                                       bp_overlay_event,
3314                                       &internal_breakpoint_ops);
3315       initialize_explicit_location (&explicit_loc);
3316       explicit_loc.function_name = ASTRDUP (func_name);
3317       b->location = new_explicit_location (&explicit_loc);
3318
3319       if (overlay_debugging == ovly_auto)
3320         {
3321           b->enable_state = bp_enabled;
3322           overlay_events_enabled = 1;
3323         }
3324       else
3325        {
3326          b->enable_state = bp_disabled;
3327          overlay_events_enabled = 0;
3328        }
3329     }
3330 }
3331
3332 static void
3333 create_longjmp_master_breakpoint (void)
3334 {
3335   scoped_restore_current_program_space restore_pspace;
3336
3337   for (struct program_space *pspace : program_spaces)
3338     {
3339       set_current_program_space (pspace);
3340
3341       for (objfile *objfile : current_program_space->objfiles ())
3342         {
3343           int i;
3344           struct gdbarch *gdbarch;
3345           struct breakpoint_objfile_data *bp_objfile_data;
3346
3347           gdbarch = objfile->arch ();
3348
3349           bp_objfile_data = get_breakpoint_objfile_data (objfile);
3350
3351           if (!bp_objfile_data->longjmp_searched)
3352             {
3353               std::vector<probe *> ret
3354                 = find_probes_in_objfile (objfile, "libc", "longjmp");
3355
3356               if (!ret.empty ())
3357                 {
3358                   /* We are only interested in checking one element.  */
3359                   probe *p = ret[0];
3360
3361                   if (!p->can_evaluate_arguments ())
3362                     {
3363                       /* We cannot use the probe interface here,
3364                          because it does not know how to evaluate
3365                          arguments.  */
3366                       ret.clear ();
3367                     }
3368                 }
3369               bp_objfile_data->longjmp_probes = ret;
3370               bp_objfile_data->longjmp_searched = 1;
3371             }
3372
3373           if (!bp_objfile_data->longjmp_probes.empty ())
3374             {
3375               for (probe *p : bp_objfile_data->longjmp_probes)
3376                 {
3377                   struct breakpoint *b;
3378
3379                   b = create_internal_breakpoint (gdbarch,
3380                                                   p->get_relocated_address (objfile),
3381                                                   bp_longjmp_master,
3382                                                   &internal_breakpoint_ops);
3383                   b->location = new_probe_location ("-probe-stap libc:longjmp");
3384                   b->enable_state = bp_disabled;
3385                 }
3386
3387               continue;
3388             }
3389
3390           if (!gdbarch_get_longjmp_target_p (gdbarch))
3391             continue;
3392
3393           for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3394             {
3395               struct breakpoint *b;
3396               const char *func_name;
3397               CORE_ADDR addr;
3398               struct explicit_location explicit_loc;
3399
3400               if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3401                 continue;
3402
3403               func_name = longjmp_names[i];
3404               if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3405                 {
3406                   struct bound_minimal_symbol m;
3407
3408                   m = lookup_minimal_symbol_text (func_name, objfile);
3409                   if (m.minsym == NULL)
3410                     {
3411                       /* Prevent future lookups in this objfile.  */
3412                       bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3413                       continue;
3414                     }
3415                   bp_objfile_data->longjmp_msym[i] = m;
3416                 }
3417
3418               addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3419               b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3420                                               &internal_breakpoint_ops);
3421               initialize_explicit_location (&explicit_loc);
3422               explicit_loc.function_name = ASTRDUP (func_name);
3423               b->location = new_explicit_location (&explicit_loc);
3424               b->enable_state = bp_disabled;
3425             }
3426         }
3427     }
3428 }
3429
3430 /* Create a master std::terminate breakpoint.  */
3431 static void
3432 create_std_terminate_master_breakpoint (void)
3433 {
3434   const char *const func_name = "std::terminate()";
3435
3436   scoped_restore_current_program_space restore_pspace;
3437
3438   for (struct program_space *pspace : program_spaces)
3439     {
3440       CORE_ADDR addr;
3441
3442       set_current_program_space (pspace);
3443
3444       for (objfile *objfile : current_program_space->objfiles ())
3445         {
3446           struct breakpoint *b;
3447           struct breakpoint_objfile_data *bp_objfile_data;
3448           struct explicit_location explicit_loc;
3449
3450           bp_objfile_data = get_breakpoint_objfile_data (objfile);
3451
3452           if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3453             continue;
3454
3455           if (bp_objfile_data->terminate_msym.minsym == NULL)
3456             {
3457               struct bound_minimal_symbol m;
3458
3459               m = lookup_minimal_symbol (func_name, NULL, objfile);
3460               if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3461                                        && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3462                 {
3463                   /* Prevent future lookups in this objfile.  */
3464                   bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3465                   continue;
3466                 }
3467               bp_objfile_data->terminate_msym = m;
3468             }
3469
3470           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3471           b = create_internal_breakpoint (objfile->arch (), addr,
3472                                           bp_std_terminate_master,
3473                                           &internal_breakpoint_ops);
3474           initialize_explicit_location (&explicit_loc);
3475           explicit_loc.function_name = ASTRDUP (func_name);
3476           b->location = new_explicit_location (&explicit_loc);
3477           b->enable_state = bp_disabled;
3478         }
3479     }
3480 }
3481
3482 /* Install a master breakpoint on the unwinder's debug hook.  */
3483
3484 static void
3485 create_exception_master_breakpoint (void)
3486 {
3487   const char *const func_name = "_Unwind_DebugHook";
3488
3489   for (objfile *objfile : current_program_space->objfiles ())
3490     {
3491       struct breakpoint *b;
3492       struct gdbarch *gdbarch;
3493       struct breakpoint_objfile_data *bp_objfile_data;
3494       CORE_ADDR addr;
3495       struct explicit_location explicit_loc;
3496
3497       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3498
3499       /* We prefer the SystemTap probe point if it exists.  */
3500       if (!bp_objfile_data->exception_searched)
3501         {
3502           std::vector<probe *> ret
3503             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3504
3505           if (!ret.empty ())
3506             {
3507               /* We are only interested in checking one element.  */
3508               probe *p = ret[0];
3509
3510               if (!p->can_evaluate_arguments ())
3511                 {
3512                   /* We cannot use the probe interface here, because it does
3513                      not know how to evaluate arguments.  */
3514                   ret.clear ();
3515                 }
3516             }
3517           bp_objfile_data->exception_probes = ret;
3518           bp_objfile_data->exception_searched = 1;
3519         }
3520
3521       if (!bp_objfile_data->exception_probes.empty ())
3522         {
3523           gdbarch = objfile->arch ();
3524
3525           for (probe *p : bp_objfile_data->exception_probes)
3526             {
3527               b = create_internal_breakpoint (gdbarch,
3528                                               p->get_relocated_address (objfile),
3529                                               bp_exception_master,
3530                                               &internal_breakpoint_ops);
3531               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3532               b->enable_state = bp_disabled;
3533             }
3534
3535           continue;
3536         }
3537
3538       /* Otherwise, try the hook function.  */
3539
3540       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3541         continue;
3542
3543       gdbarch = objfile->arch ();
3544
3545       if (bp_objfile_data->exception_msym.minsym == NULL)
3546         {
3547           struct bound_minimal_symbol debug_hook;
3548
3549           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3550           if (debug_hook.minsym == NULL)
3551             {
3552               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3553               continue;
3554             }
3555
3556           bp_objfile_data->exception_msym = debug_hook;
3557         }
3558
3559       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3560       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3561                                                  current_top_target ());
3562       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3563                                       &internal_breakpoint_ops);
3564       initialize_explicit_location (&explicit_loc);
3565       explicit_loc.function_name = ASTRDUP (func_name);
3566       b->location = new_explicit_location (&explicit_loc);
3567       b->enable_state = bp_disabled;
3568     }
3569 }
3570
3571 /* Does B have a location spec?  */
3572
3573 static int
3574 breakpoint_event_location_empty_p (const struct breakpoint *b)
3575 {
3576   return b->location != NULL && event_location_empty_p (b->location.get ());
3577 }
3578
3579 void
3580 update_breakpoints_after_exec (void)
3581 {
3582   struct breakpoint *b, *b_tmp;
3583   struct bp_location *bploc, **bplocp_tmp;
3584
3585   /* We're about to delete breakpoints from GDB's lists.  If the
3586      INSERTED flag is true, GDB will try to lift the breakpoints by
3587      writing the breakpoints' "shadow contents" back into memory.  The
3588      "shadow contents" are NOT valid after an exec, so GDB should not
3589      do that.  Instead, the target is responsible from marking
3590      breakpoints out as soon as it detects an exec.  We don't do that
3591      here instead, because there may be other attempts to delete
3592      breakpoints after detecting an exec and before reaching here.  */
3593   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3594     if (bploc->pspace == current_program_space)
3595       gdb_assert (!bploc->inserted);
3596
3597   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3598   {
3599     if (b->pspace != current_program_space)
3600       continue;
3601
3602     /* Solib breakpoints must be explicitly reset after an exec().  */
3603     if (b->type == bp_shlib_event)
3604       {
3605         delete_breakpoint (b);
3606         continue;
3607       }
3608
3609     /* JIT breakpoints must be explicitly reset after an exec().  */
3610     if (b->type == bp_jit_event)
3611       {
3612         delete_breakpoint (b);
3613         continue;
3614       }
3615
3616     /* Thread event breakpoints must be set anew after an exec(),
3617        as must overlay event and longjmp master breakpoints.  */
3618     if (b->type == bp_thread_event || b->type == bp_overlay_event
3619         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3620         || b->type == bp_exception_master)
3621       {
3622         delete_breakpoint (b);
3623         continue;
3624       }
3625
3626     /* Step-resume breakpoints are meaningless after an exec().  */
3627     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3628       {
3629         delete_breakpoint (b);
3630         continue;
3631       }
3632
3633     /* Just like single-step breakpoints.  */
3634     if (b->type == bp_single_step)
3635       {
3636         delete_breakpoint (b);
3637         continue;
3638       }
3639
3640     /* Longjmp and longjmp-resume breakpoints are also meaningless
3641        after an exec.  */
3642     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3643         || b->type == bp_longjmp_call_dummy
3644         || b->type == bp_exception || b->type == bp_exception_resume)
3645       {
3646         delete_breakpoint (b);
3647         continue;
3648       }
3649
3650     if (b->type == bp_catchpoint)
3651       {
3652         /* For now, none of the bp_catchpoint breakpoints need to
3653            do anything at this point.  In the future, if some of
3654            the catchpoints need to something, we will need to add
3655            a new method, and call this method from here.  */
3656         continue;
3657       }
3658
3659     /* bp_finish is a special case.  The only way we ought to be able
3660        to see one of these when an exec() has happened, is if the user
3661        caught a vfork, and then said "finish".  Ordinarily a finish just
3662        carries them to the call-site of the current callee, by setting
3663        a temporary bp there and resuming.  But in this case, the finish
3664        will carry them entirely through the vfork & exec.
3665
3666        We don't want to allow a bp_finish to remain inserted now.  But
3667        we can't safely delete it, 'cause finish_command has a handle to
3668        the bp on a bpstat, and will later want to delete it.  There's a
3669        chance (and I've seen it happen) that if we delete the bp_finish
3670        here, that its storage will get reused by the time finish_command
3671        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3672        We really must allow finish_command to delete a bp_finish.
3673
3674        In the absence of a general solution for the "how do we know
3675        it's safe to delete something others may have handles to?"
3676        problem, what we'll do here is just uninsert the bp_finish, and
3677        let finish_command delete it.
3678
3679        (We know the bp_finish is "doomed" in the sense that it's
3680        momentary, and will be deleted as soon as finish_command sees
3681        the inferior stopped.  So it doesn't matter that the bp's
3682        address is probably bogus in the new a.out, unlike e.g., the
3683        solib breakpoints.)  */
3684
3685     if (b->type == bp_finish)
3686       {
3687         continue;
3688       }
3689
3690     /* Without a symbolic address, we have little hope of the
3691        pre-exec() address meaning the same thing in the post-exec()
3692        a.out.  */
3693     if (breakpoint_event_location_empty_p (b))
3694       {
3695         delete_breakpoint (b);
3696         continue;
3697       }
3698   }
3699 }
3700
3701 int
3702 detach_breakpoints (ptid_t ptid)
3703 {
3704   struct bp_location *bl, **blp_tmp;
3705   int val = 0;
3706   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3707   struct inferior *inf = current_inferior ();
3708
3709   if (ptid.pid () == inferior_ptid.pid ())
3710     error (_("Cannot detach breakpoints of inferior_ptid"));
3711
3712   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3713   inferior_ptid = ptid;
3714   ALL_BP_LOCATIONS (bl, blp_tmp)
3715   {
3716     if (bl->pspace != inf->pspace)
3717       continue;
3718
3719     /* This function must physically remove breakpoints locations
3720        from the specified ptid, without modifying the breakpoint
3721        package's state.  Locations of type bp_loc_other are only
3722        maintained at GDB side.  So, there is no need to remove
3723        these bp_loc_other locations.  Moreover, removing these
3724        would modify the breakpoint package's state.  */
3725     if (bl->loc_type == bp_loc_other)
3726       continue;
3727
3728     if (bl->inserted)
3729       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3730   }
3731
3732   return val;
3733 }
3734
3735 /* Remove the breakpoint location BL from the current address space.
3736    Note that this is used to detach breakpoints from a child fork.
3737    When we get here, the child isn't in the inferior list, and neither
3738    do we have objects to represent its address space --- we should
3739    *not* look at bl->pspace->aspace here.  */
3740
3741 static int
3742 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3743 {
3744   int val;
3745
3746   /* BL is never in moribund_locations by our callers.  */
3747   gdb_assert (bl->owner != NULL);
3748
3749   /* The type of none suggests that owner is actually deleted.
3750      This should not ever happen.  */
3751   gdb_assert (bl->owner->type != bp_none);
3752
3753   if (bl->loc_type == bp_loc_software_breakpoint
3754       || bl->loc_type == bp_loc_hardware_breakpoint)
3755     {
3756       /* "Normal" instruction breakpoint: either the standard
3757          trap-instruction bp (bp_breakpoint), or a
3758          bp_hardware_breakpoint.  */
3759
3760       /* First check to see if we have to handle an overlay.  */
3761       if (overlay_debugging == ovly_off
3762           || bl->section == NULL
3763           || !(section_is_overlay (bl->section)))
3764         {
3765           /* No overlay handling: just remove the breakpoint.  */
3766
3767           /* If we're trying to uninsert a memory breakpoint that we
3768              know is set in a dynamic object that is marked
3769              shlib_disabled, then either the dynamic object was
3770              removed with "remove-symbol-file" or with
3771              "nosharedlibrary".  In the former case, we don't know
3772              whether another dynamic object might have loaded over the
3773              breakpoint's address -- the user might well let us know
3774              about it next with add-symbol-file (the whole point of
3775              add-symbol-file is letting the user manually maintain a
3776              list of dynamically loaded objects).  If we have the
3777              breakpoint's shadow memory, that is, this is a software
3778              breakpoint managed by GDB, check whether the breakpoint
3779              is still inserted in memory, to avoid overwriting wrong
3780              code with stale saved shadow contents.  Note that HW
3781              breakpoints don't have shadow memory, as they're
3782              implemented using a mechanism that is not dependent on
3783              being able to modify the target's memory, and as such
3784              they should always be removed.  */
3785           if (bl->shlib_disabled
3786               && bl->target_info.shadow_len != 0
3787               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3788             val = 0;
3789           else
3790             val = bl->owner->ops->remove_location (bl, reason);
3791         }
3792       else
3793         {
3794           /* This breakpoint is in an overlay section.
3795              Did we set a breakpoint at the LMA?  */
3796           if (!overlay_events_enabled)
3797               {
3798                 /* Yes -- overlay event support is not active, so we
3799                    should have set a breakpoint at the LMA.  Remove it.  
3800                 */
3801                 /* Ignore any failures: if the LMA is in ROM, we will
3802                    have already warned when we failed to insert it.  */
3803                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3804                   target_remove_hw_breakpoint (bl->gdbarch,
3805                                                &bl->overlay_target_info);
3806                 else
3807                   target_remove_breakpoint (bl->gdbarch,
3808                                             &bl->overlay_target_info,
3809                                             reason);
3810               }
3811           /* Did we set a breakpoint at the VMA? 
3812              If so, we will have marked the breakpoint 'inserted'.  */
3813           if (bl->inserted)
3814             {
3815               /* Yes -- remove it.  Previously we did not bother to
3816                  remove the breakpoint if the section had been
3817                  unmapped, but let's not rely on that being safe.  We
3818                  don't know what the overlay manager might do.  */
3819
3820               /* However, we should remove *software* breakpoints only
3821                  if the section is still mapped, or else we overwrite
3822                  wrong code with the saved shadow contents.  */
3823               if (bl->loc_type == bp_loc_hardware_breakpoint
3824                   || section_is_mapped (bl->section))
3825                 val = bl->owner->ops->remove_location (bl, reason);
3826               else
3827                 val = 0;
3828             }
3829           else
3830             {
3831               /* No -- not inserted, so no need to remove.  No error.  */
3832               val = 0;
3833             }
3834         }
3835
3836       /* In some cases, we might not be able to remove a breakpoint in
3837          a shared library that has already been removed, but we have
3838          not yet processed the shlib unload event.  Similarly for an
3839          unloaded add-symbol-file object - the user might not yet have
3840          had the chance to remove-symbol-file it.  shlib_disabled will
3841          be set if the library/object has already been removed, but
3842          the breakpoint hasn't been uninserted yet, e.g., after
3843          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3844          always-inserted mode.  */
3845       if (val
3846           && (bl->loc_type == bp_loc_software_breakpoint
3847               && (bl->shlib_disabled
3848                   || solib_name_from_address (bl->pspace, bl->address)
3849                   || shared_objfile_contains_address_p (bl->pspace,
3850                                                         bl->address))))
3851         val = 0;
3852
3853       if (val)
3854         return val;
3855       bl->inserted = (reason == DETACH_BREAKPOINT);
3856     }
3857   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3858     {
3859       gdb_assert (bl->owner->ops != NULL
3860                   && bl->owner->ops->remove_location != NULL);
3861
3862       bl->inserted = (reason == DETACH_BREAKPOINT);
3863       bl->owner->ops->remove_location (bl, reason);
3864
3865       /* Failure to remove any of the hardware watchpoints comes here.  */
3866       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3867         warning (_("Could not remove hardware watchpoint %d."),
3868                  bl->owner->number);
3869     }
3870   else if (bl->owner->type == bp_catchpoint
3871            && breakpoint_enabled (bl->owner)
3872            && !bl->duplicate)
3873     {
3874       gdb_assert (bl->owner->ops != NULL
3875                   && bl->owner->ops->remove_location != NULL);
3876
3877       val = bl->owner->ops->remove_location (bl, reason);
3878       if (val)
3879         return val;
3880
3881       bl->inserted = (reason == DETACH_BREAKPOINT);
3882     }
3883
3884   return 0;
3885 }
3886
3887 static int
3888 remove_breakpoint (struct bp_location *bl)
3889 {
3890   /* BL is never in moribund_locations by our callers.  */
3891   gdb_assert (bl->owner != NULL);
3892
3893   /* The type of none suggests that owner is actually deleted.
3894      This should not ever happen.  */
3895   gdb_assert (bl->owner->type != bp_none);
3896
3897   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3898
3899   switch_to_program_space_and_thread (bl->pspace);
3900
3901   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3902 }
3903
3904 /* Clear the "inserted" flag in all breakpoints.  */
3905
3906 void
3907 mark_breakpoints_out (void)
3908 {
3909   struct bp_location *bl, **blp_tmp;
3910
3911   ALL_BP_LOCATIONS (bl, blp_tmp)
3912     if (bl->pspace == current_program_space)
3913       bl->inserted = 0;
3914 }
3915
3916 /* Clear the "inserted" flag in all breakpoints and delete any
3917    breakpoints which should go away between runs of the program.
3918
3919    Plus other such housekeeping that has to be done for breakpoints
3920    between runs.
3921
3922    Note: this function gets called at the end of a run (by
3923    generic_mourn_inferior) and when a run begins (by
3924    init_wait_for_inferior).  */
3925
3926
3927
3928 void
3929 breakpoint_init_inferior (enum inf_context context)
3930 {
3931   struct breakpoint *b, *b_tmp;
3932   struct program_space *pspace = current_program_space;
3933
3934   /* If breakpoint locations are shared across processes, then there's
3935      nothing to do.  */
3936   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3937     return;
3938
3939   mark_breakpoints_out ();
3940
3941   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3942   {
3943     if (b->loc && b->loc->pspace != pspace)
3944       continue;
3945
3946     switch (b->type)
3947       {
3948       case bp_call_dummy:
3949       case bp_longjmp_call_dummy:
3950
3951         /* If the call dummy breakpoint is at the entry point it will
3952            cause problems when the inferior is rerun, so we better get
3953            rid of it.  */
3954
3955       case bp_watchpoint_scope:
3956
3957         /* Also get rid of scope breakpoints.  */
3958
3959       case bp_shlib_event:
3960
3961         /* Also remove solib event breakpoints.  Their addresses may
3962            have changed since the last time we ran the program.
3963            Actually we may now be debugging against different target;
3964            and so the solib backend that installed this breakpoint may
3965            not be used in by the target.  E.g.,
3966
3967            (gdb) file prog-linux
3968            (gdb) run               # native linux target
3969            ...
3970            (gdb) kill
3971            (gdb) file prog-win.exe
3972            (gdb) tar rem :9999     # remote Windows gdbserver.
3973         */
3974
3975       case bp_step_resume:
3976
3977         /* Also remove step-resume breakpoints.  */
3978
3979       case bp_single_step:
3980
3981         /* Also remove single-step breakpoints.  */
3982
3983         delete_breakpoint (b);
3984         break;
3985
3986       case bp_watchpoint:
3987       case bp_hardware_watchpoint:
3988       case bp_read_watchpoint:
3989       case bp_access_watchpoint:
3990         {
3991           struct watchpoint *w = (struct watchpoint *) b;
3992
3993           /* Likewise for watchpoints on local expressions.  */
3994           if (w->exp_valid_block != NULL)
3995             delete_breakpoint (b);
3996           else
3997             {
3998               /* Get rid of existing locations, which are no longer
3999                  valid.  New ones will be created in
4000                  update_watchpoint, when the inferior is restarted.
4001                  The next update_global_location_list call will
4002                  garbage collect them.  */
4003               b->loc = NULL;
4004
4005               if (context == inf_starting)
4006                 {
4007                   /* Reset val field to force reread of starting value in
4008                      insert_breakpoints.  */
4009                   w->val.reset (nullptr);
4010                   w->val_valid = false;
4011                 }
4012             }
4013         }
4014         break;
4015       default:
4016         break;
4017       }
4018   }
4019
4020   /* Get rid of the moribund locations.  */
4021   for (bp_location *bl : moribund_locations)
4022     decref_bp_location (&bl);
4023   moribund_locations.clear ();
4024 }
4025
4026 /* These functions concern about actual breakpoints inserted in the
4027    target --- to e.g. check if we need to do decr_pc adjustment or if
4028    we need to hop over the bkpt --- so we check for address space
4029    match, not program space.  */
4030
4031 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4032    exists at PC.  It returns ordinary_breakpoint_here if it's an
4033    ordinary breakpoint, or permanent_breakpoint_here if it's a
4034    permanent breakpoint.
4035    - When continuing from a location with an ordinary breakpoint, we
4036      actually single step once before calling insert_breakpoints.
4037    - When continuing from a location with a permanent breakpoint, we
4038      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4039      the target, to advance the PC past the breakpoint.  */
4040
4041 enum breakpoint_here
4042 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4043 {
4044   struct bp_location *bl, **blp_tmp;
4045   int any_breakpoint_here = 0;
4046
4047   ALL_BP_LOCATIONS (bl, blp_tmp)
4048     {
4049       if (bl->loc_type != bp_loc_software_breakpoint
4050           && bl->loc_type != bp_loc_hardware_breakpoint)
4051         continue;
4052
4053       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4054       if ((breakpoint_enabled (bl->owner)
4055            || bl->permanent)
4056           && breakpoint_location_address_match (bl, aspace, pc))
4057         {
4058           if (overlay_debugging 
4059               && section_is_overlay (bl->section)
4060               && !section_is_mapped (bl->section))
4061             continue;           /* unmapped overlay -- can't be a match */
4062           else if (bl->permanent)
4063             return permanent_breakpoint_here;
4064           else
4065             any_breakpoint_here = 1;
4066         }
4067     }
4068
4069   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4070 }
4071
4072 /* See breakpoint.h.  */
4073
4074 int
4075 breakpoint_in_range_p (const address_space *aspace,
4076                        CORE_ADDR addr, ULONGEST len)
4077 {
4078   struct bp_location *bl, **blp_tmp;
4079
4080   ALL_BP_LOCATIONS (bl, blp_tmp)
4081     {
4082       if (bl->loc_type != bp_loc_software_breakpoint
4083           && bl->loc_type != bp_loc_hardware_breakpoint)
4084         continue;
4085
4086       if ((breakpoint_enabled (bl->owner)
4087            || bl->permanent)
4088           && breakpoint_location_address_range_overlap (bl, aspace,
4089                                                         addr, len))
4090         {
4091           if (overlay_debugging
4092               && section_is_overlay (bl->section)
4093               && !section_is_mapped (bl->section))
4094             {
4095               /* Unmapped overlay -- can't be a match.  */
4096               continue;
4097             }
4098
4099           return 1;
4100         }
4101     }
4102
4103   return 0;
4104 }
4105
4106 /* Return true if there's a moribund breakpoint at PC.  */
4107
4108 int
4109 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4110 {
4111   for (bp_location *loc : moribund_locations)
4112     if (breakpoint_location_address_match (loc, aspace, pc))
4113       return 1;
4114
4115   return 0;
4116 }
4117
4118 /* Returns non-zero iff BL is inserted at PC, in address space
4119    ASPACE.  */
4120
4121 static int
4122 bp_location_inserted_here_p (struct bp_location *bl,
4123                              const address_space *aspace, CORE_ADDR pc)
4124 {
4125   if (bl->inserted
4126       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4127                                    aspace, pc))
4128     {
4129       if (overlay_debugging
4130           && section_is_overlay (bl->section)
4131           && !section_is_mapped (bl->section))
4132         return 0;               /* unmapped overlay -- can't be a match */
4133       else
4134         return 1;
4135     }
4136   return 0;
4137 }
4138
4139 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4140
4141 int
4142 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4143 {
4144   struct bp_location **blp, **blp_tmp = NULL;
4145
4146   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4147     {
4148       struct bp_location *bl = *blp;
4149
4150       if (bl->loc_type != bp_loc_software_breakpoint
4151           && bl->loc_type != bp_loc_hardware_breakpoint)
4152         continue;
4153
4154       if (bp_location_inserted_here_p (bl, aspace, pc))
4155         return 1;
4156     }
4157   return 0;
4158 }
4159
4160 /* This function returns non-zero iff there is a software breakpoint
4161    inserted at PC.  */
4162
4163 int
4164 software_breakpoint_inserted_here_p (const address_space *aspace,
4165                                      CORE_ADDR pc)
4166 {
4167   struct bp_location **blp, **blp_tmp = NULL;
4168
4169   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4170     {
4171       struct bp_location *bl = *blp;
4172
4173       if (bl->loc_type != bp_loc_software_breakpoint)
4174         continue;
4175
4176       if (bp_location_inserted_here_p (bl, aspace, pc))
4177         return 1;
4178     }
4179
4180   return 0;
4181 }
4182
4183 /* See breakpoint.h.  */
4184
4185 int
4186 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4187                                      CORE_ADDR pc)
4188 {
4189   struct bp_location **blp, **blp_tmp = NULL;
4190
4191   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4192     {
4193       struct bp_location *bl = *blp;
4194
4195       if (bl->loc_type != bp_loc_hardware_breakpoint)
4196         continue;
4197
4198       if (bp_location_inserted_here_p (bl, aspace, pc))
4199         return 1;
4200     }
4201
4202   return 0;
4203 }
4204
4205 int
4206 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4207                                        CORE_ADDR addr, ULONGEST len)
4208 {
4209   struct breakpoint *bpt;
4210
4211   ALL_BREAKPOINTS (bpt)
4212     {
4213       struct bp_location *loc;
4214
4215       if (bpt->type != bp_hardware_watchpoint
4216           && bpt->type != bp_access_watchpoint)
4217         continue;
4218
4219       if (!breakpoint_enabled (bpt))
4220         continue;
4221
4222       for (loc = bpt->loc; loc; loc = loc->next)
4223         if (loc->pspace->aspace == aspace && loc->inserted)
4224           {
4225             CORE_ADDR l, h;
4226
4227             /* Check for intersection.  */
4228             l = std::max<CORE_ADDR> (loc->address, addr);
4229             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4230             if (l < h)
4231               return 1;
4232           }
4233     }
4234   return 0;
4235 }
4236
4237 /* See breakpoint.h.  */
4238
4239 bool
4240 is_catchpoint (struct breakpoint *b)
4241 {
4242   return (b->type == bp_catchpoint);
4243 }
4244
4245 /* Frees any storage that is part of a bpstat.  Does not walk the
4246    'next' chain.  */
4247
4248 bpstats::~bpstats ()
4249 {
4250   if (bp_location_at != NULL)
4251     decref_bp_location (&bp_location_at);
4252 }
4253
4254 /* Clear a bpstat so that it says we are not at any breakpoint.
4255    Also free any storage that is part of a bpstat.  */
4256
4257 void
4258 bpstat_clear (bpstat *bsp)
4259 {
4260   bpstat p;
4261   bpstat q;
4262
4263   if (bsp == 0)
4264     return;
4265   p = *bsp;
4266   while (p != NULL)
4267     {
4268       q = p->next;
4269       delete p;
4270       p = q;
4271     }
4272   *bsp = NULL;
4273 }
4274
4275 bpstats::bpstats (const bpstats &other)
4276   : next (NULL),
4277     bp_location_at (other.bp_location_at),
4278     breakpoint_at (other.breakpoint_at),
4279     commands (other.commands),
4280     print (other.print),
4281     stop (other.stop),
4282     print_it (other.print_it)
4283 {
4284   if (other.old_val != NULL)
4285     old_val = release_value (value_copy (other.old_val.get ()));
4286   incref_bp_location (bp_location_at);
4287 }
4288
4289 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4290    is part of the bpstat is copied as well.  */
4291
4292 bpstat
4293 bpstat_copy (bpstat bs)
4294 {
4295   bpstat p = NULL;
4296   bpstat tmp;
4297   bpstat retval = NULL;
4298
4299   if (bs == NULL)
4300     return bs;
4301
4302   for (; bs != NULL; bs = bs->next)
4303     {
4304       tmp = new bpstats (*bs);
4305
4306       if (p == NULL)
4307         /* This is the first thing in the chain.  */
4308         retval = tmp;
4309       else
4310         p->next = tmp;
4311       p = tmp;
4312     }
4313   p->next = NULL;
4314   return retval;
4315 }
4316
4317 /* Find the bpstat associated with this breakpoint.  */
4318
4319 bpstat
4320 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4321 {
4322   if (bsp == NULL)
4323     return NULL;
4324
4325   for (; bsp != NULL; bsp = bsp->next)
4326     {
4327       if (bsp->breakpoint_at == breakpoint)
4328         return bsp;
4329     }
4330   return NULL;
4331 }
4332
4333 /* See breakpoint.h.  */
4334
4335 bool
4336 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4337 {
4338   for (; bsp != NULL; bsp = bsp->next)
4339     {
4340       if (bsp->breakpoint_at == NULL)
4341         {
4342           /* A moribund location can never explain a signal other than
4343              GDB_SIGNAL_TRAP.  */
4344           if (sig == GDB_SIGNAL_TRAP)
4345             return true;
4346         }
4347       else
4348         {
4349           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4350                                                         sig))
4351             return true;
4352         }
4353     }
4354
4355   return false;
4356 }
4357
4358 /* Put in *NUM the breakpoint number of the first breakpoint we are
4359    stopped at.  *BSP upon return is a bpstat which points to the
4360    remaining breakpoints stopped at (but which is not guaranteed to be
4361    good for anything but further calls to bpstat_num).
4362
4363    Return 0 if passed a bpstat which does not indicate any breakpoints.
4364    Return -1 if stopped at a breakpoint that has been deleted since
4365    we set it.
4366    Return 1 otherwise.  */
4367
4368 int
4369 bpstat_num (bpstat *bsp, int *num)
4370 {
4371   struct breakpoint *b;
4372
4373   if ((*bsp) == NULL)
4374     return 0;                   /* No more breakpoint values */
4375
4376   /* We assume we'll never have several bpstats that correspond to a
4377      single breakpoint -- otherwise, this function might return the
4378      same number more than once and this will look ugly.  */
4379   b = (*bsp)->breakpoint_at;
4380   *bsp = (*bsp)->next;
4381   if (b == NULL)
4382     return -1;                  /* breakpoint that's been deleted since */
4383
4384   *num = b->number;             /* We have its number */
4385   return 1;
4386 }
4387
4388 /* See breakpoint.h.  */
4389
4390 void
4391 bpstat_clear_actions (void)
4392 {
4393   bpstat bs;
4394
4395   if (inferior_ptid == null_ptid)
4396     return;
4397
4398   thread_info *tp = inferior_thread ();
4399   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4400     {
4401       bs->commands = NULL;
4402       bs->old_val.reset (nullptr);
4403     }
4404 }
4405
4406 /* Called when a command is about to proceed the inferior.  */
4407
4408 static void
4409 breakpoint_about_to_proceed (void)
4410 {
4411   if (inferior_ptid != null_ptid)
4412     {
4413       struct thread_info *tp = inferior_thread ();
4414
4415       /* Allow inferior function calls in breakpoint commands to not
4416          interrupt the command list.  When the call finishes
4417          successfully, the inferior will be standing at the same
4418          breakpoint as if nothing happened.  */
4419       if (tp->control.in_infcall)
4420         return;
4421     }
4422
4423   breakpoint_proceeded = 1;
4424 }
4425
4426 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4427    or its equivalent.  */
4428
4429 static int
4430 command_line_is_silent (struct command_line *cmd)
4431 {
4432   return cmd && (strcmp ("silent", cmd->line) == 0);
4433 }
4434
4435 /* Execute all the commands associated with all the breakpoints at
4436    this location.  Any of these commands could cause the process to
4437    proceed beyond this point, etc.  We look out for such changes by
4438    checking the global "breakpoint_proceeded" after each command.
4439
4440    Returns true if a breakpoint command resumed the inferior.  In that
4441    case, it is the caller's responsibility to recall it again with the
4442    bpstat of the current thread.  */
4443
4444 static int
4445 bpstat_do_actions_1 (bpstat *bsp)
4446 {
4447   bpstat bs;
4448   int again = 0;
4449
4450   /* Avoid endless recursion if a `source' command is contained
4451      in bs->commands.  */
4452   if (executing_breakpoint_commands)
4453     return 0;
4454
4455   scoped_restore save_executing
4456     = make_scoped_restore (&executing_breakpoint_commands, 1);
4457
4458   scoped_restore preventer = prevent_dont_repeat ();
4459
4460   /* This pointer will iterate over the list of bpstat's.  */
4461   bs = *bsp;
4462
4463   breakpoint_proceeded = 0;
4464   for (; bs != NULL; bs = bs->next)
4465     {
4466       struct command_line *cmd = NULL;
4467
4468       /* Take ownership of the BSP's command tree, if it has one.
4469
4470          The command tree could legitimately contain commands like
4471          'step' and 'next', which call clear_proceed_status, which
4472          frees stop_bpstat's command tree.  To make sure this doesn't
4473          free the tree we're executing out from under us, we need to
4474          take ownership of the tree ourselves.  Since a given bpstat's
4475          commands are only executed once, we don't need to copy it; we
4476          can clear the pointer in the bpstat, and make sure we free
4477          the tree when we're done.  */
4478       counted_command_line ccmd = bs->commands;
4479       bs->commands = NULL;
4480       if (ccmd != NULL)
4481         cmd = ccmd.get ();
4482       if (command_line_is_silent (cmd))
4483         {
4484           /* The action has been already done by bpstat_stop_status.  */
4485           cmd = cmd->next;
4486         }
4487
4488       while (cmd != NULL)
4489         {
4490           execute_control_command (cmd);
4491
4492           if (breakpoint_proceeded)
4493             break;
4494           else
4495             cmd = cmd->next;
4496         }
4497
4498       if (breakpoint_proceeded)
4499         {
4500           if (current_ui->async)
4501             /* If we are in async mode, then the target might be still
4502                running, not stopped at any breakpoint, so nothing for
4503                us to do here -- just return to the event loop.  */
4504             ;
4505           else
4506             /* In sync mode, when execute_control_command returns
4507                we're already standing on the next breakpoint.
4508                Breakpoint commands for that stop were not run, since
4509                execute_command does not run breakpoint commands --
4510                only command_line_handler does, but that one is not
4511                involved in execution of breakpoint commands.  So, we
4512                can now execute breakpoint commands.  It should be
4513                noted that making execute_command do bpstat actions is
4514                not an option -- in this case we'll have recursive
4515                invocation of bpstat for each breakpoint with a
4516                command, and can easily blow up GDB stack.  Instead, we
4517                return true, which will trigger the caller to recall us
4518                with the new stop_bpstat.  */
4519             again = 1;
4520           break;
4521         }
4522     }
4523   return again;
4524 }
4525
4526 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4527    one, is alive and has execution.  Return NULL otherwise.  */
4528
4529 static thread_info *
4530 get_bpstat_thread ()
4531 {
4532   if (inferior_ptid == null_ptid || !target_has_execution ())
4533     return NULL;
4534
4535   thread_info *tp = inferior_thread ();
4536   if (tp->state == THREAD_EXITED || tp->executing)
4537     return NULL;
4538   return tp;
4539 }
4540
4541 void
4542 bpstat_do_actions (void)
4543 {
4544   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4545   thread_info *tp;
4546
4547   /* Do any commands attached to breakpoint we are stopped at.  */
4548   while ((tp = get_bpstat_thread ()) != NULL)
4549     {
4550       /* Since in sync mode, bpstat_do_actions may resume the
4551          inferior, and only return when it is stopped at the next
4552          breakpoint, we keep doing breakpoint actions until it returns
4553          false to indicate the inferior was not resumed.  */
4554       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4555         break;
4556     }
4557
4558   cleanup_if_error.release ();
4559 }
4560
4561 /* Print out the (old or new) value associated with a watchpoint.  */
4562
4563 static void
4564 watchpoint_value_print (struct value *val, struct ui_file *stream)
4565 {
4566   if (val == NULL)
4567     fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4568   else
4569     {
4570       struct value_print_options opts;
4571       get_user_print_options (&opts);
4572       value_print (val, stream, &opts);
4573     }
4574 }
4575
4576 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4577    debugging multiple threads.  */
4578
4579 void
4580 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4581 {
4582   if (uiout->is_mi_like_p ())
4583     return;
4584
4585   uiout->text ("\n");
4586
4587   if (show_thread_that_caused_stop ())
4588     {
4589       const char *name;
4590       struct thread_info *thr = inferior_thread ();
4591
4592       uiout->text ("Thread ");
4593       uiout->field_string ("thread-id", print_thread_id (thr));
4594
4595       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4596       if (name != NULL)
4597         {
4598           uiout->text (" \"");
4599           uiout->field_string ("name", name);
4600           uiout->text ("\"");
4601         }
4602
4603       uiout->text (" hit ");
4604     }
4605 }
4606
4607 /* Generic routine for printing messages indicating why we
4608    stopped.  The behavior of this function depends on the value
4609    'print_it' in the bpstat structure.  Under some circumstances we
4610    may decide not to print anything here and delegate the task to
4611    normal_stop().  */
4612
4613 static enum print_stop_action
4614 print_bp_stop_message (bpstat bs)
4615 {
4616   switch (bs->print_it)
4617     {
4618     case print_it_noop:
4619       /* Nothing should be printed for this bpstat entry.  */
4620       return PRINT_UNKNOWN;
4621       break;
4622
4623     case print_it_done:
4624       /* We still want to print the frame, but we already printed the
4625          relevant messages.  */
4626       return PRINT_SRC_AND_LOC;
4627       break;
4628
4629     case print_it_normal:
4630       {
4631         struct breakpoint *b = bs->breakpoint_at;
4632
4633         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4634            which has since been deleted.  */
4635         if (b == NULL)
4636           return PRINT_UNKNOWN;
4637
4638         /* Normal case.  Call the breakpoint's print_it method.  */
4639         return b->ops->print_it (bs);
4640       }
4641       break;
4642
4643     default:
4644       internal_error (__FILE__, __LINE__,
4645                       _("print_bp_stop_message: unrecognized enum value"));
4646       break;
4647     }
4648 }
4649
4650 /* A helper function that prints a shared library stopped event.  */
4651
4652 static void
4653 print_solib_event (int is_catchpoint)
4654 {
4655   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4656   bool any_added = !current_program_space->added_solibs.empty ();
4657
4658   if (!is_catchpoint)
4659     {
4660       if (any_added || any_deleted)
4661         current_uiout->text (_("Stopped due to shared library event:\n"));
4662       else
4663         current_uiout->text (_("Stopped due to shared library event (no "
4664                                "libraries added or removed)\n"));
4665     }
4666
4667   if (current_uiout->is_mi_like_p ())
4668     current_uiout->field_string ("reason",
4669                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4670
4671   if (any_deleted)
4672     {
4673       current_uiout->text (_("  Inferior unloaded "));
4674       ui_out_emit_list list_emitter (current_uiout, "removed");
4675       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4676         {
4677           const std::string &name = current_program_space->deleted_solibs[ix];
4678
4679           if (ix > 0)
4680             current_uiout->text ("    ");
4681           current_uiout->field_string ("library", name);
4682           current_uiout->text ("\n");
4683         }
4684     }
4685
4686   if (any_added)
4687     {
4688       current_uiout->text (_("  Inferior loaded "));
4689       ui_out_emit_list list_emitter (current_uiout, "added");
4690       bool first = true;
4691       for (so_list *iter : current_program_space->added_solibs)
4692         {
4693           if (!first)
4694             current_uiout->text ("    ");
4695           first = false;
4696           current_uiout->field_string ("library", iter->so_name);
4697           current_uiout->text ("\n");
4698         }
4699     }
4700 }
4701
4702 /* Print a message indicating what happened.  This is called from
4703    normal_stop().  The input to this routine is the head of the bpstat
4704    list - a list of the eventpoints that caused this stop.  KIND is
4705    the target_waitkind for the stopping event.  This
4706    routine calls the generic print routine for printing a message
4707    about reasons for stopping.  This will print (for example) the
4708    "Breakpoint n," part of the output.  The return value of this
4709    routine is one of:
4710
4711    PRINT_UNKNOWN: Means we printed nothing.
4712    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4713    code to print the location.  An example is 
4714    "Breakpoint 1, " which should be followed by
4715    the location.
4716    PRINT_SRC_ONLY: Means we printed something, but there is no need
4717    to also print the location part of the message.
4718    An example is the catch/throw messages, which
4719    don't require a location appended to the end.
4720    PRINT_NOTHING: We have done some printing and we don't need any 
4721    further info to be printed.  */
4722
4723 enum print_stop_action
4724 bpstat_print (bpstat bs, int kind)
4725 {
4726   enum print_stop_action val;
4727
4728   /* Maybe another breakpoint in the chain caused us to stop.
4729      (Currently all watchpoints go on the bpstat whether hit or not.
4730      That probably could (should) be changed, provided care is taken
4731      with respect to bpstat_explains_signal).  */
4732   for (; bs; bs = bs->next)
4733     {
4734       val = print_bp_stop_message (bs);
4735       if (val == PRINT_SRC_ONLY 
4736           || val == PRINT_SRC_AND_LOC 
4737           || val == PRINT_NOTHING)
4738         return val;
4739     }
4740
4741   /* If we had hit a shared library event breakpoint,
4742      print_bp_stop_message would print out this message.  If we hit an
4743      OS-level shared library event, do the same thing.  */
4744   if (kind == TARGET_WAITKIND_LOADED)
4745     {
4746       print_solib_event (0);
4747       return PRINT_NOTHING;
4748     }
4749
4750   /* We reached the end of the chain, or we got a null BS to start
4751      with and nothing was printed.  */
4752   return PRINT_UNKNOWN;
4753 }
4754
4755 /* Evaluate the boolean expression EXP and return the result.  */
4756
4757 static bool
4758 breakpoint_cond_eval (expression *exp)
4759 {
4760   struct value *mark = value_mark ();
4761   bool res = value_true (evaluate_expression (exp));
4762
4763   value_free_to_mark (mark);
4764   return res;
4765 }
4766
4767 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4768
4769 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4770   : next (NULL),
4771     bp_location_at (bl),
4772     breakpoint_at (bl->owner),
4773     commands (NULL),
4774     print (0),
4775     stop (0),
4776     print_it (print_it_normal)
4777 {
4778   incref_bp_location (bl);
4779   **bs_link_pointer = this;
4780   *bs_link_pointer = &next;
4781 }
4782
4783 bpstats::bpstats ()
4784   : next (NULL),
4785     bp_location_at (NULL),
4786     breakpoint_at (NULL),
4787     commands (NULL),
4788     print (0),
4789     stop (0),
4790     print_it (print_it_normal)
4791 {
4792 }
4793 \f
4794 /* The target has stopped with waitstatus WS.  Check if any hardware
4795    watchpoints have triggered, according to the target.  */
4796
4797 int
4798 watchpoints_triggered (struct target_waitstatus *ws)
4799 {
4800   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4801   CORE_ADDR addr;
4802   struct breakpoint *b;
4803
4804   if (!stopped_by_watchpoint)
4805     {
4806       /* We were not stopped by a watchpoint.  Mark all watchpoints
4807          as not triggered.  */
4808       ALL_BREAKPOINTS (b)
4809         if (is_hardware_watchpoint (b))
4810           {
4811             struct watchpoint *w = (struct watchpoint *) b;
4812
4813             w->watchpoint_triggered = watch_triggered_no;
4814           }
4815
4816       return 0;
4817     }
4818
4819   if (!target_stopped_data_address (current_top_target (), &addr))
4820     {
4821       /* We were stopped by a watchpoint, but we don't know where.
4822          Mark all watchpoints as unknown.  */
4823       ALL_BREAKPOINTS (b)
4824         if (is_hardware_watchpoint (b))
4825           {
4826             struct watchpoint *w = (struct watchpoint *) b;
4827
4828             w->watchpoint_triggered = watch_triggered_unknown;
4829           }
4830
4831       return 1;
4832     }
4833
4834   /* The target could report the data address.  Mark watchpoints
4835      affected by this data address as triggered, and all others as not
4836      triggered.  */
4837
4838   ALL_BREAKPOINTS (b)
4839     if (is_hardware_watchpoint (b))
4840       {
4841         struct watchpoint *w = (struct watchpoint *) b;
4842         struct bp_location *loc;
4843
4844         w->watchpoint_triggered = watch_triggered_no;
4845         for (loc = b->loc; loc; loc = loc->next)
4846           {
4847             if (is_masked_watchpoint (b))
4848               {
4849                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4850                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4851
4852                 if (newaddr == start)
4853                   {
4854                     w->watchpoint_triggered = watch_triggered_yes;
4855                     break;
4856                   }
4857               }
4858             /* Exact match not required.  Within range is sufficient.  */
4859             else if (target_watchpoint_addr_within_range (current_top_target (),
4860                                                          addr, loc->address,
4861                                                          loc->length))
4862               {
4863                 w->watchpoint_triggered = watch_triggered_yes;
4864                 break;
4865               }
4866           }
4867       }
4868
4869   return 1;
4870 }
4871
4872 /* Possible return values for watchpoint_check.  */
4873 enum wp_check_result
4874   {
4875     /* The watchpoint has been deleted.  */
4876     WP_DELETED = 1,
4877
4878     /* The value has changed.  */
4879     WP_VALUE_CHANGED = 2,
4880
4881     /* The value has not changed.  */
4882     WP_VALUE_NOT_CHANGED = 3,
4883
4884     /* Ignore this watchpoint, no matter if the value changed or not.  */
4885     WP_IGNORE = 4,
4886   };
4887
4888 #define BP_TEMPFLAG 1
4889 #define BP_HARDWAREFLAG 2
4890
4891 /* Evaluate watchpoint condition expression and check if its value
4892    changed.  */
4893
4894 static wp_check_result
4895 watchpoint_check (bpstat bs)
4896 {
4897   struct watchpoint *b;
4898   struct frame_info *fr;
4899   int within_current_scope;
4900
4901   /* BS is built from an existing struct breakpoint.  */
4902   gdb_assert (bs->breakpoint_at != NULL);
4903   b = (struct watchpoint *) bs->breakpoint_at;
4904
4905   /* If this is a local watchpoint, we only want to check if the
4906      watchpoint frame is in scope if the current thread is the thread
4907      that was used to create the watchpoint.  */
4908   if (!watchpoint_in_thread_scope (b))
4909     return WP_IGNORE;
4910
4911   if (b->exp_valid_block == NULL)
4912     within_current_scope = 1;
4913   else
4914     {
4915       struct frame_info *frame = get_current_frame ();
4916       struct gdbarch *frame_arch = get_frame_arch (frame);
4917       CORE_ADDR frame_pc = get_frame_pc (frame);
4918
4919       /* stack_frame_destroyed_p() returns a non-zero value if we're
4920          still in the function but the stack frame has already been
4921          invalidated.  Since we can't rely on the values of local
4922          variables after the stack has been destroyed, we are treating
4923          the watchpoint in that state as `not changed' without further
4924          checking.  Don't mark watchpoints as changed if the current
4925          frame is in an epilogue - even if they are in some other
4926          frame, our view of the stack is likely to be wrong and
4927          frame_find_by_id could error out.  */
4928       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4929         return WP_IGNORE;
4930
4931       fr = frame_find_by_id (b->watchpoint_frame);
4932       within_current_scope = (fr != NULL);
4933
4934       /* If we've gotten confused in the unwinder, we might have
4935          returned a frame that can't describe this variable.  */
4936       if (within_current_scope)
4937         {
4938           struct symbol *function;
4939
4940           function = get_frame_function (fr);
4941           if (function == NULL
4942               || !contained_in (b->exp_valid_block,
4943                                 SYMBOL_BLOCK_VALUE (function)))
4944             within_current_scope = 0;
4945         }
4946
4947       if (within_current_scope)
4948         /* If we end up stopping, the current frame will get selected
4949            in normal_stop.  So this call to select_frame won't affect
4950            the user.  */
4951         select_frame (fr);
4952     }
4953
4954   if (within_current_scope)
4955     {
4956       /* We use value_{,free_to_}mark because it could be a *long*
4957          time before we return to the command level and call
4958          free_all_values.  We can't call free_all_values because we
4959          might be in the middle of evaluating a function call.  */
4960
4961       int pc = 0;
4962       struct value *mark;
4963       struct value *new_val;
4964
4965       if (is_masked_watchpoint (b))
4966         /* Since we don't know the exact trigger address (from
4967            stopped_data_address), just tell the user we've triggered
4968            a mask watchpoint.  */
4969         return WP_VALUE_CHANGED;
4970
4971       mark = value_mark ();
4972       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, false);
4973
4974       if (b->val_bitsize != 0)
4975         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4976
4977       /* We use value_equal_contents instead of value_equal because
4978          the latter coerces an array to a pointer, thus comparing just
4979          the address of the array instead of its contents.  This is
4980          not what we want.  */
4981       if ((b->val != NULL) != (new_val != NULL)
4982           || (b->val != NULL && !value_equal_contents (b->val.get (),
4983                                                        new_val)))
4984         {
4985           bs->old_val = b->val;
4986           b->val = release_value (new_val);
4987           b->val_valid = true;
4988           if (new_val != NULL)
4989             value_free_to_mark (mark);
4990           return WP_VALUE_CHANGED;
4991         }
4992       else
4993         {
4994           /* Nothing changed.  */
4995           value_free_to_mark (mark);
4996           return WP_VALUE_NOT_CHANGED;
4997         }
4998     }
4999   else
5000     {
5001       /* This seems like the only logical thing to do because
5002          if we temporarily ignored the watchpoint, then when
5003          we reenter the block in which it is valid it contains
5004          garbage (in the case of a function, it may have two
5005          garbage values, one before and one after the prologue).
5006          So we can't even detect the first assignment to it and
5007          watch after that (since the garbage may or may not equal
5008          the first value assigned).  */
5009       /* We print all the stop information in
5010          breakpoint_ops->print_it, but in this case, by the time we
5011          call breakpoint_ops->print_it this bp will be deleted
5012          already.  So we have no choice but print the information
5013          here.  */
5014
5015       SWITCH_THRU_ALL_UIS ()
5016         {
5017           struct ui_out *uiout = current_uiout;
5018
5019           if (uiout->is_mi_like_p ())
5020             uiout->field_string
5021               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5022           uiout->message ("\nWatchpoint %pF deleted because the program has "
5023                           "left the block in\n"
5024                           "which its expression is valid.\n",
5025                           signed_field ("wpnum", b->number));
5026         }
5027
5028       /* Make sure the watchpoint's commands aren't executed.  */
5029       b->commands = NULL;
5030       watchpoint_del_at_next_stop (b);
5031
5032       return WP_DELETED;
5033     }
5034 }
5035
5036 /* Return true if it looks like target has stopped due to hitting
5037    breakpoint location BL.  This function does not check if we should
5038    stop, only if BL explains the stop.  */
5039
5040 static int
5041 bpstat_check_location (const struct bp_location *bl,
5042                        const address_space *aspace, CORE_ADDR bp_addr,
5043                        const struct target_waitstatus *ws)
5044 {
5045   struct breakpoint *b = bl->owner;
5046
5047   /* BL is from an existing breakpoint.  */
5048   gdb_assert (b != NULL);
5049
5050   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5051 }
5052
5053 /* Determine if the watched values have actually changed, and we
5054    should stop.  If not, set BS->stop to 0.  */
5055
5056 static void
5057 bpstat_check_watchpoint (bpstat bs)
5058 {
5059   const struct bp_location *bl;
5060   struct watchpoint *b;
5061
5062   /* BS is built for existing struct breakpoint.  */
5063   bl = bs->bp_location_at;
5064   gdb_assert (bl != NULL);
5065   b = (struct watchpoint *) bs->breakpoint_at;
5066   gdb_assert (b != NULL);
5067
5068     {
5069       int must_check_value = 0;
5070       
5071       if (b->type == bp_watchpoint)
5072         /* For a software watchpoint, we must always check the
5073            watched value.  */
5074         must_check_value = 1;
5075       else if (b->watchpoint_triggered == watch_triggered_yes)
5076         /* We have a hardware watchpoint (read, write, or access)
5077            and the target earlier reported an address watched by
5078            this watchpoint.  */
5079         must_check_value = 1;
5080       else if (b->watchpoint_triggered == watch_triggered_unknown
5081                && b->type == bp_hardware_watchpoint)
5082         /* We were stopped by a hardware watchpoint, but the target could
5083            not report the data address.  We must check the watchpoint's
5084            value.  Access and read watchpoints are out of luck; without
5085            a data address, we can't figure it out.  */
5086         must_check_value = 1;
5087
5088       if (must_check_value)
5089         {
5090           wp_check_result e;
5091
5092           try
5093             {
5094               e = watchpoint_check (bs);
5095             }
5096           catch (const gdb_exception &ex)
5097             {
5098               exception_fprintf (gdb_stderr, ex,
5099                                  "Error evaluating expression "
5100                                  "for watchpoint %d\n",
5101                                  b->number);
5102
5103               SWITCH_THRU_ALL_UIS ()
5104                 {
5105                   printf_filtered (_("Watchpoint %d deleted.\n"),
5106                                    b->number);
5107                 }
5108               watchpoint_del_at_next_stop (b);
5109               e = WP_DELETED;
5110             }
5111
5112           switch (e)
5113             {
5114             case WP_DELETED:
5115               /* We've already printed what needs to be printed.  */
5116               bs->print_it = print_it_done;
5117               /* Stop.  */
5118               break;
5119             case WP_IGNORE:
5120               bs->print_it = print_it_noop;
5121               bs->stop = 0;
5122               break;
5123             case WP_VALUE_CHANGED:
5124               if (b->type == bp_read_watchpoint)
5125                 {
5126                   /* There are two cases to consider here:
5127
5128                      1. We're watching the triggered memory for reads.
5129                      In that case, trust the target, and always report
5130                      the watchpoint hit to the user.  Even though
5131                      reads don't cause value changes, the value may
5132                      have changed since the last time it was read, and
5133                      since we're not trapping writes, we will not see
5134                      those, and as such we should ignore our notion of
5135                      old value.
5136
5137                      2. We're watching the triggered memory for both
5138                      reads and writes.  There are two ways this may
5139                      happen:
5140
5141                      2.1. This is a target that can't break on data
5142                      reads only, but can break on accesses (reads or
5143                      writes), such as e.g., x86.  We detect this case
5144                      at the time we try to insert read watchpoints.
5145
5146                      2.2. Otherwise, the target supports read
5147                      watchpoints, but, the user set an access or write
5148                      watchpoint watching the same memory as this read
5149                      watchpoint.
5150
5151                      If we're watching memory writes as well as reads,
5152                      ignore watchpoint hits when we find that the
5153                      value hasn't changed, as reads don't cause
5154                      changes.  This still gives false positives when
5155                      the program writes the same value to memory as
5156                      what there was already in memory (we will confuse
5157                      it for a read), but it's much better than
5158                      nothing.  */
5159
5160                   int other_write_watchpoint = 0;
5161
5162                   if (bl->watchpoint_type == hw_read)
5163                     {
5164                       struct breakpoint *other_b;
5165
5166                       ALL_BREAKPOINTS (other_b)
5167                         if (other_b->type == bp_hardware_watchpoint
5168                             || other_b->type == bp_access_watchpoint)
5169                           {
5170                             struct watchpoint *other_w =
5171                               (struct watchpoint *) other_b;
5172
5173                             if (other_w->watchpoint_triggered
5174                                 == watch_triggered_yes)
5175                               {
5176                                 other_write_watchpoint = 1;
5177                                 break;
5178                               }
5179                           }
5180                     }
5181
5182                   if (other_write_watchpoint
5183                       || bl->watchpoint_type == hw_access)
5184                     {
5185                       /* We're watching the same memory for writes,
5186                          and the value changed since the last time we
5187                          updated it, so this trap must be for a write.
5188                          Ignore it.  */
5189                       bs->print_it = print_it_noop;
5190                       bs->stop = 0;
5191                     }
5192                 }
5193               break;
5194             case WP_VALUE_NOT_CHANGED:
5195               if (b->type == bp_hardware_watchpoint
5196                   || b->type == bp_watchpoint)
5197                 {
5198                   /* Don't stop: write watchpoints shouldn't fire if
5199                      the value hasn't changed.  */
5200                   bs->print_it = print_it_noop;
5201                   bs->stop = 0;
5202                 }
5203               /* Stop.  */
5204               break;
5205             default:
5206               /* Can't happen.  */
5207               break;
5208             }
5209         }
5210       else      /* must_check_value == 0 */
5211         {
5212           /* This is a case where some watchpoint(s) triggered, but
5213              not at the address of this watchpoint, or else no
5214              watchpoint triggered after all.  So don't print
5215              anything for this watchpoint.  */
5216           bs->print_it = print_it_noop;
5217           bs->stop = 0;
5218         }
5219     }
5220 }
5221
5222 /* For breakpoints that are currently marked as telling gdb to stop,
5223    check conditions (condition proper, frame, thread and ignore count)
5224    of breakpoint referred to by BS.  If we should not stop for this
5225    breakpoint, set BS->stop to 0.  */
5226
5227 static void
5228 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5229 {
5230   const struct bp_location *bl;
5231   struct breakpoint *b;
5232   /* Assume stop.  */
5233   bool condition_result = true;
5234   struct expression *cond;
5235
5236   gdb_assert (bs->stop);
5237
5238   /* BS is built for existing struct breakpoint.  */
5239   bl = bs->bp_location_at;
5240   gdb_assert (bl != NULL);
5241   b = bs->breakpoint_at;
5242   gdb_assert (b != NULL);
5243
5244   /* Even if the target evaluated the condition on its end and notified GDB, we
5245      need to do so again since GDB does not know if we stopped due to a
5246      breakpoint or a single step breakpoint.  */
5247
5248   if (frame_id_p (b->frame_id)
5249       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5250     {
5251       bs->stop = 0;
5252       return;
5253     }
5254
5255   /* If this is a thread/task-specific breakpoint, don't waste cpu
5256      evaluating the condition if this isn't the specified
5257      thread/task.  */
5258   if ((b->thread != -1 && b->thread != thread->global_num)
5259       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5260     {
5261       bs->stop = 0;
5262       return;
5263     }
5264
5265   /* Evaluate extension language breakpoints that have a "stop" method
5266      implemented.  */
5267   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5268
5269   if (is_watchpoint (b))
5270     {
5271       struct watchpoint *w = (struct watchpoint *) b;
5272
5273       cond = w->cond_exp.get ();
5274     }
5275   else
5276     cond = bl->cond.get ();
5277
5278   if (cond && b->disposition != disp_del_at_next_stop)
5279     {
5280       int within_current_scope = 1;
5281       struct watchpoint * w;
5282
5283       /* We use value_mark and value_free_to_mark because it could
5284          be a long time before we return to the command level and
5285          call free_all_values.  We can't call free_all_values
5286          because we might be in the middle of evaluating a
5287          function call.  */
5288       struct value *mark = value_mark ();
5289
5290       if (is_watchpoint (b))
5291         w = (struct watchpoint *) b;
5292       else
5293         w = NULL;
5294
5295       /* Need to select the frame, with all that implies so that
5296          the conditions will have the right context.  Because we
5297          use the frame, we will not see an inlined function's
5298          variables when we arrive at a breakpoint at the start
5299          of the inlined function; the current frame will be the
5300          call site.  */
5301       if (w == NULL || w->cond_exp_valid_block == NULL)
5302         select_frame (get_current_frame ());
5303       else
5304         {
5305           struct frame_info *frame;
5306
5307           /* For local watchpoint expressions, which particular
5308              instance of a local is being watched matters, so we
5309              keep track of the frame to evaluate the expression
5310              in.  To evaluate the condition however, it doesn't
5311              really matter which instantiation of the function
5312              where the condition makes sense triggers the
5313              watchpoint.  This allows an expression like "watch
5314              global if q > 10" set in `func', catch writes to
5315              global on all threads that call `func', or catch
5316              writes on all recursive calls of `func' by a single
5317              thread.  We simply always evaluate the condition in
5318              the innermost frame that's executing where it makes
5319              sense to evaluate the condition.  It seems
5320              intuitive.  */
5321           frame = block_innermost_frame (w->cond_exp_valid_block);
5322           if (frame != NULL)
5323             select_frame (frame);
5324           else
5325             within_current_scope = 0;
5326         }
5327       if (within_current_scope)
5328         {
5329           try
5330             {
5331               condition_result = breakpoint_cond_eval (cond);
5332             }
5333           catch (const gdb_exception &ex)
5334             {
5335               exception_fprintf (gdb_stderr, ex,
5336                                  "Error in testing breakpoint condition:\n");
5337             }
5338         }
5339       else
5340         {
5341           warning (_("Watchpoint condition cannot be tested "
5342                      "in the current scope"));
5343           /* If we failed to set the right context for this
5344              watchpoint, unconditionally report it.  */
5345         }
5346       /* FIXME-someday, should give breakpoint #.  */
5347       value_free_to_mark (mark);
5348     }
5349
5350   if (cond && !condition_result)
5351     {
5352       bs->stop = 0;
5353     }
5354   else if (b->ignore_count > 0)
5355     {
5356       b->ignore_count--;
5357       bs->stop = 0;
5358       /* Increase the hit count even though we don't stop.  */
5359       ++(b->hit_count);
5360       gdb::observers::breakpoint_modified.notify (b);
5361     }   
5362 }
5363
5364 /* Returns true if we need to track moribund locations of LOC's type
5365    on the current target.  */
5366
5367 static int
5368 need_moribund_for_location_type (struct bp_location *loc)
5369 {
5370   return ((loc->loc_type == bp_loc_software_breakpoint
5371            && !target_supports_stopped_by_sw_breakpoint ())
5372           || (loc->loc_type == bp_loc_hardware_breakpoint
5373               && !target_supports_stopped_by_hw_breakpoint ()));
5374 }
5375
5376 /* See breakpoint.h.  */
5377
5378 bpstat
5379 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5380                     const struct target_waitstatus *ws)
5381 {
5382   struct breakpoint *b;
5383   bpstat bs_head = NULL, *bs_link = &bs_head;
5384
5385   ALL_BREAKPOINTS (b)
5386     {
5387       if (!breakpoint_enabled (b))
5388         continue;
5389
5390       for (bp_location *bl = b->loc; bl != NULL; bl = bl->next)
5391         {
5392           /* For hardware watchpoints, we look only at the first
5393              location.  The watchpoint_check function will work on the
5394              entire expression, not the individual locations.  For
5395              read watchpoints, the watchpoints_triggered function has
5396              checked all locations already.  */
5397           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5398             break;
5399
5400           if (!bl->enabled || bl->disabled_by_cond || bl->shlib_disabled)
5401             continue;
5402
5403           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5404             continue;
5405
5406           /* Come here if it's a watchpoint, or if the break address
5407              matches.  */
5408
5409           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5410                                                            explain stop.  */
5411
5412           /* Assume we stop.  Should we find a watchpoint that is not
5413              actually triggered, or if the condition of the breakpoint
5414              evaluates as false, we'll reset 'stop' to 0.  */
5415           bs->stop = 1;
5416           bs->print = 1;
5417
5418           /* If this is a scope breakpoint, mark the associated
5419              watchpoint as triggered so that we will handle the
5420              out-of-scope event.  We'll get to the watchpoint next
5421              iteration.  */
5422           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5423             {
5424               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5425
5426               w->watchpoint_triggered = watch_triggered_yes;
5427             }
5428         }
5429     }
5430
5431   /* Check if a moribund breakpoint explains the stop.  */
5432   if (!target_supports_stopped_by_sw_breakpoint ()
5433       || !target_supports_stopped_by_hw_breakpoint ())
5434     {
5435       for (bp_location *loc : moribund_locations)
5436         {
5437           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5438               && need_moribund_for_location_type (loc))
5439             {
5440               bpstat bs = new bpstats (loc, &bs_link);
5441               /* For hits of moribund locations, we should just proceed.  */
5442               bs->stop = 0;
5443               bs->print = 0;
5444               bs->print_it = print_it_noop;
5445             }
5446         }
5447     }
5448
5449   return bs_head;
5450 }
5451
5452 /* See breakpoint.h.  */
5453
5454 bpstat
5455 bpstat_stop_status (const address_space *aspace,
5456                     CORE_ADDR bp_addr, thread_info *thread,
5457                     const struct target_waitstatus *ws,
5458                     bpstat stop_chain)
5459 {
5460   struct breakpoint *b = NULL;
5461   /* First item of allocated bpstat's.  */
5462   bpstat bs_head = stop_chain;
5463   bpstat bs;
5464   int need_remove_insert;
5465   int removed_any;
5466
5467   /* First, build the bpstat chain with locations that explain a
5468      target stop, while being careful to not set the target running,
5469      as that may invalidate locations (in particular watchpoint
5470      locations are recreated).  Resuming will happen here with
5471      breakpoint conditions or watchpoint expressions that include
5472      inferior function calls.  */
5473   if (bs_head == NULL)
5474     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5475
5476   /* A bit of special processing for shlib breakpoints.  We need to
5477      process solib loading here, so that the lists of loaded and
5478      unloaded libraries are correct before we handle "catch load" and
5479      "catch unload".  */
5480   for (bs = bs_head; bs != NULL; bs = bs->next)
5481     {
5482       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5483         {
5484           handle_solib_event ();
5485           break;
5486         }
5487     }
5488
5489   /* Now go through the locations that caused the target to stop, and
5490      check whether we're interested in reporting this stop to higher
5491      layers, or whether we should resume the target transparently.  */
5492
5493   removed_any = 0;
5494
5495   for (bs = bs_head; bs != NULL; bs = bs->next)
5496     {
5497       if (!bs->stop)
5498         continue;
5499
5500       b = bs->breakpoint_at;
5501       b->ops->check_status (bs);
5502       if (bs->stop)
5503         {
5504           bpstat_check_breakpoint_conditions (bs, thread);
5505
5506           if (bs->stop)
5507             {
5508               ++(b->hit_count);
5509               gdb::observers::breakpoint_modified.notify (b);
5510
5511               /* We will stop here.  */
5512               if (b->disposition == disp_disable)
5513                 {
5514                   --(b->enable_count);
5515                   if (b->enable_count <= 0)
5516                     b->enable_state = bp_disabled;
5517                   removed_any = 1;
5518                 }
5519               if (b->silent)
5520                 bs->print = 0;
5521               bs->commands = b->commands;
5522               if (command_line_is_silent (bs->commands
5523                                           ? bs->commands.get () : NULL))
5524                 bs->print = 0;
5525
5526               b->ops->after_condition_true (bs);
5527             }
5528
5529         }
5530
5531       /* Print nothing for this entry if we don't stop or don't
5532          print.  */
5533       if (!bs->stop || !bs->print)
5534         bs->print_it = print_it_noop;
5535     }
5536
5537   /* If we aren't stopping, the value of some hardware watchpoint may
5538      not have changed, but the intermediate memory locations we are
5539      watching may have.  Don't bother if we're stopping; this will get
5540      done later.  */
5541   need_remove_insert = 0;
5542   if (! bpstat_causes_stop (bs_head))
5543     for (bs = bs_head; bs != NULL; bs = bs->next)
5544       if (!bs->stop
5545           && bs->breakpoint_at
5546           && is_hardware_watchpoint (bs->breakpoint_at))
5547         {
5548           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5549
5550           update_watchpoint (w, 0 /* don't reparse.  */);
5551           need_remove_insert = 1;
5552         }
5553
5554   if (need_remove_insert)
5555     update_global_location_list (UGLL_MAY_INSERT);
5556   else if (removed_any)
5557     update_global_location_list (UGLL_DONT_INSERT);
5558
5559   return bs_head;
5560 }
5561
5562 static void
5563 handle_jit_event (CORE_ADDR address)
5564 {
5565   struct gdbarch *gdbarch;
5566
5567   infrun_debug_printf ("handling bp_jit_event");
5568
5569   /* Switch terminal for any messages produced by
5570      breakpoint_re_set.  */
5571   target_terminal::ours_for_output ();
5572
5573   gdbarch = get_frame_arch (get_current_frame ());
5574   /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5575      thus it is expected that its objectfile can be found through
5576      minimal symbol lookup.  If it doesn't work (and assert fails), it
5577      most likely means that `jit_breakpoint_re_set` was changes and this
5578      function needs to be updated too.  */
5579   bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5580   gdb_assert (jit_bp_sym.objfile != nullptr);
5581   jit_event_handler (gdbarch, jit_bp_sym.objfile);
5582
5583   target_terminal::inferior ();
5584 }
5585
5586 /* Prepare WHAT final decision for infrun.  */
5587
5588 /* Decide what infrun needs to do with this bpstat.  */
5589
5590 struct bpstat_what
5591 bpstat_what (bpstat bs_head)
5592 {
5593   struct bpstat_what retval;
5594   bpstat bs;
5595
5596   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5597   retval.call_dummy = STOP_NONE;
5598   retval.is_longjmp = false;
5599
5600   for (bs = bs_head; bs != NULL; bs = bs->next)
5601     {
5602       /* Extract this BS's action.  After processing each BS, we check
5603          if its action overrides all we've seem so far.  */
5604       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5605       enum bptype bptype;
5606
5607       if (bs->breakpoint_at == NULL)
5608         {
5609           /* I suspect this can happen if it was a momentary
5610              breakpoint which has since been deleted.  */
5611           bptype = bp_none;
5612         }
5613       else
5614         bptype = bs->breakpoint_at->type;
5615
5616       switch (bptype)
5617         {
5618         case bp_none:
5619           break;
5620         case bp_breakpoint:
5621         case bp_hardware_breakpoint:
5622         case bp_single_step:
5623         case bp_until:
5624         case bp_finish:
5625         case bp_shlib_event:
5626           if (bs->stop)
5627             {
5628               if (bs->print)
5629                 this_action = BPSTAT_WHAT_STOP_NOISY;
5630               else
5631                 this_action = BPSTAT_WHAT_STOP_SILENT;
5632             }
5633           else
5634             this_action = BPSTAT_WHAT_SINGLE;
5635           break;
5636         case bp_watchpoint:
5637         case bp_hardware_watchpoint:
5638         case bp_read_watchpoint:
5639         case bp_access_watchpoint:
5640           if (bs->stop)
5641             {
5642               if (bs->print)
5643                 this_action = BPSTAT_WHAT_STOP_NOISY;
5644               else
5645                 this_action = BPSTAT_WHAT_STOP_SILENT;
5646             }
5647           else
5648             {
5649               /* There was a watchpoint, but we're not stopping.
5650                  This requires no further action.  */
5651             }
5652           break;
5653         case bp_longjmp:
5654         case bp_longjmp_call_dummy:
5655         case bp_exception:
5656           if (bs->stop)
5657             {
5658               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5659               retval.is_longjmp = bptype != bp_exception;
5660             }
5661           else
5662             this_action = BPSTAT_WHAT_SINGLE;
5663           break;
5664         case bp_longjmp_resume:
5665         case bp_exception_resume:
5666           if (bs->stop)
5667             {
5668               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5669               retval.is_longjmp = bptype == bp_longjmp_resume;
5670             }
5671           else
5672             this_action = BPSTAT_WHAT_SINGLE;
5673           break;
5674         case bp_step_resume:
5675           if (bs->stop)
5676             this_action = BPSTAT_WHAT_STEP_RESUME;
5677           else
5678             {
5679               /* It is for the wrong frame.  */
5680               this_action = BPSTAT_WHAT_SINGLE;
5681             }
5682           break;
5683         case bp_hp_step_resume:
5684           if (bs->stop)
5685             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5686           else
5687             {
5688               /* It is for the wrong frame.  */
5689               this_action = BPSTAT_WHAT_SINGLE;
5690             }
5691           break;
5692         case bp_watchpoint_scope:
5693         case bp_thread_event:
5694         case bp_overlay_event:
5695         case bp_longjmp_master:
5696         case bp_std_terminate_master:
5697         case bp_exception_master:
5698           this_action = BPSTAT_WHAT_SINGLE;
5699           break;
5700         case bp_catchpoint:
5701           if (bs->stop)
5702             {
5703               if (bs->print)
5704                 this_action = BPSTAT_WHAT_STOP_NOISY;
5705               else
5706                 this_action = BPSTAT_WHAT_STOP_SILENT;
5707             }
5708           else
5709             {
5710               /* Some catchpoints are implemented with breakpoints.
5711                  For those, we need to step over the breakpoint.  */
5712               if (bs->bp_location_at->loc_type != bp_loc_other)
5713                 this_action = BPSTAT_WHAT_SINGLE;
5714             }
5715           break;
5716         case bp_jit_event:
5717           this_action = BPSTAT_WHAT_SINGLE;
5718           break;
5719         case bp_call_dummy:
5720           /* Make sure the action is stop (silent or noisy),
5721              so infrun.c pops the dummy frame.  */
5722           retval.call_dummy = STOP_STACK_DUMMY;
5723           this_action = BPSTAT_WHAT_STOP_SILENT;
5724           break;
5725         case bp_std_terminate:
5726           /* Make sure the action is stop (silent or noisy),
5727              so infrun.c pops the dummy frame.  */
5728           retval.call_dummy = STOP_STD_TERMINATE;
5729           this_action = BPSTAT_WHAT_STOP_SILENT;
5730           break;
5731         case bp_tracepoint:
5732         case bp_fast_tracepoint:
5733         case bp_static_tracepoint:
5734           /* Tracepoint hits should not be reported back to GDB, and
5735              if one got through somehow, it should have been filtered
5736              out already.  */
5737           internal_error (__FILE__, __LINE__,
5738                           _("bpstat_what: tracepoint encountered"));
5739           break;
5740         case bp_gnu_ifunc_resolver:
5741           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5742           this_action = BPSTAT_WHAT_SINGLE;
5743           break;
5744         case bp_gnu_ifunc_resolver_return:
5745           /* The breakpoint will be removed, execution will restart from the
5746              PC of the former breakpoint.  */
5747           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5748           break;
5749
5750         case bp_dprintf:
5751           if (bs->stop)
5752             this_action = BPSTAT_WHAT_STOP_SILENT;
5753           else
5754             this_action = BPSTAT_WHAT_SINGLE;
5755           break;
5756
5757         default:
5758           internal_error (__FILE__, __LINE__,
5759                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5760         }
5761
5762       retval.main_action = std::max (retval.main_action, this_action);
5763     }
5764
5765   return retval;
5766 }
5767
5768 void
5769 bpstat_run_callbacks (bpstat bs_head)
5770 {
5771   bpstat bs;
5772
5773   for (bs = bs_head; bs != NULL; bs = bs->next)
5774     {
5775       struct breakpoint *b = bs->breakpoint_at;
5776
5777       if (b == NULL)
5778         continue;
5779       switch (b->type)
5780         {
5781         case bp_jit_event:
5782           handle_jit_event (bs->bp_location_at->address);
5783           break;
5784         case bp_gnu_ifunc_resolver:
5785           gnu_ifunc_resolver_stop (b);
5786           break;
5787         case bp_gnu_ifunc_resolver_return:
5788           gnu_ifunc_resolver_return_stop (b);
5789           break;
5790         }
5791     }
5792 }
5793
5794 /* See breakpoint.h.  */
5795
5796 bool
5797 bpstat_should_step ()
5798 {
5799   struct breakpoint *b;
5800
5801   ALL_BREAKPOINTS (b)
5802     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5803       return true;
5804   return false;
5805 }
5806
5807 /* See breakpoint.h.  */
5808
5809 bool
5810 bpstat_causes_stop (bpstat bs)
5811 {
5812   for (; bs != NULL; bs = bs->next)
5813     if (bs->stop)
5814       return true;
5815
5816   return false;
5817 }
5818
5819 \f
5820
5821 /* Compute a string of spaces suitable to indent the next line
5822    so it starts at the position corresponding to the table column
5823    named COL_NAME in the currently active table of UIOUT.  */
5824
5825 static char *
5826 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5827 {
5828   static char wrap_indent[80];
5829   int i, total_width, width, align;
5830   const char *text;
5831
5832   total_width = 0;
5833   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5834     {
5835       if (strcmp (text, col_name) == 0)
5836         {
5837           gdb_assert (total_width < sizeof wrap_indent);
5838           memset (wrap_indent, ' ', total_width);
5839           wrap_indent[total_width] = 0;
5840
5841           return wrap_indent;
5842         }
5843
5844       total_width += width + 1;
5845     }
5846
5847   return NULL;
5848 }
5849
5850 /* Determine if the locations of this breakpoint will have their conditions
5851    evaluated by the target, host or a mix of both.  Returns the following:
5852
5853     "host": Host evals condition.
5854     "host or target": Host or Target evals condition.
5855     "target": Target evals condition.
5856 */
5857
5858 static const char *
5859 bp_condition_evaluator (struct breakpoint *b)
5860 {
5861   struct bp_location *bl;
5862   char host_evals = 0;
5863   char target_evals = 0;
5864
5865   if (!b)
5866     return NULL;
5867
5868   if (!is_breakpoint (b))
5869     return NULL;
5870
5871   if (gdb_evaluates_breakpoint_condition_p ()
5872       || !target_supports_evaluation_of_breakpoint_conditions ())
5873     return condition_evaluation_host;
5874
5875   for (bl = b->loc; bl; bl = bl->next)
5876     {
5877       if (bl->cond_bytecode)
5878         target_evals++;
5879       else
5880         host_evals++;
5881     }
5882
5883   if (host_evals && target_evals)
5884     return condition_evaluation_both;
5885   else if (target_evals)
5886     return condition_evaluation_target;
5887   else
5888     return condition_evaluation_host;
5889 }
5890
5891 /* Determine the breakpoint location's condition evaluator.  This is
5892    similar to bp_condition_evaluator, but for locations.  */
5893
5894 static const char *
5895 bp_location_condition_evaluator (struct bp_location *bl)
5896 {
5897   if (bl && !is_breakpoint (bl->owner))
5898     return NULL;
5899
5900   if (gdb_evaluates_breakpoint_condition_p ()
5901       || !target_supports_evaluation_of_breakpoint_conditions ())
5902     return condition_evaluation_host;
5903
5904   if (bl && bl->cond_bytecode)
5905     return condition_evaluation_target;
5906   else
5907     return condition_evaluation_host;
5908 }
5909
5910 /* Print the LOC location out of the list of B->LOC locations.  */
5911
5912 static void
5913 print_breakpoint_location (struct breakpoint *b,
5914                            struct bp_location *loc)
5915 {
5916   struct ui_out *uiout = current_uiout;
5917
5918   scoped_restore_current_program_space restore_pspace;
5919
5920   if (loc != NULL && loc->shlib_disabled)
5921     loc = NULL;
5922
5923   if (loc != NULL)
5924     set_current_program_space (loc->pspace);
5925
5926   if (b->display_canonical)
5927     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5928   else if (loc && loc->symtab)
5929     {
5930       const struct symbol *sym = loc->symbol;
5931
5932       if (sym)
5933         {
5934           uiout->text ("in ");
5935           uiout->field_string ("func", sym->print_name (),
5936                                function_name_style.style ());
5937           uiout->text (" ");
5938           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5939           uiout->text ("at ");
5940         }
5941       uiout->field_string ("file",
5942                            symtab_to_filename_for_display (loc->symtab),
5943                            file_name_style.style ());
5944       uiout->text (":");
5945
5946       if (uiout->is_mi_like_p ())
5947         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5948       
5949       uiout->field_signed ("line", loc->line_number);
5950     }
5951   else if (loc)
5952     {
5953       string_file stb;
5954
5955       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5956                               demangle, "");
5957       uiout->field_stream ("at", stb);
5958     }
5959   else
5960     {
5961       uiout->field_string ("pending",
5962                            event_location_to_string (b->location.get ()));
5963       /* If extra_string is available, it could be holding a condition
5964          or dprintf arguments.  In either case, make sure it is printed,
5965          too, but only for non-MI streams.  */
5966       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5967         {
5968           if (b->type == bp_dprintf)
5969             uiout->text (",");
5970           else
5971             uiout->text (" ");
5972           uiout->text (b->extra_string);
5973         }
5974     }
5975
5976   if (loc && is_breakpoint (b)
5977       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5978       && bp_condition_evaluator (b) == condition_evaluation_both)
5979     {
5980       uiout->text (" (");
5981       uiout->field_string ("evaluated-by",
5982                            bp_location_condition_evaluator (loc));
5983       uiout->text (")");
5984     }
5985 }
5986
5987 static const char *
5988 bptype_string (enum bptype type)
5989 {
5990   struct ep_type_description
5991     {
5992       enum bptype type;
5993       const char *description;
5994     };
5995   static struct ep_type_description bptypes[] =
5996   {
5997     {bp_none, "?deleted?"},
5998     {bp_breakpoint, "breakpoint"},
5999     {bp_hardware_breakpoint, "hw breakpoint"},
6000     {bp_single_step, "sw single-step"},
6001     {bp_until, "until"},
6002     {bp_finish, "finish"},
6003     {bp_watchpoint, "watchpoint"},
6004     {bp_hardware_watchpoint, "hw watchpoint"},
6005     {bp_read_watchpoint, "read watchpoint"},
6006     {bp_access_watchpoint, "acc watchpoint"},
6007     {bp_longjmp, "longjmp"},
6008     {bp_longjmp_resume, "longjmp resume"},
6009     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6010     {bp_exception, "exception"},
6011     {bp_exception_resume, "exception resume"},
6012     {bp_step_resume, "step resume"},
6013     {bp_hp_step_resume, "high-priority step resume"},
6014     {bp_watchpoint_scope, "watchpoint scope"},
6015     {bp_call_dummy, "call dummy"},
6016     {bp_std_terminate, "std::terminate"},
6017     {bp_shlib_event, "shlib events"},
6018     {bp_thread_event, "thread events"},
6019     {bp_overlay_event, "overlay events"},
6020     {bp_longjmp_master, "longjmp master"},
6021     {bp_std_terminate_master, "std::terminate master"},
6022     {bp_exception_master, "exception master"},
6023     {bp_catchpoint, "catchpoint"},
6024     {bp_tracepoint, "tracepoint"},
6025     {bp_fast_tracepoint, "fast tracepoint"},
6026     {bp_static_tracepoint, "static tracepoint"},
6027     {bp_dprintf, "dprintf"},
6028     {bp_jit_event, "jit events"},
6029     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6030     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6031   };
6032
6033   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6034       || ((int) type != bptypes[(int) type].type))
6035     internal_error (__FILE__, __LINE__,
6036                     _("bptypes table does not describe type #%d."),
6037                     (int) type);
6038
6039   return bptypes[(int) type].description;
6040 }
6041
6042 /* For MI, output a field named 'thread-groups' with a list as the value.
6043    For CLI, prefix the list with the string 'inf'. */
6044
6045 static void
6046 output_thread_groups (struct ui_out *uiout,
6047                       const char *field_name,
6048                       const std::vector<int> &inf_nums,
6049                       int mi_only)
6050 {
6051   int is_mi = uiout->is_mi_like_p ();
6052
6053   /* For backward compatibility, don't display inferiors in CLI unless
6054      there are several.  Always display them for MI. */
6055   if (!is_mi && mi_only)
6056     return;
6057
6058   ui_out_emit_list list_emitter (uiout, field_name);
6059
6060   for (size_t i = 0; i < inf_nums.size (); i++)
6061     {
6062       if (is_mi)
6063         {
6064           char mi_group[10];
6065
6066           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6067           uiout->field_string (NULL, mi_group);
6068         }
6069       else
6070         {
6071           if (i == 0)
6072             uiout->text (" inf ");
6073           else
6074             uiout->text (", ");
6075         
6076           uiout->text (plongest (inf_nums[i]));
6077         }
6078     }
6079 }
6080
6081 /* Print B to gdb_stdout.  If RAW_LOC, print raw breakpoint locations
6082    instead of going via breakpoint_ops::print_one.  This makes "maint
6083    info breakpoints" show the software breakpoint locations of
6084    catchpoints, which are considered internal implementation
6085    detail.  */
6086
6087 static void
6088 print_one_breakpoint_location (struct breakpoint *b,
6089                                struct bp_location *loc,
6090                                int loc_number,
6091                                struct bp_location **last_loc,
6092                                int allflag, bool raw_loc)
6093 {
6094   struct command_line *l;
6095   static char bpenables[] = "nynny";
6096
6097   struct ui_out *uiout = current_uiout;
6098   int header_of_multiple = 0;
6099   int part_of_multiple = (loc != NULL);
6100   struct value_print_options opts;
6101
6102   get_user_print_options (&opts);
6103
6104   gdb_assert (!loc || loc_number != 0);
6105   /* See comment in print_one_breakpoint concerning treatment of
6106      breakpoints with single disabled location.  */
6107   if (loc == NULL 
6108       && (b->loc != NULL 
6109           && (b->loc->next != NULL
6110               || !b->loc->enabled || b->loc->disabled_by_cond)))
6111     header_of_multiple = 1;
6112   if (loc == NULL)
6113     loc = b->loc;
6114
6115   annotate_record ();
6116
6117   /* 1 */
6118   annotate_field (0);
6119   if (part_of_multiple)
6120     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6121   else
6122     uiout->field_signed ("number", b->number);
6123
6124   /* 2 */
6125   annotate_field (1);
6126   if (part_of_multiple)
6127     uiout->field_skip ("type");
6128   else
6129     uiout->field_string ("type", bptype_string (b->type));
6130
6131   /* 3 */
6132   annotate_field (2);
6133   if (part_of_multiple)
6134     uiout->field_skip ("disp");
6135   else
6136     uiout->field_string ("disp", bpdisp_text (b->disposition));
6137
6138   /* 4 */
6139   annotate_field (3);
6140   if (part_of_multiple)
6141     uiout->field_string ("enabled", (loc->disabled_by_cond ? "N*"
6142                                      : (loc->enabled ? "y" : "n")));
6143   else
6144     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6145
6146   /* 5 and 6 */
6147   if (!raw_loc && b->ops != NULL && b->ops->print_one != NULL)
6148     b->ops->print_one (b, last_loc);
6149   else
6150     {
6151       if (is_watchpoint (b))
6152         {
6153           struct watchpoint *w = (struct watchpoint *) b;
6154
6155           /* Field 4, the address, is omitted (which makes the columns
6156              not line up too nicely with the headers, but the effect
6157              is relatively readable).  */
6158           if (opts.addressprint)
6159             uiout->field_skip ("addr");
6160           annotate_field (5);
6161           uiout->field_string ("what", w->exp_string);
6162         }
6163       else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6164                || is_ada_exception_catchpoint (b))
6165         {
6166           if (opts.addressprint)
6167             {
6168               annotate_field (4);
6169               if (header_of_multiple)
6170                 uiout->field_string ("addr", "<MULTIPLE>",
6171                                      metadata_style.style ());
6172               else if (b->loc == NULL || loc->shlib_disabled)
6173                 uiout->field_string ("addr", "<PENDING>",
6174                                      metadata_style.style ());
6175               else
6176                 uiout->field_core_addr ("addr",
6177                                         loc->gdbarch, loc->address);
6178             }
6179           annotate_field (5);
6180           if (!header_of_multiple)
6181             print_breakpoint_location (b, loc);
6182           if (b->loc)
6183             *last_loc = b->loc;
6184         }
6185     }
6186
6187   if (loc != NULL && !header_of_multiple)
6188     {
6189       std::vector<int> inf_nums;
6190       int mi_only = 1;
6191
6192       for (inferior *inf : all_inferiors ())
6193         {
6194           if (inf->pspace == loc->pspace)
6195             inf_nums.push_back (inf->num);
6196         }
6197
6198         /* For backward compatibility, don't display inferiors in CLI unless
6199            there are several.  Always display for MI. */
6200         if (allflag
6201             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6202                 && (program_spaces.size () > 1
6203                     || number_of_inferiors () > 1)
6204                 /* LOC is for existing B, it cannot be in
6205                    moribund_locations and thus having NULL OWNER.  */
6206                 && loc->owner->type != bp_catchpoint))
6207         mi_only = 0;
6208       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6209     }
6210
6211   if (!part_of_multiple)
6212     {
6213       if (b->thread != -1)
6214         {
6215           /* FIXME: This seems to be redundant and lost here; see the
6216              "stop only in" line a little further down.  */
6217           uiout->text (" thread ");
6218           uiout->field_signed ("thread", b->thread);
6219         }
6220       else if (b->task != 0)
6221         {
6222           uiout->text (" task ");
6223           uiout->field_signed ("task", b->task);
6224         }
6225     }
6226
6227   uiout->text ("\n");
6228
6229   if (!part_of_multiple)
6230     b->ops->print_one_detail (b, uiout);
6231
6232   if (part_of_multiple && frame_id_p (b->frame_id))
6233     {
6234       annotate_field (6);
6235       uiout->text ("\tstop only in stack frame at ");
6236       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6237          the frame ID.  */
6238       uiout->field_core_addr ("frame",
6239                               b->gdbarch, b->frame_id.stack_addr);
6240       uiout->text ("\n");
6241     }
6242   
6243   if (!part_of_multiple && b->cond_string)
6244     {
6245       annotate_field (7);
6246       if (is_tracepoint (b))
6247         uiout->text ("\ttrace only if ");
6248       else
6249         uiout->text ("\tstop only if ");
6250       uiout->field_string ("cond", b->cond_string);
6251
6252       /* Print whether the target is doing the breakpoint's condition
6253          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6254       if (is_breakpoint (b)
6255           && breakpoint_condition_evaluation_mode ()
6256           == condition_evaluation_target)
6257         {
6258           uiout->message (" (%pF evals)",
6259                           string_field ("evaluated-by",
6260                                         bp_condition_evaluator (b)));
6261         }
6262       uiout->text ("\n");
6263     }
6264
6265   if (!part_of_multiple && b->thread != -1)
6266     {
6267       /* FIXME should make an annotation for this.  */
6268       uiout->text ("\tstop only in thread ");
6269       if (uiout->is_mi_like_p ())
6270         uiout->field_signed ("thread", b->thread);
6271       else
6272         {
6273           struct thread_info *thr = find_thread_global_id (b->thread);
6274
6275           uiout->field_string ("thread", print_thread_id (thr));
6276         }
6277       uiout->text ("\n");
6278     }
6279   
6280   if (!part_of_multiple)
6281     {
6282       if (b->hit_count)
6283         {
6284           /* FIXME should make an annotation for this.  */
6285           if (is_catchpoint (b))
6286             uiout->text ("\tcatchpoint");
6287           else if (is_tracepoint (b))
6288             uiout->text ("\ttracepoint");
6289           else
6290             uiout->text ("\tbreakpoint");
6291           uiout->text (" already hit ");
6292           uiout->field_signed ("times", b->hit_count);
6293           if (b->hit_count == 1)
6294             uiout->text (" time\n");
6295           else
6296             uiout->text (" times\n");
6297         }
6298       else
6299         {
6300           /* Output the count also if it is zero, but only if this is mi.  */
6301           if (uiout->is_mi_like_p ())
6302             uiout->field_signed ("times", b->hit_count);
6303         }
6304     }
6305
6306   if (!part_of_multiple && b->ignore_count)
6307     {
6308       annotate_field (8);
6309       uiout->message ("\tignore next %pF hits\n",
6310                       signed_field ("ignore", b->ignore_count));
6311     }
6312
6313   /* Note that an enable count of 1 corresponds to "enable once"
6314      behavior, which is reported by the combination of enablement and
6315      disposition, so we don't need to mention it here.  */
6316   if (!part_of_multiple && b->enable_count > 1)
6317     {
6318       annotate_field (8);
6319       uiout->text ("\tdisable after ");
6320       /* Tweak the wording to clarify that ignore and enable counts
6321          are distinct, and have additive effect.  */
6322       if (b->ignore_count)
6323         uiout->text ("additional ");
6324       else
6325         uiout->text ("next ");
6326       uiout->field_signed ("enable", b->enable_count);
6327       uiout->text (" hits\n");
6328     }
6329
6330   if (!part_of_multiple && is_tracepoint (b))
6331     {
6332       struct tracepoint *tp = (struct tracepoint *) b;
6333
6334       if (tp->traceframe_usage)
6335         {
6336           uiout->text ("\ttrace buffer usage ");
6337           uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6338           uiout->text (" bytes\n");
6339         }
6340     }
6341
6342   l = b->commands ? b->commands.get () : NULL;
6343   if (!part_of_multiple && l)
6344     {
6345       annotate_field (9);
6346       ui_out_emit_tuple tuple_emitter (uiout, "script");
6347       print_command_lines (uiout, l, 4);
6348     }
6349
6350   if (is_tracepoint (b))
6351     {
6352       struct tracepoint *t = (struct tracepoint *) b;
6353
6354       if (!part_of_multiple && t->pass_count)
6355         {
6356           annotate_field (10);
6357           uiout->text ("\tpass count ");
6358           uiout->field_signed ("pass", t->pass_count);
6359           uiout->text (" \n");
6360         }
6361
6362       /* Don't display it when tracepoint or tracepoint location is
6363          pending.   */
6364       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6365         {
6366           annotate_field (11);
6367
6368           if (uiout->is_mi_like_p ())
6369             uiout->field_string ("installed",
6370                                  loc->inserted ? "y" : "n");
6371           else
6372             {
6373               if (loc->inserted)
6374                 uiout->text ("\t");
6375               else
6376                 uiout->text ("\tnot ");
6377               uiout->text ("installed on target\n");
6378             }
6379         }
6380     }
6381
6382   if (uiout->is_mi_like_p () && !part_of_multiple)
6383     {
6384       if (is_watchpoint (b))
6385         {
6386           struct watchpoint *w = (struct watchpoint *) b;
6387
6388           uiout->field_string ("original-location", w->exp_string);
6389         }
6390       else if (b->location != NULL
6391                && event_location_to_string (b->location.get ()) != NULL)
6392         uiout->field_string ("original-location",
6393                              event_location_to_string (b->location.get ()));
6394     }
6395 }
6396
6397 /* See breakpoint.h. */
6398
6399 bool fix_multi_location_breakpoint_output_globally = false;
6400
6401 static void
6402 print_one_breakpoint (struct breakpoint *b,
6403                       struct bp_location **last_loc, 
6404                       int allflag)
6405 {
6406   struct ui_out *uiout = current_uiout;
6407   bool use_fixed_output
6408     = (uiout->test_flags (fix_multi_location_breakpoint_output)
6409        || fix_multi_location_breakpoint_output_globally);
6410
6411   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6412   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag, false);
6413
6414   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6415      are outside.  */
6416   if (!use_fixed_output)
6417     bkpt_tuple_emitter.reset ();
6418
6419   /* If this breakpoint has custom print function,
6420      it's already printed.  Otherwise, print individual
6421      locations, if any.  */
6422   if (b->ops == NULL
6423       || b->ops->print_one == NULL
6424       || allflag)
6425     {
6426       /* If breakpoint has a single location that is disabled, we
6427          print it as if it had several locations, since otherwise it's
6428          hard to represent "breakpoint enabled, location disabled"
6429          situation.
6430
6431          Note that while hardware watchpoints have several locations
6432          internally, that's not a property exposed to users.
6433
6434          Likewise, while catchpoints may be implemented with
6435          breakpoints (e.g., catch throw), that's not a property
6436          exposed to users.  We do however display the internal
6437          breakpoint locations with "maint info breakpoints".  */
6438       if (!is_hardware_watchpoint (b)
6439           && (!is_catchpoint (b) || is_exception_catchpoint (b)
6440               || is_ada_exception_catchpoint (b))
6441           && (allflag
6442               || (b->loc && (b->loc->next
6443                              || !b->loc->enabled
6444                              || b->loc->disabled_by_cond))))
6445         {
6446           gdb::optional<ui_out_emit_list> locations_list;
6447
6448           /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6449              MI record.  For later versions, place breakpoint locations in a
6450              list.  */
6451           if (uiout->is_mi_like_p () && use_fixed_output)
6452             locations_list.emplace (uiout, "locations");
6453
6454           int n = 1;
6455           for (bp_location *loc = b->loc; loc != NULL; loc = loc->next, ++n)
6456             {
6457               ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6458               print_one_breakpoint_location (b, loc, n, last_loc,
6459                                              allflag, allflag);
6460             }
6461         }
6462     }
6463 }
6464
6465 static int
6466 breakpoint_address_bits (struct breakpoint *b)
6467 {
6468   int print_address_bits = 0;
6469   struct bp_location *loc;
6470
6471   /* Software watchpoints that aren't watching memory don't have an
6472      address to print.  */
6473   if (is_no_memory_software_watchpoint (b))
6474     return 0;
6475
6476   for (loc = b->loc; loc; loc = loc->next)
6477     {
6478       int addr_bit;
6479
6480       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6481       if (addr_bit > print_address_bits)
6482         print_address_bits = addr_bit;
6483     }
6484
6485   return print_address_bits;
6486 }
6487
6488 /* See breakpoint.h.  */
6489
6490 void
6491 print_breakpoint (breakpoint *b)
6492 {
6493   struct bp_location *dummy_loc = NULL;
6494   print_one_breakpoint (b, &dummy_loc, 0);
6495 }
6496
6497 /* Return true if this breakpoint was set by the user, false if it is
6498    internal or momentary.  */
6499
6500 int
6501 user_breakpoint_p (struct breakpoint *b)
6502 {
6503   return b->number > 0;
6504 }
6505
6506 /* See breakpoint.h.  */
6507
6508 int
6509 pending_breakpoint_p (struct breakpoint *b)
6510 {
6511   return b->loc == NULL;
6512 }
6513
6514 /* Print information on breakpoints (including watchpoints and tracepoints).
6515
6516    If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6517    understood by number_or_range_parser.  Only breakpoints included in this
6518    list are then printed.
6519
6520    If SHOW_INTERNAL is true, print internal breakpoints.
6521
6522    If FILTER is non-NULL, call it on each breakpoint and only include the
6523    ones for which it returns true.
6524
6525    Return the total number of breakpoints listed.  */
6526
6527 static int
6528 breakpoint_1 (const char *bp_num_list, bool show_internal,
6529               bool (*filter) (const struct breakpoint *))
6530 {
6531   struct breakpoint *b;
6532   struct bp_location *last_loc = NULL;
6533   int nr_printable_breakpoints;
6534   struct value_print_options opts;
6535   int print_address_bits = 0;
6536   int print_type_col_width = 14;
6537   struct ui_out *uiout = current_uiout;
6538   bool has_disabled_by_cond_location = false;
6539
6540   get_user_print_options (&opts);
6541
6542   /* Compute the number of rows in the table, as well as the size
6543      required for address fields.  */
6544   nr_printable_breakpoints = 0;
6545   ALL_BREAKPOINTS (b)
6546     {
6547       /* If we have a filter, only list the breakpoints it accepts.  */
6548       if (filter && !filter (b))
6549         continue;
6550
6551       /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6552          accept.  Skip the others.  */
6553       if (bp_num_list != NULL && *bp_num_list != '\0')
6554         {
6555           if (show_internal && parse_and_eval_long (bp_num_list) != b->number)
6556             continue;
6557           if (!show_internal && !number_is_in_list (bp_num_list, b->number))
6558             continue;
6559         }
6560
6561       if (show_internal || user_breakpoint_p (b))
6562         {
6563           int addr_bit, type_len;
6564
6565           addr_bit = breakpoint_address_bits (b);
6566           if (addr_bit > print_address_bits)
6567             print_address_bits = addr_bit;
6568
6569           type_len = strlen (bptype_string (b->type));
6570           if (type_len > print_type_col_width)
6571             print_type_col_width = type_len;
6572
6573           nr_printable_breakpoints++;
6574         }
6575     }
6576
6577   {
6578     ui_out_emit_table table_emitter (uiout,
6579                                      opts.addressprint ? 6 : 5,
6580                                      nr_printable_breakpoints,
6581                                      "BreakpointTable");
6582
6583     if (nr_printable_breakpoints > 0)
6584       annotate_breakpoints_headers ();
6585     if (nr_printable_breakpoints > 0)
6586       annotate_field (0);
6587     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6588     if (nr_printable_breakpoints > 0)
6589       annotate_field (1);
6590     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6591     if (nr_printable_breakpoints > 0)
6592       annotate_field (2);
6593     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6594     if (nr_printable_breakpoints > 0)
6595       annotate_field (3);
6596     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6597     if (opts.addressprint)
6598       {
6599         if (nr_printable_breakpoints > 0)
6600           annotate_field (4);
6601         if (print_address_bits <= 32)
6602           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6603         else
6604           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6605       }
6606     if (nr_printable_breakpoints > 0)
6607       annotate_field (5);
6608     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6609     uiout->table_body ();
6610     if (nr_printable_breakpoints > 0)
6611       annotate_breakpoints_table ();
6612
6613     ALL_BREAKPOINTS (b)
6614       {
6615         QUIT;
6616         /* If we have a filter, only list the breakpoints it accepts.  */
6617         if (filter && !filter (b))
6618           continue;
6619
6620         /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6621            accept.  Skip the others.  */
6622
6623         if (bp_num_list != NULL && *bp_num_list != '\0')
6624           {
6625             if (show_internal)  /* maintenance info breakpoint */
6626               {
6627                 if (parse_and_eval_long (bp_num_list) != b->number)
6628                   continue;
6629               }
6630             else                /* all others */
6631               {
6632                 if (!number_is_in_list (bp_num_list, b->number))
6633                   continue;
6634               }
6635           }
6636         /* We only print out user settable breakpoints unless the
6637            show_internal is set.  */
6638         if (show_internal || user_breakpoint_p (b))
6639           {
6640             print_one_breakpoint (b, &last_loc, show_internal);
6641             for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
6642               if (loc->disabled_by_cond)
6643                 has_disabled_by_cond_location = true;
6644           }
6645       }
6646   }
6647
6648   if (nr_printable_breakpoints == 0)
6649     {
6650       /* If there's a filter, let the caller decide how to report
6651          empty list.  */
6652       if (!filter)
6653         {
6654           if (bp_num_list == NULL || *bp_num_list == '\0')
6655             uiout->message ("No breakpoints or watchpoints.\n");
6656           else
6657             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6658                             bp_num_list);
6659         }
6660     }
6661   else
6662     {
6663       if (last_loc && !server_command)
6664         set_next_address (last_loc->gdbarch, last_loc->address);
6665
6666       if (has_disabled_by_cond_location)
6667         uiout->message (_("(*): Breakpoint condition is invalid at this "
6668                           "location.\n"));
6669     }
6670
6671   /* FIXME?  Should this be moved up so that it is only called when
6672      there have been breakpoints? */
6673   annotate_breakpoints_table_end ();
6674
6675   return nr_printable_breakpoints;
6676 }
6677
6678 /* Display the value of default-collect in a way that is generally
6679    compatible with the breakpoint list.  */
6680
6681 static void
6682 default_collect_info (void)
6683 {
6684   struct ui_out *uiout = current_uiout;
6685
6686   /* If it has no value (which is frequently the case), say nothing; a
6687      message like "No default-collect." gets in user's face when it's
6688      not wanted.  */
6689   if (!*default_collect)
6690     return;
6691
6692   /* The following phrase lines up nicely with per-tracepoint collect
6693      actions.  */
6694   uiout->text ("default collect ");
6695   uiout->field_string ("default-collect", default_collect);
6696   uiout->text (" \n");
6697 }
6698   
6699 static void
6700 info_breakpoints_command (const char *args, int from_tty)
6701 {
6702   breakpoint_1 (args, false, NULL);
6703
6704   default_collect_info ();
6705 }
6706
6707 static void
6708 info_watchpoints_command (const char *args, int from_tty)
6709 {
6710   int num_printed = breakpoint_1 (args, false, is_watchpoint);
6711   struct ui_out *uiout = current_uiout;
6712
6713   if (num_printed == 0)
6714     {
6715       if (args == NULL || *args == '\0')
6716         uiout->message ("No watchpoints.\n");
6717       else
6718         uiout->message ("No watchpoint matching '%s'.\n", args);
6719     }
6720 }
6721
6722 static void
6723 maintenance_info_breakpoints (const char *args, int from_tty)
6724 {
6725   breakpoint_1 (args, true, NULL);
6726
6727   default_collect_info ();
6728 }
6729
6730 static int
6731 breakpoint_has_pc (struct breakpoint *b,
6732                    struct program_space *pspace,
6733                    CORE_ADDR pc, struct obj_section *section)
6734 {
6735   struct bp_location *bl = b->loc;
6736
6737   for (; bl; bl = bl->next)
6738     {
6739       if (bl->pspace == pspace
6740           && bl->address == pc
6741           && (!overlay_debugging || bl->section == section))
6742         return 1;         
6743     }
6744   return 0;
6745 }
6746
6747 /* Print a message describing any user-breakpoints set at PC.  This
6748    concerns with logical breakpoints, so we match program spaces, not
6749    address spaces.  */
6750
6751 static void
6752 describe_other_breakpoints (struct gdbarch *gdbarch,
6753                             struct program_space *pspace, CORE_ADDR pc,
6754                             struct obj_section *section, int thread)
6755 {
6756   int others = 0;
6757   struct breakpoint *b;
6758
6759   ALL_BREAKPOINTS (b)
6760     others += (user_breakpoint_p (b)
6761                && breakpoint_has_pc (b, pspace, pc, section));
6762   if (others > 0)
6763     {
6764       if (others == 1)
6765         printf_filtered (_("Note: breakpoint "));
6766       else /* if (others == ???) */
6767         printf_filtered (_("Note: breakpoints "));
6768       ALL_BREAKPOINTS (b)
6769         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6770           {
6771             others--;
6772             printf_filtered ("%d", b->number);
6773             if (b->thread == -1 && thread != -1)
6774               printf_filtered (" (all threads)");
6775             else if (b->thread != -1)
6776               printf_filtered (" (thread %d)", b->thread);
6777             printf_filtered ("%s%s ",
6778                              ((b->enable_state == bp_disabled
6779                                || b->enable_state == bp_call_disabled)
6780                               ? " (disabled)"
6781                               : ""),
6782                              (others > 1) ? "," 
6783                              : ((others == 1) ? " and" : ""));
6784           }
6785       current_uiout->message (_("also set at pc %ps.\n"),
6786                               styled_string (address_style.style (),
6787                                              paddress (gdbarch, pc)));
6788     }
6789 }
6790 \f
6791
6792 /* Return true iff it is meaningful to use the address member of LOC.
6793    For some breakpoint types, the locations' address members are
6794    irrelevant and it makes no sense to attempt to compare them to
6795    other addresses (or use them for any other purpose either).
6796
6797    More specifically, software watchpoints and catchpoints that are
6798    not backed by breakpoints always have a zero valued location
6799    address and we don't want to mark breakpoints of any of these types
6800    to be a duplicate of an actual breakpoint location at address
6801    zero.  */
6802
6803 static bool
6804 bl_address_is_meaningful (bp_location *loc)
6805 {
6806   return loc->loc_type != bp_loc_other;
6807 }
6808
6809 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6810    true if LOC1 and LOC2 represent the same watchpoint location.  */
6811
6812 static int
6813 watchpoint_locations_match (struct bp_location *loc1, 
6814                             struct bp_location *loc2)
6815 {
6816   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6817   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6818
6819   /* Both of them must exist.  */
6820   gdb_assert (w1 != NULL);
6821   gdb_assert (w2 != NULL);
6822
6823   /* If the target can evaluate the condition expression in hardware,
6824      then we we need to insert both watchpoints even if they are at
6825      the same place.  Otherwise the watchpoint will only trigger when
6826      the condition of whichever watchpoint was inserted evaluates to
6827      true, not giving a chance for GDB to check the condition of the
6828      other watchpoint.  */
6829   if ((w1->cond_exp
6830        && target_can_accel_watchpoint_condition (loc1->address, 
6831                                                  loc1->length,
6832                                                  loc1->watchpoint_type,
6833                                                  w1->cond_exp.get ()))
6834       || (w2->cond_exp
6835           && target_can_accel_watchpoint_condition (loc2->address, 
6836                                                     loc2->length,
6837                                                     loc2->watchpoint_type,
6838                                                     w2->cond_exp.get ())))
6839     return 0;
6840
6841   /* Note that this checks the owner's type, not the location's.  In
6842      case the target does not support read watchpoints, but does
6843      support access watchpoints, we'll have bp_read_watchpoint
6844      watchpoints with hw_access locations.  Those should be considered
6845      duplicates of hw_read locations.  The hw_read locations will
6846      become hw_access locations later.  */
6847   return (loc1->owner->type == loc2->owner->type
6848           && loc1->pspace->aspace == loc2->pspace->aspace
6849           && loc1->address == loc2->address
6850           && loc1->length == loc2->length);
6851 }
6852
6853 /* See breakpoint.h.  */
6854
6855 int
6856 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6857                           const address_space *aspace2, CORE_ADDR addr2)
6858 {
6859   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6860            || aspace1 == aspace2)
6861           && addr1 == addr2);
6862 }
6863
6864 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6865    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6866    matches ASPACE2.  On targets that have global breakpoints, the address
6867    space doesn't really matter.  */
6868
6869 static int
6870 breakpoint_address_match_range (const address_space *aspace1,
6871                                 CORE_ADDR addr1,
6872                                 int len1, const address_space *aspace2,
6873                                 CORE_ADDR addr2)
6874 {
6875   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6876            || aspace1 == aspace2)
6877           && addr2 >= addr1 && addr2 < addr1 + len1);
6878 }
6879
6880 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6881    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6882    matches the breakpoint's address space.  On targets that have global
6883    breakpoints, the address space doesn't really matter.  */
6884
6885 static int
6886 breakpoint_location_address_match (struct bp_location *bl,
6887                                    const address_space *aspace,
6888                                    CORE_ADDR addr)
6889 {
6890   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6891                                     aspace, addr)
6892           || (bl->length
6893               && breakpoint_address_match_range (bl->pspace->aspace,
6894                                                  bl->address, bl->length,
6895                                                  aspace, addr)));
6896 }
6897
6898 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6899    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6900    match happens only if ASPACE matches the breakpoint's address
6901    space.  On targets that have global breakpoints, the address space
6902    doesn't really matter.  */
6903
6904 static int
6905 breakpoint_location_address_range_overlap (struct bp_location *bl,
6906                                            const address_space *aspace,
6907                                            CORE_ADDR addr, int len)
6908 {
6909   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6910       || bl->pspace->aspace == aspace)
6911     {
6912       int bl_len = bl->length != 0 ? bl->length : 1;
6913
6914       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6915         return 1;
6916     }
6917   return 0;
6918 }
6919
6920 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6921    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6922    true, otherwise returns false.  */
6923
6924 static int
6925 tracepoint_locations_match (struct bp_location *loc1,
6926                             struct bp_location *loc2)
6927 {
6928   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6929     /* Since tracepoint locations are never duplicated with others', tracepoint
6930        locations at the same address of different tracepoints are regarded as
6931        different locations.  */
6932     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6933   else
6934     return 0;
6935 }
6936
6937 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6938    (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
6939    the same location.  If SW_HW_BPS_MATCH is true, then software
6940    breakpoint locations and hardware breakpoint locations match,
6941    otherwise they don't.  */
6942
6943 static int
6944 breakpoint_locations_match (struct bp_location *loc1,
6945                             struct bp_location *loc2,
6946                             bool sw_hw_bps_match)
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
6965        breakpoints.  Keep this in sync with
6966        bp_location_is_less_than.  */
6967     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6968                                      loc2->pspace->aspace, loc2->address)
6969             && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
6970             && loc1->length == loc2->length);
6971 }
6972
6973 static void
6974 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6975                                int bnum, int have_bnum)
6976 {
6977   /* The longest string possibly returned by hex_string_custom
6978      is 50 chars.  These must be at least that big for safety.  */
6979   char astr1[64];
6980   char astr2[64];
6981
6982   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6983   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6984   if (have_bnum)
6985     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6986              bnum, astr1, astr2);
6987   else
6988     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6989 }
6990
6991 /* Adjust a breakpoint's address to account for architectural
6992    constraints on breakpoint placement.  Return the adjusted address.
6993    Note: Very few targets require this kind of adjustment.  For most
6994    targets, this function is simply the identity function.  */
6995
6996 static CORE_ADDR
6997 adjust_breakpoint_address (struct gdbarch *gdbarch,
6998                            CORE_ADDR bpaddr, enum bptype bptype)
6999 {
7000   if (bptype == bp_watchpoint
7001       || bptype == bp_hardware_watchpoint
7002       || bptype == bp_read_watchpoint
7003       || bptype == bp_access_watchpoint
7004       || bptype == bp_catchpoint)
7005     {
7006       /* Watchpoints and the various bp_catch_* eventpoints should not
7007          have their addresses modified.  */
7008       return bpaddr;
7009     }
7010   else if (bptype == bp_single_step)
7011     {
7012       /* Single-step breakpoints should not have their addresses
7013          modified.  If there's any architectural constrain that
7014          applies to this address, then it should have already been
7015          taken into account when the breakpoint was created in the
7016          first place.  If we didn't do this, stepping through e.g.,
7017          Thumb-2 IT blocks would break.  */
7018       return bpaddr;
7019     }
7020   else
7021     {
7022       CORE_ADDR adjusted_bpaddr = bpaddr;
7023
7024       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
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
7031       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
7032
7033       /* An adjusted breakpoint address can significantly alter
7034          a user's expectations.  Print a warning if an adjustment
7035          is required.  */
7036       if (adjusted_bpaddr != bpaddr)
7037         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7038
7039       return adjusted_bpaddr;
7040     }
7041 }
7042
7043 static bp_loc_type
7044 bp_location_from_bp_type (bptype type)
7045 {
7046   switch (type)
7047     {
7048     case bp_breakpoint:
7049     case bp_single_step:
7050     case bp_until:
7051     case bp_finish:
7052     case bp_longjmp:
7053     case bp_longjmp_resume:
7054     case bp_longjmp_call_dummy:
7055     case bp_exception:
7056     case bp_exception_resume:
7057     case bp_step_resume:
7058     case bp_hp_step_resume:
7059     case bp_watchpoint_scope:
7060     case bp_call_dummy:
7061     case bp_std_terminate:
7062     case bp_shlib_event:
7063     case bp_thread_event:
7064     case bp_overlay_event:
7065     case bp_jit_event:
7066     case bp_longjmp_master:
7067     case bp_std_terminate_master:
7068     case bp_exception_master:
7069     case bp_gnu_ifunc_resolver:
7070     case bp_gnu_ifunc_resolver_return:
7071     case bp_dprintf:
7072       return bp_loc_software_breakpoint;
7073     case bp_hardware_breakpoint:
7074       return bp_loc_hardware_breakpoint;
7075     case bp_hardware_watchpoint:
7076     case bp_read_watchpoint:
7077     case bp_access_watchpoint:
7078       return bp_loc_hardware_watchpoint;
7079     case bp_watchpoint:
7080     case bp_catchpoint:
7081     case bp_tracepoint:
7082     case bp_fast_tracepoint:
7083     case bp_static_tracepoint:
7084       return bp_loc_other;
7085     default:
7086       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7087     }
7088 }
7089
7090 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7091 {
7092   this->owner = owner;
7093   this->cond_bytecode = NULL;
7094   this->shlib_disabled = 0;
7095   this->enabled = 1;
7096   this->disabled_by_cond = false;
7097
7098   this->loc_type = type;
7099
7100   if (this->loc_type == bp_loc_software_breakpoint
7101       || this->loc_type == bp_loc_hardware_breakpoint)
7102     mark_breakpoint_location_modified (this);
7103
7104   this->refc = 1;
7105 }
7106
7107 bp_location::bp_location (breakpoint *owner)
7108   : bp_location::bp_location (owner,
7109                               bp_location_from_bp_type (owner->type))
7110 {
7111 }
7112
7113 /* Allocate a struct bp_location.  */
7114
7115 static struct bp_location *
7116 allocate_bp_location (struct breakpoint *bpt)
7117 {
7118   return bpt->ops->allocate_location (bpt);
7119 }
7120
7121 static void
7122 free_bp_location (struct bp_location *loc)
7123 {
7124   delete loc;
7125 }
7126
7127 /* Increment reference count.  */
7128
7129 static void
7130 incref_bp_location (struct bp_location *bl)
7131 {
7132   ++bl->refc;
7133 }
7134
7135 /* Decrement reference count.  If the reference count reaches 0,
7136    destroy the bp_location.  Sets *BLP to NULL.  */
7137
7138 static void
7139 decref_bp_location (struct bp_location **blp)
7140 {
7141   gdb_assert ((*blp)->refc > 0);
7142
7143   if (--(*blp)->refc == 0)
7144     free_bp_location (*blp);
7145   *blp = NULL;
7146 }
7147
7148 /* Add breakpoint B at the end of the global breakpoint chain.  */
7149
7150 static breakpoint *
7151 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7152 {
7153   struct breakpoint *b1;
7154   struct breakpoint *result = b.get ();
7155
7156   /* Add this breakpoint to the end of the chain so that a list of
7157      breakpoints will come out in order of increasing numbers.  */
7158
7159   b1 = breakpoint_chain;
7160   if (b1 == 0)
7161     breakpoint_chain = b.release ();
7162   else
7163     {
7164       while (b1->next)
7165         b1 = b1->next;
7166       b1->next = b.release ();
7167     }
7168
7169   return result;
7170 }
7171
7172 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7173
7174 static void
7175 init_raw_breakpoint_without_location (struct breakpoint *b,
7176                                       struct gdbarch *gdbarch,
7177                                       enum bptype bptype,
7178                                       const struct breakpoint_ops *ops)
7179 {
7180   gdb_assert (ops != NULL);
7181
7182   b->ops = ops;
7183   b->type = bptype;
7184   b->gdbarch = gdbarch;
7185   b->language = current_language->la_language;
7186   b->input_radix = input_radix;
7187   b->related_breakpoint = b;
7188 }
7189
7190 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7191    that has type BPTYPE and has no locations as yet.  */
7192
7193 static struct breakpoint *
7194 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7195                                      enum bptype bptype,
7196                                      const struct breakpoint_ops *ops)
7197 {
7198   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7199
7200   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7201   return add_to_breakpoint_chain (std::move (b));
7202 }
7203
7204 /* Initialize loc->function_name.  */
7205
7206 static void
7207 set_breakpoint_location_function (struct bp_location *loc)
7208 {
7209   gdb_assert (loc->owner != NULL);
7210
7211   if (loc->owner->type == bp_breakpoint
7212       || loc->owner->type == bp_hardware_breakpoint
7213       || is_tracepoint (loc->owner))
7214     {
7215       const char *function_name;
7216
7217       if (loc->msymbol != NULL
7218           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7219               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc))
7220         {
7221           struct breakpoint *b = loc->owner;
7222
7223           function_name = loc->msymbol->linkage_name ();
7224
7225           if (b->type == bp_breakpoint && b->loc == loc
7226               && loc->next == NULL && b->related_breakpoint == b)
7227             {
7228               /* Create only the whole new breakpoint of this type but do not
7229                  mess more complicated breakpoints with multiple locations.  */
7230               b->type = bp_gnu_ifunc_resolver;
7231               /* Remember the resolver's address for use by the return
7232                  breakpoint.  */
7233               loc->related_address = loc->address;
7234             }
7235         }
7236       else
7237         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7238
7239       if (function_name)
7240         loc->function_name = xstrdup (function_name);
7241     }
7242 }
7243
7244 /* Attempt to determine architecture of location identified by SAL.  */
7245 struct gdbarch *
7246 get_sal_arch (struct symtab_and_line sal)
7247 {
7248   if (sal.section)
7249     return sal.section->objfile->arch ();
7250   if (sal.symtab)
7251     return SYMTAB_OBJFILE (sal.symtab)->arch ();
7252
7253   return NULL;
7254 }
7255
7256 /* Low level routine for partially initializing a breakpoint of type
7257    BPTYPE.  The newly created breakpoint's address, section, source
7258    file name, and line number are provided by SAL.
7259
7260    It is expected that the caller will complete the initialization of
7261    the newly created breakpoint struct as well as output any status
7262    information regarding the creation of a new breakpoint.  */
7263
7264 static void
7265 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7266                      struct symtab_and_line sal, enum bptype bptype,
7267                      const struct breakpoint_ops *ops)
7268 {
7269   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7270
7271   add_location_to_breakpoint (b, &sal);
7272
7273   if (bptype != bp_catchpoint)
7274     gdb_assert (sal.pspace != NULL);
7275
7276   /* Store the program space that was used to set the breakpoint,
7277      except for ordinary breakpoints, which are independent of the
7278      program space.  */
7279   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7280     b->pspace = sal.pspace;
7281 }
7282
7283 /* set_raw_breakpoint is a low level routine for allocating and
7284    partially initializing a breakpoint of type BPTYPE.  The newly
7285    created breakpoint's address, section, source file name, and line
7286    number are provided by SAL.  The newly created and partially
7287    initialized breakpoint is added to the breakpoint chain and
7288    is also returned as the value of this function.
7289
7290    It is expected that the caller will complete the initialization of
7291    the newly created breakpoint struct as well as output any status
7292    information regarding the creation of a new breakpoint.  In
7293    particular, set_raw_breakpoint does NOT set the breakpoint
7294    number!  Care should be taken to not allow an error to occur
7295    prior to completing the initialization of the breakpoint.  If this
7296    should happen, a bogus breakpoint will be left on the chain.  */
7297
7298 struct breakpoint *
7299 set_raw_breakpoint (struct gdbarch *gdbarch,
7300                     struct symtab_and_line sal, enum bptype bptype,
7301                     const struct breakpoint_ops *ops)
7302 {
7303   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7304
7305   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7306   return add_to_breakpoint_chain (std::move (b));
7307 }
7308
7309 /* Call this routine when stepping and nexting to enable a breakpoint
7310    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7311    initiated the operation.  */
7312
7313 void
7314 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7315 {
7316   struct breakpoint *b, *b_tmp;
7317   int thread = tp->global_num;
7318
7319   /* To avoid having to rescan all objfile symbols at every step,
7320      we maintain a list of continually-inserted but always disabled
7321      longjmp "master" breakpoints.  Here, we simply create momentary
7322      clones of those and enable them for the requested thread.  */
7323   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7324     if (b->pspace == current_program_space
7325         && (b->type == bp_longjmp_master
7326             || b->type == bp_exception_master))
7327       {
7328         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7329         struct breakpoint *clone;
7330
7331         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7332            after their removal.  */
7333         clone = momentary_breakpoint_from_master (b, type,
7334                                                   &momentary_breakpoint_ops, 1);
7335         clone->thread = thread;
7336       }
7337
7338   tp->initiating_frame = frame;
7339 }
7340
7341 /* Delete all longjmp breakpoints from THREAD.  */
7342 void
7343 delete_longjmp_breakpoint (int thread)
7344 {
7345   struct breakpoint *b, *b_tmp;
7346
7347   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7348     if (b->type == bp_longjmp || b->type == bp_exception)
7349       {
7350         if (b->thread == thread)
7351           delete_breakpoint (b);
7352       }
7353 }
7354
7355 void
7356 delete_longjmp_breakpoint_at_next_stop (int thread)
7357 {
7358   struct breakpoint *b, *b_tmp;
7359
7360   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7361     if (b->type == bp_longjmp || b->type == bp_exception)
7362       {
7363         if (b->thread == thread)
7364           b->disposition = disp_del_at_next_stop;
7365       }
7366 }
7367
7368 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7369    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7370    pointer to any of them.  Return NULL if this system cannot place longjmp
7371    breakpoints.  */
7372
7373 struct breakpoint *
7374 set_longjmp_breakpoint_for_call_dummy (void)
7375 {
7376   struct breakpoint *b, *retval = NULL;
7377
7378   ALL_BREAKPOINTS (b)
7379     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7380       {
7381         struct breakpoint *new_b;
7382
7383         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7384                                                   &momentary_breakpoint_ops,
7385                                                   1);
7386         new_b->thread = inferior_thread ()->global_num;
7387
7388         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7389
7390         gdb_assert (new_b->related_breakpoint == new_b);
7391         if (retval == NULL)
7392           retval = new_b;
7393         new_b->related_breakpoint = retval;
7394         while (retval->related_breakpoint != new_b->related_breakpoint)
7395           retval = retval->related_breakpoint;
7396         retval->related_breakpoint = new_b;
7397       }
7398
7399   return retval;
7400 }
7401
7402 /* Verify all existing dummy frames and their associated breakpoints for
7403    TP.  Remove those which can no longer be found in the current frame
7404    stack.
7405
7406    You should call this function only at places where it is safe to currently
7407    unwind the whole stack.  Failed stack unwind would discard live dummy
7408    frames.  */
7409
7410 void
7411 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7412 {
7413   struct breakpoint *b, *b_tmp;
7414
7415   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7416     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7417       {
7418         struct breakpoint *dummy_b = b->related_breakpoint;
7419
7420         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7421           dummy_b = dummy_b->related_breakpoint;
7422         if (dummy_b->type != bp_call_dummy
7423             || frame_find_by_id (dummy_b->frame_id) != NULL)
7424           continue;
7425         
7426         dummy_frame_discard (dummy_b->frame_id, tp);
7427
7428         while (b->related_breakpoint != b)
7429           {
7430             if (b_tmp == b->related_breakpoint)
7431               b_tmp = b->related_breakpoint->next;
7432             delete_breakpoint (b->related_breakpoint);
7433           }
7434         delete_breakpoint (b);
7435       }
7436 }
7437
7438 void
7439 enable_overlay_breakpoints (void)
7440 {
7441   struct breakpoint *b;
7442
7443   ALL_BREAKPOINTS (b)
7444     if (b->type == bp_overlay_event)
7445     {
7446       b->enable_state = bp_enabled;
7447       update_global_location_list (UGLL_MAY_INSERT);
7448       overlay_events_enabled = 1;
7449     }
7450 }
7451
7452 void
7453 disable_overlay_breakpoints (void)
7454 {
7455   struct breakpoint *b;
7456
7457   ALL_BREAKPOINTS (b)
7458     if (b->type == bp_overlay_event)
7459     {
7460       b->enable_state = bp_disabled;
7461       update_global_location_list (UGLL_DONT_INSERT);
7462       overlay_events_enabled = 0;
7463     }
7464 }
7465
7466 /* Set an active std::terminate breakpoint for each std::terminate
7467    master breakpoint.  */
7468 void
7469 set_std_terminate_breakpoint (void)
7470 {
7471   struct breakpoint *b, *b_tmp;
7472
7473   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7474     if (b->pspace == current_program_space
7475         && b->type == bp_std_terminate_master)
7476       {
7477         momentary_breakpoint_from_master (b, bp_std_terminate,
7478                                           &momentary_breakpoint_ops, 1);
7479       }
7480 }
7481
7482 /* Delete all the std::terminate breakpoints.  */
7483 void
7484 delete_std_terminate_breakpoint (void)
7485 {
7486   struct breakpoint *b, *b_tmp;
7487
7488   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7489     if (b->type == bp_std_terminate)
7490       delete_breakpoint (b);
7491 }
7492
7493 struct breakpoint *
7494 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7495 {
7496   struct breakpoint *b;
7497
7498   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7499                                   &internal_breakpoint_ops);
7500
7501   b->enable_state = bp_enabled;
7502   /* location has to be used or breakpoint_re_set will delete me.  */
7503   b->location = new_address_location (b->loc->address, NULL, 0);
7504
7505   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7506
7507   return b;
7508 }
7509
7510 struct lang_and_radix
7511   {
7512     enum language lang;
7513     int radix;
7514   };
7515
7516 /* Create a breakpoint for JIT code registration and unregistration.  */
7517
7518 struct breakpoint *
7519 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7520 {
7521   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7522                                      &internal_breakpoint_ops);
7523 }
7524
7525 /* Remove JIT code registration and unregistration breakpoint(s).  */
7526
7527 void
7528 remove_jit_event_breakpoints (void)
7529 {
7530   struct breakpoint *b, *b_tmp;
7531
7532   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7533     if (b->type == bp_jit_event
7534         && b->loc->pspace == current_program_space)
7535       delete_breakpoint (b);
7536 }
7537
7538 void
7539 remove_solib_event_breakpoints (void)
7540 {
7541   struct breakpoint *b, *b_tmp;
7542
7543   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7544     if (b->type == bp_shlib_event
7545         && b->loc->pspace == current_program_space)
7546       delete_breakpoint (b);
7547 }
7548
7549 /* See breakpoint.h.  */
7550
7551 void
7552 remove_solib_event_breakpoints_at_next_stop (void)
7553 {
7554   struct breakpoint *b, *b_tmp;
7555
7556   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7557     if (b->type == bp_shlib_event
7558         && b->loc->pspace == current_program_space)
7559       b->disposition = disp_del_at_next_stop;
7560 }
7561
7562 /* Helper for create_solib_event_breakpoint /
7563    create_and_insert_solib_event_breakpoint.  Allows specifying which
7564    INSERT_MODE to pass through to update_global_location_list.  */
7565
7566 static struct breakpoint *
7567 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7568                                  enum ugll_insert_mode insert_mode)
7569 {
7570   struct breakpoint *b;
7571
7572   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7573                                   &internal_breakpoint_ops);
7574   update_global_location_list_nothrow (insert_mode);
7575   return b;
7576 }
7577
7578 struct breakpoint *
7579 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7580 {
7581   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7582 }
7583
7584 /* See breakpoint.h.  */
7585
7586 struct breakpoint *
7587 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7588 {
7589   struct breakpoint *b;
7590
7591   /* Explicitly tell update_global_location_list to insert
7592      locations.  */
7593   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7594   if (!b->loc->inserted)
7595     {
7596       delete_breakpoint (b);
7597       return NULL;
7598     }
7599   return b;
7600 }
7601
7602 /* Disable any breakpoints that are on code in shared libraries.  Only
7603    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7604
7605 void
7606 disable_breakpoints_in_shlibs (void)
7607 {
7608   struct bp_location *loc, **locp_tmp;
7609
7610   ALL_BP_LOCATIONS (loc, locp_tmp)
7611   {
7612     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7613     struct breakpoint *b = loc->owner;
7614
7615     /* We apply the check to all breakpoints, including disabled for
7616        those with loc->duplicate set.  This is so that when breakpoint
7617        becomes enabled, or the duplicate is removed, gdb will try to
7618        insert all breakpoints.  If we don't set shlib_disabled here,
7619        we'll try to insert those breakpoints and fail.  */
7620     if (((b->type == bp_breakpoint)
7621          || (b->type == bp_jit_event)
7622          || (b->type == bp_hardware_breakpoint)
7623          || (is_tracepoint (b)))
7624         && loc->pspace == current_program_space
7625         && !loc->shlib_disabled
7626         && solib_name_from_address (loc->pspace, loc->address)
7627         )
7628       {
7629         loc->shlib_disabled = 1;
7630       }
7631   }
7632 }
7633
7634 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7635    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7636    disabled ones can just stay disabled.  */
7637
7638 static void
7639 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7640 {
7641   struct bp_location *loc, **locp_tmp;
7642   int disabled_shlib_breaks = 0;
7643
7644   ALL_BP_LOCATIONS (loc, locp_tmp)
7645   {
7646     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7647     struct breakpoint *b = loc->owner;
7648
7649     if (solib->pspace == loc->pspace
7650         && !loc->shlib_disabled
7651         && (((b->type == bp_breakpoint
7652               || b->type == bp_jit_event
7653               || b->type == bp_hardware_breakpoint)
7654              && (loc->loc_type == bp_loc_hardware_breakpoint
7655                  || loc->loc_type == bp_loc_software_breakpoint))
7656             || is_tracepoint (b))
7657         && solib_contains_address_p (solib, loc->address))
7658       {
7659         loc->shlib_disabled = 1;
7660         /* At this point, we cannot rely on remove_breakpoint
7661            succeeding so we must mark the breakpoint as not inserted
7662            to prevent future errors occurring in remove_breakpoints.  */
7663         loc->inserted = 0;
7664
7665         /* This may cause duplicate notifications for the same breakpoint.  */
7666         gdb::observers::breakpoint_modified.notify (b);
7667
7668         if (!disabled_shlib_breaks)
7669           {
7670             target_terminal::ours_for_output ();
7671             warning (_("Temporarily disabling breakpoints "
7672                        "for unloaded shared library \"%s\""),
7673                      solib->so_name);
7674           }
7675         disabled_shlib_breaks = 1;
7676       }
7677   }
7678 }
7679
7680 /* Disable any breakpoints and tracepoints in OBJFILE upon
7681    notification of free_objfile.  Only apply to enabled breakpoints,
7682    disabled ones can just stay disabled.  */
7683
7684 static void
7685 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7686 {
7687   struct breakpoint *b;
7688
7689   if (objfile == NULL)
7690     return;
7691
7692   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7693      managed by the user with add-symbol-file/remove-symbol-file.
7694      Similarly to how breakpoints in shared libraries are handled in
7695      response to "nosharedlibrary", mark breakpoints in such modules
7696      shlib_disabled so they end up uninserted on the next global
7697      location list update.  Shared libraries not loaded by the user
7698      aren't handled here -- they're already handled in
7699      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7700      solib_unloaded observer.  We skip objfiles that are not
7701      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7702      main objfile).  */
7703   if ((objfile->flags & OBJF_SHARED) == 0
7704       || (objfile->flags & OBJF_USERLOADED) == 0)
7705     return;
7706
7707   ALL_BREAKPOINTS (b)
7708     {
7709       struct bp_location *loc;
7710       int bp_modified = 0;
7711
7712       if (!is_breakpoint (b) && !is_tracepoint (b))
7713         continue;
7714
7715       for (loc = b->loc; loc != NULL; loc = loc->next)
7716         {
7717           CORE_ADDR loc_addr = loc->address;
7718
7719           if (loc->loc_type != bp_loc_hardware_breakpoint
7720               && loc->loc_type != bp_loc_software_breakpoint)
7721             continue;
7722
7723           if (loc->shlib_disabled != 0)
7724             continue;
7725
7726           if (objfile->pspace != loc->pspace)
7727             continue;
7728
7729           if (loc->loc_type != bp_loc_hardware_breakpoint
7730               && loc->loc_type != bp_loc_software_breakpoint)
7731             continue;
7732
7733           if (is_addr_in_objfile (loc_addr, objfile))
7734             {
7735               loc->shlib_disabled = 1;
7736               /* At this point, we don't know whether the object was
7737                  unmapped from the inferior or not, so leave the
7738                  inserted flag alone.  We'll handle failure to
7739                  uninsert quietly, in case the object was indeed
7740                  unmapped.  */
7741
7742               mark_breakpoint_location_modified (loc);
7743
7744               bp_modified = 1;
7745             }
7746         }
7747
7748       if (bp_modified)
7749         gdb::observers::breakpoint_modified.notify (b);
7750     }
7751 }
7752
7753 /* FORK & VFORK catchpoints.  */
7754
7755 /* An instance of this type is used to represent a fork or vfork
7756    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7757    to CATCH_FORK_BREAKPOINT_OPS.  */
7758
7759 struct fork_catchpoint : public breakpoint
7760 {
7761   /* Process id of a child process whose forking triggered this
7762      catchpoint.  This field is only valid immediately after this
7763      catchpoint has triggered.  */
7764   ptid_t forked_inferior_pid;
7765 };
7766
7767 /* Implement the "insert" breakpoint_ops method for fork
7768    catchpoints.  */
7769
7770 static int
7771 insert_catch_fork (struct bp_location *bl)
7772 {
7773   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7774 }
7775
7776 /* Implement the "remove" breakpoint_ops method for fork
7777    catchpoints.  */
7778
7779 static int
7780 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7781 {
7782   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7783 }
7784
7785 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7786    catchpoints.  */
7787
7788 static int
7789 breakpoint_hit_catch_fork (const struct bp_location *bl,
7790                            const address_space *aspace, CORE_ADDR bp_addr,
7791                            const struct target_waitstatus *ws)
7792 {
7793   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7794
7795   if (ws->kind != TARGET_WAITKIND_FORKED)
7796     return 0;
7797
7798   c->forked_inferior_pid = ws->value.related_pid;
7799   return 1;
7800 }
7801
7802 /* Implement the "print_it" breakpoint_ops method for fork
7803    catchpoints.  */
7804
7805 static enum print_stop_action
7806 print_it_catch_fork (bpstat bs)
7807 {
7808   struct ui_out *uiout = current_uiout;
7809   struct breakpoint *b = bs->breakpoint_at;
7810   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7811
7812   annotate_catchpoint (b->number);
7813   maybe_print_thread_hit_breakpoint (uiout);
7814   if (b->disposition == disp_del)
7815     uiout->text ("Temporary catchpoint ");
7816   else
7817     uiout->text ("Catchpoint ");
7818   if (uiout->is_mi_like_p ())
7819     {
7820       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7821       uiout->field_string ("disp", bpdisp_text (b->disposition));
7822     }
7823   uiout->field_signed ("bkptno", b->number);
7824   uiout->text (" (forked process ");
7825   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7826   uiout->text ("), ");
7827   return PRINT_SRC_AND_LOC;
7828 }
7829
7830 /* Implement the "print_one" breakpoint_ops method for fork
7831    catchpoints.  */
7832
7833 static void
7834 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7835 {
7836   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7837   struct value_print_options opts;
7838   struct ui_out *uiout = current_uiout;
7839
7840   get_user_print_options (&opts);
7841
7842   /* Field 4, the address, is omitted (which makes the columns not
7843      line up too nicely with the headers, but the effect is relatively
7844      readable).  */
7845   if (opts.addressprint)
7846     uiout->field_skip ("addr");
7847   annotate_field (5);
7848   uiout->text ("fork");
7849   if (c->forked_inferior_pid != null_ptid)
7850     {
7851       uiout->text (", process ");
7852       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7853       uiout->spaces (1);
7854     }
7855
7856   if (uiout->is_mi_like_p ())
7857     uiout->field_string ("catch-type", "fork");
7858 }
7859
7860 /* Implement the "print_mention" breakpoint_ops method for fork
7861    catchpoints.  */
7862
7863 static void
7864 print_mention_catch_fork (struct breakpoint *b)
7865 {
7866   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7867 }
7868
7869 /* Implement the "print_recreate" breakpoint_ops method for fork
7870    catchpoints.  */
7871
7872 static void
7873 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7874 {
7875   fprintf_unfiltered (fp, "catch fork");
7876   print_recreate_thread (b, fp);
7877 }
7878
7879 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7880
7881 static struct breakpoint_ops catch_fork_breakpoint_ops;
7882
7883 /* Implement the "insert" breakpoint_ops method for vfork
7884    catchpoints.  */
7885
7886 static int
7887 insert_catch_vfork (struct bp_location *bl)
7888 {
7889   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7890 }
7891
7892 /* Implement the "remove" breakpoint_ops method for vfork
7893    catchpoints.  */
7894
7895 static int
7896 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7897 {
7898   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7899 }
7900
7901 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7902    catchpoints.  */
7903
7904 static int
7905 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7906                             const address_space *aspace, CORE_ADDR bp_addr,
7907                             const struct target_waitstatus *ws)
7908 {
7909   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7910
7911   if (ws->kind != TARGET_WAITKIND_VFORKED)
7912     return 0;
7913
7914   c->forked_inferior_pid = ws->value.related_pid;
7915   return 1;
7916 }
7917
7918 /* Implement the "print_it" breakpoint_ops method for vfork
7919    catchpoints.  */
7920
7921 static enum print_stop_action
7922 print_it_catch_vfork (bpstat bs)
7923 {
7924   struct ui_out *uiout = current_uiout;
7925   struct breakpoint *b = bs->breakpoint_at;
7926   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7927
7928   annotate_catchpoint (b->number);
7929   maybe_print_thread_hit_breakpoint (uiout);
7930   if (b->disposition == disp_del)
7931     uiout->text ("Temporary catchpoint ");
7932   else
7933     uiout->text ("Catchpoint ");
7934   if (uiout->is_mi_like_p ())
7935     {
7936       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7937       uiout->field_string ("disp", bpdisp_text (b->disposition));
7938     }
7939   uiout->field_signed ("bkptno", b->number);
7940   uiout->text (" (vforked process ");
7941   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7942   uiout->text ("), ");
7943   return PRINT_SRC_AND_LOC;
7944 }
7945
7946 /* Implement the "print_one" breakpoint_ops method for vfork
7947    catchpoints.  */
7948
7949 static void
7950 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7951 {
7952   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7953   struct value_print_options opts;
7954   struct ui_out *uiout = current_uiout;
7955
7956   get_user_print_options (&opts);
7957   /* Field 4, the address, is omitted (which makes the columns not
7958      line up too nicely with the headers, but the effect is relatively
7959      readable).  */
7960   if (opts.addressprint)
7961     uiout->field_skip ("addr");
7962   annotate_field (5);
7963   uiout->text ("vfork");
7964   if (c->forked_inferior_pid != null_ptid)
7965     {
7966       uiout->text (", process ");
7967       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7968       uiout->spaces (1);
7969     }
7970
7971   if (uiout->is_mi_like_p ())
7972     uiout->field_string ("catch-type", "vfork");
7973 }
7974
7975 /* Implement the "print_mention" breakpoint_ops method for vfork
7976    catchpoints.  */
7977
7978 static void
7979 print_mention_catch_vfork (struct breakpoint *b)
7980 {
7981   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7982 }
7983
7984 /* Implement the "print_recreate" breakpoint_ops method for vfork
7985    catchpoints.  */
7986
7987 static void
7988 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7989 {
7990   fprintf_unfiltered (fp, "catch vfork");
7991   print_recreate_thread (b, fp);
7992 }
7993
7994 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7995
7996 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7997
7998 /* An instance of this type is used to represent an solib catchpoint.
7999    A breakpoint is really of this type iff its ops pointer points to
8000    CATCH_SOLIB_BREAKPOINT_OPS.  */
8001
8002 struct solib_catchpoint : public breakpoint
8003 {
8004   ~solib_catchpoint () override;
8005
8006   /* True for "catch load", false for "catch unload".  */
8007   bool is_load;
8008
8009   /* Regular expression to match, if any.  COMPILED is only valid when
8010      REGEX is non-NULL.  */
8011   char *regex;
8012   std::unique_ptr<compiled_regex> compiled;
8013 };
8014
8015 solib_catchpoint::~solib_catchpoint ()
8016 {
8017   xfree (this->regex);
8018 }
8019
8020 static int
8021 insert_catch_solib (struct bp_location *ignore)
8022 {
8023   return 0;
8024 }
8025
8026 static int
8027 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8028 {
8029   return 0;
8030 }
8031
8032 static int
8033 breakpoint_hit_catch_solib (const struct bp_location *bl,
8034                             const address_space *aspace,
8035                             CORE_ADDR bp_addr,
8036                             const struct target_waitstatus *ws)
8037 {
8038   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8039   struct breakpoint *other;
8040
8041   if (ws->kind == TARGET_WAITKIND_LOADED)
8042     return 1;
8043
8044   ALL_BREAKPOINTS (other)
8045   {
8046     struct bp_location *other_bl;
8047
8048     if (other == bl->owner)
8049       continue;
8050
8051     if (other->type != bp_shlib_event)
8052       continue;
8053
8054     if (self->pspace != NULL && other->pspace != self->pspace)
8055       continue;
8056
8057     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8058       {
8059         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8060           return 1;
8061       }
8062   }
8063
8064   return 0;
8065 }
8066
8067 static void
8068 check_status_catch_solib (struct bpstats *bs)
8069 {
8070   struct solib_catchpoint *self
8071     = (struct solib_catchpoint *) bs->breakpoint_at;
8072
8073   if (self->is_load)
8074     {
8075       for (so_list *iter : current_program_space->added_solibs)
8076         {
8077           if (!self->regex
8078               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8079             return;
8080         }
8081     }
8082   else
8083     {
8084       for (const std::string &iter : current_program_space->deleted_solibs)
8085         {
8086           if (!self->regex
8087               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8088             return;
8089         }
8090     }
8091
8092   bs->stop = 0;
8093   bs->print_it = print_it_noop;
8094 }
8095
8096 static enum print_stop_action
8097 print_it_catch_solib (bpstat bs)
8098 {
8099   struct breakpoint *b = bs->breakpoint_at;
8100   struct ui_out *uiout = current_uiout;
8101
8102   annotate_catchpoint (b->number);
8103   maybe_print_thread_hit_breakpoint (uiout);
8104   if (b->disposition == disp_del)
8105     uiout->text ("Temporary catchpoint ");
8106   else
8107     uiout->text ("Catchpoint ");
8108   uiout->field_signed ("bkptno", b->number);
8109   uiout->text ("\n");
8110   if (uiout->is_mi_like_p ())
8111     uiout->field_string ("disp", bpdisp_text (b->disposition));
8112   print_solib_event (1);
8113   return PRINT_SRC_AND_LOC;
8114 }
8115
8116 static void
8117 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8118 {
8119   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8120   struct value_print_options opts;
8121   struct ui_out *uiout = current_uiout;
8122
8123   get_user_print_options (&opts);
8124   /* Field 4, the address, is omitted (which makes the columns not
8125      line up too nicely with the headers, but the effect is relatively
8126      readable).  */
8127   if (opts.addressprint)
8128     {
8129       annotate_field (4);
8130       uiout->field_skip ("addr");
8131     }
8132
8133   std::string msg;
8134   annotate_field (5);
8135   if (self->is_load)
8136     {
8137       if (self->regex)
8138         msg = string_printf (_("load of library matching %s"), self->regex);
8139       else
8140         msg = _("load of library");
8141     }
8142   else
8143     {
8144       if (self->regex)
8145         msg = string_printf (_("unload of library matching %s"), self->regex);
8146       else
8147         msg = _("unload of library");
8148     }
8149   uiout->field_string ("what", msg);
8150
8151   if (uiout->is_mi_like_p ())
8152     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8153 }
8154
8155 static void
8156 print_mention_catch_solib (struct breakpoint *b)
8157 {
8158   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8159
8160   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8161                    self->is_load ? "load" : "unload");
8162 }
8163
8164 static void
8165 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8166 {
8167   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8168
8169   fprintf_unfiltered (fp, "%s %s",
8170                       b->disposition == disp_del ? "tcatch" : "catch",
8171                       self->is_load ? "load" : "unload");
8172   if (self->regex)
8173     fprintf_unfiltered (fp, " %s", self->regex);
8174   fprintf_unfiltered (fp, "\n");
8175 }
8176
8177 static struct breakpoint_ops catch_solib_breakpoint_ops;
8178
8179 /* See breakpoint.h.  */
8180
8181 void
8182 add_solib_catchpoint (const char *arg, bool is_load, bool is_temp, bool enabled)
8183 {
8184   struct gdbarch *gdbarch = get_current_arch ();
8185
8186   if (!arg)
8187     arg = "";
8188   arg = skip_spaces (arg);
8189
8190   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8191
8192   if (*arg != '\0')
8193     {
8194       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8195                                              _("Invalid regexp")));
8196       c->regex = xstrdup (arg);
8197     }
8198
8199   c->is_load = is_load;
8200   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8201                    &catch_solib_breakpoint_ops);
8202
8203   c->enable_state = enabled ? bp_enabled : bp_disabled;
8204
8205   install_breakpoint (0, std::move (c), 1);
8206 }
8207
8208 /* A helper function that does all the work for "catch load" and
8209    "catch unload".  */
8210
8211 static void
8212 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8213                       struct cmd_list_element *command)
8214 {
8215   const int enabled = 1;
8216   bool temp = get_cmd_context (command) == CATCH_TEMPORARY;
8217
8218   add_solib_catchpoint (arg, is_load, temp, enabled);
8219 }
8220
8221 static void
8222 catch_load_command_1 (const char *arg, int from_tty,
8223                       struct cmd_list_element *command)
8224 {
8225   catch_load_or_unload (arg, from_tty, 1, command);
8226 }
8227
8228 static void
8229 catch_unload_command_1 (const char *arg, int from_tty,
8230                         struct cmd_list_element *command)
8231 {
8232   catch_load_or_unload (arg, from_tty, 0, command);
8233 }
8234
8235 /* See breakpoint.h.  */
8236
8237 void
8238 init_catchpoint (struct breakpoint *b,
8239                  struct gdbarch *gdbarch, bool temp,
8240                  const char *cond_string,
8241                  const struct breakpoint_ops *ops)
8242 {
8243   symtab_and_line sal;
8244   sal.pspace = current_program_space;
8245
8246   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8247
8248   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8249   b->disposition = temp ? disp_del : disp_donttouch;
8250 }
8251
8252 void
8253 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8254 {
8255   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8256   set_breakpoint_number (internal, b);
8257   if (is_tracepoint (b))
8258     set_tracepoint_count (breakpoint_count);
8259   if (!internal)
8260     mention (b);
8261   gdb::observers::breakpoint_created.notify (b);
8262
8263   if (update_gll)
8264     update_global_location_list (UGLL_MAY_INSERT);
8265 }
8266
8267 static void
8268 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8269                                     bool temp, const char *cond_string,
8270                                     const struct breakpoint_ops *ops)
8271 {
8272   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8273
8274   init_catchpoint (c.get (), gdbarch, temp, cond_string, ops);
8275
8276   c->forked_inferior_pid = null_ptid;
8277
8278   install_breakpoint (0, std::move (c), 1);
8279 }
8280
8281 /* Exec catchpoints.  */
8282
8283 /* An instance of this type is used to represent an exec catchpoint.
8284    A breakpoint is really of this type iff its ops pointer points to
8285    CATCH_EXEC_BREAKPOINT_OPS.  */
8286
8287 struct exec_catchpoint : public breakpoint
8288 {
8289   ~exec_catchpoint () override;
8290
8291   /* Filename of a program whose exec triggered this catchpoint.
8292      This field is only valid immediately after this catchpoint has
8293      triggered.  */
8294   char *exec_pathname;
8295 };
8296
8297 /* Exec catchpoint destructor.  */
8298
8299 exec_catchpoint::~exec_catchpoint ()
8300 {
8301   xfree (this->exec_pathname);
8302 }
8303
8304 static int
8305 insert_catch_exec (struct bp_location *bl)
8306 {
8307   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8308 }
8309
8310 static int
8311 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8312 {
8313   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8314 }
8315
8316 static int
8317 breakpoint_hit_catch_exec (const struct bp_location *bl,
8318                            const address_space *aspace, CORE_ADDR bp_addr,
8319                            const struct target_waitstatus *ws)
8320 {
8321   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8322
8323   if (ws->kind != TARGET_WAITKIND_EXECD)
8324     return 0;
8325
8326   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8327   return 1;
8328 }
8329
8330 static enum print_stop_action
8331 print_it_catch_exec (bpstat bs)
8332 {
8333   struct ui_out *uiout = current_uiout;
8334   struct breakpoint *b = bs->breakpoint_at;
8335   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8336
8337   annotate_catchpoint (b->number);
8338   maybe_print_thread_hit_breakpoint (uiout);
8339   if (b->disposition == disp_del)
8340     uiout->text ("Temporary catchpoint ");
8341   else
8342     uiout->text ("Catchpoint ");
8343   if (uiout->is_mi_like_p ())
8344     {
8345       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8346       uiout->field_string ("disp", bpdisp_text (b->disposition));
8347     }
8348   uiout->field_signed ("bkptno", b->number);
8349   uiout->text (" (exec'd ");
8350   uiout->field_string ("new-exec", c->exec_pathname);
8351   uiout->text ("), ");
8352
8353   return PRINT_SRC_AND_LOC;
8354 }
8355
8356 static void
8357 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8358 {
8359   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8360   struct value_print_options opts;
8361   struct ui_out *uiout = current_uiout;
8362
8363   get_user_print_options (&opts);
8364
8365   /* Field 4, the address, is omitted (which makes the columns
8366      not line up too nicely with the headers, but the effect
8367      is relatively readable).  */
8368   if (opts.addressprint)
8369     uiout->field_skip ("addr");
8370   annotate_field (5);
8371   uiout->text ("exec");
8372   if (c->exec_pathname != NULL)
8373     {
8374       uiout->text (", program \"");
8375       uiout->field_string ("what", c->exec_pathname);
8376       uiout->text ("\" ");
8377     }
8378
8379   if (uiout->is_mi_like_p ())
8380     uiout->field_string ("catch-type", "exec");
8381 }
8382
8383 static void
8384 print_mention_catch_exec (struct breakpoint *b)
8385 {
8386   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8387 }
8388
8389 /* Implement the "print_recreate" breakpoint_ops method for exec
8390    catchpoints.  */
8391
8392 static void
8393 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8394 {
8395   fprintf_unfiltered (fp, "catch exec");
8396   print_recreate_thread (b, fp);
8397 }
8398
8399 static struct breakpoint_ops catch_exec_breakpoint_ops;
8400
8401 static int
8402 hw_breakpoint_used_count (void)
8403 {
8404   int i = 0;
8405   struct breakpoint *b;
8406   struct bp_location *bl;
8407
8408   ALL_BREAKPOINTS (b)
8409   {
8410     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8411       for (bl = b->loc; bl; bl = bl->next)
8412         {
8413           /* Special types of hardware breakpoints may use more than
8414              one register.  */
8415           i += b->ops->resources_needed (bl);
8416         }
8417   }
8418
8419   return i;
8420 }
8421
8422 /* Returns the resources B would use if it were a hardware
8423    watchpoint.  */
8424
8425 static int
8426 hw_watchpoint_use_count (struct breakpoint *b)
8427 {
8428   int i = 0;
8429   struct bp_location *bl;
8430
8431   if (!breakpoint_enabled (b))
8432     return 0;
8433
8434   for (bl = b->loc; bl; bl = bl->next)
8435     {
8436       /* Special types of hardware watchpoints may use more than
8437          one register.  */
8438       i += b->ops->resources_needed (bl);
8439     }
8440
8441   return i;
8442 }
8443
8444 /* Returns the sum the used resources of all hardware watchpoints of
8445    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8446    the sum of the used resources of all hardware watchpoints of other
8447    types _not_ TYPE.  */
8448
8449 static int
8450 hw_watchpoint_used_count_others (struct breakpoint *except,
8451                                  enum bptype type, int *other_type_used)
8452 {
8453   int i = 0;
8454   struct breakpoint *b;
8455
8456   *other_type_used = 0;
8457   ALL_BREAKPOINTS (b)
8458     {
8459       if (b == except)
8460         continue;
8461       if (!breakpoint_enabled (b))
8462         continue;
8463
8464       if (b->type == type)
8465         i += hw_watchpoint_use_count (b);
8466       else if (is_hardware_watchpoint (b))
8467         *other_type_used = 1;
8468     }
8469
8470   return i;
8471 }
8472
8473 void
8474 disable_watchpoints_before_interactive_call_start (void)
8475 {
8476   struct breakpoint *b;
8477
8478   ALL_BREAKPOINTS (b)
8479   {
8480     if (is_watchpoint (b) && breakpoint_enabled (b))
8481       {
8482         b->enable_state = bp_call_disabled;
8483         update_global_location_list (UGLL_DONT_INSERT);
8484       }
8485   }
8486 }
8487
8488 void
8489 enable_watchpoints_after_interactive_call_stop (void)
8490 {
8491   struct breakpoint *b;
8492
8493   ALL_BREAKPOINTS (b)
8494   {
8495     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8496       {
8497         b->enable_state = bp_enabled;
8498         update_global_location_list (UGLL_MAY_INSERT);
8499       }
8500   }
8501 }
8502
8503 void
8504 disable_breakpoints_before_startup (void)
8505 {
8506   current_program_space->executing_startup = 1;
8507   update_global_location_list (UGLL_DONT_INSERT);
8508 }
8509
8510 void
8511 enable_breakpoints_after_startup (void)
8512 {
8513   current_program_space->executing_startup = 0;
8514   breakpoint_re_set ();
8515 }
8516
8517 /* Create a new single-step breakpoint for thread THREAD, with no
8518    locations.  */
8519
8520 static struct breakpoint *
8521 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8522 {
8523   std::unique_ptr<breakpoint> b (new breakpoint ());
8524
8525   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8526                                         &momentary_breakpoint_ops);
8527
8528   b->disposition = disp_donttouch;
8529   b->frame_id = null_frame_id;
8530
8531   b->thread = thread;
8532   gdb_assert (b->thread != 0);
8533
8534   return add_to_breakpoint_chain (std::move (b));
8535 }
8536
8537 /* Set a momentary breakpoint of type TYPE at address specified by
8538    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8539    frame.  */
8540
8541 breakpoint_up
8542 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8543                           struct frame_id frame_id, enum bptype type)
8544 {
8545   struct breakpoint *b;
8546
8547   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8548      tail-called one.  */
8549   gdb_assert (!frame_id_artificial_p (frame_id));
8550
8551   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8552   b->enable_state = bp_enabled;
8553   b->disposition = disp_donttouch;
8554   b->frame_id = frame_id;
8555
8556   b->thread = inferior_thread ()->global_num;
8557
8558   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8559
8560   return breakpoint_up (b);
8561 }
8562
8563 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8564    The new breakpoint will have type TYPE, use OPS as its
8565    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8566
8567 static struct breakpoint *
8568 momentary_breakpoint_from_master (struct breakpoint *orig,
8569                                   enum bptype type,
8570                                   const struct breakpoint_ops *ops,
8571                                   int loc_enabled)
8572 {
8573   struct breakpoint *copy;
8574
8575   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8576   copy->loc = allocate_bp_location (copy);
8577   set_breakpoint_location_function (copy->loc);
8578
8579   copy->loc->gdbarch = orig->loc->gdbarch;
8580   copy->loc->requested_address = orig->loc->requested_address;
8581   copy->loc->address = orig->loc->address;
8582   copy->loc->section = orig->loc->section;
8583   copy->loc->pspace = orig->loc->pspace;
8584   copy->loc->probe = orig->loc->probe;
8585   copy->loc->line_number = orig->loc->line_number;
8586   copy->loc->symtab = orig->loc->symtab;
8587   copy->loc->enabled = loc_enabled;
8588   copy->frame_id = orig->frame_id;
8589   copy->thread = orig->thread;
8590   copy->pspace = orig->pspace;
8591
8592   copy->enable_state = bp_enabled;
8593   copy->disposition = disp_donttouch;
8594   copy->number = internal_breakpoint_number--;
8595
8596   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8597   return copy;
8598 }
8599
8600 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8601    ORIG is NULL.  */
8602
8603 struct breakpoint *
8604 clone_momentary_breakpoint (struct breakpoint *orig)
8605 {
8606   /* If there's nothing to clone, then return nothing.  */
8607   if (orig == NULL)
8608     return NULL;
8609
8610   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8611 }
8612
8613 breakpoint_up
8614 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8615                                 enum bptype type)
8616 {
8617   struct symtab_and_line sal;
8618
8619   sal = find_pc_line (pc, 0);
8620   sal.pc = pc;
8621   sal.section = find_pc_overlay (pc);
8622   sal.explicit_pc = 1;
8623
8624   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8625 }
8626 \f
8627
8628 /* Tell the user we have just set a breakpoint B.  */
8629
8630 static void
8631 mention (struct breakpoint *b)
8632 {
8633   b->ops->print_mention (b);
8634   current_uiout->text ("\n");
8635 }
8636 \f
8637
8638 static bool bp_loc_is_permanent (struct bp_location *loc);
8639
8640 /* Handle "set breakpoint auto-hw on".
8641
8642    If the explicitly specified breakpoint type is not hardware
8643    breakpoint, check the memory map to see whether the breakpoint
8644    address is in read-only memory.
8645
8646    - location type is not hardware breakpoint, memory is read-only.
8647    We change the type of the location to hardware breakpoint.
8648
8649    - location type is hardware breakpoint, memory is read-write.  This
8650    means we've previously made the location hardware one, but then the
8651    memory map changed, so we undo.
8652 */
8653
8654 static void
8655 handle_automatic_hardware_breakpoints (bp_location *bl)
8656 {
8657   if (automatic_hardware_breakpoints
8658       && bl->owner->type != bp_hardware_breakpoint
8659       && (bl->loc_type == bp_loc_software_breakpoint
8660           || bl->loc_type == bp_loc_hardware_breakpoint))
8661     {
8662       /* When breakpoints are removed, remove_breakpoints will use
8663          location types we've just set here, the only possible problem
8664          is that memory map has changed during running program, but
8665          it's not going to work anyway with current gdb.  */
8666       mem_region *mr = lookup_mem_region (bl->address);
8667
8668       if (mr != nullptr)
8669         {
8670           enum bp_loc_type new_type;
8671
8672           if (mr->attrib.mode != MEM_RW)
8673             new_type = bp_loc_hardware_breakpoint;
8674           else
8675             new_type = bp_loc_software_breakpoint;
8676
8677           if (new_type != bl->loc_type)
8678             {
8679               static bool said = false;
8680
8681               bl->loc_type = new_type;
8682               if (!said)
8683                 {
8684                   fprintf_filtered (gdb_stdout,
8685                                     _("Note: automatically using "
8686                                       "hardware breakpoints for "
8687                                       "read-only addresses.\n"));
8688                   said = true;
8689                 }
8690             }
8691         }
8692     }
8693 }
8694
8695 static struct bp_location *
8696 add_location_to_breakpoint (struct breakpoint *b,
8697                             const struct symtab_and_line *sal)
8698 {
8699   struct bp_location *loc, **tmp;
8700   CORE_ADDR adjusted_address;
8701   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8702
8703   if (loc_gdbarch == NULL)
8704     loc_gdbarch = b->gdbarch;
8705
8706   /* Adjust the breakpoint's address prior to allocating a location.
8707      Once we call allocate_bp_location(), that mostly uninitialized
8708      location will be placed on the location chain.  Adjustment of the
8709      breakpoint may cause target_read_memory() to be called and we do
8710      not want its scan of the location chain to find a breakpoint and
8711      location that's only been partially initialized.  */
8712   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8713                                                 sal->pc, b->type);
8714
8715   /* Sort the locations by their ADDRESS.  */
8716   loc = allocate_bp_location (b);
8717   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8718        tmp = &((*tmp)->next))
8719     ;
8720   loc->next = *tmp;
8721   *tmp = loc;
8722
8723   loc->requested_address = sal->pc;
8724   loc->address = adjusted_address;
8725   loc->pspace = sal->pspace;
8726   loc->probe.prob = sal->prob;
8727   loc->probe.objfile = sal->objfile;
8728   gdb_assert (loc->pspace != NULL);
8729   loc->section = sal->section;
8730   loc->gdbarch = loc_gdbarch;
8731   loc->line_number = sal->line;
8732   loc->symtab = sal->symtab;
8733   loc->symbol = sal->symbol;
8734   loc->msymbol = sal->msymbol;
8735   loc->objfile = sal->objfile;
8736
8737   set_breakpoint_location_function (loc);
8738
8739   /* While by definition, permanent breakpoints are already present in the
8740      code, we don't mark the location as inserted.  Normally one would expect
8741      that GDB could rely on that breakpoint instruction to stop the program,
8742      thus removing the need to insert its own breakpoint, except that executing
8743      the breakpoint instruction can kill the target instead of reporting a
8744      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8745      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8746      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8747      breakpoint be inserted normally results in QEMU knowing about the GDB
8748      breakpoint, and thus trap before the breakpoint instruction is executed.
8749      (If GDB later needs to continue execution past the permanent breakpoint,
8750      it manually increments the PC, thus avoiding executing the breakpoint
8751      instruction.)  */
8752   if (bp_loc_is_permanent (loc))
8753     loc->permanent = 1;
8754
8755   return loc;
8756 }
8757 \f
8758
8759 /* Return true if LOC is pointing to a permanent breakpoint,
8760    return false otherwise.  */
8761
8762 static bool
8763 bp_loc_is_permanent (struct bp_location *loc)
8764 {
8765   gdb_assert (loc != NULL);
8766
8767   /* If we have a non-breakpoint-backed catchpoint or a software
8768      watchpoint, just return 0.  We should not attempt to read from
8769      the addresses the locations of these breakpoint types point to.
8770      gdbarch_program_breakpoint_here_p, below, will attempt to read
8771      memory.  */
8772   if (!bl_address_is_meaningful (loc))
8773     return false;
8774
8775   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8776   switch_to_program_space_and_thread (loc->pspace);
8777   return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8778 }
8779
8780 /* Build a command list for the dprintf corresponding to the current
8781    settings of the dprintf style options.  */
8782
8783 static void
8784 update_dprintf_command_list (struct breakpoint *b)
8785 {
8786   char *dprintf_args = b->extra_string;
8787   char *printf_line = NULL;
8788
8789   if (!dprintf_args)
8790     return;
8791
8792   dprintf_args = skip_spaces (dprintf_args);
8793
8794   /* Allow a comma, as it may have terminated a location, but don't
8795      insist on it.  */
8796   if (*dprintf_args == ',')
8797     ++dprintf_args;
8798   dprintf_args = skip_spaces (dprintf_args);
8799
8800   if (*dprintf_args != '"')
8801     error (_("Bad format string, missing '\"'."));
8802
8803   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8804     printf_line = xstrprintf ("printf %s", dprintf_args);
8805   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8806     {
8807       if (!dprintf_function)
8808         error (_("No function supplied for dprintf call"));
8809
8810       if (dprintf_channel && strlen (dprintf_channel) > 0)
8811         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8812                                   dprintf_function,
8813                                   dprintf_channel,
8814                                   dprintf_args);
8815       else
8816         printf_line = xstrprintf ("call (void) %s (%s)",
8817                                   dprintf_function,
8818                                   dprintf_args);
8819     }
8820   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8821     {
8822       if (target_can_run_breakpoint_commands ())
8823         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8824       else
8825         {
8826           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8827           printf_line = xstrprintf ("printf %s", dprintf_args);
8828         }
8829     }
8830   else
8831     internal_error (__FILE__, __LINE__,
8832                     _("Invalid dprintf style."));
8833
8834   gdb_assert (printf_line != NULL);
8835
8836   /* Manufacture a printf sequence.  */
8837   struct command_line *printf_cmd_line
8838     = new struct command_line (simple_control, printf_line);
8839   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8840                                                     command_lines_deleter ()));
8841 }
8842
8843 /* Update all dprintf commands, making their command lists reflect
8844    current style settings.  */
8845
8846 static void
8847 update_dprintf_commands (const char *args, int from_tty,
8848                          struct cmd_list_element *c)
8849 {
8850   struct breakpoint *b;
8851
8852   ALL_BREAKPOINTS (b)
8853     {
8854       if (b->type == bp_dprintf)
8855         update_dprintf_command_list (b);
8856     }
8857 }
8858
8859 /* Create a breakpoint with SAL as location.  Use LOCATION
8860    as a description of the location, and COND_STRING
8861    as condition expression.  If LOCATION is NULL then create an
8862    "address location" from the address in the SAL.  */
8863
8864 static void
8865 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8866                      gdb::array_view<const symtab_and_line> sals,
8867                      event_location_up &&location,
8868                      gdb::unique_xmalloc_ptr<char> filter,
8869                      gdb::unique_xmalloc_ptr<char> cond_string,
8870                      gdb::unique_xmalloc_ptr<char> extra_string,
8871                      enum bptype type, enum bpdisp disposition,
8872                      int thread, int task, int ignore_count,
8873                      const struct breakpoint_ops *ops, int from_tty,
8874                      int enabled, int internal, unsigned flags,
8875                      int display_canonical)
8876 {
8877   int i;
8878
8879   if (type == bp_hardware_breakpoint)
8880     {
8881       int target_resources_ok;
8882
8883       i = hw_breakpoint_used_count ();
8884       target_resources_ok =
8885         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8886                                             i + 1, 0);
8887       if (target_resources_ok == 0)
8888         error (_("No hardware breakpoint support in the target."));
8889       else if (target_resources_ok < 0)
8890         error (_("Hardware breakpoints used exceeds limit."));
8891     }
8892
8893   gdb_assert (!sals.empty ());
8894
8895   for (const auto &sal : sals)
8896     {
8897       struct bp_location *loc;
8898
8899       if (from_tty)
8900         {
8901           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8902           if (!loc_gdbarch)
8903             loc_gdbarch = gdbarch;
8904
8905           describe_other_breakpoints (loc_gdbarch,
8906                                       sal.pspace, sal.pc, sal.section, thread);
8907         }
8908
8909       if (&sal == &sals[0])
8910         {
8911           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8912           b->thread = thread;
8913           b->task = task;
8914
8915           b->cond_string = cond_string.release ();
8916           b->extra_string = extra_string.release ();
8917           b->ignore_count = ignore_count;
8918           b->enable_state = enabled ? bp_enabled : bp_disabled;
8919           b->disposition = disposition;
8920
8921           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8922             b->loc->inserted = 1;
8923
8924           if (type == bp_static_tracepoint)
8925             {
8926               struct tracepoint *t = (struct tracepoint *) b;
8927               struct static_tracepoint_marker marker;
8928
8929               if (strace_marker_p (b))
8930                 {
8931                   /* We already know the marker exists, otherwise, we
8932                      wouldn't see a sal for it.  */
8933                   const char *p
8934                     = &event_location_to_string (b->location.get ())[3];
8935                   const char *endp;
8936
8937                   p = skip_spaces (p);
8938
8939                   endp = skip_to_space (p);
8940
8941                   t->static_trace_marker_id.assign (p, endp - p);
8942
8943                   printf_filtered (_("Probed static tracepoint "
8944                                      "marker \"%s\"\n"),
8945                                    t->static_trace_marker_id.c_str ());
8946                 }
8947               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8948                 {
8949                   t->static_trace_marker_id = std::move (marker.str_id);
8950
8951                   printf_filtered (_("Probed static tracepoint "
8952                                      "marker \"%s\"\n"),
8953                                    t->static_trace_marker_id.c_str ());
8954                 }
8955               else
8956                 warning (_("Couldn't determine the static "
8957                            "tracepoint marker to probe"));
8958             }
8959
8960           loc = b->loc;
8961         }
8962       else
8963         {
8964           loc = add_location_to_breakpoint (b, &sal);
8965           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8966             loc->inserted = 1;
8967         }
8968
8969       /* Do not set breakpoint locations conditions yet.  As locations
8970          are inserted, they get sorted based on their addresses.  Let
8971          the list stabilize to have reliable location numbers.  */
8972
8973       /* Dynamic printf requires and uses additional arguments on the
8974          command line, otherwise it's an error.  */
8975       if (type == bp_dprintf)
8976         {
8977           if (b->extra_string)
8978             update_dprintf_command_list (b);
8979           else
8980             error (_("Format string required"));
8981         }
8982       else if (b->extra_string)
8983         error (_("Garbage '%s' at end of command"), b->extra_string);
8984     }
8985
8986
8987   /* The order of the locations is now stable.  Set the location
8988      condition using the location's number.  */
8989   int loc_num = 1;
8990   for (bp_location *loc = b->loc; loc != nullptr; loc = loc->next)
8991     {
8992       if (b->cond_string != nullptr)
8993         set_breakpoint_location_condition (b->cond_string, loc, b->number,
8994                                            loc_num);
8995
8996       ++loc_num;
8997     }
8998
8999   b->display_canonical = display_canonical;
9000   if (location != NULL)
9001     b->location = std::move (location);
9002   else
9003     b->location = new_address_location (b->loc->address, NULL, 0);
9004   b->filter = std::move (filter);
9005 }
9006
9007 static void
9008 create_breakpoint_sal (struct gdbarch *gdbarch,
9009                        gdb::array_view<const symtab_and_line> sals,
9010                        event_location_up &&location,
9011                        gdb::unique_xmalloc_ptr<char> filter,
9012                        gdb::unique_xmalloc_ptr<char> cond_string,
9013                        gdb::unique_xmalloc_ptr<char> extra_string,
9014                        enum bptype type, enum bpdisp disposition,
9015                        int thread, int task, int ignore_count,
9016                        const struct breakpoint_ops *ops, int from_tty,
9017                        int enabled, int internal, unsigned flags,
9018                        int display_canonical)
9019 {
9020   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
9021
9022   init_breakpoint_sal (b.get (), gdbarch,
9023                        sals, std::move (location),
9024                        std::move (filter),
9025                        std::move (cond_string),
9026                        std::move (extra_string),
9027                        type, disposition,
9028                        thread, task, ignore_count,
9029                        ops, from_tty,
9030                        enabled, internal, flags,
9031                        display_canonical);
9032
9033   install_breakpoint (internal, std::move (b), 0);
9034 }
9035
9036 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9037    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9038    value.  COND_STRING, if not NULL, specified the condition to be
9039    used for all breakpoints.  Essentially the only case where
9040    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9041    function.  In that case, it's still not possible to specify
9042    separate conditions for different overloaded functions, so
9043    we take just a single condition string.
9044    
9045    NOTE: If the function succeeds, the caller is expected to cleanup
9046    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9047    array contents).  If the function fails (error() is called), the
9048    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9049    COND and SALS arrays and each of those arrays contents.  */
9050
9051 static void
9052 create_breakpoints_sal (struct gdbarch *gdbarch,
9053                         struct linespec_result *canonical,
9054                         gdb::unique_xmalloc_ptr<char> cond_string,
9055                         gdb::unique_xmalloc_ptr<char> extra_string,
9056                         enum bptype type, enum bpdisp disposition,
9057                         int thread, int task, int ignore_count,
9058                         const struct breakpoint_ops *ops, int from_tty,
9059                         int enabled, int internal, unsigned flags)
9060 {
9061   if (canonical->pre_expanded)
9062     gdb_assert (canonical->lsals.size () == 1);
9063
9064   for (const auto &lsal : canonical->lsals)
9065     {
9066       /* Note that 'location' can be NULL in the case of a plain
9067          'break', without arguments.  */
9068       event_location_up location
9069         = (canonical->location != NULL
9070            ? copy_event_location (canonical->location.get ()) : NULL);
9071       gdb::unique_xmalloc_ptr<char> filter_string
9072         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9073
9074       create_breakpoint_sal (gdbarch, lsal.sals,
9075                              std::move (location),
9076                              std::move (filter_string),
9077                              std::move (cond_string),
9078                              std::move (extra_string),
9079                              type, disposition,
9080                              thread, task, ignore_count, ops,
9081                              from_tty, enabled, internal, flags,
9082                              canonical->special_display);
9083     }
9084 }
9085
9086 /* Parse LOCATION which is assumed to be a SAL specification possibly
9087    followed by conditionals.  On return, SALS contains an array of SAL
9088    addresses found.  LOCATION points to the end of the SAL (for
9089    linespec locations).
9090
9091    The array and the line spec strings are allocated on the heap, it is
9092    the caller's responsibility to free them.  */
9093
9094 static void
9095 parse_breakpoint_sals (struct event_location *location,
9096                        struct linespec_result *canonical)
9097 {
9098   struct symtab_and_line cursal;
9099
9100   if (event_location_type (location) == LINESPEC_LOCATION)
9101     {
9102       const char *spec = get_linespec_location (location)->spec_string;
9103
9104       if (spec == NULL)
9105         {
9106           /* The last displayed codepoint, if it's valid, is our default
9107              breakpoint address.  */
9108           if (last_displayed_sal_is_valid ())
9109             {
9110               /* Set sal's pspace, pc, symtab, and line to the values
9111                  corresponding to the last call to print_frame_info.
9112                  Be sure to reinitialize LINE with NOTCURRENT == 0
9113                  as the breakpoint line number is inappropriate otherwise.
9114                  find_pc_line would adjust PC, re-set it back.  */
9115               symtab_and_line sal = get_last_displayed_sal ();
9116               CORE_ADDR pc = sal.pc;
9117
9118               sal = find_pc_line (pc, 0);
9119
9120               /* "break" without arguments is equivalent to "break *PC"
9121                  where PC is the last displayed codepoint's address.  So
9122                  make sure to set sal.explicit_pc to prevent GDB from
9123                  trying to expand the list of sals to include all other
9124                  instances with the same symtab and line.  */
9125               sal.pc = pc;
9126               sal.explicit_pc = 1;
9127
9128               struct linespec_sals lsal;
9129               lsal.sals = {sal};
9130               lsal.canonical = NULL;
9131
9132               canonical->lsals.push_back (std::move (lsal));
9133               return;
9134             }
9135           else
9136             error (_("No default breakpoint address now."));
9137         }
9138     }
9139
9140   /* Force almost all breakpoints to be in terms of the
9141      current_source_symtab (which is decode_line_1's default).
9142      This should produce the results we want almost all of the
9143      time while leaving default_breakpoint_* alone.
9144
9145      ObjC: However, don't match an Objective-C method name which
9146      may have a '+' or '-' succeeded by a '['.  */
9147   cursal = get_current_source_symtab_and_line ();
9148   if (last_displayed_sal_is_valid ())
9149     {
9150       const char *spec = NULL;
9151
9152       if (event_location_type (location) == LINESPEC_LOCATION)
9153         spec = get_linespec_location (location)->spec_string;
9154
9155       if (!cursal.symtab
9156           || (spec != NULL
9157               && strchr ("+-", spec[0]) != NULL
9158               && spec[1] != '['))
9159         {
9160           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9161                             get_last_displayed_symtab (),
9162                             get_last_displayed_line (),
9163                             canonical, NULL, NULL);
9164           return;
9165         }
9166     }
9167
9168   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9169                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9170 }
9171
9172
9173 /* Convert each SAL into a real PC.  Verify that the PC can be
9174    inserted as a breakpoint.  If it can't throw an error.  */
9175
9176 static void
9177 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9178 {    
9179   for (auto &sal : sals)
9180     resolve_sal_pc (&sal);
9181 }
9182
9183 /* Fast tracepoints may have restrictions on valid locations.  For
9184    instance, a fast tracepoint using a jump instead of a trap will
9185    likely have to overwrite more bytes than a trap would, and so can
9186    only be placed where the instruction is longer than the jump, or a
9187    multi-instruction sequence does not have a jump into the middle of
9188    it, etc.  */
9189
9190 static void
9191 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9192                             gdb::array_view<const symtab_and_line> sals)
9193 {
9194   for (const auto &sal : sals)
9195     {
9196       struct gdbarch *sarch;
9197
9198       sarch = get_sal_arch (sal);
9199       /* We fall back to GDBARCH if there is no architecture
9200          associated with SAL.  */
9201       if (sarch == NULL)
9202         sarch = gdbarch;
9203       std::string msg;
9204       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9205         error (_("May not have a fast tracepoint at %s%s"),
9206                paddress (sarch, sal.pc), msg.c_str ());
9207     }
9208 }
9209
9210 /* Given TOK, a string specification of condition and thread, as
9211    accepted by the 'break' command, extract the condition
9212    string and thread number and set *COND_STRING and *THREAD.
9213    PC identifies the context at which the condition should be parsed.
9214    If no condition is found, *COND_STRING is set to NULL.
9215    If no thread is found, *THREAD is set to -1.  */
9216
9217 static void
9218 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9219                            char **cond_string, int *thread, int *task,
9220                            char **rest)
9221 {
9222   *cond_string = NULL;
9223   *thread = -1;
9224   *task = 0;
9225   *rest = NULL;
9226   bool force = false;
9227
9228   while (tok && *tok)
9229     {
9230       const char *end_tok;
9231       int toklen;
9232       const char *cond_start = NULL;
9233       const char *cond_end = NULL;
9234
9235       tok = skip_spaces (tok);
9236
9237       if ((*tok == '"' || *tok == ',') && rest)
9238         {
9239           *rest = savestring (tok, strlen (tok));
9240           return;
9241         }
9242
9243       end_tok = skip_to_space (tok);
9244
9245       toklen = end_tok - tok;
9246
9247       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9248         {
9249           tok = cond_start = end_tok + 1;
9250           try
9251             {
9252               parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9253             }
9254           catch (const gdb_exception_error &)
9255             {
9256               if (!force)
9257                 throw;
9258               else
9259                 tok = tok + strlen (tok);
9260             }
9261           cond_end = tok;
9262           *cond_string = savestring (cond_start, cond_end - cond_start);
9263         }
9264       else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
9265         {
9266           tok = cond_start = end_tok + 1;
9267           force = true;
9268         }
9269       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9270         {
9271           const char *tmptok;
9272           struct thread_info *thr;
9273
9274           tok = end_tok + 1;
9275           thr = parse_thread_id (tok, &tmptok);
9276           if (tok == tmptok)
9277             error (_("Junk after thread keyword."));
9278           *thread = thr->global_num;
9279           tok = tmptok;
9280         }
9281       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9282         {
9283           char *tmptok;
9284
9285           tok = end_tok + 1;
9286           *task = strtol (tok, &tmptok, 0);
9287           if (tok == tmptok)
9288             error (_("Junk after task keyword."));
9289           if (!valid_task_id (*task))
9290             error (_("Unknown task %d."), *task);
9291           tok = tmptok;
9292         }
9293       else if (rest)
9294         {
9295           *rest = savestring (tok, strlen (tok));
9296           return;
9297         }
9298       else
9299         error (_("Junk at end of arguments."));
9300     }
9301 }
9302
9303 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
9304    succeeds.  The parsed values are written to COND_STRING, THREAD,
9305    TASK, and REST.  See the comment of 'find_condition_and_thread'
9306    for the description of these parameters and INPUT.  */
9307
9308 static void
9309 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
9310                                     const char *input, char **cond_string,
9311                                     int *thread, int *task, char **rest)
9312 {
9313   int num_failures = 0;
9314   for (auto &sal : sals)
9315     {
9316       char *cond = nullptr;
9317       int thread_id = 0;
9318       int task_id = 0;
9319       char *remaining = nullptr;
9320
9321       /* Here we want to parse 'arg' to separate condition from thread
9322          number.  But because parsing happens in a context and the
9323          contexts of sals might be different, try each until there is
9324          success.  Finding one successful parse is sufficient for our
9325          goal.  When setting the breakpoint we'll re-parse the
9326          condition in the context of each sal.  */
9327       try
9328         {
9329           find_condition_and_thread (input, sal.pc, &cond, &thread_id,
9330                                      &task_id, &remaining);
9331           *cond_string = cond;
9332           *thread = thread_id;
9333           *task = task_id;
9334           *rest = remaining;
9335           break;
9336         }
9337       catch (const gdb_exception_error &e)
9338         {
9339           num_failures++;
9340           /* If no sal remains, do not continue.  */
9341           if (num_failures == sals.size ())
9342             throw;
9343         }
9344     }
9345 }
9346
9347 /* Decode a static tracepoint marker spec.  */
9348
9349 static std::vector<symtab_and_line>
9350 decode_static_tracepoint_spec (const char **arg_p)
9351 {
9352   const char *p = &(*arg_p)[3];
9353   const char *endp;
9354
9355   p = skip_spaces (p);
9356
9357   endp = skip_to_space (p);
9358
9359   std::string marker_str (p, endp - p);
9360
9361   std::vector<static_tracepoint_marker> markers
9362     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9363   if (markers.empty ())
9364     error (_("No known static tracepoint marker named %s"),
9365            marker_str.c_str ());
9366
9367   std::vector<symtab_and_line> sals;
9368   sals.reserve (markers.size ());
9369
9370   for (const static_tracepoint_marker &marker : markers)
9371     {
9372       symtab_and_line sal = find_pc_line (marker.address, 0);
9373       sal.pc = marker.address;
9374       sals.push_back (sal);
9375    }
9376
9377   *arg_p = endp;
9378   return sals;
9379 }
9380
9381 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
9382    according to IS_TRACEPOINT.  */
9383
9384 static const struct breakpoint_ops *
9385 breakpoint_ops_for_event_location_type (enum event_location_type location_type,
9386                                         bool is_tracepoint)
9387 {
9388   if (is_tracepoint)
9389     {
9390       if (location_type == PROBE_LOCATION)
9391         return &tracepoint_probe_breakpoint_ops;
9392       else
9393         return &tracepoint_breakpoint_ops;
9394     }
9395   else
9396     {
9397       if (location_type == PROBE_LOCATION)
9398         return &bkpt_probe_breakpoint_ops;
9399       else
9400         return &bkpt_breakpoint_ops;
9401     }
9402 }
9403
9404 /* See breakpoint.h.  */
9405
9406 const struct breakpoint_ops *
9407 breakpoint_ops_for_event_location (const struct event_location *location,
9408                                    bool is_tracepoint)
9409 {
9410   if (location != nullptr)
9411     return breakpoint_ops_for_event_location_type
9412       (event_location_type (location), is_tracepoint);
9413   return is_tracepoint ? &tracepoint_breakpoint_ops : &bkpt_breakpoint_ops;
9414 }
9415
9416 /* See breakpoint.h.  */
9417
9418 int
9419 create_breakpoint (struct gdbarch *gdbarch,
9420                    struct event_location *location,
9421                    const char *cond_string,
9422                    int thread, const char *extra_string,
9423                    int parse_extra,
9424                    int tempflag, enum bptype type_wanted,
9425                    int ignore_count,
9426                    enum auto_boolean pending_break_support,
9427                    const struct breakpoint_ops *ops,
9428                    int from_tty, int enabled, int internal,
9429                    unsigned flags)
9430 {
9431   struct linespec_result canonical;
9432   int pending = 0;
9433   int task = 0;
9434   int prev_bkpt_count = breakpoint_count;
9435
9436   gdb_assert (ops != NULL);
9437
9438   /* If extra_string isn't useful, set it to NULL.  */
9439   if (extra_string != NULL && *extra_string == '\0')
9440     extra_string = NULL;
9441
9442   try
9443     {
9444       ops->create_sals_from_location (location, &canonical, type_wanted);
9445     }
9446   catch (const gdb_exception_error &e)
9447     {
9448       /* If caller is interested in rc value from parse, set
9449          value.  */
9450       if (e.error == NOT_FOUND_ERROR)
9451         {
9452           /* If pending breakpoint support is turned off, throw
9453              error.  */
9454
9455           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9456             throw;
9457
9458           exception_print (gdb_stderr, e);
9459
9460           /* If pending breakpoint support is auto query and the user
9461              selects no, then simply return the error code.  */
9462           if (pending_break_support == AUTO_BOOLEAN_AUTO
9463               && !nquery (_("Make %s pending on future shared library load? "),
9464                           bptype_string (type_wanted)))
9465             return 0;
9466
9467           /* At this point, either the user was queried about setting
9468              a pending breakpoint and selected yes, or pending
9469              breakpoint behavior is on and thus a pending breakpoint
9470              is defaulted on behalf of the user.  */
9471           pending = 1;
9472         }
9473       else
9474         throw;
9475     }
9476
9477   if (!pending && canonical.lsals.empty ())
9478     return 0;
9479
9480   /* Resolve all line numbers to PC's and verify that the addresses
9481      are ok for the target.  */
9482   if (!pending)
9483     {
9484       for (auto &lsal : canonical.lsals)
9485         breakpoint_sals_to_pc (lsal.sals);
9486     }
9487
9488   /* Fast tracepoints may have additional restrictions on location.  */
9489   if (!pending && type_wanted == bp_fast_tracepoint)
9490     {
9491       for (const auto &lsal : canonical.lsals)
9492         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9493     }
9494
9495   /* Verify that condition can be parsed, before setting any
9496      breakpoints.  Allocate a separate condition expression for each
9497      breakpoint.  */
9498   if (!pending)
9499     {
9500       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9501       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9502
9503       if (parse_extra)
9504         {
9505           char *rest;
9506           char *cond;
9507
9508           const linespec_sals &lsal = canonical.lsals[0];
9509
9510           find_condition_and_thread_for_sals (lsal.sals, extra_string,
9511                                               &cond, &thread, &task, &rest);
9512           cond_string_copy.reset (cond);
9513           extra_string_copy.reset (rest);
9514         }
9515       else
9516         {
9517           if (type_wanted != bp_dprintf
9518               && extra_string != NULL && *extra_string != '\0')
9519                 error (_("Garbage '%s' at end of location"), extra_string);
9520
9521           /* Create a private copy of condition string.  */
9522           if (cond_string)
9523             cond_string_copy.reset (xstrdup (cond_string));
9524           /* Create a private copy of any extra string.  */
9525           if (extra_string)
9526             extra_string_copy.reset (xstrdup (extra_string));
9527         }
9528
9529       ops->create_breakpoints_sal (gdbarch, &canonical,
9530                                    std::move (cond_string_copy),
9531                                    std::move (extra_string_copy),
9532                                    type_wanted,
9533                                    tempflag ? disp_del : disp_donttouch,
9534                                    thread, task, ignore_count, ops,
9535                                    from_tty, enabled, internal, flags);
9536     }
9537   else
9538     {
9539       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9540
9541       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9542       b->location = copy_event_location (location);
9543
9544       if (parse_extra)
9545         b->cond_string = NULL;
9546       else
9547         {
9548           /* Create a private copy of condition string.  */
9549           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9550           b->thread = thread;
9551         }
9552
9553       /* Create a private copy of any extra string.  */
9554       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9555       b->ignore_count = ignore_count;
9556       b->disposition = tempflag ? disp_del : disp_donttouch;
9557       b->condition_not_parsed = 1;
9558       b->enable_state = enabled ? bp_enabled : bp_disabled;
9559       if ((type_wanted != bp_breakpoint
9560            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9561         b->pspace = current_program_space;
9562
9563       install_breakpoint (internal, std::move (b), 0);
9564     }
9565   
9566   if (canonical.lsals.size () > 1)
9567     {
9568       warning (_("Multiple breakpoints were set.\nUse the "
9569                  "\"delete\" command to delete unwanted breakpoints."));
9570       prev_breakpoint_count = prev_bkpt_count;
9571     }
9572
9573   update_global_location_list (UGLL_MAY_INSERT);
9574
9575   return 1;
9576 }
9577
9578 /* Set a breakpoint.
9579    ARG is a string describing breakpoint address,
9580    condition, and thread.
9581    FLAG specifies if a breakpoint is hardware on,
9582    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9583    and BP_TEMPFLAG.  */
9584
9585 static void
9586 break_command_1 (const char *arg, int flag, int from_tty)
9587 {
9588   int tempflag = flag & BP_TEMPFLAG;
9589   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9590                              ? bp_hardware_breakpoint
9591                              : bp_breakpoint);
9592
9593   event_location_up location = string_to_event_location (&arg, current_language);
9594   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
9595     (location.get (), false /* is_tracepoint */);
9596
9597   create_breakpoint (get_current_arch (),
9598                      location.get (),
9599                      NULL, 0, arg, 1 /* parse arg */,
9600                      tempflag, type_wanted,
9601                      0 /* Ignore count */,
9602                      pending_break_support,
9603                      ops,
9604                      from_tty,
9605                      1 /* enabled */,
9606                      0 /* internal */,
9607                      0);
9608 }
9609
9610 /* Helper function for break_command_1 and disassemble_command.  */
9611
9612 void
9613 resolve_sal_pc (struct symtab_and_line *sal)
9614 {
9615   CORE_ADDR pc;
9616
9617   if (sal->pc == 0 && sal->symtab != NULL)
9618     {
9619       if (!find_line_pc (sal->symtab, sal->line, &pc))
9620         error (_("No line %d in file \"%s\"."),
9621                sal->line, symtab_to_filename_for_display (sal->symtab));
9622       sal->pc = pc;
9623
9624       /* If this SAL corresponds to a breakpoint inserted using a line
9625          number, then skip the function prologue if necessary.  */
9626       if (sal->explicit_line)
9627         skip_prologue_sal (sal);
9628     }
9629
9630   if (sal->section == 0 && sal->symtab != NULL)
9631     {
9632       const struct blockvector *bv;
9633       const struct block *b;
9634       struct symbol *sym;
9635
9636       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9637                                     SYMTAB_COMPUNIT (sal->symtab));
9638       if (bv != NULL)
9639         {
9640           sym = block_linkage_function (b);
9641           if (sym != NULL)
9642             {
9643               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9644               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9645                                                  sym);
9646             }
9647           else
9648             {
9649               /* It really is worthwhile to have the section, so we'll
9650                  just have to look harder. This case can be executed
9651                  if we have line numbers but no functions (as can
9652                  happen in assembly source).  */
9653
9654               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9655               switch_to_program_space_and_thread (sal->pspace);
9656
9657               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9658               if (msym.minsym)
9659                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9660             }
9661         }
9662     }
9663 }
9664
9665 void
9666 break_command (const char *arg, int from_tty)
9667 {
9668   break_command_1 (arg, 0, from_tty);
9669 }
9670
9671 void
9672 tbreak_command (const char *arg, int from_tty)
9673 {
9674   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9675 }
9676
9677 static void
9678 hbreak_command (const char *arg, int from_tty)
9679 {
9680   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9681 }
9682
9683 static void
9684 thbreak_command (const char *arg, int from_tty)
9685 {
9686   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9687 }
9688
9689 static void
9690 stop_command (const char *arg, int from_tty)
9691 {
9692   printf_filtered (_("Specify the type of breakpoint to set.\n\
9693 Usage: stop in <function | address>\n\
9694        stop at <line>\n"));
9695 }
9696
9697 static void
9698 stopin_command (const char *arg, int from_tty)
9699 {
9700   int badInput = 0;
9701
9702   if (arg == NULL)
9703     badInput = 1;
9704   else if (*arg != '*')
9705     {
9706       const char *argptr = arg;
9707       int hasColon = 0;
9708
9709       /* Look for a ':'.  If this is a line number specification, then
9710          say it is bad, otherwise, it should be an address or
9711          function/method name.  */
9712       while (*argptr && !hasColon)
9713         {
9714           hasColon = (*argptr == ':');
9715           argptr++;
9716         }
9717
9718       if (hasColon)
9719         badInput = (*argptr != ':');    /* Not a class::method */
9720       else
9721         badInput = isdigit (*arg);      /* a simple line number */
9722     }
9723
9724   if (badInput)
9725     printf_filtered (_("Usage: stop in <function | address>\n"));
9726   else
9727     break_command_1 (arg, 0, from_tty);
9728 }
9729
9730 static void
9731 stopat_command (const char *arg, int from_tty)
9732 {
9733   int badInput = 0;
9734
9735   if (arg == NULL || *arg == '*')       /* no line number */
9736     badInput = 1;
9737   else
9738     {
9739       const char *argptr = arg;
9740       int hasColon = 0;
9741
9742       /* Look for a ':'.  If there is a '::' then get out, otherwise
9743          it is probably a line number.  */
9744       while (*argptr && !hasColon)
9745         {
9746           hasColon = (*argptr == ':');
9747           argptr++;
9748         }
9749
9750       if (hasColon)
9751         badInput = (*argptr == ':');    /* we have class::method */
9752       else
9753         badInput = !isdigit (*arg);     /* not a line number */
9754     }
9755
9756   if (badInput)
9757     printf_filtered (_("Usage: stop at LINE\n"));
9758   else
9759     break_command_1 (arg, 0, from_tty);
9760 }
9761
9762 /* The dynamic printf command is mostly like a regular breakpoint, but
9763    with a prewired command list consisting of a single output command,
9764    built from extra arguments supplied on the dprintf command
9765    line.  */
9766
9767 static void
9768 dprintf_command (const char *arg, int from_tty)
9769 {
9770   event_location_up location = string_to_event_location (&arg, current_language);
9771
9772   /* If non-NULL, ARG should have been advanced past the location;
9773      the next character must be ','.  */
9774   if (arg != NULL)
9775     {
9776       if (arg[0] != ',' || arg[1] == '\0')
9777         error (_("Format string required"));
9778       else
9779         {
9780           /* Skip the comma.  */
9781           ++arg;
9782         }
9783     }
9784
9785   create_breakpoint (get_current_arch (),
9786                      location.get (),
9787                      NULL, 0, arg, 1 /* parse arg */,
9788                      0, bp_dprintf,
9789                      0 /* Ignore count */,
9790                      pending_break_support,
9791                      &dprintf_breakpoint_ops,
9792                      from_tty,
9793                      1 /* enabled */,
9794                      0 /* internal */,
9795                      0);
9796 }
9797
9798 static void
9799 agent_printf_command (const char *arg, int from_tty)
9800 {
9801   error (_("May only run agent-printf on the target"));
9802 }
9803
9804 /* Implement the "breakpoint_hit" breakpoint_ops method for
9805    ranged breakpoints.  */
9806
9807 static int
9808 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9809                                   const address_space *aspace,
9810                                   CORE_ADDR bp_addr,
9811                                   const struct target_waitstatus *ws)
9812 {
9813   if (ws->kind != TARGET_WAITKIND_STOPPED
9814       || ws->value.sig != GDB_SIGNAL_TRAP)
9815     return 0;
9816
9817   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9818                                          bl->length, aspace, bp_addr);
9819 }
9820
9821 /* Implement the "resources_needed" breakpoint_ops method for
9822    ranged breakpoints.  */
9823
9824 static int
9825 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9826 {
9827   return target_ranged_break_num_registers ();
9828 }
9829
9830 /* Implement the "print_it" breakpoint_ops method for
9831    ranged breakpoints.  */
9832
9833 static enum print_stop_action
9834 print_it_ranged_breakpoint (bpstat bs)
9835 {
9836   struct breakpoint *b = bs->breakpoint_at;
9837   struct bp_location *bl = b->loc;
9838   struct ui_out *uiout = current_uiout;
9839
9840   gdb_assert (b->type == bp_hardware_breakpoint);
9841
9842   /* Ranged breakpoints have only one location.  */
9843   gdb_assert (bl && bl->next == NULL);
9844
9845   annotate_breakpoint (b->number);
9846
9847   maybe_print_thread_hit_breakpoint (uiout);
9848
9849   if (b->disposition == disp_del)
9850     uiout->text ("Temporary ranged breakpoint ");
9851   else
9852     uiout->text ("Ranged breakpoint ");
9853   if (uiout->is_mi_like_p ())
9854     {
9855       uiout->field_string ("reason",
9856                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9857       uiout->field_string ("disp", bpdisp_text (b->disposition));
9858     }
9859   uiout->field_signed ("bkptno", b->number);
9860   uiout->text (", ");
9861
9862   return PRINT_SRC_AND_LOC;
9863 }
9864
9865 /* Implement the "print_one" breakpoint_ops method for
9866    ranged breakpoints.  */
9867
9868 static void
9869 print_one_ranged_breakpoint (struct breakpoint *b,
9870                              struct bp_location **last_loc)
9871 {
9872   struct bp_location *bl = b->loc;
9873   struct value_print_options opts;
9874   struct ui_out *uiout = current_uiout;
9875
9876   /* Ranged breakpoints have only one location.  */
9877   gdb_assert (bl && bl->next == NULL);
9878
9879   get_user_print_options (&opts);
9880
9881   if (opts.addressprint)
9882     /* We don't print the address range here, it will be printed later
9883        by print_one_detail_ranged_breakpoint.  */
9884     uiout->field_skip ("addr");
9885   annotate_field (5);
9886   print_breakpoint_location (b, bl);
9887   *last_loc = bl;
9888 }
9889
9890 /* Implement the "print_one_detail" breakpoint_ops method for
9891    ranged breakpoints.  */
9892
9893 static void
9894 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9895                                     struct ui_out *uiout)
9896 {
9897   CORE_ADDR address_start, address_end;
9898   struct bp_location *bl = b->loc;
9899   string_file stb;
9900
9901   gdb_assert (bl);
9902
9903   address_start = bl->address;
9904   address_end = address_start + bl->length - 1;
9905
9906   uiout->text ("\taddress range: ");
9907   stb.printf ("[%s, %s]",
9908               print_core_address (bl->gdbarch, address_start),
9909               print_core_address (bl->gdbarch, address_end));
9910   uiout->field_stream ("addr", stb);
9911   uiout->text ("\n");
9912 }
9913
9914 /* Implement the "print_mention" breakpoint_ops method for
9915    ranged breakpoints.  */
9916
9917 static void
9918 print_mention_ranged_breakpoint (struct breakpoint *b)
9919 {
9920   struct bp_location *bl = b->loc;
9921   struct ui_out *uiout = current_uiout;
9922
9923   gdb_assert (bl);
9924   gdb_assert (b->type == bp_hardware_breakpoint);
9925
9926   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9927                   b->number, paddress (bl->gdbarch, bl->address),
9928                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9929 }
9930
9931 /* Implement the "print_recreate" breakpoint_ops method for
9932    ranged breakpoints.  */
9933
9934 static void
9935 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9936 {
9937   fprintf_unfiltered (fp, "break-range %s, %s",
9938                       event_location_to_string (b->location.get ()),
9939                       event_location_to_string (b->location_range_end.get ()));
9940   print_recreate_thread (b, fp);
9941 }
9942
9943 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9944
9945 static struct breakpoint_ops ranged_breakpoint_ops;
9946
9947 /* Find the address where the end of the breakpoint range should be
9948    placed, given the SAL of the end of the range.  This is so that if
9949    the user provides a line number, the end of the range is set to the
9950    last instruction of the given line.  */
9951
9952 static CORE_ADDR
9953 find_breakpoint_range_end (struct symtab_and_line sal)
9954 {
9955   CORE_ADDR end;
9956
9957   /* If the user provided a PC value, use it.  Otherwise,
9958      find the address of the end of the given location.  */
9959   if (sal.explicit_pc)
9960     end = sal.pc;
9961   else
9962     {
9963       int ret;
9964       CORE_ADDR start;
9965
9966       ret = find_line_pc_range (sal, &start, &end);
9967       if (!ret)
9968         error (_("Could not find location of the end of the range."));
9969
9970       /* find_line_pc_range returns the start of the next line.  */
9971       end--;
9972     }
9973
9974   return end;
9975 }
9976
9977 /* Implement the "break-range" CLI command.  */
9978
9979 static void
9980 break_range_command (const char *arg, int from_tty)
9981 {
9982   const char *arg_start;
9983   struct linespec_result canonical_start, canonical_end;
9984   int bp_count, can_use_bp, length;
9985   CORE_ADDR end;
9986   struct breakpoint *b;
9987
9988   /* We don't support software ranged breakpoints.  */
9989   if (target_ranged_break_num_registers () < 0)
9990     error (_("This target does not support hardware ranged breakpoints."));
9991
9992   bp_count = hw_breakpoint_used_count ();
9993   bp_count += target_ranged_break_num_registers ();
9994   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9995                                                    bp_count, 0);
9996   if (can_use_bp < 0)
9997     error (_("Hardware breakpoints used exceeds limit."));
9998
9999   arg = skip_spaces (arg);
10000   if (arg == NULL || arg[0] == '\0')
10001     error(_("No address range specified."));
10002
10003   arg_start = arg;
10004   event_location_up start_location = string_to_event_location (&arg,
10005                                                                current_language);
10006   parse_breakpoint_sals (start_location.get (), &canonical_start);
10007
10008   if (arg[0] != ',')
10009     error (_("Too few arguments."));
10010   else if (canonical_start.lsals.empty ())
10011     error (_("Could not find location of the beginning of the range."));
10012
10013   const linespec_sals &lsal_start = canonical_start.lsals[0];
10014
10015   if (canonical_start.lsals.size () > 1
10016       || lsal_start.sals.size () != 1)
10017     error (_("Cannot create a ranged breakpoint with multiple locations."));
10018
10019   const symtab_and_line &sal_start = lsal_start.sals[0];
10020   std::string addr_string_start (arg_start, arg - arg_start);
10021
10022   arg++;        /* Skip the comma.  */
10023   arg = skip_spaces (arg);
10024
10025   /* Parse the end location.  */
10026
10027   arg_start = arg;
10028
10029   /* We call decode_line_full directly here instead of using
10030      parse_breakpoint_sals because we need to specify the start location's
10031      symtab and line as the default symtab and line for the end of the
10032      range.  This makes it possible to have ranges like "foo.c:27, +14",
10033      where +14 means 14 lines from the start location.  */
10034   event_location_up end_location = string_to_event_location (&arg,
10035                                                              current_language);
10036   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10037                     sal_start.symtab, sal_start.line,
10038                     &canonical_end, NULL, NULL);
10039
10040   if (canonical_end.lsals.empty ())
10041     error (_("Could not find location of the end of the range."));
10042
10043   const linespec_sals &lsal_end = canonical_end.lsals[0];
10044   if (canonical_end.lsals.size () > 1
10045       || lsal_end.sals.size () != 1)
10046     error (_("Cannot create a ranged breakpoint with multiple locations."));
10047
10048   const symtab_and_line &sal_end = lsal_end.sals[0];
10049
10050   end = find_breakpoint_range_end (sal_end);
10051   if (sal_start.pc > end)
10052     error (_("Invalid address range, end precedes start."));
10053
10054   length = end - sal_start.pc + 1;
10055   if (length < 0)
10056     /* Length overflowed.  */
10057     error (_("Address range too large."));
10058   else if (length == 1)
10059     {
10060       /* This range is simple enough to be handled by
10061          the `hbreak' command.  */
10062       hbreak_command (&addr_string_start[0], 1);
10063
10064       return;
10065     }
10066
10067   /* Now set up the breakpoint.  */
10068   b = set_raw_breakpoint (get_current_arch (), sal_start,
10069                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10070   set_breakpoint_count (breakpoint_count + 1);
10071   b->number = breakpoint_count;
10072   b->disposition = disp_donttouch;
10073   b->location = std::move (start_location);
10074   b->location_range_end = std::move (end_location);
10075   b->loc->length = length;
10076
10077   mention (b);
10078   gdb::observers::breakpoint_created.notify (b);
10079   update_global_location_list (UGLL_MAY_INSERT);
10080 }
10081
10082 /*  Return non-zero if EXP is verified as constant.  Returned zero
10083     means EXP is variable.  Also the constant detection may fail for
10084     some constant expressions and in such case still falsely return
10085     zero.  */
10086
10087 static bool
10088 watchpoint_exp_is_const (const struct expression *exp)
10089 {
10090   int i = exp->nelts;
10091
10092   while (i > 0)
10093     {
10094       int oplenp, argsp;
10095
10096       /* We are only interested in the descriptor of each element.  */
10097       operator_length (exp, i, &oplenp, &argsp);
10098       i -= oplenp;
10099
10100       switch (exp->elts[i].opcode)
10101         {
10102         case BINOP_ADD:
10103         case BINOP_SUB:
10104         case BINOP_MUL:
10105         case BINOP_DIV:
10106         case BINOP_REM:
10107         case BINOP_MOD:
10108         case BINOP_LSH:
10109         case BINOP_RSH:
10110         case BINOP_LOGICAL_AND:
10111         case BINOP_LOGICAL_OR:
10112         case BINOP_BITWISE_AND:
10113         case BINOP_BITWISE_IOR:
10114         case BINOP_BITWISE_XOR:
10115         case BINOP_EQUAL:
10116         case BINOP_NOTEQUAL:
10117         case BINOP_LESS:
10118         case BINOP_GTR:
10119         case BINOP_LEQ:
10120         case BINOP_GEQ:
10121         case BINOP_REPEAT:
10122         case BINOP_COMMA:
10123         case BINOP_EXP:
10124         case BINOP_MIN:
10125         case BINOP_MAX:
10126         case BINOP_INTDIV:
10127         case BINOP_CONCAT:
10128         case TERNOP_COND:
10129         case TERNOP_SLICE:
10130
10131         case OP_LONG:
10132         case OP_FLOAT:
10133         case OP_LAST:
10134         case OP_COMPLEX:
10135         case OP_STRING:
10136         case OP_ARRAY:
10137         case OP_TYPE:
10138         case OP_TYPEOF:
10139         case OP_DECLTYPE:
10140         case OP_TYPEID:
10141         case OP_NAME:
10142         case OP_OBJC_NSSTRING:
10143
10144         case UNOP_NEG:
10145         case UNOP_LOGICAL_NOT:
10146         case UNOP_COMPLEMENT:
10147         case UNOP_ADDR:
10148         case UNOP_HIGH:
10149         case UNOP_CAST:
10150
10151         case UNOP_CAST_TYPE:
10152         case UNOP_REINTERPRET_CAST:
10153         case UNOP_DYNAMIC_CAST:
10154           /* Unary, binary and ternary operators: We have to check
10155              their operands.  If they are constant, then so is the
10156              result of that operation.  For instance, if A and B are
10157              determined to be constants, then so is "A + B".
10158
10159              UNOP_IND is one exception to the rule above, because the
10160              value of *ADDR is not necessarily a constant, even when
10161              ADDR is.  */
10162           break;
10163
10164         case OP_VAR_VALUE:
10165           /* Check whether the associated symbol is a constant.
10166
10167              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10168              possible that a buggy compiler could mark a variable as
10169              constant even when it is not, and TYPE_CONST would return
10170              true in this case, while SYMBOL_CLASS wouldn't.
10171
10172              We also have to check for function symbols because they
10173              are always constant.  */
10174           {
10175             struct symbol *s = exp->elts[i + 2].symbol;
10176
10177             if (SYMBOL_CLASS (s) != LOC_BLOCK
10178                 && SYMBOL_CLASS (s) != LOC_CONST
10179                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10180               return false;
10181             break;
10182           }
10183
10184         /* The default action is to return 0 because we are using
10185            the optimistic approach here: If we don't know something,
10186            then it is not a constant.  */
10187         default:
10188           return false;
10189         }
10190     }
10191
10192   return true;
10193 }
10194
10195 /* Watchpoint destructor.  */
10196
10197 watchpoint::~watchpoint ()
10198 {
10199   xfree (this->exp_string);
10200   xfree (this->exp_string_reparse);
10201 }
10202
10203 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10204
10205 static void
10206 re_set_watchpoint (struct breakpoint *b)
10207 {
10208   struct watchpoint *w = (struct watchpoint *) b;
10209
10210   /* Watchpoint can be either on expression using entirely global
10211      variables, or it can be on local variables.
10212
10213      Watchpoints of the first kind are never auto-deleted, and even
10214      persist across program restarts.  Since they can use variables
10215      from shared libraries, we need to reparse expression as libraries
10216      are loaded and unloaded.
10217
10218      Watchpoints on local variables can also change meaning as result
10219      of solib event.  For example, if a watchpoint uses both a local
10220      and a global variables in expression, it's a local watchpoint,
10221      but unloading of a shared library will make the expression
10222      invalid.  This is not a very common use case, but we still
10223      re-evaluate expression, to avoid surprises to the user.
10224
10225      Note that for local watchpoints, we re-evaluate it only if
10226      watchpoints frame id is still valid.  If it's not, it means the
10227      watchpoint is out of scope and will be deleted soon.  In fact,
10228      I'm not sure we'll ever be called in this case.
10229
10230      If a local watchpoint's frame id is still valid, then
10231      w->exp_valid_block is likewise valid, and we can safely use it.
10232
10233      Don't do anything about disabled watchpoints, since they will be
10234      reevaluated again when enabled.  */
10235   update_watchpoint (w, 1 /* reparse */);
10236 }
10237
10238 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10239
10240 static int
10241 insert_watchpoint (struct bp_location *bl)
10242 {
10243   struct watchpoint *w = (struct watchpoint *) bl->owner;
10244   int length = w->exact ? 1 : bl->length;
10245
10246   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10247                                    w->cond_exp.get ());
10248 }
10249
10250 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10251
10252 static int
10253 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10254 {
10255   struct watchpoint *w = (struct watchpoint *) bl->owner;
10256   int length = w->exact ? 1 : bl->length;
10257
10258   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10259                                    w->cond_exp.get ());
10260 }
10261
10262 static int
10263 breakpoint_hit_watchpoint (const struct bp_location *bl,
10264                            const address_space *aspace, CORE_ADDR bp_addr,
10265                            const struct target_waitstatus *ws)
10266 {
10267   struct breakpoint *b = bl->owner;
10268   struct watchpoint *w = (struct watchpoint *) b;
10269
10270   /* Continuable hardware watchpoints are treated as non-existent if the
10271      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10272      some data address).  Otherwise gdb won't stop on a break instruction
10273      in the code (not from a breakpoint) when a hardware watchpoint has
10274      been defined.  Also skip watchpoints which we know did not trigger
10275      (did not match the data address).  */
10276   if (is_hardware_watchpoint (b)
10277       && w->watchpoint_triggered == watch_triggered_no)
10278     return 0;
10279
10280   return 1;
10281 }
10282
10283 static void
10284 check_status_watchpoint (bpstat bs)
10285 {
10286   gdb_assert (is_watchpoint (bs->breakpoint_at));
10287
10288   bpstat_check_watchpoint (bs);
10289 }
10290
10291 /* Implement the "resources_needed" breakpoint_ops method for
10292    hardware watchpoints.  */
10293
10294 static int
10295 resources_needed_watchpoint (const struct bp_location *bl)
10296 {
10297   struct watchpoint *w = (struct watchpoint *) bl->owner;
10298   int length = w->exact? 1 : bl->length;
10299
10300   return target_region_ok_for_hw_watchpoint (bl->address, length);
10301 }
10302
10303 /* Implement the "works_in_software_mode" breakpoint_ops method for
10304    hardware watchpoints.  */
10305
10306 static int
10307 works_in_software_mode_watchpoint (const struct breakpoint *b)
10308 {
10309   /* Read and access watchpoints only work with hardware support.  */
10310   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10311 }
10312
10313 static enum print_stop_action
10314 print_it_watchpoint (bpstat bs)
10315 {
10316   struct breakpoint *b;
10317   enum print_stop_action result;
10318   struct watchpoint *w;
10319   struct ui_out *uiout = current_uiout;
10320
10321   gdb_assert (bs->bp_location_at != NULL);
10322
10323   b = bs->breakpoint_at;
10324   w = (struct watchpoint *) b;
10325
10326   annotate_watchpoint (b->number);
10327   maybe_print_thread_hit_breakpoint (uiout);
10328
10329   string_file stb;
10330
10331   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10332   switch (b->type)
10333     {
10334     case bp_watchpoint:
10335     case bp_hardware_watchpoint:
10336       if (uiout->is_mi_like_p ())
10337         uiout->field_string
10338           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10339       mention (b);
10340       tuple_emitter.emplace (uiout, "value");
10341       uiout->text ("\nOld value = ");
10342       watchpoint_value_print (bs->old_val.get (), &stb);
10343       uiout->field_stream ("old", stb);
10344       uiout->text ("\nNew value = ");
10345       watchpoint_value_print (w->val.get (), &stb);
10346       uiout->field_stream ("new", stb);
10347       uiout->text ("\n");
10348       /* More than one watchpoint may have been triggered.  */
10349       result = PRINT_UNKNOWN;
10350       break;
10351
10352     case bp_read_watchpoint:
10353       if (uiout->is_mi_like_p ())
10354         uiout->field_string
10355           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10356       mention (b);
10357       tuple_emitter.emplace (uiout, "value");
10358       uiout->text ("\nValue = ");
10359       watchpoint_value_print (w->val.get (), &stb);
10360       uiout->field_stream ("value", stb);
10361       uiout->text ("\n");
10362       result = PRINT_UNKNOWN;
10363       break;
10364
10365     case bp_access_watchpoint:
10366       if (bs->old_val != NULL)
10367         {
10368           if (uiout->is_mi_like_p ())
10369             uiout->field_string
10370               ("reason",
10371                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10372           mention (b);
10373           tuple_emitter.emplace (uiout, "value");
10374           uiout->text ("\nOld value = ");
10375           watchpoint_value_print (bs->old_val.get (), &stb);
10376           uiout->field_stream ("old", stb);
10377           uiout->text ("\nNew value = ");
10378         }
10379       else
10380         {
10381           mention (b);
10382           if (uiout->is_mi_like_p ())
10383             uiout->field_string
10384               ("reason",
10385                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10386           tuple_emitter.emplace (uiout, "value");
10387           uiout->text ("\nValue = ");
10388         }
10389       watchpoint_value_print (w->val.get (), &stb);
10390       uiout->field_stream ("new", stb);
10391       uiout->text ("\n");
10392       result = PRINT_UNKNOWN;
10393       break;
10394     default:
10395       result = PRINT_UNKNOWN;
10396     }
10397
10398   return result;
10399 }
10400
10401 /* Implement the "print_mention" breakpoint_ops method for hardware
10402    watchpoints.  */
10403
10404 static void
10405 print_mention_watchpoint (struct breakpoint *b)
10406 {
10407   struct watchpoint *w = (struct watchpoint *) b;
10408   struct ui_out *uiout = current_uiout;
10409   const char *tuple_name;
10410
10411   switch (b->type)
10412     {
10413     case bp_watchpoint:
10414       uiout->text ("Watchpoint ");
10415       tuple_name = "wpt";
10416       break;
10417     case bp_hardware_watchpoint:
10418       uiout->text ("Hardware watchpoint ");
10419       tuple_name = "wpt";
10420       break;
10421     case bp_read_watchpoint:
10422       uiout->text ("Hardware read watchpoint ");
10423       tuple_name = "hw-rwpt";
10424       break;
10425     case bp_access_watchpoint:
10426       uiout->text ("Hardware access (read/write) watchpoint ");
10427       tuple_name = "hw-awpt";
10428       break;
10429     default:
10430       internal_error (__FILE__, __LINE__,
10431                       _("Invalid hardware watchpoint type."));
10432     }
10433
10434   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10435   uiout->field_signed ("number", b->number);
10436   uiout->text (": ");
10437   uiout->field_string ("exp", w->exp_string);
10438 }
10439
10440 /* Implement the "print_recreate" breakpoint_ops method for
10441    watchpoints.  */
10442
10443 static void
10444 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10445 {
10446   struct watchpoint *w = (struct watchpoint *) b;
10447
10448   switch (b->type)
10449     {
10450     case bp_watchpoint:
10451     case bp_hardware_watchpoint:
10452       fprintf_unfiltered (fp, "watch");
10453       break;
10454     case bp_read_watchpoint:
10455       fprintf_unfiltered (fp, "rwatch");
10456       break;
10457     case bp_access_watchpoint:
10458       fprintf_unfiltered (fp, "awatch");
10459       break;
10460     default:
10461       internal_error (__FILE__, __LINE__,
10462                       _("Invalid watchpoint type."));
10463     }
10464
10465   fprintf_unfiltered (fp, " %s", w->exp_string);
10466   print_recreate_thread (b, fp);
10467 }
10468
10469 /* Implement the "explains_signal" breakpoint_ops method for
10470    watchpoints.  */
10471
10472 static int
10473 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10474 {
10475   /* A software watchpoint cannot cause a signal other than
10476      GDB_SIGNAL_TRAP.  */
10477   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10478     return 0;
10479
10480   return 1;
10481 }
10482
10483 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10484
10485 static struct breakpoint_ops watchpoint_breakpoint_ops;
10486
10487 /* Implement the "insert" breakpoint_ops method for
10488    masked hardware watchpoints.  */
10489
10490 static int
10491 insert_masked_watchpoint (struct bp_location *bl)
10492 {
10493   struct watchpoint *w = (struct watchpoint *) bl->owner;
10494
10495   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10496                                         bl->watchpoint_type);
10497 }
10498
10499 /* Implement the "remove" breakpoint_ops method for
10500    masked hardware watchpoints.  */
10501
10502 static int
10503 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10504 {
10505   struct watchpoint *w = (struct watchpoint *) bl->owner;
10506
10507   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10508                                         bl->watchpoint_type);
10509 }
10510
10511 /* Implement the "resources_needed" breakpoint_ops method for
10512    masked hardware watchpoints.  */
10513
10514 static int
10515 resources_needed_masked_watchpoint (const struct bp_location *bl)
10516 {
10517   struct watchpoint *w = (struct watchpoint *) bl->owner;
10518
10519   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10520 }
10521
10522 /* Implement the "works_in_software_mode" breakpoint_ops method for
10523    masked hardware watchpoints.  */
10524
10525 static int
10526 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10527 {
10528   return 0;
10529 }
10530
10531 /* Implement the "print_it" breakpoint_ops method for
10532    masked hardware watchpoints.  */
10533
10534 static enum print_stop_action
10535 print_it_masked_watchpoint (bpstat bs)
10536 {
10537   struct breakpoint *b = bs->breakpoint_at;
10538   struct ui_out *uiout = current_uiout;
10539
10540   /* Masked watchpoints have only one location.  */
10541   gdb_assert (b->loc && b->loc->next == NULL);
10542
10543   annotate_watchpoint (b->number);
10544   maybe_print_thread_hit_breakpoint (uiout);
10545
10546   switch (b->type)
10547     {
10548     case bp_hardware_watchpoint:
10549       if (uiout->is_mi_like_p ())
10550         uiout->field_string
10551           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10552       break;
10553
10554     case bp_read_watchpoint:
10555       if (uiout->is_mi_like_p ())
10556         uiout->field_string
10557           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10558       break;
10559
10560     case bp_access_watchpoint:
10561       if (uiout->is_mi_like_p ())
10562         uiout->field_string
10563           ("reason",
10564            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10565       break;
10566     default:
10567       internal_error (__FILE__, __LINE__,
10568                       _("Invalid hardware watchpoint type."));
10569     }
10570
10571   mention (b);
10572   uiout->text (_("\n\
10573 Check the underlying instruction at PC for the memory\n\
10574 address and value which triggered this watchpoint.\n"));
10575   uiout->text ("\n");
10576
10577   /* More than one watchpoint may have been triggered.  */
10578   return PRINT_UNKNOWN;
10579 }
10580
10581 /* Implement the "print_one_detail" breakpoint_ops method for
10582    masked hardware watchpoints.  */
10583
10584 static void
10585 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10586                                     struct ui_out *uiout)
10587 {
10588   struct watchpoint *w = (struct watchpoint *) b;
10589
10590   /* Masked watchpoints have only one location.  */
10591   gdb_assert (b->loc && b->loc->next == NULL);
10592
10593   uiout->text ("\tmask ");
10594   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10595   uiout->text ("\n");
10596 }
10597
10598 /* Implement the "print_mention" breakpoint_ops method for
10599    masked hardware watchpoints.  */
10600
10601 static void
10602 print_mention_masked_watchpoint (struct breakpoint *b)
10603 {
10604   struct watchpoint *w = (struct watchpoint *) b;
10605   struct ui_out *uiout = current_uiout;
10606   const char *tuple_name;
10607
10608   switch (b->type)
10609     {
10610     case bp_hardware_watchpoint:
10611       uiout->text ("Masked hardware watchpoint ");
10612       tuple_name = "wpt";
10613       break;
10614     case bp_read_watchpoint:
10615       uiout->text ("Masked hardware read watchpoint ");
10616       tuple_name = "hw-rwpt";
10617       break;
10618     case bp_access_watchpoint:
10619       uiout->text ("Masked hardware access (read/write) watchpoint ");
10620       tuple_name = "hw-awpt";
10621       break;
10622     default:
10623       internal_error (__FILE__, __LINE__,
10624                       _("Invalid hardware watchpoint type."));
10625     }
10626
10627   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10628   uiout->field_signed ("number", b->number);
10629   uiout->text (": ");
10630   uiout->field_string ("exp", w->exp_string);
10631 }
10632
10633 /* Implement the "print_recreate" breakpoint_ops method for
10634    masked hardware watchpoints.  */
10635
10636 static void
10637 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10638 {
10639   struct watchpoint *w = (struct watchpoint *) b;
10640
10641   switch (b->type)
10642     {
10643     case bp_hardware_watchpoint:
10644       fprintf_unfiltered (fp, "watch");
10645       break;
10646     case bp_read_watchpoint:
10647       fprintf_unfiltered (fp, "rwatch");
10648       break;
10649     case bp_access_watchpoint:
10650       fprintf_unfiltered (fp, "awatch");
10651       break;
10652     default:
10653       internal_error (__FILE__, __LINE__,
10654                       _("Invalid hardware watchpoint type."));
10655     }
10656
10657   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string,
10658                       phex (w->hw_wp_mask, sizeof (CORE_ADDR)));
10659   print_recreate_thread (b, fp);
10660 }
10661
10662 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10663
10664 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10665
10666 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10667
10668 static bool
10669 is_masked_watchpoint (const struct breakpoint *b)
10670 {
10671   return b->ops == &masked_watchpoint_breakpoint_ops;
10672 }
10673
10674 /* accessflag:  hw_write:  watch write, 
10675                 hw_read:   watch read, 
10676                 hw_access: watch access (read or write) */
10677 static void
10678 watch_command_1 (const char *arg, int accessflag, int from_tty,
10679                  bool just_location, bool internal)
10680 {
10681   struct breakpoint *scope_breakpoint = NULL;
10682   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10683   struct value *result;
10684   int saved_bitpos = 0, saved_bitsize = 0;
10685   const char *exp_start = NULL;
10686   const char *exp_end = NULL;
10687   const char *tok, *end_tok;
10688   int toklen = -1;
10689   const char *cond_start = NULL;
10690   const char *cond_end = NULL;
10691   enum bptype bp_type;
10692   int thread = -1;
10693   int pc = 0;
10694   /* Flag to indicate whether we are going to use masks for
10695      the hardware watchpoint.  */
10696   bool use_mask = false;
10697   CORE_ADDR mask = 0;
10698
10699   /* Make sure that we actually have parameters to parse.  */
10700   if (arg != NULL && arg[0] != '\0')
10701     {
10702       const char *value_start;
10703
10704       exp_end = arg + strlen (arg);
10705
10706       /* Look for "parameter value" pairs at the end
10707          of the arguments string.  */
10708       for (tok = exp_end - 1; tok > arg; tok--)
10709         {
10710           /* Skip whitespace at the end of the argument list.  */
10711           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10712             tok--;
10713
10714           /* Find the beginning of the last token.
10715              This is the value of the parameter.  */
10716           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10717             tok--;
10718           value_start = tok + 1;
10719
10720           /* Skip whitespace.  */
10721           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10722             tok--;
10723
10724           end_tok = tok;
10725
10726           /* Find the beginning of the second to last token.
10727              This is the parameter itself.  */
10728           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10729             tok--;
10730           tok++;
10731           toklen = end_tok - tok + 1;
10732
10733           if (toklen == 6 && startswith (tok, "thread"))
10734             {
10735               struct thread_info *thr;
10736               /* At this point we've found a "thread" token, which means
10737                  the user is trying to set a watchpoint that triggers
10738                  only in a specific thread.  */
10739               const char *endp;
10740
10741               if (thread != -1)
10742                 error(_("You can specify only one thread."));
10743
10744               /* Extract the thread ID from the next token.  */
10745               thr = parse_thread_id (value_start, &endp);
10746
10747               /* Check if the user provided a valid thread ID.  */
10748               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10749                 invalid_thread_id_error (value_start);
10750
10751               thread = thr->global_num;
10752             }
10753           else if (toklen == 4 && startswith (tok, "mask"))
10754             {
10755               /* We've found a "mask" token, which means the user wants to
10756                  create a hardware watchpoint that is going to have the mask
10757                  facility.  */
10758               struct value *mask_value, *mark;
10759
10760               if (use_mask)
10761                 error(_("You can specify only one mask."));
10762
10763               use_mask = just_location = true;
10764
10765               mark = value_mark ();
10766               mask_value = parse_to_comma_and_eval (&value_start);
10767               mask = value_as_address (mask_value);
10768               value_free_to_mark (mark);
10769             }
10770           else
10771             /* We didn't recognize what we found.  We should stop here.  */
10772             break;
10773
10774           /* Truncate the string and get rid of the "parameter value" pair before
10775              the arguments string is parsed by the parse_exp_1 function.  */
10776           exp_end = tok;
10777         }
10778     }
10779   else
10780     exp_end = arg;
10781
10782   /* Parse the rest of the arguments.  From here on out, everything
10783      is in terms of a newly allocated string instead of the original
10784      ARG.  */
10785   std::string expression (arg, exp_end - arg);
10786   exp_start = arg = expression.c_str ();
10787   innermost_block_tracker tracker;
10788   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10789   exp_end = arg;
10790   /* Remove trailing whitespace from the expression before saving it.
10791      This makes the eventual display of the expression string a bit
10792      prettier.  */
10793   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10794     --exp_end;
10795
10796   /* Checking if the expression is not constant.  */
10797   if (watchpoint_exp_is_const (exp.get ()))
10798     {
10799       int len;
10800
10801       len = exp_end - exp_start;
10802       while (len > 0 && isspace (exp_start[len - 1]))
10803         len--;
10804       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10805     }
10806
10807   exp_valid_block = tracker.block ();
10808   struct value *mark = value_mark ();
10809   struct value *val_as_value = nullptr;
10810   fetch_subexp_value (exp.get (), &pc, &val_as_value, &result, NULL,
10811                       just_location);
10812
10813   if (val_as_value != NULL && just_location)
10814     {
10815       saved_bitpos = value_bitpos (val_as_value);
10816       saved_bitsize = value_bitsize (val_as_value);
10817     }
10818
10819   value_ref_ptr val;
10820   if (just_location)
10821     {
10822       int ret;
10823
10824       exp_valid_block = NULL;
10825       val = release_value (value_addr (result));
10826       value_free_to_mark (mark);
10827
10828       if (use_mask)
10829         {
10830           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10831                                                    mask);
10832           if (ret == -1)
10833             error (_("This target does not support masked watchpoints."));
10834           else if (ret == -2)
10835             error (_("Invalid mask or memory region."));
10836         }
10837     }
10838   else if (val_as_value != NULL)
10839     val = release_value (val_as_value);
10840
10841   tok = skip_spaces (arg);
10842   end_tok = skip_to_space (tok);
10843
10844   toklen = end_tok - tok;
10845   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10846     {
10847       tok = cond_start = end_tok + 1;
10848       innermost_block_tracker if_tracker;
10849       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10850
10851       /* The watchpoint expression may not be local, but the condition
10852          may still be.  E.g.: `watch global if local > 0'.  */
10853       cond_exp_valid_block = if_tracker.block ();
10854
10855       cond_end = tok;
10856     }
10857   if (*tok)
10858     error (_("Junk at end of command."));
10859
10860   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10861
10862   /* Save this because create_internal_breakpoint below invalidates
10863      'wp_frame'.  */
10864   frame_id watchpoint_frame = get_frame_id (wp_frame);
10865
10866   /* If the expression is "local", then set up a "watchpoint scope"
10867      breakpoint at the point where we've left the scope of the watchpoint
10868      expression.  Create the scope breakpoint before the watchpoint, so
10869      that we will encounter it first in bpstat_stop_status.  */
10870   if (exp_valid_block != NULL && wp_frame != NULL)
10871     {
10872       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10873
10874       if (frame_id_p (caller_frame_id))
10875         {
10876           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10877           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10878
10879           scope_breakpoint
10880             = create_internal_breakpoint (caller_arch, caller_pc,
10881                                           bp_watchpoint_scope,
10882                                           &momentary_breakpoint_ops);
10883
10884           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10885           wp_frame = NULL;
10886
10887           scope_breakpoint->enable_state = bp_enabled;
10888
10889           /* Automatically delete the breakpoint when it hits.  */
10890           scope_breakpoint->disposition = disp_del;
10891
10892           /* Only break in the proper frame (help with recursion).  */
10893           scope_breakpoint->frame_id = caller_frame_id;
10894
10895           /* Set the address at which we will stop.  */
10896           scope_breakpoint->loc->gdbarch = caller_arch;
10897           scope_breakpoint->loc->requested_address = caller_pc;
10898           scope_breakpoint->loc->address
10899             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10900                                          scope_breakpoint->loc->requested_address,
10901                                          scope_breakpoint->type);
10902         }
10903     }
10904
10905   /* Now set up the breakpoint.  We create all watchpoints as hardware
10906      watchpoints here even if hardware watchpoints are turned off, a call
10907      to update_watchpoint later in this function will cause the type to
10908      drop back to bp_watchpoint (software watchpoint) if required.  */
10909
10910   if (accessflag == hw_read)
10911     bp_type = bp_read_watchpoint;
10912   else if (accessflag == hw_access)
10913     bp_type = bp_access_watchpoint;
10914   else
10915     bp_type = bp_hardware_watchpoint;
10916
10917   std::unique_ptr<watchpoint> w (new watchpoint ());
10918
10919   if (use_mask)
10920     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10921                                           &masked_watchpoint_breakpoint_ops);
10922   else
10923     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10924                                           &watchpoint_breakpoint_ops);
10925   w->thread = thread;
10926   w->disposition = disp_donttouch;
10927   w->pspace = current_program_space;
10928   w->exp = std::move (exp);
10929   w->exp_valid_block = exp_valid_block;
10930   w->cond_exp_valid_block = cond_exp_valid_block;
10931   if (just_location)
10932     {
10933       struct type *t = value_type (val.get ());
10934       CORE_ADDR addr = value_as_address (val.get ());
10935
10936       w->exp_string_reparse
10937         = current_language->watch_location_expression (t, addr).release ();
10938
10939       w->exp_string = xstrprintf ("-location %.*s",
10940                                   (int) (exp_end - exp_start), exp_start);
10941     }
10942   else
10943     w->exp_string = savestring (exp_start, exp_end - exp_start);
10944
10945   if (use_mask)
10946     {
10947       w->hw_wp_mask = mask;
10948     }
10949   else
10950     {
10951       w->val = val;
10952       w->val_bitpos = saved_bitpos;
10953       w->val_bitsize = saved_bitsize;
10954       w->val_valid = true;
10955     }
10956
10957   if (cond_start)
10958     w->cond_string = savestring (cond_start, cond_end - cond_start);
10959   else
10960     w->cond_string = 0;
10961
10962   if (frame_id_p (watchpoint_frame))
10963     {
10964       w->watchpoint_frame = watchpoint_frame;
10965       w->watchpoint_thread = inferior_ptid;
10966     }
10967   else
10968     {
10969       w->watchpoint_frame = null_frame_id;
10970       w->watchpoint_thread = null_ptid;
10971     }
10972
10973   if (scope_breakpoint != NULL)
10974     {
10975       /* The scope breakpoint is related to the watchpoint.  We will
10976          need to act on them together.  */
10977       w->related_breakpoint = scope_breakpoint;
10978       scope_breakpoint->related_breakpoint = w.get ();
10979     }
10980
10981   if (!just_location)
10982     value_free_to_mark (mark);
10983
10984   /* Finally update the new watchpoint.  This creates the locations
10985      that should be inserted.  */
10986   update_watchpoint (w.get (), 1);
10987
10988   install_breakpoint (internal, std::move (w), 1);
10989 }
10990
10991 /* Return count of debug registers needed to watch the given expression.
10992    If the watchpoint cannot be handled in hardware return zero.  */
10993
10994 static int
10995 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10996 {
10997   int found_memory_cnt = 0;
10998
10999   /* Did the user specifically forbid us to use hardware watchpoints? */
11000   if (!can_use_hw_watchpoints)
11001     return 0;
11002
11003   gdb_assert (!vals.empty ());
11004   struct value *head = vals[0].get ();
11005
11006   /* Make sure that the value of the expression depends only upon
11007      memory contents, and values computed from them within GDB.  If we
11008      find any register references or function calls, we can't use a
11009      hardware watchpoint.
11010
11011      The idea here is that evaluating an expression generates a series
11012      of values, one holding the value of every subexpression.  (The
11013      expression a*b+c has five subexpressions: a, b, a*b, c, and
11014      a*b+c.)  GDB's values hold almost enough information to establish
11015      the criteria given above --- they identify memory lvalues,
11016      register lvalues, computed values, etcetera.  So we can evaluate
11017      the expression, and then scan the chain of values that leaves
11018      behind to decide whether we can detect any possible change to the
11019      expression's final value using only hardware watchpoints.
11020
11021      However, I don't think that the values returned by inferior
11022      function calls are special in any way.  So this function may not
11023      notice that an expression involving an inferior function call
11024      can't be watched with hardware watchpoints.  FIXME.  */
11025   for (const value_ref_ptr &iter : vals)
11026     {
11027       struct value *v = iter.get ();
11028
11029       if (VALUE_LVAL (v) == lval_memory)
11030         {
11031           if (v != head && value_lazy (v))
11032             /* A lazy memory lvalue in the chain is one that GDB never
11033                needed to fetch; we either just used its address (e.g.,
11034                `a' in `a.b') or we never needed it at all (e.g., `a'
11035                in `a,b').  This doesn't apply to HEAD; if that is
11036                lazy then it was not readable, but watch it anyway.  */
11037             ;
11038           else
11039             {
11040               /* Ahh, memory we actually used!  Check if we can cover
11041                  it with hardware watchpoints.  */
11042               struct type *vtype = check_typedef (value_type (v));
11043
11044               /* We only watch structs and arrays if user asked for it
11045                  explicitly, never if they just happen to appear in a
11046                  middle of some value chain.  */
11047               if (v == head
11048                   || (vtype->code () != TYPE_CODE_STRUCT
11049                       && vtype->code () != TYPE_CODE_ARRAY))
11050                 {
11051                   CORE_ADDR vaddr = value_address (v);
11052                   int len;
11053                   int num_regs;
11054
11055                   len = (target_exact_watchpoints
11056                          && is_scalar_type_recursive (vtype))?
11057                     1 : TYPE_LENGTH (value_type (v));
11058
11059                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11060                   if (!num_regs)
11061                     return 0;
11062                   else
11063                     found_memory_cnt += num_regs;
11064                 }
11065             }
11066         }
11067       else if (VALUE_LVAL (v) != not_lval
11068                && deprecated_value_modifiable (v) == 0)
11069         return 0;       /* These are values from the history (e.g., $1).  */
11070       else if (VALUE_LVAL (v) == lval_register)
11071         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11072     }
11073
11074   /* The expression itself looks suitable for using a hardware
11075      watchpoint, but give the target machine a chance to reject it.  */
11076   return found_memory_cnt;
11077 }
11078
11079 void
11080 watch_command_wrapper (const char *arg, int from_tty, bool internal)
11081 {
11082   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11083 }
11084
11085 /* Options for the watch, awatch, and rwatch commands.  */
11086
11087 struct watch_options
11088 {
11089   /* For -location.  */
11090   bool location = false;
11091 };
11092
11093 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
11094
11095    Historically GDB always accepted both '-location' and '-l' flags for
11096    these commands (both flags being synonyms).  When converting to the
11097    newer option scheme only '-location' is added here.  That's fine (for
11098    backward compatibility) as any non-ambiguous prefix of a flag will be
11099    accepted, so '-l', '-loc', are now all accepted.
11100
11101    What this means is that, if in the future, we add any new flag here
11102    that starts with '-l' then this will break backward compatibility, so
11103    please, don't do that!  */
11104
11105 static const gdb::option::option_def watch_option_defs[] = {
11106   gdb::option::flag_option_def<watch_options> {
11107     "location",
11108     [] (watch_options *opt) { return &opt->location; },
11109     N_("\
11110 This evaluates EXPRESSION and watches the memory to which is refers.\n\
11111 -l can be used as a short form of -location."),
11112   },
11113 };
11114
11115 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
11116    commands.  */
11117
11118 static gdb::option::option_def_group
11119 make_watch_options_def_group (watch_options *opts)
11120 {
11121   return {{watch_option_defs}, opts};
11122 }
11123
11124 /* A helper function that looks for the "-location" argument and then
11125    calls watch_command_1.  */
11126
11127 static void
11128 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11129 {
11130   watch_options opts;
11131   auto grp = make_watch_options_def_group (&opts);
11132   gdb::option::process_options
11133     (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
11134   if (arg != nullptr && *arg == '\0')
11135     arg = nullptr;
11136
11137   watch_command_1 (arg, accessflag, from_tty, opts.location, false);
11138 }
11139
11140 /* Command completion for 'watch', 'awatch', and 'rwatch' commands.   */
11141 static void
11142 watch_command_completer (struct cmd_list_element *ignore,
11143                          completion_tracker &tracker,
11144                          const char *text, const char * /*word*/)
11145 {
11146   const auto group = make_watch_options_def_group (nullptr);
11147   if (gdb::option::complete_options
11148       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
11149     return;
11150
11151   const char *word = advance_to_expression_complete_word_point (tracker, text);
11152   expression_completer (ignore, tracker, text, word);
11153 }
11154
11155 static void
11156 watch_command (const char *arg, int from_tty)
11157 {
11158   watch_maybe_just_location (arg, hw_write, from_tty);
11159 }
11160
11161 void
11162 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
11163 {
11164   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11165 }
11166
11167 static void
11168 rwatch_command (const char *arg, int from_tty)
11169 {
11170   watch_maybe_just_location (arg, hw_read, from_tty);
11171 }
11172
11173 void
11174 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
11175 {
11176   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11177 }
11178
11179 static void
11180 awatch_command (const char *arg, int from_tty)
11181 {
11182   watch_maybe_just_location (arg, hw_access, from_tty);
11183 }
11184 \f
11185
11186 /* Data for the FSM that manages the until(location)/advance commands
11187    in infcmd.c.  Here because it uses the mechanisms of
11188    breakpoints.  */
11189
11190 struct until_break_fsm : public thread_fsm
11191 {
11192   /* The thread that was current when the command was executed.  */
11193   int thread;
11194
11195   /* The breakpoint set at the return address in the caller frame,
11196      plus breakpoints at all the destination locations.  */
11197   std::vector<breakpoint_up> breakpoints;
11198
11199   until_break_fsm (struct interp *cmd_interp, int thread,
11200                    std::vector<breakpoint_up> &&breakpoints)
11201     : thread_fsm (cmd_interp),
11202       thread (thread),
11203       breakpoints (std::move (breakpoints))
11204   {
11205   }
11206
11207   void clean_up (struct thread_info *thread) override;
11208   bool should_stop (struct thread_info *thread) override;
11209   enum async_reply_reason do_async_reply_reason () override;
11210 };
11211
11212 /* Implementation of the 'should_stop' FSM method for the
11213    until(location)/advance commands.  */
11214
11215 bool
11216 until_break_fsm::should_stop (struct thread_info *tp)
11217 {
11218   for (const breakpoint_up &bp : breakpoints)
11219     if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11220                                 bp.get ()) != NULL)
11221       {
11222         set_finished ();
11223         break;
11224       }
11225
11226   return true;
11227 }
11228
11229 /* Implementation of the 'clean_up' FSM method for the
11230    until(location)/advance commands.  */
11231
11232 void
11233 until_break_fsm::clean_up (struct thread_info *)
11234 {
11235   /* Clean up our temporary breakpoints.  */
11236   breakpoints.clear ();
11237   delete_longjmp_breakpoint (thread);
11238 }
11239
11240 /* Implementation of the 'async_reply_reason' FSM method for the
11241    until(location)/advance commands.  */
11242
11243 enum async_reply_reason
11244 until_break_fsm::do_async_reply_reason ()
11245 {
11246   return EXEC_ASYNC_LOCATION_REACHED;
11247 }
11248
11249 void
11250 until_break_command (const char *arg, int from_tty, int anywhere)
11251 {
11252   struct frame_info *frame;
11253   struct gdbarch *frame_gdbarch;
11254   struct frame_id stack_frame_id;
11255   struct frame_id caller_frame_id;
11256   int thread;
11257   struct thread_info *tp;
11258
11259   clear_proceed_status (0);
11260
11261   /* Set a breakpoint where the user wants it and at return from
11262      this function.  */
11263
11264   event_location_up location = string_to_event_location (&arg, current_language);
11265
11266   std::vector<symtab_and_line> sals
11267     = (last_displayed_sal_is_valid ()
11268        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11269                         get_last_displayed_symtab (),
11270                         get_last_displayed_line ())
11271        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11272                         NULL, NULL, 0));
11273
11274   if (sals.empty ())
11275     error (_("Couldn't get information on specified line."));
11276
11277   if (*arg)
11278     error (_("Junk at end of arguments."));
11279
11280   tp = inferior_thread ();
11281   thread = tp->global_num;
11282
11283   /* Note linespec handling above invalidates the frame chain.
11284      Installing a breakpoint also invalidates the frame chain (as it
11285      may need to switch threads), so do any frame handling before
11286      that.  */
11287
11288   frame = get_selected_frame (NULL);
11289   frame_gdbarch = get_frame_arch (frame);
11290   stack_frame_id = get_stack_frame_id (frame);
11291   caller_frame_id = frame_unwind_caller_id (frame);
11292
11293   /* Keep within the current frame, or in frames called by the current
11294      one.  */
11295
11296   std::vector<breakpoint_up> breakpoints;
11297
11298   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
11299
11300   if (frame_id_p (caller_frame_id))
11301     {
11302       struct symtab_and_line sal2;
11303       struct gdbarch *caller_gdbarch;
11304
11305       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11306       sal2.pc = frame_unwind_caller_pc (frame);
11307       caller_gdbarch = frame_unwind_caller_arch (frame);
11308
11309       breakpoint_up caller_breakpoint
11310         = set_momentary_breakpoint (caller_gdbarch, sal2,
11311                                     caller_frame_id, bp_until);
11312       breakpoints.emplace_back (std::move (caller_breakpoint));
11313
11314       set_longjmp_breakpoint (tp, caller_frame_id);
11315       lj_deleter.emplace (thread);
11316     }
11317
11318   /* set_momentary_breakpoint could invalidate FRAME.  */
11319   frame = NULL;
11320
11321   /* If the user told us to continue until a specified location, we
11322      don't specify a frame at which we need to stop.  Otherwise,
11323      specify the selected frame, because we want to stop only at the
11324      very same frame.  */
11325   frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
11326
11327   for (symtab_and_line &sal : sals)
11328     {
11329       resolve_sal_pc (&sal);
11330
11331       breakpoint_up location_breakpoint
11332         = set_momentary_breakpoint (frame_gdbarch, sal,
11333                                     stop_frame_id, bp_until);
11334       breakpoints.emplace_back (std::move (location_breakpoint));
11335     }
11336
11337   tp->thread_fsm = new until_break_fsm (command_interp (), tp->global_num,
11338                                         std::move (breakpoints));
11339
11340   if (lj_deleter)
11341     lj_deleter->release ();
11342
11343   proceed (-1, GDB_SIGNAL_DEFAULT);
11344 }
11345
11346 /* This function attempts to parse an optional "if <cond>" clause
11347    from the arg string.  If one is not found, it returns NULL.
11348
11349    Else, it returns a pointer to the condition string.  (It does not
11350    attempt to evaluate the string against a particular block.)  And,
11351    it updates arg to point to the first character following the parsed
11352    if clause in the arg string.  */
11353
11354 const char *
11355 ep_parse_optional_if_clause (const char **arg)
11356 {
11357   const char *cond_string;
11358
11359   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11360     return NULL;
11361
11362   /* Skip the "if" keyword.  */
11363   (*arg) += 2;
11364
11365   /* Skip any extra leading whitespace, and record the start of the
11366      condition string.  */
11367   *arg = skip_spaces (*arg);
11368   cond_string = *arg;
11369
11370   /* Assume that the condition occupies the remainder of the arg
11371      string.  */
11372   (*arg) += strlen (cond_string);
11373
11374   return cond_string;
11375 }
11376
11377 /* Commands to deal with catching events, such as signals, exceptions,
11378    process start/exit, etc.  */
11379
11380 typedef enum
11381 {
11382   catch_fork_temporary, catch_vfork_temporary,
11383   catch_fork_permanent, catch_vfork_permanent
11384 }
11385 catch_fork_kind;
11386
11387 static void
11388 catch_fork_command_1 (const char *arg, int from_tty,
11389                       struct cmd_list_element *command)
11390 {
11391   struct gdbarch *gdbarch = get_current_arch ();
11392   const char *cond_string = NULL;
11393   catch_fork_kind fork_kind;
11394
11395   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11396   bool temp = (fork_kind == catch_fork_temporary
11397                || fork_kind == catch_vfork_temporary);
11398
11399   if (!arg)
11400     arg = "";
11401   arg = skip_spaces (arg);
11402
11403   /* The allowed syntax is:
11404      catch [v]fork
11405      catch [v]fork if <cond>
11406
11407      First, check if there's an if clause.  */
11408   cond_string = ep_parse_optional_if_clause (&arg);
11409
11410   if ((*arg != '\0') && !isspace (*arg))
11411     error (_("Junk at end of arguments."));
11412
11413   /* If this target supports it, create a fork or vfork catchpoint
11414      and enable reporting of such events.  */
11415   switch (fork_kind)
11416     {
11417     case catch_fork_temporary:
11418     case catch_fork_permanent:
11419       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11420                                           &catch_fork_breakpoint_ops);
11421       break;
11422     case catch_vfork_temporary:
11423     case catch_vfork_permanent:
11424       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11425                                           &catch_vfork_breakpoint_ops);
11426       break;
11427     default:
11428       error (_("unsupported or unknown fork kind; cannot catch it"));
11429       break;
11430     }
11431 }
11432
11433 static void
11434 catch_exec_command_1 (const char *arg, int from_tty,
11435                       struct cmd_list_element *command)
11436 {
11437   struct gdbarch *gdbarch = get_current_arch ();
11438   const char *cond_string = NULL;
11439   bool temp = get_cmd_context (command) == CATCH_TEMPORARY;
11440
11441   if (!arg)
11442     arg = "";
11443   arg = skip_spaces (arg);
11444
11445   /* The allowed syntax is:
11446      catch exec
11447      catch exec if <cond>
11448
11449      First, check if there's an if clause.  */
11450   cond_string = ep_parse_optional_if_clause (&arg);
11451
11452   if ((*arg != '\0') && !isspace (*arg))
11453     error (_("Junk at end of arguments."));
11454
11455   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11456   init_catchpoint (c.get (), gdbarch, temp, cond_string,
11457                    &catch_exec_breakpoint_ops);
11458   c->exec_pathname = NULL;
11459
11460   install_breakpoint (0, std::move (c), 1);
11461 }
11462
11463 void
11464 init_ada_exception_breakpoint (struct breakpoint *b,
11465                                struct gdbarch *gdbarch,
11466                                struct symtab_and_line sal,
11467                                const char *addr_string,
11468                                const struct breakpoint_ops *ops,
11469                                int tempflag,
11470                                int enabled,
11471                                int from_tty)
11472 {
11473   if (from_tty)
11474     {
11475       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11476       if (!loc_gdbarch)
11477         loc_gdbarch = gdbarch;
11478
11479       describe_other_breakpoints (loc_gdbarch,
11480                                   sal.pspace, sal.pc, sal.section, -1);
11481       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11482          version for exception catchpoints, because two catchpoints
11483          used for different exception names will use the same address.
11484          In this case, a "breakpoint ... also set at..." warning is
11485          unproductive.  Besides, the warning phrasing is also a bit
11486          inappropriate, we should use the word catchpoint, and tell
11487          the user what type of catchpoint it is.  The above is good
11488          enough for now, though.  */
11489     }
11490
11491   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
11492
11493   b->enable_state = enabled ? bp_enabled : bp_disabled;
11494   b->disposition = tempflag ? disp_del : disp_donttouch;
11495   b->location = string_to_event_location (&addr_string,
11496                                           language_def (language_ada));
11497   b->language = language_ada;
11498 }
11499
11500 \f
11501
11502 /* Compare two breakpoints and return a strcmp-like result.  */
11503
11504 static int
11505 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11506 {
11507   uintptr_t ua = (uintptr_t) a;
11508   uintptr_t ub = (uintptr_t) b;
11509
11510   if (a->number < b->number)
11511     return -1;
11512   else if (a->number > b->number)
11513     return 1;
11514
11515   /* Now sort by address, in case we see, e..g, two breakpoints with
11516      the number 0.  */
11517   if (ua < ub)
11518     return -1;
11519   return ua > ub ? 1 : 0;
11520 }
11521
11522 /* Delete breakpoints by address or line.  */
11523
11524 static void
11525 clear_command (const char *arg, int from_tty)
11526 {
11527   struct breakpoint *b;
11528   int default_match;
11529
11530   std::vector<symtab_and_line> decoded_sals;
11531   symtab_and_line last_sal;
11532   gdb::array_view<symtab_and_line> sals;
11533   if (arg)
11534     {
11535       decoded_sals
11536         = decode_line_with_current_source (arg,
11537                                            (DECODE_LINE_FUNFIRSTLINE
11538                                             | DECODE_LINE_LIST_MODE));
11539       default_match = 0;
11540       sals = decoded_sals;
11541     }
11542   else
11543     {
11544       /* Set sal's line, symtab, pc, and pspace to the values
11545          corresponding to the last call to print_frame_info.  If the
11546          codepoint is not valid, this will set all the fields to 0.  */
11547       last_sal = get_last_displayed_sal ();
11548       if (last_sal.symtab == 0)
11549         error (_("No source file specified."));
11550
11551       default_match = 1;
11552       sals = last_sal;
11553     }
11554
11555   /* We don't call resolve_sal_pc here.  That's not as bad as it
11556      seems, because all existing breakpoints typically have both
11557      file/line and pc set.  So, if clear is given file/line, we can
11558      match this to existing breakpoint without obtaining pc at all.
11559
11560      We only support clearing given the address explicitly 
11561      present in breakpoint table.  Say, we've set breakpoint 
11562      at file:line.  There were several PC values for that file:line,
11563      due to optimization, all in one block.
11564
11565      We've picked one PC value.  If "clear" is issued with another
11566      PC corresponding to the same file:line, the breakpoint won't
11567      be cleared.  We probably can still clear the breakpoint, but 
11568      since the other PC value is never presented to user, user
11569      can only find it by guessing, and it does not seem important
11570      to support that.  */
11571
11572   /* For each line spec given, delete bps which correspond to it.  Do
11573      it in two passes, solely to preserve the current behavior that
11574      from_tty is forced true if we delete more than one
11575      breakpoint.  */
11576
11577   std::vector<struct breakpoint *> found;
11578   for (const auto &sal : sals)
11579     {
11580       const char *sal_fullname;
11581
11582       /* If exact pc given, clear bpts at that pc.
11583          If line given (pc == 0), clear all bpts on specified line.
11584          If defaulting, clear all bpts on default line
11585          or at default pc.
11586
11587          defaulting    sal.pc != 0    tests to do
11588
11589          0              1             pc
11590          1              1             pc _and_ line
11591          0              0             line
11592          1              0             <can't happen> */
11593
11594       sal_fullname = (sal.symtab == NULL
11595                       ? NULL : symtab_to_fullname (sal.symtab));
11596
11597       /* Find all matching breakpoints and add them to 'found'.  */
11598       ALL_BREAKPOINTS (b)
11599         {
11600           int match = 0;
11601           /* Are we going to delete b?  */
11602           if (b->type != bp_none && !is_watchpoint (b))
11603             {
11604               struct bp_location *loc = b->loc;
11605               for (; loc; loc = loc->next)
11606                 {
11607                   /* If the user specified file:line, don't allow a PC
11608                      match.  This matches historical gdb behavior.  */
11609                   int pc_match = (!sal.explicit_line
11610                                   && sal.pc
11611                                   && (loc->pspace == sal.pspace)
11612                                   && (loc->address == sal.pc)
11613                                   && (!section_is_overlay (loc->section)
11614                                       || loc->section == sal.section));
11615                   int line_match = 0;
11616
11617                   if ((default_match || sal.explicit_line)
11618                       && loc->symtab != NULL
11619                       && sal_fullname != NULL
11620                       && sal.pspace == loc->pspace
11621                       && loc->line_number == sal.line
11622                       && filename_cmp (symtab_to_fullname (loc->symtab),
11623                                        sal_fullname) == 0)
11624                     line_match = 1;
11625
11626                   if (pc_match || line_match)
11627                     {
11628                       match = 1;
11629                       break;
11630                     }
11631                 }
11632             }
11633
11634           if (match)
11635             found.push_back (b);
11636         }
11637     }
11638
11639   /* Now go thru the 'found' chain and delete them.  */
11640   if (found.empty ())
11641     {
11642       if (arg)
11643         error (_("No breakpoint at %s."), arg);
11644       else
11645         error (_("No breakpoint at this line."));
11646     }
11647
11648   /* Remove duplicates from the vec.  */
11649   std::sort (found.begin (), found.end (),
11650              [] (const breakpoint *bp_a, const breakpoint *bp_b)
11651              {
11652                return compare_breakpoints (bp_a, bp_b) < 0;
11653              });
11654   found.erase (std::unique (found.begin (), found.end (),
11655                             [] (const breakpoint *bp_a, const breakpoint *bp_b)
11656                             {
11657                               return compare_breakpoints (bp_a, bp_b) == 0;
11658                             }),
11659                found.end ());
11660
11661   if (found.size () > 1)
11662     from_tty = 1;       /* Always report if deleted more than one.  */
11663   if (from_tty)
11664     {
11665       if (found.size () == 1)
11666         printf_unfiltered (_("Deleted breakpoint "));
11667       else
11668         printf_unfiltered (_("Deleted breakpoints "));
11669     }
11670
11671   for (breakpoint *iter : found)
11672     {
11673       if (from_tty)
11674         printf_unfiltered ("%d ", iter->number);
11675       delete_breakpoint (iter);
11676     }
11677   if (from_tty)
11678     putchar_unfiltered ('\n');
11679 }
11680 \f
11681 /* Delete breakpoint in BS if they are `delete' breakpoints and
11682    all breakpoints that are marked for deletion, whether hit or not.
11683    This is called after any breakpoint is hit, or after errors.  */
11684
11685 void
11686 breakpoint_auto_delete (bpstat bs)
11687 {
11688   struct breakpoint *b, *b_tmp;
11689
11690   for (; bs; bs = bs->next)
11691     if (bs->breakpoint_at
11692         && bs->breakpoint_at->disposition == disp_del
11693         && bs->stop)
11694       delete_breakpoint (bs->breakpoint_at);
11695
11696   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11697   {
11698     if (b->disposition == disp_del_at_next_stop)
11699       delete_breakpoint (b);
11700   }
11701 }
11702
11703 /* A comparison function for bp_location AP and BP being interfaced to
11704    std::sort.  Sort elements primarily by their ADDRESS (no matter what
11705    bl_address_is_meaningful says), secondarily by ordering first
11706    permanent elements and terciarily just ensuring the array is sorted
11707    stable way despite std::sort being an unstable algorithm.  */
11708
11709 static int
11710 bp_location_is_less_than (const bp_location *a, const bp_location *b)
11711 {
11712   if (a->address != b->address)
11713     return a->address < b->address;
11714
11715   /* Sort locations at the same address by their pspace number, keeping
11716      locations of the same inferior (in a multi-inferior environment)
11717      grouped.  */
11718
11719   if (a->pspace->num != b->pspace->num)
11720     return a->pspace->num < b->pspace->num;
11721
11722   /* Sort permanent breakpoints first.  */
11723   if (a->permanent != b->permanent)
11724     return a->permanent > b->permanent;
11725
11726   /* Sort by type in order to make duplicate determination easier.
11727      See update_global_location_list.  This is kept in sync with
11728      breakpoint_locations_match.  */
11729   if (a->loc_type < b->loc_type)
11730     return true;
11731
11732   /* Likewise, for range-breakpoints, sort by length.  */
11733   if (a->loc_type == bp_loc_hardware_breakpoint
11734       && b->loc_type == bp_loc_hardware_breakpoint
11735       && a->length < b->length)
11736     return true;
11737
11738   /* Make the internal GDB representation stable across GDB runs
11739      where A and B memory inside GDB can differ.  Breakpoint locations of
11740      the same type at the same address can be sorted in arbitrary order.  */
11741
11742   if (a->owner->number != b->owner->number)
11743     return a->owner->number < b->owner->number;
11744
11745   return a < b;
11746 }
11747
11748 /* Set bp_locations_placed_address_before_address_max and
11749    bp_locations_shadow_len_after_address_max according to the current
11750    content of the bp_locations array.  */
11751
11752 static void
11753 bp_locations_target_extensions_update (void)
11754 {
11755   struct bp_location *bl, **blp_tmp;
11756
11757   bp_locations_placed_address_before_address_max = 0;
11758   bp_locations_shadow_len_after_address_max = 0;
11759
11760   ALL_BP_LOCATIONS (bl, blp_tmp)
11761     {
11762       CORE_ADDR start, end, addr;
11763
11764       if (!bp_location_has_shadow (bl))
11765         continue;
11766
11767       start = bl->target_info.placed_address;
11768       end = start + bl->target_info.shadow_len;
11769
11770       gdb_assert (bl->address >= start);
11771       addr = bl->address - start;
11772       if (addr > bp_locations_placed_address_before_address_max)
11773         bp_locations_placed_address_before_address_max = addr;
11774
11775       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11776
11777       gdb_assert (bl->address < end);
11778       addr = end - bl->address;
11779       if (addr > bp_locations_shadow_len_after_address_max)
11780         bp_locations_shadow_len_after_address_max = addr;
11781     }
11782 }
11783
11784 /* Download tracepoint locations if they haven't been.  */
11785
11786 static void
11787 download_tracepoint_locations (void)
11788 {
11789   struct breakpoint *b;
11790   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11791
11792   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11793
11794   ALL_TRACEPOINTS (b)
11795     {
11796       struct bp_location *bl;
11797       struct tracepoint *t;
11798       int bp_location_downloaded = 0;
11799
11800       if ((b->type == bp_fast_tracepoint
11801            ? !may_insert_fast_tracepoints
11802            : !may_insert_tracepoints))
11803         continue;
11804
11805       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11806         {
11807           if (target_can_download_tracepoint ())
11808             can_download_tracepoint = TRIBOOL_TRUE;
11809           else
11810             can_download_tracepoint = TRIBOOL_FALSE;
11811         }
11812
11813       if (can_download_tracepoint == TRIBOOL_FALSE)
11814         break;
11815
11816       for (bl = b->loc; bl; bl = bl->next)
11817         {
11818           /* In tracepoint, locations are _never_ duplicated, so
11819              should_be_inserted is equivalent to
11820              unduplicated_should_be_inserted.  */
11821           if (!should_be_inserted (bl) || bl->inserted)
11822             continue;
11823
11824           switch_to_program_space_and_thread (bl->pspace);
11825
11826           target_download_tracepoint (bl);
11827
11828           bl->inserted = 1;
11829           bp_location_downloaded = 1;
11830         }
11831       t = (struct tracepoint *) b;
11832       t->number_on_target = b->number;
11833       if (bp_location_downloaded)
11834         gdb::observers::breakpoint_modified.notify (b);
11835     }
11836 }
11837
11838 /* Swap the insertion/duplication state between two locations.  */
11839
11840 static void
11841 swap_insertion (struct bp_location *left, struct bp_location *right)
11842 {
11843   const int left_inserted = left->inserted;
11844   const int left_duplicate = left->duplicate;
11845   const int left_needs_update = left->needs_update;
11846   const struct bp_target_info left_target_info = left->target_info;
11847
11848   /* Locations of tracepoints can never be duplicated.  */
11849   if (is_tracepoint (left->owner))
11850     gdb_assert (!left->duplicate);
11851   if (is_tracepoint (right->owner))
11852     gdb_assert (!right->duplicate);
11853
11854   left->inserted = right->inserted;
11855   left->duplicate = right->duplicate;
11856   left->needs_update = right->needs_update;
11857   left->target_info = right->target_info;
11858   right->inserted = left_inserted;
11859   right->duplicate = left_duplicate;
11860   right->needs_update = left_needs_update;
11861   right->target_info = left_target_info;
11862 }
11863
11864 /* Force the re-insertion of the locations at ADDRESS.  This is called
11865    once a new/deleted/modified duplicate location is found and we are evaluating
11866    conditions on the target's side.  Such conditions need to be updated on
11867    the target.  */
11868
11869 static void
11870 force_breakpoint_reinsertion (struct bp_location *bl)
11871 {
11872   struct bp_location **locp = NULL, **loc2p;
11873   struct bp_location *loc;
11874   CORE_ADDR address = 0;
11875   int pspace_num;
11876
11877   address = bl->address;
11878   pspace_num = bl->pspace->num;
11879
11880   /* This is only meaningful if the target is
11881      evaluating conditions and if the user has
11882      opted for condition evaluation on the target's
11883      side.  */
11884   if (gdb_evaluates_breakpoint_condition_p ()
11885       || !target_supports_evaluation_of_breakpoint_conditions ())
11886     return;
11887
11888   /* Flag all breakpoint locations with this address and
11889      the same program space as the location
11890      as "its condition has changed".  We need to
11891      update the conditions on the target's side.  */
11892   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11893     {
11894       loc = *loc2p;
11895
11896       if (!is_breakpoint (loc->owner)
11897           || pspace_num != loc->pspace->num)
11898         continue;
11899
11900       /* Flag the location appropriately.  We use a different state to
11901          let everyone know that we already updated the set of locations
11902          with addr bl->address and program space bl->pspace.  This is so
11903          we don't have to keep calling these functions just to mark locations
11904          that have already been marked.  */
11905       loc->condition_changed = condition_updated;
11906
11907       /* Free the agent expression bytecode as well.  We will compute
11908          it later on.  */
11909       loc->cond_bytecode.reset ();
11910     }
11911 }
11912
11913 /* Called whether new breakpoints are created, or existing breakpoints
11914    deleted, to update the global location list and recompute which
11915    locations are duplicate of which.
11916
11917    The INSERT_MODE flag determines whether locations may not, may, or
11918    shall be inserted now.  See 'enum ugll_insert_mode' for more
11919    info.  */
11920
11921 static void
11922 update_global_location_list (enum ugll_insert_mode insert_mode)
11923 {
11924   struct breakpoint *b;
11925   struct bp_location **locp, *loc;
11926   /* Last breakpoint location address that was marked for update.  */
11927   CORE_ADDR last_addr = 0;
11928   /* Last breakpoint location program space that was marked for update.  */
11929   int last_pspace_num = -1;
11930
11931   /* Used in the duplicates detection below.  When iterating over all
11932      bp_locations, points to the first bp_location of a given address.
11933      Breakpoints and watchpoints of different types are never
11934      duplicates of each other.  Keep one pointer for each type of
11935      breakpoint/watchpoint, so we only need to loop over all locations
11936      once.  */
11937   struct bp_location *bp_loc_first;  /* breakpoint */
11938   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11939   struct bp_location *awp_loc_first; /* access watchpoint */
11940   struct bp_location *rwp_loc_first; /* read watchpoint */
11941
11942   /* Saved former bp_locations array which we compare against the newly
11943      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11944   struct bp_location **old_locp;
11945   unsigned old_locations_count;
11946   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11947
11948   old_locations_count = bp_locations_count;
11949   bp_locations = NULL;
11950   bp_locations_count = 0;
11951
11952   ALL_BREAKPOINTS (b)
11953     for (loc = b->loc; loc; loc = loc->next)
11954       bp_locations_count++;
11955
11956   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11957   locp = bp_locations;
11958   ALL_BREAKPOINTS (b)
11959     for (loc = b->loc; loc; loc = loc->next)
11960       *locp++ = loc;
11961
11962   /* See if we need to "upgrade" a software breakpoint to a hardware
11963      breakpoint.  Do this before deciding whether locations are
11964      duplicates.  Also do this before sorting because sorting order
11965      depends on location type.  */
11966   for (locp = bp_locations;
11967        locp < bp_locations + bp_locations_count;
11968        locp++)
11969     {
11970       loc = *locp;
11971       if (!loc->inserted && should_be_inserted (loc))
11972         handle_automatic_hardware_breakpoints (loc);
11973     }
11974
11975   std::sort (bp_locations, bp_locations + bp_locations_count,
11976              bp_location_is_less_than);
11977
11978   bp_locations_target_extensions_update ();
11979
11980   /* Identify bp_location instances that are no longer present in the
11981      new list, and therefore should be freed.  Note that it's not
11982      necessary that those locations should be removed from inferior --
11983      if there's another location at the same address (previously
11984      marked as duplicate), we don't need to remove/insert the
11985      location.
11986      
11987      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11988      and former bp_location array state respectively.  */
11989
11990   locp = bp_locations;
11991   for (old_locp = old_locations.get ();
11992        old_locp < old_locations.get () + old_locations_count;
11993        old_locp++)
11994     {
11995       struct bp_location *old_loc = *old_locp;
11996       struct bp_location **loc2p;
11997
11998       /* Tells if 'old_loc' is found among the new locations.  If
11999          not, we have to free it.  */
12000       int found_object = 0;
12001       /* Tells if the location should remain inserted in the target.  */
12002       int keep_in_target = 0;
12003       int removed = 0;
12004
12005       /* Skip LOCP entries which will definitely never be needed.
12006          Stop either at or being the one matching OLD_LOC.  */
12007       while (locp < bp_locations + bp_locations_count
12008              && (*locp)->address < old_loc->address)
12009         locp++;
12010
12011       for (loc2p = locp;
12012            (loc2p < bp_locations + bp_locations_count
12013             && (*loc2p)->address == old_loc->address);
12014            loc2p++)
12015         {
12016           /* Check if this is a new/duplicated location or a duplicated
12017              location that had its condition modified.  If so, we want to send
12018              its condition to the target if evaluation of conditions is taking
12019              place there.  */
12020           if ((*loc2p)->condition_changed == condition_modified
12021               && (last_addr != old_loc->address
12022                   || last_pspace_num != old_loc->pspace->num))
12023             {
12024               force_breakpoint_reinsertion (*loc2p);
12025               last_pspace_num = old_loc->pspace->num;
12026             }
12027
12028           if (*loc2p == old_loc)
12029             found_object = 1;
12030         }
12031
12032       /* We have already handled this address, update it so that we don't
12033          have to go through updates again.  */
12034       last_addr = old_loc->address;
12035
12036       /* Target-side condition evaluation: Handle deleted locations.  */
12037       if (!found_object)
12038         force_breakpoint_reinsertion (old_loc);
12039
12040       /* If this location is no longer present, and inserted, look if
12041          there's maybe a new location at the same address.  If so,
12042          mark that one inserted, and don't remove this one.  This is
12043          needed so that we don't have a time window where a breakpoint
12044          at certain location is not inserted.  */
12045
12046       if (old_loc->inserted)
12047         {
12048           /* If the location is inserted now, we might have to remove
12049              it.  */
12050
12051           if (found_object && should_be_inserted (old_loc))
12052             {
12053               /* The location is still present in the location list,
12054                  and still should be inserted.  Don't do anything.  */
12055               keep_in_target = 1;
12056             }
12057           else
12058             {
12059               /* This location still exists, but it won't be kept in the
12060                  target since it may have been disabled.  We proceed to
12061                  remove its target-side condition.  */
12062
12063               /* The location is either no longer present, or got
12064                  disabled.  See if there's another location at the
12065                  same address, in which case we don't need to remove
12066                  this one from the target.  */
12067
12068               /* OLD_LOC comes from existing struct breakpoint.  */
12069               if (bl_address_is_meaningful (old_loc))
12070                 {
12071                   for (loc2p = locp;
12072                        (loc2p < bp_locations + bp_locations_count
12073                         && (*loc2p)->address == old_loc->address);
12074                        loc2p++)
12075                     {
12076                       struct bp_location *loc2 = *loc2p;
12077
12078                       if (loc2 == old_loc)
12079                         continue;
12080
12081                       if (breakpoint_locations_match (loc2, old_loc))
12082                         {
12083                           /* Read watchpoint locations are switched to
12084                              access watchpoints, if the former are not
12085                              supported, but the latter are.  */
12086                           if (is_hardware_watchpoint (old_loc->owner))
12087                             {
12088                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12089                               loc2->watchpoint_type = old_loc->watchpoint_type;
12090                             }
12091
12092                           /* loc2 is a duplicated location. We need to check
12093                              if it should be inserted in case it will be
12094                              unduplicated.  */
12095                           if (unduplicated_should_be_inserted (loc2))
12096                             {
12097                               swap_insertion (old_loc, loc2);
12098                               keep_in_target = 1;
12099                               break;
12100                             }
12101                         }
12102                     }
12103                 }
12104             }
12105
12106           if (!keep_in_target)
12107             {
12108               if (remove_breakpoint (old_loc))
12109                 {
12110                   /* This is just about all we can do.  We could keep
12111                      this location on the global list, and try to
12112                      remove it next time, but there's no particular
12113                      reason why we will succeed next time.
12114                      
12115                      Note that at this point, old_loc->owner is still
12116                      valid, as delete_breakpoint frees the breakpoint
12117                      only after calling us.  */
12118                   printf_filtered (_("warning: Error removing "
12119                                      "breakpoint %d\n"), 
12120                                    old_loc->owner->number);
12121                 }
12122               removed = 1;
12123             }
12124         }
12125
12126       if (!found_object)
12127         {
12128           if (removed && target_is_non_stop_p ()
12129               && need_moribund_for_location_type (old_loc))
12130             {
12131               /* This location was removed from the target.  In
12132                  non-stop mode, a race condition is possible where
12133                  we've removed a breakpoint, but stop events for that
12134                  breakpoint are already queued and will arrive later.
12135                  We apply an heuristic to be able to distinguish such
12136                  SIGTRAPs from other random SIGTRAPs: we keep this
12137                  breakpoint location for a bit, and will retire it
12138                  after we see some number of events.  The theory here
12139                  is that reporting of events should, "on the average",
12140                  be fair, so after a while we'll see events from all
12141                  threads that have anything of interest, and no longer
12142                  need to keep this breakpoint location around.  We
12143                  don't hold locations forever so to reduce chances of
12144                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12145                  SIGTRAP.
12146
12147                  The heuristic failing can be disastrous on
12148                  decr_pc_after_break targets.
12149
12150                  On decr_pc_after_break targets, like e.g., x86-linux,
12151                  if we fail to recognize a late breakpoint SIGTRAP,
12152                  because events_till_retirement has reached 0 too
12153                  soon, we'll fail to do the PC adjustment, and report
12154                  a random SIGTRAP to the user.  When the user resumes
12155                  the inferior, it will most likely immediately crash
12156                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12157                  corrupted, because of being resumed e.g., in the
12158                  middle of a multi-byte instruction, or skipped a
12159                  one-byte instruction.  This was actually seen happen
12160                  on native x86-linux, and should be less rare on
12161                  targets that do not support new thread events, like
12162                  remote, due to the heuristic depending on
12163                  thread_count.
12164
12165                  Mistaking a random SIGTRAP for a breakpoint trap
12166                  causes similar symptoms (PC adjustment applied when
12167                  it shouldn't), but then again, playing with SIGTRAPs
12168                  behind the debugger's back is asking for trouble.
12169
12170                  Since hardware watchpoint traps are always
12171                  distinguishable from other traps, so we don't need to
12172                  apply keep hardware watchpoint moribund locations
12173                  around.  We simply always ignore hardware watchpoint
12174                  traps we can no longer explain.  */
12175
12176               process_stratum_target *proc_target = nullptr;
12177               for (inferior *inf : all_inferiors ())
12178                 if (inf->pspace == old_loc->pspace)
12179                   {
12180                     proc_target = inf->process_target ();
12181                     break;
12182                   }
12183               if (proc_target != nullptr)
12184                 old_loc->events_till_retirement
12185                   = 3 * (thread_count (proc_target) + 1);
12186               else
12187                 old_loc->events_till_retirement = 1;
12188               old_loc->owner = NULL;
12189
12190               moribund_locations.push_back (old_loc);
12191             }
12192           else
12193             {
12194               old_loc->owner = NULL;
12195               decref_bp_location (&old_loc);
12196             }
12197         }
12198     }
12199
12200   /* Rescan breakpoints at the same address and section, marking the
12201      first one as "first" and any others as "duplicates".  This is so
12202      that the bpt instruction is only inserted once.  If we have a
12203      permanent breakpoint at the same place as BPT, make that one the
12204      official one, and the rest as duplicates.  Permanent breakpoints
12205      are sorted first for the same address.
12206
12207      Do the same for hardware watchpoints, but also considering the
12208      watchpoint's type (regular/access/read) and length.  */
12209
12210   bp_loc_first = NULL;
12211   wp_loc_first = NULL;
12212   awp_loc_first = NULL;
12213   rwp_loc_first = NULL;
12214   ALL_BP_LOCATIONS (loc, locp)
12215     {
12216       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12217          non-NULL.  */
12218       struct bp_location **loc_first_p;
12219       b = loc->owner;
12220
12221       if (!unduplicated_should_be_inserted (loc)
12222           || !bl_address_is_meaningful (loc)
12223           /* Don't detect duplicate for tracepoint locations because they are
12224            never duplicated.  See the comments in field `duplicate' of
12225            `struct bp_location'.  */
12226           || is_tracepoint (b))
12227         {
12228           /* Clear the condition modification flag.  */
12229           loc->condition_changed = condition_unchanged;
12230           continue;
12231         }
12232
12233       if (b->type == bp_hardware_watchpoint)
12234         loc_first_p = &wp_loc_first;
12235       else if (b->type == bp_read_watchpoint)
12236         loc_first_p = &rwp_loc_first;
12237       else if (b->type == bp_access_watchpoint)
12238         loc_first_p = &awp_loc_first;
12239       else
12240         loc_first_p = &bp_loc_first;
12241
12242       if (*loc_first_p == NULL
12243           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12244           || !breakpoint_locations_match (loc, *loc_first_p))
12245         {
12246           *loc_first_p = loc;
12247           loc->duplicate = 0;
12248
12249           if (is_breakpoint (loc->owner) && loc->condition_changed)
12250             {
12251               loc->needs_update = 1;
12252               /* Clear the condition modification flag.  */
12253               loc->condition_changed = condition_unchanged;
12254             }
12255           continue;
12256         }
12257
12258
12259       /* This and the above ensure the invariant that the first location
12260          is not duplicated, and is the inserted one.
12261          All following are marked as duplicated, and are not inserted.  */
12262       if (loc->inserted)
12263         swap_insertion (loc, *loc_first_p);
12264       loc->duplicate = 1;
12265
12266       /* Clear the condition modification flag.  */
12267       loc->condition_changed = condition_unchanged;
12268     }
12269
12270   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12271     {
12272       if (insert_mode != UGLL_DONT_INSERT)
12273         insert_breakpoint_locations ();
12274       else
12275         {
12276           /* Even though the caller told us to not insert new
12277              locations, we may still need to update conditions on the
12278              target's side of breakpoints that were already inserted
12279              if the target is evaluating breakpoint conditions.  We
12280              only update conditions for locations that are marked
12281              "needs_update".  */
12282           update_inserted_breakpoint_locations ();
12283         }
12284     }
12285
12286   if (insert_mode != UGLL_DONT_INSERT)
12287     download_tracepoint_locations ();
12288 }
12289
12290 void
12291 breakpoint_retire_moribund (void)
12292 {
12293   for (int ix = 0; ix < moribund_locations.size (); ++ix)
12294     {
12295       struct bp_location *loc = moribund_locations[ix];
12296       if (--(loc->events_till_retirement) == 0)
12297         {
12298           decref_bp_location (&loc);
12299           unordered_remove (moribund_locations, ix);
12300           --ix;
12301         }
12302     }
12303 }
12304
12305 static void
12306 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12307 {
12308
12309   try
12310     {
12311       update_global_location_list (insert_mode);
12312     }
12313   catch (const gdb_exception_error &e)
12314     {
12315     }
12316 }
12317
12318 /* Clear BKP from a BPS.  */
12319
12320 static void
12321 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12322 {
12323   bpstat bs;
12324
12325   for (bs = bps; bs; bs = bs->next)
12326     if (bs->breakpoint_at == bpt)
12327       {
12328         bs->breakpoint_at = NULL;
12329         bs->old_val = NULL;
12330         /* bs->commands will be freed later.  */
12331       }
12332 }
12333
12334 /* Callback for iterate_over_threads.  */
12335 static int
12336 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12337 {
12338   struct breakpoint *bpt = (struct breakpoint *) data;
12339
12340   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12341   return 0;
12342 }
12343
12344 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12345    callbacks.  */
12346
12347 static void
12348 say_where (struct breakpoint *b)
12349 {
12350   struct value_print_options opts;
12351
12352   get_user_print_options (&opts);
12353
12354   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12355      single string.  */
12356   if (b->loc == NULL)
12357     {
12358       /* For pending locations, the output differs slightly based
12359          on b->extra_string.  If this is non-NULL, it contains either
12360          a condition or dprintf arguments.  */
12361       if (b->extra_string == NULL)
12362         {
12363           printf_filtered (_(" (%s) pending."),
12364                            event_location_to_string (b->location.get ()));
12365         }
12366       else if (b->type == bp_dprintf)
12367         {
12368           printf_filtered (_(" (%s,%s) pending."),
12369                            event_location_to_string (b->location.get ()),
12370                            b->extra_string);
12371         }
12372       else
12373         {
12374           printf_filtered (_(" (%s %s) pending."),
12375                            event_location_to_string (b->location.get ()),
12376                            b->extra_string);
12377         }
12378     }
12379   else
12380     {
12381       if (opts.addressprint || b->loc->symtab == NULL)
12382         printf_filtered (" at %ps",
12383                          styled_string (address_style.style (),
12384                                         paddress (b->loc->gdbarch,
12385                                                   b->loc->address)));
12386       if (b->loc->symtab != NULL)
12387         {
12388           /* If there is a single location, we can print the location
12389              more nicely.  */
12390           if (b->loc->next == NULL)
12391             {
12392               const char *filename
12393                 = symtab_to_filename_for_display (b->loc->symtab);
12394               printf_filtered (": file %ps, line %d.",
12395                                styled_string (file_name_style.style (),
12396                                               filename),
12397                                b->loc->line_number);
12398             }
12399           else
12400             /* This is not ideal, but each location may have a
12401                different file name, and this at least reflects the
12402                real situation somewhat.  */
12403             printf_filtered (": %s.",
12404                              event_location_to_string (b->location.get ()));
12405         }
12406
12407       if (b->loc->next)
12408         {
12409           struct bp_location *loc = b->loc;
12410           int n = 0;
12411           for (; loc; loc = loc->next)
12412             ++n;
12413           printf_filtered (" (%d locations)", n);
12414         }
12415     }
12416 }
12417
12418 bp_location::~bp_location ()
12419 {
12420   xfree (function_name);
12421 }
12422
12423 /* Destructor for the breakpoint base class.  */
12424
12425 breakpoint::~breakpoint ()
12426 {
12427   xfree (this->cond_string);
12428   xfree (this->extra_string);
12429 }
12430
12431 static struct bp_location *
12432 base_breakpoint_allocate_location (struct breakpoint *self)
12433 {
12434   return new bp_location (self);
12435 }
12436
12437 static void
12438 base_breakpoint_re_set (struct breakpoint *b)
12439 {
12440   /* Nothing to re-set. */
12441 }
12442
12443 #define internal_error_pure_virtual_called() \
12444   gdb_assert_not_reached ("pure virtual function called")
12445
12446 static int
12447 base_breakpoint_insert_location (struct bp_location *bl)
12448 {
12449   internal_error_pure_virtual_called ();
12450 }
12451
12452 static int
12453 base_breakpoint_remove_location (struct bp_location *bl,
12454                                  enum remove_bp_reason reason)
12455 {
12456   internal_error_pure_virtual_called ();
12457 }
12458
12459 static int
12460 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12461                                 const address_space *aspace,
12462                                 CORE_ADDR bp_addr,
12463                                 const struct target_waitstatus *ws)
12464 {
12465   internal_error_pure_virtual_called ();
12466 }
12467
12468 static void
12469 base_breakpoint_check_status (bpstat bs)
12470 {
12471   /* Always stop.   */
12472 }
12473
12474 /* A "works_in_software_mode" breakpoint_ops method that just internal
12475    errors.  */
12476
12477 static int
12478 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12479 {
12480   internal_error_pure_virtual_called ();
12481 }
12482
12483 /* A "resources_needed" breakpoint_ops method that just internal
12484    errors.  */
12485
12486 static int
12487 base_breakpoint_resources_needed (const struct bp_location *bl)
12488 {
12489   internal_error_pure_virtual_called ();
12490 }
12491
12492 static enum print_stop_action
12493 base_breakpoint_print_it (bpstat bs)
12494 {
12495   internal_error_pure_virtual_called ();
12496 }
12497
12498 static void
12499 base_breakpoint_print_one_detail (const struct breakpoint *self,
12500                                   struct ui_out *uiout)
12501 {
12502   /* nothing */
12503 }
12504
12505 static void
12506 base_breakpoint_print_mention (struct breakpoint *b)
12507 {
12508   internal_error_pure_virtual_called ();
12509 }
12510
12511 static void
12512 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12513 {
12514   internal_error_pure_virtual_called ();
12515 }
12516
12517 static void
12518 base_breakpoint_create_sals_from_location
12519   (struct event_location *location,
12520    struct linespec_result *canonical,
12521    enum bptype type_wanted)
12522 {
12523   internal_error_pure_virtual_called ();
12524 }
12525
12526 static void
12527 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12528                                         struct linespec_result *c,
12529                                         gdb::unique_xmalloc_ptr<char> cond_string,
12530                                         gdb::unique_xmalloc_ptr<char> extra_string,
12531                                         enum bptype type_wanted,
12532                                         enum bpdisp disposition,
12533                                         int thread,
12534                                         int task, int ignore_count,
12535                                         const struct breakpoint_ops *o,
12536                                         int from_tty, int enabled,
12537                                         int internal, unsigned flags)
12538 {
12539   internal_error_pure_virtual_called ();
12540 }
12541
12542 static std::vector<symtab_and_line>
12543 base_breakpoint_decode_location (struct breakpoint *b,
12544                                  struct event_location *location,
12545                                  struct program_space *search_pspace)
12546 {
12547   internal_error_pure_virtual_called ();
12548 }
12549
12550 /* The default 'explains_signal' method.  */
12551
12552 static int
12553 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12554 {
12555   return 1;
12556 }
12557
12558 /* The default "after_condition_true" method.  */
12559
12560 static void
12561 base_breakpoint_after_condition_true (struct bpstats *bs)
12562 {
12563   /* Nothing to do.   */
12564 }
12565
12566 struct breakpoint_ops base_breakpoint_ops =
12567 {
12568   base_breakpoint_allocate_location,
12569   base_breakpoint_re_set,
12570   base_breakpoint_insert_location,
12571   base_breakpoint_remove_location,
12572   base_breakpoint_breakpoint_hit,
12573   base_breakpoint_check_status,
12574   base_breakpoint_resources_needed,
12575   base_breakpoint_works_in_software_mode,
12576   base_breakpoint_print_it,
12577   NULL,
12578   base_breakpoint_print_one_detail,
12579   base_breakpoint_print_mention,
12580   base_breakpoint_print_recreate,
12581   base_breakpoint_create_sals_from_location,
12582   base_breakpoint_create_breakpoints_sal,
12583   base_breakpoint_decode_location,
12584   base_breakpoint_explains_signal,
12585   base_breakpoint_after_condition_true,
12586 };
12587
12588 /* Default breakpoint_ops methods.  */
12589
12590 static void
12591 bkpt_re_set (struct breakpoint *b)
12592 {
12593   /* FIXME: is this still reachable?  */
12594   if (breakpoint_event_location_empty_p (b))
12595     {
12596       /* Anything without a location can't be re-set.  */
12597       delete_breakpoint (b);
12598       return;
12599     }
12600
12601   breakpoint_re_set_default (b);
12602 }
12603
12604 static int
12605 bkpt_insert_location (struct bp_location *bl)
12606 {
12607   CORE_ADDR addr = bl->target_info.reqstd_address;
12608
12609   bl->target_info.kind = breakpoint_kind (bl, &addr);
12610   bl->target_info.placed_address = addr;
12611
12612   if (bl->loc_type == bp_loc_hardware_breakpoint)
12613     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12614   else
12615     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12616 }
12617
12618 static int
12619 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12620 {
12621   if (bl->loc_type == bp_loc_hardware_breakpoint)
12622     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12623   else
12624     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12625 }
12626
12627 static int
12628 bkpt_breakpoint_hit (const struct bp_location *bl,
12629                      const address_space *aspace, CORE_ADDR bp_addr,
12630                      const struct target_waitstatus *ws)
12631 {
12632   if (ws->kind != TARGET_WAITKIND_STOPPED
12633       || ws->value.sig != GDB_SIGNAL_TRAP)
12634     return 0;
12635
12636   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12637                                  aspace, bp_addr))
12638     return 0;
12639
12640   if (overlay_debugging         /* unmapped overlay section */
12641       && section_is_overlay (bl->section)
12642       && !section_is_mapped (bl->section))
12643     return 0;
12644
12645   return 1;
12646 }
12647
12648 static int
12649 dprintf_breakpoint_hit (const struct bp_location *bl,
12650                         const address_space *aspace, CORE_ADDR bp_addr,
12651                         const struct target_waitstatus *ws)
12652 {
12653   if (dprintf_style == dprintf_style_agent
12654       && target_can_run_breakpoint_commands ())
12655     {
12656       /* An agent-style dprintf never causes a stop.  If we see a trap
12657          for this address it must be for a breakpoint that happens to
12658          be set at the same address.  */
12659       return 0;
12660     }
12661
12662   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12663 }
12664
12665 static int
12666 bkpt_resources_needed (const struct bp_location *bl)
12667 {
12668   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12669
12670   return 1;
12671 }
12672
12673 static enum print_stop_action
12674 bkpt_print_it (bpstat bs)
12675 {
12676   struct breakpoint *b;
12677   const struct bp_location *bl;
12678   int bp_temp;
12679   struct ui_out *uiout = current_uiout;
12680
12681   gdb_assert (bs->bp_location_at != NULL);
12682
12683   bl = bs->bp_location_at;
12684   b = bs->breakpoint_at;
12685
12686   bp_temp = b->disposition == disp_del;
12687   if (bl->address != bl->requested_address)
12688     breakpoint_adjustment_warning (bl->requested_address,
12689                                    bl->address,
12690                                    b->number, 1);
12691   annotate_breakpoint (b->number);
12692   maybe_print_thread_hit_breakpoint (uiout);
12693
12694   if (uiout->is_mi_like_p ())
12695     {
12696       uiout->field_string ("reason",
12697                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12698       uiout->field_string ("disp", bpdisp_text (b->disposition));
12699     }
12700   if (bp_temp)
12701     uiout->message ("Temporary breakpoint %pF, ",
12702                     signed_field ("bkptno", b->number));
12703   else
12704     uiout->message ("Breakpoint %pF, ",
12705                     signed_field ("bkptno", b->number));
12706
12707   return PRINT_SRC_AND_LOC;
12708 }
12709
12710 static void
12711 bkpt_print_mention (struct breakpoint *b)
12712 {
12713   if (current_uiout->is_mi_like_p ())
12714     return;
12715
12716   switch (b->type)
12717     {
12718     case bp_breakpoint:
12719     case bp_gnu_ifunc_resolver:
12720       if (b->disposition == disp_del)
12721         printf_filtered (_("Temporary breakpoint"));
12722       else
12723         printf_filtered (_("Breakpoint"));
12724       printf_filtered (_(" %d"), b->number);
12725       if (b->type == bp_gnu_ifunc_resolver)
12726         printf_filtered (_(" at gnu-indirect-function resolver"));
12727       break;
12728     case bp_hardware_breakpoint:
12729       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12730       break;
12731     case bp_dprintf:
12732       printf_filtered (_("Dprintf %d"), b->number);
12733       break;
12734     }
12735
12736   say_where (b);
12737 }
12738
12739 static void
12740 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12741 {
12742   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12743     fprintf_unfiltered (fp, "tbreak");
12744   else if (tp->type == bp_breakpoint)
12745     fprintf_unfiltered (fp, "break");
12746   else if (tp->type == bp_hardware_breakpoint
12747            && tp->disposition == disp_del)
12748     fprintf_unfiltered (fp, "thbreak");
12749   else if (tp->type == bp_hardware_breakpoint)
12750     fprintf_unfiltered (fp, "hbreak");
12751   else
12752     internal_error (__FILE__, __LINE__,
12753                     _("unhandled breakpoint type %d"), (int) tp->type);
12754
12755   fprintf_unfiltered (fp, " %s",
12756                       event_location_to_string (tp->location.get ()));
12757
12758   /* Print out extra_string if this breakpoint is pending.  It might
12759      contain, for example, conditions that were set by the user.  */
12760   if (tp->loc == NULL && tp->extra_string != NULL)
12761     fprintf_unfiltered (fp, " %s", tp->extra_string);
12762
12763   print_recreate_thread (tp, fp);
12764 }
12765
12766 static void
12767 bkpt_create_sals_from_location (struct event_location *location,
12768                                 struct linespec_result *canonical,
12769                                 enum bptype type_wanted)
12770 {
12771   create_sals_from_location_default (location, canonical, type_wanted);
12772 }
12773
12774 static void
12775 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12776                              struct linespec_result *canonical,
12777                              gdb::unique_xmalloc_ptr<char> cond_string,
12778                              gdb::unique_xmalloc_ptr<char> extra_string,
12779                              enum bptype type_wanted,
12780                              enum bpdisp disposition,
12781                              int thread,
12782                              int task, int ignore_count,
12783                              const struct breakpoint_ops *ops,
12784                              int from_tty, int enabled,
12785                              int internal, unsigned flags)
12786 {
12787   create_breakpoints_sal_default (gdbarch, canonical,
12788                                   std::move (cond_string),
12789                                   std::move (extra_string),
12790                                   type_wanted,
12791                                   disposition, thread, task,
12792                                   ignore_count, ops, from_tty,
12793                                   enabled, internal, flags);
12794 }
12795
12796 static std::vector<symtab_and_line>
12797 bkpt_decode_location (struct breakpoint *b,
12798                       struct event_location *location,
12799                       struct program_space *search_pspace)
12800 {
12801   return decode_location_default (b, location, search_pspace);
12802 }
12803
12804 /* Virtual table for internal breakpoints.  */
12805
12806 static void
12807 internal_bkpt_re_set (struct breakpoint *b)
12808 {
12809   switch (b->type)
12810     {
12811       /* Delete overlay event and longjmp master breakpoints; they
12812          will be reset later by breakpoint_re_set.  */
12813     case bp_overlay_event:
12814     case bp_longjmp_master:
12815     case bp_std_terminate_master:
12816     case bp_exception_master:
12817       delete_breakpoint (b);
12818       break;
12819
12820       /* This breakpoint is special, it's set up when the inferior
12821          starts and we really don't want to touch it.  */
12822     case bp_shlib_event:
12823
12824       /* Like bp_shlib_event, this breakpoint type is special.  Once
12825          it is set up, we do not want to touch it.  */
12826     case bp_thread_event:
12827       break;
12828     }
12829 }
12830
12831 static void
12832 internal_bkpt_check_status (bpstat bs)
12833 {
12834   if (bs->breakpoint_at->type == bp_shlib_event)
12835     {
12836       /* If requested, stop when the dynamic linker notifies GDB of
12837          events.  This allows the user to get control and place
12838          breakpoints in initializer routines for dynamically loaded
12839          objects (among other things).  */
12840       bs->stop = stop_on_solib_events;
12841       bs->print = stop_on_solib_events;
12842     }
12843   else
12844     bs->stop = 0;
12845 }
12846
12847 static enum print_stop_action
12848 internal_bkpt_print_it (bpstat bs)
12849 {
12850   struct breakpoint *b;
12851
12852   b = bs->breakpoint_at;
12853
12854   switch (b->type)
12855     {
12856     case bp_shlib_event:
12857       /* Did we stop because the user set the stop_on_solib_events
12858          variable?  (If so, we report this as a generic, "Stopped due
12859          to shlib event" message.) */
12860       print_solib_event (0);
12861       break;
12862
12863     case bp_thread_event:
12864       /* Not sure how we will get here.
12865          GDB should not stop for these breakpoints.  */
12866       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12867       break;
12868
12869     case bp_overlay_event:
12870       /* By analogy with the thread event, GDB should not stop for these.  */
12871       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12872       break;
12873
12874     case bp_longjmp_master:
12875       /* These should never be enabled.  */
12876       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12877       break;
12878
12879     case bp_std_terminate_master:
12880       /* These should never be enabled.  */
12881       printf_filtered (_("std::terminate Master Breakpoint: "
12882                          "gdb should not stop!\n"));
12883       break;
12884
12885     case bp_exception_master:
12886       /* These should never be enabled.  */
12887       printf_filtered (_("Exception Master Breakpoint: "
12888                          "gdb should not stop!\n"));
12889       break;
12890     }
12891
12892   return PRINT_NOTHING;
12893 }
12894
12895 static void
12896 internal_bkpt_print_mention (struct breakpoint *b)
12897 {
12898   /* Nothing to mention.  These breakpoints are internal.  */
12899 }
12900
12901 /* Virtual table for momentary breakpoints  */
12902
12903 static void
12904 momentary_bkpt_re_set (struct breakpoint *b)
12905 {
12906   /* Keep temporary breakpoints, which can be encountered when we step
12907      over a dlopen call and solib_add is resetting the breakpoints.
12908      Otherwise these should have been blown away via the cleanup chain
12909      or by breakpoint_init_inferior when we rerun the executable.  */
12910 }
12911
12912 static void
12913 momentary_bkpt_check_status (bpstat bs)
12914 {
12915   /* Nothing.  The point of these breakpoints is causing a stop.  */
12916 }
12917
12918 static enum print_stop_action
12919 momentary_bkpt_print_it (bpstat bs)
12920 {
12921   return PRINT_UNKNOWN;
12922 }
12923
12924 static void
12925 momentary_bkpt_print_mention (struct breakpoint *b)
12926 {
12927   /* Nothing to mention.  These breakpoints are internal.  */
12928 }
12929
12930 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12931
12932    It gets cleared already on the removal of the first one of such placed
12933    breakpoints.  This is OK as they get all removed altogether.  */
12934
12935 longjmp_breakpoint::~longjmp_breakpoint ()
12936 {
12937   thread_info *tp = find_thread_global_id (this->thread);
12938
12939   if (tp != NULL)
12940     tp->initiating_frame = null_frame_id;
12941 }
12942
12943 /* Specific methods for probe breakpoints.  */
12944
12945 static int
12946 bkpt_probe_insert_location (struct bp_location *bl)
12947 {
12948   int v = bkpt_insert_location (bl);
12949
12950   if (v == 0)
12951     {
12952       /* The insertion was successful, now let's set the probe's semaphore
12953          if needed.  */
12954       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12955     }
12956
12957   return v;
12958 }
12959
12960 static int
12961 bkpt_probe_remove_location (struct bp_location *bl,
12962                             enum remove_bp_reason reason)
12963 {
12964   /* Let's clear the semaphore before removing the location.  */
12965   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12966
12967   return bkpt_remove_location (bl, reason);
12968 }
12969
12970 static void
12971 bkpt_probe_create_sals_from_location (struct event_location *location,
12972                                       struct linespec_result *canonical,
12973                                       enum bptype type_wanted)
12974 {
12975   struct linespec_sals lsal;
12976
12977   lsal.sals = parse_probes (location, NULL, canonical);
12978   lsal.canonical
12979     = xstrdup (event_location_to_string (canonical->location.get ()));
12980   canonical->lsals.push_back (std::move (lsal));
12981 }
12982
12983 static std::vector<symtab_and_line>
12984 bkpt_probe_decode_location (struct breakpoint *b,
12985                             struct event_location *location,
12986                             struct program_space *search_pspace)
12987 {
12988   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12989   if (sals.empty ())
12990     error (_("probe not found"));
12991   return sals;
12992 }
12993
12994 /* The breakpoint_ops structure to be used in tracepoints.  */
12995
12996 static void
12997 tracepoint_re_set (struct breakpoint *b)
12998 {
12999   breakpoint_re_set_default (b);
13000 }
13001
13002 static int
13003 tracepoint_breakpoint_hit (const struct bp_location *bl,
13004                            const address_space *aspace, CORE_ADDR bp_addr,
13005                            const struct target_waitstatus *ws)
13006 {
13007   /* By definition, the inferior does not report stops at
13008      tracepoints.  */
13009   return 0;
13010 }
13011
13012 static void
13013 tracepoint_print_one_detail (const struct breakpoint *self,
13014                              struct ui_out *uiout)
13015 {
13016   struct tracepoint *tp = (struct tracepoint *) self;
13017   if (!tp->static_trace_marker_id.empty ())
13018     {
13019       gdb_assert (self->type == bp_static_tracepoint);
13020
13021       uiout->message ("\tmarker id is %pF\n",
13022                       string_field ("static-tracepoint-marker-string-id",
13023                                     tp->static_trace_marker_id.c_str ()));
13024     }
13025 }
13026
13027 static void
13028 tracepoint_print_mention (struct breakpoint *b)
13029 {
13030   if (current_uiout->is_mi_like_p ())
13031     return;
13032
13033   switch (b->type)
13034     {
13035     case bp_tracepoint:
13036       printf_filtered (_("Tracepoint"));
13037       printf_filtered (_(" %d"), b->number);
13038       break;
13039     case bp_fast_tracepoint:
13040       printf_filtered (_("Fast tracepoint"));
13041       printf_filtered (_(" %d"), b->number);
13042       break;
13043     case bp_static_tracepoint:
13044       printf_filtered (_("Static tracepoint"));
13045       printf_filtered (_(" %d"), b->number);
13046       break;
13047     default:
13048       internal_error (__FILE__, __LINE__,
13049                       _("unhandled tracepoint type %d"), (int) b->type);
13050     }
13051
13052   say_where (b);
13053 }
13054
13055 static void
13056 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13057 {
13058   struct tracepoint *tp = (struct tracepoint *) self;
13059
13060   if (self->type == bp_fast_tracepoint)
13061     fprintf_unfiltered (fp, "ftrace");
13062   else if (self->type == bp_static_tracepoint)
13063     fprintf_unfiltered (fp, "strace");
13064   else if (self->type == bp_tracepoint)
13065     fprintf_unfiltered (fp, "trace");
13066   else
13067     internal_error (__FILE__, __LINE__,
13068                     _("unhandled tracepoint type %d"), (int) self->type);
13069
13070   fprintf_unfiltered (fp, " %s",
13071                       event_location_to_string (self->location.get ()));
13072   print_recreate_thread (self, fp);
13073
13074   if (tp->pass_count)
13075     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13076 }
13077
13078 static void
13079 tracepoint_create_sals_from_location (struct event_location *location,
13080                                       struct linespec_result *canonical,
13081                                       enum bptype type_wanted)
13082 {
13083   create_sals_from_location_default (location, canonical, type_wanted);
13084 }
13085
13086 static void
13087 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13088                                    struct linespec_result *canonical,
13089                                    gdb::unique_xmalloc_ptr<char> cond_string,
13090                                    gdb::unique_xmalloc_ptr<char> extra_string,
13091                                    enum bptype type_wanted,
13092                                    enum bpdisp disposition,
13093                                    int thread,
13094                                    int task, int ignore_count,
13095                                    const struct breakpoint_ops *ops,
13096                                    int from_tty, int enabled,
13097                                    int internal, unsigned flags)
13098 {
13099   create_breakpoints_sal_default (gdbarch, canonical,
13100                                   std::move (cond_string),
13101                                   std::move (extra_string),
13102                                   type_wanted,
13103                                   disposition, thread, task,
13104                                   ignore_count, ops, from_tty,
13105                                   enabled, internal, flags);
13106 }
13107
13108 static std::vector<symtab_and_line>
13109 tracepoint_decode_location (struct breakpoint *b,
13110                             struct event_location *location,
13111                             struct program_space *search_pspace)
13112 {
13113   return decode_location_default (b, location, search_pspace);
13114 }
13115
13116 struct breakpoint_ops tracepoint_breakpoint_ops;
13117
13118 /* Virtual table for tracepoints on static probes.  */
13119
13120 static void
13121 tracepoint_probe_create_sals_from_location
13122   (struct event_location *location,
13123    struct linespec_result *canonical,
13124    enum bptype type_wanted)
13125 {
13126   /* We use the same method for breakpoint on probes.  */
13127   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13128 }
13129
13130 static std::vector<symtab_and_line>
13131 tracepoint_probe_decode_location (struct breakpoint *b,
13132                                   struct event_location *location,
13133                                   struct program_space *search_pspace)
13134 {
13135   /* We use the same method for breakpoint on probes.  */
13136   return bkpt_probe_decode_location (b, location, search_pspace);
13137 }
13138
13139 /* Dprintf breakpoint_ops methods.  */
13140
13141 static void
13142 dprintf_re_set (struct breakpoint *b)
13143 {
13144   breakpoint_re_set_default (b);
13145
13146   /* extra_string should never be non-NULL for dprintf.  */
13147   gdb_assert (b->extra_string != NULL);
13148
13149   /* 1 - connect to target 1, that can run breakpoint commands.
13150      2 - create a dprintf, which resolves fine.
13151      3 - disconnect from target 1
13152      4 - connect to target 2, that can NOT run breakpoint commands.
13153
13154      After steps #3/#4, you'll want the dprintf command list to
13155      be updated, because target 1 and 2 may well return different
13156      answers for target_can_run_breakpoint_commands().
13157      Given absence of finer grained resetting, we get to do
13158      it all the time.  */
13159   if (b->extra_string != NULL)
13160     update_dprintf_command_list (b);
13161 }
13162
13163 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13164
13165 static void
13166 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13167 {
13168   fprintf_unfiltered (fp, "dprintf %s,%s",
13169                       event_location_to_string (tp->location.get ()),
13170                       tp->extra_string);
13171   print_recreate_thread (tp, fp);
13172 }
13173
13174 /* Implement the "after_condition_true" breakpoint_ops method for
13175    dprintf.
13176
13177    dprintf's are implemented with regular commands in their command
13178    list, but we run the commands here instead of before presenting the
13179    stop to the user, as dprintf's don't actually cause a stop.  This
13180    also makes it so that the commands of multiple dprintfs at the same
13181    address are all handled.  */
13182
13183 static void
13184 dprintf_after_condition_true (struct bpstats *bs)
13185 {
13186   struct bpstats tmp_bs;
13187   struct bpstats *tmp_bs_p = &tmp_bs;
13188
13189   /* dprintf's never cause a stop.  This wasn't set in the
13190      check_status hook instead because that would make the dprintf's
13191      condition not be evaluated.  */
13192   bs->stop = 0;
13193
13194   /* Run the command list here.  Take ownership of it instead of
13195      copying.  We never want these commands to run later in
13196      bpstat_do_actions, if a breakpoint that causes a stop happens to
13197      be set at same address as this dprintf, or even if running the
13198      commands here throws.  */
13199   tmp_bs.commands = bs->commands;
13200   bs->commands = NULL;
13201
13202   bpstat_do_actions_1 (&tmp_bs_p);
13203
13204   /* 'tmp_bs.commands' will usually be NULL by now, but
13205      bpstat_do_actions_1 may return early without processing the whole
13206      list.  */
13207 }
13208
13209 /* The breakpoint_ops structure to be used on static tracepoints with
13210    markers (`-m').  */
13211
13212 static void
13213 strace_marker_create_sals_from_location (struct event_location *location,
13214                                          struct linespec_result *canonical,
13215                                          enum bptype type_wanted)
13216 {
13217   struct linespec_sals lsal;
13218   const char *arg_start, *arg;
13219
13220   arg = arg_start = get_linespec_location (location)->spec_string;
13221   lsal.sals = decode_static_tracepoint_spec (&arg);
13222
13223   std::string str (arg_start, arg - arg_start);
13224   const char *ptr = str.c_str ();
13225   canonical->location
13226     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13227
13228   lsal.canonical
13229     = xstrdup (event_location_to_string (canonical->location.get ()));
13230   canonical->lsals.push_back (std::move (lsal));
13231 }
13232
13233 static void
13234 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13235                                       struct linespec_result *canonical,
13236                                       gdb::unique_xmalloc_ptr<char> cond_string,
13237                                       gdb::unique_xmalloc_ptr<char> extra_string,
13238                                       enum bptype type_wanted,
13239                                       enum bpdisp disposition,
13240                                       int thread,
13241                                       int task, int ignore_count,
13242                                       const struct breakpoint_ops *ops,
13243                                       int from_tty, int enabled,
13244                                       int internal, unsigned flags)
13245 {
13246   const linespec_sals &lsal = canonical->lsals[0];
13247
13248   /* If the user is creating a static tracepoint by marker id
13249      (strace -m MARKER_ID), then store the sals index, so that
13250      breakpoint_re_set can try to match up which of the newly
13251      found markers corresponds to this one, and, don't try to
13252      expand multiple locations for each sal, given than SALS
13253      already should contain all sals for MARKER_ID.  */
13254
13255   for (size_t i = 0; i < lsal.sals.size (); i++)
13256     {
13257       event_location_up location
13258         = copy_event_location (canonical->location.get ());
13259
13260       std::unique_ptr<tracepoint> tp (new tracepoint ());
13261       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13262                            std::move (location), NULL,
13263                            std::move (cond_string),
13264                            std::move (extra_string),
13265                            type_wanted, disposition,
13266                            thread, task, ignore_count, ops,
13267                            from_tty, enabled, internal, flags,
13268                            canonical->special_display);
13269       /* Given that its possible to have multiple markers with
13270          the same string id, if the user is creating a static
13271          tracepoint by marker id ("strace -m MARKER_ID"), then
13272          store the sals index, so that breakpoint_re_set can
13273          try to match up which of the newly found markers
13274          corresponds to this one  */
13275       tp->static_trace_marker_id_idx = i;
13276
13277       install_breakpoint (internal, std::move (tp), 0);
13278     }
13279 }
13280
13281 static std::vector<symtab_and_line>
13282 strace_marker_decode_location (struct breakpoint *b,
13283                                struct event_location *location,
13284                                struct program_space *search_pspace)
13285 {
13286   struct tracepoint *tp = (struct tracepoint *) b;
13287   const char *s = get_linespec_location (location)->spec_string;
13288
13289   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13290   if (sals.size () > tp->static_trace_marker_id_idx)
13291     {
13292       sals[0] = sals[tp->static_trace_marker_id_idx];
13293       sals.resize (1);
13294       return sals;
13295     }
13296   else
13297     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13298 }
13299
13300 static struct breakpoint_ops strace_marker_breakpoint_ops;
13301
13302 static int
13303 strace_marker_p (struct breakpoint *b)
13304 {
13305   return b->ops == &strace_marker_breakpoint_ops;
13306 }
13307
13308 /* Delete a breakpoint and clean up all traces of it in the data
13309    structures.  */
13310
13311 void
13312 delete_breakpoint (struct breakpoint *bpt)
13313 {
13314   struct breakpoint *b;
13315
13316   gdb_assert (bpt != NULL);
13317
13318   /* Has this bp already been deleted?  This can happen because
13319      multiple lists can hold pointers to bp's.  bpstat lists are
13320      especial culprits.
13321
13322      One example of this happening is a watchpoint's scope bp.  When
13323      the scope bp triggers, we notice that the watchpoint is out of
13324      scope, and delete it.  We also delete its scope bp.  But the
13325      scope bp is marked "auto-deleting", and is already on a bpstat.
13326      That bpstat is then checked for auto-deleting bp's, which are
13327      deleted.
13328
13329      A real solution to this problem might involve reference counts in
13330      bp's, and/or giving them pointers back to their referencing
13331      bpstat's, and teaching delete_breakpoint to only free a bp's
13332      storage when no more references were extent.  A cheaper bandaid
13333      was chosen.  */
13334   if (bpt->type == bp_none)
13335     return;
13336
13337   /* At least avoid this stale reference until the reference counting
13338      of breakpoints gets resolved.  */
13339   if (bpt->related_breakpoint != bpt)
13340     {
13341       struct breakpoint *related;
13342       struct watchpoint *w;
13343
13344       if (bpt->type == bp_watchpoint_scope)
13345         w = (struct watchpoint *) bpt->related_breakpoint;
13346       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13347         w = (struct watchpoint *) bpt;
13348       else
13349         w = NULL;
13350       if (w != NULL)
13351         watchpoint_del_at_next_stop (w);
13352
13353       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13354       for (related = bpt; related->related_breakpoint != bpt;
13355            related = related->related_breakpoint);
13356       related->related_breakpoint = bpt->related_breakpoint;
13357       bpt->related_breakpoint = bpt;
13358     }
13359
13360   /* watch_command_1 creates a watchpoint but only sets its number if
13361      update_watchpoint succeeds in creating its bp_locations.  If there's
13362      a problem in that process, we'll be asked to delete the half-created
13363      watchpoint.  In that case, don't announce the deletion.  */
13364   if (bpt->number)
13365     gdb::observers::breakpoint_deleted.notify (bpt);
13366
13367   if (breakpoint_chain == bpt)
13368     breakpoint_chain = bpt->next;
13369
13370   ALL_BREAKPOINTS (b)
13371     if (b->next == bpt)
13372     {
13373       b->next = bpt->next;
13374       break;
13375     }
13376
13377   /* Be sure no bpstat's are pointing at the breakpoint after it's
13378      been freed.  */
13379   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13380      in all threads for now.  Note that we cannot just remove bpstats
13381      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13382      commands are associated with the bpstat; if we remove it here,
13383      then the later call to bpstat_do_actions (&stop_bpstat); in
13384      event-top.c won't do anything, and temporary breakpoints with
13385      commands won't work.  */
13386
13387   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13388
13389   /* Now that breakpoint is removed from breakpoint list, update the
13390      global location list.  This will remove locations that used to
13391      belong to this breakpoint.  Do this before freeing the breakpoint
13392      itself, since remove_breakpoint looks at location's owner.  It
13393      might be better design to have location completely
13394      self-contained, but it's not the case now.  */
13395   update_global_location_list (UGLL_DONT_INSERT);
13396
13397   /* On the chance that someone will soon try again to delete this
13398      same bp, we mark it as deleted before freeing its storage.  */
13399   bpt->type = bp_none;
13400   delete bpt;
13401 }
13402
13403 /* Iterator function to call a user-provided callback function once
13404    for each of B and its related breakpoints.  */
13405
13406 static void
13407 iterate_over_related_breakpoints (struct breakpoint *b,
13408                                   gdb::function_view<void (breakpoint *)> function)
13409 {
13410   struct breakpoint *related;
13411
13412   related = b;
13413   do
13414     {
13415       struct breakpoint *next;
13416
13417       /* FUNCTION may delete RELATED.  */
13418       next = related->related_breakpoint;
13419
13420       if (next == related)
13421         {
13422           /* RELATED is the last ring entry.  */
13423           function (related);
13424
13425           /* FUNCTION may have deleted it, so we'd never reach back to
13426              B.  There's nothing left to do anyway, so just break
13427              out.  */
13428           break;
13429         }
13430       else
13431         function (related);
13432
13433       related = next;
13434     }
13435   while (related != b);
13436 }
13437
13438 static void
13439 delete_command (const char *arg, int from_tty)
13440 {
13441   struct breakpoint *b, *b_tmp;
13442
13443   dont_repeat ();
13444
13445   if (arg == 0)
13446     {
13447       int breaks_to_delete = 0;
13448
13449       /* Delete all breakpoints if no argument.  Do not delete
13450          internal breakpoints, these have to be deleted with an
13451          explicit breakpoint number argument.  */
13452       ALL_BREAKPOINTS (b)
13453         if (user_breakpoint_p (b))
13454           {
13455             breaks_to_delete = 1;
13456             break;
13457           }
13458
13459       /* Ask user only if there are some breakpoints to delete.  */
13460       if (!from_tty
13461           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13462         {
13463           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13464             if (user_breakpoint_p (b))
13465               delete_breakpoint (b);
13466         }
13467     }
13468   else
13469     map_breakpoint_numbers
13470       (arg, [&] (breakpoint *br)
13471        {
13472          iterate_over_related_breakpoints (br, delete_breakpoint);
13473        });
13474 }
13475
13476 /* Return true if all locations of B bound to PSPACE are pending.  If
13477    PSPACE is NULL, all locations of all program spaces are
13478    considered.  */
13479
13480 static int
13481 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13482 {
13483   struct bp_location *loc;
13484
13485   for (loc = b->loc; loc != NULL; loc = loc->next)
13486     if ((pspace == NULL
13487          || loc->pspace == pspace)
13488         && !loc->shlib_disabled
13489         && !loc->pspace->executing_startup)
13490       return 0;
13491   return 1;
13492 }
13493
13494 /* Subroutine of update_breakpoint_locations to simplify it.
13495    Return non-zero if multiple fns in list LOC have the same name.
13496    Null names are ignored.  */
13497
13498 static int
13499 ambiguous_names_p (struct bp_location *loc)
13500 {
13501   struct bp_location *l;
13502   htab_up htab (htab_create_alloc (13, htab_hash_string, streq_hash, NULL,
13503                                    xcalloc, xfree));
13504
13505   for (l = loc; l != NULL; l = l->next)
13506     {
13507       const char **slot;
13508       const char *name = l->function_name;
13509
13510       /* Allow for some names to be NULL, ignore them.  */
13511       if (name == NULL)
13512         continue;
13513
13514       slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
13515                                              INSERT);
13516       /* NOTE: We can assume slot != NULL here because xcalloc never
13517          returns NULL.  */
13518       if (*slot != NULL)
13519         return 1;
13520       *slot = name;
13521     }
13522
13523   return 0;
13524 }
13525
13526 /* When symbols change, it probably means the sources changed as well,
13527    and it might mean the static tracepoint markers are no longer at
13528    the same address or line numbers they used to be at last we
13529    checked.  Losing your static tracepoints whenever you rebuild is
13530    undesirable.  This function tries to resync/rematch gdb static
13531    tracepoints with the markers on the target, for static tracepoints
13532    that have not been set by marker id.  Static tracepoint that have
13533    been set by marker id are reset by marker id in breakpoint_re_set.
13534    The heuristic is:
13535
13536    1) For a tracepoint set at a specific address, look for a marker at
13537    the old PC.  If one is found there, assume to be the same marker.
13538    If the name / string id of the marker found is different from the
13539    previous known name, assume that means the user renamed the marker
13540    in the sources, and output a warning.
13541
13542    2) For a tracepoint set at a given line number, look for a marker
13543    at the new address of the old line number.  If one is found there,
13544    assume to be the same marker.  If the name / string id of the
13545    marker found is different from the previous known name, assume that
13546    means the user renamed the marker in the sources, and output a
13547    warning.
13548
13549    3) If a marker is no longer found at the same address or line, it
13550    may mean the marker no longer exists.  But it may also just mean
13551    the code changed a bit.  Maybe the user added a few lines of code
13552    that made the marker move up or down (in line number terms).  Ask
13553    the target for info about the marker with the string id as we knew
13554    it.  If found, update line number and address in the matching
13555    static tracepoint.  This will get confused if there's more than one
13556    marker with the same ID (possible in UST, although unadvised
13557    precisely because it confuses tools).  */
13558
13559 static struct symtab_and_line
13560 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13561 {
13562   struct tracepoint *tp = (struct tracepoint *) b;
13563   struct static_tracepoint_marker marker;
13564   CORE_ADDR pc;
13565
13566   pc = sal.pc;
13567   if (sal.line)
13568     find_line_pc (sal.symtab, sal.line, &pc);
13569
13570   if (target_static_tracepoint_marker_at (pc, &marker))
13571     {
13572       if (tp->static_trace_marker_id != marker.str_id)
13573         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13574                  b->number, tp->static_trace_marker_id.c_str (),
13575                  marker.str_id.c_str ());
13576
13577       tp->static_trace_marker_id = std::move (marker.str_id);
13578
13579       return sal;
13580     }
13581
13582   /* Old marker wasn't found on target at lineno.  Try looking it up
13583      by string ID.  */
13584   if (!sal.explicit_pc
13585       && sal.line != 0
13586       && sal.symtab != NULL
13587       && !tp->static_trace_marker_id.empty ())
13588     {
13589       std::vector<static_tracepoint_marker> markers
13590         = target_static_tracepoint_markers_by_strid
13591             (tp->static_trace_marker_id.c_str ());
13592
13593       if (!markers.empty ())
13594         {
13595           struct symbol *sym;
13596           struct static_tracepoint_marker *tpmarker;
13597           struct ui_out *uiout = current_uiout;
13598           struct explicit_location explicit_loc;
13599
13600           tpmarker = &markers[0];
13601
13602           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13603
13604           warning (_("marker for static tracepoint %d (%s) not "
13605                      "found at previous line number"),
13606                    b->number, tp->static_trace_marker_id.c_str ());
13607
13608           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13609           sym = find_pc_sect_function (tpmarker->address, NULL);
13610           uiout->text ("Now in ");
13611           if (sym)
13612             {
13613               uiout->field_string ("func", sym->print_name (),
13614                                    function_name_style.style ());
13615               uiout->text (" at ");
13616             }
13617           uiout->field_string ("file",
13618                                symtab_to_filename_for_display (sal2.symtab),
13619                                file_name_style.style ());
13620           uiout->text (":");
13621
13622           if (uiout->is_mi_like_p ())
13623             {
13624               const char *fullname = symtab_to_fullname (sal2.symtab);
13625
13626               uiout->field_string ("fullname", fullname);
13627             }
13628
13629           uiout->field_signed ("line", sal2.line);
13630           uiout->text ("\n");
13631
13632           b->loc->line_number = sal2.line;
13633           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13634
13635           b->location.reset (NULL);
13636           initialize_explicit_location (&explicit_loc);
13637           explicit_loc.source_filename
13638             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13639           explicit_loc.line_offset.offset = b->loc->line_number;
13640           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13641           b->location = new_explicit_location (&explicit_loc);
13642
13643           /* Might be nice to check if function changed, and warn if
13644              so.  */
13645         }
13646     }
13647   return sal;
13648 }
13649
13650 /* Returns 1 iff locations A and B are sufficiently same that
13651    we don't need to report breakpoint as changed.  */
13652
13653 static int
13654 locations_are_equal (struct bp_location *a, struct bp_location *b)
13655 {
13656   while (a && b)
13657     {
13658       if (a->address != b->address)
13659         return 0;
13660
13661       if (a->shlib_disabled != b->shlib_disabled)
13662         return 0;
13663
13664       if (a->enabled != b->enabled)
13665         return 0;
13666
13667       if (a->disabled_by_cond != b->disabled_by_cond)
13668         return 0;
13669
13670       a = a->next;
13671       b = b->next;
13672     }
13673
13674   if ((a == NULL) != (b == NULL))
13675     return 0;
13676
13677   return 1;
13678 }
13679
13680 /* Split all locations of B that are bound to PSPACE out of B's
13681    location list to a separate list and return that list's head.  If
13682    PSPACE is NULL, hoist out all locations of B.  */
13683
13684 static struct bp_location *
13685 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13686 {
13687   struct bp_location head;
13688   struct bp_location *i = b->loc;
13689   struct bp_location **i_link = &b->loc;
13690   struct bp_location *hoisted = &head;
13691
13692   if (pspace == NULL)
13693     {
13694       i = b->loc;
13695       b->loc = NULL;
13696       return i;
13697     }
13698
13699   head.next = NULL;
13700
13701   while (i != NULL)
13702     {
13703       if (i->pspace == pspace)
13704         {
13705           *i_link = i->next;
13706           i->next = NULL;
13707           hoisted->next = i;
13708           hoisted = i;
13709         }
13710       else
13711         i_link = &i->next;
13712       i = *i_link;
13713     }
13714
13715   return head.next;
13716 }
13717
13718 /* Create new breakpoint locations for B (a hardware or software
13719    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13720    zero, then B is a ranged breakpoint.  Only recreates locations for
13721    FILTER_PSPACE.  Locations of other program spaces are left
13722    untouched.  */
13723
13724 void
13725 update_breakpoint_locations (struct breakpoint *b,
13726                              struct program_space *filter_pspace,
13727                              gdb::array_view<const symtab_and_line> sals,
13728                              gdb::array_view<const symtab_and_line> sals_end)
13729 {
13730   struct bp_location *existing_locations;
13731
13732   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13733     {
13734       /* Ranged breakpoints have only one start location and one end
13735          location.  */
13736       b->enable_state = bp_disabled;
13737       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13738                            "multiple locations found\n"),
13739                          b->number);
13740       return;
13741     }
13742
13743   /* If there's no new locations, and all existing locations are
13744      pending, don't do anything.  This optimizes the common case where
13745      all locations are in the same shared library, that was unloaded.
13746      We'd like to retain the location, so that when the library is
13747      loaded again, we don't loose the enabled/disabled status of the
13748      individual locations.  */
13749   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13750     return;
13751
13752   existing_locations = hoist_existing_locations (b, filter_pspace);
13753
13754   for (const auto &sal : sals)
13755     {
13756       struct bp_location *new_loc;
13757
13758       switch_to_program_space_and_thread (sal.pspace);
13759
13760       new_loc = add_location_to_breakpoint (b, &sal);
13761
13762       /* Reparse conditions, they might contain references to the
13763          old symtab.  */
13764       if (b->cond_string != NULL)
13765         {
13766           const char *s;
13767
13768           s = b->cond_string;
13769           try
13770             {
13771               new_loc->cond = parse_exp_1 (&s, sal.pc,
13772                                            block_for_pc (sal.pc),
13773                                            0);
13774             }
13775           catch (const gdb_exception_error &e)
13776             {
13777               new_loc->disabled_by_cond = true;
13778             }
13779         }
13780
13781       if (!sals_end.empty ())
13782         {
13783           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13784
13785           new_loc->length = end - sals[0].pc + 1;
13786         }
13787     }
13788
13789   /* If possible, carry over 'disable' status from existing
13790      breakpoints.  */
13791   {
13792     struct bp_location *e = existing_locations;
13793     /* If there are multiple breakpoints with the same function name,
13794        e.g. for inline functions, comparing function names won't work.
13795        Instead compare pc addresses; this is just a heuristic as things
13796        may have moved, but in practice it gives the correct answer
13797        often enough until a better solution is found.  */
13798     int have_ambiguous_names = ambiguous_names_p (b->loc);
13799
13800     for (; e; e = e->next)
13801       {
13802         if ((!e->enabled || e->disabled_by_cond) && e->function_name)
13803           {
13804             struct bp_location *l = b->loc;
13805             if (have_ambiguous_names)
13806               {
13807                 for (; l; l = l->next)
13808                   {
13809                     /* Ignore software vs hardware location type at
13810                        this point, because with "set breakpoint
13811                        auto-hw", after a re-set, locations that were
13812                        hardware can end up as software, or vice versa.
13813                        As mentioned above, this is an heuristic and in
13814                        practice should give the correct answer often
13815                        enough.  */
13816                     if (breakpoint_locations_match (e, l, true))
13817                       {
13818                         l->enabled = e->enabled;
13819                         l->disabled_by_cond = e->disabled_by_cond;
13820                         break;
13821                       }
13822                   }
13823               }
13824             else
13825               {
13826                 for (; l; l = l->next)
13827                   if (l->function_name
13828                       && strcmp (e->function_name, l->function_name) == 0)
13829                     {
13830                       l->enabled = e->enabled;
13831                       l->disabled_by_cond = e->disabled_by_cond;
13832                       break;
13833                     }
13834               }
13835           }
13836       }
13837   }
13838
13839   if (!locations_are_equal (existing_locations, b->loc))
13840     gdb::observers::breakpoint_modified.notify (b);
13841 }
13842
13843 /* Find the SaL locations corresponding to the given LOCATION.
13844    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13845
13846 static std::vector<symtab_and_line>
13847 location_to_sals (struct breakpoint *b, struct event_location *location,
13848                   struct program_space *search_pspace, int *found)
13849 {
13850   struct gdb_exception exception;
13851
13852   gdb_assert (b->ops != NULL);
13853
13854   std::vector<symtab_and_line> sals;
13855
13856   try
13857     {
13858       sals = b->ops->decode_location (b, location, search_pspace);
13859     }
13860   catch (gdb_exception_error &e)
13861     {
13862       int not_found_and_ok = 0;
13863
13864       /* For pending breakpoints, it's expected that parsing will
13865          fail until the right shared library is loaded.  User has
13866          already told to create pending breakpoints and don't need
13867          extra messages.  If breakpoint is in bp_shlib_disabled
13868          state, then user already saw the message about that
13869          breakpoint being disabled, and don't want to see more
13870          errors.  */
13871       if (e.error == NOT_FOUND_ERROR
13872           && (b->condition_not_parsed
13873               || (b->loc != NULL
13874                   && search_pspace != NULL
13875                   && b->loc->pspace != search_pspace)
13876               || (b->loc && b->loc->shlib_disabled)
13877               || (b->loc && b->loc->pspace->executing_startup)
13878               || b->enable_state == bp_disabled))
13879         not_found_and_ok = 1;
13880
13881       if (!not_found_and_ok)
13882         {
13883           /* We surely don't want to warn about the same breakpoint
13884              10 times.  One solution, implemented here, is disable
13885              the breakpoint on error.  Another solution would be to
13886              have separate 'warning emitted' flag.  Since this
13887              happens only when a binary has changed, I don't know
13888              which approach is better.  */
13889           b->enable_state = bp_disabled;
13890           throw;
13891         }
13892
13893       exception = std::move (e);
13894     }
13895
13896   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13897     {
13898       for (auto &sal : sals)
13899         resolve_sal_pc (&sal);
13900       if (b->condition_not_parsed && b->extra_string != NULL)
13901         {
13902           char *cond_string, *extra_string;
13903           int thread, task;
13904
13905           find_condition_and_thread_for_sals (sals, b->extra_string,
13906                                               &cond_string, &thread,
13907                                               &task, &extra_string);
13908           gdb_assert (b->cond_string == NULL);
13909           if (cond_string)
13910             b->cond_string = cond_string;
13911           b->thread = thread;
13912           b->task = task;
13913           if (extra_string)
13914             {
13915               xfree (b->extra_string);
13916               b->extra_string = extra_string;
13917             }
13918           b->condition_not_parsed = 0;
13919         }
13920
13921       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13922         sals[0] = update_static_tracepoint (b, sals[0]);
13923
13924       *found = 1;
13925     }
13926   else
13927     *found = 0;
13928
13929   return sals;
13930 }
13931
13932 /* The default re_set method, for typical hardware or software
13933    breakpoints.  Reevaluate the breakpoint and recreate its
13934    locations.  */
13935
13936 static void
13937 breakpoint_re_set_default (struct breakpoint *b)
13938 {
13939   struct program_space *filter_pspace = current_program_space;
13940   std::vector<symtab_and_line> expanded, expanded_end;
13941
13942   int found;
13943   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13944                                                         filter_pspace, &found);
13945   if (found)
13946     expanded = std::move (sals);
13947
13948   if (b->location_range_end != NULL)
13949     {
13950       std::vector<symtab_and_line> sals_end
13951         = location_to_sals (b, b->location_range_end.get (),
13952                             filter_pspace, &found);
13953       if (found)
13954         expanded_end = std::move (sals_end);
13955     }
13956
13957   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13958 }
13959
13960 /* Default method for creating SALs from an address string.  It basically
13961    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13962
13963 static void
13964 create_sals_from_location_default (struct event_location *location,
13965                                    struct linespec_result *canonical,
13966                                    enum bptype type_wanted)
13967 {
13968   parse_breakpoint_sals (location, canonical);
13969 }
13970
13971 /* Call create_breakpoints_sal for the given arguments.  This is the default
13972    function for the `create_breakpoints_sal' method of
13973    breakpoint_ops.  */
13974
13975 static void
13976 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13977                                 struct linespec_result *canonical,
13978                                 gdb::unique_xmalloc_ptr<char> cond_string,
13979                                 gdb::unique_xmalloc_ptr<char> extra_string,
13980                                 enum bptype type_wanted,
13981                                 enum bpdisp disposition,
13982                                 int thread,
13983                                 int task, int ignore_count,
13984                                 const struct breakpoint_ops *ops,
13985                                 int from_tty, int enabled,
13986                                 int internal, unsigned flags)
13987 {
13988   create_breakpoints_sal (gdbarch, canonical,
13989                           std::move (cond_string),
13990                           std::move (extra_string),
13991                           type_wanted, disposition,
13992                           thread, task, ignore_count, ops, from_tty,
13993                           enabled, internal, flags);
13994 }
13995
13996 /* Decode the line represented by S by calling decode_line_full.  This is the
13997    default function for the `decode_location' method of breakpoint_ops.  */
13998
13999 static std::vector<symtab_and_line>
14000 decode_location_default (struct breakpoint *b,
14001                          struct event_location *location,
14002                          struct program_space *search_pspace)
14003 {
14004   struct linespec_result canonical;
14005
14006   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
14007                     NULL, 0, &canonical, multiple_symbols_all,
14008                     b->filter.get ());
14009
14010   /* We should get 0 or 1 resulting SALs.  */
14011   gdb_assert (canonical.lsals.size () < 2);
14012
14013   if (!canonical.lsals.empty ())
14014     {
14015       const linespec_sals &lsal = canonical.lsals[0];
14016       return std::move (lsal.sals);
14017     }
14018   return {};
14019 }
14020
14021 /* Reset a breakpoint.  */
14022
14023 static void
14024 breakpoint_re_set_one (breakpoint *b)
14025 {
14026   input_radix = b->input_radix;
14027   set_language (b->language);
14028
14029   b->ops->re_set (b);
14030 }
14031
14032 /* Re-set breakpoint locations for the current program space.
14033    Locations bound to other program spaces are left untouched.  */
14034
14035 void
14036 breakpoint_re_set (void)
14037 {
14038   struct breakpoint *b, *b_tmp;
14039
14040   {
14041     scoped_restore_current_language save_language;
14042     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
14043     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14044
14045     /* breakpoint_re_set_one sets the current_language to the language
14046        of the breakpoint it is resetting (see prepare_re_set_context)
14047        before re-evaluating the breakpoint's location.  This change can
14048        unfortunately get undone by accident if the language_mode is set
14049        to auto, and we either switch frames, or more likely in this context,
14050        we select the current frame.
14051
14052        We prevent this by temporarily turning the language_mode to
14053        language_mode_manual.  We restore it once all breakpoints
14054        have been reset.  */
14055     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
14056     language_mode = language_mode_manual;
14057
14058     /* Note: we must not try to insert locations until after all
14059        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14060        breakpoint 1, we'd insert the locations of breakpoint 2, which
14061        hadn't been re-set yet, and thus may have stale locations.  */
14062
14063     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14064       {
14065         try
14066           {
14067             breakpoint_re_set_one (b);
14068           }
14069         catch (const gdb_exception &ex)
14070           {
14071             exception_fprintf (gdb_stderr, ex,
14072                                "Error in re-setting breakpoint %d: ",
14073                                b->number);
14074           }
14075       }
14076
14077     jit_breakpoint_re_set ();
14078   }
14079
14080   create_overlay_event_breakpoint ();
14081   create_longjmp_master_breakpoint ();
14082   create_std_terminate_master_breakpoint ();
14083   create_exception_master_breakpoint ();
14084
14085   /* Now we can insert.  */
14086   update_global_location_list (UGLL_MAY_INSERT);
14087 }
14088 \f
14089 /* Reset the thread number of this breakpoint:
14090
14091    - If the breakpoint is for all threads, leave it as-is.
14092    - Else, reset it to the current thread for inferior_ptid.  */
14093 void
14094 breakpoint_re_set_thread (struct breakpoint *b)
14095 {
14096   if (b->thread != -1)
14097     {
14098       b->thread = inferior_thread ()->global_num;
14099
14100       /* We're being called after following a fork.  The new fork is
14101          selected as current, and unless this was a vfork will have a
14102          different program space from the original thread.  Reset that
14103          as well.  */
14104       b->loc->pspace = current_program_space;
14105     }
14106 }
14107
14108 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14109    If from_tty is nonzero, it prints a message to that effect,
14110    which ends with a period (no newline).  */
14111
14112 void
14113 set_ignore_count (int bptnum, int count, int from_tty)
14114 {
14115   struct breakpoint *b;
14116
14117   if (count < 0)
14118     count = 0;
14119
14120   ALL_BREAKPOINTS (b)
14121     if (b->number == bptnum)
14122     {
14123       if (is_tracepoint (b))
14124         {
14125           if (from_tty && count != 0)
14126             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14127                              bptnum);
14128           return;
14129         }
14130       
14131       b->ignore_count = count;
14132       if (from_tty)
14133         {
14134           if (count == 0)
14135             printf_filtered (_("Will stop next time "
14136                                "breakpoint %d is reached."),
14137                              bptnum);
14138           else if (count == 1)
14139             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14140                              bptnum);
14141           else
14142             printf_filtered (_("Will ignore next %d "
14143                                "crossings of breakpoint %d."),
14144                              count, bptnum);
14145         }
14146       gdb::observers::breakpoint_modified.notify (b);
14147       return;
14148     }
14149
14150   error (_("No breakpoint number %d."), bptnum);
14151 }
14152
14153 /* Command to set ignore-count of breakpoint N to COUNT.  */
14154
14155 static void
14156 ignore_command (const char *args, int from_tty)
14157 {
14158   const char *p = args;
14159   int num;
14160
14161   if (p == 0)
14162     error_no_arg (_("a breakpoint number"));
14163
14164   num = get_number (&p);
14165   if (num == 0)
14166     error (_("bad breakpoint number: '%s'"), args);
14167   if (*p == 0)
14168     error (_("Second argument (specified ignore-count) is missing."));
14169
14170   set_ignore_count (num,
14171                     longest_to_int (value_as_long (parse_and_eval (p))),
14172                     from_tty);
14173   if (from_tty)
14174     printf_filtered ("\n");
14175 }
14176 \f
14177
14178 /* Call FUNCTION on each of the breakpoints with numbers in the range
14179    defined by BP_NUM_RANGE (an inclusive range).  */
14180
14181 static void
14182 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14183                              gdb::function_view<void (breakpoint *)> function)
14184 {
14185   if (bp_num_range.first == 0)
14186     {
14187       warning (_("bad breakpoint number at or near '%d'"),
14188                bp_num_range.first);
14189     }
14190   else
14191     {
14192       struct breakpoint *b, *tmp;
14193
14194       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14195         {
14196           bool match = false;
14197
14198           ALL_BREAKPOINTS_SAFE (b, tmp)
14199             if (b->number == i)
14200               {
14201                 match = true;
14202                 function (b);
14203                 break;
14204               }
14205           if (!match)
14206             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14207         }
14208     }
14209 }
14210
14211 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14212    ARGS.  */
14213
14214 static void
14215 map_breakpoint_numbers (const char *args,
14216                         gdb::function_view<void (breakpoint *)> function)
14217 {
14218   if (args == NULL || *args == '\0')
14219     error_no_arg (_("one or more breakpoint numbers"));
14220
14221   number_or_range_parser parser (args);
14222
14223   while (!parser.finished ())
14224     {
14225       int num = parser.get_number ();
14226       map_breakpoint_number_range (std::make_pair (num, num), function);
14227     }
14228 }
14229
14230 /* Return the breakpoint location structure corresponding to the
14231    BP_NUM and LOC_NUM values.  */
14232
14233 static struct bp_location *
14234 find_location_by_number (int bp_num, int loc_num)
14235 {
14236   struct breakpoint *b;
14237
14238   ALL_BREAKPOINTS (b)
14239     if (b->number == bp_num)
14240       {
14241         break;
14242       }
14243
14244   if (!b || b->number != bp_num)
14245     error (_("Bad breakpoint number '%d'"), bp_num);
14246   
14247   if (loc_num == 0)
14248     error (_("Bad breakpoint location number '%d'"), loc_num);
14249
14250   int n = 0;
14251   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14252     if (++n == loc_num)
14253       return loc;
14254
14255   error (_("Bad breakpoint location number '%d'"), loc_num);
14256 }
14257
14258 /* Modes of operation for extract_bp_num.  */
14259 enum class extract_bp_kind
14260 {
14261   /* Extracting a breakpoint number.  */
14262   bp,
14263
14264   /* Extracting a location number.  */
14265   loc,
14266 };
14267
14268 /* Extract a breakpoint or location number (as determined by KIND)
14269    from the string starting at START.  TRAILER is a character which
14270    can be found after the number.  If you don't want a trailer, use
14271    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14272    string.  This always returns a positive integer.  */
14273
14274 static int
14275 extract_bp_num (extract_bp_kind kind, const char *start,
14276                 int trailer, const char **end_out = NULL)
14277 {
14278   const char *end = start;
14279   int num = get_number_trailer (&end, trailer);
14280   if (num < 0)
14281     error (kind == extract_bp_kind::bp
14282            ? _("Negative breakpoint number '%.*s'")
14283            : _("Negative breakpoint location number '%.*s'"),
14284            int (end - start), start);
14285   if (num == 0)
14286     error (kind == extract_bp_kind::bp
14287            ? _("Bad breakpoint number '%.*s'")
14288            : _("Bad breakpoint location number '%.*s'"),
14289            int (end - start), start);
14290
14291   if (end_out != NULL)
14292     *end_out = end;
14293   return num;
14294 }
14295
14296 /* Extract a breakpoint or location range (as determined by KIND) in
14297    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14298    representing the (inclusive) range.  The returned pair's elements
14299    are always positive integers.  */
14300
14301 static std::pair<int, int>
14302 extract_bp_or_bp_range (extract_bp_kind kind,
14303                         const std::string &arg,
14304                         std::string::size_type arg_offset)
14305 {
14306   std::pair<int, int> range;
14307   const char *bp_loc = &arg[arg_offset];
14308   std::string::size_type dash = arg.find ('-', arg_offset);
14309   if (dash != std::string::npos)
14310     {
14311       /* bp_loc is a range (x-z).  */
14312       if (arg.length () == dash + 1)
14313         error (kind == extract_bp_kind::bp
14314                ? _("Bad breakpoint number at or near: '%s'")
14315                : _("Bad breakpoint location number at or near: '%s'"),
14316                bp_loc);
14317
14318       const char *end;
14319       const char *start_first = bp_loc;
14320       const char *start_second = &arg[dash + 1];
14321       range.first = extract_bp_num (kind, start_first, '-');
14322       range.second = extract_bp_num (kind, start_second, '\0', &end);
14323
14324       if (range.first > range.second)
14325         error (kind == extract_bp_kind::bp
14326                ? _("Inverted breakpoint range at '%.*s'")
14327                : _("Inverted breakpoint location range at '%.*s'"),
14328                int (end - start_first), start_first);
14329     }
14330   else
14331     {
14332       /* bp_loc is a single value.  */
14333       range.first = extract_bp_num (kind, bp_loc, '\0');
14334       range.second = range.first;
14335     }
14336   return range;
14337 }
14338
14339 /* Extract the breakpoint/location range specified by ARG.  Returns
14340    the breakpoint range in BP_NUM_RANGE, and the location range in
14341    BP_LOC_RANGE.
14342
14343    ARG may be in any of the following forms:
14344
14345    x     where 'x' is a breakpoint number.
14346    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14347    x.y   where 'x' is a breakpoint number and 'y' a location number.
14348    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14349          location number range.
14350 */
14351
14352 static void
14353 extract_bp_number_and_location (const std::string &arg,
14354                                 std::pair<int, int> &bp_num_range,
14355                                 std::pair<int, int> &bp_loc_range)
14356 {
14357   std::string::size_type dot = arg.find ('.');
14358
14359   if (dot != std::string::npos)
14360     {
14361       /* Handle 'x.y' and 'x.y-z' cases.  */
14362
14363       if (arg.length () == dot + 1 || dot == 0)
14364         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14365
14366       bp_num_range.first
14367         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14368       bp_num_range.second = bp_num_range.first;
14369
14370       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14371                                              arg, dot + 1);
14372     }
14373   else
14374     {
14375       /* Handle x and x-y cases.  */
14376
14377       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14378       bp_loc_range.first = 0;
14379       bp_loc_range.second = 0;
14380     }
14381 }
14382
14383 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14384    specifies whether to enable or disable.  */
14385
14386 static void
14387 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14388 {
14389   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14390   if (loc != NULL)
14391     {
14392       if (loc->disabled_by_cond && enable)
14393         error (_("Breakpoint %d's condition is invalid at location %d, "
14394                  "cannot enable."), bp_num, loc_num);
14395
14396       if (loc->enabled != enable)
14397         {
14398           loc->enabled = enable;
14399           mark_breakpoint_location_modified (loc);
14400         }
14401       if (target_supports_enable_disable_tracepoint ()
14402           && current_trace_status ()->running && loc->owner
14403           && is_tracepoint (loc->owner))
14404         target_disable_tracepoint (loc);
14405     }
14406   update_global_location_list (UGLL_DONT_INSERT);
14407
14408   gdb::observers::breakpoint_modified.notify (loc->owner);
14409 }
14410
14411 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14412    number of the breakpoint, and BP_LOC_RANGE specifies the
14413    (inclusive) range of location numbers of that breakpoint to
14414    enable/disable.  ENABLE specifies whether to enable or disable the
14415    location.  */
14416
14417 static void
14418 enable_disable_breakpoint_location_range (int bp_num,
14419                                           std::pair<int, int> &bp_loc_range,
14420                                           bool enable)
14421 {
14422   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14423     enable_disable_bp_num_loc (bp_num, i, enable);
14424 }
14425
14426 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14427    If from_tty is nonzero, it prints a message to that effect,
14428    which ends with a period (no newline).  */
14429
14430 void
14431 disable_breakpoint (struct breakpoint *bpt)
14432 {
14433   /* Never disable a watchpoint scope breakpoint; we want to
14434      hit them when we leave scope so we can delete both the
14435      watchpoint and its scope breakpoint at that time.  */
14436   if (bpt->type == bp_watchpoint_scope)
14437     return;
14438
14439   bpt->enable_state = bp_disabled;
14440
14441   /* Mark breakpoint locations modified.  */
14442   mark_breakpoint_modified (bpt);
14443
14444   if (target_supports_enable_disable_tracepoint ()
14445       && current_trace_status ()->running && is_tracepoint (bpt))
14446     {
14447       struct bp_location *location;
14448      
14449       for (location = bpt->loc; location; location = location->next)
14450         target_disable_tracepoint (location);
14451     }
14452
14453   update_global_location_list (UGLL_DONT_INSERT);
14454
14455   gdb::observers::breakpoint_modified.notify (bpt);
14456 }
14457
14458 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14459    specified in ARGS.  ARGS may be in any of the formats handled by
14460    extract_bp_number_and_location.  ENABLE specifies whether to enable
14461    or disable the breakpoints/locations.  */
14462
14463 static void
14464 enable_disable_command (const char *args, int from_tty, bool enable)
14465 {
14466   if (args == 0)
14467     {
14468       struct breakpoint *bpt;
14469
14470       ALL_BREAKPOINTS (bpt)
14471         if (user_breakpoint_p (bpt))
14472           {
14473             if (enable)
14474               enable_breakpoint (bpt);
14475             else
14476               disable_breakpoint (bpt);
14477           }
14478     }
14479   else
14480     {
14481       std::string num = extract_arg (&args);
14482
14483       while (!num.empty ())
14484         {
14485           std::pair<int, int> bp_num_range, bp_loc_range;
14486
14487           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14488
14489           if (bp_loc_range.first == bp_loc_range.second
14490               && bp_loc_range.first == 0)
14491             {
14492               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14493               map_breakpoint_number_range (bp_num_range,
14494                                            enable
14495                                            ? enable_breakpoint
14496                                            : disable_breakpoint);
14497             }
14498           else
14499             {
14500               /* Handle breakpoint ids with formats 'x.y' or
14501                  'x.y-z'.  */
14502               enable_disable_breakpoint_location_range
14503                 (bp_num_range.first, bp_loc_range, enable);
14504             }
14505           num = extract_arg (&args);
14506         }
14507     }
14508 }
14509
14510 /* The disable command disables the specified breakpoints/locations
14511    (or all defined breakpoints) so they're no longer effective in
14512    stopping the inferior.  ARGS may be in any of the forms defined in
14513    extract_bp_number_and_location.  */
14514
14515 static void
14516 disable_command (const char *args, int from_tty)
14517 {
14518   enable_disable_command (args, from_tty, false);
14519 }
14520
14521 static void
14522 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14523                         int count)
14524 {
14525   int target_resources_ok;
14526
14527   if (bpt->type == bp_hardware_breakpoint)
14528     {
14529       int i;
14530       i = hw_breakpoint_used_count ();
14531       target_resources_ok = 
14532         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14533                                             i + 1, 0);
14534       if (target_resources_ok == 0)
14535         error (_("No hardware breakpoint support in the target."));
14536       else if (target_resources_ok < 0)
14537         error (_("Hardware breakpoints used exceeds limit."));
14538     }
14539
14540   if (is_watchpoint (bpt))
14541     {
14542       /* Initialize it just to avoid a GCC false warning.  */
14543       enum enable_state orig_enable_state = bp_disabled;
14544
14545       try
14546         {
14547           struct watchpoint *w = (struct watchpoint *) bpt;
14548
14549           orig_enable_state = bpt->enable_state;
14550           bpt->enable_state = bp_enabled;
14551           update_watchpoint (w, 1 /* reparse */);
14552         }
14553       catch (const gdb_exception &e)
14554         {
14555           bpt->enable_state = orig_enable_state;
14556           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14557                              bpt->number);
14558           return;
14559         }
14560     }
14561
14562   bpt->enable_state = bp_enabled;
14563
14564   /* Mark breakpoint locations modified.  */
14565   mark_breakpoint_modified (bpt);
14566
14567   if (target_supports_enable_disable_tracepoint ()
14568       && current_trace_status ()->running && is_tracepoint (bpt))
14569     {
14570       struct bp_location *location;
14571
14572       for (location = bpt->loc; location; location = location->next)
14573         target_enable_tracepoint (location);
14574     }
14575
14576   bpt->disposition = disposition;
14577   bpt->enable_count = count;
14578   update_global_location_list (UGLL_MAY_INSERT);
14579
14580   gdb::observers::breakpoint_modified.notify (bpt);
14581 }
14582
14583
14584 void
14585 enable_breakpoint (struct breakpoint *bpt)
14586 {
14587   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14588 }
14589
14590 /* The enable command enables the specified breakpoints/locations (or
14591    all defined breakpoints) so they once again become (or continue to
14592    be) effective in stopping the inferior.  ARGS may be in any of the
14593    forms defined in extract_bp_number_and_location.  */
14594
14595 static void
14596 enable_command (const char *args, int from_tty)
14597 {
14598   enable_disable_command (args, from_tty, true);
14599 }
14600
14601 static void
14602 enable_once_command (const char *args, int from_tty)
14603 {
14604   map_breakpoint_numbers
14605     (args, [&] (breakpoint *b)
14606      {
14607        iterate_over_related_breakpoints
14608          (b, [&] (breakpoint *bpt)
14609           {
14610             enable_breakpoint_disp (bpt, disp_disable, 1);
14611           });
14612      });
14613 }
14614
14615 static void
14616 enable_count_command (const char *args, int from_tty)
14617 {
14618   int count;
14619
14620   if (args == NULL)
14621     error_no_arg (_("hit count"));
14622
14623   count = get_number (&args);
14624
14625   map_breakpoint_numbers
14626     (args, [&] (breakpoint *b)
14627      {
14628        iterate_over_related_breakpoints
14629          (b, [&] (breakpoint *bpt)
14630           {
14631             enable_breakpoint_disp (bpt, disp_disable, count);
14632           });
14633      });
14634 }
14635
14636 static void
14637 enable_delete_command (const char *args, int from_tty)
14638 {
14639   map_breakpoint_numbers
14640     (args, [&] (breakpoint *b)
14641      {
14642        iterate_over_related_breakpoints
14643          (b, [&] (breakpoint *bpt)
14644           {
14645             enable_breakpoint_disp (bpt, disp_del, 1);
14646           });
14647      });
14648 }
14649 \f
14650 /* Invalidate last known value of any hardware watchpoint if
14651    the memory which that value represents has been written to by
14652    GDB itself.  */
14653
14654 static void
14655 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14656                                       CORE_ADDR addr, ssize_t len,
14657                                       const bfd_byte *data)
14658 {
14659   struct breakpoint *bp;
14660
14661   ALL_BREAKPOINTS (bp)
14662     if (bp->enable_state == bp_enabled
14663         && bp->type == bp_hardware_watchpoint)
14664       {
14665         struct watchpoint *wp = (struct watchpoint *) bp;
14666
14667         if (wp->val_valid && wp->val != nullptr)
14668           {
14669             struct bp_location *loc;
14670
14671             for (loc = bp->loc; loc != NULL; loc = loc->next)
14672               if (loc->loc_type == bp_loc_hardware_watchpoint
14673                   && loc->address + loc->length > addr
14674                   && addr + len > loc->address)
14675                 {
14676                   wp->val = NULL;
14677                   wp->val_valid = false;
14678                 }
14679           }
14680       }
14681 }
14682
14683 /* Create and insert a breakpoint for software single step.  */
14684
14685 void
14686 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14687                                const address_space *aspace,
14688                                CORE_ADDR next_pc)
14689 {
14690   struct thread_info *tp = inferior_thread ();
14691   struct symtab_and_line sal;
14692   CORE_ADDR pc = next_pc;
14693
14694   if (tp->control.single_step_breakpoints == NULL)
14695     {
14696       tp->control.single_step_breakpoints
14697         = new_single_step_breakpoint (tp->global_num, gdbarch);
14698     }
14699
14700   sal = find_pc_line (pc, 0);
14701   sal.pc = pc;
14702   sal.section = find_pc_overlay (pc);
14703   sal.explicit_pc = 1;
14704   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14705
14706   update_global_location_list (UGLL_INSERT);
14707 }
14708
14709 /* Insert single step breakpoints according to the current state.  */
14710
14711 int
14712 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14713 {
14714   struct regcache *regcache = get_current_regcache ();
14715   std::vector<CORE_ADDR> next_pcs;
14716
14717   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14718
14719   if (!next_pcs.empty ())
14720     {
14721       struct frame_info *frame = get_current_frame ();
14722       const address_space *aspace = get_frame_address_space (frame);
14723
14724       for (CORE_ADDR pc : next_pcs)
14725         insert_single_step_breakpoint (gdbarch, aspace, pc);
14726
14727       return 1;
14728     }
14729   else
14730     return 0;
14731 }
14732
14733 /* See breakpoint.h.  */
14734
14735 int
14736 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14737                                        const address_space *aspace,
14738                                        CORE_ADDR pc)
14739 {
14740   struct bp_location *loc;
14741
14742   for (loc = bp->loc; loc != NULL; loc = loc->next)
14743     if (loc->inserted
14744         && breakpoint_location_address_match (loc, aspace, pc))
14745       return 1;
14746
14747   return 0;
14748 }
14749
14750 /* Check whether a software single-step breakpoint is inserted at
14751    PC.  */
14752
14753 int
14754 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14755                                         CORE_ADDR pc)
14756 {
14757   struct breakpoint *bpt;
14758
14759   ALL_BREAKPOINTS (bpt)
14760     {
14761       if (bpt->type == bp_single_step
14762           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14763         return 1;
14764     }
14765   return 0;
14766 }
14767
14768 /* Tracepoint-specific operations.  */
14769
14770 /* Set tracepoint count to NUM.  */
14771 static void
14772 set_tracepoint_count (int num)
14773 {
14774   tracepoint_count = num;
14775   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14776 }
14777
14778 static void
14779 trace_command (const char *arg, int from_tty)
14780 {
14781   event_location_up location = string_to_event_location (&arg,
14782                                                          current_language);
14783   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
14784     (location.get (), true /* is_tracepoint */);
14785
14786   create_breakpoint (get_current_arch (),
14787                      location.get (),
14788                      NULL, 0, arg, 1 /* parse arg */,
14789                      0 /* tempflag */,
14790                      bp_tracepoint /* type_wanted */,
14791                      0 /* Ignore count */,
14792                      pending_break_support,
14793                      ops,
14794                      from_tty,
14795                      1 /* enabled */,
14796                      0 /* internal */, 0);
14797 }
14798
14799 static void
14800 ftrace_command (const char *arg, int from_tty)
14801 {
14802   event_location_up location = string_to_event_location (&arg,
14803                                                          current_language);
14804   create_breakpoint (get_current_arch (),
14805                      location.get (),
14806                      NULL, 0, arg, 1 /* parse arg */,
14807                      0 /* tempflag */,
14808                      bp_fast_tracepoint /* type_wanted */,
14809                      0 /* Ignore count */,
14810                      pending_break_support,
14811                      &tracepoint_breakpoint_ops,
14812                      from_tty,
14813                      1 /* enabled */,
14814                      0 /* internal */, 0);
14815 }
14816
14817 /* strace command implementation.  Creates a static tracepoint.  */
14818
14819 static void
14820 strace_command (const char *arg, int from_tty)
14821 {
14822   struct breakpoint_ops *ops;
14823   event_location_up location;
14824
14825   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14826      or with a normal static tracepoint.  */
14827   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14828     {
14829       ops = &strace_marker_breakpoint_ops;
14830       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14831     }
14832   else
14833     {
14834       ops = &tracepoint_breakpoint_ops;
14835       location = string_to_event_location (&arg, current_language);
14836     }
14837
14838   create_breakpoint (get_current_arch (),
14839                      location.get (),
14840                      NULL, 0, arg, 1 /* parse arg */,
14841                      0 /* tempflag */,
14842                      bp_static_tracepoint /* type_wanted */,
14843                      0 /* Ignore count */,
14844                      pending_break_support,
14845                      ops,
14846                      from_tty,
14847                      1 /* enabled */,
14848                      0 /* internal */, 0);
14849 }
14850
14851 /* Set up a fake reader function that gets command lines from a linked
14852    list that was acquired during tracepoint uploading.  */
14853
14854 static struct uploaded_tp *this_utp;
14855 static int next_cmd;
14856
14857 static char *
14858 read_uploaded_action (void)
14859 {
14860   char *rslt = nullptr;
14861
14862   if (next_cmd < this_utp->cmd_strings.size ())
14863     {
14864       rslt = this_utp->cmd_strings[next_cmd].get ();
14865       next_cmd++;
14866     }
14867
14868   return rslt;
14869 }
14870
14871 /* Given information about a tracepoint as recorded on a target (which
14872    can be either a live system or a trace file), attempt to create an
14873    equivalent GDB tracepoint.  This is not a reliable process, since
14874    the target does not necessarily have all the information used when
14875    the tracepoint was originally defined.  */
14876   
14877 struct tracepoint *
14878 create_tracepoint_from_upload (struct uploaded_tp *utp)
14879 {
14880   const char *addr_str;
14881   char small_buf[100];
14882   struct tracepoint *tp;
14883
14884   if (utp->at_string)
14885     addr_str = utp->at_string.get ();
14886   else
14887     {
14888       /* In the absence of a source location, fall back to raw
14889          address.  Since there is no way to confirm that the address
14890          means the same thing as when the trace was started, warn the
14891          user.  */
14892       warning (_("Uploaded tracepoint %d has no "
14893                  "source location, using raw address"),
14894                utp->number);
14895       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14896       addr_str = small_buf;
14897     }
14898
14899   /* There's not much we can do with a sequence of bytecodes.  */
14900   if (utp->cond && !utp->cond_string)
14901     warning (_("Uploaded tracepoint %d condition "
14902                "has no source form, ignoring it"),
14903              utp->number);
14904
14905   event_location_up location = string_to_event_location (&addr_str,
14906                                                          current_language);
14907   if (!create_breakpoint (get_current_arch (),
14908                           location.get (),
14909                           utp->cond_string.get (), -1, addr_str,
14910                           0 /* parse cond/thread */,
14911                           0 /* tempflag */,
14912                           utp->type /* type_wanted */,
14913                           0 /* Ignore count */,
14914                           pending_break_support,
14915                           &tracepoint_breakpoint_ops,
14916                           0 /* from_tty */,
14917                           utp->enabled /* enabled */,
14918                           0 /* internal */,
14919                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14920     return NULL;
14921
14922   /* Get the tracepoint we just created.  */
14923   tp = get_tracepoint (tracepoint_count);
14924   gdb_assert (tp != NULL);
14925
14926   if (utp->pass > 0)
14927     {
14928       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14929                  tp->number);
14930
14931       trace_pass_command (small_buf, 0);
14932     }
14933
14934   /* If we have uploaded versions of the original commands, set up a
14935      special-purpose "reader" function and call the usual command line
14936      reader, then pass the result to the breakpoint command-setting
14937      function.  */
14938   if (!utp->cmd_strings.empty ())
14939     {
14940       counted_command_line cmd_list;
14941
14942       this_utp = utp;
14943       next_cmd = 0;
14944
14945       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14946
14947       breakpoint_set_commands (tp, std::move (cmd_list));
14948     }
14949   else if (!utp->actions.empty ()
14950            || !utp->step_actions.empty ())
14951     warning (_("Uploaded tracepoint %d actions "
14952                "have no source form, ignoring them"),
14953              utp->number);
14954
14955   /* Copy any status information that might be available.  */
14956   tp->hit_count = utp->hit_count;
14957   tp->traceframe_usage = utp->traceframe_usage;
14958
14959   return tp;
14960 }
14961   
14962 /* Print information on tracepoint number TPNUM_EXP, or all if
14963    omitted.  */
14964
14965 static void
14966 info_tracepoints_command (const char *args, int from_tty)
14967 {
14968   struct ui_out *uiout = current_uiout;
14969   int num_printed;
14970
14971   num_printed = breakpoint_1 (args, false, is_tracepoint);
14972
14973   if (num_printed == 0)
14974     {
14975       if (args == NULL || *args == '\0')
14976         uiout->message ("No tracepoints.\n");
14977       else
14978         uiout->message ("No tracepoint matching '%s'.\n", args);
14979     }
14980
14981   default_collect_info ();
14982 }
14983
14984 /* The 'enable trace' command enables tracepoints.
14985    Not supported by all targets.  */
14986 static void
14987 enable_trace_command (const char *args, int from_tty)
14988 {
14989   enable_command (args, from_tty);
14990 }
14991
14992 /* The 'disable trace' command disables tracepoints.
14993    Not supported by all targets.  */
14994 static void
14995 disable_trace_command (const char *args, int from_tty)
14996 {
14997   disable_command (args, from_tty);
14998 }
14999
15000 /* Remove a tracepoint (or all if no argument).  */
15001 static void
15002 delete_trace_command (const char *arg, int from_tty)
15003 {
15004   struct breakpoint *b, *b_tmp;
15005
15006   dont_repeat ();
15007
15008   if (arg == 0)
15009     {
15010       int breaks_to_delete = 0;
15011
15012       /* Delete all breakpoints if no argument.
15013          Do not delete internal or call-dummy breakpoints, these
15014          have to be deleted with an explicit breakpoint number 
15015          argument.  */
15016       ALL_TRACEPOINTS (b)
15017         if (is_tracepoint (b) && user_breakpoint_p (b))
15018           {
15019             breaks_to_delete = 1;
15020             break;
15021           }
15022
15023       /* Ask user only if there are some breakpoints to delete.  */
15024       if (!from_tty
15025           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15026         {
15027           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15028             if (is_tracepoint (b) && user_breakpoint_p (b))
15029               delete_breakpoint (b);
15030         }
15031     }
15032   else
15033     map_breakpoint_numbers
15034       (arg, [&] (breakpoint *br)
15035        {
15036          iterate_over_related_breakpoints (br, delete_breakpoint);
15037        });
15038 }
15039
15040 /* Helper function for trace_pass_command.  */
15041
15042 static void
15043 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15044 {
15045   tp->pass_count = count;
15046   gdb::observers::breakpoint_modified.notify (tp);
15047   if (from_tty)
15048     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15049                      tp->number, count);
15050 }
15051
15052 /* Set passcount for tracepoint.
15053
15054    First command argument is passcount, second is tracepoint number.
15055    If tracepoint number omitted, apply to most recently defined.
15056    Also accepts special argument "all".  */
15057
15058 static void
15059 trace_pass_command (const char *args, int from_tty)
15060 {
15061   struct tracepoint *t1;
15062   ULONGEST count;
15063
15064   if (args == 0 || *args == 0)
15065     error (_("passcount command requires an "
15066              "argument (count + optional TP num)"));
15067
15068   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
15069
15070   args = skip_spaces (args);
15071   if (*args && strncasecmp (args, "all", 3) == 0)
15072     {
15073       struct breakpoint *b;
15074
15075       args += 3;                        /* Skip special argument "all".  */
15076       if (*args)
15077         error (_("Junk at end of arguments."));
15078
15079       ALL_TRACEPOINTS (b)
15080       {
15081         t1 = (struct tracepoint *) b;
15082         trace_pass_set_count (t1, count, from_tty);
15083       }
15084     }
15085   else if (*args == '\0')
15086     {
15087       t1 = get_tracepoint_by_number (&args, NULL);
15088       if (t1)
15089         trace_pass_set_count (t1, count, from_tty);
15090     }
15091   else
15092     {
15093       number_or_range_parser parser (args);
15094       while (!parser.finished ())
15095         {
15096           t1 = get_tracepoint_by_number (&args, &parser);
15097           if (t1)
15098             trace_pass_set_count (t1, count, from_tty);
15099         }
15100     }
15101 }
15102
15103 struct tracepoint *
15104 get_tracepoint (int num)
15105 {
15106   struct breakpoint *t;
15107
15108   ALL_TRACEPOINTS (t)
15109     if (t->number == num)
15110       return (struct tracepoint *) t;
15111
15112   return NULL;
15113 }
15114
15115 /* Find the tracepoint with the given target-side number (which may be
15116    different from the tracepoint number after disconnecting and
15117    reconnecting).  */
15118
15119 struct tracepoint *
15120 get_tracepoint_by_number_on_target (int num)
15121 {
15122   struct breakpoint *b;
15123
15124   ALL_TRACEPOINTS (b)
15125     {
15126       struct tracepoint *t = (struct tracepoint *) b;
15127
15128       if (t->number_on_target == num)
15129         return t;
15130     }
15131
15132   return NULL;
15133 }
15134
15135 /* Utility: parse a tracepoint number and look it up in the list.
15136    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15137    If the argument is missing, the most recent tracepoint
15138    (tracepoint_count) is returned.  */
15139
15140 struct tracepoint *
15141 get_tracepoint_by_number (const char **arg,
15142                           number_or_range_parser *parser)
15143 {
15144   struct breakpoint *t;
15145   int tpnum;
15146   const char *instring = arg == NULL ? NULL : *arg;
15147
15148   if (parser != NULL)
15149     {
15150       gdb_assert (!parser->finished ());
15151       tpnum = parser->get_number ();
15152     }
15153   else if (arg == NULL || *arg == NULL || ! **arg)
15154     tpnum = tracepoint_count;
15155   else
15156     tpnum = get_number (arg);
15157
15158   if (tpnum <= 0)
15159     {
15160       if (instring && *instring)
15161         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15162                          instring);
15163       else
15164         printf_filtered (_("No previous tracepoint\n"));
15165       return NULL;
15166     }
15167
15168   ALL_TRACEPOINTS (t)
15169     if (t->number == tpnum)
15170     {
15171       return (struct tracepoint *) t;
15172     }
15173
15174   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15175   return NULL;
15176 }
15177
15178 void
15179 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15180 {
15181   if (b->thread != -1)
15182     fprintf_unfiltered (fp, " thread %d", b->thread);
15183
15184   if (b->task != 0)
15185     fprintf_unfiltered (fp, " task %d", b->task);
15186
15187   fprintf_unfiltered (fp, "\n");
15188 }
15189
15190 /* Save information on user settable breakpoints (watchpoints, etc) to
15191    a new script file named FILENAME.  If FILTER is non-NULL, call it
15192    on each breakpoint and only include the ones for which it returns
15193    true.  */
15194
15195 static void
15196 save_breakpoints (const char *filename, int from_tty,
15197                   bool (*filter) (const struct breakpoint *))
15198 {
15199   struct breakpoint *tp;
15200   int any = 0;
15201   int extra_trace_bits = 0;
15202
15203   if (filename == 0 || *filename == 0)
15204     error (_("Argument required (file name in which to save)"));
15205
15206   /* See if we have anything to save.  */
15207   ALL_BREAKPOINTS (tp)
15208   {
15209     /* Skip internal and momentary breakpoints.  */
15210     if (!user_breakpoint_p (tp))
15211       continue;
15212
15213     /* If we have a filter, only save the breakpoints it accepts.  */
15214     if (filter && !filter (tp))
15215       continue;
15216
15217     any = 1;
15218
15219     if (is_tracepoint (tp))
15220       {
15221         extra_trace_bits = 1;
15222
15223         /* We can stop searching.  */
15224         break;
15225       }
15226   }
15227
15228   if (!any)
15229     {
15230       warning (_("Nothing to save."));
15231       return;
15232     }
15233
15234   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15235
15236   stdio_file fp;
15237
15238   if (!fp.open (expanded_filename.get (), "w"))
15239     error (_("Unable to open file '%s' for saving (%s)"),
15240            expanded_filename.get (), safe_strerror (errno));
15241
15242   if (extra_trace_bits)
15243     save_trace_state_variables (&fp);
15244
15245   ALL_BREAKPOINTS (tp)
15246   {
15247     /* Skip internal and momentary breakpoints.  */
15248     if (!user_breakpoint_p (tp))
15249       continue;
15250
15251     /* If we have a filter, only save the breakpoints it accepts.  */
15252     if (filter && !filter (tp))
15253       continue;
15254
15255     tp->ops->print_recreate (tp, &fp);
15256
15257     /* Note, we can't rely on tp->number for anything, as we can't
15258        assume the recreated breakpoint numbers will match.  Use $bpnum
15259        instead.  */
15260
15261     if (tp->cond_string)
15262       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15263
15264     if (tp->ignore_count)
15265       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15266
15267     if (tp->type != bp_dprintf && tp->commands)
15268       {
15269         fp.puts ("  commands\n");
15270         
15271         current_uiout->redirect (&fp);
15272         try
15273           {
15274             print_command_lines (current_uiout, tp->commands.get (), 2);
15275           }
15276         catch (const gdb_exception &ex)
15277           {
15278           current_uiout->redirect (NULL);
15279             throw;
15280           }
15281
15282         current_uiout->redirect (NULL);
15283         fp.puts ("  end\n");
15284       }
15285
15286     if (tp->enable_state == bp_disabled)
15287       fp.puts ("disable $bpnum\n");
15288
15289     /* If this is a multi-location breakpoint, check if the locations
15290        should be individually disabled.  Watchpoint locations are
15291        special, and not user visible.  */
15292     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15293       {
15294         struct bp_location *loc;
15295         int n = 1;
15296
15297         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15298           if (!loc->enabled)
15299             fp.printf ("disable $bpnum.%d\n", n);
15300       }
15301   }
15302
15303   if (extra_trace_bits && *default_collect)
15304     fp.printf ("set default-collect %s\n", default_collect);
15305
15306   if (from_tty)
15307     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15308 }
15309
15310 /* The `save breakpoints' command.  */
15311
15312 static void
15313 save_breakpoints_command (const char *args, int from_tty)
15314 {
15315   save_breakpoints (args, from_tty, NULL);
15316 }
15317
15318 /* The `save tracepoints' command.  */
15319
15320 static void
15321 save_tracepoints_command (const char *args, int from_tty)
15322 {
15323   save_breakpoints (args, from_tty, is_tracepoint);
15324 }
15325
15326 /* Create a vector of all tracepoints.  */
15327
15328 std::vector<breakpoint *>
15329 all_tracepoints (void)
15330 {
15331   std::vector<breakpoint *> tp_vec;
15332   struct breakpoint *tp;
15333
15334   ALL_TRACEPOINTS (tp)
15335   {
15336     tp_vec.push_back (tp);
15337   }
15338
15339   return tp_vec;
15340 }
15341
15342 \f
15343 /* This help string is used to consolidate all the help string for specifying
15344    locations used by several commands.  */
15345
15346 #define LOCATION_HELP_STRING \
15347 "Linespecs are colon-separated lists of location parameters, such as\n\
15348 source filename, function name, label name, and line number.\n\
15349 Example: To specify the start of a label named \"the_top\" in the\n\
15350 function \"fact\" in the file \"factorial.c\", use\n\
15351 \"factorial.c:fact:the_top\".\n\
15352 \n\
15353 Address locations begin with \"*\" and specify an exact address in the\n\
15354 program.  Example: To specify the fourth byte past the start function\n\
15355 \"main\", use \"*main + 4\".\n\
15356 \n\
15357 Explicit locations are similar to linespecs but use an option/argument\n\
15358 syntax to specify location parameters.\n\
15359 Example: To specify the start of the label named \"the_top\" in the\n\
15360 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15361 -function fact -label the_top\".\n\
15362 \n\
15363 By default, a specified function is matched against the program's\n\
15364 functions in all scopes.  For C++, this means in all namespaces and\n\
15365 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15366 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15367 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15368 specified name as a complete fully-qualified name instead."
15369
15370 /* This help string is used for the break, hbreak, tbreak and thbreak
15371    commands.  It is defined as a macro to prevent duplication.
15372    COMMAND should be a string constant containing the name of the
15373    command.  */
15374
15375 #define BREAK_ARGS_HELP(command) \
15376 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
15377 \t[-force-condition] [if CONDITION]\n\
15378 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15379 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15380 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15381 `-probe-dtrace' (for a DTrace probe).\n\
15382 LOCATION may be a linespec, address, or explicit location as described\n\
15383 below.\n\
15384 \n\
15385 With no LOCATION, uses current execution address of the selected\n\
15386 stack frame.  This is useful for breaking on return to a stack frame.\n\
15387 \n\
15388 THREADNUM is the number from \"info threads\".\n\
15389 CONDITION is a boolean expression.\n\
15390 \n\
15391 With the \"-force-condition\" flag, the condition is defined even when\n\
15392 it is invalid for all current locations.\n\
15393 \n" LOCATION_HELP_STRING "\n\n\
15394 Multiple breakpoints at one place are permitted, and useful if their\n\
15395 conditions are different.\n\
15396 \n\
15397 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15398
15399 /* List of subcommands for "catch".  */
15400 static struct cmd_list_element *catch_cmdlist;
15401
15402 /* List of subcommands for "tcatch".  */
15403 static struct cmd_list_element *tcatch_cmdlist;
15404
15405 void
15406 add_catch_command (const char *name, const char *docstring,
15407                    cmd_const_sfunc_ftype *sfunc,
15408                    completer_ftype *completer,
15409                    void *user_data_catch,
15410                    void *user_data_tcatch)
15411 {
15412   struct cmd_list_element *command;
15413
15414   command = add_cmd (name, class_breakpoint, docstring,
15415                      &catch_cmdlist);
15416   set_cmd_sfunc (command, sfunc);
15417   set_cmd_context (command, user_data_catch);
15418   set_cmd_completer (command, completer);
15419
15420   command = add_cmd (name, class_breakpoint, docstring,
15421                      &tcatch_cmdlist);
15422   set_cmd_sfunc (command, sfunc);
15423   set_cmd_context (command, user_data_tcatch);
15424   set_cmd_completer (command, completer);
15425 }
15426
15427 struct breakpoint *
15428 iterate_over_breakpoints (gdb::function_view<bool (breakpoint *)> callback)
15429 {
15430   struct breakpoint *b, *b_tmp;
15431
15432   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15433     {
15434       if (callback (b))
15435         return b;
15436     }
15437
15438   return NULL;
15439 }
15440
15441 /* Zero if any of the breakpoint's locations could be a location where
15442    functions have been inlined, nonzero otherwise.  */
15443
15444 static int
15445 is_non_inline_function (struct breakpoint *b)
15446 {
15447   /* The shared library event breakpoint is set on the address of a
15448      non-inline function.  */
15449   if (b->type == bp_shlib_event)
15450     return 1;
15451
15452   return 0;
15453 }
15454
15455 /* Nonzero if the specified PC cannot be a location where functions
15456    have been inlined.  */
15457
15458 int
15459 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15460                            const struct target_waitstatus *ws)
15461 {
15462   struct breakpoint *b;
15463   struct bp_location *bl;
15464
15465   ALL_BREAKPOINTS (b)
15466     {
15467       if (!is_non_inline_function (b))
15468         continue;
15469
15470       for (bl = b->loc; bl != NULL; bl = bl->next)
15471         {
15472           if (!bl->shlib_disabled
15473               && bpstat_check_location (bl, aspace, pc, ws))
15474             return 1;
15475         }
15476     }
15477
15478   return 0;
15479 }
15480
15481 /* Remove any references to OBJFILE which is going to be freed.  */
15482
15483 void
15484 breakpoint_free_objfile (struct objfile *objfile)
15485 {
15486   struct bp_location **locp, *loc;
15487
15488   ALL_BP_LOCATIONS (loc, locp)
15489     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15490       loc->symtab = NULL;
15491 }
15492
15493 void
15494 initialize_breakpoint_ops (void)
15495 {
15496   static int initialized = 0;
15497
15498   struct breakpoint_ops *ops;
15499
15500   if (initialized)
15501     return;
15502   initialized = 1;
15503
15504   /* The breakpoint_ops structure to be inherit by all kinds of
15505      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15506      internal and momentary breakpoints, etc.).  */
15507   ops = &bkpt_base_breakpoint_ops;
15508   *ops = base_breakpoint_ops;
15509   ops->re_set = bkpt_re_set;
15510   ops->insert_location = bkpt_insert_location;
15511   ops->remove_location = bkpt_remove_location;
15512   ops->breakpoint_hit = bkpt_breakpoint_hit;
15513   ops->create_sals_from_location = bkpt_create_sals_from_location;
15514   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15515   ops->decode_location = bkpt_decode_location;
15516
15517   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15518   ops = &bkpt_breakpoint_ops;
15519   *ops = bkpt_base_breakpoint_ops;
15520   ops->re_set = bkpt_re_set;
15521   ops->resources_needed = bkpt_resources_needed;
15522   ops->print_it = bkpt_print_it;
15523   ops->print_mention = bkpt_print_mention;
15524   ops->print_recreate = bkpt_print_recreate;
15525
15526   /* Ranged breakpoints.  */
15527   ops = &ranged_breakpoint_ops;
15528   *ops = bkpt_breakpoint_ops;
15529   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15530   ops->resources_needed = resources_needed_ranged_breakpoint;
15531   ops->print_it = print_it_ranged_breakpoint;
15532   ops->print_one = print_one_ranged_breakpoint;
15533   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15534   ops->print_mention = print_mention_ranged_breakpoint;
15535   ops->print_recreate = print_recreate_ranged_breakpoint;
15536
15537   /* Internal breakpoints.  */
15538   ops = &internal_breakpoint_ops;
15539   *ops = bkpt_base_breakpoint_ops;
15540   ops->re_set = internal_bkpt_re_set;
15541   ops->check_status = internal_bkpt_check_status;
15542   ops->print_it = internal_bkpt_print_it;
15543   ops->print_mention = internal_bkpt_print_mention;
15544
15545   /* Momentary breakpoints.  */
15546   ops = &momentary_breakpoint_ops;
15547   *ops = bkpt_base_breakpoint_ops;
15548   ops->re_set = momentary_bkpt_re_set;
15549   ops->check_status = momentary_bkpt_check_status;
15550   ops->print_it = momentary_bkpt_print_it;
15551   ops->print_mention = momentary_bkpt_print_mention;
15552
15553   /* Probe breakpoints.  */
15554   ops = &bkpt_probe_breakpoint_ops;
15555   *ops = bkpt_breakpoint_ops;
15556   ops->insert_location = bkpt_probe_insert_location;
15557   ops->remove_location = bkpt_probe_remove_location;
15558   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15559   ops->decode_location = bkpt_probe_decode_location;
15560
15561   /* Watchpoints.  */
15562   ops = &watchpoint_breakpoint_ops;
15563   *ops = base_breakpoint_ops;
15564   ops->re_set = re_set_watchpoint;
15565   ops->insert_location = insert_watchpoint;
15566   ops->remove_location = remove_watchpoint;
15567   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15568   ops->check_status = check_status_watchpoint;
15569   ops->resources_needed = resources_needed_watchpoint;
15570   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15571   ops->print_it = print_it_watchpoint;
15572   ops->print_mention = print_mention_watchpoint;
15573   ops->print_recreate = print_recreate_watchpoint;
15574   ops->explains_signal = explains_signal_watchpoint;
15575
15576   /* Masked watchpoints.  */
15577   ops = &masked_watchpoint_breakpoint_ops;
15578   *ops = watchpoint_breakpoint_ops;
15579   ops->insert_location = insert_masked_watchpoint;
15580   ops->remove_location = remove_masked_watchpoint;
15581   ops->resources_needed = resources_needed_masked_watchpoint;
15582   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15583   ops->print_it = print_it_masked_watchpoint;
15584   ops->print_one_detail = print_one_detail_masked_watchpoint;
15585   ops->print_mention = print_mention_masked_watchpoint;
15586   ops->print_recreate = print_recreate_masked_watchpoint;
15587
15588   /* Tracepoints.  */
15589   ops = &tracepoint_breakpoint_ops;
15590   *ops = base_breakpoint_ops;
15591   ops->re_set = tracepoint_re_set;
15592   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15593   ops->print_one_detail = tracepoint_print_one_detail;
15594   ops->print_mention = tracepoint_print_mention;
15595   ops->print_recreate = tracepoint_print_recreate;
15596   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15597   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15598   ops->decode_location = tracepoint_decode_location;
15599
15600   /* Probe tracepoints.  */
15601   ops = &tracepoint_probe_breakpoint_ops;
15602   *ops = tracepoint_breakpoint_ops;
15603   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15604   ops->decode_location = tracepoint_probe_decode_location;
15605
15606   /* Static tracepoints with marker (`-m').  */
15607   ops = &strace_marker_breakpoint_ops;
15608   *ops = tracepoint_breakpoint_ops;
15609   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15610   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15611   ops->decode_location = strace_marker_decode_location;
15612
15613   /* Fork catchpoints.  */
15614   ops = &catch_fork_breakpoint_ops;
15615   *ops = base_breakpoint_ops;
15616   ops->insert_location = insert_catch_fork;
15617   ops->remove_location = remove_catch_fork;
15618   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15619   ops->print_it = print_it_catch_fork;
15620   ops->print_one = print_one_catch_fork;
15621   ops->print_mention = print_mention_catch_fork;
15622   ops->print_recreate = print_recreate_catch_fork;
15623
15624   /* Vfork catchpoints.  */
15625   ops = &catch_vfork_breakpoint_ops;
15626   *ops = base_breakpoint_ops;
15627   ops->insert_location = insert_catch_vfork;
15628   ops->remove_location = remove_catch_vfork;
15629   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15630   ops->print_it = print_it_catch_vfork;
15631   ops->print_one = print_one_catch_vfork;
15632   ops->print_mention = print_mention_catch_vfork;
15633   ops->print_recreate = print_recreate_catch_vfork;
15634
15635   /* Exec catchpoints.  */
15636   ops = &catch_exec_breakpoint_ops;
15637   *ops = base_breakpoint_ops;
15638   ops->insert_location = insert_catch_exec;
15639   ops->remove_location = remove_catch_exec;
15640   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15641   ops->print_it = print_it_catch_exec;
15642   ops->print_one = print_one_catch_exec;
15643   ops->print_mention = print_mention_catch_exec;
15644   ops->print_recreate = print_recreate_catch_exec;
15645
15646   /* Solib-related catchpoints.  */
15647   ops = &catch_solib_breakpoint_ops;
15648   *ops = base_breakpoint_ops;
15649   ops->insert_location = insert_catch_solib;
15650   ops->remove_location = remove_catch_solib;
15651   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15652   ops->check_status = check_status_catch_solib;
15653   ops->print_it = print_it_catch_solib;
15654   ops->print_one = print_one_catch_solib;
15655   ops->print_mention = print_mention_catch_solib;
15656   ops->print_recreate = print_recreate_catch_solib;
15657
15658   ops = &dprintf_breakpoint_ops;
15659   *ops = bkpt_base_breakpoint_ops;
15660   ops->re_set = dprintf_re_set;
15661   ops->resources_needed = bkpt_resources_needed;
15662   ops->print_it = bkpt_print_it;
15663   ops->print_mention = bkpt_print_mention;
15664   ops->print_recreate = dprintf_print_recreate;
15665   ops->after_condition_true = dprintf_after_condition_true;
15666   ops->breakpoint_hit = dprintf_breakpoint_hit;
15667 }
15668
15669 /* Chain containing all defined "enable breakpoint" subcommands.  */
15670
15671 static struct cmd_list_element *enablebreaklist = NULL;
15672
15673 /* See breakpoint.h.  */
15674
15675 cmd_list_element *commands_cmd_element = nullptr;
15676
15677 void _initialize_breakpoint ();
15678 void
15679 _initialize_breakpoint ()
15680 {
15681   struct cmd_list_element *c;
15682
15683   initialize_breakpoint_ops ();
15684
15685   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib);
15686   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile);
15687   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change);
15688
15689   breakpoint_chain = 0;
15690   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15691      before a breakpoint is set.  */
15692   breakpoint_count = 0;
15693
15694   tracepoint_count = 0;
15695
15696   add_com ("ignore", class_breakpoint, ignore_command, _("\
15697 Set ignore-count of breakpoint number N to COUNT.\n\
15698 Usage is `ignore N COUNT'."));
15699
15700   commands_cmd_element = add_com ("commands", class_breakpoint,
15701                                   commands_command, _("\
15702 Set commands to be executed when the given breakpoints are hit.\n\
15703 Give a space-separated breakpoint list as argument after \"commands\".\n\
15704 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15705 (e.g. `5-7').\n\
15706 With no argument, the targeted breakpoint is the last one set.\n\
15707 The commands themselves follow starting on the next line.\n\
15708 Type a line containing \"end\" to indicate the end of them.\n\
15709 Give \"silent\" as the first line to make the breakpoint silent;\n\
15710 then no output is printed when it is hit, except what the commands print."));
15711
15712   const auto cc_opts = make_condition_command_options_def_group (nullptr);
15713   static std::string condition_command_help
15714     = gdb::option::build_help (_("\
15715 Specify breakpoint number N to break only if COND is true.\n\
15716 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
15717 is an expression to be evaluated whenever breakpoint N is reached.\n\
15718 \n\
15719 Options:\n\
15720 %OPTIONS%"), cc_opts);
15721
15722   c = add_com ("condition", class_breakpoint, condition_command,
15723                condition_command_help.c_str ());
15724   set_cmd_completer_handle_brkchars (c, condition_completer);
15725
15726   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15727 Set a temporary breakpoint.\n\
15728 Like \"break\" except the breakpoint is only temporary,\n\
15729 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15730 by using \"enable delete\" on the breakpoint number.\n\
15731 \n"
15732 BREAK_ARGS_HELP ("tbreak")));
15733   set_cmd_completer (c, location_completer);
15734
15735   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15736 Set a hardware assisted breakpoint.\n\
15737 Like \"break\" except the breakpoint requires hardware support,\n\
15738 some target hardware may not have this support.\n\
15739 \n"
15740 BREAK_ARGS_HELP ("hbreak")));
15741   set_cmd_completer (c, location_completer);
15742
15743   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15744 Set a temporary hardware assisted breakpoint.\n\
15745 Like \"hbreak\" except the breakpoint is only temporary,\n\
15746 so it will be deleted when hit.\n\
15747 \n"
15748 BREAK_ARGS_HELP ("thbreak")));
15749   set_cmd_completer (c, location_completer);
15750
15751   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15752 Enable all or some breakpoints.\n\
15753 Usage: enable [BREAKPOINTNUM]...\n\
15754 Give breakpoint numbers (separated by spaces) as arguments.\n\
15755 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15756 This is used to cancel the effect of the \"disable\" command.\n\
15757 With a subcommand you can enable temporarily."),
15758                   &enablelist, "enable ", 1, &cmdlist);
15759
15760   add_com_alias ("en", "enable", class_breakpoint, 1);
15761
15762   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15763 Enable all or some breakpoints.\n\
15764 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
15765 Give breakpoint numbers (separated by spaces) as arguments.\n\
15766 This is used to cancel the effect of the \"disable\" command.\n\
15767 May be abbreviated to simply \"enable\"."),
15768                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15769
15770   add_cmd ("once", no_class, enable_once_command, _("\
15771 Enable some breakpoints for one hit.\n\
15772 Usage: enable breakpoints once BREAKPOINTNUM...\n\
15773 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15774            &enablebreaklist);
15775
15776   add_cmd ("delete", no_class, enable_delete_command, _("\
15777 Enable some breakpoints and delete when hit.\n\
15778 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
15779 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15780            &enablebreaklist);
15781
15782   add_cmd ("count", no_class, enable_count_command, _("\
15783 Enable some breakpoints for COUNT hits.\n\
15784 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
15785 If a breakpoint is hit while enabled in this fashion,\n\
15786 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15787            &enablebreaklist);
15788
15789   add_cmd ("delete", no_class, enable_delete_command, _("\
15790 Enable some breakpoints and delete when hit.\n\
15791 Usage: enable delete BREAKPOINTNUM...\n\
15792 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15793            &enablelist);
15794
15795   add_cmd ("once", no_class, enable_once_command, _("\
15796 Enable some breakpoints for one hit.\n\
15797 Usage: enable once BREAKPOINTNUM...\n\
15798 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15799            &enablelist);
15800
15801   add_cmd ("count", no_class, enable_count_command, _("\
15802 Enable some breakpoints for COUNT hits.\n\
15803 Usage: enable count COUNT BREAKPOINTNUM...\n\
15804 If a breakpoint is hit while enabled in this fashion,\n\
15805 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15806            &enablelist);
15807
15808   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15809 Disable all or some breakpoints.\n\
15810 Usage: disable [BREAKPOINTNUM]...\n\
15811 Arguments are breakpoint numbers with spaces in between.\n\
15812 To disable all breakpoints, give no argument.\n\
15813 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15814                   &disablelist, "disable ", 1, &cmdlist);
15815   add_com_alias ("dis", "disable", class_breakpoint, 1);
15816   add_com_alias ("disa", "disable", class_breakpoint, 1);
15817
15818   add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
15819 Disable all or some breakpoints.\n\
15820 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
15821 Arguments are breakpoint numbers with spaces in between.\n\
15822 To disable all breakpoints, give no argument.\n\
15823 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15824 This command may be abbreviated \"disable\"."),
15825            &disablelist);
15826
15827   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15828 Delete all or some breakpoints.\n\
15829 Usage: delete [BREAKPOINTNUM]...\n\
15830 Arguments are breakpoint numbers with spaces in between.\n\
15831 To delete all breakpoints, give no argument.\n\
15832 \n\
15833 Also a prefix command for deletion of other GDB objects."),
15834                   &deletelist, "delete ", 1, &cmdlist);
15835   add_com_alias ("d", "delete", class_breakpoint, 1);
15836   add_com_alias ("del", "delete", class_breakpoint, 1);
15837
15838   add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
15839 Delete all or some breakpoints or auto-display expressions.\n\
15840 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
15841 Arguments are breakpoint numbers with spaces in between.\n\
15842 To delete all breakpoints, give no argument.\n\
15843 This command may be abbreviated \"delete\"."),
15844            &deletelist);
15845
15846   add_com ("clear", class_breakpoint, clear_command, _("\
15847 Clear breakpoint at specified location.\n\
15848 Argument may be a linespec, explicit, or address location as described below.\n\
15849 \n\
15850 With no argument, clears all breakpoints in the line that the selected frame\n\
15851 is executing in.\n"
15852 "\n" LOCATION_HELP_STRING "\n\n\
15853 See also the \"delete\" command which clears breakpoints by number."));
15854   add_com_alias ("cl", "clear", class_breakpoint, 1);
15855
15856   c = add_com ("break", class_breakpoint, break_command, _("\
15857 Set breakpoint at specified location.\n"
15858 BREAK_ARGS_HELP ("break")));
15859   set_cmd_completer (c, location_completer);
15860
15861   add_com_alias ("b", "break", class_run, 1);
15862   add_com_alias ("br", "break", class_run, 1);
15863   add_com_alias ("bre", "break", class_run, 1);
15864   add_com_alias ("brea", "break", class_run, 1);
15865
15866   if (dbx_commands)
15867     {
15868       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15869 Break in function/address or break at a line in the current file."),
15870                              &stoplist, "stop ", 1, &cmdlist);
15871       add_cmd ("in", class_breakpoint, stopin_command,
15872                _("Break in function or address."), &stoplist);
15873       add_cmd ("at", class_breakpoint, stopat_command,
15874                _("Break at a line in the current file."), &stoplist);
15875       add_com ("status", class_info, info_breakpoints_command, _("\
15876 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15877 The \"Type\" column indicates one of:\n\
15878 \tbreakpoint     - normal breakpoint\n\
15879 \twatchpoint     - watchpoint\n\
15880 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15881 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15882 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15883 address and file/line number respectively.\n\
15884 \n\
15885 Convenience variable \"$_\" and default examine address for \"x\"\n\
15886 are set to the address of the last breakpoint listed unless the command\n\
15887 is prefixed with \"server \".\n\n\
15888 Convenience variable \"$bpnum\" contains the number of the last\n\
15889 breakpoint set."));
15890     }
15891
15892   add_info ("breakpoints", info_breakpoints_command, _("\
15893 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15894 The \"Type\" column indicates one of:\n\
15895 \tbreakpoint     - normal breakpoint\n\
15896 \twatchpoint     - watchpoint\n\
15897 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15898 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15899 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15900 address and file/line number respectively.\n\
15901 \n\
15902 Convenience variable \"$_\" and default examine address for \"x\"\n\
15903 are set to the address of the last breakpoint listed unless the command\n\
15904 is prefixed with \"server \".\n\n\
15905 Convenience variable \"$bpnum\" contains the number of the last\n\
15906 breakpoint set."));
15907
15908   add_info_alias ("b", "breakpoints", 1);
15909
15910   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15911 Status of all breakpoints, or breakpoint number NUMBER.\n\
15912 The \"Type\" column indicates one of:\n\
15913 \tbreakpoint     - normal breakpoint\n\
15914 \twatchpoint     - watchpoint\n\
15915 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15916 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15917 \tuntil          - internal breakpoint used by the \"until\" command\n\
15918 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15919 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15920 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15921 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15922 address and file/line number respectively.\n\
15923 \n\
15924 Convenience variable \"$_\" and default examine address for \"x\"\n\
15925 are set to the address of the last breakpoint listed unless the command\n\
15926 is prefixed with \"server \".\n\n\
15927 Convenience variable \"$bpnum\" contains the number of the last\n\
15928 breakpoint set."),
15929            &maintenanceinfolist);
15930
15931   add_basic_prefix_cmd ("catch", class_breakpoint, _("\
15932 Set catchpoints to catch events."),
15933                         &catch_cmdlist, "catch ",
15934                         0/*allow-unknown*/, &cmdlist);
15935
15936   add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
15937 Set temporary catchpoints to catch events."),
15938                         &tcatch_cmdlist, "tcatch ",
15939                         0/*allow-unknown*/, &cmdlist);
15940
15941   add_catch_command ("fork", _("Catch calls to fork."),
15942                      catch_fork_command_1,
15943                      NULL,
15944                      (void *) (uintptr_t) catch_fork_permanent,
15945                      (void *) (uintptr_t) catch_fork_temporary);
15946   add_catch_command ("vfork", _("Catch calls to vfork."),
15947                      catch_fork_command_1,
15948                      NULL,
15949                      (void *) (uintptr_t) catch_vfork_permanent,
15950                      (void *) (uintptr_t) catch_vfork_temporary);
15951   add_catch_command ("exec", _("Catch calls to exec."),
15952                      catch_exec_command_1,
15953                      NULL,
15954                      CATCH_PERMANENT,
15955                      CATCH_TEMPORARY);
15956   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15957 Usage: catch load [REGEX]\n\
15958 If REGEX is given, only stop for libraries matching the regular expression."),
15959                      catch_load_command_1,
15960                      NULL,
15961                      CATCH_PERMANENT,
15962                      CATCH_TEMPORARY);
15963   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15964 Usage: catch unload [REGEX]\n\
15965 If REGEX is given, only stop for libraries matching the regular expression."),
15966                      catch_unload_command_1,
15967                      NULL,
15968                      CATCH_PERMANENT,
15969                      CATCH_TEMPORARY);
15970
15971   const auto opts = make_watch_options_def_group (nullptr);
15972
15973   static const std::string watch_help = gdb::option::build_help (_("\
15974 Set a watchpoint for EXPRESSION.\n\
15975 Usage: watch [-location] EXPRESSION\n\
15976 \n\
15977 Options:\n\
15978 %OPTIONS%\n\
15979 \n\
15980 A watchpoint stops execution of your program whenever the value of\n\
15981 an expression changes."), opts);
15982   c = add_com ("watch", class_breakpoint, watch_command,
15983                watch_help.c_str ());
15984   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15985
15986   static const std::string rwatch_help = gdb::option::build_help (_("\
15987 Set a read watchpoint for EXPRESSION.\n\
15988 Usage: rwatch [-location] EXPRESSION\n\
15989 \n\
15990 Options:\n\
15991 %OPTIONS%\n\
15992 \n\
15993 A read watchpoint stops execution of your program whenever the value of\n\
15994 an expression is read."), opts);
15995   c = add_com ("rwatch", class_breakpoint, rwatch_command,
15996                rwatch_help.c_str ());
15997   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15998
15999   static const std::string awatch_help = gdb::option::build_help (_("\
16000 Set an access watchpoint for EXPRESSION.\n\
16001 Usage: awatch [-location] EXPRESSION\n\
16002 \n\
16003 Options:\n\
16004 %OPTIONS%\n\
16005 \n\
16006 An access watchpoint stops execution of your program whenever the value\n\
16007 of an expression is either read or written."), opts);
16008   c = add_com ("awatch", class_breakpoint, awatch_command,
16009                awatch_help.c_str ());
16010   set_cmd_completer_handle_brkchars (c, watch_command_completer);
16011
16012   add_info ("watchpoints", info_watchpoints_command, _("\
16013 Status of specified watchpoints (all watchpoints if no argument)."));
16014
16015   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16016      respond to changes - contrary to the description.  */
16017   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16018                             &can_use_hw_watchpoints, _("\
16019 Set debugger's willingness to use watchpoint hardware."), _("\
16020 Show debugger's willingness to use watchpoint hardware."), _("\
16021 If zero, gdb will not use hardware for new watchpoints, even if\n\
16022 such is available.  (However, any hardware watchpoints that were\n\
16023 created before setting this to nonzero, will continue to use watchpoint\n\
16024 hardware.)"),
16025                             NULL,
16026                             show_can_use_hw_watchpoints,
16027                             &setlist, &showlist);
16028
16029   can_use_hw_watchpoints = 1;
16030
16031   /* Tracepoint manipulation commands.  */
16032
16033   c = add_com ("trace", class_breakpoint, trace_command, _("\
16034 Set a tracepoint at specified location.\n\
16035 \n"
16036 BREAK_ARGS_HELP ("trace") "\n\
16037 Do \"help tracepoints\" for info on other tracepoint commands."));
16038   set_cmd_completer (c, location_completer);
16039
16040   add_com_alias ("tp", "trace", class_breakpoint, 0);
16041   add_com_alias ("tr", "trace", class_breakpoint, 1);
16042   add_com_alias ("tra", "trace", class_breakpoint, 1);
16043   add_com_alias ("trac", "trace", class_breakpoint, 1);
16044
16045   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16046 Set a fast tracepoint at specified location.\n\
16047 \n"
16048 BREAK_ARGS_HELP ("ftrace") "\n\
16049 Do \"help tracepoints\" for info on other tracepoint commands."));
16050   set_cmd_completer (c, location_completer);
16051
16052   c = add_com ("strace", class_breakpoint, strace_command, _("\
16053 Set a static tracepoint at location or marker.\n\
16054 \n\
16055 strace [LOCATION] [if CONDITION]\n\
16056 LOCATION may be a linespec, explicit, or address location (described below) \n\
16057 or -m MARKER_ID.\n\n\
16058 If a marker id is specified, probe the marker with that name.  With\n\
16059 no LOCATION, uses current execution address of the selected stack frame.\n\
16060 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16061 This collects arbitrary user data passed in the probe point call to the\n\
16062 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16063 by printing the $_sdata variable like any other convenience variable.\n\
16064 \n\
16065 CONDITION is a boolean expression.\n\
16066 \n" LOCATION_HELP_STRING "\n\n\
16067 Multiple tracepoints at one place are permitted, and useful if their\n\
16068 conditions are different.\n\
16069 \n\
16070 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16071 Do \"help tracepoints\" for info on other tracepoint commands."));
16072   set_cmd_completer (c, location_completer);
16073
16074   add_info ("tracepoints", info_tracepoints_command, _("\
16075 Status of specified tracepoints (all tracepoints if no argument).\n\
16076 Convenience variable \"$tpnum\" contains the number of the\n\
16077 last tracepoint set."));
16078
16079   add_info_alias ("tp", "tracepoints", 1);
16080
16081   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16082 Delete specified tracepoints.\n\
16083 Arguments are tracepoint numbers, separated by spaces.\n\
16084 No argument means delete all tracepoints."),
16085            &deletelist);
16086   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16087
16088   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16089 Disable specified tracepoints.\n\
16090 Arguments are tracepoint numbers, separated by spaces.\n\
16091 No argument means disable all tracepoints."),
16092            &disablelist);
16093   deprecate_cmd (c, "disable");
16094
16095   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16096 Enable specified tracepoints.\n\
16097 Arguments are tracepoint numbers, separated by spaces.\n\
16098 No argument means enable all tracepoints."),
16099            &enablelist);
16100   deprecate_cmd (c, "enable");
16101
16102   add_com ("passcount", class_trace, trace_pass_command, _("\
16103 Set the passcount for a tracepoint.\n\
16104 The trace will end when the tracepoint has been passed 'count' times.\n\
16105 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16106 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16107
16108   add_basic_prefix_cmd ("save", class_breakpoint,
16109                         _("Save breakpoint definitions as a script."),
16110                         &save_cmdlist, "save ",
16111                         0/*allow-unknown*/, &cmdlist);
16112
16113   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16114 Save current breakpoint definitions as a script.\n\
16115 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16116 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16117 session to restore them."),
16118                &save_cmdlist);
16119   set_cmd_completer (c, filename_completer);
16120
16121   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16122 Save current tracepoint definitions as a script.\n\
16123 Use the 'source' command in another debug session to restore them."),
16124                &save_cmdlist);
16125   set_cmd_completer (c, filename_completer);
16126
16127   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16128   deprecate_cmd (c, "save tracepoints");
16129
16130   add_basic_prefix_cmd ("breakpoint", class_maintenance, _("\
16131 Breakpoint specific settings.\n\
16132 Configure various breakpoint-specific variables such as\n\
16133 pending breakpoint behavior."),
16134                         &breakpoint_set_cmdlist, "set breakpoint ",
16135                         0/*allow-unknown*/, &setlist);
16136   add_show_prefix_cmd ("breakpoint", class_maintenance, _("\
16137 Breakpoint specific settings.\n\
16138 Configure various breakpoint-specific variables such as\n\
16139 pending breakpoint behavior."),
16140                        &breakpoint_show_cmdlist, "show breakpoint ",
16141                        0/*allow-unknown*/, &showlist);
16142
16143   add_setshow_auto_boolean_cmd ("pending", no_class,
16144                                 &pending_break_support, _("\
16145 Set debugger's behavior regarding pending breakpoints."), _("\
16146 Show debugger's behavior regarding pending breakpoints."), _("\
16147 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16148 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16149 an error.  If auto, an unrecognized breakpoint location results in a\n\
16150 user-query to see if a pending breakpoint should be created."),
16151                                 NULL,
16152                                 show_pending_break_support,
16153                                 &breakpoint_set_cmdlist,
16154                                 &breakpoint_show_cmdlist);
16155
16156   pending_break_support = AUTO_BOOLEAN_AUTO;
16157
16158   add_setshow_boolean_cmd ("auto-hw", no_class,
16159                            &automatic_hardware_breakpoints, _("\
16160 Set automatic usage of hardware breakpoints."), _("\
16161 Show automatic usage of hardware breakpoints."), _("\
16162 If set, the debugger will automatically use hardware breakpoints for\n\
16163 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16164 a warning will be emitted for such breakpoints."),
16165                            NULL,
16166                            show_automatic_hardware_breakpoints,
16167                            &breakpoint_set_cmdlist,
16168                            &breakpoint_show_cmdlist);
16169
16170   add_setshow_boolean_cmd ("always-inserted", class_support,
16171                            &always_inserted_mode, _("\
16172 Set mode for inserting breakpoints."), _("\
16173 Show mode for inserting breakpoints."), _("\
16174 When this mode is on, breakpoints are inserted immediately as soon as\n\
16175 they're created, kept inserted even when execution stops, and removed\n\
16176 only when the user deletes them.  When this mode is off (the default),\n\
16177 breakpoints are inserted only when execution continues, and removed\n\
16178 when execution stops."),
16179                                 NULL,
16180                                 &show_always_inserted_mode,
16181                                 &breakpoint_set_cmdlist,
16182                                 &breakpoint_show_cmdlist);
16183
16184   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16185                         condition_evaluation_enums,
16186                         &condition_evaluation_mode_1, _("\
16187 Set mode of breakpoint condition evaluation."), _("\
16188 Show mode of breakpoint condition evaluation."), _("\
16189 When this is set to \"host\", breakpoint conditions will be\n\
16190 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16191 breakpoint conditions will be downloaded to the target (if the target\n\
16192 supports such feature) and conditions will be evaluated on the target's side.\n\
16193 If this is set to \"auto\" (default), this will be automatically set to\n\
16194 \"target\" if it supports condition evaluation, otherwise it will\n\
16195 be set to \"host\"."),
16196                            &set_condition_evaluation_mode,
16197                            &show_condition_evaluation_mode,
16198                            &breakpoint_set_cmdlist,
16199                            &breakpoint_show_cmdlist);
16200
16201   add_com ("break-range", class_breakpoint, break_range_command, _("\
16202 Set a breakpoint for an address range.\n\
16203 break-range START-LOCATION, END-LOCATION\n\
16204 where START-LOCATION and END-LOCATION can be one of the following:\n\
16205   LINENUM, for that line in the current file,\n\
16206   FILE:LINENUM, for that line in that file,\n\
16207   +OFFSET, for that number of lines after the current line\n\
16208            or the start of the range\n\
16209   FUNCTION, for the first line in that function,\n\
16210   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16211   *ADDRESS, for the instruction at that address.\n\
16212 \n\
16213 The breakpoint will stop execution of the inferior whenever it executes\n\
16214 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16215 range (including START-LOCATION and END-LOCATION)."));
16216
16217   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16218 Set a dynamic printf at specified location.\n\
16219 dprintf location,format string,arg1,arg2,...\n\
16220 location may be a linespec, explicit, or address location.\n"
16221 "\n" LOCATION_HELP_STRING));
16222   set_cmd_completer (c, location_completer);
16223
16224   add_setshow_enum_cmd ("dprintf-style", class_support,
16225                         dprintf_style_enums, &dprintf_style, _("\
16226 Set the style of usage for dynamic printf."), _("\
16227 Show the style of usage for dynamic printf."), _("\
16228 This setting chooses how GDB will do a dynamic printf.\n\
16229 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16230 console, as with the \"printf\" command.\n\
16231 If the value is \"call\", the print is done by calling a function in your\n\
16232 program; by default printf(), but you can choose a different function or\n\
16233 output stream by setting dprintf-function and dprintf-channel."),
16234                         update_dprintf_commands, NULL,
16235                         &setlist, &showlist);
16236
16237   dprintf_function = xstrdup ("printf");
16238   add_setshow_string_cmd ("dprintf-function", class_support,
16239                           &dprintf_function, _("\
16240 Set the function to use for dynamic printf."), _("\
16241 Show the function to use for dynamic printf."), NULL,
16242                           update_dprintf_commands, NULL,
16243                           &setlist, &showlist);
16244
16245   dprintf_channel = xstrdup ("");
16246   add_setshow_string_cmd ("dprintf-channel", class_support,
16247                           &dprintf_channel, _("\
16248 Set the channel to use for dynamic printf."), _("\
16249 Show the channel to use for dynamic printf."), NULL,
16250                           update_dprintf_commands, NULL,
16251                           &setlist, &showlist);
16252
16253   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16254                            &disconnected_dprintf, _("\
16255 Set whether dprintf continues after GDB disconnects."), _("\
16256 Show whether dprintf continues after GDB disconnects."), _("\
16257 Use this to let dprintf commands continue to hit and produce output\n\
16258 even if GDB disconnects or detaches from the target."),
16259                            NULL,
16260                            NULL,
16261                            &setlist, &showlist);
16262
16263   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16264 Target agent only formatted printing, like the C \"printf\" function.\n\
16265 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
16266 This supports most C printf format specifications, like %s, %d, etc.\n\
16267 This is useful for formatted output in user-defined commands."));
16268
16269   automatic_hardware_breakpoints = true;
16270
16271   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed);
16272   gdb::observers::thread_exit.attach (remove_threaded_breakpoints);
16273 }
This page took 0.932878 seconds and 4 git commands to generate.