]> Git Repo - binutils.git/blob - gdb/breakpoint.c
Unify gdb printf functions
[binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2022 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 "gdbsupport/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 #include "cli/cli-decode.h"
71
72 /* readline include files */
73 #include "readline/tilde.h"
74
75 /* readline defines this.  */
76 #undef savestring
77
78 #include "mi/mi-common.h"
79 #include "extension.h"
80 #include <algorithm>
81 #include "progspace-and-thread.h"
82 #include "gdbsupport/array-view.h"
83 #include "gdbsupport/gdb_optional.h"
84
85 /* Prototypes for local functions.  */
86
87 static void map_breakpoint_numbers (const char *,
88                                     gdb::function_view<void (breakpoint *)>);
89
90 static void breakpoint_re_set_default (struct breakpoint *);
91
92 static void
93   create_sals_from_location_default (struct event_location *location,
94                                      struct linespec_result *canonical,
95                                      enum bptype type_wanted);
96
97 static void create_breakpoints_sal_default (struct gdbarch *,
98                                             struct linespec_result *,
99                                             gdb::unique_xmalloc_ptr<char>,
100                                             gdb::unique_xmalloc_ptr<char>,
101                                             enum bptype,
102                                             enum bpdisp, int, int,
103                                             int,
104                                             const struct breakpoint_ops *,
105                                             int, int, int, unsigned);
106
107 static std::vector<symtab_and_line> decode_location_default
108   (struct breakpoint *b, struct event_location *location,
109    struct program_space *search_pspace);
110
111 static int can_use_hardware_watchpoint
112     (const std::vector<value_ref_ptr> &vals);
113
114 static void mention (struct breakpoint *);
115
116 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
117                                                                enum bptype,
118                                                                const struct breakpoint_ops *);
119 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
120                                                        const struct symtab_and_line *);
121
122 /* This function is used in gdbtk sources and thus can not be made
123    static.  */
124 static struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
125                                               struct symtab_and_line,
126                                               enum bptype,
127                                               const struct breakpoint_ops *);
128
129 static struct breakpoint *
130   momentary_breakpoint_from_master (struct breakpoint *orig,
131                                     enum bptype type,
132                                     const struct breakpoint_ops *ops,
133                                     int loc_enabled);
134
135 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
136
137 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
138                                             CORE_ADDR bpaddr,
139                                             enum bptype bptype);
140
141 static void describe_other_breakpoints (struct gdbarch *,
142                                         struct program_space *, CORE_ADDR,
143                                         struct obj_section *, int);
144
145 static int watchpoint_locations_match (struct bp_location *loc1,
146                                        struct bp_location *loc2);
147
148 static int breakpoint_locations_match (struct bp_location *loc1,
149                                        struct bp_location *loc2,
150                                        bool sw_hw_bps_match = false);
151
152 static int breakpoint_location_address_match (struct bp_location *bl,
153                                               const struct address_space *aspace,
154                                               CORE_ADDR addr);
155
156 static int breakpoint_location_address_range_overlap (struct bp_location *,
157                                                       const address_space *,
158                                                       CORE_ADDR, int);
159
160 static int remove_breakpoint (struct bp_location *);
161 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
162
163 static enum print_stop_action print_bp_stop_message (bpstat *bs);
164
165 static int hw_breakpoint_used_count (void);
166
167 static int hw_watchpoint_use_count (struct breakpoint *);
168
169 static int hw_watchpoint_used_count_others (struct breakpoint *except,
170                                             enum bptype type,
171                                             int *other_type_used);
172
173 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
174                                     int count);
175
176 static void decref_bp_location (struct bp_location **loc);
177
178 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
179
180 /* update_global_location_list's modes of operation wrt to whether to
181    insert locations now.  */
182 enum ugll_insert_mode
183 {
184   /* Don't insert any breakpoint locations into the inferior, only
185      remove already-inserted locations that no longer should be
186      inserted.  Functions that delete a breakpoint or breakpoints
187      should specify this mode, so that deleting a breakpoint doesn't
188      have the side effect of inserting the locations of other
189      breakpoints that are marked not-inserted, but should_be_inserted
190      returns true on them.
191
192      This behavior is useful is situations close to tear-down -- e.g.,
193      after an exec, while the target still has execution, but
194      breakpoint shadows of the previous executable image should *NOT*
195      be restored to the new image; or before detaching, where the
196      target still has execution and wants to delete breakpoints from
197      GDB's lists, and all breakpoints had already been removed from
198      the inferior.  */
199   UGLL_DONT_INSERT,
200
201   /* May insert breakpoints iff breakpoints_should_be_inserted_now
202      claims breakpoints should be inserted now.  */
203   UGLL_MAY_INSERT,
204
205   /* Insert locations now, irrespective of
206      breakpoints_should_be_inserted_now.  E.g., say all threads are
207      stopped right now, and the user did "continue".  We need to
208      insert breakpoints _before_ resuming the target, but
209      UGLL_MAY_INSERT wouldn't insert them, because
210      breakpoints_should_be_inserted_now returns false at that point,
211      as no thread is running yet.  */
212   UGLL_INSERT
213 };
214
215 static void update_global_location_list (enum ugll_insert_mode);
216
217 static void update_global_location_list_nothrow (enum ugll_insert_mode);
218
219 static void insert_breakpoint_locations (void);
220
221 static void trace_pass_command (const char *, int);
222
223 static void set_tracepoint_count (int num);
224
225 static bool is_masked_watchpoint (const struct breakpoint *b);
226
227 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
228    otherwise.  */
229
230 static int strace_marker_p (struct breakpoint *b);
231
232 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
233    that are implemented on top of software or hardware breakpoints
234    (user breakpoints, internal and momentary breakpoints, etc.).  */
235 static struct breakpoint_ops bkpt_base_breakpoint_ops;
236
237 /* Internal breakpoints class type.  */
238 static struct breakpoint_ops internal_breakpoint_ops;
239
240 /* Momentary breakpoints class type.  */
241 static struct breakpoint_ops momentary_breakpoint_ops;
242
243 /* The breakpoint_ops structure to be used in regular user created
244    breakpoints.  */
245 struct breakpoint_ops bkpt_breakpoint_ops;
246
247 /* Breakpoints set on probes.  */
248 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
249
250 /* Tracepoints set on probes.  */
251 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
252
253 /* Dynamic printf class type.  */
254 struct breakpoint_ops dprintf_breakpoint_ops;
255
256 /* The style in which to perform a dynamic printf.  This is a user
257    option because different output options have different tradeoffs;
258    if GDB does the printing, there is better error handling if there
259    is a problem with any of the arguments, but using an inferior
260    function lets you have special-purpose printers and sending of
261    output to the same place as compiled-in print functions.  */
262
263 static const char dprintf_style_gdb[] = "gdb";
264 static const char dprintf_style_call[] = "call";
265 static const char dprintf_style_agent[] = "agent";
266 static const char *const dprintf_style_enums[] = {
267   dprintf_style_gdb,
268   dprintf_style_call,
269   dprintf_style_agent,
270   NULL
271 };
272 static const char *dprintf_style = dprintf_style_gdb;
273
274 /* The function to use for dynamic printf if the preferred style is to
275    call into the inferior.  The value is simply a string that is
276    copied into the command, so it can be anything that GDB can
277    evaluate to a callable address, not necessarily a function name.  */
278
279 static std::string dprintf_function = "printf";
280
281 /* The channel to use for dynamic printf if the preferred style is to
282    call into the inferior; if a nonempty string, it will be passed to
283    the call as the first argument, with the format string as the
284    second.  As with the dprintf function, this can be anything that
285    GDB knows how to evaluate, so in addition to common choices like
286    "stderr", this could be an app-specific expression like
287    "mystreams[curlogger]".  */
288
289 static std::string dprintf_channel;
290
291 /* True if dprintf commands should continue to operate even if GDB
292    has disconnected.  */
293 static bool disconnected_dprintf = true;
294
295 struct command_line *
296 breakpoint_commands (struct breakpoint *b)
297 {
298   return b->commands ? b->commands.get () : NULL;
299 }
300
301 /* Flag indicating that a command has proceeded the inferior past the
302    current breakpoint.  */
303
304 static bool breakpoint_proceeded;
305
306 const char *
307 bpdisp_text (enum bpdisp disp)
308 {
309   /* NOTE: the following values are a part of MI protocol and
310      represent values of 'disp' field returned when inferior stops at
311      a breakpoint.  */
312   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
313
314   return bpdisps[(int) disp];
315 }
316
317 /* Prototypes for exported functions.  */
318 /* If FALSE, gdb will not use hardware support for watchpoints, even
319    if such is available.  */
320 static int can_use_hw_watchpoints;
321
322 static void
323 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
324                              struct cmd_list_element *c,
325                              const char *value)
326 {
327   gdb_printf (file,
328               _("Debugger's willingness to use "
329                 "watchpoint hardware is %s.\n"),
330               value);
331 }
332
333 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
334    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
335    for unrecognized breakpoint locations.
336    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
337 static enum auto_boolean pending_break_support;
338 static void
339 show_pending_break_support (struct ui_file *file, int from_tty,
340                             struct cmd_list_element *c,
341                             const char *value)
342 {
343   gdb_printf (file,
344               _("Debugger's behavior regarding "
345                 "pending breakpoints is %s.\n"),
346               value);
347 }
348
349 /* If true, gdb will automatically use hardware breakpoints for breakpoints
350    set with "break" but falling in read-only memory.
351    If false, gdb will warn about such breakpoints, but won't automatically
352    use hardware breakpoints.  */
353 static bool automatic_hardware_breakpoints;
354 static void
355 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
356                                      struct cmd_list_element *c,
357                                      const char *value)
358 {
359   gdb_printf (file,
360               _("Automatic usage of hardware breakpoints is %s.\n"),
361               value);
362 }
363
364 /* If on, GDB keeps breakpoints inserted even if the inferior is
365    stopped, and immediately inserts any new breakpoints as soon as
366    they're created.  If off (default), GDB keeps breakpoints off of
367    the target as long as possible.  That is, it delays inserting
368    breakpoints until the next resume, and removes them again when the
369    target fully stops.  This is a bit safer in case GDB crashes while
370    processing user input.  */
371 static bool always_inserted_mode = false;
372
373 static void
374 show_always_inserted_mode (struct ui_file *file, int from_tty,
375                      struct cmd_list_element *c, const char *value)
376 {
377   gdb_printf (file, _("Always inserted breakpoint mode is %s.\n"),
378               value);
379 }
380
381 /* See breakpoint.h.  */
382
383 int
384 breakpoints_should_be_inserted_now (void)
385 {
386   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
387     {
388       /* If breakpoints are global, they should be inserted even if no
389          thread under gdb's control is running, or even if there are
390          no threads under GDB's control yet.  */
391       return 1;
392     }
393   else
394     {
395       if (always_inserted_mode)
396         {
397           /* The user wants breakpoints inserted even if all threads
398              are stopped.  */
399           return 1;
400         }
401
402       for (inferior *inf : all_inferiors ())
403         if (inf->has_execution ()
404             && threads_are_executing (inf->process_target ()))
405           return 1;
406
407       /* Don't remove breakpoints yet if, even though all threads are
408          stopped, we still have events to process.  */
409       for (thread_info *tp : all_non_exited_threads ())
410         if (tp->resumed () && tp->has_pending_waitstatus ())
411           return 1;
412     }
413   return 0;
414 }
415
416 static const char condition_evaluation_both[] = "host or target";
417
418 /* Modes for breakpoint condition evaluation.  */
419 static const char condition_evaluation_auto[] = "auto";
420 static const char condition_evaluation_host[] = "host";
421 static const char condition_evaluation_target[] = "target";
422 static const char *const condition_evaluation_enums[] = {
423   condition_evaluation_auto,
424   condition_evaluation_host,
425   condition_evaluation_target,
426   NULL
427 };
428
429 /* Global that holds the current mode for breakpoint condition evaluation.  */
430 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
431
432 /* Global that we use to display information to the user (gets its value from
433    condition_evaluation_mode_1.  */
434 static const char *condition_evaluation_mode = condition_evaluation_auto;
435
436 /* Translate a condition evaluation mode MODE into either "host"
437    or "target".  This is used mostly to translate from "auto" to the
438    real setting that is being used.  It returns the translated
439    evaluation mode.  */
440
441 static const char *
442 translate_condition_evaluation_mode (const char *mode)
443 {
444   if (mode == condition_evaluation_auto)
445     {
446       if (target_supports_evaluation_of_breakpoint_conditions ())
447         return condition_evaluation_target;
448       else
449         return condition_evaluation_host;
450     }
451   else
452     return mode;
453 }
454
455 /* Discovers what condition_evaluation_auto translates to.  */
456
457 static const char *
458 breakpoint_condition_evaluation_mode (void)
459 {
460   return translate_condition_evaluation_mode (condition_evaluation_mode);
461 }
462
463 /* Return true if GDB should evaluate breakpoint conditions or false
464    otherwise.  */
465
466 static int
467 gdb_evaluates_breakpoint_condition_p (void)
468 {
469   const char *mode = breakpoint_condition_evaluation_mode ();
470
471   return (mode == condition_evaluation_host);
472 }
473
474 /* Are we executing breakpoint commands?  */
475 static int executing_breakpoint_commands;
476
477 /* Are overlay event breakpoints enabled? */
478 static int overlay_events_enabled;
479
480 /* See description in breakpoint.h. */
481 bool target_exact_watchpoints = false;
482
483 /* Walk the following statement or block through all breakpoints.
484    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
485    current breakpoint.  */
486
487 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
488         for (B = breakpoint_chain;      \
489              B ? (TMP=B->next, 1): 0;   \
490              B = TMP)
491
492 /* Chains of all breakpoints defined.  */
493
494 static struct breakpoint *breakpoint_chain;
495
496 /* See breakpoint.h.  */
497
498 breakpoint_range
499 all_breakpoints ()
500 {
501   return breakpoint_range (breakpoint_chain);
502 }
503
504 /* See breakpoint.h.  */
505
506 breakpoint_safe_range
507 all_breakpoints_safe ()
508 {
509   return breakpoint_safe_range (all_breakpoints ());
510 }
511
512 /* See breakpoint.h.  */
513
514 tracepoint_range
515 all_tracepoints ()
516 {
517   return tracepoint_range (breakpoint_chain);
518 }
519
520 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS.  */
521
522 static std::vector<bp_location *> bp_locations;
523
524 /* See breakpoint.h.  */
525
526 const std::vector<bp_location *> &
527 all_bp_locations ()
528 {
529   return bp_locations;
530 }
531
532 /* Range to iterate over breakpoint locations at a given address.  */
533
534 struct bp_locations_at_addr_range
535 {
536   using iterator = std::vector<bp_location *>::iterator;
537
538   bp_locations_at_addr_range (CORE_ADDR addr)
539   {
540     struct compare
541     {
542       bool operator() (const bp_location *loc, CORE_ADDR addr_) const
543       { return loc->address < addr_; }
544
545       bool operator() (CORE_ADDR addr_, const bp_location *loc) const
546       { return addr_ < loc->address; }
547     };
548
549     auto it_pair = std::equal_range (bp_locations.begin (), bp_locations.end (),
550                                      addr, compare ());
551
552     m_begin = it_pair.first;
553     m_end = it_pair.second;
554   }
555
556   iterator begin () const
557   { return m_begin; }
558
559   iterator end () const
560   { return m_end; }
561
562 private:
563   iterator m_begin;
564   iterator m_end;
565 };
566
567 /* Return a range to iterate over all breakpoint locations exactly at address
568    ADDR.
569
570    If it's needed to iterate multiple times on the same range, it's possible
571    to save the range in a local variable and use it multiple times:
572
573      auto range = all_bp_locations_at_addr (addr);
574
575      for (bp_location *loc : range)
576        // use loc
577
578      for (bp_location *loc : range)
579        // use loc
580
581    This saves a bit of time, as it avoids re-doing the binary searches to find
582    the range's boundaries.  Just remember not to change the bp_locations vector
583    in the mean time, as it could make the range's iterators stale.  */
584
585 static bp_locations_at_addr_range
586 all_bp_locations_at_addr (CORE_ADDR addr)
587 {
588   return bp_locations_at_addr_range (addr);
589 }
590
591 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
592    ADDRESS for the current elements of BP_LOCATIONS which get a valid
593    result from bp_location_has_shadow.  You can use it for roughly
594    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
595    an address you need to read.  */
596
597 static CORE_ADDR bp_locations_placed_address_before_address_max;
598
599 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
600    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
601    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
602    You can use it for roughly limiting the subrange of BP_LOCATIONS to
603    scan for shadow bytes for an address you need to read.  */
604
605 static CORE_ADDR bp_locations_shadow_len_after_address_max;
606
607 /* The locations that no longer correspond to any breakpoint, unlinked
608    from the bp_locations array, but for which a hit may still be
609    reported by a target.  */
610 static std::vector<bp_location *> moribund_locations;
611
612 /* Number of last breakpoint made.  */
613
614 static int breakpoint_count;
615
616 /* The value of `breakpoint_count' before the last command that
617    created breakpoints.  If the last (break-like) command created more
618    than one breakpoint, then the difference between BREAKPOINT_COUNT
619    and PREV_BREAKPOINT_COUNT is more than one.  */
620 static int prev_breakpoint_count;
621
622 /* Number of last tracepoint made.  */
623
624 static int tracepoint_count;
625
626 static struct cmd_list_element *breakpoint_set_cmdlist;
627 static struct cmd_list_element *breakpoint_show_cmdlist;
628 struct cmd_list_element *save_cmdlist;
629
630 /* Return whether a breakpoint is an active enabled breakpoint.  */
631 static int
632 breakpoint_enabled (struct breakpoint *b)
633 {
634   return (b->enable_state == bp_enabled);
635 }
636
637 /* Set breakpoint count to NUM.  */
638
639 static void
640 set_breakpoint_count (int num)
641 {
642   prev_breakpoint_count = breakpoint_count;
643   breakpoint_count = num;
644   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
645 }
646
647 /* Used by `start_rbreak_breakpoints' below, to record the current
648    breakpoint count before "rbreak" creates any breakpoint.  */
649 static int rbreak_start_breakpoint_count;
650
651 /* Called at the start an "rbreak" command to record the first
652    breakpoint made.  */
653
654 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
655 {
656   rbreak_start_breakpoint_count = breakpoint_count;
657 }
658
659 /* Called at the end of an "rbreak" command to record the last
660    breakpoint made.  */
661
662 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
663 {
664   prev_breakpoint_count = rbreak_start_breakpoint_count;
665 }
666
667 /* Used in run_command to zero the hit count when a new run starts.  */
668
669 void
670 clear_breakpoint_hit_counts (void)
671 {
672   for (breakpoint *b : all_breakpoints ())
673     b->hit_count = 0;
674 }
675
676 \f
677 /* Return the breakpoint with the specified number, or NULL
678    if the number does not refer to an existing breakpoint.  */
679
680 struct breakpoint *
681 get_breakpoint (int num)
682 {
683   for (breakpoint *b : all_breakpoints ())
684     if (b->number == num)
685       return b;
686   
687   return nullptr;
688 }
689
690 \f
691
692 /* Mark locations as "conditions have changed" in case the target supports
693    evaluating conditions on its side.  */
694
695 static void
696 mark_breakpoint_modified (struct breakpoint *b)
697 {
698   /* This is only meaningful if the target is
699      evaluating conditions and if the user has
700      opted for condition evaluation on the target's
701      side.  */
702   if (gdb_evaluates_breakpoint_condition_p ()
703       || !target_supports_evaluation_of_breakpoint_conditions ())
704     return;
705
706   if (!is_breakpoint (b))
707     return;
708
709   for (bp_location *loc : b->locations ())
710     loc->condition_changed = condition_modified;
711 }
712
713 /* Mark location as "conditions have changed" in case the target supports
714    evaluating conditions on its side.  */
715
716 static void
717 mark_breakpoint_location_modified (struct bp_location *loc)
718 {
719   /* This is only meaningful if the target is
720      evaluating conditions and if the user has
721      opted for condition evaluation on the target's
722      side.  */
723   if (gdb_evaluates_breakpoint_condition_p ()
724       || !target_supports_evaluation_of_breakpoint_conditions ())
725
726     return;
727
728   if (!is_breakpoint (loc->owner))
729     return;
730
731   loc->condition_changed = condition_modified;
732 }
733
734 /* Sets the condition-evaluation mode using the static global
735    condition_evaluation_mode.  */
736
737 static void
738 set_condition_evaluation_mode (const char *args, int from_tty,
739                                struct cmd_list_element *c)
740 {
741   const char *old_mode, *new_mode;
742
743   if ((condition_evaluation_mode_1 == condition_evaluation_target)
744       && !target_supports_evaluation_of_breakpoint_conditions ())
745     {
746       condition_evaluation_mode_1 = condition_evaluation_mode;
747       warning (_("Target does not support breakpoint condition evaluation.\n"
748                  "Using host evaluation mode instead."));
749       return;
750     }
751
752   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
753   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
754
755   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
756      settings was "auto".  */
757   condition_evaluation_mode = condition_evaluation_mode_1;
758
759   /* Only update the mode if the user picked a different one.  */
760   if (new_mode != old_mode)
761     {
762       /* If the user switched to a different evaluation mode, we
763          need to synch the changes with the target as follows:
764
765          "host" -> "target": Send all (valid) conditions to the target.
766          "target" -> "host": Remove all the conditions from the target.
767       */
768
769       if (new_mode == condition_evaluation_target)
770         {
771           /* Mark everything modified and synch conditions with the
772              target.  */
773           for (bp_location *loc : all_bp_locations ())
774             mark_breakpoint_location_modified (loc);
775         }
776       else
777         {
778           /* Manually mark non-duplicate locations to synch conditions
779              with the target.  We do this to remove all the conditions the
780              target knows about.  */
781           for (bp_location *loc : all_bp_locations ())
782             if (is_breakpoint (loc->owner) && loc->inserted)
783               loc->needs_update = 1;
784         }
785
786       /* Do the update.  */
787       update_global_location_list (UGLL_MAY_INSERT);
788     }
789
790   return;
791 }
792
793 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
794    what "auto" is translating to.  */
795
796 static void
797 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
798                                 struct cmd_list_element *c, const char *value)
799 {
800   if (condition_evaluation_mode == condition_evaluation_auto)
801     gdb_printf (file,
802                 _("Breakpoint condition evaluation "
803                   "mode is %s (currently %s).\n"),
804                 value,
805                 breakpoint_condition_evaluation_mode ());
806   else
807     gdb_printf (file, _("Breakpoint condition evaluation mode is %s.\n"),
808                 value);
809 }
810
811 /* Parse COND_STRING in the context of LOC and set as the condition
812    expression of LOC.  BP_NUM is the number of LOC's owner, LOC_NUM is
813    the number of LOC within its owner.  In case of parsing error, mark
814    LOC as DISABLED_BY_COND.  In case of success, unset DISABLED_BY_COND.  */
815
816 static void
817 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
818                                    int bp_num, int loc_num)
819 {
820   bool has_junk = false;
821   try
822     {
823       expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
824                                            block_for_pc (loc->address), 0);
825       if (*cond_string != 0)
826         has_junk = true;
827       else
828         {
829           loc->cond = std::move (new_exp);
830           if (loc->disabled_by_cond && loc->enabled)
831             gdb_printf (_("Breakpoint %d's condition is now valid at "
832                           "location %d, enabling.\n"),
833                         bp_num, loc_num);
834
835           loc->disabled_by_cond = false;
836         }
837     }
838   catch (const gdb_exception_error &e)
839     {
840       if (loc->enabled)
841         {
842           /* Warn if a user-enabled location is now becoming disabled-by-cond.
843              BP_NUM is 0 if the breakpoint is being defined for the first
844              time using the "break ... if ..." command, and non-zero if
845              already defined.  */
846           if (bp_num != 0)
847             warning (_("failed to validate condition at location %d.%d, "
848                        "disabling:\n  %s"), bp_num, loc_num, e.what ());
849           else
850             warning (_("failed to validate condition at location %d, "
851                        "disabling:\n  %s"), loc_num, e.what ());
852         }
853
854       loc->disabled_by_cond = true;
855     }
856
857   if (has_junk)
858     error (_("Garbage '%s' follows condition"), cond_string);
859 }
860
861 void
862 set_breakpoint_condition (struct breakpoint *b, const char *exp,
863                           int from_tty, bool force)
864 {
865   if (*exp == 0)
866     {
867       b->cond_string.reset ();
868
869       if (is_watchpoint (b))
870         static_cast<watchpoint *> (b)->cond_exp.reset ();
871       else
872         {
873           int loc_num = 1;
874           for (bp_location *loc : b->locations ())
875             {
876               loc->cond.reset ();
877               if (loc->disabled_by_cond && loc->enabled)
878                 gdb_printf (_("Breakpoint %d's condition is now valid at "
879                               "location %d, enabling.\n"),
880                             b->number, loc_num);
881               loc->disabled_by_cond = false;
882               loc_num++;
883
884               /* No need to free the condition agent expression
885                  bytecode (if we have one).  We will handle this
886                  when we go through update_global_location_list.  */
887             }
888         }
889
890       if (from_tty)
891         gdb_printf (_("Breakpoint %d now unconditional.\n"), b->number);
892     }
893   else
894     {
895       if (is_watchpoint (b))
896         {
897           innermost_block_tracker tracker;
898           const char *arg = exp;
899           expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
900           if (*arg != 0)
901             error (_("Junk at end of expression"));
902           watchpoint *w = static_cast<watchpoint *> (b);
903           w->cond_exp = std::move (new_exp);
904           w->cond_exp_valid_block = tracker.block ();
905         }
906       else
907         {
908           /* Parse and set condition expressions.  We make two passes.
909              In the first, we parse the condition string to see if it
910              is valid in at least one location.  If so, the condition
911              would be accepted.  So we go ahead and set the locations'
912              conditions.  In case no valid case is found, we throw
913              the error and the condition string will be rejected.
914              This two-pass approach is taken to avoid setting the
915              state of locations in case of a reject.  */
916           for (bp_location *loc : b->locations ())
917             {
918               try
919                 {
920                   const char *arg = exp;
921                   parse_exp_1 (&arg, loc->address,
922                                block_for_pc (loc->address), 0);
923                   if (*arg != 0)
924                     error (_("Junk at end of expression"));
925                   break;
926                 }
927               catch (const gdb_exception_error &e)
928                 {
929                   /* Condition string is invalid.  If this happens to
930                      be the last loc, abandon (if not forced) or continue
931                      (if forced).  */
932                   if (loc->next == nullptr && !force)
933                     throw;
934                 }
935             }
936
937           /* If we reach here, the condition is valid at some locations.  */
938           int loc_num = 1;
939           for (bp_location *loc : b->locations ())
940             {
941               set_breakpoint_location_condition (exp, loc, b->number, loc_num);
942               loc_num++;
943             }
944         }
945
946       /* We know that the new condition parsed successfully.  The
947          condition string of the breakpoint can be safely updated.  */
948       b->cond_string = make_unique_xstrdup (exp);
949       b->condition_not_parsed = 0;
950     }
951   mark_breakpoint_modified (b);
952
953   gdb::observers::breakpoint_modified.notify (b);
954 }
955
956 /* See breakpoint.h.  */
957
958 void
959 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
960                           bool force)
961 {
962   for (breakpoint *b : all_breakpoints ())
963     if (b->number == bpnum)
964       {
965         /* Check if this breakpoint has a "stop" method implemented in an
966            extension language.  This method and conditions entered into GDB
967            from the CLI are mutually exclusive.  */
968         const struct extension_language_defn *extlang
969           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
970
971         if (extlang != NULL)
972           {
973             error (_("Only one stop condition allowed.  There is currently"
974                      " a %s stop condition defined for this breakpoint."),
975                    ext_lang_capitalized_name (extlang));
976           }
977         set_breakpoint_condition (b, exp, from_tty, force);
978
979         if (is_breakpoint (b))
980           update_global_location_list (UGLL_MAY_INSERT);
981
982         return;
983       }
984
985   error (_("No breakpoint number %d."), bpnum);
986 }
987
988 /* The options for the "condition" command.  */
989
990 struct condition_command_opts
991 {
992   /* For "-force".  */
993   bool force_condition = false;
994 };
995
996 static const gdb::option::option_def condition_command_option_defs[] = {
997
998   gdb::option::flag_option_def<condition_command_opts> {
999     "force",
1000     [] (condition_command_opts *opts) { return &opts->force_condition; },
1001     N_("Set the condition even if it is invalid for all current locations."),
1002   },
1003
1004 };
1005
1006 /* Create an option_def_group for the "condition" options, with
1007    CC_OPTS as context.  */
1008
1009 static inline gdb::option::option_def_group
1010 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1011 {
1012   return {{condition_command_option_defs}, cc_opts};
1013 }
1014
1015 /* Completion for the "condition" command.  */
1016
1017 static void
1018 condition_completer (struct cmd_list_element *cmd,
1019                      completion_tracker &tracker,
1020                      const char *text, const char * /*word*/)
1021 {
1022   bool has_no_arguments = (*text == '\0');
1023   condition_command_opts cc_opts;
1024   const auto group = make_condition_command_options_def_group (&cc_opts);
1025   if (gdb::option::complete_options
1026       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1027     return;
1028
1029   text = skip_spaces (text);
1030   const char *space = skip_to_space (text);
1031   if (*space == '\0')
1032     {
1033       int len;
1034
1035       if (text[0] == '$')
1036         {
1037           tracker.advance_custom_word_point_by (1);
1038           /* We don't support completion of history indices.  */
1039           if (!isdigit (text[1]))
1040             complete_internalvar (tracker, &text[1]);
1041           return;
1042         }
1043
1044       /* Suggest the "-force" flag if no arguments are given.  If
1045          arguments were passed, they either already include the flag,
1046          or we are beyond the point of suggesting it because it's
1047          positionally the first argument.  */
1048       if (has_no_arguments)
1049         gdb::option::complete_on_all_options (tracker, group);
1050
1051       /* We're completing the breakpoint number.  */
1052       len = strlen (text);
1053
1054       for (breakpoint *b : all_breakpoints ())
1055         {
1056           char number[50];
1057
1058           xsnprintf (number, sizeof (number), "%d", b->number);
1059
1060           if (strncmp (number, text, len) == 0)
1061             tracker.add_completion (make_unique_xstrdup (number));
1062         }
1063
1064       return;
1065     }
1066
1067   /* We're completing the expression part.  Skip the breakpoint num.  */
1068   const char *exp_start = skip_spaces (space);
1069   tracker.advance_custom_word_point_by (exp_start - text);
1070   text = exp_start;
1071   const char *word = advance_to_expression_complete_word_point (tracker, text);
1072   expression_completer (cmd, tracker, text, word);
1073 }
1074
1075 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1076
1077 static void
1078 condition_command (const char *arg, int from_tty)
1079 {
1080   const char *p;
1081   int bnum;
1082
1083   if (arg == 0)
1084     error_no_arg (_("breakpoint number"));
1085
1086   p = arg;
1087
1088   /* Check if the "-force" flag was passed.  */
1089   condition_command_opts cc_opts;
1090   const auto group = make_condition_command_options_def_group (&cc_opts);
1091   gdb::option::process_options
1092     (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1093
1094   bnum = get_number (&p);
1095   if (bnum == 0)
1096     error (_("Bad breakpoint argument: '%s'"), arg);
1097
1098   set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1099 }
1100
1101 /* Check that COMMAND do not contain commands that are suitable
1102    only for tracepoints and not suitable for ordinary breakpoints.
1103    Throw if any such commands is found.  */
1104
1105 static void
1106 check_no_tracepoint_commands (struct command_line *commands)
1107 {
1108   struct command_line *c;
1109
1110   for (c = commands; c; c = c->next)
1111     {
1112       if (c->control_type == while_stepping_control)
1113         error (_("The 'while-stepping' command can "
1114                  "only be used for tracepoints"));
1115
1116       check_no_tracepoint_commands (c->body_list_0.get ());
1117       check_no_tracepoint_commands (c->body_list_1.get ());
1118
1119       /* Not that command parsing removes leading whitespace and comment
1120          lines and also empty lines.  So, we only need to check for
1121          command directly.  */
1122       if (strstr (c->line, "collect ") == c->line)
1123         error (_("The 'collect' command can only be used for tracepoints"));
1124
1125       if (strstr (c->line, "teval ") == c->line)
1126         error (_("The 'teval' command can only be used for tracepoints"));
1127     }
1128 }
1129
1130 struct longjmp_breakpoint : public breakpoint
1131 {
1132   ~longjmp_breakpoint () override;
1133 };
1134
1135 /* Encapsulate tests for different types of tracepoints.  */
1136
1137 static bool
1138 is_tracepoint_type (bptype type)
1139 {
1140   return (type == bp_tracepoint
1141           || type == bp_fast_tracepoint
1142           || type == bp_static_tracepoint);
1143 }
1144
1145 static bool
1146 is_longjmp_type (bptype type)
1147 {
1148   return type == bp_longjmp || type == bp_exception;
1149 }
1150
1151 /* See breakpoint.h.  */
1152
1153 bool
1154 is_tracepoint (const struct breakpoint *b)
1155 {
1156   return is_tracepoint_type (b->type);
1157 }
1158
1159 /* Factory function to create an appropriate instance of breakpoint given
1160    TYPE.  */
1161
1162 static std::unique_ptr<breakpoint>
1163 new_breakpoint_from_type (bptype type)
1164 {
1165   breakpoint *b;
1166
1167   if (is_tracepoint_type (type))
1168     b = new tracepoint ();
1169   else if (is_longjmp_type (type))
1170     b = new longjmp_breakpoint ();
1171   else
1172     b = new breakpoint ();
1173
1174   return std::unique_ptr<breakpoint> (b);
1175 }
1176
1177 /* A helper function that validates that COMMANDS are valid for a
1178    breakpoint.  This function will throw an exception if a problem is
1179    found.  */
1180
1181 static void
1182 validate_commands_for_breakpoint (struct breakpoint *b,
1183                                   struct command_line *commands)
1184 {
1185   if (is_tracepoint (b))
1186     {
1187       struct tracepoint *t = (struct tracepoint *) b;
1188       struct command_line *c;
1189       struct command_line *while_stepping = 0;
1190
1191       /* Reset the while-stepping step count.  The previous commands
1192          might have included a while-stepping action, while the new
1193          ones might not.  */
1194       t->step_count = 0;
1195
1196       /* We need to verify that each top-level element of commands is
1197          valid for tracepoints, that there's at most one
1198          while-stepping element, and that the while-stepping's body
1199          has valid tracing commands excluding nested while-stepping.
1200          We also need to validate the tracepoint action line in the
1201          context of the tracepoint --- validate_actionline actually
1202          has side effects, like setting the tracepoint's
1203          while-stepping STEP_COUNT, in addition to checking if the
1204          collect/teval actions parse and make sense in the
1205          tracepoint's context.  */
1206       for (c = commands; c; c = c->next)
1207         {
1208           if (c->control_type == while_stepping_control)
1209             {
1210               if (b->type == bp_fast_tracepoint)
1211                 error (_("The 'while-stepping' command "
1212                          "cannot be used for fast tracepoint"));
1213               else if (b->type == bp_static_tracepoint)
1214                 error (_("The 'while-stepping' command "
1215                          "cannot be used for static tracepoint"));
1216
1217               if (while_stepping)
1218                 error (_("The 'while-stepping' command "
1219                          "can be used only once"));
1220               else
1221                 while_stepping = c;
1222             }
1223
1224           validate_actionline (c->line, b);
1225         }
1226       if (while_stepping)
1227         {
1228           struct command_line *c2;
1229
1230           gdb_assert (while_stepping->body_list_1 == nullptr);
1231           c2 = while_stepping->body_list_0.get ();
1232           for (; c2; c2 = c2->next)
1233             {
1234               if (c2->control_type == while_stepping_control)
1235                 error (_("The 'while-stepping' command cannot be nested"));
1236             }
1237         }
1238     }
1239   else
1240     {
1241       check_no_tracepoint_commands (commands);
1242     }
1243 }
1244
1245 /* Return a vector of all the static tracepoints set at ADDR.  The
1246    caller is responsible for releasing the vector.  */
1247
1248 std::vector<breakpoint *>
1249 static_tracepoints_here (CORE_ADDR addr)
1250 {
1251   std::vector<breakpoint *> found;
1252
1253   for (breakpoint *b : all_breakpoints ())
1254     if (b->type == bp_static_tracepoint)
1255       {
1256         for (bp_location *loc : b->locations ())
1257           if (loc->address == addr)
1258             found.push_back (b);
1259       }
1260
1261   return found;
1262 }
1263
1264 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1265    validate that only allowed commands are included.  */
1266
1267 void
1268 breakpoint_set_commands (struct breakpoint *b, 
1269                          counted_command_line &&commands)
1270 {
1271   validate_commands_for_breakpoint (b, commands.get ());
1272
1273   b->commands = std::move (commands);
1274   gdb::observers::breakpoint_modified.notify (b);
1275 }
1276
1277 /* Set the internal `silent' flag on the breakpoint.  Note that this
1278    is not the same as the "silent" that may appear in the breakpoint's
1279    commands.  */
1280
1281 void
1282 breakpoint_set_silent (struct breakpoint *b, int silent)
1283 {
1284   int old_silent = b->silent;
1285
1286   b->silent = silent;
1287   if (old_silent != silent)
1288     gdb::observers::breakpoint_modified.notify (b);
1289 }
1290
1291 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1292    breakpoint work for any thread.  */
1293
1294 void
1295 breakpoint_set_thread (struct breakpoint *b, int thread)
1296 {
1297   int old_thread = b->thread;
1298
1299   b->thread = thread;
1300   if (old_thread != thread)
1301     gdb::observers::breakpoint_modified.notify (b);
1302 }
1303
1304 /* Set the task for this breakpoint.  If TASK is 0, make the
1305    breakpoint work for any task.  */
1306
1307 void
1308 breakpoint_set_task (struct breakpoint *b, int task)
1309 {
1310   int old_task = b->task;
1311
1312   b->task = task;
1313   if (old_task != task)
1314     gdb::observers::breakpoint_modified.notify (b);
1315 }
1316
1317 static void
1318 commands_command_1 (const char *arg, int from_tty,
1319                     struct command_line *control)
1320 {
1321   counted_command_line cmd;
1322   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1323      NULL after the call to read_command_lines if the user provides an empty
1324      list of command by just typing "end".  */
1325   bool cmd_read = false;
1326
1327   std::string new_arg;
1328
1329   if (arg == NULL || !*arg)
1330     {
1331       /* Argument not explicitly given.  Synthesize it.  */
1332       if (breakpoint_count - prev_breakpoint_count > 1)
1333         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1334                                  breakpoint_count);
1335       else if (breakpoint_count > 0)
1336         new_arg = string_printf ("%d", breakpoint_count);
1337     }
1338   else
1339     {
1340       /* Create a copy of ARG.  This is needed because the "commands"
1341          command may be coming from a script.  In that case, the read
1342          line buffer is going to be overwritten in the lambda of
1343          'map_breakpoint_numbers' below when reading the next line
1344          before we are are done parsing the breakpoint numbers.  */
1345       new_arg = arg;
1346     }
1347   arg = new_arg.c_str ();
1348
1349   map_breakpoint_numbers
1350     (arg, [&] (breakpoint *b)
1351      {
1352        if (!cmd_read)
1353          {
1354            gdb_assert (cmd == NULL);
1355            if (control != NULL)
1356              cmd = control->body_list_0;
1357            else
1358              {
1359                std::string str
1360                  = string_printf (_("Type commands for breakpoint(s) "
1361                                     "%s, one per line."),
1362                                   arg);
1363
1364                auto do_validate = [=] (const char *line)
1365                                   {
1366                                     validate_actionline (line, b);
1367                                   };
1368                gdb::function_view<void (const char *)> validator;
1369                if (is_tracepoint (b))
1370                  validator = do_validate;
1371
1372                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1373              }
1374            cmd_read = true;
1375          }
1376
1377        /* If a breakpoint was on the list more than once, we don't need to
1378           do anything.  */
1379        if (b->commands != cmd)
1380          {
1381            validate_commands_for_breakpoint (b, cmd.get ());
1382            b->commands = cmd;
1383            gdb::observers::breakpoint_modified.notify (b);
1384          }
1385      });
1386 }
1387
1388 static void
1389 commands_command (const char *arg, int from_tty)
1390 {
1391   commands_command_1 (arg, from_tty, NULL);
1392 }
1393
1394 /* Like commands_command, but instead of reading the commands from
1395    input stream, takes them from an already parsed command structure.
1396
1397    This is used by cli-script.c to DTRT with breakpoint commands
1398    that are part of if and while bodies.  */
1399 enum command_control_type
1400 commands_from_control_command (const char *arg, struct command_line *cmd)
1401 {
1402   commands_command_1 (arg, 0, cmd);
1403   return simple_control;
1404 }
1405
1406 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1407
1408 static int
1409 bp_location_has_shadow (struct bp_location *bl)
1410 {
1411   if (bl->loc_type != bp_loc_software_breakpoint)
1412     return 0;
1413   if (!bl->inserted)
1414     return 0;
1415   if (bl->target_info.shadow_len == 0)
1416     /* BL isn't valid, or doesn't shadow memory.  */
1417     return 0;
1418   return 1;
1419 }
1420
1421 /* Update BUF, which is LEN bytes read from the target address
1422    MEMADDR, by replacing a memory breakpoint with its shadowed
1423    contents.
1424
1425    If READBUF is not NULL, this buffer must not overlap with the of
1426    the breakpoint location's shadow_contents buffer.  Otherwise, a
1427    failed assertion internal error will be raised.  */
1428
1429 static void
1430 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1431                             const gdb_byte *writebuf_org,
1432                             ULONGEST memaddr, LONGEST len,
1433                             struct bp_target_info *target_info,
1434                             struct gdbarch *gdbarch)
1435 {
1436   /* Now do full processing of the found relevant range of elements.  */
1437   CORE_ADDR bp_addr = 0;
1438   int bp_size = 0;
1439   int bptoffset = 0;
1440
1441   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1442                                  current_program_space->aspace, 0))
1443     {
1444       /* The breakpoint is inserted in a different address space.  */
1445       return;
1446     }
1447
1448   /* Addresses and length of the part of the breakpoint that
1449      we need to copy.  */
1450   bp_addr = target_info->placed_address;
1451   bp_size = target_info->shadow_len;
1452
1453   if (bp_addr + bp_size <= memaddr)
1454     {
1455       /* The breakpoint is entirely before the chunk of memory we are
1456          reading.  */
1457       return;
1458     }
1459
1460   if (bp_addr >= memaddr + len)
1461     {
1462       /* The breakpoint is entirely after the chunk of memory we are
1463          reading.  */
1464       return;
1465     }
1466
1467   /* Offset within shadow_contents.  */
1468   if (bp_addr < memaddr)
1469     {
1470       /* Only copy the second part of the breakpoint.  */
1471       bp_size -= memaddr - bp_addr;
1472       bptoffset = memaddr - bp_addr;
1473       bp_addr = memaddr;
1474     }
1475
1476   if (bp_addr + bp_size > memaddr + len)
1477     {
1478       /* Only copy the first part of the breakpoint.  */
1479       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1480     }
1481
1482   if (readbuf != NULL)
1483     {
1484       /* Verify that the readbuf buffer does not overlap with the
1485          shadow_contents buffer.  */
1486       gdb_assert (target_info->shadow_contents >= readbuf + len
1487                   || readbuf >= (target_info->shadow_contents
1488                                  + target_info->shadow_len));
1489
1490       /* Update the read buffer with this inserted breakpoint's
1491          shadow.  */
1492       memcpy (readbuf + bp_addr - memaddr,
1493               target_info->shadow_contents + bptoffset, bp_size);
1494     }
1495   else
1496     {
1497       const unsigned char *bp;
1498       CORE_ADDR addr = target_info->reqstd_address;
1499       int placed_size;
1500
1501       /* Update the shadow with what we want to write to memory.  */
1502       memcpy (target_info->shadow_contents + bptoffset,
1503               writebuf_org + bp_addr - memaddr, bp_size);
1504
1505       /* Determine appropriate breakpoint contents and size for this
1506          address.  */
1507       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1508
1509       /* Update the final write buffer with this inserted
1510          breakpoint's INSN.  */
1511       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1512     }
1513 }
1514
1515 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1516    by replacing any memory breakpoints with their shadowed contents.
1517
1518    If READBUF is not NULL, this buffer must not overlap with any of
1519    the breakpoint location's shadow_contents buffers.  Otherwise,
1520    a failed assertion internal error will be raised.
1521
1522    The range of shadowed area by each bp_location is:
1523      bl->address - bp_locations_placed_address_before_address_max
1524      up to bl->address + bp_locations_shadow_len_after_address_max
1525    The range we were requested to resolve shadows for is:
1526      memaddr ... memaddr + len
1527    Thus the safe cutoff boundaries for performance optimization are
1528      memaddr + len <= (bl->address
1529                        - bp_locations_placed_address_before_address_max)
1530    and:
1531      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1532
1533 void
1534 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1535                         const gdb_byte *writebuf_org,
1536                         ULONGEST memaddr, LONGEST len)
1537 {
1538   /* Left boundary, right boundary and median element of our binary
1539      search.  */
1540   unsigned bc_l, bc_r, bc;
1541
1542   /* Find BC_L which is a leftmost element which may affect BUF
1543      content.  It is safe to report lower value but a failure to
1544      report higher one.  */
1545
1546   bc_l = 0;
1547   bc_r = bp_locations.size ();
1548   while (bc_l + 1 < bc_r)
1549     {
1550       struct bp_location *bl;
1551
1552       bc = (bc_l + bc_r) / 2;
1553       bl = bp_locations[bc];
1554
1555       /* Check first BL->ADDRESS will not overflow due to the added
1556          constant.  Then advance the left boundary only if we are sure
1557          the BC element can in no way affect the BUF content (MEMADDR
1558          to MEMADDR + LEN range).
1559
1560          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1561          offset so that we cannot miss a breakpoint with its shadow
1562          range tail still reaching MEMADDR.  */
1563
1564       if ((bl->address + bp_locations_shadow_len_after_address_max
1565            >= bl->address)
1566           && (bl->address + bp_locations_shadow_len_after_address_max
1567               <= memaddr))
1568         bc_l = bc;
1569       else
1570         bc_r = bc;
1571     }
1572
1573   /* Due to the binary search above, we need to make sure we pick the
1574      first location that's at BC_L's address.  E.g., if there are
1575      multiple locations at the same address, BC_L may end up pointing
1576      at a duplicate location, and miss the "master"/"inserted"
1577      location.  Say, given locations L1, L2 and L3 at addresses A and
1578      B:
1579
1580       L1@A, L2@A, L3@B, ...
1581
1582      BC_L could end up pointing at location L2, while the "master"
1583      location could be L1.  Since the `loc->inserted' flag is only set
1584      on "master" locations, we'd forget to restore the shadow of L1
1585      and L2.  */
1586   while (bc_l > 0
1587          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1588     bc_l--;
1589
1590   /* Now do full processing of the found relevant range of elements.  */
1591
1592   for (bc = bc_l; bc < bp_locations.size (); bc++)
1593     {
1594       struct bp_location *bl = bp_locations[bc];
1595
1596       /* bp_location array has BL->OWNER always non-NULL.  */
1597       if (bl->owner->type == bp_none)
1598         warning (_("reading through apparently deleted breakpoint #%d?"),
1599                  bl->owner->number);
1600
1601       /* Performance optimization: any further element can no longer affect BUF
1602          content.  */
1603
1604       if (bl->address >= bp_locations_placed_address_before_address_max
1605           && (memaddr + len
1606               <= (bl->address
1607                   - bp_locations_placed_address_before_address_max)))
1608         break;
1609
1610       if (!bp_location_has_shadow (bl))
1611         continue;
1612
1613       one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1614                                   memaddr, len, &bl->target_info, bl->gdbarch);
1615     }
1616 }
1617
1618 /* See breakpoint.h.  */
1619
1620 bool
1621 is_breakpoint (const struct breakpoint *bpt)
1622 {
1623   return (bpt->type == bp_breakpoint
1624           || bpt->type == bp_hardware_breakpoint
1625           || bpt->type == bp_dprintf);
1626 }
1627
1628 /* Return true if BPT is of any hardware watchpoint kind.  */
1629
1630 static bool
1631 is_hardware_watchpoint (const struct breakpoint *bpt)
1632 {
1633   return (bpt->type == bp_hardware_watchpoint
1634           || bpt->type == bp_read_watchpoint
1635           || bpt->type == bp_access_watchpoint);
1636 }
1637
1638 /* See breakpoint.h.  */
1639
1640 bool
1641 is_watchpoint (const struct breakpoint *bpt)
1642 {
1643   return (is_hardware_watchpoint (bpt)
1644           || bpt->type == bp_watchpoint);
1645 }
1646
1647 /* Returns true if the current thread and its running state are safe
1648    to evaluate or update watchpoint B.  Watchpoints on local
1649    expressions need to be evaluated in the context of the thread that
1650    was current when the watchpoint was created, and, that thread needs
1651    to be stopped to be able to select the correct frame context.
1652    Watchpoints on global expressions can be evaluated on any thread,
1653    and in any state.  It is presently left to the target allowing
1654    memory accesses when threads are running.  */
1655
1656 static int
1657 watchpoint_in_thread_scope (struct watchpoint *b)
1658 {
1659   return (b->pspace == current_program_space
1660           && (b->watchpoint_thread == null_ptid
1661               || (inferior_ptid == b->watchpoint_thread
1662                   && !inferior_thread ()->executing ())));
1663 }
1664
1665 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1666    associated bp_watchpoint_scope breakpoint.  */
1667
1668 static void
1669 watchpoint_del_at_next_stop (struct watchpoint *w)
1670 {
1671   if (w->related_breakpoint != w)
1672     {
1673       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1674       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1675       w->related_breakpoint->disposition = disp_del_at_next_stop;
1676       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1677       w->related_breakpoint = w;
1678     }
1679   w->disposition = disp_del_at_next_stop;
1680 }
1681
1682 /* Extract a bitfield value from value VAL using the bit parameters contained in
1683    watchpoint W.  */
1684
1685 static struct value *
1686 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1687 {
1688   struct value *bit_val;
1689
1690   if (val == NULL)
1691     return NULL;
1692
1693   bit_val = allocate_value (value_type (val));
1694
1695   unpack_value_bitfield (bit_val,
1696                          w->val_bitpos,
1697                          w->val_bitsize,
1698                          value_contents_for_printing (val).data (),
1699                          value_offset (val),
1700                          val);
1701
1702   return bit_val;
1703 }
1704
1705 /* Allocate a dummy location and add it to B, which must be a software
1706    watchpoint.  This is required because even if a software watchpoint
1707    is not watching any memory, bpstat_stop_status requires a location
1708    to be able to report stops.  */
1709
1710 static void
1711 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1712                                             struct program_space *pspace)
1713 {
1714   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1715
1716   b->loc = allocate_bp_location (b);
1717   b->loc->pspace = pspace;
1718   b->loc->address = -1;
1719   b->loc->length = -1;
1720 }
1721
1722 /* Returns true if B is a software watchpoint that is not watching any
1723    memory (e.g., "watch $pc").  */
1724
1725 static bool
1726 is_no_memory_software_watchpoint (struct breakpoint *b)
1727 {
1728   return (b->type == bp_watchpoint
1729           && b->loc != NULL
1730           && b->loc->next == NULL
1731           && b->loc->address == -1
1732           && b->loc->length == -1);
1733 }
1734
1735 /* Assuming that B is a watchpoint:
1736    - Reparse watchpoint expression, if REPARSE is non-zero
1737    - Evaluate expression and store the result in B->val
1738    - Evaluate the condition if there is one, and store the result
1739      in b->loc->cond.
1740    - Update the list of values that must be watched in B->loc.
1741
1742    If the watchpoint disposition is disp_del_at_next_stop, then do
1743    nothing.  If this is local watchpoint that is out of scope, delete
1744    it.
1745
1746    Even with `set breakpoint always-inserted on' the watchpoints are
1747    removed + inserted on each stop here.  Normal breakpoints must
1748    never be removed because they might be missed by a running thread
1749    when debugging in non-stop mode.  On the other hand, hardware
1750    watchpoints (is_hardware_watchpoint; processed here) are specific
1751    to each LWP since they are stored in each LWP's hardware debug
1752    registers.  Therefore, such LWP must be stopped first in order to
1753    be able to modify its hardware watchpoints.
1754
1755    Hardware watchpoints must be reset exactly once after being
1756    presented to the user.  It cannot be done sooner, because it would
1757    reset the data used to present the watchpoint hit to the user.  And
1758    it must not be done later because it could display the same single
1759    watchpoint hit during multiple GDB stops.  Note that the latter is
1760    relevant only to the hardware watchpoint types bp_read_watchpoint
1761    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1762    not user-visible - its hit is suppressed if the memory content has
1763    not changed.
1764
1765    The following constraints influence the location where we can reset
1766    hardware watchpoints:
1767
1768    * target_stopped_by_watchpoint and target_stopped_data_address are
1769      called several times when GDB stops.
1770
1771    [linux] 
1772    * Multiple hardware watchpoints can be hit at the same time,
1773      causing GDB to stop.  GDB only presents one hardware watchpoint
1774      hit at a time as the reason for stopping, and all the other hits
1775      are presented later, one after the other, each time the user
1776      requests the execution to be resumed.  Execution is not resumed
1777      for the threads still having pending hit event stored in
1778      LWP_INFO->STATUS.  While the watchpoint is already removed from
1779      the inferior on the first stop the thread hit event is kept being
1780      reported from its cached value by linux_nat_stopped_data_address
1781      until the real thread resume happens after the watchpoint gets
1782      presented and thus its LWP_INFO->STATUS gets reset.
1783
1784    Therefore the hardware watchpoint hit can get safely reset on the
1785    watchpoint removal from inferior.  */
1786
1787 static void
1788 update_watchpoint (struct watchpoint *b, int reparse)
1789 {
1790   int within_current_scope;
1791   struct frame_id saved_frame_id;
1792   int frame_saved;
1793
1794   /* If this is a local watchpoint, we only want to check if the
1795      watchpoint frame is in scope if the current thread is the thread
1796      that was used to create the watchpoint.  */
1797   if (!watchpoint_in_thread_scope (b))
1798     return;
1799
1800   if (b->disposition == disp_del_at_next_stop)
1801     return;
1802  
1803   frame_saved = 0;
1804
1805   /* Determine if the watchpoint is within scope.  */
1806   if (b->exp_valid_block == NULL)
1807     within_current_scope = 1;
1808   else
1809     {
1810       struct frame_info *fi = get_current_frame ();
1811       struct gdbarch *frame_arch = get_frame_arch (fi);
1812       CORE_ADDR frame_pc = get_frame_pc (fi);
1813
1814       /* If we're at a point where the stack has been destroyed
1815          (e.g. in a function epilogue), unwinding may not work
1816          properly. Do not attempt to recreate locations at this
1817          point.  See similar comments in watchpoint_check.  */
1818       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1819         return;
1820
1821       /* Save the current frame's ID so we can restore it after
1822          evaluating the watchpoint expression on its own frame.  */
1823       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1824          took a frame parameter, so that we didn't have to change the
1825          selected frame.  */
1826       frame_saved = 1;
1827       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1828
1829       fi = frame_find_by_id (b->watchpoint_frame);
1830       within_current_scope = (fi != NULL);
1831       if (within_current_scope)
1832         select_frame (fi);
1833     }
1834
1835   /* We don't free locations.  They are stored in the bp_location array
1836      and update_global_location_list will eventually delete them and
1837      remove breakpoints if needed.  */
1838   b->loc = NULL;
1839
1840   if (within_current_scope && reparse)
1841     {
1842       const char *s;
1843
1844       b->exp.reset ();
1845       s = (b->exp_string_reparse
1846            ? b->exp_string_reparse.get ()
1847            : b->exp_string.get ());
1848       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1849       /* If the meaning of expression itself changed, the old value is
1850          no longer relevant.  We don't want to report a watchpoint hit
1851          to the user when the old value and the new value may actually
1852          be completely different objects.  */
1853       b->val = NULL;
1854       b->val_valid = false;
1855
1856       /* Note that unlike with breakpoints, the watchpoint's condition
1857          expression is stored in the breakpoint object, not in the
1858          locations (re)created below.  */
1859       if (b->cond_string != NULL)
1860         {
1861           b->cond_exp.reset ();
1862
1863           s = b->cond_string.get ();
1864           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1865         }
1866     }
1867
1868   /* If we failed to parse the expression, for example because
1869      it refers to a global variable in a not-yet-loaded shared library,
1870      don't try to insert watchpoint.  We don't automatically delete
1871      such watchpoint, though, since failure to parse expression
1872      is different from out-of-scope watchpoint.  */
1873   if (!target_has_execution ())
1874     {
1875       /* Without execution, memory can't change.  No use to try and
1876          set watchpoint locations.  The watchpoint will be reset when
1877          the target gains execution, through breakpoint_re_set.  */
1878       if (!can_use_hw_watchpoints)
1879         {
1880           if (b->ops->works_in_software_mode (b))
1881             b->type = bp_watchpoint;
1882           else
1883             error (_("Can't set read/access watchpoint when "
1884                      "hardware watchpoints are disabled."));
1885         }
1886     }
1887   else if (within_current_scope && b->exp)
1888     {
1889       std::vector<value_ref_ptr> val_chain;
1890       struct value *v, *result;
1891       struct program_space *frame_pspace;
1892
1893       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
1894                           &val_chain, false);
1895
1896       /* Avoid setting b->val if it's already set.  The meaning of
1897          b->val is 'the last value' user saw, and we should update
1898          it only if we reported that last value to user.  As it
1899          happens, the code that reports it updates b->val directly.
1900          We don't keep track of the memory value for masked
1901          watchpoints.  */
1902       if (!b->val_valid && !is_masked_watchpoint (b))
1903         {
1904           if (b->val_bitsize != 0)
1905             v = extract_bitfield_from_watchpoint_value (b, v);
1906           b->val = release_value (v);
1907           b->val_valid = true;
1908         }
1909
1910       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1911
1912       /* Look at each value on the value chain.  */
1913       gdb_assert (!val_chain.empty ());
1914       for (const value_ref_ptr &iter : val_chain)
1915         {
1916           v = iter.get ();
1917
1918           /* If it's a memory location, and GDB actually needed
1919              its contents to evaluate the expression, then we
1920              must watch it.  If the first value returned is
1921              still lazy, that means an error occurred reading it;
1922              watch it anyway in case it becomes readable.  */
1923           if (VALUE_LVAL (v) == lval_memory
1924               && (v == val_chain[0] || ! value_lazy (v)))
1925             {
1926               struct type *vtype = check_typedef (value_type (v));
1927
1928               /* We only watch structs and arrays if user asked
1929                  for it explicitly, never if they just happen to
1930                  appear in the middle of some value chain.  */
1931               if (v == result
1932                   || (vtype->code () != TYPE_CODE_STRUCT
1933                       && vtype->code () != TYPE_CODE_ARRAY))
1934                 {
1935                   CORE_ADDR addr;
1936                   enum target_hw_bp_type type;
1937                   struct bp_location *loc, **tmp;
1938                   int bitpos = 0, bitsize = 0;
1939
1940                   if (value_bitsize (v) != 0)
1941                     {
1942                       /* Extract the bit parameters out from the bitfield
1943                          sub-expression.  */
1944                       bitpos = value_bitpos (v);
1945                       bitsize = value_bitsize (v);
1946                     }
1947                   else if (v == result && b->val_bitsize != 0)
1948                     {
1949                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1950                         lvalue whose bit parameters are saved in the fields
1951                         VAL_BITPOS and VAL_BITSIZE.  */
1952                       bitpos = b->val_bitpos;
1953                       bitsize = b->val_bitsize;
1954                     }
1955
1956                   addr = value_address (v);
1957                   if (bitsize != 0)
1958                     {
1959                       /* Skip the bytes that don't contain the bitfield.  */
1960                       addr += bitpos / 8;
1961                     }
1962
1963                   type = hw_write;
1964                   if (b->type == bp_read_watchpoint)
1965                     type = hw_read;
1966                   else if (b->type == bp_access_watchpoint)
1967                     type = hw_access;
1968
1969                   loc = allocate_bp_location (b);
1970                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1971                     ;
1972                   *tmp = loc;
1973                   loc->gdbarch = value_type (v)->arch ();
1974
1975                   loc->pspace = frame_pspace;
1976                   loc->address = address_significant (loc->gdbarch, addr);
1977
1978                   if (bitsize != 0)
1979                     {
1980                       /* Just cover the bytes that make up the bitfield.  */
1981                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1982                     }
1983                   else
1984                     loc->length = TYPE_LENGTH (value_type (v));
1985
1986                   loc->watchpoint_type = type;
1987                 }
1988             }
1989         }
1990
1991       /* Change the type of breakpoint between hardware assisted or
1992          an ordinary watchpoint depending on the hardware support
1993          and free hardware slots.  REPARSE is set when the inferior
1994          is started.  */
1995       if (reparse)
1996         {
1997           int reg_cnt;
1998           enum bp_loc_type loc_type;
1999
2000           reg_cnt = can_use_hardware_watchpoint (val_chain);
2001
2002           if (reg_cnt)
2003             {
2004               int i, target_resources_ok, other_type_used;
2005               enum bptype type;
2006
2007               /* Use an exact watchpoint when there's only one memory region to be
2008                  watched, and only one debug register is needed to watch it.  */
2009               b->exact = target_exact_watchpoints && reg_cnt == 1;
2010
2011               /* We need to determine how many resources are already
2012                  used for all other hardware watchpoints plus this one
2013                  to see if we still have enough resources to also fit
2014                  this watchpoint in as well.  */
2015
2016               /* If this is a software watchpoint, we try to turn it
2017                  to a hardware one -- count resources as if B was of
2018                  hardware watchpoint type.  */
2019               type = b->type;
2020               if (type == bp_watchpoint)
2021                 type = bp_hardware_watchpoint;
2022
2023               /* This watchpoint may or may not have been placed on
2024                  the list yet at this point (it won't be in the list
2025                  if we're trying to create it for the first time,
2026                  through watch_command), so always account for it
2027                  manually.  */
2028
2029               /* Count resources used by all watchpoints except B.  */
2030               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2031
2032               /* Add in the resources needed for B.  */
2033               i += hw_watchpoint_use_count (b);
2034
2035               target_resources_ok
2036                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2037               if (target_resources_ok <= 0)
2038                 {
2039                   int sw_mode = b->ops->works_in_software_mode (b);
2040
2041                   if (target_resources_ok == 0 && !sw_mode)
2042                     error (_("Target does not support this type of "
2043                              "hardware watchpoint."));
2044                   else if (target_resources_ok < 0 && !sw_mode)
2045                     error (_("There are not enough available hardware "
2046                              "resources for this watchpoint."));
2047
2048                   /* Downgrade to software watchpoint.  */
2049                   b->type = bp_watchpoint;
2050                 }
2051               else
2052                 {
2053                   /* If this was a software watchpoint, we've just
2054                      found we have enough resources to turn it to a
2055                      hardware watchpoint.  Otherwise, this is a
2056                      nop.  */
2057                   b->type = type;
2058                 }
2059             }
2060           else if (!b->ops->works_in_software_mode (b))
2061             {
2062               if (!can_use_hw_watchpoints)
2063                 error (_("Can't set read/access watchpoint when "
2064                          "hardware watchpoints are disabled."));
2065               else
2066                 error (_("Expression cannot be implemented with "
2067                          "read/access watchpoint."));
2068             }
2069           else
2070             b->type = bp_watchpoint;
2071
2072           loc_type = (b->type == bp_watchpoint? bp_loc_other
2073                       : bp_loc_hardware_watchpoint);
2074           for (bp_location *bl : b->locations ())
2075             bl->loc_type = loc_type;
2076         }
2077
2078       /* If a software watchpoint is not watching any memory, then the
2079          above left it without any location set up.  But,
2080          bpstat_stop_status requires a location to be able to report
2081          stops, so make sure there's at least a dummy one.  */
2082       if (b->type == bp_watchpoint && b->loc == NULL)
2083         software_watchpoint_add_no_memory_location (b, frame_pspace);
2084     }
2085   else if (!within_current_scope)
2086     {
2087       gdb_printf (_("\
2088 Watchpoint %d deleted because the program has left the block\n\
2089 in which its expression is valid.\n"),
2090                   b->number);
2091       watchpoint_del_at_next_stop (b);
2092     }
2093
2094   /* Restore the selected frame.  */
2095   if (frame_saved)
2096     select_frame (frame_find_by_id (saved_frame_id));
2097 }
2098
2099
2100 /* Returns 1 iff breakpoint location should be
2101    inserted in the inferior.  We don't differentiate the type of BL's owner
2102    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2103    breakpoint_ops is not defined, because in insert_bp_location,
2104    tracepoint's insert_location will not be called.  */
2105 static int
2106 should_be_inserted (struct bp_location *bl)
2107 {
2108   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2109     return 0;
2110
2111   if (bl->owner->disposition == disp_del_at_next_stop)
2112     return 0;
2113
2114   if (!bl->enabled || bl->disabled_by_cond
2115       || bl->shlib_disabled || bl->duplicate)
2116     return 0;
2117
2118   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2119     return 0;
2120
2121   /* This is set for example, when we're attached to the parent of a
2122      vfork, and have detached from the child.  The child is running
2123      free, and we expect it to do an exec or exit, at which point the
2124      OS makes the parent schedulable again (and the target reports
2125      that the vfork is done).  Until the child is done with the shared
2126      memory region, do not insert breakpoints in the parent, otherwise
2127      the child could still trip on the parent's breakpoints.  Since
2128      the parent is blocked anyway, it won't miss any breakpoint.  */
2129   if (bl->pspace->breakpoints_not_allowed)
2130     return 0;
2131
2132   /* Don't insert a breakpoint if we're trying to step past its
2133      location, except if the breakpoint is a single-step breakpoint,
2134      and the breakpoint's thread is the thread which is stepping past
2135      a breakpoint.  */
2136   if ((bl->loc_type == bp_loc_software_breakpoint
2137        || bl->loc_type == bp_loc_hardware_breakpoint)
2138       && stepping_past_instruction_at (bl->pspace->aspace,
2139                                        bl->address)
2140       /* The single-step breakpoint may be inserted at the location
2141          we're trying to step if the instruction branches to itself.
2142          However, the instruction won't be executed at all and it may
2143          break the semantics of the instruction, for example, the
2144          instruction is a conditional branch or updates some flags.
2145          We can't fix it unless GDB is able to emulate the instruction
2146          or switch to displaced stepping.  */
2147       && !(bl->owner->type == bp_single_step
2148            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2149     {
2150       infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2151                            paddress (bl->gdbarch, bl->address));
2152       return 0;
2153     }
2154
2155   /* Don't insert watchpoints if we're trying to step past the
2156      instruction that triggered one.  */
2157   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2158       && stepping_past_nonsteppable_watchpoint ())
2159     {
2160       infrun_debug_printf ("stepping past non-steppable watchpoint. "
2161                            "skipping watchpoint at %s:%d",
2162                            paddress (bl->gdbarch, bl->address), bl->length);
2163       return 0;
2164     }
2165
2166   return 1;
2167 }
2168
2169 /* Same as should_be_inserted but does the check assuming
2170    that the location is not duplicated.  */
2171
2172 static int
2173 unduplicated_should_be_inserted (struct bp_location *bl)
2174 {
2175   int result;
2176   const int save_duplicate = bl->duplicate;
2177
2178   bl->duplicate = 0;
2179   result = should_be_inserted (bl);
2180   bl->duplicate = save_duplicate;
2181   return result;
2182 }
2183
2184 /* Parses a conditional described by an expression COND into an
2185    agent expression bytecode suitable for evaluation
2186    by the bytecode interpreter.  Return NULL if there was
2187    any error during parsing.  */
2188
2189 static agent_expr_up
2190 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2191 {
2192   if (cond == NULL)
2193     return NULL;
2194
2195   agent_expr_up aexpr;
2196
2197   /* We don't want to stop processing, so catch any errors
2198      that may show up.  */
2199   try
2200     {
2201       aexpr = gen_eval_for_expr (scope, cond);
2202     }
2203
2204   catch (const gdb_exception_error &ex)
2205     {
2206       /* If we got here, it means the condition could not be parsed to a valid
2207          bytecode expression and thus can't be evaluated on the target's side.
2208          It's no use iterating through the conditions.  */
2209     }
2210
2211   /* We have a valid agent expression.  */
2212   return aexpr;
2213 }
2214
2215 /* Based on location BL, create a list of breakpoint conditions to be
2216    passed on to the target.  If we have duplicated locations with different
2217    conditions, we will add such conditions to the list.  The idea is that the
2218    target will evaluate the list of conditions and will only notify GDB when
2219    one of them is true.  */
2220
2221 static void
2222 build_target_condition_list (struct bp_location *bl)
2223 {
2224   int null_condition_or_parse_error = 0;
2225   int modified = bl->needs_update;
2226
2227   /* Release conditions left over from a previous insert.  */
2228   bl->target_info.conditions.clear ();
2229
2230   /* This is only meaningful if the target is
2231      evaluating conditions and if the user has
2232      opted for condition evaluation on the target's
2233      side.  */
2234   if (gdb_evaluates_breakpoint_condition_p ()
2235       || !target_supports_evaluation_of_breakpoint_conditions ())
2236     return;
2237
2238   auto loc_range = all_bp_locations_at_addr (bl->address);
2239
2240   /* Do a first pass to check for locations with no assigned
2241      conditions or conditions that fail to parse to a valid agent
2242      expression bytecode.  If any of these happen, then it's no use to
2243      send conditions to the target since this location will always
2244      trigger and generate a response back to GDB.  Note we consider
2245      all locations at the same address irrespective of type, i.e.,
2246      even if the locations aren't considered duplicates (e.g.,
2247      software breakpoint and hardware breakpoint at the same
2248      address).  */
2249   for (bp_location *loc : loc_range)
2250     {
2251       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2252         {
2253           if (modified)
2254             {
2255               /* Re-parse the conditions since something changed.  In that
2256                  case we already freed the condition bytecodes (see
2257                  force_breakpoint_reinsertion).  We just
2258                  need to parse the condition to bytecodes again.  */
2259               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2260                                                         loc->cond.get ());
2261             }
2262
2263           /* If we have a NULL bytecode expression, it means something
2264              went wrong or we have a null condition expression.  */
2265           if (!loc->cond_bytecode)
2266             {
2267               null_condition_or_parse_error = 1;
2268               break;
2269             }
2270         }
2271     }
2272
2273   /* If any of these happened, it means we will have to evaluate the conditions
2274      for the location's address on gdb's side.  It is no use keeping bytecodes
2275      for all the other duplicate locations, thus we free all of them here.
2276
2277      This is so we have a finer control over which locations' conditions are
2278      being evaluated by GDB or the remote stub.  */
2279   if (null_condition_or_parse_error)
2280     {
2281       for (bp_location *loc : loc_range)
2282         {
2283           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2284             {
2285               /* Only go as far as the first NULL bytecode is
2286                  located.  */
2287               if (!loc->cond_bytecode)
2288                 return;
2289
2290               loc->cond_bytecode.reset ();
2291             }
2292         }
2293     }
2294
2295   /* No NULL conditions or failed bytecode generation.  Build a
2296      condition list for this location's address.  If we have software
2297      and hardware locations at the same address, they aren't
2298      considered duplicates, but we still marge all the conditions
2299      anyway, as it's simpler, and doesn't really make a practical
2300      difference.  */
2301   for (bp_location *loc : loc_range)
2302     if (loc->cond
2303         && is_breakpoint (loc->owner)
2304         && loc->pspace->num == bl->pspace->num
2305         && loc->owner->enable_state == bp_enabled
2306         && loc->enabled
2307         && !loc->disabled_by_cond)
2308       {
2309         /* Add the condition to the vector.  This will be used later
2310            to send the conditions to the target.  */
2311         bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2312       }
2313
2314   return;
2315 }
2316
2317 /* Parses a command described by string CMD into an agent expression
2318    bytecode suitable for evaluation by the bytecode interpreter.
2319    Return NULL if there was any error during parsing.  */
2320
2321 static agent_expr_up
2322 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2323 {
2324   const char *cmdrest;
2325   const char *format_start, *format_end;
2326   struct gdbarch *gdbarch = get_current_arch ();
2327
2328   if (cmd == NULL)
2329     return NULL;
2330
2331   cmdrest = cmd;
2332
2333   if (*cmdrest == ',')
2334     ++cmdrest;
2335   cmdrest = skip_spaces (cmdrest);
2336
2337   if (*cmdrest++ != '"')
2338     error (_("No format string following the location"));
2339
2340   format_start = cmdrest;
2341
2342   format_pieces fpieces (&cmdrest);
2343
2344   format_end = cmdrest;
2345
2346   if (*cmdrest++ != '"')
2347     error (_("Bad format string, non-terminated '\"'."));
2348   
2349   cmdrest = skip_spaces (cmdrest);
2350
2351   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2352     error (_("Invalid argument syntax"));
2353
2354   if (*cmdrest == ',')
2355     cmdrest++;
2356   cmdrest = skip_spaces (cmdrest);
2357
2358   /* For each argument, make an expression.  */
2359
2360   std::vector<struct expression *> argvec;
2361   while (*cmdrest != '\0')
2362     {
2363       const char *cmd1;
2364
2365       cmd1 = cmdrest;
2366       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2367       argvec.push_back (expr.release ());
2368       cmdrest = cmd1;
2369       if (*cmdrest == ',')
2370         ++cmdrest;
2371     }
2372
2373   agent_expr_up aexpr;
2374
2375   /* We don't want to stop processing, so catch any errors
2376      that may show up.  */
2377   try
2378     {
2379       aexpr = gen_printf (scope, gdbarch, 0, 0,
2380                           format_start, format_end - format_start,
2381                           argvec.size (), argvec.data ());
2382     }
2383   catch (const gdb_exception_error &ex)
2384     {
2385       /* If we got here, it means the command could not be parsed to a valid
2386          bytecode expression and thus can't be evaluated on the target's side.
2387          It's no use iterating through the other commands.  */
2388     }
2389
2390   /* We have a valid agent expression, return it.  */
2391   return aexpr;
2392 }
2393
2394 /* Based on location BL, create a list of breakpoint commands to be
2395    passed on to the target.  If we have duplicated locations with
2396    different commands, we will add any such to the list.  */
2397
2398 static void
2399 build_target_command_list (struct bp_location *bl)
2400 {
2401   int null_command_or_parse_error = 0;
2402   int modified = bl->needs_update;
2403
2404   /* Clear commands left over from a previous insert.  */
2405   bl->target_info.tcommands.clear ();
2406
2407   if (!target_can_run_breakpoint_commands ())
2408     return;
2409
2410   /* For now, limit to agent-style dprintf breakpoints.  */
2411   if (dprintf_style != dprintf_style_agent)
2412     return;
2413
2414   auto loc_range = all_bp_locations_at_addr (bl->address);
2415
2416   /* For now, if we have any location at the same address that isn't a
2417      dprintf, don't install the target-side commands, as that would
2418      make the breakpoint not be reported to the core, and we'd lose
2419      control.  */
2420   for (bp_location *loc : loc_range)
2421     if (is_breakpoint (loc->owner)
2422         && loc->pspace->num == bl->pspace->num
2423         && loc->owner->type != bp_dprintf)
2424       return;
2425
2426   /* Do a first pass to check for locations with no assigned
2427      conditions or conditions that fail to parse to a valid agent expression
2428      bytecode.  If any of these happen, then it's no use to send conditions
2429      to the target since this location will always trigger and generate a
2430      response back to GDB.  */
2431   for (bp_location *loc : loc_range)
2432     {
2433       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2434         {
2435           if (modified)
2436             {
2437               /* Re-parse the commands since something changed.  In that
2438                  case we already freed the command bytecodes (see
2439                  force_breakpoint_reinsertion).  We just
2440                  need to parse the command to bytecodes again.  */
2441               loc->cmd_bytecode
2442                 = parse_cmd_to_aexpr (bl->address,
2443                                       loc->owner->extra_string.get ());
2444             }
2445
2446           /* If we have a NULL bytecode expression, it means something
2447              went wrong or we have a null command expression.  */
2448           if (!loc->cmd_bytecode)
2449             {
2450               null_command_or_parse_error = 1;
2451               break;
2452             }
2453         }
2454     }
2455
2456   /* If anything failed, then we're not doing target-side commands,
2457      and so clean up.  */
2458   if (null_command_or_parse_error)
2459     {
2460       for (bp_location *loc : loc_range)
2461         if (is_breakpoint (loc->owner)
2462             && loc->pspace->num == bl->pspace->num)
2463           {
2464             /* Only go as far as the first NULL bytecode is
2465                located.  */
2466             if (loc->cmd_bytecode == NULL)
2467               return;
2468
2469             loc->cmd_bytecode.reset ();
2470           }
2471     }
2472
2473   /* No NULL commands or failed bytecode generation.  Build a command
2474      list for all duplicate locations at this location's address.
2475      Note that here we must care for whether the breakpoint location
2476      types are considered duplicates, otherwise, say, if we have a
2477      software and hardware location at the same address, the target
2478      could end up running the commands twice.  For the moment, we only
2479      support targets-side commands with dprintf, but it doesn't hurt
2480      to be pedantically correct in case that changes.  */
2481   for (bp_location *loc : loc_range)
2482     if (breakpoint_locations_match (bl, loc)
2483         && loc->owner->extra_string
2484         && is_breakpoint (loc->owner)
2485         && loc->pspace->num == bl->pspace->num
2486         && loc->owner->enable_state == bp_enabled
2487         && loc->enabled
2488         && !loc->disabled_by_cond)
2489       {
2490         /* Add the command to the vector.  This will be used later
2491            to send the commands to the target.  */
2492         bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2493       }
2494
2495   bl->target_info.persist = 0;
2496   /* Maybe flag this location as persistent.  */
2497   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2498     bl->target_info.persist = 1;
2499 }
2500
2501 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2502    of breakpoint according to ADDR except single-step breakpoint.
2503    Get the kind of single-step breakpoint according to the current
2504    registers state.  */
2505
2506 static int
2507 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2508 {
2509   if (bl->owner->type == bp_single_step)
2510     {
2511       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2512       struct regcache *regcache;
2513
2514       regcache = get_thread_regcache (thr);
2515
2516       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2517                                                          regcache, addr);
2518     }
2519   else
2520     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2521 }
2522
2523 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2524    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2525    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2526    Returns 0 for success, 1 if the bp_location type is not supported or
2527    -1 for failure.
2528
2529    NOTE drow/2003-09-09: This routine could be broken down to an
2530    object-style method for each breakpoint or catchpoint type.  */
2531 static int
2532 insert_bp_location (struct bp_location *bl,
2533                     struct ui_file *tmp_error_stream,
2534                     int *disabled_breaks,
2535                     int *hw_breakpoint_error,
2536                     int *hw_bp_error_explained_already)
2537 {
2538   gdb_exception bp_excpt;
2539
2540   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2541     return 0;
2542
2543   /* Note we don't initialize bl->target_info, as that wipes out
2544      the breakpoint location's shadow_contents if the breakpoint
2545      is still inserted at that location.  This in turn breaks
2546      target_read_memory which depends on these buffers when
2547      a memory read is requested at the breakpoint location:
2548      Once the target_info has been wiped, we fail to see that
2549      we have a breakpoint inserted at that address and thus
2550      read the breakpoint instead of returning the data saved in
2551      the breakpoint location's shadow contents.  */
2552   bl->target_info.reqstd_address = bl->address;
2553   bl->target_info.placed_address_space = bl->pspace->aspace;
2554   bl->target_info.length = bl->length;
2555
2556   /* When working with target-side conditions, we must pass all the conditions
2557      for the same breakpoint address down to the target since GDB will not
2558      insert those locations.  With a list of breakpoint conditions, the target
2559      can decide when to stop and notify GDB.  */
2560
2561   if (is_breakpoint (bl->owner))
2562     {
2563       build_target_condition_list (bl);
2564       build_target_command_list (bl);
2565       /* Reset the modification marker.  */
2566       bl->needs_update = 0;
2567     }
2568
2569   /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2570      set at a read-only address, then a breakpoint location will have
2571      been changed to hardware breakpoint before we get here.  If it is
2572      "off" however, error out before actually trying to insert the
2573      breakpoint, with a nicer error message.  */
2574   if (bl->loc_type == bp_loc_software_breakpoint
2575       && !automatic_hardware_breakpoints)
2576     {
2577       mem_region *mr = lookup_mem_region (bl->address);
2578
2579       if (mr != nullptr && mr->attrib.mode != MEM_RW)
2580         {
2581           gdb_printf (tmp_error_stream,
2582                       _("Cannot insert breakpoint %d.\n"
2583                         "Cannot set software breakpoint "
2584                         "at read-only address %s\n"),
2585                       bl->owner->number,
2586                       paddress (bl->gdbarch, bl->address));
2587           return 1;
2588         }
2589     }
2590
2591   if (bl->loc_type == bp_loc_software_breakpoint
2592       || bl->loc_type == bp_loc_hardware_breakpoint)
2593     {
2594       /* First check to see if we have to handle an overlay.  */
2595       if (overlay_debugging == ovly_off
2596           || bl->section == NULL
2597           || !(section_is_overlay (bl->section)))
2598         {
2599           /* No overlay handling: just set the breakpoint.  */
2600           try
2601             {
2602               int val;
2603
2604               val = bl->owner->ops->insert_location (bl);
2605               if (val)
2606                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2607             }
2608           catch (gdb_exception &e)
2609             {
2610               bp_excpt = std::move (e);
2611             }
2612         }
2613       else
2614         {
2615           /* This breakpoint is in an overlay section.
2616              Shall we set a breakpoint at the LMA?  */
2617           if (!overlay_events_enabled)
2618             {
2619               /* Yes -- overlay event support is not active, 
2620                  so we must try to set a breakpoint at the LMA.
2621                  This will not work for a hardware breakpoint.  */
2622               if (bl->loc_type == bp_loc_hardware_breakpoint)
2623                 warning (_("hardware breakpoint %d not supported in overlay!"),
2624                          bl->owner->number);
2625               else
2626                 {
2627                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2628                                                              bl->section);
2629                   /* Set a software (trap) breakpoint at the LMA.  */
2630                   bl->overlay_target_info = bl->target_info;
2631                   bl->overlay_target_info.reqstd_address = addr;
2632
2633                   /* No overlay handling: just set the breakpoint.  */
2634                   try
2635                     {
2636                       int val;
2637
2638                       bl->overlay_target_info.kind
2639                         = breakpoint_kind (bl, &addr);
2640                       bl->overlay_target_info.placed_address = addr;
2641                       val = target_insert_breakpoint (bl->gdbarch,
2642                                                       &bl->overlay_target_info);
2643                       if (val)
2644                         bp_excpt
2645                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2646                     }
2647                   catch (gdb_exception &e)
2648                     {
2649                       bp_excpt = std::move (e);
2650                     }
2651
2652                   if (bp_excpt.reason != 0)
2653                     gdb_printf (tmp_error_stream,
2654                                 "Overlay breakpoint %d "
2655                                 "failed: in ROM?\n",
2656                                 bl->owner->number);
2657                 }
2658             }
2659           /* Shall we set a breakpoint at the VMA? */
2660           if (section_is_mapped (bl->section))
2661             {
2662               /* Yes.  This overlay section is mapped into memory.  */
2663               try
2664                 {
2665                   int val;
2666
2667                   val = bl->owner->ops->insert_location (bl);
2668                   if (val)
2669                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2670                 }
2671               catch (gdb_exception &e)
2672                 {
2673                   bp_excpt = std::move (e);
2674                 }
2675             }
2676           else
2677             {
2678               /* No.  This breakpoint will not be inserted.  
2679                  No error, but do not mark the bp as 'inserted'.  */
2680               return 0;
2681             }
2682         }
2683
2684       if (bp_excpt.reason != 0)
2685         {
2686           /* Can't set the breakpoint.  */
2687
2688           /* If the target has closed then it will have deleted any
2689              breakpoints inserted within the target inferior, as a result
2690              any further attempts to interact with the breakpoint objects
2691              is not possible.  Just rethrow the error.  */
2692           if (bp_excpt.error == TARGET_CLOSE_ERROR)
2693             throw bp_excpt;
2694           gdb_assert (bl->owner != nullptr);
2695
2696           /* In some cases, we might not be able to insert a
2697              breakpoint in a shared library that has already been
2698              removed, but we have not yet processed the shlib unload
2699              event.  Unfortunately, some targets that implement
2700              breakpoint insertion themselves can't tell why the
2701              breakpoint insertion failed (e.g., the remote target
2702              doesn't define error codes), so we must treat generic
2703              errors as memory errors.  */
2704           if (bp_excpt.reason == RETURN_ERROR
2705               && (bp_excpt.error == GENERIC_ERROR
2706                   || bp_excpt.error == MEMORY_ERROR)
2707               && bl->loc_type == bp_loc_software_breakpoint
2708               && (solib_name_from_address (bl->pspace, bl->address)
2709                   || shared_objfile_contains_address_p (bl->pspace,
2710                                                         bl->address)))
2711             {
2712               /* See also: disable_breakpoints_in_shlibs.  */
2713               bl->shlib_disabled = 1;
2714               gdb::observers::breakpoint_modified.notify (bl->owner);
2715               if (!*disabled_breaks)
2716                 {
2717                   gdb_printf (tmp_error_stream, 
2718                               "Cannot insert breakpoint %d.\n", 
2719                               bl->owner->number);
2720                   gdb_printf (tmp_error_stream, 
2721                               "Temporarily disabling shared "
2722                               "library breakpoints:\n");
2723                 }
2724               *disabled_breaks = 1;
2725               gdb_printf (tmp_error_stream,
2726                           "breakpoint #%d\n", bl->owner->number);
2727               return 0;
2728             }
2729           else
2730             {
2731               if (bl->loc_type == bp_loc_hardware_breakpoint)
2732                 {
2733                   *hw_breakpoint_error = 1;
2734                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2735                   gdb_printf (tmp_error_stream,
2736                               "Cannot insert hardware breakpoint %d%s",
2737                               bl->owner->number,
2738                               bp_excpt.message ? ":" : ".\n");
2739                   if (bp_excpt.message != NULL)
2740                     gdb_printf (tmp_error_stream, "%s.\n",
2741                                 bp_excpt.what ());
2742                 }
2743               else
2744                 {
2745                   if (bp_excpt.message == NULL)
2746                     {
2747                       std::string message
2748                         = memory_error_message (TARGET_XFER_E_IO,
2749                                                 bl->gdbarch, bl->address);
2750
2751                       gdb_printf (tmp_error_stream,
2752                                   "Cannot insert breakpoint %d.\n"
2753                                   "%s\n",
2754                                   bl->owner->number, message.c_str ());
2755                     }
2756                   else
2757                     {
2758                       gdb_printf (tmp_error_stream,
2759                                   "Cannot insert breakpoint %d: %s\n",
2760                                   bl->owner->number,
2761                                   bp_excpt.what ());
2762                     }
2763                 }
2764               return 1;
2765
2766             }
2767         }
2768       else
2769         bl->inserted = 1;
2770
2771       return 0;
2772     }
2773
2774   else if (bl->loc_type == bp_loc_hardware_watchpoint
2775            /* NOTE drow/2003-09-08: This state only exists for removing
2776               watchpoints.  It's not clear that it's necessary...  */
2777            && bl->owner->disposition != disp_del_at_next_stop)
2778     {
2779       int val;
2780
2781       gdb_assert (bl->owner->ops != NULL
2782                   && bl->owner->ops->insert_location != NULL);
2783
2784       val = bl->owner->ops->insert_location (bl);
2785
2786       /* If trying to set a read-watchpoint, and it turns out it's not
2787          supported, try emulating one with an access watchpoint.  */
2788       if (val == 1 && bl->watchpoint_type == hw_read)
2789         {
2790           /* But don't try to insert it, if there's already another
2791              hw_access location that would be considered a duplicate
2792              of this one.  */
2793           for (bp_location *loc : all_bp_locations ())
2794             if (loc != bl
2795                 && loc->watchpoint_type == hw_access
2796                 && watchpoint_locations_match (bl, loc))
2797               {
2798                 bl->duplicate = 1;
2799                 bl->inserted = 1;
2800                 bl->target_info = loc->target_info;
2801                 bl->watchpoint_type = hw_access;
2802                 val = 0;
2803                 break;
2804               }
2805
2806           if (val == 1)
2807             {
2808               bl->watchpoint_type = hw_access;
2809               val = bl->owner->ops->insert_location (bl);
2810
2811               if (val)
2812                 /* Back to the original value.  */
2813                 bl->watchpoint_type = hw_read;
2814             }
2815         }
2816
2817       bl->inserted = (val == 0);
2818     }
2819
2820   else if (bl->owner->type == bp_catchpoint)
2821     {
2822       int val;
2823
2824       gdb_assert (bl->owner->ops != NULL
2825                   && bl->owner->ops->insert_location != NULL);
2826
2827       val = bl->owner->ops->insert_location (bl);
2828       if (val)
2829         {
2830           bl->owner->enable_state = bp_disabled;
2831
2832           if (val == 1)
2833             warning (_("\
2834 Error inserting catchpoint %d: Your system does not support this type\n\
2835 of catchpoint."), bl->owner->number);
2836           else
2837             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2838         }
2839
2840       bl->inserted = (val == 0);
2841
2842       /* We've already printed an error message if there was a problem
2843          inserting this catchpoint, and we've disabled the catchpoint,
2844          so just return success.  */
2845       return 0;
2846     }
2847
2848   return 0;
2849 }
2850
2851 /* This function is called when program space PSPACE is about to be
2852    deleted.  It takes care of updating breakpoints to not reference
2853    PSPACE anymore.  */
2854
2855 void
2856 breakpoint_program_space_exit (struct program_space *pspace)
2857 {
2858   /* Remove any breakpoint that was set through this program space.  */
2859   for (breakpoint *b : all_breakpoints_safe ())
2860     if (b->pspace == pspace)
2861       delete_breakpoint (b);
2862
2863   /* Breakpoints set through other program spaces could have locations
2864      bound to PSPACE as well.  Remove those.  */
2865   for (bp_location *loc : all_bp_locations ())
2866     {
2867       struct bp_location *tmp;
2868
2869       if (loc->pspace == pspace)
2870         {
2871           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2872           if (loc->owner->loc == loc)
2873             loc->owner->loc = loc->next;
2874           else
2875             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2876               if (tmp->next == loc)
2877                 {
2878                   tmp->next = loc->next;
2879                   break;
2880                 }
2881         }
2882     }
2883
2884   /* Now update the global location list to permanently delete the
2885      removed locations above.  */
2886   update_global_location_list (UGLL_DONT_INSERT);
2887 }
2888
2889 /* Make sure all breakpoints are inserted in inferior.
2890    Throws exception on any error.
2891    A breakpoint that is already inserted won't be inserted
2892    again, so calling this function twice is safe.  */
2893 void
2894 insert_breakpoints (void)
2895 {
2896   for (breakpoint *bpt : all_breakpoints ())
2897     if (is_hardware_watchpoint (bpt))
2898       {
2899         struct watchpoint *w = (struct watchpoint *) bpt;
2900
2901         update_watchpoint (w, 0 /* don't reparse.  */);
2902       }
2903
2904   /* Updating watchpoints creates new locations, so update the global
2905      location list.  Explicitly tell ugll to insert locations and
2906      ignore breakpoints_always_inserted_mode.  Also,
2907      update_global_location_list tries to "upgrade" software
2908      breakpoints to hardware breakpoints to handle "set breakpoint
2909      auto-hw", so we need to call it even if we don't have new
2910      locations.  */
2911   update_global_location_list (UGLL_INSERT);
2912 }
2913
2914 /* This is used when we need to synch breakpoint conditions between GDB and the
2915    target.  It is the case with deleting and disabling of breakpoints when using
2916    always-inserted mode.  */
2917
2918 static void
2919 update_inserted_breakpoint_locations (void)
2920 {
2921   int error_flag = 0;
2922   int val = 0;
2923   int disabled_breaks = 0;
2924   int hw_breakpoint_error = 0;
2925   int hw_bp_details_reported = 0;
2926
2927   string_file tmp_error_stream;
2928
2929   /* Explicitly mark the warning -- this will only be printed if
2930      there was an error.  */
2931   tmp_error_stream.puts ("Warning:\n");
2932
2933   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2934
2935   for (bp_location *bl : all_bp_locations ())
2936     {
2937       /* We only want to update software breakpoints and hardware
2938          breakpoints.  */
2939       if (!is_breakpoint (bl->owner))
2940         continue;
2941
2942       /* We only want to update locations that are already inserted
2943          and need updating.  This is to avoid unwanted insertion during
2944          deletion of breakpoints.  */
2945       if (!bl->inserted || !bl->needs_update)
2946         continue;
2947
2948       switch_to_program_space_and_thread (bl->pspace);
2949
2950       /* For targets that support global breakpoints, there's no need
2951          to select an inferior to insert breakpoint to.  In fact, even
2952          if we aren't attached to any process yet, we should still
2953          insert breakpoints.  */
2954       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2955           && (inferior_ptid == null_ptid || !target_has_execution ()))
2956         continue;
2957
2958       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2959                                     &hw_breakpoint_error, &hw_bp_details_reported);
2960       if (val)
2961         error_flag = val;
2962     }
2963
2964   if (error_flag)
2965     {
2966       target_terminal::ours_for_output ();
2967       error_stream (tmp_error_stream);
2968     }
2969 }
2970
2971 /* Used when starting or continuing the program.  */
2972
2973 static void
2974 insert_breakpoint_locations (void)
2975 {
2976   int error_flag = 0;
2977   int val = 0;
2978   int disabled_breaks = 0;
2979   int hw_breakpoint_error = 0;
2980   int hw_bp_error_explained_already = 0;
2981
2982   string_file tmp_error_stream;
2983
2984   /* Explicitly mark the warning -- this will only be printed if
2985      there was an error.  */
2986   tmp_error_stream.puts ("Warning:\n");
2987
2988   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2989
2990   for (bp_location *bl : all_bp_locations ())
2991     {
2992       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2993         continue;
2994
2995       /* There is no point inserting thread-specific breakpoints if
2996          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2997          has BL->OWNER always non-NULL.  */
2998       if (bl->owner->thread != -1
2999           && !valid_global_thread_id (bl->owner->thread))
3000         continue;
3001
3002       switch_to_program_space_and_thread (bl->pspace);
3003
3004       /* For targets that support global breakpoints, there's no need
3005          to select an inferior to insert breakpoint to.  In fact, even
3006          if we aren't attached to any process yet, we should still
3007          insert breakpoints.  */
3008       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3009           && (inferior_ptid == null_ptid || !target_has_execution ()))
3010         continue;
3011
3012       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3013                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3014       if (val)
3015         error_flag = val;
3016     }
3017
3018   /* If we failed to insert all locations of a watchpoint, remove
3019      them, as half-inserted watchpoint is of limited use.  */
3020   for (breakpoint *bpt : all_breakpoints ())
3021     {
3022       int some_failed = 0;
3023
3024       if (!is_hardware_watchpoint (bpt))
3025         continue;
3026
3027       if (!breakpoint_enabled (bpt))
3028         continue;
3029
3030       if (bpt->disposition == disp_del_at_next_stop)
3031         continue;
3032       
3033       for (bp_location *loc : bpt->locations ())
3034         if (!loc->inserted && should_be_inserted (loc))
3035           {
3036             some_failed = 1;
3037             break;
3038           }
3039
3040       if (some_failed)
3041         {
3042           for (bp_location *loc : bpt->locations ())
3043             if (loc->inserted)
3044               remove_breakpoint (loc);
3045
3046           hw_breakpoint_error = 1;
3047           tmp_error_stream.printf ("Could not insert "
3048                                    "hardware watchpoint %d.\n",
3049                                    bpt->number);
3050           error_flag = -1;
3051         }
3052     }
3053
3054   if (error_flag)
3055     {
3056       /* If a hardware breakpoint or watchpoint was inserted, add a
3057          message about possibly exhausted resources.  */
3058       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3059         {
3060           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3061 You may have requested too many hardware breakpoints/watchpoints.\n");
3062         }
3063       target_terminal::ours_for_output ();
3064       error_stream (tmp_error_stream);
3065     }
3066 }
3067
3068 /* Used when the program stops.
3069    Returns zero if successful, or non-zero if there was a problem
3070    removing a breakpoint location.  */
3071
3072 int
3073 remove_breakpoints (void)
3074 {
3075   int val = 0;
3076
3077   for (bp_location *bl : all_bp_locations ())
3078     if (bl->inserted && !is_tracepoint (bl->owner))
3079       val |= remove_breakpoint (bl);
3080
3081   return val;
3082 }
3083
3084 /* When a thread exits, remove breakpoints that are related to
3085    that thread.  */
3086
3087 static void
3088 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3089 {
3090   for (breakpoint *b : all_breakpoints_safe ())
3091     {
3092       if (b->thread == tp->global_num && user_breakpoint_p (b))
3093         {
3094           b->disposition = disp_del_at_next_stop;
3095
3096           gdb_printf (_("\
3097 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3098                       b->number, print_thread_id (tp));
3099
3100           /* Hide it from the user.  */
3101           b->number = 0;
3102        }
3103     }
3104 }
3105
3106 /* See breakpoint.h.  */
3107
3108 void
3109 remove_breakpoints_inf (inferior *inf)
3110 {
3111   int val;
3112
3113   for (bp_location *bl : all_bp_locations ())
3114     {
3115       if (bl->pspace != inf->pspace)
3116         continue;
3117
3118       if (bl->inserted && !bl->target_info.persist)
3119         {
3120           val = remove_breakpoint (bl);
3121           if (val != 0)
3122             return;
3123         }
3124     }
3125 }
3126
3127 static int internal_breakpoint_number = -1;
3128
3129 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3130    If INTERNAL is non-zero, the breakpoint number will be populated
3131    from internal_breakpoint_number and that variable decremented.
3132    Otherwise the breakpoint number will be populated from
3133    breakpoint_count and that value incremented.  Internal breakpoints
3134    do not set the internal var bpnum.  */
3135 static void
3136 set_breakpoint_number (int internal, struct breakpoint *b)
3137 {
3138   if (internal)
3139     b->number = internal_breakpoint_number--;
3140   else
3141     {
3142       set_breakpoint_count (breakpoint_count + 1);
3143       b->number = breakpoint_count;
3144     }
3145 }
3146
3147 static struct breakpoint *
3148 create_internal_breakpoint (struct gdbarch *gdbarch,
3149                             CORE_ADDR address, enum bptype type,
3150                             const struct breakpoint_ops *ops)
3151 {
3152   symtab_and_line sal;
3153   sal.pc = address;
3154   sal.section = find_pc_overlay (sal.pc);
3155   sal.pspace = current_program_space;
3156
3157   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3158   b->number = internal_breakpoint_number--;
3159   b->disposition = disp_donttouch;
3160
3161   return b;
3162 }
3163
3164 static const char *const longjmp_names[] =
3165   {
3166     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3167   };
3168 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3169
3170 /* Per-objfile data private to breakpoint.c.  */
3171 struct breakpoint_objfile_data
3172 {
3173   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3174   struct bound_minimal_symbol overlay_msym;
3175
3176   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3177   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3178
3179   /* True if we have looked for longjmp probes.  */
3180   int longjmp_searched = 0;
3181
3182   /* SystemTap probe points for longjmp (if any).  These are non-owning
3183      references.  */
3184   std::vector<probe *> longjmp_probes;
3185
3186   /* Minimal symbol for "std::terminate()" (if any).  */
3187   struct bound_minimal_symbol terminate_msym;
3188
3189   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3190   struct bound_minimal_symbol exception_msym;
3191
3192   /* True if we have looked for exception probes.  */
3193   int exception_searched = 0;
3194
3195   /* SystemTap probe points for unwinding (if any).  These are non-owning
3196      references.  */
3197   std::vector<probe *> exception_probes;
3198 };
3199
3200 static const struct objfile_key<breakpoint_objfile_data>
3201   breakpoint_objfile_key;
3202
3203 /* Minimal symbol not found sentinel.  */
3204 static struct minimal_symbol msym_not_found;
3205
3206 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3207
3208 static int
3209 msym_not_found_p (const struct minimal_symbol *msym)
3210 {
3211   return msym == &msym_not_found;
3212 }
3213
3214 /* Return per-objfile data needed by breakpoint.c.
3215    Allocate the data if necessary.  */
3216
3217 static struct breakpoint_objfile_data *
3218 get_breakpoint_objfile_data (struct objfile *objfile)
3219 {
3220   struct breakpoint_objfile_data *bp_objfile_data;
3221
3222   bp_objfile_data = breakpoint_objfile_key.get (objfile);
3223   if (bp_objfile_data == NULL)
3224     bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3225   return bp_objfile_data;
3226 }
3227
3228 static void
3229 create_overlay_event_breakpoint (void)
3230 {
3231   const char *const func_name = "_ovly_debug_event";
3232
3233   for (objfile *objfile : current_program_space->objfiles ())
3234     {
3235       struct breakpoint *b;
3236       struct breakpoint_objfile_data *bp_objfile_data;
3237       CORE_ADDR addr;
3238       struct explicit_location explicit_loc;
3239
3240       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3241
3242       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3243         continue;
3244
3245       if (bp_objfile_data->overlay_msym.minsym == NULL)
3246         {
3247           struct bound_minimal_symbol m;
3248
3249           m = lookup_minimal_symbol_text (func_name, objfile);
3250           if (m.minsym == NULL)
3251             {
3252               /* Avoid future lookups in this objfile.  */
3253               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3254               continue;
3255             }
3256           bp_objfile_data->overlay_msym = m;
3257         }
3258
3259       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3260       b = create_internal_breakpoint (objfile->arch (), addr,
3261                                       bp_overlay_event,
3262                                       &internal_breakpoint_ops);
3263       initialize_explicit_location (&explicit_loc);
3264       explicit_loc.function_name = ASTRDUP (func_name);
3265       b->location = new_explicit_location (&explicit_loc);
3266
3267       if (overlay_debugging == ovly_auto)
3268         {
3269           b->enable_state = bp_enabled;
3270           overlay_events_enabled = 1;
3271         }
3272       else
3273        {
3274          b->enable_state = bp_disabled;
3275          overlay_events_enabled = 0;
3276        }
3277     }
3278 }
3279
3280 /* Install a master longjmp breakpoint for OBJFILE using a probe.  Return
3281    true if a breakpoint was installed.  */
3282
3283 static bool
3284 create_longjmp_master_breakpoint_probe (objfile *objfile)
3285 {
3286   struct gdbarch *gdbarch = objfile->arch ();
3287   struct breakpoint_objfile_data *bp_objfile_data
3288     = get_breakpoint_objfile_data (objfile);
3289
3290   if (!bp_objfile_data->longjmp_searched)
3291     {
3292       std::vector<probe *> ret
3293         = find_probes_in_objfile (objfile, "libc", "longjmp");
3294
3295       if (!ret.empty ())
3296         {
3297           /* We are only interested in checking one element.  */
3298           probe *p = ret[0];
3299
3300           if (!p->can_evaluate_arguments ())
3301             {
3302               /* We cannot use the probe interface here,
3303                  because it does not know how to evaluate
3304                  arguments.  */
3305               ret.clear ();
3306             }
3307         }
3308       bp_objfile_data->longjmp_probes = ret;
3309       bp_objfile_data->longjmp_searched = 1;
3310     }
3311
3312   if (bp_objfile_data->longjmp_probes.empty ())
3313     return false;
3314
3315   for (probe *p : bp_objfile_data->longjmp_probes)
3316     {
3317       struct breakpoint *b;
3318
3319       b = create_internal_breakpoint (gdbarch,
3320                                       p->get_relocated_address (objfile),
3321                                       bp_longjmp_master,
3322                                       &internal_breakpoint_ops);
3323       b->location = new_probe_location ("-probe-stap libc:longjmp");
3324       b->enable_state = bp_disabled;
3325     }
3326
3327   return true;
3328 }
3329
3330 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3331    Return true if at least one breakpoint was installed.  */
3332
3333 static bool
3334 create_longjmp_master_breakpoint_names (objfile *objfile)
3335 {
3336   struct gdbarch *gdbarch = objfile->arch ();
3337   if (!gdbarch_get_longjmp_target_p (gdbarch))
3338     return false;
3339
3340   struct breakpoint_objfile_data *bp_objfile_data
3341     = get_breakpoint_objfile_data (objfile);
3342   unsigned int installed_bp = 0;
3343
3344   for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3345     {
3346       struct breakpoint *b;
3347       const char *func_name;
3348       CORE_ADDR addr;
3349       struct explicit_location explicit_loc;
3350
3351       if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3352         continue;
3353
3354       func_name = longjmp_names[i];
3355       if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3356         {
3357           struct bound_minimal_symbol m;
3358
3359           m = lookup_minimal_symbol_text (func_name, objfile);
3360           if (m.minsym == NULL)
3361             {
3362               /* Prevent future lookups in this objfile.  */
3363               bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3364               continue;
3365             }
3366           bp_objfile_data->longjmp_msym[i] = m;
3367         }
3368
3369       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3370       b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3371                                       &internal_breakpoint_ops);
3372       initialize_explicit_location (&explicit_loc);
3373       explicit_loc.function_name = ASTRDUP (func_name);
3374       b->location = new_explicit_location (&explicit_loc);
3375       b->enable_state = bp_disabled;
3376       installed_bp++;
3377     }
3378
3379   return installed_bp > 0;
3380 }
3381
3382 /* Create a master longjmp breakpoint.  */
3383
3384 static void
3385 create_longjmp_master_breakpoint (void)
3386 {
3387   scoped_restore_current_program_space restore_pspace;
3388
3389   for (struct program_space *pspace : program_spaces)
3390     {
3391       set_current_program_space (pspace);
3392
3393       for (objfile *obj : current_program_space->objfiles ())
3394         {
3395           /* Skip separate debug object, it's handled in the loop below.  */
3396           if (obj->separate_debug_objfile_backlink != nullptr)
3397             continue;
3398
3399           /* Try a probe kind breakpoint on main objfile.  */
3400           if (create_longjmp_master_breakpoint_probe (obj))
3401             continue;
3402
3403           /* Try longjmp_names kind breakpoints on main and separate_debug
3404              objfiles.  */
3405           for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3406             if (create_longjmp_master_breakpoint_names (debug_objfile))
3407               break;
3408         }
3409     }
3410 }
3411
3412 /* Create a master std::terminate breakpoint.  */
3413 static void
3414 create_std_terminate_master_breakpoint (void)
3415 {
3416   const char *const func_name = "std::terminate()";
3417
3418   scoped_restore_current_program_space restore_pspace;
3419
3420   for (struct program_space *pspace : program_spaces)
3421     {
3422       CORE_ADDR addr;
3423
3424       set_current_program_space (pspace);
3425
3426       for (objfile *objfile : current_program_space->objfiles ())
3427         {
3428           struct breakpoint *b;
3429           struct breakpoint_objfile_data *bp_objfile_data;
3430           struct explicit_location explicit_loc;
3431
3432           bp_objfile_data = get_breakpoint_objfile_data (objfile);
3433
3434           if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3435             continue;
3436
3437           if (bp_objfile_data->terminate_msym.minsym == NULL)
3438             {
3439               struct bound_minimal_symbol m;
3440
3441               m = lookup_minimal_symbol (func_name, NULL, objfile);
3442               if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3443                                        && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3444                 {
3445                   /* Prevent future lookups in this objfile.  */
3446                   bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3447                   continue;
3448                 }
3449               bp_objfile_data->terminate_msym = m;
3450             }
3451
3452           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3453           b = create_internal_breakpoint (objfile->arch (), addr,
3454                                           bp_std_terminate_master,
3455                                           &internal_breakpoint_ops);
3456           initialize_explicit_location (&explicit_loc);
3457           explicit_loc.function_name = ASTRDUP (func_name);
3458           b->location = new_explicit_location (&explicit_loc);
3459           b->enable_state = bp_disabled;
3460         }
3461     }
3462 }
3463
3464 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3465    probe.  Return true if a breakpoint was installed.  */
3466
3467 static bool
3468 create_exception_master_breakpoint_probe (objfile *objfile)
3469 {
3470   struct breakpoint *b;
3471   struct gdbarch *gdbarch;
3472   struct breakpoint_objfile_data *bp_objfile_data;
3473
3474   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3475
3476   /* We prefer the SystemTap probe point if it exists.  */
3477   if (!bp_objfile_data->exception_searched)
3478     {
3479       std::vector<probe *> ret
3480         = find_probes_in_objfile (objfile, "libgcc", "unwind");
3481
3482       if (!ret.empty ())
3483         {
3484           /* We are only interested in checking one element.  */
3485           probe *p = ret[0];
3486
3487           if (!p->can_evaluate_arguments ())
3488             {
3489               /* We cannot use the probe interface here, because it does
3490                  not know how to evaluate arguments.  */
3491               ret.clear ();
3492             }
3493         }
3494       bp_objfile_data->exception_probes = ret;
3495       bp_objfile_data->exception_searched = 1;
3496     }
3497
3498   if (bp_objfile_data->exception_probes.empty ())
3499     return false;
3500
3501   gdbarch = objfile->arch ();
3502
3503   for (probe *p : bp_objfile_data->exception_probes)
3504     {
3505       b = create_internal_breakpoint (gdbarch,
3506                                       p->get_relocated_address (objfile),
3507                                       bp_exception_master,
3508                                       &internal_breakpoint_ops);
3509       b->location = new_probe_location ("-probe-stap libgcc:unwind");
3510       b->enable_state = bp_disabled;
3511     }
3512
3513   return true;
3514 }
3515
3516 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3517    _Unwind_DebugHook.  Return true if a breakpoint was installed.  */
3518
3519 static bool
3520 create_exception_master_breakpoint_hook (objfile *objfile)
3521 {
3522   const char *const func_name = "_Unwind_DebugHook";
3523   struct breakpoint *b;
3524   struct gdbarch *gdbarch;
3525   struct breakpoint_objfile_data *bp_objfile_data;
3526   CORE_ADDR addr;
3527   struct explicit_location explicit_loc;
3528
3529   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3530
3531   if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3532     return false;
3533
3534   gdbarch = objfile->arch ();
3535
3536   if (bp_objfile_data->exception_msym.minsym == NULL)
3537     {
3538       struct bound_minimal_symbol debug_hook;
3539
3540       debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3541       if (debug_hook.minsym == NULL)
3542         {
3543           bp_objfile_data->exception_msym.minsym = &msym_not_found;
3544           return false;
3545         }
3546
3547       bp_objfile_data->exception_msym = debug_hook;
3548     }
3549
3550   addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3551   addr = gdbarch_convert_from_func_ptr_addr
3552     (gdbarch, addr, current_inferior ()->top_target ());
3553   b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3554                                   &internal_breakpoint_ops);
3555   initialize_explicit_location (&explicit_loc);
3556   explicit_loc.function_name = ASTRDUP (func_name);
3557   b->location = new_explicit_location (&explicit_loc);
3558   b->enable_state = bp_disabled;
3559
3560   return true;
3561 }
3562
3563 /* Install a master breakpoint on the unwinder's debug hook.  */
3564
3565 static void
3566 create_exception_master_breakpoint (void)
3567 {
3568   for (objfile *obj : current_program_space->objfiles ())
3569     {
3570       /* Skip separate debug object.  */
3571       if (obj->separate_debug_objfile_backlink)
3572         continue;
3573
3574       /* Try a probe kind breakpoint.  */
3575       if (create_exception_master_breakpoint_probe (obj))
3576         continue;
3577
3578       /* Iterate over main and separate debug objects and try an
3579          _Unwind_DebugHook kind breakpoint.  */
3580       for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3581         if (create_exception_master_breakpoint_hook (debug_objfile))
3582           break;
3583     }
3584 }
3585
3586 /* Does B have a location spec?  */
3587
3588 static int
3589 breakpoint_event_location_empty_p (const struct breakpoint *b)
3590 {
3591   return b->location != NULL && event_location_empty_p (b->location.get ());
3592 }
3593
3594 void
3595 update_breakpoints_after_exec (void)
3596 {
3597   /* We're about to delete breakpoints from GDB's lists.  If the
3598      INSERTED flag is true, GDB will try to lift the breakpoints by
3599      writing the breakpoints' "shadow contents" back into memory.  The
3600      "shadow contents" are NOT valid after an exec, so GDB should not
3601      do that.  Instead, the target is responsible from marking
3602      breakpoints out as soon as it detects an exec.  We don't do that
3603      here instead, because there may be other attempts to delete
3604      breakpoints after detecting an exec and before reaching here.  */
3605   for (bp_location *bploc : all_bp_locations ())
3606     if (bploc->pspace == current_program_space)
3607       gdb_assert (!bploc->inserted);
3608
3609   for (breakpoint *b : all_breakpoints_safe ())
3610     {
3611       if (b->pspace != current_program_space)
3612         continue;
3613
3614       /* Solib breakpoints must be explicitly reset after an exec().  */
3615       if (b->type == bp_shlib_event)
3616         {
3617           delete_breakpoint (b);
3618           continue;
3619         }
3620
3621       /* JIT breakpoints must be explicitly reset after an exec().  */
3622       if (b->type == bp_jit_event)
3623         {
3624           delete_breakpoint (b);
3625           continue;
3626         }
3627
3628       /* Thread event breakpoints must be set anew after an exec(),
3629          as must overlay event and longjmp master breakpoints.  */
3630       if (b->type == bp_thread_event || b->type == bp_overlay_event
3631           || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3632           || b->type == bp_exception_master)
3633         {
3634           delete_breakpoint (b);
3635           continue;
3636         }
3637
3638       /* Step-resume breakpoints are meaningless after an exec().  */
3639       if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3640         {
3641           delete_breakpoint (b);
3642           continue;
3643         }
3644
3645       /* Just like single-step breakpoints.  */
3646       if (b->type == bp_single_step)
3647         {
3648           delete_breakpoint (b);
3649           continue;
3650         }
3651
3652       /* Longjmp and longjmp-resume breakpoints are also meaningless
3653          after an exec.  */
3654       if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3655           || b->type == bp_longjmp_call_dummy
3656           || b->type == bp_exception || b->type == bp_exception_resume)
3657         {
3658           delete_breakpoint (b);
3659           continue;
3660         }
3661
3662       if (b->type == bp_catchpoint)
3663         {
3664           /* For now, none of the bp_catchpoint breakpoints need to
3665              do anything at this point.  In the future, if some of
3666              the catchpoints need to something, we will need to add
3667              a new method, and call this method from here.  */
3668           continue;
3669         }
3670
3671       /* bp_finish is a special case.  The only way we ought to be able
3672          to see one of these when an exec() has happened, is if the user
3673          caught a vfork, and then said "finish".  Ordinarily a finish just
3674          carries them to the call-site of the current callee, by setting
3675          a temporary bp there and resuming.  But in this case, the finish
3676          will carry them entirely through the vfork & exec.
3677
3678          We don't want to allow a bp_finish to remain inserted now.  But
3679          we can't safely delete it, 'cause finish_command has a handle to
3680          the bp on a bpstat, and will later want to delete it.  There's a
3681          chance (and I've seen it happen) that if we delete the bp_finish
3682          here, that its storage will get reused by the time finish_command
3683          gets 'round to deleting the "use to be a bp_finish" breakpoint.
3684          We really must allow finish_command to delete a bp_finish.
3685
3686          In the absence of a general solution for the "how do we know
3687          it's safe to delete something others may have handles to?"
3688          problem, what we'll do here is just uninsert the bp_finish, and
3689          let finish_command delete it.
3690
3691          (We know the bp_finish is "doomed" in the sense that it's
3692          momentary, and will be deleted as soon as finish_command sees
3693          the inferior stopped.  So it doesn't matter that the bp's
3694          address is probably bogus in the new a.out, unlike e.g., the
3695          solib breakpoints.)  */
3696
3697       if (b->type == bp_finish)
3698         {
3699           continue;
3700         }
3701
3702       /* Without a symbolic address, we have little hope of the
3703          pre-exec() address meaning the same thing in the post-exec()
3704          a.out.  */
3705       if (breakpoint_event_location_empty_p (b))
3706         {
3707           delete_breakpoint (b);
3708           continue;
3709         }
3710     }
3711 }
3712
3713 int
3714 detach_breakpoints (ptid_t ptid)
3715 {
3716   int val = 0;
3717   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3718   struct inferior *inf = current_inferior ();
3719
3720   if (ptid.pid () == inferior_ptid.pid ())
3721     error (_("Cannot detach breakpoints of inferior_ptid"));
3722
3723   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3724   inferior_ptid = ptid;
3725   for (bp_location *bl : all_bp_locations ())
3726     {
3727       if (bl->pspace != inf->pspace)
3728         continue;
3729
3730       /* This function must physically remove breakpoints locations
3731          from the specified ptid, without modifying the breakpoint
3732          package's state.  Locations of type bp_loc_other are only
3733          maintained at GDB side.  So, there is no need to remove
3734          these bp_loc_other locations.  Moreover, removing these
3735          would modify the breakpoint package's state.  */
3736       if (bl->loc_type == bp_loc_other)
3737         continue;
3738
3739       if (bl->inserted)
3740         val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3741     }
3742
3743   return val;
3744 }
3745
3746 /* Remove the breakpoint location BL from the current address space.
3747    Note that this is used to detach breakpoints from a child fork.
3748    When we get here, the child isn't in the inferior list, and neither
3749    do we have objects to represent its address space --- we should
3750    *not* look at bl->pspace->aspace here.  */
3751
3752 static int
3753 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3754 {
3755   int val;
3756
3757   /* BL is never in moribund_locations by our callers.  */
3758   gdb_assert (bl->owner != NULL);
3759
3760   /* The type of none suggests that owner is actually deleted.
3761      This should not ever happen.  */
3762   gdb_assert (bl->owner->type != bp_none);
3763
3764   if (bl->loc_type == bp_loc_software_breakpoint
3765       || bl->loc_type == bp_loc_hardware_breakpoint)
3766     {
3767       /* "Normal" instruction breakpoint: either the standard
3768          trap-instruction bp (bp_breakpoint), or a
3769          bp_hardware_breakpoint.  */
3770
3771       /* First check to see if we have to handle an overlay.  */
3772       if (overlay_debugging == ovly_off
3773           || bl->section == NULL
3774           || !(section_is_overlay (bl->section)))
3775         {
3776           /* No overlay handling: just remove the breakpoint.  */
3777
3778           /* If we're trying to uninsert a memory breakpoint that we
3779              know is set in a dynamic object that is marked
3780              shlib_disabled, then either the dynamic object was
3781              removed with "remove-symbol-file" or with
3782              "nosharedlibrary".  In the former case, we don't know
3783              whether another dynamic object might have loaded over the
3784              breakpoint's address -- the user might well let us know
3785              about it next with add-symbol-file (the whole point of
3786              add-symbol-file is letting the user manually maintain a
3787              list of dynamically loaded objects).  If we have the
3788              breakpoint's shadow memory, that is, this is a software
3789              breakpoint managed by GDB, check whether the breakpoint
3790              is still inserted in memory, to avoid overwriting wrong
3791              code with stale saved shadow contents.  Note that HW
3792              breakpoints don't have shadow memory, as they're
3793              implemented using a mechanism that is not dependent on
3794              being able to modify the target's memory, and as such
3795              they should always be removed.  */
3796           if (bl->shlib_disabled
3797               && bl->target_info.shadow_len != 0
3798               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3799             val = 0;
3800           else
3801             val = bl->owner->ops->remove_location (bl, reason);
3802         }
3803       else
3804         {
3805           /* This breakpoint is in an overlay section.
3806              Did we set a breakpoint at the LMA?  */
3807           if (!overlay_events_enabled)
3808               {
3809                 /* Yes -- overlay event support is not active, so we
3810                    should have set a breakpoint at the LMA.  Remove it.  
3811                 */
3812                 /* Ignore any failures: if the LMA is in ROM, we will
3813                    have already warned when we failed to insert it.  */
3814                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3815                   target_remove_hw_breakpoint (bl->gdbarch,
3816                                                &bl->overlay_target_info);
3817                 else
3818                   target_remove_breakpoint (bl->gdbarch,
3819                                             &bl->overlay_target_info,
3820                                             reason);
3821               }
3822           /* Did we set a breakpoint at the VMA? 
3823              If so, we will have marked the breakpoint 'inserted'.  */
3824           if (bl->inserted)
3825             {
3826               /* Yes -- remove it.  Previously we did not bother to
3827                  remove the breakpoint if the section had been
3828                  unmapped, but let's not rely on that being safe.  We
3829                  don't know what the overlay manager might do.  */
3830
3831               /* However, we should remove *software* breakpoints only
3832                  if the section is still mapped, or else we overwrite
3833                  wrong code with the saved shadow contents.  */
3834               if (bl->loc_type == bp_loc_hardware_breakpoint
3835                   || section_is_mapped (bl->section))
3836                 val = bl->owner->ops->remove_location (bl, reason);
3837               else
3838                 val = 0;
3839             }
3840           else
3841             {
3842               /* No -- not inserted, so no need to remove.  No error.  */
3843               val = 0;
3844             }
3845         }
3846
3847       /* In some cases, we might not be able to remove a breakpoint in
3848          a shared library that has already been removed, but we have
3849          not yet processed the shlib unload event.  Similarly for an
3850          unloaded add-symbol-file object - the user might not yet have
3851          had the chance to remove-symbol-file it.  shlib_disabled will
3852          be set if the library/object has already been removed, but
3853          the breakpoint hasn't been uninserted yet, e.g., after
3854          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3855          always-inserted mode.  */
3856       if (val
3857           && (bl->loc_type == bp_loc_software_breakpoint
3858               && (bl->shlib_disabled
3859                   || solib_name_from_address (bl->pspace, bl->address)
3860                   || shared_objfile_contains_address_p (bl->pspace,
3861                                                         bl->address))))
3862         val = 0;
3863
3864       if (val)
3865         return val;
3866       bl->inserted = (reason == DETACH_BREAKPOINT);
3867     }
3868   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3869     {
3870       gdb_assert (bl->owner->ops != NULL
3871                   && bl->owner->ops->remove_location != NULL);
3872
3873       bl->inserted = (reason == DETACH_BREAKPOINT);
3874       bl->owner->ops->remove_location (bl, reason);
3875
3876       /* Failure to remove any of the hardware watchpoints comes here.  */
3877       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3878         warning (_("Could not remove hardware watchpoint %d."),
3879                  bl->owner->number);
3880     }
3881   else if (bl->owner->type == bp_catchpoint
3882            && breakpoint_enabled (bl->owner)
3883            && !bl->duplicate)
3884     {
3885       gdb_assert (bl->owner->ops != NULL
3886                   && bl->owner->ops->remove_location != NULL);
3887
3888       val = bl->owner->ops->remove_location (bl, reason);
3889       if (val)
3890         return val;
3891
3892       bl->inserted = (reason == DETACH_BREAKPOINT);
3893     }
3894
3895   return 0;
3896 }
3897
3898 static int
3899 remove_breakpoint (struct bp_location *bl)
3900 {
3901   /* BL is never in moribund_locations by our callers.  */
3902   gdb_assert (bl->owner != NULL);
3903
3904   /* The type of none suggests that owner is actually deleted.
3905      This should not ever happen.  */
3906   gdb_assert (bl->owner->type != bp_none);
3907
3908   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3909
3910   switch_to_program_space_and_thread (bl->pspace);
3911
3912   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3913 }
3914
3915 /* Clear the "inserted" flag in all breakpoints.  */
3916
3917 void
3918 mark_breakpoints_out (void)
3919 {
3920   for (bp_location *bl : all_bp_locations ())
3921     if (bl->pspace == current_program_space)
3922       bl->inserted = 0;
3923 }
3924
3925 /* Clear the "inserted" flag in all breakpoints and delete any
3926    breakpoints which should go away between runs of the program.
3927
3928    Plus other such housekeeping that has to be done for breakpoints
3929    between runs.
3930
3931    Note: this function gets called at the end of a run (by
3932    generic_mourn_inferior) and when a run begins (by
3933    init_wait_for_inferior).  */
3934
3935
3936
3937 void
3938 breakpoint_init_inferior (enum inf_context context)
3939 {
3940   struct program_space *pspace = current_program_space;
3941
3942   /* If breakpoint locations are shared across processes, then there's
3943      nothing to do.  */
3944   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3945     return;
3946
3947   mark_breakpoints_out ();
3948
3949   for (breakpoint *b : all_breakpoints_safe ())
3950     {
3951       if (b->loc && b->loc->pspace != pspace)
3952         continue;
3953
3954       switch (b->type)
3955         {
3956         case bp_call_dummy:
3957         case bp_longjmp_call_dummy:
3958
3959           /* If the call dummy breakpoint is at the entry point it will
3960              cause problems when the inferior is rerun, so we better get
3961              rid of it.  */
3962
3963         case bp_watchpoint_scope:
3964
3965           /* Also get rid of scope breakpoints.  */
3966
3967         case bp_shlib_event:
3968
3969           /* Also remove solib event breakpoints.  Their addresses may
3970              have changed since the last time we ran the program.
3971              Actually we may now be debugging against different target;
3972              and so the solib backend that installed this breakpoint may
3973              not be used in by the target.  E.g.,
3974
3975              (gdb) file prog-linux
3976              (gdb) run               # native linux target
3977              ...
3978              (gdb) kill
3979              (gdb) file prog-win.exe
3980              (gdb) tar rem :9999     # remote Windows gdbserver.
3981           */
3982
3983         case bp_step_resume:
3984
3985           /* Also remove step-resume breakpoints.  */
3986
3987         case bp_single_step:
3988
3989           /* Also remove single-step breakpoints.  */
3990
3991           delete_breakpoint (b);
3992           break;
3993
3994         case bp_watchpoint:
3995         case bp_hardware_watchpoint:
3996         case bp_read_watchpoint:
3997         case bp_access_watchpoint:
3998           {
3999             struct watchpoint *w = (struct watchpoint *) b;
4000
4001             /* Likewise for watchpoints on local expressions.  */
4002             if (w->exp_valid_block != NULL)
4003               delete_breakpoint (b);
4004             else
4005               {
4006                 /* Get rid of existing locations, which are no longer
4007                    valid.  New ones will be created in
4008                    update_watchpoint, when the inferior is restarted.
4009                    The next update_global_location_list call will
4010                    garbage collect them.  */
4011                 b->loc = NULL;
4012
4013                 if (context == inf_starting)
4014                   {
4015                     /* Reset val field to force reread of starting value in
4016                        insert_breakpoints.  */
4017                     w->val.reset (nullptr);
4018                     w->val_valid = false;
4019                   }
4020               }
4021           }
4022           break;
4023         default:
4024           break;
4025         }
4026     }
4027
4028   /* Get rid of the moribund locations.  */
4029   for (bp_location *bl : moribund_locations)
4030     decref_bp_location (&bl);
4031   moribund_locations.clear ();
4032 }
4033
4034 /* These functions concern about actual breakpoints inserted in the
4035    target --- to e.g. check if we need to do decr_pc adjustment or if
4036    we need to hop over the bkpt --- so we check for address space
4037    match, not program space.  */
4038
4039 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4040    exists at PC.  It returns ordinary_breakpoint_here if it's an
4041    ordinary breakpoint, or permanent_breakpoint_here if it's a
4042    permanent breakpoint.
4043    - When continuing from a location with an ordinary breakpoint, we
4044      actually single step once before calling insert_breakpoints.
4045    - When continuing from a location with a permanent breakpoint, we
4046      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4047      the target, to advance the PC past the breakpoint.  */
4048
4049 enum breakpoint_here
4050 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4051 {
4052   int any_breakpoint_here = 0;
4053
4054   for (bp_location *bl : all_bp_locations ())
4055     {
4056       if (bl->loc_type != bp_loc_software_breakpoint
4057           && bl->loc_type != bp_loc_hardware_breakpoint)
4058         continue;
4059
4060       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4061       if ((breakpoint_enabled (bl->owner)
4062            || bl->permanent)
4063           && breakpoint_location_address_match (bl, aspace, pc))
4064         {
4065           if (overlay_debugging 
4066               && section_is_overlay (bl->section)
4067               && !section_is_mapped (bl->section))
4068             continue;           /* unmapped overlay -- can't be a match */
4069           else if (bl->permanent)
4070             return permanent_breakpoint_here;
4071           else
4072             any_breakpoint_here = 1;
4073         }
4074     }
4075
4076   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4077 }
4078
4079 /* See breakpoint.h.  */
4080
4081 int
4082 breakpoint_in_range_p (const address_space *aspace,
4083                        CORE_ADDR addr, ULONGEST len)
4084 {
4085   for (bp_location *bl : all_bp_locations ())
4086     {
4087       if (bl->loc_type != bp_loc_software_breakpoint
4088           && bl->loc_type != bp_loc_hardware_breakpoint)
4089         continue;
4090
4091       if ((breakpoint_enabled (bl->owner)
4092            || bl->permanent)
4093           && breakpoint_location_address_range_overlap (bl, aspace,
4094                                                         addr, len))
4095         {
4096           if (overlay_debugging
4097               && section_is_overlay (bl->section)
4098               && !section_is_mapped (bl->section))
4099             {
4100               /* Unmapped overlay -- can't be a match.  */
4101               continue;
4102             }
4103
4104           return 1;
4105         }
4106     }
4107
4108   return 0;
4109 }
4110
4111 /* Return true if there's a moribund breakpoint at PC.  */
4112
4113 int
4114 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4115 {
4116   for (bp_location *loc : moribund_locations)
4117     if (breakpoint_location_address_match (loc, aspace, pc))
4118       return 1;
4119
4120   return 0;
4121 }
4122
4123 /* Returns non-zero iff BL is inserted at PC, in address space
4124    ASPACE.  */
4125
4126 static int
4127 bp_location_inserted_here_p (struct bp_location *bl,
4128                              const address_space *aspace, CORE_ADDR pc)
4129 {
4130   if (bl->inserted
4131       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4132                                    aspace, pc))
4133     {
4134       if (overlay_debugging
4135           && section_is_overlay (bl->section)
4136           && !section_is_mapped (bl->section))
4137         return 0;               /* unmapped overlay -- can't be a match */
4138       else
4139         return 1;
4140     }
4141   return 0;
4142 }
4143
4144 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4145
4146 int
4147 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4148 {
4149   for (bp_location *bl : all_bp_locations_at_addr (pc))
4150     {
4151       if (bl->loc_type != bp_loc_software_breakpoint
4152           && bl->loc_type != bp_loc_hardware_breakpoint)
4153         continue;
4154
4155       if (bp_location_inserted_here_p (bl, aspace, pc))
4156         return 1;
4157     }
4158   return 0;
4159 }
4160
4161 /* This function returns non-zero iff there is a software breakpoint
4162    inserted at PC.  */
4163
4164 int
4165 software_breakpoint_inserted_here_p (const address_space *aspace,
4166                                      CORE_ADDR pc)
4167 {
4168   for (bp_location *bl : all_bp_locations_at_addr (pc))
4169     {
4170       if (bl->loc_type != bp_loc_software_breakpoint)
4171         continue;
4172
4173       if (bp_location_inserted_here_p (bl, aspace, pc))
4174         return 1;
4175     }
4176
4177   return 0;
4178 }
4179
4180 /* See breakpoint.h.  */
4181
4182 int
4183 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4184                                      CORE_ADDR pc)
4185 {
4186   for (bp_location *bl : all_bp_locations_at_addr (pc))
4187     {
4188       if (bl->loc_type != bp_loc_hardware_breakpoint)
4189         continue;
4190
4191       if (bp_location_inserted_here_p (bl, aspace, pc))
4192         return 1;
4193     }
4194
4195   return 0;
4196 }
4197
4198 int
4199 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4200                                        CORE_ADDR addr, ULONGEST len)
4201 {
4202   for (breakpoint *bpt : all_breakpoints ())
4203     {
4204       if (bpt->type != bp_hardware_watchpoint
4205           && bpt->type != bp_access_watchpoint)
4206         continue;
4207
4208       if (!breakpoint_enabled (bpt))
4209         continue;
4210
4211       for (bp_location *loc : bpt->locations ())
4212         if (loc->pspace->aspace == aspace && loc->inserted)
4213           {
4214             CORE_ADDR l, h;
4215
4216             /* Check for intersection.  */
4217             l = std::max<CORE_ADDR> (loc->address, addr);
4218             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4219             if (l < h)
4220               return 1;
4221           }
4222     }
4223   return 0;
4224 }
4225
4226 /* See breakpoint.h.  */
4227
4228 bool
4229 is_catchpoint (struct breakpoint *b)
4230 {
4231   return (b->type == bp_catchpoint);
4232 }
4233
4234 /* Clear a bpstat so that it says we are not at any breakpoint.
4235    Also free any storage that is part of a bpstat.  */
4236
4237 void
4238 bpstat_clear (bpstat **bsp)
4239 {
4240   bpstat *p;
4241   bpstat *q;
4242
4243   if (bsp == 0)
4244     return;
4245   p = *bsp;
4246   while (p != NULL)
4247     {
4248       q = p->next;
4249       delete p;
4250       p = q;
4251     }
4252   *bsp = NULL;
4253 }
4254
4255 bpstat::bpstat (const bpstat &other)
4256   : next (NULL),
4257     bp_location_at (other.bp_location_at),
4258     breakpoint_at (other.breakpoint_at),
4259     commands (other.commands),
4260     print (other.print),
4261     stop (other.stop),
4262     print_it (other.print_it)
4263 {
4264   if (other.old_val != NULL)
4265     old_val = release_value (value_copy (other.old_val.get ()));
4266 }
4267
4268 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4269    is part of the bpstat is copied as well.  */
4270
4271 bpstat *
4272 bpstat_copy (bpstat *bs)
4273 {
4274   bpstat *p = nullptr;
4275   bpstat *tmp;
4276   bpstat *retval = nullptr;
4277
4278   if (bs == NULL)
4279     return bs;
4280
4281   for (; bs != NULL; bs = bs->next)
4282     {
4283       tmp = new bpstat (*bs);
4284
4285       if (p == NULL)
4286         /* This is the first thing in the chain.  */
4287         retval = tmp;
4288       else
4289         p->next = tmp;
4290       p = tmp;
4291     }
4292   p->next = NULL;
4293   return retval;
4294 }
4295
4296 /* Find the bpstat associated with this breakpoint.  */
4297
4298 bpstat *
4299 bpstat_find_breakpoint (bpstat *bsp, struct breakpoint *breakpoint)
4300 {
4301   if (bsp == NULL)
4302     return NULL;
4303
4304   for (; bsp != NULL; bsp = bsp->next)
4305     {
4306       if (bsp->breakpoint_at == breakpoint)
4307         return bsp;
4308     }
4309   return NULL;
4310 }
4311
4312 /* See breakpoint.h.  */
4313
4314 bool
4315 bpstat_explains_signal (bpstat *bsp, enum gdb_signal sig)
4316 {
4317   for (; bsp != NULL; bsp = bsp->next)
4318     {
4319       if (bsp->breakpoint_at == NULL)
4320         {
4321           /* A moribund location can never explain a signal other than
4322              GDB_SIGNAL_TRAP.  */
4323           if (sig == GDB_SIGNAL_TRAP)
4324             return true;
4325         }
4326       else
4327         {
4328           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4329                                                         sig))
4330             return true;
4331         }
4332     }
4333
4334   return false;
4335 }
4336
4337 /* Put in *NUM the breakpoint number of the first breakpoint we are
4338    stopped at.  *BSP upon return is a bpstat which points to the
4339    remaining breakpoints stopped at (but which is not guaranteed to be
4340    good for anything but further calls to bpstat_num).
4341
4342    Return 0 if passed a bpstat which does not indicate any breakpoints.
4343    Return -1 if stopped at a breakpoint that has been deleted since
4344    we set it.
4345    Return 1 otherwise.  */
4346
4347 int
4348 bpstat_num (bpstat **bsp, int *num)
4349 {
4350   struct breakpoint *b;
4351
4352   if ((*bsp) == NULL)
4353     return 0;                   /* No more breakpoint values */
4354
4355   /* We assume we'll never have several bpstats that correspond to a
4356      single breakpoint -- otherwise, this function might return the
4357      same number more than once and this will look ugly.  */
4358   b = (*bsp)->breakpoint_at;
4359   *bsp = (*bsp)->next;
4360   if (b == NULL)
4361     return -1;                  /* breakpoint that's been deleted since */
4362
4363   *num = b->number;             /* We have its number */
4364   return 1;
4365 }
4366
4367 /* See breakpoint.h.  */
4368
4369 void
4370 bpstat_clear_actions (void)
4371 {
4372   bpstat *bs;
4373
4374   if (inferior_ptid == null_ptid)
4375     return;
4376
4377   thread_info *tp = inferior_thread ();
4378   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4379     {
4380       bs->commands = NULL;
4381       bs->old_val.reset (nullptr);
4382     }
4383 }
4384
4385 /* Called when a command is about to proceed the inferior.  */
4386
4387 static void
4388 breakpoint_about_to_proceed (void)
4389 {
4390   if (inferior_ptid != null_ptid)
4391     {
4392       struct thread_info *tp = inferior_thread ();
4393
4394       /* Allow inferior function calls in breakpoint commands to not
4395          interrupt the command list.  When the call finishes
4396          successfully, the inferior will be standing at the same
4397          breakpoint as if nothing happened.  */
4398       if (tp->control.in_infcall)
4399         return;
4400     }
4401
4402   breakpoint_proceeded = 1;
4403 }
4404
4405 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4406    or its equivalent.  */
4407
4408 static int
4409 command_line_is_silent (struct command_line *cmd)
4410 {
4411   return cmd && (strcmp ("silent", cmd->line) == 0);
4412 }
4413
4414 /* Execute all the commands associated with all the breakpoints at
4415    this location.  Any of these commands could cause the process to
4416    proceed beyond this point, etc.  We look out for such changes by
4417    checking the global "breakpoint_proceeded" after each command.
4418
4419    Returns true if a breakpoint command resumed the inferior.  In that
4420    case, it is the caller's responsibility to recall it again with the
4421    bpstat of the current thread.  */
4422
4423 static int
4424 bpstat_do_actions_1 (bpstat **bsp)
4425 {
4426   bpstat *bs;
4427   int again = 0;
4428
4429   /* Avoid endless recursion if a `source' command is contained
4430      in bs->commands.  */
4431   if (executing_breakpoint_commands)
4432     return 0;
4433
4434   scoped_restore save_executing
4435     = make_scoped_restore (&executing_breakpoint_commands, 1);
4436
4437   scoped_restore preventer = prevent_dont_repeat ();
4438
4439   /* This pointer will iterate over the list of bpstat's.  */
4440   bs = *bsp;
4441
4442   breakpoint_proceeded = 0;
4443   for (; bs != NULL; bs = bs->next)
4444     {
4445       struct command_line *cmd = NULL;
4446
4447       /* Take ownership of the BSP's command tree, if it has one.
4448
4449          The command tree could legitimately contain commands like
4450          'step' and 'next', which call clear_proceed_status, which
4451          frees stop_bpstat's command tree.  To make sure this doesn't
4452          free the tree we're executing out from under us, we need to
4453          take ownership of the tree ourselves.  Since a given bpstat's
4454          commands are only executed once, we don't need to copy it; we
4455          can clear the pointer in the bpstat, and make sure we free
4456          the tree when we're done.  */
4457       counted_command_line ccmd = bs->commands;
4458       bs->commands = NULL;
4459       if (ccmd != NULL)
4460         cmd = ccmd.get ();
4461       if (command_line_is_silent (cmd))
4462         {
4463           /* The action has been already done by bpstat_stop_status.  */
4464           cmd = cmd->next;
4465         }
4466
4467       while (cmd != NULL)
4468         {
4469           execute_control_command (cmd);
4470
4471           if (breakpoint_proceeded)
4472             break;
4473           else
4474             cmd = cmd->next;
4475         }
4476
4477       if (breakpoint_proceeded)
4478         {
4479           if (current_ui->async)
4480             /* If we are in async mode, then the target might be still
4481                running, not stopped at any breakpoint, so nothing for
4482                us to do here -- just return to the event loop.  */
4483             ;
4484           else
4485             /* In sync mode, when execute_control_command returns
4486                we're already standing on the next breakpoint.
4487                Breakpoint commands for that stop were not run, since
4488                execute_command does not run breakpoint commands --
4489                only command_line_handler does, but that one is not
4490                involved in execution of breakpoint commands.  So, we
4491                can now execute breakpoint commands.  It should be
4492                noted that making execute_command do bpstat actions is
4493                not an option -- in this case we'll have recursive
4494                invocation of bpstat for each breakpoint with a
4495                command, and can easily blow up GDB stack.  Instead, we
4496                return true, which will trigger the caller to recall us
4497                with the new stop_bpstat.  */
4498             again = 1;
4499           break;
4500         }
4501     }
4502   return again;
4503 }
4504
4505 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4506    one, is alive and has execution.  Return NULL otherwise.  */
4507
4508 static thread_info *
4509 get_bpstat_thread ()
4510 {
4511   if (inferior_ptid == null_ptid || !target_has_execution ())
4512     return NULL;
4513
4514   thread_info *tp = inferior_thread ();
4515   if (tp->state == THREAD_EXITED || tp->executing ())
4516     return NULL;
4517   return tp;
4518 }
4519
4520 void
4521 bpstat_do_actions (void)
4522 {
4523   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4524   thread_info *tp;
4525
4526   /* Do any commands attached to breakpoint we are stopped at.  */
4527   while ((tp = get_bpstat_thread ()) != NULL)
4528     {
4529       /* Since in sync mode, bpstat_do_actions may resume the
4530          inferior, and only return when it is stopped at the next
4531          breakpoint, we keep doing breakpoint actions until it returns
4532          false to indicate the inferior was not resumed.  */
4533       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4534         break;
4535     }
4536
4537   cleanup_if_error.release ();
4538 }
4539
4540 /* Print out the (old or new) value associated with a watchpoint.  */
4541
4542 static void
4543 watchpoint_value_print (struct value *val, struct ui_file *stream)
4544 {
4545   if (val == NULL)
4546     fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4547   else
4548     {
4549       struct value_print_options opts;
4550       get_user_print_options (&opts);
4551       value_print (val, stream, &opts);
4552     }
4553 }
4554
4555 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4556    debugging multiple threads.  */
4557
4558 void
4559 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4560 {
4561   if (uiout->is_mi_like_p ())
4562     return;
4563
4564   uiout->text ("\n");
4565
4566   if (show_thread_that_caused_stop ())
4567     {
4568       struct thread_info *thr = inferior_thread ();
4569
4570       uiout->text ("Thread ");
4571       uiout->field_string ("thread-id", print_thread_id (thr));
4572
4573       const char *name = thread_name (thr);
4574       if (name != NULL)
4575         {
4576           uiout->text (" \"");
4577           uiout->field_string ("name", name);
4578           uiout->text ("\"");
4579         }
4580
4581       uiout->text (" hit ");
4582     }
4583 }
4584
4585 /* Generic routine for printing messages indicating why we
4586    stopped.  The behavior of this function depends on the value
4587    'print_it' in the bpstat structure.  Under some circumstances we
4588    may decide not to print anything here and delegate the task to
4589    normal_stop().  */
4590
4591 static enum print_stop_action
4592 print_bp_stop_message (bpstat *bs)
4593 {
4594   switch (bs->print_it)
4595     {
4596     case print_it_noop:
4597       /* Nothing should be printed for this bpstat entry.  */
4598       return PRINT_UNKNOWN;
4599       break;
4600
4601     case print_it_done:
4602       /* We still want to print the frame, but we already printed the
4603          relevant messages.  */
4604       return PRINT_SRC_AND_LOC;
4605       break;
4606
4607     case print_it_normal:
4608       {
4609         struct breakpoint *b = bs->breakpoint_at;
4610
4611         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4612            which has since been deleted.  */
4613         if (b == NULL)
4614           return PRINT_UNKNOWN;
4615
4616         /* Normal case.  Call the breakpoint's print_it method.  */
4617         return b->ops->print_it (bs);
4618       }
4619       break;
4620
4621     default:
4622       internal_error (__FILE__, __LINE__,
4623                       _("print_bp_stop_message: unrecognized enum value"));
4624       break;
4625     }
4626 }
4627
4628 /* A helper function that prints a shared library stopped event.  */
4629
4630 static void
4631 print_solib_event (int is_catchpoint)
4632 {
4633   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4634   bool any_added = !current_program_space->added_solibs.empty ();
4635
4636   if (!is_catchpoint)
4637     {
4638       if (any_added || any_deleted)
4639         current_uiout->text (_("Stopped due to shared library event:\n"));
4640       else
4641         current_uiout->text (_("Stopped due to shared library event (no "
4642                                "libraries added or removed)\n"));
4643     }
4644
4645   if (current_uiout->is_mi_like_p ())
4646     current_uiout->field_string ("reason",
4647                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4648
4649   if (any_deleted)
4650     {
4651       current_uiout->text (_("  Inferior unloaded "));
4652       ui_out_emit_list list_emitter (current_uiout, "removed");
4653       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4654         {
4655           const std::string &name = current_program_space->deleted_solibs[ix];
4656
4657           if (ix > 0)
4658             current_uiout->text ("    ");
4659           current_uiout->field_string ("library", name);
4660           current_uiout->text ("\n");
4661         }
4662     }
4663
4664   if (any_added)
4665     {
4666       current_uiout->text (_("  Inferior loaded "));
4667       ui_out_emit_list list_emitter (current_uiout, "added");
4668       bool first = true;
4669       for (so_list *iter : current_program_space->added_solibs)
4670         {
4671           if (!first)
4672             current_uiout->text ("    ");
4673           first = false;
4674           current_uiout->field_string ("library", iter->so_name);
4675           current_uiout->text ("\n");
4676         }
4677     }
4678 }
4679
4680 /* Print a message indicating what happened.  This is called from
4681    normal_stop().  The input to this routine is the head of the bpstat
4682    list - a list of the eventpoints that caused this stop.  KIND is
4683    the target_waitkind for the stopping event.  This
4684    routine calls the generic print routine for printing a message
4685    about reasons for stopping.  This will print (for example) the
4686    "Breakpoint n," part of the output.  The return value of this
4687    routine is one of:
4688
4689    PRINT_UNKNOWN: Means we printed nothing.
4690    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4691    code to print the location.  An example is 
4692    "Breakpoint 1, " which should be followed by
4693    the location.
4694    PRINT_SRC_ONLY: Means we printed something, but there is no need
4695    to also print the location part of the message.
4696    An example is the catch/throw messages, which
4697    don't require a location appended to the end.
4698    PRINT_NOTHING: We have done some printing and we don't need any 
4699    further info to be printed.  */
4700
4701 enum print_stop_action
4702 bpstat_print (bpstat *bs, int kind)
4703 {
4704   enum print_stop_action val;
4705
4706   /* Maybe another breakpoint in the chain caused us to stop.
4707      (Currently all watchpoints go on the bpstat whether hit or not.
4708      That probably could (should) be changed, provided care is taken
4709      with respect to bpstat_explains_signal).  */
4710   for (; bs; bs = bs->next)
4711     {
4712       val = print_bp_stop_message (bs);
4713       if (val == PRINT_SRC_ONLY 
4714           || val == PRINT_SRC_AND_LOC 
4715           || val == PRINT_NOTHING)
4716         return val;
4717     }
4718
4719   /* If we had hit a shared library event breakpoint,
4720      print_bp_stop_message would print out this message.  If we hit an
4721      OS-level shared library event, do the same thing.  */
4722   if (kind == TARGET_WAITKIND_LOADED)
4723     {
4724       print_solib_event (0);
4725       return PRINT_NOTHING;
4726     }
4727
4728   /* We reached the end of the chain, or we got a null BS to start
4729      with and nothing was printed.  */
4730   return PRINT_UNKNOWN;
4731 }
4732
4733 /* Evaluate the boolean expression EXP and return the result.  */
4734
4735 static bool
4736 breakpoint_cond_eval (expression *exp)
4737 {
4738   struct value *mark = value_mark ();
4739   bool res = value_true (evaluate_expression (exp));
4740
4741   value_free_to_mark (mark);
4742   return res;
4743 }
4744
4745 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4746
4747 bpstat::bpstat (struct bp_location *bl, bpstat ***bs_link_pointer)
4748   : next (NULL),
4749     bp_location_at (bp_location_ref_ptr::new_reference (bl)),
4750     breakpoint_at (bl->owner),
4751     commands (NULL),
4752     print (0),
4753     stop (0),
4754     print_it (print_it_normal)
4755 {
4756   **bs_link_pointer = this;
4757   *bs_link_pointer = &next;
4758 }
4759
4760 bpstat::bpstat ()
4761   : next (NULL),
4762     breakpoint_at (NULL),
4763     commands (NULL),
4764     print (0),
4765     stop (0),
4766     print_it (print_it_normal)
4767 {
4768 }
4769 \f
4770 /* The target has stopped with waitstatus WS.  Check if any hardware
4771    watchpoints have triggered, according to the target.  */
4772
4773 int
4774 watchpoints_triggered (const target_waitstatus &ws)
4775 {
4776   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4777   CORE_ADDR addr;
4778
4779   if (!stopped_by_watchpoint)
4780     {
4781       /* We were not stopped by a watchpoint.  Mark all watchpoints
4782          as not triggered.  */
4783       for (breakpoint *b : all_breakpoints ())
4784         if (is_hardware_watchpoint (b))
4785           {
4786             struct watchpoint *w = (struct watchpoint *) b;
4787
4788             w->watchpoint_triggered = watch_triggered_no;
4789           }
4790
4791       return 0;
4792     }
4793
4794   if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
4795     {
4796       /* We were stopped by a watchpoint, but we don't know where.
4797          Mark all watchpoints as unknown.  */
4798       for (breakpoint *b : all_breakpoints ())
4799         if (is_hardware_watchpoint (b))
4800           {
4801             struct watchpoint *w = (struct watchpoint *) b;
4802
4803             w->watchpoint_triggered = watch_triggered_unknown;
4804           }
4805
4806       return 1;
4807     }
4808
4809   /* The target could report the data address.  Mark watchpoints
4810      affected by this data address as triggered, and all others as not
4811      triggered.  */
4812
4813   for (breakpoint *b : all_breakpoints ())
4814     if (is_hardware_watchpoint (b))
4815       {
4816         struct watchpoint *w = (struct watchpoint *) b;
4817
4818         w->watchpoint_triggered = watch_triggered_no;
4819         for (bp_location *loc : b->locations ())
4820           {
4821             if (is_masked_watchpoint (b))
4822               {
4823                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4824                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4825
4826                 if (newaddr == start)
4827                   {
4828                     w->watchpoint_triggered = watch_triggered_yes;
4829                     break;
4830                   }
4831               }
4832             /* Exact match not required.  Within range is sufficient.  */
4833             else if (target_watchpoint_addr_within_range
4834                        (current_inferior ()->top_target (), addr, loc->address,
4835                         loc->length))
4836               {
4837                 w->watchpoint_triggered = watch_triggered_yes;
4838                 break;
4839               }
4840           }
4841       }
4842
4843   return 1;
4844 }
4845
4846 /* Possible return values for watchpoint_check.  */
4847 enum wp_check_result
4848   {
4849     /* The watchpoint has been deleted.  */
4850     WP_DELETED = 1,
4851
4852     /* The value has changed.  */
4853     WP_VALUE_CHANGED = 2,
4854
4855     /* The value has not changed.  */
4856     WP_VALUE_NOT_CHANGED = 3,
4857
4858     /* Ignore this watchpoint, no matter if the value changed or not.  */
4859     WP_IGNORE = 4,
4860   };
4861
4862 #define BP_TEMPFLAG 1
4863 #define BP_HARDWAREFLAG 2
4864
4865 /* Evaluate watchpoint condition expression and check if its value
4866    changed.  */
4867
4868 static wp_check_result
4869 watchpoint_check (bpstat *bs)
4870 {
4871   struct watchpoint *b;
4872   struct frame_info *fr;
4873   int within_current_scope;
4874
4875   /* BS is built from an existing struct breakpoint.  */
4876   gdb_assert (bs->breakpoint_at != NULL);
4877   b = (struct watchpoint *) bs->breakpoint_at;
4878
4879   /* If this is a local watchpoint, we only want to check if the
4880      watchpoint frame is in scope if the current thread is the thread
4881      that was used to create the watchpoint.  */
4882   if (!watchpoint_in_thread_scope (b))
4883     return WP_IGNORE;
4884
4885   if (b->exp_valid_block == NULL)
4886     within_current_scope = 1;
4887   else
4888     {
4889       struct frame_info *frame = get_current_frame ();
4890       struct gdbarch *frame_arch = get_frame_arch (frame);
4891       CORE_ADDR frame_pc = get_frame_pc (frame);
4892
4893       /* stack_frame_destroyed_p() returns a non-zero value if we're
4894          still in the function but the stack frame has already been
4895          invalidated.  Since we can't rely on the values of local
4896          variables after the stack has been destroyed, we are treating
4897          the watchpoint in that state as `not changed' without further
4898          checking.  Don't mark watchpoints as changed if the current
4899          frame is in an epilogue - even if they are in some other
4900          frame, our view of the stack is likely to be wrong and
4901          frame_find_by_id could error out.  */
4902       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4903         return WP_IGNORE;
4904
4905       fr = frame_find_by_id (b->watchpoint_frame);
4906       within_current_scope = (fr != NULL);
4907
4908       /* If we've gotten confused in the unwinder, we might have
4909          returned a frame that can't describe this variable.  */
4910       if (within_current_scope)
4911         {
4912           struct symbol *function;
4913
4914           function = get_frame_function (fr);
4915           if (function == NULL
4916               || !contained_in (b->exp_valid_block,
4917                                 SYMBOL_BLOCK_VALUE (function)))
4918             within_current_scope = 0;
4919         }
4920
4921       if (within_current_scope)
4922         /* If we end up stopping, the current frame will get selected
4923            in normal_stop.  So this call to select_frame won't affect
4924            the user.  */
4925         select_frame (fr);
4926     }
4927
4928   if (within_current_scope)
4929     {
4930       /* We use value_{,free_to_}mark because it could be a *long*
4931          time before we return to the command level and call
4932          free_all_values.  We can't call free_all_values because we
4933          might be in the middle of evaluating a function call.  */
4934
4935       struct value *mark;
4936       struct value *new_val;
4937
4938       if (is_masked_watchpoint (b))
4939         /* Since we don't know the exact trigger address (from
4940            stopped_data_address), just tell the user we've triggered
4941            a mask watchpoint.  */
4942         return WP_VALUE_CHANGED;
4943
4944       mark = value_mark ();
4945       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
4946                           NULL, NULL, false);
4947
4948       if (b->val_bitsize != 0)
4949         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4950
4951       /* We use value_equal_contents instead of value_equal because
4952          the latter coerces an array to a pointer, thus comparing just
4953          the address of the array instead of its contents.  This is
4954          not what we want.  */
4955       if ((b->val != NULL) != (new_val != NULL)
4956           || (b->val != NULL && !value_equal_contents (b->val.get (),
4957                                                        new_val)))
4958         {
4959           bs->old_val = b->val;
4960           b->val = release_value (new_val);
4961           b->val_valid = true;
4962           if (new_val != NULL)
4963             value_free_to_mark (mark);
4964           return WP_VALUE_CHANGED;
4965         }
4966       else
4967         {
4968           /* Nothing changed.  */
4969           value_free_to_mark (mark);
4970           return WP_VALUE_NOT_CHANGED;
4971         }
4972     }
4973   else
4974     {
4975       /* This seems like the only logical thing to do because
4976          if we temporarily ignored the watchpoint, then when
4977          we reenter the block in which it is valid it contains
4978          garbage (in the case of a function, it may have two
4979          garbage values, one before and one after the prologue).
4980          So we can't even detect the first assignment to it and
4981          watch after that (since the garbage may or may not equal
4982          the first value assigned).  */
4983       /* We print all the stop information in
4984          breakpoint_ops->print_it, but in this case, by the time we
4985          call breakpoint_ops->print_it this bp will be deleted
4986          already.  So we have no choice but print the information
4987          here.  */
4988
4989       SWITCH_THRU_ALL_UIS ()
4990         {
4991           struct ui_out *uiout = current_uiout;
4992
4993           if (uiout->is_mi_like_p ())
4994             uiout->field_string
4995               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4996           uiout->message ("\nWatchpoint %pF deleted because the program has "
4997                           "left the block in\n"
4998                           "which its expression is valid.\n",
4999                           signed_field ("wpnum", b->number));
5000         }
5001
5002       /* Make sure the watchpoint's commands aren't executed.  */
5003       b->commands = NULL;
5004       watchpoint_del_at_next_stop (b);
5005
5006       return WP_DELETED;
5007     }
5008 }
5009
5010 /* Return true if it looks like target has stopped due to hitting
5011    breakpoint location BL.  This function does not check if we should
5012    stop, only if BL explains the stop.  */
5013
5014 static int
5015 bpstat_check_location (const struct bp_location *bl,
5016                        const address_space *aspace, CORE_ADDR bp_addr,
5017                        const target_waitstatus &ws)
5018 {
5019   struct breakpoint *b = bl->owner;
5020
5021   /* BL is from an existing breakpoint.  */
5022   gdb_assert (b != NULL);
5023
5024   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5025 }
5026
5027 /* Determine if the watched values have actually changed, and we
5028    should stop.  If not, set BS->stop to 0.  */
5029
5030 static void
5031 bpstat_check_watchpoint (bpstat *bs)
5032 {
5033   const struct bp_location *bl;
5034   struct watchpoint *b;
5035
5036   /* BS is built for existing struct breakpoint.  */
5037   bl = bs->bp_location_at.get ();
5038   gdb_assert (bl != NULL);
5039   b = (struct watchpoint *) bs->breakpoint_at;
5040   gdb_assert (b != NULL);
5041
5042     {
5043       int must_check_value = 0;
5044       
5045       if (b->type == bp_watchpoint)
5046         /* For a software watchpoint, we must always check the
5047            watched value.  */
5048         must_check_value = 1;
5049       else if (b->watchpoint_triggered == watch_triggered_yes)
5050         /* We have a hardware watchpoint (read, write, or access)
5051            and the target earlier reported an address watched by
5052            this watchpoint.  */
5053         must_check_value = 1;
5054       else if (b->watchpoint_triggered == watch_triggered_unknown
5055                && b->type == bp_hardware_watchpoint)
5056         /* We were stopped by a hardware watchpoint, but the target could
5057            not report the data address.  We must check the watchpoint's
5058            value.  Access and read watchpoints are out of luck; without
5059            a data address, we can't figure it out.  */
5060         must_check_value = 1;
5061
5062       if (must_check_value)
5063         {
5064           wp_check_result e;
5065
5066           try
5067             {
5068               e = watchpoint_check (bs);
5069             }
5070           catch (const gdb_exception &ex)
5071             {
5072               exception_fprintf (gdb_stderr, ex,
5073                                  "Error evaluating expression "
5074                                  "for watchpoint %d\n",
5075                                  b->number);
5076
5077               SWITCH_THRU_ALL_UIS ()
5078                 {
5079                   gdb_printf (_("Watchpoint %d deleted.\n"),
5080                               b->number);
5081                 }
5082               watchpoint_del_at_next_stop (b);
5083               e = WP_DELETED;
5084             }
5085
5086           switch (e)
5087             {
5088             case WP_DELETED:
5089               /* We've already printed what needs to be printed.  */
5090               bs->print_it = print_it_done;
5091               /* Stop.  */
5092               break;
5093             case WP_IGNORE:
5094               bs->print_it = print_it_noop;
5095               bs->stop = 0;
5096               break;
5097             case WP_VALUE_CHANGED:
5098               if (b->type == bp_read_watchpoint)
5099                 {
5100                   /* There are two cases to consider here:
5101
5102                      1. We're watching the triggered memory for reads.
5103                      In that case, trust the target, and always report
5104                      the watchpoint hit to the user.  Even though
5105                      reads don't cause value changes, the value may
5106                      have changed since the last time it was read, and
5107                      since we're not trapping writes, we will not see
5108                      those, and as such we should ignore our notion of
5109                      old value.
5110
5111                      2. We're watching the triggered memory for both
5112                      reads and writes.  There are two ways this may
5113                      happen:
5114
5115                      2.1. This is a target that can't break on data
5116                      reads only, but can break on accesses (reads or
5117                      writes), such as e.g., x86.  We detect this case
5118                      at the time we try to insert read watchpoints.
5119
5120                      2.2. Otherwise, the target supports read
5121                      watchpoints, but, the user set an access or write
5122                      watchpoint watching the same memory as this read
5123                      watchpoint.
5124
5125                      If we're watching memory writes as well as reads,
5126                      ignore watchpoint hits when we find that the
5127                      value hasn't changed, as reads don't cause
5128                      changes.  This still gives false positives when
5129                      the program writes the same value to memory as
5130                      what there was already in memory (we will confuse
5131                      it for a read), but it's much better than
5132                      nothing.  */
5133
5134                   int other_write_watchpoint = 0;
5135
5136                   if (bl->watchpoint_type == hw_read)
5137                     {
5138                       for (breakpoint *other_b : all_breakpoints ())
5139                         if (other_b->type == bp_hardware_watchpoint
5140                             || other_b->type == bp_access_watchpoint)
5141                           {
5142                             struct watchpoint *other_w =
5143                               (struct watchpoint *) other_b;
5144
5145                             if (other_w->watchpoint_triggered
5146                                 == watch_triggered_yes)
5147                               {
5148                                 other_write_watchpoint = 1;
5149                                 break;
5150                               }
5151                           }
5152                     }
5153
5154                   if (other_write_watchpoint
5155                       || bl->watchpoint_type == hw_access)
5156                     {
5157                       /* We're watching the same memory for writes,
5158                          and the value changed since the last time we
5159                          updated it, so this trap must be for a write.
5160                          Ignore it.  */
5161                       bs->print_it = print_it_noop;
5162                       bs->stop = 0;
5163                     }
5164                 }
5165               break;
5166             case WP_VALUE_NOT_CHANGED:
5167               if (b->type == bp_hardware_watchpoint
5168                   || b->type == bp_watchpoint)
5169                 {
5170                   /* Don't stop: write watchpoints shouldn't fire if
5171                      the value hasn't changed.  */
5172                   bs->print_it = print_it_noop;
5173                   bs->stop = 0;
5174                 }
5175               /* Stop.  */
5176               break;
5177             default:
5178               /* Can't happen.  */
5179               break;
5180             }
5181         }
5182       else      /* must_check_value == 0 */
5183         {
5184           /* This is a case where some watchpoint(s) triggered, but
5185              not at the address of this watchpoint, or else no
5186              watchpoint triggered after all.  So don't print
5187              anything for this watchpoint.  */
5188           bs->print_it = print_it_noop;
5189           bs->stop = 0;
5190         }
5191     }
5192 }
5193
5194 /* For breakpoints that are currently marked as telling gdb to stop,
5195    check conditions (condition proper, frame, thread and ignore count)
5196    of breakpoint referred to by BS.  If we should not stop for this
5197    breakpoint, set BS->stop to 0.  */
5198
5199 static void
5200 bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
5201 {
5202   const struct bp_location *bl;
5203   struct breakpoint *b;
5204   /* Assume stop.  */
5205   bool condition_result = true;
5206   struct expression *cond;
5207
5208   gdb_assert (bs->stop);
5209
5210   /* BS is built for existing struct breakpoint.  */
5211   bl = bs->bp_location_at.get ();
5212   gdb_assert (bl != NULL);
5213   b = bs->breakpoint_at;
5214   gdb_assert (b != NULL);
5215
5216   /* Even if the target evaluated the condition on its end and notified GDB, we
5217      need to do so again since GDB does not know if we stopped due to a
5218      breakpoint or a single step breakpoint.  */
5219
5220   if (frame_id_p (b->frame_id)
5221       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5222     {
5223       bs->stop = 0;
5224       return;
5225     }
5226
5227   /* If this is a thread/task-specific breakpoint, don't waste cpu
5228      evaluating the condition if this isn't the specified
5229      thread/task.  */
5230   if ((b->thread != -1 && b->thread != thread->global_num)
5231       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5232     {
5233       bs->stop = 0;
5234       return;
5235     }
5236
5237   /* Evaluate extension language breakpoints that have a "stop" method
5238      implemented.  */
5239   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5240
5241   if (is_watchpoint (b))
5242     {
5243       struct watchpoint *w = (struct watchpoint *) b;
5244
5245       cond = w->cond_exp.get ();
5246     }
5247   else
5248     cond = bl->cond.get ();
5249
5250   if (cond && b->disposition != disp_del_at_next_stop)
5251     {
5252       int within_current_scope = 1;
5253       struct watchpoint * w;
5254
5255       /* We use value_mark and value_free_to_mark because it could
5256          be a long time before we return to the command level and
5257          call free_all_values.  We can't call free_all_values
5258          because we might be in the middle of evaluating a
5259          function call.  */
5260       struct value *mark = value_mark ();
5261
5262       if (is_watchpoint (b))
5263         w = (struct watchpoint *) b;
5264       else
5265         w = NULL;
5266
5267       /* Need to select the frame, with all that implies so that
5268          the conditions will have the right context.  Because we
5269          use the frame, we will not see an inlined function's
5270          variables when we arrive at a breakpoint at the start
5271          of the inlined function; the current frame will be the
5272          call site.  */
5273       if (w == NULL || w->cond_exp_valid_block == NULL)
5274         select_frame (get_current_frame ());
5275       else
5276         {
5277           struct frame_info *frame;
5278
5279           /* For local watchpoint expressions, which particular
5280              instance of a local is being watched matters, so we
5281              keep track of the frame to evaluate the expression
5282              in.  To evaluate the condition however, it doesn't
5283              really matter which instantiation of the function
5284              where the condition makes sense triggers the
5285              watchpoint.  This allows an expression like "watch
5286              global if q > 10" set in `func', catch writes to
5287              global on all threads that call `func', or catch
5288              writes on all recursive calls of `func' by a single
5289              thread.  We simply always evaluate the condition in
5290              the innermost frame that's executing where it makes
5291              sense to evaluate the condition.  It seems
5292              intuitive.  */
5293           frame = block_innermost_frame (w->cond_exp_valid_block);
5294           if (frame != NULL)
5295             select_frame (frame);
5296           else
5297             within_current_scope = 0;
5298         }
5299       if (within_current_scope)
5300         {
5301           try
5302             {
5303               condition_result = breakpoint_cond_eval (cond);
5304             }
5305           catch (const gdb_exception &ex)
5306             {
5307               exception_fprintf (gdb_stderr, ex,
5308                                  "Error in testing breakpoint condition:\n");
5309             }
5310         }
5311       else
5312         {
5313           warning (_("Watchpoint condition cannot be tested "
5314                      "in the current scope"));
5315           /* If we failed to set the right context for this
5316              watchpoint, unconditionally report it.  */
5317         }
5318       /* FIXME-someday, should give breakpoint #.  */
5319       value_free_to_mark (mark);
5320     }
5321
5322   if (cond && !condition_result)
5323     {
5324       bs->stop = 0;
5325     }
5326   else if (b->ignore_count > 0)
5327     {
5328       b->ignore_count--;
5329       bs->stop = 0;
5330       /* Increase the hit count even though we don't stop.  */
5331       ++(b->hit_count);
5332       gdb::observers::breakpoint_modified.notify (b);
5333     }   
5334 }
5335
5336 /* Returns true if we need to track moribund locations of LOC's type
5337    on the current target.  */
5338
5339 static int
5340 need_moribund_for_location_type (struct bp_location *loc)
5341 {
5342   return ((loc->loc_type == bp_loc_software_breakpoint
5343            && !target_supports_stopped_by_sw_breakpoint ())
5344           || (loc->loc_type == bp_loc_hardware_breakpoint
5345               && !target_supports_stopped_by_hw_breakpoint ()));
5346 }
5347
5348 /* See breakpoint.h.  */
5349
5350 bpstat *
5351 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5352                     const target_waitstatus &ws)
5353 {
5354   bpstat *bs_head = nullptr, **bs_link = &bs_head;
5355
5356   for (breakpoint *b : all_breakpoints ())
5357     {
5358       if (!breakpoint_enabled (b))
5359         continue;
5360
5361       for (bp_location *bl : b->locations ())
5362         {
5363           /* For hardware watchpoints, we look only at the first
5364              location.  The watchpoint_check function will work on the
5365              entire expression, not the individual locations.  For
5366              read watchpoints, the watchpoints_triggered function has
5367              checked all locations already.  */
5368           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5369             break;
5370
5371           if (!bl->enabled || bl->disabled_by_cond || bl->shlib_disabled)
5372             continue;
5373
5374           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5375             continue;
5376
5377           /* Come here if it's a watchpoint, or if the break address
5378              matches.  */
5379
5380           bpstat *bs = new bpstat (bl, &bs_link);       /* Alloc a bpstat to
5381                                                            explain stop.  */
5382
5383           /* Assume we stop.  Should we find a watchpoint that is not
5384              actually triggered, or if the condition of the breakpoint
5385              evaluates as false, we'll reset 'stop' to 0.  */
5386           bs->stop = 1;
5387           bs->print = 1;
5388
5389           /* If this is a scope breakpoint, mark the associated
5390              watchpoint as triggered so that we will handle the
5391              out-of-scope event.  We'll get to the watchpoint next
5392              iteration.  */
5393           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5394             {
5395               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5396
5397               w->watchpoint_triggered = watch_triggered_yes;
5398             }
5399         }
5400     }
5401
5402   /* Check if a moribund breakpoint explains the stop.  */
5403   if (!target_supports_stopped_by_sw_breakpoint ()
5404       || !target_supports_stopped_by_hw_breakpoint ())
5405     {
5406       for (bp_location *loc : moribund_locations)
5407         {
5408           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5409               && need_moribund_for_location_type (loc))
5410             {
5411               bpstat *bs = new bpstat (loc, &bs_link);
5412               /* For hits of moribund locations, we should just proceed.  */
5413               bs->stop = 0;
5414               bs->print = 0;
5415               bs->print_it = print_it_noop;
5416             }
5417         }
5418     }
5419
5420   return bs_head;
5421 }
5422
5423 /* See breakpoint.h.  */
5424
5425 bpstat *
5426 bpstat_stop_status (const address_space *aspace,
5427                     CORE_ADDR bp_addr, thread_info *thread,
5428                     const target_waitstatus &ws,
5429                     bpstat *stop_chain)
5430 {
5431   struct breakpoint *b = NULL;
5432   /* First item of allocated bpstat's.  */
5433   bpstat *bs_head = stop_chain;
5434   bpstat *bs;
5435   int need_remove_insert;
5436   int removed_any;
5437
5438   /* First, build the bpstat chain with locations that explain a
5439      target stop, while being careful to not set the target running,
5440      as that may invalidate locations (in particular watchpoint
5441      locations are recreated).  Resuming will happen here with
5442      breakpoint conditions or watchpoint expressions that include
5443      inferior function calls.  */
5444   if (bs_head == NULL)
5445     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5446
5447   /* A bit of special processing for shlib breakpoints.  We need to
5448      process solib loading here, so that the lists of loaded and
5449      unloaded libraries are correct before we handle "catch load" and
5450      "catch unload".  */
5451   for (bs = bs_head; bs != NULL; bs = bs->next)
5452     {
5453       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5454         {
5455           handle_solib_event ();
5456           break;
5457         }
5458     }
5459
5460   /* Now go through the locations that caused the target to stop, and
5461      check whether we're interested in reporting this stop to higher
5462      layers, or whether we should resume the target transparently.  */
5463
5464   removed_any = 0;
5465
5466   for (bs = bs_head; bs != NULL; bs = bs->next)
5467     {
5468       if (!bs->stop)
5469         continue;
5470
5471       b = bs->breakpoint_at;
5472       b->ops->check_status (bs);
5473       if (bs->stop)
5474         {
5475           bpstat_check_breakpoint_conditions (bs, thread);
5476
5477           if (bs->stop)
5478             {
5479               ++(b->hit_count);
5480
5481               /* We will stop here.  */
5482               if (b->disposition == disp_disable)
5483                 {
5484                   --(b->enable_count);
5485                   if (b->enable_count <= 0)
5486                     b->enable_state = bp_disabled;
5487                   removed_any = 1;
5488                 }
5489               gdb::observers::breakpoint_modified.notify (b);
5490               if (b->silent)
5491                 bs->print = 0;
5492               bs->commands = b->commands;
5493               if (command_line_is_silent (bs->commands
5494                                           ? bs->commands.get () : NULL))
5495                 bs->print = 0;
5496
5497               b->ops->after_condition_true (bs);
5498             }
5499
5500         }
5501
5502       /* Print nothing for this entry if we don't stop or don't
5503          print.  */
5504       if (!bs->stop || !bs->print)
5505         bs->print_it = print_it_noop;
5506     }
5507
5508   /* If we aren't stopping, the value of some hardware watchpoint may
5509      not have changed, but the intermediate memory locations we are
5510      watching may have.  Don't bother if we're stopping; this will get
5511      done later.  */
5512   need_remove_insert = 0;
5513   if (! bpstat_causes_stop (bs_head))
5514     for (bs = bs_head; bs != NULL; bs = bs->next)
5515       if (!bs->stop
5516           && bs->breakpoint_at
5517           && is_hardware_watchpoint (bs->breakpoint_at))
5518         {
5519           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5520
5521           update_watchpoint (w, 0 /* don't reparse.  */);
5522           need_remove_insert = 1;
5523         }
5524
5525   if (need_remove_insert)
5526     update_global_location_list (UGLL_MAY_INSERT);
5527   else if (removed_any)
5528     update_global_location_list (UGLL_DONT_INSERT);
5529
5530   return bs_head;
5531 }
5532
5533 /* See breakpoint.h.  */
5534
5535 bpstat *
5536 bpstat_stop_status_nowatch (const address_space *aspace, CORE_ADDR bp_addr,
5537                             thread_info *thread, const target_waitstatus &ws)
5538 {
5539   gdb_assert (!target_stopped_by_watchpoint ());
5540
5541   /* Clear all watchpoints' 'watchpoint_triggered' value from a
5542      previous stop to avoid confusing bpstat_stop_status.  */
5543   watchpoints_triggered (ws);
5544
5545   return bpstat_stop_status (aspace, bp_addr, thread, ws);
5546 }
5547
5548 static void
5549 handle_jit_event (CORE_ADDR address)
5550 {
5551   struct gdbarch *gdbarch;
5552
5553   infrun_debug_printf ("handling bp_jit_event");
5554
5555   /* Switch terminal for any messages produced by
5556      breakpoint_re_set.  */
5557   target_terminal::ours_for_output ();
5558
5559   gdbarch = get_frame_arch (get_current_frame ());
5560   /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5561      thus it is expected that its objectfile can be found through
5562      minimal symbol lookup.  If it doesn't work (and assert fails), it
5563      most likely means that `jit_breakpoint_re_set` was changes and this
5564      function needs to be updated too.  */
5565   bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5566   gdb_assert (jit_bp_sym.objfile != nullptr);
5567   jit_event_handler (gdbarch, jit_bp_sym.objfile);
5568
5569   target_terminal::inferior ();
5570 }
5571
5572 /* Prepare WHAT final decision for infrun.  */
5573
5574 /* Decide what infrun needs to do with this bpstat.  */
5575
5576 struct bpstat_what
5577 bpstat_what (bpstat *bs_head)
5578 {
5579   struct bpstat_what retval;
5580   bpstat *bs;
5581
5582   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5583   retval.call_dummy = STOP_NONE;
5584   retval.is_longjmp = false;
5585
5586   for (bs = bs_head; bs != NULL; bs = bs->next)
5587     {
5588       /* Extract this BS's action.  After processing each BS, we check
5589          if its action overrides all we've seem so far.  */
5590       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5591       enum bptype bptype;
5592
5593       if (bs->breakpoint_at == NULL)
5594         {
5595           /* I suspect this can happen if it was a momentary
5596              breakpoint which has since been deleted.  */
5597           bptype = bp_none;
5598         }
5599       else
5600         bptype = bs->breakpoint_at->type;
5601
5602       switch (bptype)
5603         {
5604         case bp_none:
5605           break;
5606         case bp_breakpoint:
5607         case bp_hardware_breakpoint:
5608         case bp_single_step:
5609         case bp_until:
5610         case bp_finish:
5611         case bp_shlib_event:
5612           if (bs->stop)
5613             {
5614               if (bs->print)
5615                 this_action = BPSTAT_WHAT_STOP_NOISY;
5616               else
5617                 this_action = BPSTAT_WHAT_STOP_SILENT;
5618             }
5619           else
5620             this_action = BPSTAT_WHAT_SINGLE;
5621           break;
5622         case bp_watchpoint:
5623         case bp_hardware_watchpoint:
5624         case bp_read_watchpoint:
5625         case bp_access_watchpoint:
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             {
5635               /* There was a watchpoint, but we're not stopping.
5636                  This requires no further action.  */
5637             }
5638           break;
5639         case bp_longjmp:
5640         case bp_longjmp_call_dummy:
5641         case bp_exception:
5642           if (bs->stop)
5643             {
5644               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5645               retval.is_longjmp = bptype != bp_exception;
5646             }
5647           else
5648             this_action = BPSTAT_WHAT_SINGLE;
5649           break;
5650         case bp_longjmp_resume:
5651         case bp_exception_resume:
5652           if (bs->stop)
5653             {
5654               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5655               retval.is_longjmp = bptype == bp_longjmp_resume;
5656             }
5657           else
5658             this_action = BPSTAT_WHAT_SINGLE;
5659           break;
5660         case bp_step_resume:
5661           if (bs->stop)
5662             this_action = BPSTAT_WHAT_STEP_RESUME;
5663           else
5664             {
5665               /* It is for the wrong frame.  */
5666               this_action = BPSTAT_WHAT_SINGLE;
5667             }
5668           break;
5669         case bp_hp_step_resume:
5670           if (bs->stop)
5671             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5672           else
5673             {
5674               /* It is for the wrong frame.  */
5675               this_action = BPSTAT_WHAT_SINGLE;
5676             }
5677           break;
5678         case bp_watchpoint_scope:
5679         case bp_thread_event:
5680         case bp_overlay_event:
5681         case bp_longjmp_master:
5682         case bp_std_terminate_master:
5683         case bp_exception_master:
5684           this_action = BPSTAT_WHAT_SINGLE;
5685           break;
5686         case bp_catchpoint:
5687           if (bs->stop)
5688             {
5689               if (bs->print)
5690                 this_action = BPSTAT_WHAT_STOP_NOISY;
5691               else
5692                 this_action = BPSTAT_WHAT_STOP_SILENT;
5693             }
5694           else
5695             {
5696               /* Some catchpoints are implemented with breakpoints.
5697                  For those, we need to step over the breakpoint.  */
5698               if (bs->bp_location_at->loc_type != bp_loc_other)
5699                 this_action = BPSTAT_WHAT_SINGLE;
5700             }
5701           break;
5702         case bp_jit_event:
5703           this_action = BPSTAT_WHAT_SINGLE;
5704           break;
5705         case bp_call_dummy:
5706           /* Make sure the action is stop (silent or noisy),
5707              so infrun.c pops the dummy frame.  */
5708           retval.call_dummy = STOP_STACK_DUMMY;
5709           this_action = BPSTAT_WHAT_STOP_SILENT;
5710           break;
5711         case bp_std_terminate:
5712           /* Make sure the action is stop (silent or noisy),
5713              so infrun.c pops the dummy frame.  */
5714           retval.call_dummy = STOP_STD_TERMINATE;
5715           this_action = BPSTAT_WHAT_STOP_SILENT;
5716           break;
5717         case bp_tracepoint:
5718         case bp_fast_tracepoint:
5719         case bp_static_tracepoint:
5720           /* Tracepoint hits should not be reported back to GDB, and
5721              if one got through somehow, it should have been filtered
5722              out already.  */
5723           internal_error (__FILE__, __LINE__,
5724                           _("bpstat_what: tracepoint encountered"));
5725           break;
5726         case bp_gnu_ifunc_resolver:
5727           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5728           this_action = BPSTAT_WHAT_SINGLE;
5729           break;
5730         case bp_gnu_ifunc_resolver_return:
5731           /* The breakpoint will be removed, execution will restart from the
5732              PC of the former breakpoint.  */
5733           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5734           break;
5735
5736         case bp_dprintf:
5737           if (bs->stop)
5738             this_action = BPSTAT_WHAT_STOP_SILENT;
5739           else
5740             this_action = BPSTAT_WHAT_SINGLE;
5741           break;
5742
5743         default:
5744           internal_error (__FILE__, __LINE__,
5745                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5746         }
5747
5748       retval.main_action = std::max (retval.main_action, this_action);
5749     }
5750
5751   return retval;
5752 }
5753
5754 void
5755 bpstat_run_callbacks (bpstat *bs_head)
5756 {
5757   bpstat *bs;
5758
5759   for (bs = bs_head; bs != NULL; bs = bs->next)
5760     {
5761       struct breakpoint *b = bs->breakpoint_at;
5762
5763       if (b == NULL)
5764         continue;
5765       switch (b->type)
5766         {
5767         case bp_jit_event:
5768           handle_jit_event (bs->bp_location_at->address);
5769           break;
5770         case bp_gnu_ifunc_resolver:
5771           gnu_ifunc_resolver_stop (b);
5772           break;
5773         case bp_gnu_ifunc_resolver_return:
5774           gnu_ifunc_resolver_return_stop (b);
5775           break;
5776         }
5777     }
5778 }
5779
5780 /* See breakpoint.h.  */
5781
5782 bool
5783 bpstat_should_step ()
5784 {
5785   for (breakpoint *b : all_breakpoints ())
5786     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5787       return true;
5788
5789   return false;
5790 }
5791
5792 /* See breakpoint.h.  */
5793
5794 bool
5795 bpstat_causes_stop (bpstat *bs)
5796 {
5797   for (; bs != NULL; bs = bs->next)
5798     if (bs->stop)
5799       return true;
5800
5801   return false;
5802 }
5803
5804 \f
5805
5806 /* Compute a number of spaces suitable to indent the next line
5807    so it starts at the position corresponding to the table column
5808    named COL_NAME in the currently active table of UIOUT.  */
5809
5810 static int
5811 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5812 {
5813   int i, total_width, width, align;
5814   const char *text;
5815
5816   total_width = 0;
5817   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5818     {
5819       if (strcmp (text, col_name) == 0)
5820         return total_width;
5821
5822       total_width += width + 1;
5823     }
5824
5825   return 0;
5826 }
5827
5828 /* Determine if the locations of this breakpoint will have their conditions
5829    evaluated by the target, host or a mix of both.  Returns the following:
5830
5831     "host": Host evals condition.
5832     "host or target": Host or Target evals condition.
5833     "target": Target evals condition.
5834 */
5835
5836 static const char *
5837 bp_condition_evaluator (struct breakpoint *b)
5838 {
5839   char host_evals = 0;
5840   char target_evals = 0;
5841
5842   if (!b)
5843     return NULL;
5844
5845   if (!is_breakpoint (b))
5846     return NULL;
5847
5848   if (gdb_evaluates_breakpoint_condition_p ()
5849       || !target_supports_evaluation_of_breakpoint_conditions ())
5850     return condition_evaluation_host;
5851
5852   for (bp_location *bl : b->locations ())
5853     {
5854       if (bl->cond_bytecode)
5855         target_evals++;
5856       else
5857         host_evals++;
5858     }
5859
5860   if (host_evals && target_evals)
5861     return condition_evaluation_both;
5862   else if (target_evals)
5863     return condition_evaluation_target;
5864   else
5865     return condition_evaluation_host;
5866 }
5867
5868 /* Determine the breakpoint location's condition evaluator.  This is
5869    similar to bp_condition_evaluator, but for locations.  */
5870
5871 static const char *
5872 bp_location_condition_evaluator (struct bp_location *bl)
5873 {
5874   if (bl && !is_breakpoint (bl->owner))
5875     return NULL;
5876
5877   if (gdb_evaluates_breakpoint_condition_p ()
5878       || !target_supports_evaluation_of_breakpoint_conditions ())
5879     return condition_evaluation_host;
5880
5881   if (bl && bl->cond_bytecode)
5882     return condition_evaluation_target;
5883   else
5884     return condition_evaluation_host;
5885 }
5886
5887 /* Print the LOC location out of the list of B->LOC locations.  */
5888
5889 static void
5890 print_breakpoint_location (struct breakpoint *b,
5891                            struct bp_location *loc)
5892 {
5893   struct ui_out *uiout = current_uiout;
5894
5895   scoped_restore_current_program_space restore_pspace;
5896
5897   if (loc != NULL && loc->shlib_disabled)
5898     loc = NULL;
5899
5900   if (loc != NULL)
5901     set_current_program_space (loc->pspace);
5902
5903   if (b->display_canonical)
5904     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5905   else if (loc && loc->symtab)
5906     {
5907       const struct symbol *sym = loc->symbol;
5908
5909       if (sym)
5910         {
5911           uiout->text ("in ");
5912           uiout->field_string ("func", sym->print_name (),
5913                                function_name_style.style ());
5914           uiout->text (" ");
5915           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5916           uiout->text ("at ");
5917         }
5918       uiout->field_string ("file",
5919                            symtab_to_filename_for_display (loc->symtab),
5920                            file_name_style.style ());
5921       uiout->text (":");
5922
5923       if (uiout->is_mi_like_p ())
5924         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5925       
5926       uiout->field_signed ("line", loc->line_number);
5927     }
5928   else if (loc)
5929     {
5930       string_file stb;
5931
5932       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5933                               demangle, "");
5934       uiout->field_stream ("at", stb);
5935     }
5936   else
5937     {
5938       uiout->field_string ("pending",
5939                            event_location_to_string (b->location.get ()));
5940       /* If extra_string is available, it could be holding a condition
5941          or dprintf arguments.  In either case, make sure it is printed,
5942          too, but only for non-MI streams.  */
5943       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5944         {
5945           if (b->type == bp_dprintf)
5946             uiout->text (",");
5947           else
5948             uiout->text (" ");
5949           uiout->text (b->extra_string.get ());
5950         }
5951     }
5952
5953   if (loc && is_breakpoint (b)
5954       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5955       && bp_condition_evaluator (b) == condition_evaluation_both)
5956     {
5957       uiout->text (" (");
5958       uiout->field_string ("evaluated-by",
5959                            bp_location_condition_evaluator (loc));
5960       uiout->text (")");
5961     }
5962 }
5963
5964 static const char *
5965 bptype_string (enum bptype type)
5966 {
5967   struct ep_type_description
5968     {
5969       enum bptype type;
5970       const char *description;
5971     };
5972   static struct ep_type_description bptypes[] =
5973   {
5974     {bp_none, "?deleted?"},
5975     {bp_breakpoint, "breakpoint"},
5976     {bp_hardware_breakpoint, "hw breakpoint"},
5977     {bp_single_step, "sw single-step"},
5978     {bp_until, "until"},
5979     {bp_finish, "finish"},
5980     {bp_watchpoint, "watchpoint"},
5981     {bp_hardware_watchpoint, "hw watchpoint"},
5982     {bp_read_watchpoint, "read watchpoint"},
5983     {bp_access_watchpoint, "acc watchpoint"},
5984     {bp_longjmp, "longjmp"},
5985     {bp_longjmp_resume, "longjmp resume"},
5986     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5987     {bp_exception, "exception"},
5988     {bp_exception_resume, "exception resume"},
5989     {bp_step_resume, "step resume"},
5990     {bp_hp_step_resume, "high-priority step resume"},
5991     {bp_watchpoint_scope, "watchpoint scope"},
5992     {bp_call_dummy, "call dummy"},
5993     {bp_std_terminate, "std::terminate"},
5994     {bp_shlib_event, "shlib events"},
5995     {bp_thread_event, "thread events"},
5996     {bp_overlay_event, "overlay events"},
5997     {bp_longjmp_master, "longjmp master"},
5998     {bp_std_terminate_master, "std::terminate master"},
5999     {bp_exception_master, "exception master"},
6000     {bp_catchpoint, "catchpoint"},
6001     {bp_tracepoint, "tracepoint"},
6002     {bp_fast_tracepoint, "fast tracepoint"},
6003     {bp_static_tracepoint, "static tracepoint"},
6004     {bp_dprintf, "dprintf"},
6005     {bp_jit_event, "jit events"},
6006     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6007     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6008   };
6009
6010   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6011       || ((int) type != bptypes[(int) type].type))
6012     internal_error (__FILE__, __LINE__,
6013                     _("bptypes table does not describe type #%d."),
6014                     (int) type);
6015
6016   return bptypes[(int) type].description;
6017 }
6018
6019 /* For MI, output a field named 'thread-groups' with a list as the value.
6020    For CLI, prefix the list with the string 'inf'. */
6021
6022 static void
6023 output_thread_groups (struct ui_out *uiout,
6024                       const char *field_name,
6025                       const std::vector<int> &inf_nums,
6026                       int mi_only)
6027 {
6028   int is_mi = uiout->is_mi_like_p ();
6029
6030   /* For backward compatibility, don't display inferiors in CLI unless
6031      there are several.  Always display them for MI. */
6032   if (!is_mi && mi_only)
6033     return;
6034
6035   ui_out_emit_list list_emitter (uiout, field_name);
6036
6037   for (size_t i = 0; i < inf_nums.size (); i++)
6038     {
6039       if (is_mi)
6040         {
6041           char mi_group[10];
6042
6043           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6044           uiout->field_string (NULL, mi_group);
6045         }
6046       else
6047         {
6048           if (i == 0)
6049             uiout->text (" inf ");
6050           else
6051             uiout->text (", ");
6052         
6053           uiout->text (plongest (inf_nums[i]));
6054         }
6055     }
6056 }
6057
6058 /* Print B to gdb_stdout.  If RAW_LOC, print raw breakpoint locations
6059    instead of going via breakpoint_ops::print_one.  This makes "maint
6060    info breakpoints" show the software breakpoint locations of
6061    catchpoints, which are considered internal implementation
6062    detail.  */
6063
6064 static void
6065 print_one_breakpoint_location (struct breakpoint *b,
6066                                struct bp_location *loc,
6067                                int loc_number,
6068                                struct bp_location **last_loc,
6069                                int allflag, bool raw_loc)
6070 {
6071   struct command_line *l;
6072   static char bpenables[] = "nynny";
6073
6074   struct ui_out *uiout = current_uiout;
6075   int header_of_multiple = 0;
6076   int part_of_multiple = (loc != NULL);
6077   struct value_print_options opts;
6078
6079   get_user_print_options (&opts);
6080
6081   gdb_assert (!loc || loc_number != 0);
6082   /* See comment in print_one_breakpoint concerning treatment of
6083      breakpoints with single disabled location.  */
6084   if (loc == NULL 
6085       && (b->loc != NULL 
6086           && (b->loc->next != NULL
6087               || !b->loc->enabled || b->loc->disabled_by_cond)))
6088     header_of_multiple = 1;
6089   if (loc == NULL)
6090     loc = b->loc;
6091
6092   annotate_record ();
6093
6094   /* 1 */
6095   annotate_field (0);
6096   if (part_of_multiple)
6097     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6098   else
6099     uiout->field_signed ("number", b->number);
6100
6101   /* 2 */
6102   annotate_field (1);
6103   if (part_of_multiple)
6104     uiout->field_skip ("type");
6105   else
6106     uiout->field_string ("type", bptype_string (b->type));
6107
6108   /* 3 */
6109   annotate_field (2);
6110   if (part_of_multiple)
6111     uiout->field_skip ("disp");
6112   else
6113     uiout->field_string ("disp", bpdisp_text (b->disposition));
6114
6115   /* 4 */
6116   annotate_field (3);
6117   /* For locations that are disabled because of an invalid condition,
6118      display "N*" on CLI, where "*" refers to a footnote below the
6119      table.  For MI, simply display a "N" without a footnote.  */
6120   const char *N = (uiout->is_mi_like_p ()) ? "N" : "N*";
6121   if (part_of_multiple)
6122     uiout->field_string ("enabled", (loc->disabled_by_cond ? N
6123                                      : (loc->enabled ? "y" : "n")));
6124   else
6125     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6126
6127   /* 5 and 6 */
6128   if (!raw_loc && b->ops != NULL && b->ops->print_one != NULL)
6129     b->ops->print_one (b, last_loc);
6130   else
6131     {
6132       if (is_watchpoint (b))
6133         {
6134           struct watchpoint *w = (struct watchpoint *) b;
6135
6136           /* Field 4, the address, is omitted (which makes the columns
6137              not line up too nicely with the headers, but the effect
6138              is relatively readable).  */
6139           if (opts.addressprint)
6140             uiout->field_skip ("addr");
6141           annotate_field (5);
6142           uiout->field_string ("what", w->exp_string.get ());
6143         }
6144       else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6145                || is_ada_exception_catchpoint (b))
6146         {
6147           if (opts.addressprint)
6148             {
6149               annotate_field (4);
6150               if (header_of_multiple)
6151                 uiout->field_string ("addr", "<MULTIPLE>",
6152                                      metadata_style.style ());
6153               else if (b->loc == NULL || loc->shlib_disabled)
6154                 uiout->field_string ("addr", "<PENDING>",
6155                                      metadata_style.style ());
6156               else
6157                 uiout->field_core_addr ("addr",
6158                                         loc->gdbarch, loc->address);
6159             }
6160           annotate_field (5);
6161           if (!header_of_multiple)
6162             print_breakpoint_location (b, loc);
6163           if (b->loc)
6164             *last_loc = b->loc;
6165         }
6166     }
6167
6168   if (loc != NULL && !header_of_multiple)
6169     {
6170       std::vector<int> inf_nums;
6171       int mi_only = 1;
6172
6173       for (inferior *inf : all_inferiors ())
6174         {
6175           if (inf->pspace == loc->pspace)
6176             inf_nums.push_back (inf->num);
6177         }
6178
6179         /* For backward compatibility, don't display inferiors in CLI unless
6180            there are several.  Always display for MI. */
6181         if (allflag
6182             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6183                 && (program_spaces.size () > 1
6184                     || number_of_inferiors () > 1)
6185                 /* LOC is for existing B, it cannot be in
6186                    moribund_locations and thus having NULL OWNER.  */
6187                 && loc->owner->type != bp_catchpoint))
6188         mi_only = 0;
6189       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6190     }
6191
6192   if (!part_of_multiple)
6193     {
6194       if (b->thread != -1)
6195         {
6196           /* FIXME: This seems to be redundant and lost here; see the
6197              "stop only in" line a little further down.  */
6198           uiout->text (" thread ");
6199           uiout->field_signed ("thread", b->thread);
6200         }
6201       else if (b->task != 0)
6202         {
6203           uiout->text (" task ");
6204           uiout->field_signed ("task", b->task);
6205         }
6206     }
6207
6208   uiout->text ("\n");
6209
6210   if (!part_of_multiple)
6211     b->ops->print_one_detail (b, uiout);
6212
6213   if (part_of_multiple && frame_id_p (b->frame_id))
6214     {
6215       annotate_field (6);
6216       uiout->text ("\tstop only in stack frame at ");
6217       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6218          the frame ID.  */
6219       uiout->field_core_addr ("frame",
6220                               b->gdbarch, b->frame_id.stack_addr);
6221       uiout->text ("\n");
6222     }
6223   
6224   if (!part_of_multiple && b->cond_string)
6225     {
6226       annotate_field (7);
6227       if (is_tracepoint (b))
6228         uiout->text ("\ttrace only if ");
6229       else
6230         uiout->text ("\tstop only if ");
6231       uiout->field_string ("cond", b->cond_string.get ());
6232
6233       /* Print whether the target is doing the breakpoint's condition
6234          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6235       if (is_breakpoint (b)
6236           && breakpoint_condition_evaluation_mode ()
6237           == condition_evaluation_target)
6238         {
6239           uiout->message (" (%pF evals)",
6240                           string_field ("evaluated-by",
6241                                         bp_condition_evaluator (b)));
6242         }
6243       uiout->text ("\n");
6244     }
6245
6246   if (!part_of_multiple && b->thread != -1)
6247     {
6248       /* FIXME should make an annotation for this.  */
6249       uiout->text ("\tstop only in thread ");
6250       if (uiout->is_mi_like_p ())
6251         uiout->field_signed ("thread", b->thread);
6252       else
6253         {
6254           struct thread_info *thr = find_thread_global_id (b->thread);
6255
6256           uiout->field_string ("thread", print_thread_id (thr));
6257         }
6258       uiout->text ("\n");
6259     }
6260   
6261   if (!part_of_multiple)
6262     {
6263       if (b->hit_count)
6264         {
6265           /* FIXME should make an annotation for this.  */
6266           if (is_catchpoint (b))
6267             uiout->text ("\tcatchpoint");
6268           else if (is_tracepoint (b))
6269             uiout->text ("\ttracepoint");
6270           else
6271             uiout->text ("\tbreakpoint");
6272           uiout->text (" already hit ");
6273           uiout->field_signed ("times", b->hit_count);
6274           if (b->hit_count == 1)
6275             uiout->text (" time\n");
6276           else
6277             uiout->text (" times\n");
6278         }
6279       else
6280         {
6281           /* Output the count also if it is zero, but only if this is mi.  */
6282           if (uiout->is_mi_like_p ())
6283             uiout->field_signed ("times", b->hit_count);
6284         }
6285     }
6286
6287   if (!part_of_multiple && b->ignore_count)
6288     {
6289       annotate_field (8);
6290       uiout->message ("\tignore next %pF hits\n",
6291                       signed_field ("ignore", b->ignore_count));
6292     }
6293
6294   /* Note that an enable count of 1 corresponds to "enable once"
6295      behavior, which is reported by the combination of enablement and
6296      disposition, so we don't need to mention it here.  */
6297   if (!part_of_multiple && b->enable_count > 1)
6298     {
6299       annotate_field (8);
6300       uiout->text ("\tdisable after ");
6301       /* Tweak the wording to clarify that ignore and enable counts
6302          are distinct, and have additive effect.  */
6303       if (b->ignore_count)
6304         uiout->text ("additional ");
6305       else
6306         uiout->text ("next ");
6307       uiout->field_signed ("enable", b->enable_count);
6308       uiout->text (" hits\n");
6309     }
6310
6311   if (!part_of_multiple && is_tracepoint (b))
6312     {
6313       struct tracepoint *tp = (struct tracepoint *) b;
6314
6315       if (tp->traceframe_usage)
6316         {
6317           uiout->text ("\ttrace buffer usage ");
6318           uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6319           uiout->text (" bytes\n");
6320         }
6321     }
6322
6323   l = b->commands ? b->commands.get () : NULL;
6324   if (!part_of_multiple && l)
6325     {
6326       annotate_field (9);
6327       ui_out_emit_tuple tuple_emitter (uiout, "script");
6328       print_command_lines (uiout, l, 4);
6329     }
6330
6331   if (is_tracepoint (b))
6332     {
6333       struct tracepoint *t = (struct tracepoint *) b;
6334
6335       if (!part_of_multiple && t->pass_count)
6336         {
6337           annotate_field (10);
6338           uiout->text ("\tpass count ");
6339           uiout->field_signed ("pass", t->pass_count);
6340           uiout->text (" \n");
6341         }
6342
6343       /* Don't display it when tracepoint or tracepoint location is
6344          pending.   */
6345       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6346         {
6347           annotate_field (11);
6348
6349           if (uiout->is_mi_like_p ())
6350             uiout->field_string ("installed",
6351                                  loc->inserted ? "y" : "n");
6352           else
6353             {
6354               if (loc->inserted)
6355                 uiout->text ("\t");
6356               else
6357                 uiout->text ("\tnot ");
6358               uiout->text ("installed on target\n");
6359             }
6360         }
6361     }
6362
6363   if (uiout->is_mi_like_p () && !part_of_multiple)
6364     {
6365       if (is_watchpoint (b))
6366         {
6367           struct watchpoint *w = (struct watchpoint *) b;
6368
6369           uiout->field_string ("original-location", w->exp_string.get ());
6370         }
6371       else if (b->location != NULL
6372                && event_location_to_string (b->location.get ()) != NULL)
6373         uiout->field_string ("original-location",
6374                              event_location_to_string (b->location.get ()));
6375     }
6376 }
6377
6378 /* See breakpoint.h. */
6379
6380 bool fix_multi_location_breakpoint_output_globally = false;
6381
6382 static void
6383 print_one_breakpoint (struct breakpoint *b,
6384                       struct bp_location **last_loc, 
6385                       int allflag)
6386 {
6387   struct ui_out *uiout = current_uiout;
6388   bool use_fixed_output
6389     = (uiout->test_flags (fix_multi_location_breakpoint_output)
6390        || fix_multi_location_breakpoint_output_globally);
6391
6392   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6393   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag, false);
6394
6395   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6396      are outside.  */
6397   if (!use_fixed_output)
6398     bkpt_tuple_emitter.reset ();
6399
6400   /* If this breakpoint has custom print function,
6401      it's already printed.  Otherwise, print individual
6402      locations, if any.  */
6403   if (b->ops == NULL
6404       || b->ops->print_one == NULL
6405       || allflag)
6406     {
6407       /* If breakpoint has a single location that is disabled, we
6408          print it as if it had several locations, since otherwise it's
6409          hard to represent "breakpoint enabled, location disabled"
6410          situation.
6411
6412          Note that while hardware watchpoints have several locations
6413          internally, that's not a property exposed to users.
6414
6415          Likewise, while catchpoints may be implemented with
6416          breakpoints (e.g., catch throw), that's not a property
6417          exposed to users.  We do however display the internal
6418          breakpoint locations with "maint info breakpoints".  */
6419       if (!is_hardware_watchpoint (b)
6420           && (!is_catchpoint (b) || is_exception_catchpoint (b)
6421               || is_ada_exception_catchpoint (b))
6422           && (allflag
6423               || (b->loc && (b->loc->next
6424                              || !b->loc->enabled
6425                              || b->loc->disabled_by_cond))))
6426         {
6427           gdb::optional<ui_out_emit_list> locations_list;
6428
6429           /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6430              MI record.  For later versions, place breakpoint locations in a
6431              list.  */
6432           if (uiout->is_mi_like_p () && use_fixed_output)
6433             locations_list.emplace (uiout, "locations");
6434
6435           int n = 1;
6436           for (bp_location *loc : b->locations ())
6437             {
6438               ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6439               print_one_breakpoint_location (b, loc, n, last_loc,
6440                                              allflag, allflag);
6441               n++;
6442             }
6443         }
6444     }
6445 }
6446
6447 static int
6448 breakpoint_address_bits (struct breakpoint *b)
6449 {
6450   int print_address_bits = 0;
6451
6452   /* Software watchpoints that aren't watching memory don't have an
6453      address to print.  */
6454   if (is_no_memory_software_watchpoint (b))
6455     return 0;
6456
6457   for (bp_location *loc : b->locations ())
6458     {
6459       int addr_bit;
6460
6461       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6462       if (addr_bit > print_address_bits)
6463         print_address_bits = addr_bit;
6464     }
6465
6466   return print_address_bits;
6467 }
6468
6469 /* See breakpoint.h.  */
6470
6471 void
6472 print_breakpoint (breakpoint *b)
6473 {
6474   struct bp_location *dummy_loc = NULL;
6475   print_one_breakpoint (b, &dummy_loc, 0);
6476 }
6477
6478 /* Return true if this breakpoint was set by the user, false if it is
6479    internal or momentary.  */
6480
6481 int
6482 user_breakpoint_p (struct breakpoint *b)
6483 {
6484   return b->number > 0;
6485 }
6486
6487 /* See breakpoint.h.  */
6488
6489 int
6490 pending_breakpoint_p (struct breakpoint *b)
6491 {
6492   return b->loc == NULL;
6493 }
6494
6495 /* Print information on breakpoints (including watchpoints and tracepoints).
6496
6497    If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6498    understood by number_or_range_parser.  Only breakpoints included in this
6499    list are then printed.
6500
6501    If SHOW_INTERNAL is true, print internal breakpoints.
6502
6503    If FILTER is non-NULL, call it on each breakpoint and only include the
6504    ones for which it returns true.
6505
6506    Return the total number of breakpoints listed.  */
6507
6508 static int
6509 breakpoint_1 (const char *bp_num_list, bool show_internal,
6510               bool (*filter) (const struct breakpoint *))
6511 {
6512   struct bp_location *last_loc = NULL;
6513   int nr_printable_breakpoints;
6514   struct value_print_options opts;
6515   int print_address_bits = 0;
6516   int print_type_col_width = 14;
6517   struct ui_out *uiout = current_uiout;
6518   bool has_disabled_by_cond_location = false;
6519
6520   get_user_print_options (&opts);
6521
6522   /* Compute the number of rows in the table, as well as the size
6523      required for address fields.  */
6524   nr_printable_breakpoints = 0;
6525   for (breakpoint *b : all_breakpoints ())
6526     {
6527       /* If we have a filter, only list the breakpoints it accepts.  */
6528       if (filter && !filter (b))
6529         continue;
6530
6531       /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6532          accept.  Skip the others.  */
6533       if (bp_num_list != NULL && *bp_num_list != '\0')
6534         {
6535           if (show_internal && parse_and_eval_long (bp_num_list) != b->number)
6536             continue;
6537           if (!show_internal && !number_is_in_list (bp_num_list, b->number))
6538             continue;
6539         }
6540
6541       if (show_internal || user_breakpoint_p (b))
6542         {
6543           int addr_bit, type_len;
6544
6545           addr_bit = breakpoint_address_bits (b);
6546           if (addr_bit > print_address_bits)
6547             print_address_bits = addr_bit;
6548
6549           type_len = strlen (bptype_string (b->type));
6550           if (type_len > print_type_col_width)
6551             print_type_col_width = type_len;
6552
6553           nr_printable_breakpoints++;
6554         }
6555     }
6556
6557   {
6558     ui_out_emit_table table_emitter (uiout,
6559                                      opts.addressprint ? 6 : 5,
6560                                      nr_printable_breakpoints,
6561                                      "BreakpointTable");
6562
6563     if (nr_printable_breakpoints > 0)
6564       annotate_breakpoints_headers ();
6565     if (nr_printable_breakpoints > 0)
6566       annotate_field (0);
6567     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6568     if (nr_printable_breakpoints > 0)
6569       annotate_field (1);
6570     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6571     if (nr_printable_breakpoints > 0)
6572       annotate_field (2);
6573     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6574     if (nr_printable_breakpoints > 0)
6575       annotate_field (3);
6576     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6577     if (opts.addressprint)
6578       {
6579         if (nr_printable_breakpoints > 0)
6580           annotate_field (4);
6581         if (print_address_bits <= 32)
6582           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6583         else
6584           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6585       }
6586     if (nr_printable_breakpoints > 0)
6587       annotate_field (5);
6588     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6589     uiout->table_body ();
6590     if (nr_printable_breakpoints > 0)
6591       annotate_breakpoints_table ();
6592
6593     for (breakpoint *b : all_breakpoints ())
6594       {
6595         QUIT;
6596         /* If we have a filter, only list the breakpoints it accepts.  */
6597         if (filter && !filter (b))
6598           continue;
6599
6600         /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6601            accept.  Skip the others.  */
6602
6603         if (bp_num_list != NULL && *bp_num_list != '\0')
6604           {
6605             if (show_internal)  /* maintenance info breakpoint */
6606               {
6607                 if (parse_and_eval_long (bp_num_list) != b->number)
6608                   continue;
6609               }
6610             else                /* all others */
6611               {
6612                 if (!number_is_in_list (bp_num_list, b->number))
6613                   continue;
6614               }
6615           }
6616         /* We only print out user settable breakpoints unless the
6617            show_internal is set.  */
6618         if (show_internal || user_breakpoint_p (b))
6619           {
6620             print_one_breakpoint (b, &last_loc, show_internal);
6621             for (bp_location *loc : b->locations ())
6622               if (loc->disabled_by_cond)
6623                 has_disabled_by_cond_location = true;
6624           }
6625       }
6626   }
6627
6628   if (nr_printable_breakpoints == 0)
6629     {
6630       /* If there's a filter, let the caller decide how to report
6631          empty list.  */
6632       if (!filter)
6633         {
6634           if (bp_num_list == NULL || *bp_num_list == '\0')
6635             uiout->message ("No breakpoints or watchpoints.\n");
6636           else
6637             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6638                             bp_num_list);
6639         }
6640     }
6641   else
6642     {
6643       if (last_loc && !server_command)
6644         set_next_address (last_loc->gdbarch, last_loc->address);
6645
6646       if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
6647         uiout->message (_("(*): Breakpoint condition is invalid at this "
6648                           "location.\n"));
6649     }
6650
6651   /* FIXME?  Should this be moved up so that it is only called when
6652      there have been breakpoints? */
6653   annotate_breakpoints_table_end ();
6654
6655   return nr_printable_breakpoints;
6656 }
6657
6658 /* Display the value of default-collect in a way that is generally
6659    compatible with the breakpoint list.  */
6660
6661 static void
6662 default_collect_info (void)
6663 {
6664   struct ui_out *uiout = current_uiout;
6665
6666   /* If it has no value (which is frequently the case), say nothing; a
6667      message like "No default-collect." gets in user's face when it's
6668      not wanted.  */
6669   if (default_collect.empty ())
6670     return;
6671
6672   /* The following phrase lines up nicely with per-tracepoint collect
6673      actions.  */
6674   uiout->text ("default collect ");
6675   uiout->field_string ("default-collect", default_collect);
6676   uiout->text (" \n");
6677 }
6678   
6679 static void
6680 info_breakpoints_command (const char *args, int from_tty)
6681 {
6682   breakpoint_1 (args, false, NULL);
6683
6684   default_collect_info ();
6685 }
6686
6687 static void
6688 info_watchpoints_command (const char *args, int from_tty)
6689 {
6690   int num_printed = breakpoint_1 (args, false, is_watchpoint);
6691   struct ui_out *uiout = current_uiout;
6692
6693   if (num_printed == 0)
6694     {
6695       if (args == NULL || *args == '\0')
6696         uiout->message ("No watchpoints.\n");
6697       else
6698         uiout->message ("No watchpoint matching '%s'.\n", args);
6699     }
6700 }
6701
6702 static void
6703 maintenance_info_breakpoints (const char *args, int from_tty)
6704 {
6705   breakpoint_1 (args, true, NULL);
6706
6707   default_collect_info ();
6708 }
6709
6710 static int
6711 breakpoint_has_pc (struct breakpoint *b,
6712                    struct program_space *pspace,
6713                    CORE_ADDR pc, struct obj_section *section)
6714 {
6715   for (bp_location *bl : b->locations ())
6716     {
6717       if (bl->pspace == pspace
6718           && bl->address == pc
6719           && (!overlay_debugging || bl->section == section))
6720         return 1;         
6721     }
6722   return 0;
6723 }
6724
6725 /* Print a message describing any user-breakpoints set at PC.  This
6726    concerns with logical breakpoints, so we match program spaces, not
6727    address spaces.  */
6728
6729 static void
6730 describe_other_breakpoints (struct gdbarch *gdbarch,
6731                             struct program_space *pspace, CORE_ADDR pc,
6732                             struct obj_section *section, int thread)
6733 {
6734   int others = 0;
6735
6736   for (breakpoint *b : all_breakpoints ())
6737     others += (user_breakpoint_p (b)
6738                && breakpoint_has_pc (b, pspace, pc, section));
6739
6740   if (others > 0)
6741     {
6742       if (others == 1)
6743         gdb_printf (_("Note: breakpoint "));
6744       else /* if (others == ???) */
6745         gdb_printf (_("Note: breakpoints "));
6746       for (breakpoint *b : all_breakpoints ())
6747         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6748           {
6749             others--;
6750             gdb_printf ("%d", b->number);
6751             if (b->thread == -1 && thread != -1)
6752               gdb_printf (" (all threads)");
6753             else if (b->thread != -1)
6754               gdb_printf (" (thread %d)", b->thread);
6755             gdb_printf ("%s%s ",
6756                         ((b->enable_state == bp_disabled
6757                           || b->enable_state == bp_call_disabled)
6758                          ? " (disabled)"
6759                          : ""),
6760                         (others > 1) ? "," 
6761                         : ((others == 1) ? " and" : ""));
6762           }
6763       current_uiout->message (_("also set at pc %ps.\n"),
6764                               styled_string (address_style.style (),
6765                                              paddress (gdbarch, pc)));
6766     }
6767 }
6768 \f
6769
6770 /* Return true iff it is meaningful to use the address member of LOC.
6771    For some breakpoint types, the locations' address members are
6772    irrelevant and it makes no sense to attempt to compare them to
6773    other addresses (or use them for any other purpose either).
6774
6775    More specifically, software watchpoints and catchpoints that are
6776    not backed by breakpoints always have a zero valued location
6777    address and we don't want to mark breakpoints of any of these types
6778    to be a duplicate of an actual breakpoint location at address
6779    zero.  */
6780
6781 static bool
6782 bl_address_is_meaningful (bp_location *loc)
6783 {
6784   return loc->loc_type != bp_loc_other;
6785 }
6786
6787 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6788    true if LOC1 and LOC2 represent the same watchpoint location.  */
6789
6790 static int
6791 watchpoint_locations_match (struct bp_location *loc1, 
6792                             struct bp_location *loc2)
6793 {
6794   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6795   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6796
6797   /* Both of them must exist.  */
6798   gdb_assert (w1 != NULL);
6799   gdb_assert (w2 != NULL);
6800
6801   /* If the target can evaluate the condition expression in hardware,
6802      then we we need to insert both watchpoints even if they are at
6803      the same place.  Otherwise the watchpoint will only trigger when
6804      the condition of whichever watchpoint was inserted evaluates to
6805      true, not giving a chance for GDB to check the condition of the
6806      other watchpoint.  */
6807   if ((w1->cond_exp
6808        && target_can_accel_watchpoint_condition (loc1->address, 
6809                                                  loc1->length,
6810                                                  loc1->watchpoint_type,
6811                                                  w1->cond_exp.get ()))
6812       || (w2->cond_exp
6813           && target_can_accel_watchpoint_condition (loc2->address, 
6814                                                     loc2->length,
6815                                                     loc2->watchpoint_type,
6816                                                     w2->cond_exp.get ())))
6817     return 0;
6818
6819   /* Note that this checks the owner's type, not the location's.  In
6820      case the target does not support read watchpoints, but does
6821      support access watchpoints, we'll have bp_read_watchpoint
6822      watchpoints with hw_access locations.  Those should be considered
6823      duplicates of hw_read locations.  The hw_read locations will
6824      become hw_access locations later.  */
6825   return (loc1->owner->type == loc2->owner->type
6826           && loc1->pspace->aspace == loc2->pspace->aspace
6827           && loc1->address == loc2->address
6828           && loc1->length == loc2->length);
6829 }
6830
6831 /* See breakpoint.h.  */
6832
6833 int
6834 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6835                           const address_space *aspace2, CORE_ADDR addr2)
6836 {
6837   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6838            || aspace1 == aspace2)
6839           && addr1 == addr2);
6840 }
6841
6842 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6843    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6844    matches ASPACE2.  On targets that have global breakpoints, the address
6845    space doesn't really matter.  */
6846
6847 static int
6848 breakpoint_address_match_range (const address_space *aspace1,
6849                                 CORE_ADDR addr1,
6850                                 int len1, const address_space *aspace2,
6851                                 CORE_ADDR addr2)
6852 {
6853   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6854            || aspace1 == aspace2)
6855           && addr2 >= addr1 && addr2 < addr1 + len1);
6856 }
6857
6858 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6859    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6860    matches the breakpoint's address space.  On targets that have global
6861    breakpoints, the address space doesn't really matter.  */
6862
6863 static int
6864 breakpoint_location_address_match (struct bp_location *bl,
6865                                    const address_space *aspace,
6866                                    CORE_ADDR addr)
6867 {
6868   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6869                                     aspace, addr)
6870           || (bl->length
6871               && breakpoint_address_match_range (bl->pspace->aspace,
6872                                                  bl->address, bl->length,
6873                                                  aspace, addr)));
6874 }
6875
6876 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6877    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6878    match happens only if ASPACE matches the breakpoint's address
6879    space.  On targets that have global breakpoints, the address space
6880    doesn't really matter.  */
6881
6882 static int
6883 breakpoint_location_address_range_overlap (struct bp_location *bl,
6884                                            const address_space *aspace,
6885                                            CORE_ADDR addr, int len)
6886 {
6887   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6888       || bl->pspace->aspace == aspace)
6889     {
6890       int bl_len = bl->length != 0 ? bl->length : 1;
6891
6892       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6893         return 1;
6894     }
6895   return 0;
6896 }
6897
6898 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6899    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6900    true, otherwise returns false.  */
6901
6902 static int
6903 tracepoint_locations_match (struct bp_location *loc1,
6904                             struct bp_location *loc2)
6905 {
6906   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6907     /* Since tracepoint locations are never duplicated with others', tracepoint
6908        locations at the same address of different tracepoints are regarded as
6909        different locations.  */
6910     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6911   else
6912     return 0;
6913 }
6914
6915 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6916    (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
6917    the same location.  If SW_HW_BPS_MATCH is true, then software
6918    breakpoint locations and hardware breakpoint locations match,
6919    otherwise they don't.  */
6920
6921 static int
6922 breakpoint_locations_match (struct bp_location *loc1,
6923                             struct bp_location *loc2,
6924                             bool sw_hw_bps_match)
6925 {
6926   int hw_point1, hw_point2;
6927
6928   /* Both of them must not be in moribund_locations.  */
6929   gdb_assert (loc1->owner != NULL);
6930   gdb_assert (loc2->owner != NULL);
6931
6932   hw_point1 = is_hardware_watchpoint (loc1->owner);
6933   hw_point2 = is_hardware_watchpoint (loc2->owner);
6934
6935   if (hw_point1 != hw_point2)
6936     return 0;
6937   else if (hw_point1)
6938     return watchpoint_locations_match (loc1, loc2);
6939   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6940     return tracepoint_locations_match (loc1, loc2);
6941   else
6942     /* We compare bp_location.length in order to cover ranged
6943        breakpoints.  Keep this in sync with
6944        bp_location_is_less_than.  */
6945     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6946                                      loc2->pspace->aspace, loc2->address)
6947             && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
6948             && loc1->length == loc2->length);
6949 }
6950
6951 static void
6952 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6953                                int bnum, int have_bnum)
6954 {
6955   /* The longest string possibly returned by hex_string_custom
6956      is 50 chars.  These must be at least that big for safety.  */
6957   char astr1[64];
6958   char astr2[64];
6959
6960   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6961   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6962   if (have_bnum)
6963     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6964              bnum, astr1, astr2);
6965   else
6966     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6967 }
6968
6969 /* Adjust a breakpoint's address to account for architectural
6970    constraints on breakpoint placement.  Return the adjusted address.
6971    Note: Very few targets require this kind of adjustment.  For most
6972    targets, this function is simply the identity function.  */
6973
6974 static CORE_ADDR
6975 adjust_breakpoint_address (struct gdbarch *gdbarch,
6976                            CORE_ADDR bpaddr, enum bptype bptype)
6977 {
6978   if (bptype == bp_watchpoint
6979       || bptype == bp_hardware_watchpoint
6980       || bptype == bp_read_watchpoint
6981       || bptype == bp_access_watchpoint
6982       || bptype == bp_catchpoint)
6983     {
6984       /* Watchpoints and the various bp_catch_* eventpoints should not
6985          have their addresses modified.  */
6986       return bpaddr;
6987     }
6988   else if (bptype == bp_single_step)
6989     {
6990       /* Single-step breakpoints should not have their addresses
6991          modified.  If there's any architectural constrain that
6992          applies to this address, then it should have already been
6993          taken into account when the breakpoint was created in the
6994          first place.  If we didn't do this, stepping through e.g.,
6995          Thumb-2 IT blocks would break.  */
6996       return bpaddr;
6997     }
6998   else
6999     {
7000       CORE_ADDR adjusted_bpaddr = bpaddr;
7001
7002       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7003         {
7004           /* Some targets have architectural constraints on the placement
7005              of breakpoint instructions.  Obtain the adjusted address.  */
7006           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7007         }
7008
7009       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
7010
7011       /* An adjusted breakpoint address can significantly alter
7012          a user's expectations.  Print a warning if an adjustment
7013          is required.  */
7014       if (adjusted_bpaddr != bpaddr)
7015         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7016
7017       return adjusted_bpaddr;
7018     }
7019 }
7020
7021 static bp_loc_type
7022 bp_location_from_bp_type (bptype type)
7023 {
7024   switch (type)
7025     {
7026     case bp_breakpoint:
7027     case bp_single_step:
7028     case bp_until:
7029     case bp_finish:
7030     case bp_longjmp:
7031     case bp_longjmp_resume:
7032     case bp_longjmp_call_dummy:
7033     case bp_exception:
7034     case bp_exception_resume:
7035     case bp_step_resume:
7036     case bp_hp_step_resume:
7037     case bp_watchpoint_scope:
7038     case bp_call_dummy:
7039     case bp_std_terminate:
7040     case bp_shlib_event:
7041     case bp_thread_event:
7042     case bp_overlay_event:
7043     case bp_jit_event:
7044     case bp_longjmp_master:
7045     case bp_std_terminate_master:
7046     case bp_exception_master:
7047     case bp_gnu_ifunc_resolver:
7048     case bp_gnu_ifunc_resolver_return:
7049     case bp_dprintf:
7050       return bp_loc_software_breakpoint;
7051     case bp_hardware_breakpoint:
7052       return bp_loc_hardware_breakpoint;
7053     case bp_hardware_watchpoint:
7054     case bp_read_watchpoint:
7055     case bp_access_watchpoint:
7056       return bp_loc_hardware_watchpoint;
7057     case bp_watchpoint:
7058     case bp_catchpoint:
7059     case bp_tracepoint:
7060     case bp_fast_tracepoint:
7061     case bp_static_tracepoint:
7062       return bp_loc_other;
7063     default:
7064       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7065     }
7066 }
7067
7068 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7069 {
7070   this->owner = owner;
7071   this->cond_bytecode = NULL;
7072   this->shlib_disabled = 0;
7073   this->enabled = 1;
7074   this->disabled_by_cond = false;
7075
7076   this->loc_type = type;
7077
7078   if (this->loc_type == bp_loc_software_breakpoint
7079       || this->loc_type == bp_loc_hardware_breakpoint)
7080     mark_breakpoint_location_modified (this);
7081
7082   incref ();
7083 }
7084
7085 bp_location::bp_location (breakpoint *owner)
7086   : bp_location::bp_location (owner,
7087                               bp_location_from_bp_type (owner->type))
7088 {
7089 }
7090
7091 /* Allocate a struct bp_location.  */
7092
7093 static struct bp_location *
7094 allocate_bp_location (struct breakpoint *bpt)
7095 {
7096   return bpt->ops->allocate_location (bpt);
7097 }
7098
7099 /* Decrement reference count.  If the reference count reaches 0,
7100    destroy the bp_location.  Sets *BLP to NULL.  */
7101
7102 static void
7103 decref_bp_location (struct bp_location **blp)
7104 {
7105   bp_location_ref_policy::decref (*blp);
7106   *blp = NULL;
7107 }
7108
7109 /* Add breakpoint B at the end of the global breakpoint chain.  */
7110
7111 static breakpoint *
7112 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7113 {
7114   struct breakpoint *b1;
7115   struct breakpoint *result = b.get ();
7116
7117   /* Add this breakpoint to the end of the chain so that a list of
7118      breakpoints will come out in order of increasing numbers.  */
7119
7120   b1 = breakpoint_chain;
7121   if (b1 == 0)
7122     breakpoint_chain = b.release ();
7123   else
7124     {
7125       while (b1->next)
7126         b1 = b1->next;
7127       b1->next = b.release ();
7128     }
7129
7130   return result;
7131 }
7132
7133 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7134
7135 static void
7136 init_raw_breakpoint_without_location (struct breakpoint *b,
7137                                       struct gdbarch *gdbarch,
7138                                       enum bptype bptype,
7139                                       const struct breakpoint_ops *ops)
7140 {
7141   gdb_assert (ops != NULL);
7142
7143   b->ops = ops;
7144   b->type = bptype;
7145   b->gdbarch = gdbarch;
7146   b->language = current_language->la_language;
7147   b->input_radix = input_radix;
7148   b->related_breakpoint = b;
7149 }
7150
7151 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7152    that has type BPTYPE and has no locations as yet.  */
7153
7154 static struct breakpoint *
7155 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7156                                      enum bptype bptype,
7157                                      const struct breakpoint_ops *ops)
7158 {
7159   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7160
7161   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7162   return add_to_breakpoint_chain (std::move (b));
7163 }
7164
7165 /* Initialize loc->function_name.  */
7166
7167 static void
7168 set_breakpoint_location_function (struct bp_location *loc)
7169 {
7170   gdb_assert (loc->owner != NULL);
7171
7172   if (loc->owner->type == bp_breakpoint
7173       || loc->owner->type == bp_hardware_breakpoint
7174       || is_tracepoint (loc->owner))
7175     {
7176       const char *function_name;
7177
7178       if (loc->msymbol != NULL
7179           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7180               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc))
7181         {
7182           struct breakpoint *b = loc->owner;
7183
7184           function_name = loc->msymbol->linkage_name ();
7185
7186           if (b->type == bp_breakpoint && b->loc == loc
7187               && loc->next == NULL && b->related_breakpoint == b)
7188             {
7189               /* Create only the whole new breakpoint of this type but do not
7190                  mess more complicated breakpoints with multiple locations.  */
7191               b->type = bp_gnu_ifunc_resolver;
7192               /* Remember the resolver's address for use by the return
7193                  breakpoint.  */
7194               loc->related_address = loc->address;
7195             }
7196         }
7197       else
7198         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7199
7200       if (function_name)
7201         loc->function_name = make_unique_xstrdup (function_name);
7202     }
7203 }
7204
7205 /* Attempt to determine architecture of location identified by SAL.  */
7206 struct gdbarch *
7207 get_sal_arch (struct symtab_and_line sal)
7208 {
7209   if (sal.section)
7210     return sal.section->objfile->arch ();
7211   if (sal.symtab)
7212     return sal.symtab->objfile ()->arch ();
7213
7214   return NULL;
7215 }
7216
7217 /* Low level routine for partially initializing a breakpoint of type
7218    BPTYPE.  The newly created breakpoint's address, section, source
7219    file name, and line number are provided by SAL.
7220
7221    It is expected that the caller will complete the initialization of
7222    the newly created breakpoint struct as well as output any status
7223    information regarding the creation of a new breakpoint.  */
7224
7225 static void
7226 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7227                      struct symtab_and_line sal, enum bptype bptype,
7228                      const struct breakpoint_ops *ops)
7229 {
7230   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7231
7232   add_location_to_breakpoint (b, &sal);
7233
7234   if (bptype != bp_catchpoint)
7235     gdb_assert (sal.pspace != NULL);
7236
7237   /* Store the program space that was used to set the breakpoint,
7238      except for ordinary breakpoints, which are independent of the
7239      program space.  */
7240   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7241     b->pspace = sal.pspace;
7242 }
7243
7244 /* set_raw_breakpoint is a low level routine for allocating and
7245    partially initializing a breakpoint of type BPTYPE.  The newly
7246    created breakpoint's address, section, source file name, and line
7247    number are provided by SAL.  The newly created and partially
7248    initialized breakpoint is added to the breakpoint chain and
7249    is also returned as the value of this function.
7250
7251    It is expected that the caller will complete the initialization of
7252    the newly created breakpoint struct as well as output any status
7253    information regarding the creation of a new breakpoint.  In
7254    particular, set_raw_breakpoint does NOT set the breakpoint
7255    number!  Care should be taken to not allow an error to occur
7256    prior to completing the initialization of the breakpoint.  If this
7257    should happen, a bogus breakpoint will be left on the chain.  */
7258
7259 static struct breakpoint *
7260 set_raw_breakpoint (struct gdbarch *gdbarch,
7261                     struct symtab_and_line sal, enum bptype bptype,
7262                     const struct breakpoint_ops *ops)
7263 {
7264   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7265
7266   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7267   return add_to_breakpoint_chain (std::move (b));
7268 }
7269
7270 /* Call this routine when stepping and nexting to enable a breakpoint
7271    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7272    initiated the operation.  */
7273
7274 void
7275 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7276 {
7277   int thread = tp->global_num;
7278
7279   /* To avoid having to rescan all objfile symbols at every step,
7280      we maintain a list of continually-inserted but always disabled
7281      longjmp "master" breakpoints.  Here, we simply create momentary
7282      clones of those and enable them for the requested thread.  */
7283   for (breakpoint *b : all_breakpoints_safe ())
7284     if (b->pspace == current_program_space
7285         && (b->type == bp_longjmp_master
7286             || b->type == bp_exception_master))
7287       {
7288         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7289         struct breakpoint *clone;
7290
7291         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7292            after their removal.  */
7293         clone = momentary_breakpoint_from_master (b, type,
7294                                                   &momentary_breakpoint_ops, 1);
7295         clone->thread = thread;
7296       }
7297
7298   tp->initiating_frame = frame;
7299 }
7300
7301 /* Delete all longjmp breakpoints from THREAD.  */
7302 void
7303 delete_longjmp_breakpoint (int thread)
7304 {
7305   for (breakpoint *b : all_breakpoints_safe ())
7306     if (b->type == bp_longjmp || b->type == bp_exception)
7307       {
7308         if (b->thread == thread)
7309           delete_breakpoint (b);
7310       }
7311 }
7312
7313 void
7314 delete_longjmp_breakpoint_at_next_stop (int thread)
7315 {
7316   for (breakpoint *b : all_breakpoints_safe ())
7317     if (b->type == bp_longjmp || b->type == bp_exception)
7318       {
7319         if (b->thread == thread)
7320           b->disposition = disp_del_at_next_stop;
7321       }
7322 }
7323
7324 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7325    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7326    pointer to any of them.  Return NULL if this system cannot place longjmp
7327    breakpoints.  */
7328
7329 struct breakpoint *
7330 set_longjmp_breakpoint_for_call_dummy (void)
7331 {
7332   breakpoint *retval = nullptr;
7333
7334   for (breakpoint *b : all_breakpoints ())
7335     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7336       {
7337         struct breakpoint *new_b;
7338
7339         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7340                                                   &momentary_breakpoint_ops,
7341                                                   1);
7342         new_b->thread = inferior_thread ()->global_num;
7343
7344         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7345
7346         gdb_assert (new_b->related_breakpoint == new_b);
7347         if (retval == NULL)
7348           retval = new_b;
7349         new_b->related_breakpoint = retval;
7350         while (retval->related_breakpoint != new_b->related_breakpoint)
7351           retval = retval->related_breakpoint;
7352         retval->related_breakpoint = new_b;
7353       }
7354
7355   return retval;
7356 }
7357
7358 /* Verify all existing dummy frames and their associated breakpoints for
7359    TP.  Remove those which can no longer be found in the current frame
7360    stack.
7361
7362    If the unwind fails then there is not sufficient information to discard
7363    dummy frames.  In this case, elide the clean up and the dummy frames will
7364    be cleaned up next time this function is called from a location where
7365    unwinding is possible.  */
7366
7367 void
7368 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7369 {
7370   struct breakpoint *b, *b_tmp;
7371
7372   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7373     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7374       {
7375         struct breakpoint *dummy_b = b->related_breakpoint;
7376
7377         /* Find the bp_call_dummy breakpoint in the list of breakpoints
7378            chained off b->related_breakpoint.  */
7379         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7380           dummy_b = dummy_b->related_breakpoint;
7381
7382         /* If there was no bp_call_dummy breakpoint then there's nothing
7383            more to do.  Or, if the dummy frame associated with the
7384            bp_call_dummy is still on the stack then we need to leave this
7385            bp_call_dummy in place.  */
7386         if (dummy_b->type != bp_call_dummy
7387             || frame_find_by_id (dummy_b->frame_id) != NULL)
7388           continue;
7389
7390         /* We didn't find the dummy frame on the stack, this could be
7391            because we have longjmp'd to a stack frame that is previous to
7392            the dummy frame, or it could be because the stack unwind is
7393            broken at some point between the longjmp frame and the dummy
7394            frame.
7395
7396            Next we figure out why the stack unwind stopped.  If it looks
7397            like the unwind is complete then we assume the dummy frame has
7398            been jumped over, however, if the unwind stopped for an
7399            unexpected reason then we assume the stack unwind is currently
7400            broken, and that we will (eventually) return to the dummy
7401            frame.
7402
7403            It might be tempting to consider using frame_id_inner here, but
7404            that is not safe.   There is no guarantee that the stack frames
7405            we are looking at here are even on the same stack as the
7406            original dummy frame, hence frame_id_inner can't be used.  See
7407            the comments on frame_id_inner for more details.  */
7408         bool unwind_finished_unexpectedly = false;
7409         for (struct frame_info *fi = get_current_frame (); fi != nullptr; )
7410           {
7411             struct frame_info *prev = get_prev_frame (fi);
7412             if (prev == nullptr)
7413               {
7414                 /* FI is the last stack frame.  Why did this frame not
7415                    unwind further?  */
7416                 auto stop_reason = get_frame_unwind_stop_reason (fi);
7417                 if (stop_reason != UNWIND_NO_REASON
7418                     && stop_reason != UNWIND_OUTERMOST)
7419                   unwind_finished_unexpectedly = true;
7420               }
7421             fi = prev;
7422           }
7423         if (unwind_finished_unexpectedly)
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   for (breakpoint *b : all_breakpoints ())
7442     if (b->type == bp_overlay_event)
7443       {
7444         b->enable_state = bp_enabled;
7445         update_global_location_list (UGLL_MAY_INSERT);
7446         overlay_events_enabled = 1;
7447       }
7448 }
7449
7450 void
7451 disable_overlay_breakpoints (void)
7452 {
7453   for (breakpoint *b : all_breakpoints ())
7454     if (b->type == bp_overlay_event)
7455       {
7456         b->enable_state = bp_disabled;
7457         update_global_location_list (UGLL_DONT_INSERT);
7458         overlay_events_enabled = 0;
7459       }
7460 }
7461
7462 /* Set an active std::terminate breakpoint for each std::terminate
7463    master breakpoint.  */
7464 void
7465 set_std_terminate_breakpoint (void)
7466 {
7467   for (breakpoint *b : all_breakpoints_safe ())
7468     if (b->pspace == current_program_space
7469         && b->type == bp_std_terminate_master)
7470       {
7471         momentary_breakpoint_from_master (b, bp_std_terminate,
7472                                           &momentary_breakpoint_ops, 1);
7473       }
7474 }
7475
7476 /* Delete all the std::terminate breakpoints.  */
7477 void
7478 delete_std_terminate_breakpoint (void)
7479 {
7480   for (breakpoint *b : all_breakpoints_safe ())
7481     if (b->type == bp_std_terminate)
7482       delete_breakpoint (b);
7483 }
7484
7485 struct breakpoint *
7486 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7487 {
7488   struct breakpoint *b;
7489
7490   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7491                                   &internal_breakpoint_ops);
7492
7493   b->enable_state = bp_enabled;
7494   /* location has to be used or breakpoint_re_set will delete me.  */
7495   b->location = new_address_location (b->loc->address, NULL, 0);
7496
7497   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7498
7499   return b;
7500 }
7501
7502 struct lang_and_radix
7503   {
7504     enum language lang;
7505     int radix;
7506   };
7507
7508 /* Create a breakpoint for JIT code registration and unregistration.  */
7509
7510 struct breakpoint *
7511 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7512 {
7513   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7514                                      &internal_breakpoint_ops);
7515 }
7516
7517 /* Remove JIT code registration and unregistration breakpoint(s).  */
7518
7519 void
7520 remove_jit_event_breakpoints (void)
7521 {
7522   for (breakpoint *b : all_breakpoints_safe ())
7523     if (b->type == bp_jit_event
7524         && b->loc->pspace == current_program_space)
7525       delete_breakpoint (b);
7526 }
7527
7528 void
7529 remove_solib_event_breakpoints (void)
7530 {
7531   for (breakpoint *b : all_breakpoints_safe ())
7532     if (b->type == bp_shlib_event
7533         && b->loc->pspace == current_program_space)
7534       delete_breakpoint (b);
7535 }
7536
7537 /* See breakpoint.h.  */
7538
7539 void
7540 remove_solib_event_breakpoints_at_next_stop (void)
7541 {
7542   for (breakpoint *b : all_breakpoints_safe ())
7543     if (b->type == bp_shlib_event
7544         && b->loc->pspace == current_program_space)
7545       b->disposition = disp_del_at_next_stop;
7546 }
7547
7548 /* Helper for create_solib_event_breakpoint /
7549    create_and_insert_solib_event_breakpoint.  Allows specifying which
7550    INSERT_MODE to pass through to update_global_location_list.  */
7551
7552 static struct breakpoint *
7553 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7554                                  enum ugll_insert_mode insert_mode)
7555 {
7556   struct breakpoint *b;
7557
7558   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7559                                   &internal_breakpoint_ops);
7560   update_global_location_list_nothrow (insert_mode);
7561   return b;
7562 }
7563
7564 struct breakpoint *
7565 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7566 {
7567   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7568 }
7569
7570 /* See breakpoint.h.  */
7571
7572 struct breakpoint *
7573 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7574 {
7575   struct breakpoint *b;
7576
7577   /* Explicitly tell update_global_location_list to insert
7578      locations.  */
7579   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7580   if (!b->loc->inserted)
7581     {
7582       delete_breakpoint (b);
7583       return NULL;
7584     }
7585   return b;
7586 }
7587
7588 /* Disable any breakpoints that are on code in shared libraries.  Only
7589    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7590
7591 void
7592 disable_breakpoints_in_shlibs (void)
7593 {
7594   for (bp_location *loc : all_bp_locations ())
7595     {
7596       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7597       struct breakpoint *b = loc->owner;
7598
7599       /* We apply the check to all breakpoints, including disabled for
7600          those with loc->duplicate set.  This is so that when breakpoint
7601          becomes enabled, or the duplicate is removed, gdb will try to
7602          insert all breakpoints.  If we don't set shlib_disabled here,
7603          we'll try to insert those breakpoints and fail.  */
7604       if (((b->type == bp_breakpoint)
7605            || (b->type == bp_jit_event)
7606            || (b->type == bp_hardware_breakpoint)
7607            || (is_tracepoint (b)))
7608           && loc->pspace == current_program_space
7609           && !loc->shlib_disabled
7610           && solib_name_from_address (loc->pspace, loc->address)
7611           )
7612         {
7613           loc->shlib_disabled = 1;
7614         }
7615     }
7616 }
7617
7618 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7619    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7620    disabled ones can just stay disabled.  */
7621
7622 static void
7623 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7624 {
7625   int disabled_shlib_breaks = 0;
7626
7627   for (bp_location *loc : all_bp_locations ())
7628     {
7629       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7630       struct breakpoint *b = loc->owner;
7631
7632       if (solib->pspace == loc->pspace
7633           && !loc->shlib_disabled
7634           && (((b->type == bp_breakpoint
7635                 || b->type == bp_jit_event
7636                 || b->type == bp_hardware_breakpoint)
7637                && (loc->loc_type == bp_loc_hardware_breakpoint
7638                    || loc->loc_type == bp_loc_software_breakpoint))
7639               || is_tracepoint (b))
7640           && solib_contains_address_p (solib, loc->address))
7641         {
7642           loc->shlib_disabled = 1;
7643           /* At this point, we cannot rely on remove_breakpoint
7644              succeeding so we must mark the breakpoint as not inserted
7645              to prevent future errors occurring in remove_breakpoints.  */
7646           loc->inserted = 0;
7647
7648           /* This may cause duplicate notifications for the same breakpoint.  */
7649           gdb::observers::breakpoint_modified.notify (b);
7650
7651           if (!disabled_shlib_breaks)
7652             {
7653               target_terminal::ours_for_output ();
7654               warning (_("Temporarily disabling breakpoints "
7655                          "for unloaded shared library \"%s\""),
7656                        solib->so_name);
7657             }
7658           disabled_shlib_breaks = 1;
7659         }
7660     }
7661 }
7662
7663 /* Disable any breakpoints and tracepoints in OBJFILE upon
7664    notification of free_objfile.  Only apply to enabled breakpoints,
7665    disabled ones can just stay disabled.  */
7666
7667 static void
7668 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7669 {
7670   if (objfile == NULL)
7671     return;
7672
7673   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7674      managed by the user with add-symbol-file/remove-symbol-file.
7675      Similarly to how breakpoints in shared libraries are handled in
7676      response to "nosharedlibrary", mark breakpoints in such modules
7677      shlib_disabled so they end up uninserted on the next global
7678      location list update.  Shared libraries not loaded by the user
7679      aren't handled here -- they're already handled in
7680      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7681      solib_unloaded observer.  We skip objfiles that are not
7682      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7683      main objfile).  */
7684   if ((objfile->flags & OBJF_SHARED) == 0
7685       || (objfile->flags & OBJF_USERLOADED) == 0)
7686     return;
7687
7688   for (breakpoint *b : all_breakpoints ())
7689     {
7690       int bp_modified = 0;
7691
7692       if (!is_breakpoint (b) && !is_tracepoint (b))
7693         continue;
7694
7695       for (bp_location *loc : b->locations ())
7696         {
7697           CORE_ADDR loc_addr = loc->address;
7698
7699           if (loc->loc_type != bp_loc_hardware_breakpoint
7700               && loc->loc_type != bp_loc_software_breakpoint)
7701             continue;
7702
7703           if (loc->shlib_disabled != 0)
7704             continue;
7705
7706           if (objfile->pspace != loc->pspace)
7707             continue;
7708
7709           if (loc->loc_type != bp_loc_hardware_breakpoint
7710               && loc->loc_type != bp_loc_software_breakpoint)
7711             continue;
7712
7713           if (is_addr_in_objfile (loc_addr, objfile))
7714             {
7715               loc->shlib_disabled = 1;
7716               /* At this point, we don't know whether the object was
7717                  unmapped from the inferior or not, so leave the
7718                  inserted flag alone.  We'll handle failure to
7719                  uninsert quietly, in case the object was indeed
7720                  unmapped.  */
7721
7722               mark_breakpoint_location_modified (loc);
7723
7724               bp_modified = 1;
7725             }
7726         }
7727
7728       if (bp_modified)
7729         gdb::observers::breakpoint_modified.notify (b);
7730     }
7731 }
7732
7733 /* An instance of this type is used to represent an solib catchpoint.
7734    A breakpoint is really of this type iff its ops pointer points to
7735    CATCH_SOLIB_BREAKPOINT_OPS.  */
7736
7737 struct solib_catchpoint : public breakpoint
7738 {
7739   /* True for "catch load", false for "catch unload".  */
7740   bool is_load;
7741
7742   /* Regular expression to match, if any.  COMPILED is only valid when
7743      REGEX is non-NULL.  */
7744   gdb::unique_xmalloc_ptr<char> regex;
7745   std::unique_ptr<compiled_regex> compiled;
7746 };
7747
7748 static int
7749 insert_catch_solib (struct bp_location *ignore)
7750 {
7751   return 0;
7752 }
7753
7754 static int
7755 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
7756 {
7757   return 0;
7758 }
7759
7760 static int
7761 breakpoint_hit_catch_solib (const struct bp_location *bl,
7762                             const address_space *aspace,
7763                             CORE_ADDR bp_addr,
7764                             const target_waitstatus &ws)
7765 {
7766   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7767
7768   if (ws.kind () == TARGET_WAITKIND_LOADED)
7769     return 1;
7770
7771   for (breakpoint *other : all_breakpoints ())
7772     {
7773       if (other == bl->owner)
7774         continue;
7775
7776       if (other->type != bp_shlib_event)
7777         continue;
7778
7779       if (self->pspace != NULL && other->pspace != self->pspace)
7780         continue;
7781
7782       for (bp_location *other_bl : other->locations ())
7783         {
7784           if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7785             return 1;
7786         }
7787     }
7788
7789   return 0;
7790 }
7791
7792 static void
7793 check_status_catch_solib (struct bpstat *bs)
7794 {
7795   struct solib_catchpoint *self
7796     = (struct solib_catchpoint *) bs->breakpoint_at;
7797
7798   if (self->is_load)
7799     {
7800       for (so_list *iter : current_program_space->added_solibs)
7801         {
7802           if (!self->regex
7803               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
7804             return;
7805         }
7806     }
7807   else
7808     {
7809       for (const std::string &iter : current_program_space->deleted_solibs)
7810         {
7811           if (!self->regex
7812               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
7813             return;
7814         }
7815     }
7816
7817   bs->stop = 0;
7818   bs->print_it = print_it_noop;
7819 }
7820
7821 static enum print_stop_action
7822 print_it_catch_solib (bpstat *bs)
7823 {
7824   struct breakpoint *b = bs->breakpoint_at;
7825   struct ui_out *uiout = current_uiout;
7826
7827   annotate_catchpoint (b->number);
7828   maybe_print_thread_hit_breakpoint (uiout);
7829   if (b->disposition == disp_del)
7830     uiout->text ("Temporary catchpoint ");
7831   else
7832     uiout->text ("Catchpoint ");
7833   uiout->field_signed ("bkptno", b->number);
7834   uiout->text ("\n");
7835   if (uiout->is_mi_like_p ())
7836     uiout->field_string ("disp", bpdisp_text (b->disposition));
7837   print_solib_event (1);
7838   return PRINT_SRC_AND_LOC;
7839 }
7840
7841 static void
7842 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7843 {
7844   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7845   struct value_print_options opts;
7846   struct ui_out *uiout = current_uiout;
7847
7848   get_user_print_options (&opts);
7849   /* Field 4, the address, is omitted (which makes the columns not
7850      line up too nicely with the headers, but the effect is relatively
7851      readable).  */
7852   if (opts.addressprint)
7853     {
7854       annotate_field (4);
7855       uiout->field_skip ("addr");
7856     }
7857
7858   std::string msg;
7859   annotate_field (5);
7860   if (self->is_load)
7861     {
7862       if (self->regex)
7863         msg = string_printf (_("load of library matching %s"),
7864                              self->regex.get ());
7865       else
7866         msg = _("load of library");
7867     }
7868   else
7869     {
7870       if (self->regex)
7871         msg = string_printf (_("unload of library matching %s"),
7872                              self->regex.get ());
7873       else
7874         msg = _("unload of library");
7875     }
7876   uiout->field_string ("what", msg);
7877
7878   if (uiout->is_mi_like_p ())
7879     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
7880 }
7881
7882 static void
7883 print_mention_catch_solib (struct breakpoint *b)
7884 {
7885   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7886
7887   gdb_printf (_("Catchpoint %d (%s)"), b->number,
7888               self->is_load ? "load" : "unload");
7889 }
7890
7891 static void
7892 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7893 {
7894   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7895
7896   gdb_printf (fp, "%s %s",
7897               b->disposition == disp_del ? "tcatch" : "catch",
7898               self->is_load ? "load" : "unload");
7899   if (self->regex)
7900     gdb_printf (fp, " %s", self->regex.get ());
7901   gdb_printf (fp, "\n");
7902 }
7903
7904 static struct breakpoint_ops catch_solib_breakpoint_ops;
7905
7906 /* See breakpoint.h.  */
7907
7908 void
7909 add_solib_catchpoint (const char *arg, bool is_load, bool is_temp, bool enabled)
7910 {
7911   struct gdbarch *gdbarch = get_current_arch ();
7912
7913   if (!arg)
7914     arg = "";
7915   arg = skip_spaces (arg);
7916
7917   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
7918
7919   if (*arg != '\0')
7920     {
7921       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
7922                                              _("Invalid regexp")));
7923       c->regex = make_unique_xstrdup (arg);
7924     }
7925
7926   c->is_load = is_load;
7927   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
7928                    &catch_solib_breakpoint_ops);
7929
7930   c->enable_state = enabled ? bp_enabled : bp_disabled;
7931
7932   install_breakpoint (0, std::move (c), 1);
7933 }
7934
7935 /* A helper function that does all the work for "catch load" and
7936    "catch unload".  */
7937
7938 static void
7939 catch_load_or_unload (const char *arg, int from_tty, int is_load,
7940                       struct cmd_list_element *command)
7941 {
7942   const int enabled = 1;
7943   bool temp = command->context () == CATCH_TEMPORARY;
7944
7945   add_solib_catchpoint (arg, is_load, temp, enabled);
7946 }
7947
7948 static void
7949 catch_load_command_1 (const char *arg, int from_tty,
7950                       struct cmd_list_element *command)
7951 {
7952   catch_load_or_unload (arg, from_tty, 1, command);
7953 }
7954
7955 static void
7956 catch_unload_command_1 (const char *arg, int from_tty,
7957                         struct cmd_list_element *command)
7958 {
7959   catch_load_or_unload (arg, from_tty, 0, command);
7960 }
7961
7962 /* See breakpoint.h.  */
7963
7964 void
7965 init_catchpoint (struct breakpoint *b,
7966                  struct gdbarch *gdbarch, bool temp,
7967                  const char *cond_string,
7968                  const struct breakpoint_ops *ops)
7969 {
7970   symtab_and_line sal;
7971   sal.pspace = current_program_space;
7972
7973   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7974
7975   if (cond_string == nullptr)
7976     b->cond_string.reset ();
7977   else
7978     b->cond_string = make_unique_xstrdup (cond_string);
7979   b->disposition = temp ? disp_del : disp_donttouch;
7980 }
7981
7982 void
7983 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
7984 {
7985   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
7986   set_breakpoint_number (internal, b);
7987   if (is_tracepoint (b))
7988     set_tracepoint_count (breakpoint_count);
7989   if (!internal)
7990     mention (b);
7991   gdb::observers::breakpoint_created.notify (b);
7992
7993   if (update_gll)
7994     update_global_location_list (UGLL_MAY_INSERT);
7995 }
7996
7997 static int
7998 hw_breakpoint_used_count (void)
7999 {
8000   int i = 0;
8001
8002   for (breakpoint *b : all_breakpoints ())
8003     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8004       for (bp_location *bl : b->locations ())
8005         {
8006           /* Special types of hardware breakpoints may use more than
8007              one register.  */
8008           i += b->ops->resources_needed (bl);
8009         }
8010
8011   return i;
8012 }
8013
8014 /* Returns the resources B would use if it were a hardware
8015    watchpoint.  */
8016
8017 static int
8018 hw_watchpoint_use_count (struct breakpoint *b)
8019 {
8020   int i = 0;
8021
8022   if (!breakpoint_enabled (b))
8023     return 0;
8024
8025   for (bp_location *bl : b->locations ())
8026     {
8027       /* Special types of hardware watchpoints may use more than
8028          one register.  */
8029       i += b->ops->resources_needed (bl);
8030     }
8031
8032   return i;
8033 }
8034
8035 /* Returns the sum the used resources of all hardware watchpoints of
8036    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8037    the sum of the used resources of all hardware watchpoints of other
8038    types _not_ TYPE.  */
8039
8040 static int
8041 hw_watchpoint_used_count_others (struct breakpoint *except,
8042                                  enum bptype type, int *other_type_used)
8043 {
8044   int i = 0;
8045
8046   *other_type_used = 0;
8047   for (breakpoint *b : all_breakpoints ())
8048     {
8049       if (b == except)
8050         continue;
8051       if (!breakpoint_enabled (b))
8052         continue;
8053
8054       if (b->type == type)
8055         i += hw_watchpoint_use_count (b);
8056       else if (is_hardware_watchpoint (b))
8057         *other_type_used = 1;
8058     }
8059
8060   return i;
8061 }
8062
8063 void
8064 disable_watchpoints_before_interactive_call_start (void)
8065 {
8066   for (breakpoint *b : all_breakpoints ())
8067     if (is_watchpoint (b) && breakpoint_enabled (b))
8068       {
8069         b->enable_state = bp_call_disabled;
8070         update_global_location_list (UGLL_DONT_INSERT);
8071       }
8072 }
8073
8074 void
8075 enable_watchpoints_after_interactive_call_stop (void)
8076 {
8077   for (breakpoint *b : all_breakpoints ())
8078     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8079       {
8080         b->enable_state = bp_enabled;
8081         update_global_location_list (UGLL_MAY_INSERT);
8082       }
8083 }
8084
8085 void
8086 disable_breakpoints_before_startup (void)
8087 {
8088   current_program_space->executing_startup = 1;
8089   update_global_location_list (UGLL_DONT_INSERT);
8090 }
8091
8092 void
8093 enable_breakpoints_after_startup (void)
8094 {
8095   current_program_space->executing_startup = 0;
8096   breakpoint_re_set ();
8097 }
8098
8099 /* Create a new single-step breakpoint for thread THREAD, with no
8100    locations.  */
8101
8102 static struct breakpoint *
8103 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8104 {
8105   std::unique_ptr<breakpoint> b (new breakpoint ());
8106
8107   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8108                                         &momentary_breakpoint_ops);
8109
8110   b->disposition = disp_donttouch;
8111   b->frame_id = null_frame_id;
8112
8113   b->thread = thread;
8114   gdb_assert (b->thread != 0);
8115
8116   return add_to_breakpoint_chain (std::move (b));
8117 }
8118
8119 /* Set a momentary breakpoint of type TYPE at address specified by
8120    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8121    frame.  */
8122
8123 breakpoint_up
8124 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8125                           struct frame_id frame_id, enum bptype type)
8126 {
8127   struct breakpoint *b;
8128
8129   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8130      tail-called one.  */
8131   gdb_assert (!frame_id_artificial_p (frame_id));
8132
8133   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8134   b->enable_state = bp_enabled;
8135   b->disposition = disp_donttouch;
8136   b->frame_id = frame_id;
8137
8138   b->thread = inferior_thread ()->global_num;
8139
8140   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8141
8142   return breakpoint_up (b);
8143 }
8144
8145 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8146    The new breakpoint will have type TYPE, use OPS as its
8147    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8148
8149 static struct breakpoint *
8150 momentary_breakpoint_from_master (struct breakpoint *orig,
8151                                   enum bptype type,
8152                                   const struct breakpoint_ops *ops,
8153                                   int loc_enabled)
8154 {
8155   struct breakpoint *copy;
8156
8157   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8158   copy->loc = allocate_bp_location (copy);
8159   set_breakpoint_location_function (copy->loc);
8160
8161   copy->loc->gdbarch = orig->loc->gdbarch;
8162   copy->loc->requested_address = orig->loc->requested_address;
8163   copy->loc->address = orig->loc->address;
8164   copy->loc->section = orig->loc->section;
8165   copy->loc->pspace = orig->loc->pspace;
8166   copy->loc->probe = orig->loc->probe;
8167   copy->loc->line_number = orig->loc->line_number;
8168   copy->loc->symtab = orig->loc->symtab;
8169   copy->loc->enabled = loc_enabled;
8170   copy->frame_id = orig->frame_id;
8171   copy->thread = orig->thread;
8172   copy->pspace = orig->pspace;
8173
8174   copy->enable_state = bp_enabled;
8175   copy->disposition = disp_donttouch;
8176   copy->number = internal_breakpoint_number--;
8177
8178   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8179   return copy;
8180 }
8181
8182 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8183    ORIG is NULL.  */
8184
8185 struct breakpoint *
8186 clone_momentary_breakpoint (struct breakpoint *orig)
8187 {
8188   /* If there's nothing to clone, then return nothing.  */
8189   if (orig == NULL)
8190     return NULL;
8191
8192   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8193 }
8194
8195 breakpoint_up
8196 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8197                                 enum bptype type)
8198 {
8199   struct symtab_and_line sal;
8200
8201   sal = find_pc_line (pc, 0);
8202   sal.pc = pc;
8203   sal.section = find_pc_overlay (pc);
8204   sal.explicit_pc = 1;
8205
8206   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8207 }
8208 \f
8209
8210 /* Tell the user we have just set a breakpoint B.  */
8211
8212 static void
8213 mention (struct breakpoint *b)
8214 {
8215   b->ops->print_mention (b);
8216   current_uiout->text ("\n");
8217 }
8218 \f
8219
8220 static bool bp_loc_is_permanent (struct bp_location *loc);
8221
8222 /* Handle "set breakpoint auto-hw on".
8223
8224    If the explicitly specified breakpoint type is not hardware
8225    breakpoint, check the memory map to see whether the breakpoint
8226    address is in read-only memory.
8227
8228    - location type is not hardware breakpoint, memory is read-only.
8229    We change the type of the location to hardware breakpoint.
8230
8231    - location type is hardware breakpoint, memory is read-write.  This
8232    means we've previously made the location hardware one, but then the
8233    memory map changed, so we undo.
8234 */
8235
8236 static void
8237 handle_automatic_hardware_breakpoints (bp_location *bl)
8238 {
8239   if (automatic_hardware_breakpoints
8240       && bl->owner->type != bp_hardware_breakpoint
8241       && (bl->loc_type == bp_loc_software_breakpoint
8242           || bl->loc_type == bp_loc_hardware_breakpoint))
8243     {
8244       /* When breakpoints are removed, remove_breakpoints will use
8245          location types we've just set here, the only possible problem
8246          is that memory map has changed during running program, but
8247          it's not going to work anyway with current gdb.  */
8248       mem_region *mr = lookup_mem_region (bl->address);
8249
8250       if (mr != nullptr)
8251         {
8252           enum bp_loc_type new_type;
8253
8254           if (mr->attrib.mode != MEM_RW)
8255             new_type = bp_loc_hardware_breakpoint;
8256           else
8257             new_type = bp_loc_software_breakpoint;
8258
8259           if (new_type != bl->loc_type)
8260             {
8261               static bool said = false;
8262
8263               bl->loc_type = new_type;
8264               if (!said)
8265                 {
8266                   gdb_printf (_("Note: automatically using "
8267                                 "hardware breakpoints for "
8268                                 "read-only addresses.\n"));
8269                   said = true;
8270                 }
8271             }
8272         }
8273     }
8274 }
8275
8276 static struct bp_location *
8277 add_location_to_breakpoint (struct breakpoint *b,
8278                             const struct symtab_and_line *sal)
8279 {
8280   struct bp_location *loc, **tmp;
8281   CORE_ADDR adjusted_address;
8282   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8283
8284   if (loc_gdbarch == NULL)
8285     loc_gdbarch = b->gdbarch;
8286
8287   /* Adjust the breakpoint's address prior to allocating a location.
8288      Once we call allocate_bp_location(), that mostly uninitialized
8289      location will be placed on the location chain.  Adjustment of the
8290      breakpoint may cause target_read_memory() to be called and we do
8291      not want its scan of the location chain to find a breakpoint and
8292      location that's only been partially initialized.  */
8293   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8294                                                 sal->pc, b->type);
8295
8296   /* Sort the locations by their ADDRESS.  */
8297   loc = allocate_bp_location (b);
8298   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8299        tmp = &((*tmp)->next))
8300     ;
8301   loc->next = *tmp;
8302   *tmp = loc;
8303
8304   loc->requested_address = sal->pc;
8305   loc->address = adjusted_address;
8306   loc->pspace = sal->pspace;
8307   loc->probe.prob = sal->prob;
8308   loc->probe.objfile = sal->objfile;
8309   gdb_assert (loc->pspace != NULL);
8310   loc->section = sal->section;
8311   loc->gdbarch = loc_gdbarch;
8312   loc->line_number = sal->line;
8313   loc->symtab = sal->symtab;
8314   loc->symbol = sal->symbol;
8315   loc->msymbol = sal->msymbol;
8316   loc->objfile = sal->objfile;
8317
8318   set_breakpoint_location_function (loc);
8319
8320   /* While by definition, permanent breakpoints are already present in the
8321      code, we don't mark the location as inserted.  Normally one would expect
8322      that GDB could rely on that breakpoint instruction to stop the program,
8323      thus removing the need to insert its own breakpoint, except that executing
8324      the breakpoint instruction can kill the target instead of reporting a
8325      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8326      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8327      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8328      breakpoint be inserted normally results in QEMU knowing about the GDB
8329      breakpoint, and thus trap before the breakpoint instruction is executed.
8330      (If GDB later needs to continue execution past the permanent breakpoint,
8331      it manually increments the PC, thus avoiding executing the breakpoint
8332      instruction.)  */
8333   if (bp_loc_is_permanent (loc))
8334     loc->permanent = 1;
8335
8336   return loc;
8337 }
8338 \f
8339
8340 /* Return true if LOC is pointing to a permanent breakpoint,
8341    return false otherwise.  */
8342
8343 static bool
8344 bp_loc_is_permanent (struct bp_location *loc)
8345 {
8346   gdb_assert (loc != NULL);
8347
8348   /* If we have a non-breakpoint-backed catchpoint or a software
8349      watchpoint, just return 0.  We should not attempt to read from
8350      the addresses the locations of these breakpoint types point to.
8351      gdbarch_program_breakpoint_here_p, below, will attempt to read
8352      memory.  */
8353   if (!bl_address_is_meaningful (loc))
8354     return false;
8355
8356   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8357   switch_to_program_space_and_thread (loc->pspace);
8358   return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8359 }
8360
8361 /* Build a command list for the dprintf corresponding to the current
8362    settings of the dprintf style options.  */
8363
8364 static void
8365 update_dprintf_command_list (struct breakpoint *b)
8366 {
8367   const char *dprintf_args = b->extra_string.get ();
8368   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
8369
8370   if (!dprintf_args)
8371     return;
8372
8373   dprintf_args = skip_spaces (dprintf_args);
8374
8375   /* Allow a comma, as it may have terminated a location, but don't
8376      insist on it.  */
8377   if (*dprintf_args == ',')
8378     ++dprintf_args;
8379   dprintf_args = skip_spaces (dprintf_args);
8380
8381   if (*dprintf_args != '"')
8382     error (_("Bad format string, missing '\"'."));
8383
8384   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8385     printf_line = xstrprintf ("printf %s", dprintf_args);
8386   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8387     {
8388       if (dprintf_function.empty ())
8389         error (_("No function supplied for dprintf call"));
8390
8391       if (!dprintf_channel.empty ())
8392         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8393                                   dprintf_function.c_str (),
8394                                   dprintf_channel.c_str (),
8395                                   dprintf_args);
8396       else
8397         printf_line = xstrprintf ("call (void) %s (%s)",
8398                                   dprintf_function.c_str (),
8399                                   dprintf_args);
8400     }
8401   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8402     {
8403       if (target_can_run_breakpoint_commands ())
8404         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8405       else
8406         {
8407           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8408           printf_line = xstrprintf ("printf %s", dprintf_args);
8409         }
8410     }
8411   else
8412     internal_error (__FILE__, __LINE__,
8413                     _("Invalid dprintf style."));
8414
8415   gdb_assert (printf_line != NULL);
8416
8417   /* Manufacture a printf sequence.  */
8418   struct command_line *printf_cmd_line
8419     = new struct command_line (simple_control, printf_line.release ());
8420   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8421                                                     command_lines_deleter ()));
8422 }
8423
8424 /* Update all dprintf commands, making their command lists reflect
8425    current style settings.  */
8426
8427 static void
8428 update_dprintf_commands (const char *args, int from_tty,
8429                          struct cmd_list_element *c)
8430 {
8431   for (breakpoint *b : all_breakpoints ())
8432     if (b->type == bp_dprintf)
8433         update_dprintf_command_list (b);
8434 }
8435
8436 /* Create a breakpoint with SAL as location.  Use LOCATION
8437    as a description of the location, and COND_STRING
8438    as condition expression.  If LOCATION is NULL then create an
8439    "address location" from the address in the SAL.  */
8440
8441 static void
8442 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8443                      gdb::array_view<const symtab_and_line> sals,
8444                      event_location_up &&location,
8445                      gdb::unique_xmalloc_ptr<char> filter,
8446                      gdb::unique_xmalloc_ptr<char> cond_string,
8447                      gdb::unique_xmalloc_ptr<char> extra_string,
8448                      enum bptype type, enum bpdisp disposition,
8449                      int thread, int task, int ignore_count,
8450                      const struct breakpoint_ops *ops, int from_tty,
8451                      int enabled, int internal, unsigned flags,
8452                      int display_canonical)
8453 {
8454   int i;
8455
8456   if (type == bp_hardware_breakpoint)
8457     {
8458       int target_resources_ok;
8459
8460       i = hw_breakpoint_used_count ();
8461       target_resources_ok =
8462         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8463                                             i + 1, 0);
8464       if (target_resources_ok == 0)
8465         error (_("No hardware breakpoint support in the target."));
8466       else if (target_resources_ok < 0)
8467         error (_("Hardware breakpoints used exceeds limit."));
8468     }
8469
8470   gdb_assert (!sals.empty ());
8471
8472   for (const auto &sal : sals)
8473     {
8474       struct bp_location *loc;
8475
8476       if (from_tty)
8477         {
8478           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8479           if (!loc_gdbarch)
8480             loc_gdbarch = gdbarch;
8481
8482           describe_other_breakpoints (loc_gdbarch,
8483                                       sal.pspace, sal.pc, sal.section, thread);
8484         }
8485
8486       if (&sal == &sals[0])
8487         {
8488           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8489           b->thread = thread;
8490           b->task = task;
8491
8492           b->cond_string = std::move (cond_string);
8493           b->extra_string = std::move (extra_string);
8494           b->ignore_count = ignore_count;
8495           b->enable_state = enabled ? bp_enabled : bp_disabled;
8496           b->disposition = disposition;
8497
8498           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8499             b->loc->inserted = 1;
8500
8501           if (type == bp_static_tracepoint)
8502             {
8503               struct tracepoint *t = (struct tracepoint *) b;
8504               struct static_tracepoint_marker marker;
8505
8506               if (strace_marker_p (b))
8507                 {
8508                   /* We already know the marker exists, otherwise, we
8509                      wouldn't see a sal for it.  */
8510                   const char *p
8511                     = &event_location_to_string (b->location.get ())[3];
8512                   const char *endp;
8513
8514                   p = skip_spaces (p);
8515
8516                   endp = skip_to_space (p);
8517
8518                   t->static_trace_marker_id.assign (p, endp - p);
8519
8520                   gdb_printf (_("Probed static tracepoint "
8521                                 "marker \"%s\"\n"),
8522                               t->static_trace_marker_id.c_str ());
8523                 }
8524               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8525                 {
8526                   t->static_trace_marker_id = std::move (marker.str_id);
8527
8528                   gdb_printf (_("Probed static tracepoint "
8529                                 "marker \"%s\"\n"),
8530                               t->static_trace_marker_id.c_str ());
8531                 }
8532               else
8533                 warning (_("Couldn't determine the static "
8534                            "tracepoint marker to probe"));
8535             }
8536
8537           loc = b->loc;
8538         }
8539       else
8540         {
8541           loc = add_location_to_breakpoint (b, &sal);
8542           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8543             loc->inserted = 1;
8544         }
8545
8546       /* Do not set breakpoint locations conditions yet.  As locations
8547          are inserted, they get sorted based on their addresses.  Let
8548          the list stabilize to have reliable location numbers.  */
8549
8550       /* Dynamic printf requires and uses additional arguments on the
8551          command line, otherwise it's an error.  */
8552       if (type == bp_dprintf)
8553         {
8554           if (b->extra_string)
8555             update_dprintf_command_list (b);
8556           else
8557             error (_("Format string required"));
8558         }
8559       else if (b->extra_string)
8560         error (_("Garbage '%s' at end of command"), b->extra_string.get ());
8561     }
8562
8563
8564   /* The order of the locations is now stable.  Set the location
8565      condition using the location's number.  */
8566   int loc_num = 1;
8567   for (bp_location *loc : b->locations ())
8568     {
8569       if (b->cond_string != nullptr)
8570         set_breakpoint_location_condition (b->cond_string.get (), loc,
8571                                            b->number, loc_num);
8572
8573       ++loc_num;
8574     }
8575
8576   b->display_canonical = display_canonical;
8577   if (location != NULL)
8578     b->location = std::move (location);
8579   else
8580     b->location = new_address_location (b->loc->address, NULL, 0);
8581   b->filter = std::move (filter);
8582 }
8583
8584 static void
8585 create_breakpoint_sal (struct gdbarch *gdbarch,
8586                        gdb::array_view<const symtab_and_line> sals,
8587                        event_location_up &&location,
8588                        gdb::unique_xmalloc_ptr<char> filter,
8589                        gdb::unique_xmalloc_ptr<char> cond_string,
8590                        gdb::unique_xmalloc_ptr<char> extra_string,
8591                        enum bptype type, enum bpdisp disposition,
8592                        int thread, int task, int ignore_count,
8593                        const struct breakpoint_ops *ops, int from_tty,
8594                        int enabled, int internal, unsigned flags,
8595                        int display_canonical)
8596 {
8597   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8598
8599   init_breakpoint_sal (b.get (), gdbarch,
8600                        sals, std::move (location),
8601                        std::move (filter),
8602                        std::move (cond_string),
8603                        std::move (extra_string),
8604                        type, disposition,
8605                        thread, task, ignore_count,
8606                        ops, from_tty,
8607                        enabled, internal, flags,
8608                        display_canonical);
8609
8610   install_breakpoint (internal, std::move (b), 0);
8611 }
8612
8613 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8614    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8615    value.  COND_STRING, if not NULL, specified the condition to be
8616    used for all breakpoints.  Essentially the only case where
8617    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8618    function.  In that case, it's still not possible to specify
8619    separate conditions for different overloaded functions, so
8620    we take just a single condition string.
8621    
8622    NOTE: If the function succeeds, the caller is expected to cleanup
8623    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8624    array contents).  If the function fails (error() is called), the
8625    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8626    COND and SALS arrays and each of those arrays contents.  */
8627
8628 static void
8629 create_breakpoints_sal (struct gdbarch *gdbarch,
8630                         struct linespec_result *canonical,
8631                         gdb::unique_xmalloc_ptr<char> cond_string,
8632                         gdb::unique_xmalloc_ptr<char> extra_string,
8633                         enum bptype type, enum bpdisp disposition,
8634                         int thread, int task, int ignore_count,
8635                         const struct breakpoint_ops *ops, int from_tty,
8636                         int enabled, int internal, unsigned flags)
8637 {
8638   if (canonical->pre_expanded)
8639     gdb_assert (canonical->lsals.size () == 1);
8640
8641   for (const auto &lsal : canonical->lsals)
8642     {
8643       /* Note that 'location' can be NULL in the case of a plain
8644          'break', without arguments.  */
8645       event_location_up location
8646         = (canonical->location != NULL
8647            ? copy_event_location (canonical->location.get ()) : NULL);
8648       gdb::unique_xmalloc_ptr<char> filter_string
8649         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8650
8651       create_breakpoint_sal (gdbarch, lsal.sals,
8652                              std::move (location),
8653                              std::move (filter_string),
8654                              std::move (cond_string),
8655                              std::move (extra_string),
8656                              type, disposition,
8657                              thread, task, ignore_count, ops,
8658                              from_tty, enabled, internal, flags,
8659                              canonical->special_display);
8660     }
8661 }
8662
8663 /* Parse LOCATION which is assumed to be a SAL specification possibly
8664    followed by conditionals.  On return, SALS contains an array of SAL
8665    addresses found.  LOCATION points to the end of the SAL (for
8666    linespec locations).
8667
8668    The array and the line spec strings are allocated on the heap, it is
8669    the caller's responsibility to free them.  */
8670
8671 static void
8672 parse_breakpoint_sals (struct event_location *location,
8673                        struct linespec_result *canonical)
8674 {
8675   struct symtab_and_line cursal;
8676
8677   if (event_location_type (location) == LINESPEC_LOCATION)
8678     {
8679       const char *spec = get_linespec_location (location)->spec_string;
8680
8681       if (spec == NULL)
8682         {
8683           /* The last displayed codepoint, if it's valid, is our default
8684              breakpoint address.  */
8685           if (last_displayed_sal_is_valid ())
8686             {
8687               /* Set sal's pspace, pc, symtab, and line to the values
8688                  corresponding to the last call to print_frame_info.
8689                  Be sure to reinitialize LINE with NOTCURRENT == 0
8690                  as the breakpoint line number is inappropriate otherwise.
8691                  find_pc_line would adjust PC, re-set it back.  */
8692               symtab_and_line sal = get_last_displayed_sal ();
8693               CORE_ADDR pc = sal.pc;
8694
8695               sal = find_pc_line (pc, 0);
8696
8697               /* "break" without arguments is equivalent to "break *PC"
8698                  where PC is the last displayed codepoint's address.  So
8699                  make sure to set sal.explicit_pc to prevent GDB from
8700                  trying to expand the list of sals to include all other
8701                  instances with the same symtab and line.  */
8702               sal.pc = pc;
8703               sal.explicit_pc = 1;
8704
8705               struct linespec_sals lsal;
8706               lsal.sals = {sal};
8707               lsal.canonical = NULL;
8708
8709               canonical->lsals.push_back (std::move (lsal));
8710               return;
8711             }
8712           else
8713             error (_("No default breakpoint address now."));
8714         }
8715     }
8716
8717   /* Force almost all breakpoints to be in terms of the
8718      current_source_symtab (which is decode_line_1's default).
8719      This should produce the results we want almost all of the
8720      time while leaving default_breakpoint_* alone.
8721
8722      ObjC: However, don't match an Objective-C method name which
8723      may have a '+' or '-' succeeded by a '['.  */
8724   cursal = get_current_source_symtab_and_line ();
8725   if (last_displayed_sal_is_valid ())
8726     {
8727       const char *spec = NULL;
8728
8729       if (event_location_type (location) == LINESPEC_LOCATION)
8730         spec = get_linespec_location (location)->spec_string;
8731
8732       if (!cursal.symtab
8733           || (spec != NULL
8734               && strchr ("+-", spec[0]) != NULL
8735               && spec[1] != '['))
8736         {
8737           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
8738                             get_last_displayed_symtab (),
8739                             get_last_displayed_line (),
8740                             canonical, NULL, NULL);
8741           return;
8742         }
8743     }
8744
8745   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
8746                     cursal.symtab, cursal.line, canonical, NULL, NULL);
8747 }
8748
8749
8750 /* Convert each SAL into a real PC.  Verify that the PC can be
8751    inserted as a breakpoint.  If it can't throw an error.  */
8752
8753 static void
8754 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
8755 {    
8756   for (auto &sal : sals)
8757     resolve_sal_pc (&sal);
8758 }
8759
8760 /* Fast tracepoints may have restrictions on valid locations.  For
8761    instance, a fast tracepoint using a jump instead of a trap will
8762    likely have to overwrite more bytes than a trap would, and so can
8763    only be placed where the instruction is longer than the jump, or a
8764    multi-instruction sequence does not have a jump into the middle of
8765    it, etc.  */
8766
8767 static void
8768 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8769                             gdb::array_view<const symtab_and_line> sals)
8770 {
8771   for (const auto &sal : sals)
8772     {
8773       struct gdbarch *sarch;
8774
8775       sarch = get_sal_arch (sal);
8776       /* We fall back to GDBARCH if there is no architecture
8777          associated with SAL.  */
8778       if (sarch == NULL)
8779         sarch = gdbarch;
8780       std::string msg;
8781       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
8782         error (_("May not have a fast tracepoint at %s%s"),
8783                paddress (sarch, sal.pc), msg.c_str ());
8784     }
8785 }
8786
8787 /* Given TOK, a string specification of condition and thread, as
8788    accepted by the 'break' command, extract the condition
8789    string and thread number and set *COND_STRING and *THREAD.
8790    PC identifies the context at which the condition should be parsed.
8791    If no condition is found, *COND_STRING is set to NULL.
8792    If no thread is found, *THREAD is set to -1.  */
8793
8794 static void
8795 find_condition_and_thread (const char *tok, CORE_ADDR pc,
8796                            gdb::unique_xmalloc_ptr<char> *cond_string,
8797                            int *thread, int *task,
8798                            gdb::unique_xmalloc_ptr<char> *rest)
8799 {
8800   cond_string->reset ();
8801   *thread = -1;
8802   *task = 0;
8803   rest->reset ();
8804   bool force = false;
8805
8806   while (tok && *tok)
8807     {
8808       const char *end_tok;
8809       int toklen;
8810       const char *cond_start = NULL;
8811       const char *cond_end = NULL;
8812
8813       tok = skip_spaces (tok);
8814
8815       if ((*tok == '"' || *tok == ',') && rest)
8816         {
8817           rest->reset (savestring (tok, strlen (tok)));
8818           return;
8819         }
8820
8821       end_tok = skip_to_space (tok);
8822
8823       toklen = end_tok - tok;
8824
8825       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8826         {
8827           tok = cond_start = end_tok + 1;
8828           try
8829             {
8830               parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
8831             }
8832           catch (const gdb_exception_error &)
8833             {
8834               if (!force)
8835                 throw;
8836               else
8837                 tok = tok + strlen (tok);
8838             }
8839           cond_end = tok;
8840           cond_string->reset (savestring (cond_start, cond_end - cond_start));
8841         }
8842       else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
8843         {
8844           tok = tok + toklen;
8845           force = true;
8846         }
8847       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8848         {
8849           const char *tmptok;
8850           struct thread_info *thr;
8851
8852           tok = end_tok + 1;
8853           thr = parse_thread_id (tok, &tmptok);
8854           if (tok == tmptok)
8855             error (_("Junk after thread keyword."));
8856           *thread = thr->global_num;
8857           tok = tmptok;
8858         }
8859       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8860         {
8861           char *tmptok;
8862
8863           tok = end_tok + 1;
8864           *task = strtol (tok, &tmptok, 0);
8865           if (tok == tmptok)
8866             error (_("Junk after task keyword."));
8867           if (!valid_task_id (*task))
8868             error (_("Unknown task %d."), *task);
8869           tok = tmptok;
8870         }
8871       else if (rest)
8872         {
8873           rest->reset (savestring (tok, strlen (tok)));
8874           return;
8875         }
8876       else
8877         error (_("Junk at end of arguments."));
8878     }
8879 }
8880
8881 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
8882    succeeds.  The parsed values are written to COND_STRING, THREAD,
8883    TASK, and REST.  See the comment of 'find_condition_and_thread'
8884    for the description of these parameters and INPUT.  */
8885
8886 static void
8887 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
8888                                     const char *input,
8889                                     gdb::unique_xmalloc_ptr<char> *cond_string,
8890                                     int *thread, int *task,
8891                                     gdb::unique_xmalloc_ptr<char> *rest)
8892 {
8893   int num_failures = 0;
8894   for (auto &sal : sals)
8895     {
8896       gdb::unique_xmalloc_ptr<char> cond;
8897       int thread_id = 0;
8898       int task_id = 0;
8899       gdb::unique_xmalloc_ptr<char> remaining;
8900
8901       /* Here we want to parse 'arg' to separate condition from thread
8902          number.  But because parsing happens in a context and the
8903          contexts of sals might be different, try each until there is
8904          success.  Finding one successful parse is sufficient for our
8905          goal.  When setting the breakpoint we'll re-parse the
8906          condition in the context of each sal.  */
8907       try
8908         {
8909           find_condition_and_thread (input, sal.pc, &cond, &thread_id,
8910                                      &task_id, &remaining);
8911           *cond_string = std::move (cond);
8912           *thread = thread_id;
8913           *task = task_id;
8914           *rest = std::move (remaining);
8915           break;
8916         }
8917       catch (const gdb_exception_error &e)
8918         {
8919           num_failures++;
8920           /* If no sal remains, do not continue.  */
8921           if (num_failures == sals.size ())
8922             throw;
8923         }
8924     }
8925 }
8926
8927 /* Decode a static tracepoint marker spec.  */
8928
8929 static std::vector<symtab_and_line>
8930 decode_static_tracepoint_spec (const char **arg_p)
8931 {
8932   const char *p = &(*arg_p)[3];
8933   const char *endp;
8934
8935   p = skip_spaces (p);
8936
8937   endp = skip_to_space (p);
8938
8939   std::string marker_str (p, endp - p);
8940
8941   std::vector<static_tracepoint_marker> markers
8942     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
8943   if (markers.empty ())
8944     error (_("No known static tracepoint marker named %s"),
8945            marker_str.c_str ());
8946
8947   std::vector<symtab_and_line> sals;
8948   sals.reserve (markers.size ());
8949
8950   for (const static_tracepoint_marker &marker : markers)
8951     {
8952       symtab_and_line sal = find_pc_line (marker.address, 0);
8953       sal.pc = marker.address;
8954       sals.push_back (sal);
8955    }
8956
8957   *arg_p = endp;
8958   return sals;
8959 }
8960
8961 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
8962    according to IS_TRACEPOINT.  */
8963
8964 static const struct breakpoint_ops *
8965 breakpoint_ops_for_event_location_type (enum event_location_type location_type,
8966                                         bool is_tracepoint)
8967 {
8968   if (is_tracepoint)
8969     {
8970       if (location_type == PROBE_LOCATION)
8971         return &tracepoint_probe_breakpoint_ops;
8972       else
8973         return &tracepoint_breakpoint_ops;
8974     }
8975   else
8976     {
8977       if (location_type == PROBE_LOCATION)
8978         return &bkpt_probe_breakpoint_ops;
8979       else
8980         return &bkpt_breakpoint_ops;
8981     }
8982 }
8983
8984 /* See breakpoint.h.  */
8985
8986 const struct breakpoint_ops *
8987 breakpoint_ops_for_event_location (const struct event_location *location,
8988                                    bool is_tracepoint)
8989 {
8990   if (location != nullptr)
8991     return breakpoint_ops_for_event_location_type
8992       (event_location_type (location), is_tracepoint);
8993   return is_tracepoint ? &tracepoint_breakpoint_ops : &bkpt_breakpoint_ops;
8994 }
8995
8996 /* See breakpoint.h.  */
8997
8998 int
8999 create_breakpoint (struct gdbarch *gdbarch,
9000                    struct event_location *location,
9001                    const char *cond_string,
9002                    int thread, const char *extra_string,
9003                    bool force_condition, int parse_extra,
9004                    int tempflag, enum bptype type_wanted,
9005                    int ignore_count,
9006                    enum auto_boolean pending_break_support,
9007                    const struct breakpoint_ops *ops,
9008                    int from_tty, int enabled, int internal,
9009                    unsigned flags)
9010 {
9011   struct linespec_result canonical;
9012   int pending = 0;
9013   int task = 0;
9014   int prev_bkpt_count = breakpoint_count;
9015
9016   gdb_assert (ops != NULL);
9017
9018   /* If extra_string isn't useful, set it to NULL.  */
9019   if (extra_string != NULL && *extra_string == '\0')
9020     extra_string = NULL;
9021
9022   try
9023     {
9024       ops->create_sals_from_location (location, &canonical, type_wanted);
9025     }
9026   catch (const gdb_exception_error &e)
9027     {
9028       /* If caller is interested in rc value from parse, set
9029          value.  */
9030       if (e.error == NOT_FOUND_ERROR)
9031         {
9032           /* If pending breakpoint support is turned off, throw
9033              error.  */
9034
9035           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9036             throw;
9037
9038           exception_print (gdb_stderr, e);
9039
9040           /* If pending breakpoint support is auto query and the user
9041              selects no, then simply return the error code.  */
9042           if (pending_break_support == AUTO_BOOLEAN_AUTO
9043               && !nquery (_("Make %s pending on future shared library load? "),
9044                           bptype_string (type_wanted)))
9045             return 0;
9046
9047           /* At this point, either the user was queried about setting
9048              a pending breakpoint and selected yes, or pending
9049              breakpoint behavior is on and thus a pending breakpoint
9050              is defaulted on behalf of the user.  */
9051           pending = 1;
9052         }
9053       else
9054         throw;
9055     }
9056
9057   if (!pending && canonical.lsals.empty ())
9058     return 0;
9059
9060   /* Resolve all line numbers to PC's and verify that the addresses
9061      are ok for the target.  */
9062   if (!pending)
9063     {
9064       for (auto &lsal : canonical.lsals)
9065         breakpoint_sals_to_pc (lsal.sals);
9066     }
9067
9068   /* Fast tracepoints may have additional restrictions on location.  */
9069   if (!pending && type_wanted == bp_fast_tracepoint)
9070     {
9071       for (const auto &lsal : canonical.lsals)
9072         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9073     }
9074
9075   /* Verify that condition can be parsed, before setting any
9076      breakpoints.  Allocate a separate condition expression for each
9077      breakpoint.  */
9078   if (!pending)
9079     {
9080       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9081       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9082
9083       if (parse_extra)
9084         {
9085           gdb::unique_xmalloc_ptr<char> rest;
9086           gdb::unique_xmalloc_ptr<char> cond;
9087
9088           const linespec_sals &lsal = canonical.lsals[0];
9089
9090           find_condition_and_thread_for_sals (lsal.sals, extra_string,
9091                                               &cond, &thread, &task, &rest);
9092           cond_string_copy = std::move (cond);
9093           extra_string_copy = std::move (rest);
9094         }
9095       else
9096         {
9097           if (type_wanted != bp_dprintf
9098               && extra_string != NULL && *extra_string != '\0')
9099                 error (_("Garbage '%s' at end of location"), extra_string);
9100
9101           /* Check the validity of the condition.  We should error out
9102              if the condition is invalid at all of the locations and
9103              if it is not forced.  In the PARSE_EXTRA case above, this
9104              check is done when parsing the EXTRA_STRING.  */
9105           if (cond_string != nullptr && !force_condition)
9106             {
9107               int num_failures = 0;
9108               const linespec_sals &lsal = canonical.lsals[0];
9109               for (const auto &sal : lsal.sals)
9110                 {
9111                   const char *cond = cond_string;
9112                   try
9113                     {
9114                       parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
9115                       /* One success is sufficient to keep going.  */
9116                       break;
9117                     }
9118                   catch (const gdb_exception_error &)
9119                     {
9120                       num_failures++;
9121                       /* If this is the last sal, error out.  */
9122                       if (num_failures == lsal.sals.size ())
9123                         throw;
9124                     }
9125                 }
9126             }
9127
9128           /* Create a private copy of condition string.  */
9129           if (cond_string)
9130             cond_string_copy.reset (xstrdup (cond_string));
9131           /* Create a private copy of any extra string.  */
9132           if (extra_string)
9133             extra_string_copy.reset (xstrdup (extra_string));
9134         }
9135
9136       ops->create_breakpoints_sal (gdbarch, &canonical,
9137                                    std::move (cond_string_copy),
9138                                    std::move (extra_string_copy),
9139                                    type_wanted,
9140                                    tempflag ? disp_del : disp_donttouch,
9141                                    thread, task, ignore_count, ops,
9142                                    from_tty, enabled, internal, flags);
9143     }
9144   else
9145     {
9146       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9147
9148       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9149       b->location = copy_event_location (location);
9150
9151       if (parse_extra)
9152         b->cond_string = NULL;
9153       else
9154         {
9155           /* Create a private copy of condition string.  */
9156           b->cond_string.reset (cond_string != NULL
9157                                 ? xstrdup (cond_string)
9158                                 : NULL);
9159           b->thread = thread;
9160         }
9161
9162       /* Create a private copy of any extra string.  */
9163       b->extra_string.reset (extra_string != NULL
9164                              ? xstrdup (extra_string)
9165                              : NULL);
9166       b->ignore_count = ignore_count;
9167       b->disposition = tempflag ? disp_del : disp_donttouch;
9168       b->condition_not_parsed = 1;
9169       b->enable_state = enabled ? bp_enabled : bp_disabled;
9170       if ((type_wanted != bp_breakpoint
9171            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9172         b->pspace = current_program_space;
9173
9174       install_breakpoint (internal, std::move (b), 0);
9175     }
9176   
9177   if (canonical.lsals.size () > 1)
9178     {
9179       warning (_("Multiple breakpoints were set.\nUse the "
9180                  "\"delete\" command to delete unwanted breakpoints."));
9181       prev_breakpoint_count = prev_bkpt_count;
9182     }
9183
9184   update_global_location_list (UGLL_MAY_INSERT);
9185
9186   return 1;
9187 }
9188
9189 /* Set a breakpoint.
9190    ARG is a string describing breakpoint address,
9191    condition, and thread.
9192    FLAG specifies if a breakpoint is hardware on,
9193    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9194    and BP_TEMPFLAG.  */
9195
9196 static void
9197 break_command_1 (const char *arg, int flag, int from_tty)
9198 {
9199   int tempflag = flag & BP_TEMPFLAG;
9200   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9201                              ? bp_hardware_breakpoint
9202                              : bp_breakpoint);
9203
9204   event_location_up location = string_to_event_location (&arg, current_language);
9205   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
9206     (location.get (), false /* is_tracepoint */);
9207
9208   create_breakpoint (get_current_arch (),
9209                      location.get (),
9210                      NULL, 0, arg, false, 1 /* parse arg */,
9211                      tempflag, type_wanted,
9212                      0 /* Ignore count */,
9213                      pending_break_support,
9214                      ops,
9215                      from_tty,
9216                      1 /* enabled */,
9217                      0 /* internal */,
9218                      0);
9219 }
9220
9221 /* Helper function for break_command_1 and disassemble_command.  */
9222
9223 void
9224 resolve_sal_pc (struct symtab_and_line *sal)
9225 {
9226   CORE_ADDR pc;
9227
9228   if (sal->pc == 0 && sal->symtab != NULL)
9229     {
9230       if (!find_line_pc (sal->symtab, sal->line, &pc))
9231         error (_("No line %d in file \"%s\"."),
9232                sal->line, symtab_to_filename_for_display (sal->symtab));
9233       sal->pc = pc;
9234
9235       /* If this SAL corresponds to a breakpoint inserted using a line
9236          number, then skip the function prologue if necessary.  */
9237       if (sal->explicit_line)
9238         skip_prologue_sal (sal);
9239     }
9240
9241   if (sal->section == 0 && sal->symtab != NULL)
9242     {
9243       const struct blockvector *bv;
9244       const struct block *b;
9245       struct symbol *sym;
9246
9247       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9248                                     sal->symtab->compunit ());
9249       if (bv != NULL)
9250         {
9251           sym = block_linkage_function (b);
9252           if (sym != NULL)
9253             {
9254               fixup_symbol_section (sym, sal->symtab->objfile ());
9255               sal->section = sym->obj_section (sal->symtab->objfile ());
9256             }
9257           else
9258             {
9259               /* It really is worthwhile to have the section, so we'll
9260                  just have to look harder. This case can be executed
9261                  if we have line numbers but no functions (as can
9262                  happen in assembly source).  */
9263
9264               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9265               switch_to_program_space_and_thread (sal->pspace);
9266
9267               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9268               if (msym.minsym)
9269                 sal->section = msym.obj_section ();
9270             }
9271         }
9272     }
9273 }
9274
9275 void
9276 break_command (const char *arg, int from_tty)
9277 {
9278   break_command_1 (arg, 0, from_tty);
9279 }
9280
9281 void
9282 tbreak_command (const char *arg, int from_tty)
9283 {
9284   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9285 }
9286
9287 static void
9288 hbreak_command (const char *arg, int from_tty)
9289 {
9290   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9291 }
9292
9293 static void
9294 thbreak_command (const char *arg, int from_tty)
9295 {
9296   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9297 }
9298
9299 static void
9300 stop_command (const char *arg, int from_tty)
9301 {
9302   gdb_printf (_("Specify the type of breakpoint to set.\n\
9303 Usage: stop in <function | address>\n\
9304        stop at <line>\n"));
9305 }
9306
9307 static void
9308 stopin_command (const char *arg, int from_tty)
9309 {
9310   int badInput = 0;
9311
9312   if (arg == NULL)
9313     badInput = 1;
9314   else if (*arg != '*')
9315     {
9316       const char *argptr = arg;
9317       int hasColon = 0;
9318
9319       /* Look for a ':'.  If this is a line number specification, then
9320          say it is bad, otherwise, it should be an address or
9321          function/method name.  */
9322       while (*argptr && !hasColon)
9323         {
9324           hasColon = (*argptr == ':');
9325           argptr++;
9326         }
9327
9328       if (hasColon)
9329         badInput = (*argptr != ':');    /* Not a class::method */
9330       else
9331         badInput = isdigit (*arg);      /* a simple line number */
9332     }
9333
9334   if (badInput)
9335     gdb_printf (_("Usage: stop in <function | address>\n"));
9336   else
9337     break_command_1 (arg, 0, from_tty);
9338 }
9339
9340 static void
9341 stopat_command (const char *arg, int from_tty)
9342 {
9343   int badInput = 0;
9344
9345   if (arg == NULL || *arg == '*')       /* no line number */
9346     badInput = 1;
9347   else
9348     {
9349       const char *argptr = arg;
9350       int hasColon = 0;
9351
9352       /* Look for a ':'.  If there is a '::' then get out, otherwise
9353          it is probably a line number.  */
9354       while (*argptr && !hasColon)
9355         {
9356           hasColon = (*argptr == ':');
9357           argptr++;
9358         }
9359
9360       if (hasColon)
9361         badInput = (*argptr == ':');    /* we have class::method */
9362       else
9363         badInput = !isdigit (*arg);     /* not a line number */
9364     }
9365
9366   if (badInput)
9367     gdb_printf (_("Usage: stop at LINE\n"));
9368   else
9369     break_command_1 (arg, 0, from_tty);
9370 }
9371
9372 /* The dynamic printf command is mostly like a regular breakpoint, but
9373    with a prewired command list consisting of a single output command,
9374    built from extra arguments supplied on the dprintf command
9375    line.  */
9376
9377 static void
9378 dprintf_command (const char *arg, int from_tty)
9379 {
9380   event_location_up location = string_to_event_location (&arg, current_language);
9381
9382   /* If non-NULL, ARG should have been advanced past the location;
9383      the next character must be ','.  */
9384   if (arg != NULL)
9385     {
9386       if (arg[0] != ',' || arg[1] == '\0')
9387         error (_("Format string required"));
9388       else
9389         {
9390           /* Skip the comma.  */
9391           ++arg;
9392         }
9393     }
9394
9395   create_breakpoint (get_current_arch (),
9396                      location.get (),
9397                      NULL, 0, arg, false, 1 /* parse arg */,
9398                      0, bp_dprintf,
9399                      0 /* Ignore count */,
9400                      pending_break_support,
9401                      &dprintf_breakpoint_ops,
9402                      from_tty,
9403                      1 /* enabled */,
9404                      0 /* internal */,
9405                      0);
9406 }
9407
9408 static void
9409 agent_printf_command (const char *arg, int from_tty)
9410 {
9411   error (_("May only run agent-printf on the target"));
9412 }
9413
9414 /* Implement the "breakpoint_hit" breakpoint_ops method for
9415    ranged breakpoints.  */
9416
9417 static int
9418 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9419                                   const address_space *aspace,
9420                                   CORE_ADDR bp_addr,
9421                                   const target_waitstatus &ws)
9422 {
9423   if (ws.kind () != TARGET_WAITKIND_STOPPED
9424       || ws.sig () != GDB_SIGNAL_TRAP)
9425     return 0;
9426
9427   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9428                                          bl->length, aspace, bp_addr);
9429 }
9430
9431 /* Implement the "resources_needed" breakpoint_ops method for
9432    ranged breakpoints.  */
9433
9434 static int
9435 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9436 {
9437   return target_ranged_break_num_registers ();
9438 }
9439
9440 /* Implement the "print_it" breakpoint_ops method for
9441    ranged breakpoints.  */
9442
9443 static enum print_stop_action
9444 print_it_ranged_breakpoint (bpstat *bs)
9445 {
9446   struct breakpoint *b = bs->breakpoint_at;
9447   struct bp_location *bl = b->loc;
9448   struct ui_out *uiout = current_uiout;
9449
9450   gdb_assert (b->type == bp_hardware_breakpoint);
9451
9452   /* Ranged breakpoints have only one location.  */
9453   gdb_assert (bl && bl->next == NULL);
9454
9455   annotate_breakpoint (b->number);
9456
9457   maybe_print_thread_hit_breakpoint (uiout);
9458
9459   if (b->disposition == disp_del)
9460     uiout->text ("Temporary ranged breakpoint ");
9461   else
9462     uiout->text ("Ranged breakpoint ");
9463   if (uiout->is_mi_like_p ())
9464     {
9465       uiout->field_string ("reason",
9466                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9467       uiout->field_string ("disp", bpdisp_text (b->disposition));
9468     }
9469   uiout->field_signed ("bkptno", b->number);
9470   uiout->text (", ");
9471
9472   return PRINT_SRC_AND_LOC;
9473 }
9474
9475 /* Implement the "print_one" breakpoint_ops method for
9476    ranged breakpoints.  */
9477
9478 static void
9479 print_one_ranged_breakpoint (struct breakpoint *b,
9480                              struct bp_location **last_loc)
9481 {
9482   struct bp_location *bl = b->loc;
9483   struct value_print_options opts;
9484   struct ui_out *uiout = current_uiout;
9485
9486   /* Ranged breakpoints have only one location.  */
9487   gdb_assert (bl && bl->next == NULL);
9488
9489   get_user_print_options (&opts);
9490
9491   if (opts.addressprint)
9492     /* We don't print the address range here, it will be printed later
9493        by print_one_detail_ranged_breakpoint.  */
9494     uiout->field_skip ("addr");
9495   annotate_field (5);
9496   print_breakpoint_location (b, bl);
9497   *last_loc = bl;
9498 }
9499
9500 /* Implement the "print_one_detail" breakpoint_ops method for
9501    ranged breakpoints.  */
9502
9503 static void
9504 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9505                                     struct ui_out *uiout)
9506 {
9507   CORE_ADDR address_start, address_end;
9508   struct bp_location *bl = b->loc;
9509   string_file stb;
9510
9511   gdb_assert (bl);
9512
9513   address_start = bl->address;
9514   address_end = address_start + bl->length - 1;
9515
9516   uiout->text ("\taddress range: ");
9517   stb.printf ("[%s, %s]",
9518               print_core_address (bl->gdbarch, address_start),
9519               print_core_address (bl->gdbarch, address_end));
9520   uiout->field_stream ("addr", stb);
9521   uiout->text ("\n");
9522 }
9523
9524 /* Implement the "print_mention" breakpoint_ops method for
9525    ranged breakpoints.  */
9526
9527 static void
9528 print_mention_ranged_breakpoint (struct breakpoint *b)
9529 {
9530   struct bp_location *bl = b->loc;
9531   struct ui_out *uiout = current_uiout;
9532
9533   gdb_assert (bl);
9534   gdb_assert (b->type == bp_hardware_breakpoint);
9535
9536   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9537                   b->number, paddress (bl->gdbarch, bl->address),
9538                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9539 }
9540
9541 /* Implement the "print_recreate" breakpoint_ops method for
9542    ranged breakpoints.  */
9543
9544 static void
9545 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9546 {
9547   gdb_printf (fp, "break-range %s, %s",
9548               event_location_to_string (b->location.get ()),
9549               event_location_to_string (b->location_range_end.get ()));
9550   print_recreate_thread (b, fp);
9551 }
9552
9553 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9554
9555 static struct breakpoint_ops ranged_breakpoint_ops;
9556
9557 /* Find the address where the end of the breakpoint range should be
9558    placed, given the SAL of the end of the range.  This is so that if
9559    the user provides a line number, the end of the range is set to the
9560    last instruction of the given line.  */
9561
9562 static CORE_ADDR
9563 find_breakpoint_range_end (struct symtab_and_line sal)
9564 {
9565   CORE_ADDR end;
9566
9567   /* If the user provided a PC value, use it.  Otherwise,
9568      find the address of the end of the given location.  */
9569   if (sal.explicit_pc)
9570     end = sal.pc;
9571   else
9572     {
9573       int ret;
9574       CORE_ADDR start;
9575
9576       ret = find_line_pc_range (sal, &start, &end);
9577       if (!ret)
9578         error (_("Could not find location of the end of the range."));
9579
9580       /* find_line_pc_range returns the start of the next line.  */
9581       end--;
9582     }
9583
9584   return end;
9585 }
9586
9587 /* Implement the "break-range" CLI command.  */
9588
9589 static void
9590 break_range_command (const char *arg, int from_tty)
9591 {
9592   const char *arg_start;
9593   struct linespec_result canonical_start, canonical_end;
9594   int bp_count, can_use_bp, length;
9595   CORE_ADDR end;
9596   struct breakpoint *b;
9597
9598   /* We don't support software ranged breakpoints.  */
9599   if (target_ranged_break_num_registers () < 0)
9600     error (_("This target does not support hardware ranged breakpoints."));
9601
9602   bp_count = hw_breakpoint_used_count ();
9603   bp_count += target_ranged_break_num_registers ();
9604   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9605                                                    bp_count, 0);
9606   if (can_use_bp < 0)
9607     error (_("Hardware breakpoints used exceeds limit."));
9608
9609   arg = skip_spaces (arg);
9610   if (arg == NULL || arg[0] == '\0')
9611     error(_("No address range specified."));
9612
9613   arg_start = arg;
9614   event_location_up start_location = string_to_event_location (&arg,
9615                                                                current_language);
9616   parse_breakpoint_sals (start_location.get (), &canonical_start);
9617
9618   if (arg[0] != ',')
9619     error (_("Too few arguments."));
9620   else if (canonical_start.lsals.empty ())
9621     error (_("Could not find location of the beginning of the range."));
9622
9623   const linespec_sals &lsal_start = canonical_start.lsals[0];
9624
9625   if (canonical_start.lsals.size () > 1
9626       || lsal_start.sals.size () != 1)
9627     error (_("Cannot create a ranged breakpoint with multiple locations."));
9628
9629   const symtab_and_line &sal_start = lsal_start.sals[0];
9630   std::string addr_string_start (arg_start, arg - arg_start);
9631
9632   arg++;        /* Skip the comma.  */
9633   arg = skip_spaces (arg);
9634
9635   /* Parse the end location.  */
9636
9637   arg_start = arg;
9638
9639   /* We call decode_line_full directly here instead of using
9640      parse_breakpoint_sals because we need to specify the start location's
9641      symtab and line as the default symtab and line for the end of the
9642      range.  This makes it possible to have ranges like "foo.c:27, +14",
9643      where +14 means 14 lines from the start location.  */
9644   event_location_up end_location = string_to_event_location (&arg,
9645                                                              current_language);
9646   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9647                     sal_start.symtab, sal_start.line,
9648                     &canonical_end, NULL, NULL);
9649
9650   if (canonical_end.lsals.empty ())
9651     error (_("Could not find location of the end of the range."));
9652
9653   const linespec_sals &lsal_end = canonical_end.lsals[0];
9654   if (canonical_end.lsals.size () > 1
9655       || lsal_end.sals.size () != 1)
9656     error (_("Cannot create a ranged breakpoint with multiple locations."));
9657
9658   const symtab_and_line &sal_end = lsal_end.sals[0];
9659
9660   end = find_breakpoint_range_end (sal_end);
9661   if (sal_start.pc > end)
9662     error (_("Invalid address range, end precedes start."));
9663
9664   length = end - sal_start.pc + 1;
9665   if (length < 0)
9666     /* Length overflowed.  */
9667     error (_("Address range too large."));
9668   else if (length == 1)
9669     {
9670       /* This range is simple enough to be handled by
9671          the `hbreak' command.  */
9672       hbreak_command (&addr_string_start[0], 1);
9673
9674       return;
9675     }
9676
9677   /* Now set up the breakpoint.  */
9678   b = set_raw_breakpoint (get_current_arch (), sal_start,
9679                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9680   set_breakpoint_count (breakpoint_count + 1);
9681   b->number = breakpoint_count;
9682   b->disposition = disp_donttouch;
9683   b->location = std::move (start_location);
9684   b->location_range_end = std::move (end_location);
9685   b->loc->length = length;
9686
9687   mention (b);
9688   gdb::observers::breakpoint_created.notify (b);
9689   update_global_location_list (UGLL_MAY_INSERT);
9690 }
9691
9692 /*  Return non-zero if EXP is verified as constant.  Returned zero
9693     means EXP is variable.  Also the constant detection may fail for
9694     some constant expressions and in such case still falsely return
9695     zero.  */
9696
9697 static bool
9698 watchpoint_exp_is_const (const struct expression *exp)
9699 {
9700   return exp->op->constant_p ();
9701 }
9702
9703 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9704
9705 static void
9706 re_set_watchpoint (struct breakpoint *b)
9707 {
9708   struct watchpoint *w = (struct watchpoint *) b;
9709
9710   /* Watchpoint can be either on expression using entirely global
9711      variables, or it can be on local variables.
9712
9713      Watchpoints of the first kind are never auto-deleted, and even
9714      persist across program restarts.  Since they can use variables
9715      from shared libraries, we need to reparse expression as libraries
9716      are loaded and unloaded.
9717
9718      Watchpoints on local variables can also change meaning as result
9719      of solib event.  For example, if a watchpoint uses both a local
9720      and a global variables in expression, it's a local watchpoint,
9721      but unloading of a shared library will make the expression
9722      invalid.  This is not a very common use case, but we still
9723      re-evaluate expression, to avoid surprises to the user.
9724
9725      Note that for local watchpoints, we re-evaluate it only if
9726      watchpoints frame id is still valid.  If it's not, it means the
9727      watchpoint is out of scope and will be deleted soon.  In fact,
9728      I'm not sure we'll ever be called in this case.
9729
9730      If a local watchpoint's frame id is still valid, then
9731      w->exp_valid_block is likewise valid, and we can safely use it.
9732
9733      Don't do anything about disabled watchpoints, since they will be
9734      reevaluated again when enabled.  */
9735   update_watchpoint (w, 1 /* reparse */);
9736 }
9737
9738 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
9739
9740 static int
9741 insert_watchpoint (struct bp_location *bl)
9742 {
9743   struct watchpoint *w = (struct watchpoint *) bl->owner;
9744   int length = w->exact ? 1 : bl->length;
9745
9746   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9747                                    w->cond_exp.get ());
9748 }
9749
9750 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
9751
9752 static int
9753 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
9754 {
9755   struct watchpoint *w = (struct watchpoint *) bl->owner;
9756   int length = w->exact ? 1 : bl->length;
9757
9758   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9759                                    w->cond_exp.get ());
9760 }
9761
9762 static int
9763 breakpoint_hit_watchpoint (const struct bp_location *bl,
9764                            const address_space *aspace, CORE_ADDR bp_addr,
9765                            const target_waitstatus &ws)
9766 {
9767   struct breakpoint *b = bl->owner;
9768   struct watchpoint *w = (struct watchpoint *) b;
9769
9770   /* Continuable hardware watchpoints are treated as non-existent if the
9771      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9772      some data address).  Otherwise gdb won't stop on a break instruction
9773      in the code (not from a breakpoint) when a hardware watchpoint has
9774      been defined.  Also skip watchpoints which we know did not trigger
9775      (did not match the data address).  */
9776   if (is_hardware_watchpoint (b)
9777       && w->watchpoint_triggered == watch_triggered_no)
9778     return 0;
9779
9780   return 1;
9781 }
9782
9783 static void
9784 check_status_watchpoint (bpstat *bs)
9785 {
9786   gdb_assert (is_watchpoint (bs->breakpoint_at));
9787
9788   bpstat_check_watchpoint (bs);
9789 }
9790
9791 /* Implement the "resources_needed" breakpoint_ops method for
9792    hardware watchpoints.  */
9793
9794 static int
9795 resources_needed_watchpoint (const struct bp_location *bl)
9796 {
9797   struct watchpoint *w = (struct watchpoint *) bl->owner;
9798   int length = w->exact? 1 : bl->length;
9799
9800   return target_region_ok_for_hw_watchpoint (bl->address, length);
9801 }
9802
9803 /* Implement the "works_in_software_mode" breakpoint_ops method for
9804    hardware watchpoints.  */
9805
9806 static int
9807 works_in_software_mode_watchpoint (const struct breakpoint *b)
9808 {
9809   /* Read and access watchpoints only work with hardware support.  */
9810   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
9811 }
9812
9813 static enum print_stop_action
9814 print_it_watchpoint (bpstat *bs)
9815 {
9816   struct breakpoint *b;
9817   enum print_stop_action result;
9818   struct watchpoint *w;
9819   struct ui_out *uiout = current_uiout;
9820
9821   gdb_assert (bs->bp_location_at != NULL);
9822
9823   b = bs->breakpoint_at;
9824   w = (struct watchpoint *) b;
9825
9826   annotate_watchpoint (b->number);
9827   maybe_print_thread_hit_breakpoint (uiout);
9828
9829   string_file stb;
9830
9831   gdb::optional<ui_out_emit_tuple> tuple_emitter;
9832   switch (b->type)
9833     {
9834     case bp_watchpoint:
9835     case bp_hardware_watchpoint:
9836       if (uiout->is_mi_like_p ())
9837         uiout->field_string
9838           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9839       mention (b);
9840       tuple_emitter.emplace (uiout, "value");
9841       uiout->text ("\nOld value = ");
9842       watchpoint_value_print (bs->old_val.get (), &stb);
9843       uiout->field_stream ("old", stb);
9844       uiout->text ("\nNew value = ");
9845       watchpoint_value_print (w->val.get (), &stb);
9846       uiout->field_stream ("new", stb);
9847       uiout->text ("\n");
9848       /* More than one watchpoint may have been triggered.  */
9849       result = PRINT_UNKNOWN;
9850       break;
9851
9852     case bp_read_watchpoint:
9853       if (uiout->is_mi_like_p ())
9854         uiout->field_string
9855           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9856       mention (b);
9857       tuple_emitter.emplace (uiout, "value");
9858       uiout->text ("\nValue = ");
9859       watchpoint_value_print (w->val.get (), &stb);
9860       uiout->field_stream ("value", stb);
9861       uiout->text ("\n");
9862       result = PRINT_UNKNOWN;
9863       break;
9864
9865     case bp_access_watchpoint:
9866       if (bs->old_val != NULL)
9867         {
9868           if (uiout->is_mi_like_p ())
9869             uiout->field_string
9870               ("reason",
9871                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9872           mention (b);
9873           tuple_emitter.emplace (uiout, "value");
9874           uiout->text ("\nOld value = ");
9875           watchpoint_value_print (bs->old_val.get (), &stb);
9876           uiout->field_stream ("old", stb);
9877           uiout->text ("\nNew value = ");
9878         }
9879       else
9880         {
9881           mention (b);
9882           if (uiout->is_mi_like_p ())
9883             uiout->field_string
9884               ("reason",
9885                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9886           tuple_emitter.emplace (uiout, "value");
9887           uiout->text ("\nValue = ");
9888         }
9889       watchpoint_value_print (w->val.get (), &stb);
9890       uiout->field_stream ("new", stb);
9891       uiout->text ("\n");
9892       result = PRINT_UNKNOWN;
9893       break;
9894     default:
9895       result = PRINT_UNKNOWN;
9896     }
9897
9898   return result;
9899 }
9900
9901 /* Implement the "print_mention" breakpoint_ops method for hardware
9902    watchpoints.  */
9903
9904 static void
9905 print_mention_watchpoint (struct breakpoint *b)
9906 {
9907   struct watchpoint *w = (struct watchpoint *) b;
9908   struct ui_out *uiout = current_uiout;
9909   const char *tuple_name;
9910
9911   switch (b->type)
9912     {
9913     case bp_watchpoint:
9914       uiout->text ("Watchpoint ");
9915       tuple_name = "wpt";
9916       break;
9917     case bp_hardware_watchpoint:
9918       uiout->text ("Hardware watchpoint ");
9919       tuple_name = "wpt";
9920       break;
9921     case bp_read_watchpoint:
9922       uiout->text ("Hardware read watchpoint ");
9923       tuple_name = "hw-rwpt";
9924       break;
9925     case bp_access_watchpoint:
9926       uiout->text ("Hardware access (read/write) watchpoint ");
9927       tuple_name = "hw-awpt";
9928       break;
9929     default:
9930       internal_error (__FILE__, __LINE__,
9931                       _("Invalid hardware watchpoint type."));
9932     }
9933
9934   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
9935   uiout->field_signed ("number", b->number);
9936   uiout->text (": ");
9937   uiout->field_string ("exp", w->exp_string.get ());
9938 }
9939
9940 /* Implement the "print_recreate" breakpoint_ops method for
9941    watchpoints.  */
9942
9943 static void
9944 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
9945 {
9946   struct watchpoint *w = (struct watchpoint *) b;
9947
9948   switch (b->type)
9949     {
9950     case bp_watchpoint:
9951     case bp_hardware_watchpoint:
9952       gdb_printf (fp, "watch");
9953       break;
9954     case bp_read_watchpoint:
9955       gdb_printf (fp, "rwatch");
9956       break;
9957     case bp_access_watchpoint:
9958       gdb_printf (fp, "awatch");
9959       break;
9960     default:
9961       internal_error (__FILE__, __LINE__,
9962                       _("Invalid watchpoint type."));
9963     }
9964
9965   gdb_printf (fp, " %s", w->exp_string.get ());
9966   print_recreate_thread (b, fp);
9967 }
9968
9969 /* Implement the "explains_signal" breakpoint_ops method for
9970    watchpoints.  */
9971
9972 static int
9973 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
9974 {
9975   /* A software watchpoint cannot cause a signal other than
9976      GDB_SIGNAL_TRAP.  */
9977   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
9978     return 0;
9979
9980   return 1;
9981 }
9982
9983 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
9984
9985 static struct breakpoint_ops watchpoint_breakpoint_ops;
9986
9987 /* Implement the "insert" breakpoint_ops method for
9988    masked hardware watchpoints.  */
9989
9990 static int
9991 insert_masked_watchpoint (struct bp_location *bl)
9992 {
9993   struct watchpoint *w = (struct watchpoint *) bl->owner;
9994
9995   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
9996                                         bl->watchpoint_type);
9997 }
9998
9999 /* Implement the "remove" breakpoint_ops method for
10000    masked hardware watchpoints.  */
10001
10002 static int
10003 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10004 {
10005   struct watchpoint *w = (struct watchpoint *) bl->owner;
10006
10007   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10008                                         bl->watchpoint_type);
10009 }
10010
10011 /* Implement the "resources_needed" breakpoint_ops method for
10012    masked hardware watchpoints.  */
10013
10014 static int
10015 resources_needed_masked_watchpoint (const struct bp_location *bl)
10016 {
10017   struct watchpoint *w = (struct watchpoint *) bl->owner;
10018
10019   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10020 }
10021
10022 /* Implement the "works_in_software_mode" breakpoint_ops method for
10023    masked hardware watchpoints.  */
10024
10025 static int
10026 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10027 {
10028   return 0;
10029 }
10030
10031 /* Implement the "print_it" breakpoint_ops method for
10032    masked hardware watchpoints.  */
10033
10034 static enum print_stop_action
10035 print_it_masked_watchpoint (bpstat *bs)
10036 {
10037   struct breakpoint *b = bs->breakpoint_at;
10038   struct ui_out *uiout = current_uiout;
10039
10040   /* Masked watchpoints have only one location.  */
10041   gdb_assert (b->loc && b->loc->next == NULL);
10042
10043   annotate_watchpoint (b->number);
10044   maybe_print_thread_hit_breakpoint (uiout);
10045
10046   switch (b->type)
10047     {
10048     case bp_hardware_watchpoint:
10049       if (uiout->is_mi_like_p ())
10050         uiout->field_string
10051           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10052       break;
10053
10054     case bp_read_watchpoint:
10055       if (uiout->is_mi_like_p ())
10056         uiout->field_string
10057           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10058       break;
10059
10060     case bp_access_watchpoint:
10061       if (uiout->is_mi_like_p ())
10062         uiout->field_string
10063           ("reason",
10064            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10065       break;
10066     default:
10067       internal_error (__FILE__, __LINE__,
10068                       _("Invalid hardware watchpoint type."));
10069     }
10070
10071   mention (b);
10072   uiout->text (_("\n\
10073 Check the underlying instruction at PC for the memory\n\
10074 address and value which triggered this watchpoint.\n"));
10075   uiout->text ("\n");
10076
10077   /* More than one watchpoint may have been triggered.  */
10078   return PRINT_UNKNOWN;
10079 }
10080
10081 /* Implement the "print_one_detail" breakpoint_ops method for
10082    masked hardware watchpoints.  */
10083
10084 static void
10085 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10086                                     struct ui_out *uiout)
10087 {
10088   struct watchpoint *w = (struct watchpoint *) b;
10089
10090   /* Masked watchpoints have only one location.  */
10091   gdb_assert (b->loc && b->loc->next == NULL);
10092
10093   uiout->text ("\tmask ");
10094   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10095   uiout->text ("\n");
10096 }
10097
10098 /* Implement the "print_mention" breakpoint_ops method for
10099    masked hardware watchpoints.  */
10100
10101 static void
10102 print_mention_masked_watchpoint (struct breakpoint *b)
10103 {
10104   struct watchpoint *w = (struct watchpoint *) b;
10105   struct ui_out *uiout = current_uiout;
10106   const char *tuple_name;
10107
10108   switch (b->type)
10109     {
10110     case bp_hardware_watchpoint:
10111       uiout->text ("Masked hardware watchpoint ");
10112       tuple_name = "wpt";
10113       break;
10114     case bp_read_watchpoint:
10115       uiout->text ("Masked hardware read watchpoint ");
10116       tuple_name = "hw-rwpt";
10117       break;
10118     case bp_access_watchpoint:
10119       uiout->text ("Masked hardware access (read/write) watchpoint ");
10120       tuple_name = "hw-awpt";
10121       break;
10122     default:
10123       internal_error (__FILE__, __LINE__,
10124                       _("Invalid hardware watchpoint type."));
10125     }
10126
10127   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10128   uiout->field_signed ("number", b->number);
10129   uiout->text (": ");
10130   uiout->field_string ("exp", w->exp_string.get ());
10131 }
10132
10133 /* Implement the "print_recreate" breakpoint_ops method for
10134    masked hardware watchpoints.  */
10135
10136 static void
10137 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10138 {
10139   struct watchpoint *w = (struct watchpoint *) b;
10140
10141   switch (b->type)
10142     {
10143     case bp_hardware_watchpoint:
10144       gdb_printf (fp, "watch");
10145       break;
10146     case bp_read_watchpoint:
10147       gdb_printf (fp, "rwatch");
10148       break;
10149     case bp_access_watchpoint:
10150       gdb_printf (fp, "awatch");
10151       break;
10152     default:
10153       internal_error (__FILE__, __LINE__,
10154                       _("Invalid hardware watchpoint type."));
10155     }
10156
10157   gdb_printf (fp, " %s mask 0x%s", w->exp_string.get (),
10158               phex (w->hw_wp_mask, sizeof (CORE_ADDR)));
10159   print_recreate_thread (b, fp);
10160 }
10161
10162 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10163
10164 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10165
10166 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10167
10168 static bool
10169 is_masked_watchpoint (const struct breakpoint *b)
10170 {
10171   return b->ops == &masked_watchpoint_breakpoint_ops;
10172 }
10173
10174 /* accessflag:  hw_write:  watch write, 
10175                 hw_read:   watch read, 
10176                 hw_access: watch access (read or write) */
10177 static void
10178 watch_command_1 (const char *arg, int accessflag, int from_tty,
10179                  bool just_location, bool internal)
10180 {
10181   struct breakpoint *scope_breakpoint = NULL;
10182   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10183   struct value *result;
10184   int saved_bitpos = 0, saved_bitsize = 0;
10185   const char *exp_start = NULL;
10186   const char *exp_end = NULL;
10187   const char *tok, *end_tok;
10188   int toklen = -1;
10189   const char *cond_start = NULL;
10190   const char *cond_end = NULL;
10191   enum bptype bp_type;
10192   int thread = -1;
10193   /* Flag to indicate whether we are going to use masks for
10194      the hardware watchpoint.  */
10195   bool use_mask = false;
10196   CORE_ADDR mask = 0;
10197   int task = 0;
10198
10199   /* Make sure that we actually have parameters to parse.  */
10200   if (arg != NULL && arg[0] != '\0')
10201     {
10202       const char *value_start;
10203
10204       exp_end = arg + strlen (arg);
10205
10206       /* Look for "parameter value" pairs at the end
10207          of the arguments string.  */
10208       for (tok = exp_end - 1; tok > arg; tok--)
10209         {
10210           /* Skip whitespace at the end of the argument list.  */
10211           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10212             tok--;
10213
10214           /* Find the beginning of the last token.
10215              This is the value of the parameter.  */
10216           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10217             tok--;
10218           value_start = tok + 1;
10219
10220           /* Skip whitespace.  */
10221           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10222             tok--;
10223
10224           end_tok = tok;
10225
10226           /* Find the beginning of the second to last token.
10227              This is the parameter itself.  */
10228           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10229             tok--;
10230           tok++;
10231           toklen = end_tok - tok + 1;
10232
10233           if (toklen == 6 && startswith (tok, "thread"))
10234             {
10235               struct thread_info *thr;
10236               /* At this point we've found a "thread" token, which means
10237                  the user is trying to set a watchpoint that triggers
10238                  only in a specific thread.  */
10239               const char *endp;
10240
10241               if (thread != -1)
10242                 error(_("You can specify only one thread."));
10243
10244               /* Extract the thread ID from the next token.  */
10245               thr = parse_thread_id (value_start, &endp);
10246
10247               /* Check if the user provided a valid thread ID.  */
10248               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10249                 invalid_thread_id_error (value_start);
10250
10251               thread = thr->global_num;
10252             }
10253           else if (toklen == 4 && startswith (tok, "task"))
10254             {
10255               char *tmp;
10256
10257               task = strtol (value_start, &tmp, 0);
10258               if (tmp == value_start)
10259                 error (_("Junk after task keyword."));
10260               if (!valid_task_id (task))
10261                 error (_("Unknown task %d."), task);
10262             }
10263           else if (toklen == 4 && startswith (tok, "mask"))
10264             {
10265               /* We've found a "mask" token, which means the user wants to
10266                  create a hardware watchpoint that is going to have the mask
10267                  facility.  */
10268               struct value *mask_value, *mark;
10269
10270               if (use_mask)
10271                 error(_("You can specify only one mask."));
10272
10273               use_mask = just_location = true;
10274
10275               mark = value_mark ();
10276               mask_value = parse_to_comma_and_eval (&value_start);
10277               mask = value_as_address (mask_value);
10278               value_free_to_mark (mark);
10279             }
10280           else
10281             /* We didn't recognize what we found.  We should stop here.  */
10282             break;
10283
10284           /* Truncate the string and get rid of the "parameter value" pair before
10285              the arguments string is parsed by the parse_exp_1 function.  */
10286           exp_end = tok;
10287         }
10288     }
10289   else
10290     exp_end = arg;
10291
10292   /* Parse the rest of the arguments.  From here on out, everything
10293      is in terms of a newly allocated string instead of the original
10294      ARG.  */
10295   std::string expression (arg, exp_end - arg);
10296   exp_start = arg = expression.c_str ();
10297   innermost_block_tracker tracker;
10298   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10299   exp_end = arg;
10300   /* Remove trailing whitespace from the expression before saving it.
10301      This makes the eventual display of the expression string a bit
10302      prettier.  */
10303   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10304     --exp_end;
10305
10306   /* Checking if the expression is not constant.  */
10307   if (watchpoint_exp_is_const (exp.get ()))
10308     {
10309       int len;
10310
10311       len = exp_end - exp_start;
10312       while (len > 0 && isspace (exp_start[len - 1]))
10313         len--;
10314       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10315     }
10316
10317   exp_valid_block = tracker.block ();
10318   struct value *mark = value_mark ();
10319   struct value *val_as_value = nullptr;
10320   fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
10321                       just_location);
10322
10323   if (val_as_value != NULL && just_location)
10324     {
10325       saved_bitpos = value_bitpos (val_as_value);
10326       saved_bitsize = value_bitsize (val_as_value);
10327     }
10328
10329   value_ref_ptr val;
10330   if (just_location)
10331     {
10332       int ret;
10333
10334       exp_valid_block = NULL;
10335       val = release_value (value_addr (result));
10336       value_free_to_mark (mark);
10337
10338       if (use_mask)
10339         {
10340           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10341                                                    mask);
10342           if (ret == -1)
10343             error (_("This target does not support masked watchpoints."));
10344           else if (ret == -2)
10345             error (_("Invalid mask or memory region."));
10346         }
10347     }
10348   else if (val_as_value != NULL)
10349     val = release_value (val_as_value);
10350
10351   tok = skip_spaces (arg);
10352   end_tok = skip_to_space (tok);
10353
10354   toklen = end_tok - tok;
10355   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10356     {
10357       tok = cond_start = end_tok + 1;
10358       innermost_block_tracker if_tracker;
10359       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10360
10361       /* The watchpoint expression may not be local, but the condition
10362          may still be.  E.g.: `watch global if local > 0'.  */
10363       cond_exp_valid_block = if_tracker.block ();
10364
10365       cond_end = tok;
10366     }
10367   if (*tok)
10368     error (_("Junk at end of command."));
10369
10370   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10371
10372   /* Save this because create_internal_breakpoint below invalidates
10373      'wp_frame'.  */
10374   frame_id watchpoint_frame = get_frame_id (wp_frame);
10375
10376   /* If the expression is "local", then set up a "watchpoint scope"
10377      breakpoint at the point where we've left the scope of the watchpoint
10378      expression.  Create the scope breakpoint before the watchpoint, so
10379      that we will encounter it first in bpstat_stop_status.  */
10380   if (exp_valid_block != NULL && wp_frame != NULL)
10381     {
10382       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10383
10384       if (frame_id_p (caller_frame_id))
10385         {
10386           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10387           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10388
10389           scope_breakpoint
10390             = create_internal_breakpoint (caller_arch, caller_pc,
10391                                           bp_watchpoint_scope,
10392                                           &momentary_breakpoint_ops);
10393
10394           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10395           wp_frame = NULL;
10396
10397           scope_breakpoint->enable_state = bp_enabled;
10398
10399           /* Automatically delete the breakpoint when it hits.  */
10400           scope_breakpoint->disposition = disp_del;
10401
10402           /* Only break in the proper frame (help with recursion).  */
10403           scope_breakpoint->frame_id = caller_frame_id;
10404
10405           /* Set the address at which we will stop.  */
10406           scope_breakpoint->loc->gdbarch = caller_arch;
10407           scope_breakpoint->loc->requested_address = caller_pc;
10408           scope_breakpoint->loc->address
10409             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10410                                          scope_breakpoint->loc->requested_address,
10411                                          scope_breakpoint->type);
10412         }
10413     }
10414
10415   /* Now set up the breakpoint.  We create all watchpoints as hardware
10416      watchpoints here even if hardware watchpoints are turned off, a call
10417      to update_watchpoint later in this function will cause the type to
10418      drop back to bp_watchpoint (software watchpoint) if required.  */
10419
10420   if (accessflag == hw_read)
10421     bp_type = bp_read_watchpoint;
10422   else if (accessflag == hw_access)
10423     bp_type = bp_access_watchpoint;
10424   else
10425     bp_type = bp_hardware_watchpoint;
10426
10427   std::unique_ptr<watchpoint> w (new watchpoint ());
10428
10429   if (use_mask)
10430     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10431                                           &masked_watchpoint_breakpoint_ops);
10432   else
10433     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10434                                           &watchpoint_breakpoint_ops);
10435   w->thread = thread;
10436   w->task = task;
10437   w->disposition = disp_donttouch;
10438   w->pspace = current_program_space;
10439   w->exp = std::move (exp);
10440   w->exp_valid_block = exp_valid_block;
10441   w->cond_exp_valid_block = cond_exp_valid_block;
10442   if (just_location)
10443     {
10444       struct type *t = value_type (val.get ());
10445       CORE_ADDR addr = value_as_address (val.get ());
10446
10447       w->exp_string_reparse
10448         = current_language->watch_location_expression (t, addr);
10449
10450       w->exp_string = xstrprintf ("-location %.*s",
10451                                   (int) (exp_end - exp_start), exp_start);
10452     }
10453   else
10454     w->exp_string.reset (savestring (exp_start, exp_end - exp_start));
10455
10456   if (use_mask)
10457     {
10458       w->hw_wp_mask = mask;
10459     }
10460   else
10461     {
10462       w->val = val;
10463       w->val_bitpos = saved_bitpos;
10464       w->val_bitsize = saved_bitsize;
10465       w->val_valid = true;
10466     }
10467
10468   if (cond_start)
10469     w->cond_string.reset (savestring (cond_start, cond_end - cond_start));
10470   else
10471     w->cond_string = 0;
10472
10473   if (frame_id_p (watchpoint_frame))
10474     {
10475       w->watchpoint_frame = watchpoint_frame;
10476       w->watchpoint_thread = inferior_ptid;
10477     }
10478   else
10479     {
10480       w->watchpoint_frame = null_frame_id;
10481       w->watchpoint_thread = null_ptid;
10482     }
10483
10484   if (scope_breakpoint != NULL)
10485     {
10486       /* The scope breakpoint is related to the watchpoint.  We will
10487          need to act on them together.  */
10488       w->related_breakpoint = scope_breakpoint;
10489       scope_breakpoint->related_breakpoint = w.get ();
10490     }
10491
10492   if (!just_location)
10493     value_free_to_mark (mark);
10494
10495   /* Finally update the new watchpoint.  This creates the locations
10496      that should be inserted.  */
10497   update_watchpoint (w.get (), 1);
10498
10499   install_breakpoint (internal, std::move (w), 1);
10500 }
10501
10502 /* Return count of debug registers needed to watch the given expression.
10503    If the watchpoint cannot be handled in hardware return zero.  */
10504
10505 static int
10506 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10507 {
10508   int found_memory_cnt = 0;
10509
10510   /* Did the user specifically forbid us to use hardware watchpoints? */
10511   if (!can_use_hw_watchpoints)
10512     return 0;
10513
10514   gdb_assert (!vals.empty ());
10515   struct value *head = vals[0].get ();
10516
10517   /* Make sure that the value of the expression depends only upon
10518      memory contents, and values computed from them within GDB.  If we
10519      find any register references or function calls, we can't use a
10520      hardware watchpoint.
10521
10522      The idea here is that evaluating an expression generates a series
10523      of values, one holding the value of every subexpression.  (The
10524      expression a*b+c has five subexpressions: a, b, a*b, c, and
10525      a*b+c.)  GDB's values hold almost enough information to establish
10526      the criteria given above --- they identify memory lvalues,
10527      register lvalues, computed values, etcetera.  So we can evaluate
10528      the expression, and then scan the chain of values that leaves
10529      behind to decide whether we can detect any possible change to the
10530      expression's final value using only hardware watchpoints.
10531
10532      However, I don't think that the values returned by inferior
10533      function calls are special in any way.  So this function may not
10534      notice that an expression involving an inferior function call
10535      can't be watched with hardware watchpoints.  FIXME.  */
10536   for (const value_ref_ptr &iter : vals)
10537     {
10538       struct value *v = iter.get ();
10539
10540       if (VALUE_LVAL (v) == lval_memory)
10541         {
10542           if (v != head && value_lazy (v))
10543             /* A lazy memory lvalue in the chain is one that GDB never
10544                needed to fetch; we either just used its address (e.g.,
10545                `a' in `a.b') or we never needed it at all (e.g., `a'
10546                in `a,b').  This doesn't apply to HEAD; if that is
10547                lazy then it was not readable, but watch it anyway.  */
10548             ;
10549           else
10550             {
10551               /* Ahh, memory we actually used!  Check if we can cover
10552                  it with hardware watchpoints.  */
10553               struct type *vtype = check_typedef (value_type (v));
10554
10555               /* We only watch structs and arrays if user asked for it
10556                  explicitly, never if they just happen to appear in a
10557                  middle of some value chain.  */
10558               if (v == head
10559                   || (vtype->code () != TYPE_CODE_STRUCT
10560                       && vtype->code () != TYPE_CODE_ARRAY))
10561                 {
10562                   CORE_ADDR vaddr = value_address (v);
10563                   int len;
10564                   int num_regs;
10565
10566                   len = (target_exact_watchpoints
10567                          && is_scalar_type_recursive (vtype))?
10568                     1 : TYPE_LENGTH (value_type (v));
10569
10570                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10571                   if (!num_regs)
10572                     return 0;
10573                   else
10574                     found_memory_cnt += num_regs;
10575                 }
10576             }
10577         }
10578       else if (VALUE_LVAL (v) != not_lval
10579                && deprecated_value_modifiable (v) == 0)
10580         return 0;       /* These are values from the history (e.g., $1).  */
10581       else if (VALUE_LVAL (v) == lval_register)
10582         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10583     }
10584
10585   /* The expression itself looks suitable for using a hardware
10586      watchpoint, but give the target machine a chance to reject it.  */
10587   return found_memory_cnt;
10588 }
10589
10590 void
10591 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10592 {
10593   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10594 }
10595
10596 /* Options for the watch, awatch, and rwatch commands.  */
10597
10598 struct watch_options
10599 {
10600   /* For -location.  */
10601   bool location = false;
10602 };
10603
10604 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10605
10606    Historically GDB always accepted both '-location' and '-l' flags for
10607    these commands (both flags being synonyms).  When converting to the
10608    newer option scheme only '-location' is added here.  That's fine (for
10609    backward compatibility) as any non-ambiguous prefix of a flag will be
10610    accepted, so '-l', '-loc', are now all accepted.
10611
10612    What this means is that, if in the future, we add any new flag here
10613    that starts with '-l' then this will break backward compatibility, so
10614    please, don't do that!  */
10615
10616 static const gdb::option::option_def watch_option_defs[] = {
10617   gdb::option::flag_option_def<watch_options> {
10618     "location",
10619     [] (watch_options *opt) { return &opt->location; },
10620     N_("\
10621 This evaluates EXPRESSION and watches the memory to which is refers.\n\
10622 -l can be used as a short form of -location."),
10623   },
10624 };
10625
10626 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
10627    commands.  */
10628
10629 static gdb::option::option_def_group
10630 make_watch_options_def_group (watch_options *opts)
10631 {
10632   return {{watch_option_defs}, opts};
10633 }
10634
10635 /* A helper function that looks for the "-location" argument and then
10636    calls watch_command_1.  */
10637
10638 static void
10639 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10640 {
10641   watch_options opts;
10642   auto grp = make_watch_options_def_group (&opts);
10643   gdb::option::process_options
10644     (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
10645   if (arg != nullptr && *arg == '\0')
10646     arg = nullptr;
10647
10648   watch_command_1 (arg, accessflag, from_tty, opts.location, false);
10649 }
10650
10651 /* Command completion for 'watch', 'awatch', and 'rwatch' commands.   */
10652 static void
10653 watch_command_completer (struct cmd_list_element *ignore,
10654                          completion_tracker &tracker,
10655                          const char *text, const char * /*word*/)
10656 {
10657   const auto group = make_watch_options_def_group (nullptr);
10658   if (gdb::option::complete_options
10659       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
10660     return;
10661
10662   const char *word = advance_to_expression_complete_word_point (tracker, text);
10663   expression_completer (ignore, tracker, text, word);
10664 }
10665
10666 static void
10667 watch_command (const char *arg, int from_tty)
10668 {
10669   watch_maybe_just_location (arg, hw_write, from_tty);
10670 }
10671
10672 void
10673 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
10674 {
10675   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10676 }
10677
10678 static void
10679 rwatch_command (const char *arg, int from_tty)
10680 {
10681   watch_maybe_just_location (arg, hw_read, from_tty);
10682 }
10683
10684 void
10685 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
10686 {
10687   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10688 }
10689
10690 static void
10691 awatch_command (const char *arg, int from_tty)
10692 {
10693   watch_maybe_just_location (arg, hw_access, from_tty);
10694 }
10695 \f
10696
10697 /* Data for the FSM that manages the until(location)/advance commands
10698    in infcmd.c.  Here because it uses the mechanisms of
10699    breakpoints.  */
10700
10701 struct until_break_fsm : public thread_fsm
10702 {
10703   /* The thread that was current when the command was executed.  */
10704   int thread;
10705
10706   /* The breakpoint set at the return address in the caller frame,
10707      plus breakpoints at all the destination locations.  */
10708   std::vector<breakpoint_up> breakpoints;
10709
10710   until_break_fsm (struct interp *cmd_interp, int thread,
10711                    std::vector<breakpoint_up> &&breakpoints)
10712     : thread_fsm (cmd_interp),
10713       thread (thread),
10714       breakpoints (std::move (breakpoints))
10715   {
10716   }
10717
10718   void clean_up (struct thread_info *thread) override;
10719   bool should_stop (struct thread_info *thread) override;
10720   enum async_reply_reason do_async_reply_reason () override;
10721 };
10722
10723 /* Implementation of the 'should_stop' FSM method for the
10724    until(location)/advance commands.  */
10725
10726 bool
10727 until_break_fsm::should_stop (struct thread_info *tp)
10728 {
10729   for (const breakpoint_up &bp : breakpoints)
10730     if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10731                                 bp.get ()) != NULL)
10732       {
10733         set_finished ();
10734         break;
10735       }
10736
10737   return true;
10738 }
10739
10740 /* Implementation of the 'clean_up' FSM method for the
10741    until(location)/advance commands.  */
10742
10743 void
10744 until_break_fsm::clean_up (struct thread_info *)
10745 {
10746   /* Clean up our temporary breakpoints.  */
10747   breakpoints.clear ();
10748   delete_longjmp_breakpoint (thread);
10749 }
10750
10751 /* Implementation of the 'async_reply_reason' FSM method for the
10752    until(location)/advance commands.  */
10753
10754 enum async_reply_reason
10755 until_break_fsm::do_async_reply_reason ()
10756 {
10757   return EXEC_ASYNC_LOCATION_REACHED;
10758 }
10759
10760 void
10761 until_break_command (const char *arg, int from_tty, int anywhere)
10762 {
10763   struct frame_info *frame;
10764   struct gdbarch *frame_gdbarch;
10765   struct frame_id stack_frame_id;
10766   struct frame_id caller_frame_id;
10767   int thread;
10768   struct thread_info *tp;
10769
10770   clear_proceed_status (0);
10771
10772   /* Set a breakpoint where the user wants it and at return from
10773      this function.  */
10774
10775   event_location_up location = string_to_event_location (&arg, current_language);
10776
10777   std::vector<symtab_and_line> sals
10778     = (last_displayed_sal_is_valid ()
10779        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10780                         get_last_displayed_symtab (),
10781                         get_last_displayed_line ())
10782        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
10783                         NULL, NULL, 0));
10784
10785   if (sals.empty ())
10786     error (_("Couldn't get information on specified line."));
10787
10788   if (*arg)
10789     error (_("Junk at end of arguments."));
10790
10791   tp = inferior_thread ();
10792   thread = tp->global_num;
10793
10794   /* Note linespec handling above invalidates the frame chain.
10795      Installing a breakpoint also invalidates the frame chain (as it
10796      may need to switch threads), so do any frame handling before
10797      that.  */
10798
10799   frame = get_selected_frame (NULL);
10800   frame_gdbarch = get_frame_arch (frame);
10801   stack_frame_id = get_stack_frame_id (frame);
10802   caller_frame_id = frame_unwind_caller_id (frame);
10803
10804   /* Keep within the current frame, or in frames called by the current
10805      one.  */
10806
10807   std::vector<breakpoint_up> breakpoints;
10808
10809   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
10810
10811   if (frame_id_p (caller_frame_id))
10812     {
10813       struct symtab_and_line sal2;
10814       struct gdbarch *caller_gdbarch;
10815
10816       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10817       sal2.pc = frame_unwind_caller_pc (frame);
10818       caller_gdbarch = frame_unwind_caller_arch (frame);
10819
10820       breakpoint_up caller_breakpoint
10821         = set_momentary_breakpoint (caller_gdbarch, sal2,
10822                                     caller_frame_id, bp_until);
10823       breakpoints.emplace_back (std::move (caller_breakpoint));
10824
10825       set_longjmp_breakpoint (tp, caller_frame_id);
10826       lj_deleter.emplace (thread);
10827     }
10828
10829   /* set_momentary_breakpoint could invalidate FRAME.  */
10830   frame = NULL;
10831
10832   /* If the user told us to continue until a specified location, we
10833      don't specify a frame at which we need to stop.  Otherwise,
10834      specify the selected frame, because we want to stop only at the
10835      very same frame.  */
10836   frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
10837
10838   for (symtab_and_line &sal : sals)
10839     {
10840       resolve_sal_pc (&sal);
10841
10842       breakpoint_up location_breakpoint
10843         = set_momentary_breakpoint (frame_gdbarch, sal,
10844                                     stop_frame_id, bp_until);
10845       breakpoints.emplace_back (std::move (location_breakpoint));
10846     }
10847
10848   tp->set_thread_fsm
10849     (std::unique_ptr<thread_fsm>
10850      (new until_break_fsm (command_interp (), tp->global_num,
10851                            std::move (breakpoints))));
10852
10853   if (lj_deleter)
10854     lj_deleter->release ();
10855
10856   proceed (-1, GDB_SIGNAL_DEFAULT);
10857 }
10858
10859 void
10860 init_ada_exception_breakpoint (struct breakpoint *b,
10861                                struct gdbarch *gdbarch,
10862                                struct symtab_and_line sal,
10863                                const char *addr_string,
10864                                const struct breakpoint_ops *ops,
10865                                int tempflag,
10866                                int enabled,
10867                                int from_tty)
10868 {
10869   if (from_tty)
10870     {
10871       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
10872       if (!loc_gdbarch)
10873         loc_gdbarch = gdbarch;
10874
10875       describe_other_breakpoints (loc_gdbarch,
10876                                   sal.pspace, sal.pc, sal.section, -1);
10877       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
10878          version for exception catchpoints, because two catchpoints
10879          used for different exception names will use the same address.
10880          In this case, a "breakpoint ... also set at..." warning is
10881          unproductive.  Besides, the warning phrasing is also a bit
10882          inappropriate, we should use the word catchpoint, and tell
10883          the user what type of catchpoint it is.  The above is good
10884          enough for now, though.  */
10885     }
10886
10887   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
10888
10889   b->enable_state = enabled ? bp_enabled : bp_disabled;
10890   b->disposition = tempflag ? disp_del : disp_donttouch;
10891   b->location = string_to_event_location (&addr_string,
10892                                           language_def (language_ada));
10893   b->language = language_ada;
10894 }
10895
10896 \f
10897
10898 /* Compare two breakpoints and return a strcmp-like result.  */
10899
10900 static int
10901 compare_breakpoints (const breakpoint *a, const breakpoint *b)
10902 {
10903   uintptr_t ua = (uintptr_t) a;
10904   uintptr_t ub = (uintptr_t) b;
10905
10906   if (a->number < b->number)
10907     return -1;
10908   else if (a->number > b->number)
10909     return 1;
10910
10911   /* Now sort by address, in case we see, e..g, two breakpoints with
10912      the number 0.  */
10913   if (ua < ub)
10914     return -1;
10915   return ua > ub ? 1 : 0;
10916 }
10917
10918 /* Delete breakpoints by address or line.  */
10919
10920 static void
10921 clear_command (const char *arg, int from_tty)
10922 {
10923   int default_match;
10924
10925   std::vector<symtab_and_line> decoded_sals;
10926   symtab_and_line last_sal;
10927   gdb::array_view<symtab_and_line> sals;
10928   if (arg)
10929     {
10930       decoded_sals
10931         = decode_line_with_current_source (arg,
10932                                            (DECODE_LINE_FUNFIRSTLINE
10933                                             | DECODE_LINE_LIST_MODE));
10934       default_match = 0;
10935       sals = decoded_sals;
10936     }
10937   else
10938     {
10939       /* Set sal's line, symtab, pc, and pspace to the values
10940          corresponding to the last call to print_frame_info.  If the
10941          codepoint is not valid, this will set all the fields to 0.  */
10942       last_sal = get_last_displayed_sal ();
10943       if (last_sal.symtab == 0)
10944         error (_("No source file specified."));
10945
10946       default_match = 1;
10947       sals = last_sal;
10948     }
10949
10950   /* We don't call resolve_sal_pc here.  That's not as bad as it
10951      seems, because all existing breakpoints typically have both
10952      file/line and pc set.  So, if clear is given file/line, we can
10953      match this to existing breakpoint without obtaining pc at all.
10954
10955      We only support clearing given the address explicitly 
10956      present in breakpoint table.  Say, we've set breakpoint 
10957      at file:line.  There were several PC values for that file:line,
10958      due to optimization, all in one block.
10959
10960      We've picked one PC value.  If "clear" is issued with another
10961      PC corresponding to the same file:line, the breakpoint won't
10962      be cleared.  We probably can still clear the breakpoint, but 
10963      since the other PC value is never presented to user, user
10964      can only find it by guessing, and it does not seem important
10965      to support that.  */
10966
10967   /* For each line spec given, delete bps which correspond to it.  Do
10968      it in two passes, solely to preserve the current behavior that
10969      from_tty is forced true if we delete more than one
10970      breakpoint.  */
10971
10972   std::vector<struct breakpoint *> found;
10973   for (const auto &sal : sals)
10974     {
10975       const char *sal_fullname;
10976
10977       /* If exact pc given, clear bpts at that pc.
10978          If line given (pc == 0), clear all bpts on specified line.
10979          If defaulting, clear all bpts on default line
10980          or at default pc.
10981
10982          defaulting    sal.pc != 0    tests to do
10983
10984          0              1             pc
10985          1              1             pc _and_ line
10986          0              0             line
10987          1              0             <can't happen> */
10988
10989       sal_fullname = (sal.symtab == NULL
10990                       ? NULL : symtab_to_fullname (sal.symtab));
10991
10992       /* Find all matching breakpoints and add them to 'found'.  */
10993       for (breakpoint *b : all_breakpoints ())
10994         {
10995           int match = 0;
10996           /* Are we going to delete b?  */
10997           if (b->type != bp_none && !is_watchpoint (b))
10998             {
10999               for (bp_location *loc : b->locations ())
11000                 {
11001                   /* If the user specified file:line, don't allow a PC
11002                      match.  This matches historical gdb behavior.  */
11003                   int pc_match = (!sal.explicit_line
11004                                   && sal.pc
11005                                   && (loc->pspace == sal.pspace)
11006                                   && (loc->address == sal.pc)
11007                                   && (!section_is_overlay (loc->section)
11008                                       || loc->section == sal.section));
11009                   int line_match = 0;
11010
11011                   if ((default_match || sal.explicit_line)
11012                       && loc->symtab != NULL
11013                       && sal_fullname != NULL
11014                       && sal.pspace == loc->pspace
11015                       && loc->line_number == sal.line
11016                       && filename_cmp (symtab_to_fullname (loc->symtab),
11017                                        sal_fullname) == 0)
11018                     line_match = 1;
11019
11020                   if (pc_match || line_match)
11021                     {
11022                       match = 1;
11023                       break;
11024                     }
11025                 }
11026             }
11027
11028           if (match)
11029             found.push_back (b);
11030         }
11031     }
11032
11033   /* Now go thru the 'found' chain and delete them.  */
11034   if (found.empty ())
11035     {
11036       if (arg)
11037         error (_("No breakpoint at %s."), arg);
11038       else
11039         error (_("No breakpoint at this line."));
11040     }
11041
11042   /* Remove duplicates from the vec.  */
11043   std::sort (found.begin (), found.end (),
11044              [] (const breakpoint *bp_a, const breakpoint *bp_b)
11045              {
11046                return compare_breakpoints (bp_a, bp_b) < 0;
11047              });
11048   found.erase (std::unique (found.begin (), found.end (),
11049                             [] (const breakpoint *bp_a, const breakpoint *bp_b)
11050                             {
11051                               return compare_breakpoints (bp_a, bp_b) == 0;
11052                             }),
11053                found.end ());
11054
11055   if (found.size () > 1)
11056     from_tty = 1;       /* Always report if deleted more than one.  */
11057   if (from_tty)
11058     {
11059       if (found.size () == 1)
11060         gdb_printf (_("Deleted breakpoint "));
11061       else
11062         gdb_printf (_("Deleted breakpoints "));
11063     }
11064
11065   for (breakpoint *iter : found)
11066     {
11067       if (from_tty)
11068         gdb_printf ("%d ", iter->number);
11069       delete_breakpoint (iter);
11070     }
11071   if (from_tty)
11072     gdb_putc ('\n');
11073 }
11074 \f
11075 /* Delete breakpoint in BS if they are `delete' breakpoints and
11076    all breakpoints that are marked for deletion, whether hit or not.
11077    This is called after any breakpoint is hit, or after errors.  */
11078
11079 void
11080 breakpoint_auto_delete (bpstat *bs)
11081 {
11082   for (; bs; bs = bs->next)
11083     if (bs->breakpoint_at
11084         && bs->breakpoint_at->disposition == disp_del
11085         && bs->stop)
11086       delete_breakpoint (bs->breakpoint_at);
11087
11088   for (breakpoint *b : all_breakpoints_safe ())
11089     if (b->disposition == disp_del_at_next_stop)
11090       delete_breakpoint (b);
11091 }
11092
11093 /* A comparison function for bp_location AP and BP being interfaced to
11094    std::sort.  Sort elements primarily by their ADDRESS (no matter what
11095    bl_address_is_meaningful says), secondarily by ordering first
11096    permanent elements and terciarily just ensuring the array is sorted
11097    stable way despite std::sort being an unstable algorithm.  */
11098
11099 static int
11100 bp_location_is_less_than (const bp_location *a, const bp_location *b)
11101 {
11102   if (a->address != b->address)
11103     return a->address < b->address;
11104
11105   /* Sort locations at the same address by their pspace number, keeping
11106      locations of the same inferior (in a multi-inferior environment)
11107      grouped.  */
11108
11109   if (a->pspace->num != b->pspace->num)
11110     return a->pspace->num < b->pspace->num;
11111
11112   /* Sort permanent breakpoints first.  */
11113   if (a->permanent != b->permanent)
11114     return a->permanent > b->permanent;
11115
11116   /* Sort by type in order to make duplicate determination easier.
11117      See update_global_location_list.  This is kept in sync with
11118      breakpoint_locations_match.  */
11119   if (a->loc_type < b->loc_type)
11120     return true;
11121
11122   /* Likewise, for range-breakpoints, sort by length.  */
11123   if (a->loc_type == bp_loc_hardware_breakpoint
11124       && b->loc_type == bp_loc_hardware_breakpoint
11125       && a->length < b->length)
11126     return true;
11127
11128   /* Make the internal GDB representation stable across GDB runs
11129      where A and B memory inside GDB can differ.  Breakpoint locations of
11130      the same type at the same address can be sorted in arbitrary order.  */
11131
11132   if (a->owner->number != b->owner->number)
11133     return a->owner->number < b->owner->number;
11134
11135   return a < b;
11136 }
11137
11138 /* Set bp_locations_placed_address_before_address_max and
11139    bp_locations_shadow_len_after_address_max according to the current
11140    content of the bp_locations array.  */
11141
11142 static void
11143 bp_locations_target_extensions_update (void)
11144 {
11145   bp_locations_placed_address_before_address_max = 0;
11146   bp_locations_shadow_len_after_address_max = 0;
11147
11148   for (bp_location *bl : all_bp_locations ())
11149     {
11150       CORE_ADDR start, end, addr;
11151
11152       if (!bp_location_has_shadow (bl))
11153         continue;
11154
11155       start = bl->target_info.placed_address;
11156       end = start + bl->target_info.shadow_len;
11157
11158       gdb_assert (bl->address >= start);
11159       addr = bl->address - start;
11160       if (addr > bp_locations_placed_address_before_address_max)
11161         bp_locations_placed_address_before_address_max = addr;
11162
11163       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11164
11165       gdb_assert (bl->address < end);
11166       addr = end - bl->address;
11167       if (addr > bp_locations_shadow_len_after_address_max)
11168         bp_locations_shadow_len_after_address_max = addr;
11169     }
11170 }
11171
11172 /* Download tracepoint locations if they haven't been.  */
11173
11174 static void
11175 download_tracepoint_locations (void)
11176 {
11177   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11178
11179   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11180
11181   for (breakpoint *b : all_tracepoints ())
11182     {
11183       struct tracepoint *t;
11184       int bp_location_downloaded = 0;
11185
11186       if ((b->type == bp_fast_tracepoint
11187            ? !may_insert_fast_tracepoints
11188            : !may_insert_tracepoints))
11189         continue;
11190
11191       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11192         {
11193           if (target_can_download_tracepoint ())
11194             can_download_tracepoint = TRIBOOL_TRUE;
11195           else
11196             can_download_tracepoint = TRIBOOL_FALSE;
11197         }
11198
11199       if (can_download_tracepoint == TRIBOOL_FALSE)
11200         break;
11201
11202       for (bp_location *bl : b->locations ())
11203         {
11204           /* In tracepoint, locations are _never_ duplicated, so
11205              should_be_inserted is equivalent to
11206              unduplicated_should_be_inserted.  */
11207           if (!should_be_inserted (bl) || bl->inserted)
11208             continue;
11209
11210           switch_to_program_space_and_thread (bl->pspace);
11211
11212           target_download_tracepoint (bl);
11213
11214           bl->inserted = 1;
11215           bp_location_downloaded = 1;
11216         }
11217       t = (struct tracepoint *) b;
11218       t->number_on_target = b->number;
11219       if (bp_location_downloaded)
11220         gdb::observers::breakpoint_modified.notify (b);
11221     }
11222 }
11223
11224 /* Swap the insertion/duplication state between two locations.  */
11225
11226 static void
11227 swap_insertion (struct bp_location *left, struct bp_location *right)
11228 {
11229   const int left_inserted = left->inserted;
11230   const int left_duplicate = left->duplicate;
11231   const int left_needs_update = left->needs_update;
11232   const struct bp_target_info left_target_info = left->target_info;
11233
11234   /* Locations of tracepoints can never be duplicated.  */
11235   if (is_tracepoint (left->owner))
11236     gdb_assert (!left->duplicate);
11237   if (is_tracepoint (right->owner))
11238     gdb_assert (!right->duplicate);
11239
11240   left->inserted = right->inserted;
11241   left->duplicate = right->duplicate;
11242   left->needs_update = right->needs_update;
11243   left->target_info = right->target_info;
11244   right->inserted = left_inserted;
11245   right->duplicate = left_duplicate;
11246   right->needs_update = left_needs_update;
11247   right->target_info = left_target_info;
11248 }
11249
11250 /* Force the re-insertion of the locations at ADDRESS.  This is called
11251    once a new/deleted/modified duplicate location is found and we are evaluating
11252    conditions on the target's side.  Such conditions need to be updated on
11253    the target.  */
11254
11255 static void
11256 force_breakpoint_reinsertion (struct bp_location *bl)
11257 {
11258   CORE_ADDR address = 0;
11259   int pspace_num;
11260
11261   address = bl->address;
11262   pspace_num = bl->pspace->num;
11263
11264   /* This is only meaningful if the target is
11265      evaluating conditions and if the user has
11266      opted for condition evaluation on the target's
11267      side.  */
11268   if (gdb_evaluates_breakpoint_condition_p ()
11269       || !target_supports_evaluation_of_breakpoint_conditions ())
11270     return;
11271
11272   /* Flag all breakpoint locations with this address and
11273      the same program space as the location
11274      as "its condition has changed".  We need to
11275      update the conditions on the target's side.  */
11276   for (bp_location *loc : all_bp_locations_at_addr (address))
11277     {
11278       if (!is_breakpoint (loc->owner)
11279           || pspace_num != loc->pspace->num)
11280         continue;
11281
11282       /* Flag the location appropriately.  We use a different state to
11283          let everyone know that we already updated the set of locations
11284          with addr bl->address and program space bl->pspace.  This is so
11285          we don't have to keep calling these functions just to mark locations
11286          that have already been marked.  */
11287       loc->condition_changed = condition_updated;
11288
11289       /* Free the agent expression bytecode as well.  We will compute
11290          it later on.  */
11291       loc->cond_bytecode.reset ();
11292     }
11293 }
11294
11295 /* Called whether new breakpoints are created, or existing breakpoints
11296    deleted, to update the global location list and recompute which
11297    locations are duplicate of which.
11298
11299    The INSERT_MODE flag determines whether locations may not, may, or
11300    shall be inserted now.  See 'enum ugll_insert_mode' for more
11301    info.  */
11302
11303 static void
11304 update_global_location_list (enum ugll_insert_mode insert_mode)
11305 {
11306   /* Last breakpoint location address that was marked for update.  */
11307   CORE_ADDR last_addr = 0;
11308   /* Last breakpoint location program space that was marked for update.  */
11309   int last_pspace_num = -1;
11310
11311   /* Used in the duplicates detection below.  When iterating over all
11312      bp_locations, points to the first bp_location of a given address.
11313      Breakpoints and watchpoints of different types are never
11314      duplicates of each other.  Keep one pointer for each type of
11315      breakpoint/watchpoint, so we only need to loop over all locations
11316      once.  */
11317   struct bp_location *bp_loc_first;  /* breakpoint */
11318   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11319   struct bp_location *awp_loc_first; /* access watchpoint */
11320   struct bp_location *rwp_loc_first; /* read watchpoint */
11321
11322   /* Saved former bp_locations array which we compare against the newly
11323      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11324   std::vector<bp_location *> old_locations = std::move (bp_locations);
11325   bp_locations.clear ();
11326
11327   for (breakpoint *b : all_breakpoints ())
11328     for (bp_location *loc : b->locations ())
11329       bp_locations.push_back (loc);
11330
11331   /* See if we need to "upgrade" a software breakpoint to a hardware
11332      breakpoint.  Do this before deciding whether locations are
11333      duplicates.  Also do this before sorting because sorting order
11334      depends on location type.  */
11335   for (bp_location *loc : bp_locations)
11336     if (!loc->inserted && should_be_inserted (loc))
11337         handle_automatic_hardware_breakpoints (loc);
11338
11339   std::sort (bp_locations.begin (), bp_locations.end (),
11340              bp_location_is_less_than);
11341
11342   bp_locations_target_extensions_update ();
11343
11344   /* Identify bp_location instances that are no longer present in the
11345      new list, and therefore should be freed.  Note that it's not
11346      necessary that those locations should be removed from inferior --
11347      if there's another location at the same address (previously
11348      marked as duplicate), we don't need to remove/insert the
11349      location.
11350      
11351      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11352      and former bp_location array state respectively.  */
11353
11354   size_t loc_i = 0;
11355   for (bp_location *old_loc : old_locations)
11356     {
11357       /* Tells if 'old_loc' is found among the new locations.  If
11358          not, we have to free it.  */
11359       int found_object = 0;
11360       /* Tells if the location should remain inserted in the target.  */
11361       int keep_in_target = 0;
11362       int removed = 0;
11363
11364       /* Skip LOCP entries which will definitely never be needed.
11365          Stop either at or being the one matching OLD_LOC.  */
11366       while (loc_i < bp_locations.size ()
11367              && bp_locations[loc_i]->address < old_loc->address)
11368         loc_i++;
11369
11370       for (size_t loc2_i = loc_i;
11371            (loc2_i < bp_locations.size ()
11372             && bp_locations[loc2_i]->address == old_loc->address);
11373            loc2_i++)
11374         {
11375           /* Check if this is a new/duplicated location or a duplicated
11376              location that had its condition modified.  If so, we want to send
11377              its condition to the target if evaluation of conditions is taking
11378              place there.  */
11379           if (bp_locations[loc2_i]->condition_changed == condition_modified
11380               && (last_addr != old_loc->address
11381                   || last_pspace_num != old_loc->pspace->num))
11382             {
11383               force_breakpoint_reinsertion (bp_locations[loc2_i]);
11384               last_pspace_num = old_loc->pspace->num;
11385             }
11386
11387           if (bp_locations[loc2_i] == old_loc)
11388             found_object = 1;
11389         }
11390
11391       /* We have already handled this address, update it so that we don't
11392          have to go through updates again.  */
11393       last_addr = old_loc->address;
11394
11395       /* Target-side condition evaluation: Handle deleted locations.  */
11396       if (!found_object)
11397         force_breakpoint_reinsertion (old_loc);
11398
11399       /* If this location is no longer present, and inserted, look if
11400          there's maybe a new location at the same address.  If so,
11401          mark that one inserted, and don't remove this one.  This is
11402          needed so that we don't have a time window where a breakpoint
11403          at certain location is not inserted.  */
11404
11405       if (old_loc->inserted)
11406         {
11407           /* If the location is inserted now, we might have to remove
11408              it.  */
11409
11410           if (found_object && should_be_inserted (old_loc))
11411             {
11412               /* The location is still present in the location list,
11413                  and still should be inserted.  Don't do anything.  */
11414               keep_in_target = 1;
11415             }
11416           else
11417             {
11418               /* This location still exists, but it won't be kept in the
11419                  target since it may have been disabled.  We proceed to
11420                  remove its target-side condition.  */
11421
11422               /* The location is either no longer present, or got
11423                  disabled.  See if there's another location at the
11424                  same address, in which case we don't need to remove
11425                  this one from the target.  */
11426
11427               /* OLD_LOC comes from existing struct breakpoint.  */
11428               if (bl_address_is_meaningful (old_loc))
11429                 {
11430                   for (size_t loc2_i = loc_i;
11431                        (loc2_i < bp_locations.size ()
11432                         && bp_locations[loc2_i]->address == old_loc->address);
11433                        loc2_i++)
11434                     {
11435                       bp_location *loc2 = bp_locations[loc2_i];
11436
11437                       if (loc2 == old_loc)
11438                         continue;
11439
11440                       if (breakpoint_locations_match (loc2, old_loc))
11441                         {
11442                           /* Read watchpoint locations are switched to
11443                              access watchpoints, if the former are not
11444                              supported, but the latter are.  */
11445                           if (is_hardware_watchpoint (old_loc->owner))
11446                             {
11447                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11448                               loc2->watchpoint_type = old_loc->watchpoint_type;
11449                             }
11450
11451                           /* loc2 is a duplicated location. We need to check
11452                              if it should be inserted in case it will be
11453                              unduplicated.  */
11454                           if (unduplicated_should_be_inserted (loc2))
11455                             {
11456                               swap_insertion (old_loc, loc2);
11457                               keep_in_target = 1;
11458                               break;
11459                             }
11460                         }
11461                     }
11462                 }
11463             }
11464
11465           if (!keep_in_target)
11466             {
11467               if (remove_breakpoint (old_loc))
11468                 {
11469                   /* This is just about all we can do.  We could keep
11470                      this location on the global list, and try to
11471                      remove it next time, but there's no particular
11472                      reason why we will succeed next time.
11473                      
11474                      Note that at this point, old_loc->owner is still
11475                      valid, as delete_breakpoint frees the breakpoint
11476                      only after calling us.  */
11477                   gdb_printf (_("warning: Error removing "
11478                                 "breakpoint %d\n"), 
11479                               old_loc->owner->number);
11480                 }
11481               removed = 1;
11482             }
11483         }
11484
11485       if (!found_object)
11486         {
11487           if (removed && target_is_non_stop_p ()
11488               && need_moribund_for_location_type (old_loc))
11489             {
11490               /* This location was removed from the target.  In
11491                  non-stop mode, a race condition is possible where
11492                  we've removed a breakpoint, but stop events for that
11493                  breakpoint are already queued and will arrive later.
11494                  We apply an heuristic to be able to distinguish such
11495                  SIGTRAPs from other random SIGTRAPs: we keep this
11496                  breakpoint location for a bit, and will retire it
11497                  after we see some number of events.  The theory here
11498                  is that reporting of events should, "on the average",
11499                  be fair, so after a while we'll see events from all
11500                  threads that have anything of interest, and no longer
11501                  need to keep this breakpoint location around.  We
11502                  don't hold locations forever so to reduce chances of
11503                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11504                  SIGTRAP.
11505
11506                  The heuristic failing can be disastrous on
11507                  decr_pc_after_break targets.
11508
11509                  On decr_pc_after_break targets, like e.g., x86-linux,
11510                  if we fail to recognize a late breakpoint SIGTRAP,
11511                  because events_till_retirement has reached 0 too
11512                  soon, we'll fail to do the PC adjustment, and report
11513                  a random SIGTRAP to the user.  When the user resumes
11514                  the inferior, it will most likely immediately crash
11515                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11516                  corrupted, because of being resumed e.g., in the
11517                  middle of a multi-byte instruction, or skipped a
11518                  one-byte instruction.  This was actually seen happen
11519                  on native x86-linux, and should be less rare on
11520                  targets that do not support new thread events, like
11521                  remote, due to the heuristic depending on
11522                  thread_count.
11523
11524                  Mistaking a random SIGTRAP for a breakpoint trap
11525                  causes similar symptoms (PC adjustment applied when
11526                  it shouldn't), but then again, playing with SIGTRAPs
11527                  behind the debugger's back is asking for trouble.
11528
11529                  Since hardware watchpoint traps are always
11530                  distinguishable from other traps, so we don't need to
11531                  apply keep hardware watchpoint moribund locations
11532                  around.  We simply always ignore hardware watchpoint
11533                  traps we can no longer explain.  */
11534
11535               process_stratum_target *proc_target = nullptr;
11536               for (inferior *inf : all_inferiors ())
11537                 if (inf->pspace == old_loc->pspace)
11538                   {
11539                     proc_target = inf->process_target ();
11540                     break;
11541                   }
11542               if (proc_target != nullptr)
11543                 old_loc->events_till_retirement
11544                   = 3 * (thread_count (proc_target) + 1);
11545               else
11546                 old_loc->events_till_retirement = 1;
11547               old_loc->owner = NULL;
11548
11549               moribund_locations.push_back (old_loc);
11550             }
11551           else
11552             {
11553               old_loc->owner = NULL;
11554               decref_bp_location (&old_loc);
11555             }
11556         }
11557     }
11558
11559   /* Rescan breakpoints at the same address and section, marking the
11560      first one as "first" and any others as "duplicates".  This is so
11561      that the bpt instruction is only inserted once.  If we have a
11562      permanent breakpoint at the same place as BPT, make that one the
11563      official one, and the rest as duplicates.  Permanent breakpoints
11564      are sorted first for the same address.
11565
11566      Do the same for hardware watchpoints, but also considering the
11567      watchpoint's type (regular/access/read) and length.  */
11568
11569   bp_loc_first = NULL;
11570   wp_loc_first = NULL;
11571   awp_loc_first = NULL;
11572   rwp_loc_first = NULL;
11573
11574   for (bp_location *loc : all_bp_locations ())
11575     {
11576       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11577          non-NULL.  */
11578       struct bp_location **loc_first_p;
11579       breakpoint *b = loc->owner;
11580
11581       if (!unduplicated_should_be_inserted (loc)
11582           || !bl_address_is_meaningful (loc)
11583           /* Don't detect duplicate for tracepoint locations because they are
11584            never duplicated.  See the comments in field `duplicate' of
11585            `struct bp_location'.  */
11586           || is_tracepoint (b))
11587         {
11588           /* Clear the condition modification flag.  */
11589           loc->condition_changed = condition_unchanged;
11590           continue;
11591         }
11592
11593       if (b->type == bp_hardware_watchpoint)
11594         loc_first_p = &wp_loc_first;
11595       else if (b->type == bp_read_watchpoint)
11596         loc_first_p = &rwp_loc_first;
11597       else if (b->type == bp_access_watchpoint)
11598         loc_first_p = &awp_loc_first;
11599       else
11600         loc_first_p = &bp_loc_first;
11601
11602       if (*loc_first_p == NULL
11603           || (overlay_debugging && loc->section != (*loc_first_p)->section)
11604           || !breakpoint_locations_match (loc, *loc_first_p))
11605         {
11606           *loc_first_p = loc;
11607           loc->duplicate = 0;
11608
11609           if (is_breakpoint (loc->owner) && loc->condition_changed)
11610             {
11611               loc->needs_update = 1;
11612               /* Clear the condition modification flag.  */
11613               loc->condition_changed = condition_unchanged;
11614             }
11615           continue;
11616         }
11617
11618
11619       /* This and the above ensure the invariant that the first location
11620          is not duplicated, and is the inserted one.
11621          All following are marked as duplicated, and are not inserted.  */
11622       if (loc->inserted)
11623         swap_insertion (loc, *loc_first_p);
11624       loc->duplicate = 1;
11625
11626       /* Clear the condition modification flag.  */
11627       loc->condition_changed = condition_unchanged;
11628     }
11629
11630   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
11631     {
11632       if (insert_mode != UGLL_DONT_INSERT)
11633         insert_breakpoint_locations ();
11634       else
11635         {
11636           /* Even though the caller told us to not insert new
11637              locations, we may still need to update conditions on the
11638              target's side of breakpoints that were already inserted
11639              if the target is evaluating breakpoint conditions.  We
11640              only update conditions for locations that are marked
11641              "needs_update".  */
11642           update_inserted_breakpoint_locations ();
11643         }
11644     }
11645
11646   if (insert_mode != UGLL_DONT_INSERT)
11647     download_tracepoint_locations ();
11648 }
11649
11650 void
11651 breakpoint_retire_moribund (void)
11652 {
11653   for (int ix = 0; ix < moribund_locations.size (); ++ix)
11654     {
11655       struct bp_location *loc = moribund_locations[ix];
11656       if (--(loc->events_till_retirement) == 0)
11657         {
11658           decref_bp_location (&loc);
11659           unordered_remove (moribund_locations, ix);
11660           --ix;
11661         }
11662     }
11663 }
11664
11665 static void
11666 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
11667 {
11668
11669   try
11670     {
11671       update_global_location_list (insert_mode);
11672     }
11673   catch (const gdb_exception_error &e)
11674     {
11675     }
11676 }
11677
11678 /* Clear BKP from a BPS.  */
11679
11680 static void
11681 bpstat_remove_bp_location (bpstat *bps, struct breakpoint *bpt)
11682 {
11683   bpstat *bs;
11684
11685   for (bs = bps; bs; bs = bs->next)
11686     if (bs->breakpoint_at == bpt)
11687       {
11688         bs->breakpoint_at = NULL;
11689         bs->old_val = NULL;
11690         /* bs->commands will be freed later.  */
11691       }
11692 }
11693
11694 /* Callback for iterate_over_threads.  */
11695 static int
11696 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11697 {
11698   struct breakpoint *bpt = (struct breakpoint *) data;
11699
11700   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11701   return 0;
11702 }
11703
11704 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
11705    callbacks.  */
11706
11707 static void
11708 say_where (struct breakpoint *b)
11709 {
11710   struct value_print_options opts;
11711
11712   get_user_print_options (&opts);
11713
11714   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11715      single string.  */
11716   if (b->loc == NULL)
11717     {
11718       /* For pending locations, the output differs slightly based
11719          on b->extra_string.  If this is non-NULL, it contains either
11720          a condition or dprintf arguments.  */
11721       if (b->extra_string == NULL)
11722         {
11723           gdb_printf (_(" (%s) pending."),
11724                       event_location_to_string (b->location.get ()));
11725         }
11726       else if (b->type == bp_dprintf)
11727         {
11728           gdb_printf (_(" (%s,%s) pending."),
11729                       event_location_to_string (b->location.get ()),
11730                       b->extra_string.get ());
11731         }
11732       else
11733         {
11734           gdb_printf (_(" (%s %s) pending."),
11735                       event_location_to_string (b->location.get ()),
11736                       b->extra_string.get ());
11737         }
11738     }
11739   else
11740     {
11741       if (opts.addressprint || b->loc->symtab == NULL)
11742         gdb_printf (" at %ps",
11743                     styled_string (address_style.style (),
11744                                    paddress (b->loc->gdbarch,
11745                                              b->loc->address)));
11746       if (b->loc->symtab != NULL)
11747         {
11748           /* If there is a single location, we can print the location
11749              more nicely.  */
11750           if (b->loc->next == NULL)
11751             {
11752               const char *filename
11753                 = symtab_to_filename_for_display (b->loc->symtab);
11754               gdb_printf (": file %ps, line %d.",
11755                           styled_string (file_name_style.style (),
11756                                          filename),
11757                           b->loc->line_number);
11758             }
11759           else
11760             /* This is not ideal, but each location may have a
11761                different file name, and this at least reflects the
11762                real situation somewhat.  */
11763             gdb_printf (": %s.",
11764                         event_location_to_string (b->location.get ()));
11765         }
11766
11767       if (b->loc->next)
11768         {
11769           struct bp_location *loc = b->loc;
11770           int n = 0;
11771           for (; loc; loc = loc->next)
11772             ++n;
11773           gdb_printf (" (%d locations)", n);
11774         }
11775     }
11776 }
11777
11778 /* See breakpoint.h.  */
11779
11780 bp_location_range breakpoint::locations ()
11781 {
11782   return bp_location_range (this->loc);
11783 }
11784
11785 static struct bp_location *
11786 base_breakpoint_allocate_location (struct breakpoint *self)
11787 {
11788   return new bp_location (self);
11789 }
11790
11791 static void
11792 base_breakpoint_re_set (struct breakpoint *b)
11793 {
11794   /* Nothing to re-set. */
11795 }
11796
11797 #define internal_error_pure_virtual_called() \
11798   gdb_assert_not_reached ("pure virtual function called")
11799
11800 static int
11801 base_breakpoint_insert_location (struct bp_location *bl)
11802 {
11803   internal_error_pure_virtual_called ();
11804 }
11805
11806 static int
11807 base_breakpoint_remove_location (struct bp_location *bl,
11808                                  enum remove_bp_reason reason)
11809 {
11810   internal_error_pure_virtual_called ();
11811 }
11812
11813 static int
11814 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
11815                                 const address_space *aspace,
11816                                 CORE_ADDR bp_addr,
11817                                 const target_waitstatus &ws)
11818 {
11819   internal_error_pure_virtual_called ();
11820 }
11821
11822 static void
11823 base_breakpoint_check_status (bpstat *bs)
11824 {
11825   /* Always stop.   */
11826 }
11827
11828 /* A "works_in_software_mode" breakpoint_ops method that just internal
11829    errors.  */
11830
11831 static int
11832 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
11833 {
11834   internal_error_pure_virtual_called ();
11835 }
11836
11837 /* A "resources_needed" breakpoint_ops method that just internal
11838    errors.  */
11839
11840 static int
11841 base_breakpoint_resources_needed (const struct bp_location *bl)
11842 {
11843   internal_error_pure_virtual_called ();
11844 }
11845
11846 static enum print_stop_action
11847 base_breakpoint_print_it (bpstat *bs)
11848 {
11849   internal_error_pure_virtual_called ();
11850 }
11851
11852 static void
11853 base_breakpoint_print_one_detail (const struct breakpoint *self,
11854                                   struct ui_out *uiout)
11855 {
11856   /* nothing */
11857 }
11858
11859 static void
11860 base_breakpoint_print_mention (struct breakpoint *b)
11861 {
11862   internal_error_pure_virtual_called ();
11863 }
11864
11865 static void
11866 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
11867 {
11868   internal_error_pure_virtual_called ();
11869 }
11870
11871 static void
11872 base_breakpoint_create_sals_from_location
11873   (struct event_location *location,
11874    struct linespec_result *canonical,
11875    enum bptype type_wanted)
11876 {
11877   internal_error_pure_virtual_called ();
11878 }
11879
11880 static void
11881 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
11882                                         struct linespec_result *c,
11883                                         gdb::unique_xmalloc_ptr<char> cond_string,
11884                                         gdb::unique_xmalloc_ptr<char> extra_string,
11885                                         enum bptype type_wanted,
11886                                         enum bpdisp disposition,
11887                                         int thread,
11888                                         int task, int ignore_count,
11889                                         const struct breakpoint_ops *o,
11890                                         int from_tty, int enabled,
11891                                         int internal, unsigned flags)
11892 {
11893   internal_error_pure_virtual_called ();
11894 }
11895
11896 static std::vector<symtab_and_line>
11897 base_breakpoint_decode_location (struct breakpoint *b,
11898                                  struct event_location *location,
11899                                  struct program_space *search_pspace)
11900 {
11901   internal_error_pure_virtual_called ();
11902 }
11903
11904 /* The default 'explains_signal' method.  */
11905
11906 static int
11907 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
11908 {
11909   return 1;
11910 }
11911
11912 /* The default "after_condition_true" method.  */
11913
11914 static void
11915 base_breakpoint_after_condition_true (struct bpstat *bs)
11916 {
11917   /* Nothing to do.   */
11918 }
11919
11920 struct breakpoint_ops base_breakpoint_ops =
11921 {
11922   base_breakpoint_allocate_location,
11923   base_breakpoint_re_set,
11924   base_breakpoint_insert_location,
11925   base_breakpoint_remove_location,
11926   base_breakpoint_breakpoint_hit,
11927   base_breakpoint_check_status,
11928   base_breakpoint_resources_needed,
11929   base_breakpoint_works_in_software_mode,
11930   base_breakpoint_print_it,
11931   NULL,
11932   base_breakpoint_print_one_detail,
11933   base_breakpoint_print_mention,
11934   base_breakpoint_print_recreate,
11935   base_breakpoint_create_sals_from_location,
11936   base_breakpoint_create_breakpoints_sal,
11937   base_breakpoint_decode_location,
11938   base_breakpoint_explains_signal,
11939   base_breakpoint_after_condition_true,
11940 };
11941
11942 /* Default breakpoint_ops methods.  */
11943
11944 static void
11945 bkpt_re_set (struct breakpoint *b)
11946 {
11947   /* FIXME: is this still reachable?  */
11948   if (breakpoint_event_location_empty_p (b))
11949     {
11950       /* Anything without a location can't be re-set.  */
11951       delete_breakpoint (b);
11952       return;
11953     }
11954
11955   breakpoint_re_set_default (b);
11956 }
11957
11958 static int
11959 bkpt_insert_location (struct bp_location *bl)
11960 {
11961   CORE_ADDR addr = bl->target_info.reqstd_address;
11962
11963   bl->target_info.kind = breakpoint_kind (bl, &addr);
11964   bl->target_info.placed_address = addr;
11965
11966   if (bl->loc_type == bp_loc_hardware_breakpoint)
11967     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
11968   else
11969     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
11970 }
11971
11972 static int
11973 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
11974 {
11975   if (bl->loc_type == bp_loc_hardware_breakpoint)
11976     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
11977   else
11978     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
11979 }
11980
11981 static int
11982 bkpt_breakpoint_hit (const struct bp_location *bl,
11983                      const address_space *aspace, CORE_ADDR bp_addr,
11984                      const target_waitstatus &ws)
11985 {
11986   if (ws.kind () != TARGET_WAITKIND_STOPPED
11987       || ws.sig () != GDB_SIGNAL_TRAP)
11988     return 0;
11989
11990   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
11991                                  aspace, bp_addr))
11992     return 0;
11993
11994   if (overlay_debugging         /* unmapped overlay section */
11995       && section_is_overlay (bl->section)
11996       && !section_is_mapped (bl->section))
11997     return 0;
11998
11999   return 1;
12000 }
12001
12002 static int
12003 dprintf_breakpoint_hit (const struct bp_location *bl,
12004                         const address_space *aspace, CORE_ADDR bp_addr,
12005                         const target_waitstatus &ws)
12006 {
12007   if (dprintf_style == dprintf_style_agent
12008       && target_can_run_breakpoint_commands ())
12009     {
12010       /* An agent-style dprintf never causes a stop.  If we see a trap
12011          for this address it must be for a breakpoint that happens to
12012          be set at the same address.  */
12013       return 0;
12014     }
12015
12016   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12017 }
12018
12019 static int
12020 bkpt_resources_needed (const struct bp_location *bl)
12021 {
12022   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12023
12024   return 1;
12025 }
12026
12027 static enum print_stop_action
12028 bkpt_print_it (bpstat *bs)
12029 {
12030   struct breakpoint *b;
12031   const struct bp_location *bl;
12032   int bp_temp;
12033   struct ui_out *uiout = current_uiout;
12034
12035   gdb_assert (bs->bp_location_at != NULL);
12036
12037   bl = bs->bp_location_at.get ();
12038   b = bs->breakpoint_at;
12039
12040   bp_temp = b->disposition == disp_del;
12041   if (bl->address != bl->requested_address)
12042     breakpoint_adjustment_warning (bl->requested_address,
12043                                    bl->address,
12044                                    b->number, 1);
12045   annotate_breakpoint (b->number);
12046   maybe_print_thread_hit_breakpoint (uiout);
12047
12048   if (uiout->is_mi_like_p ())
12049     {
12050       uiout->field_string ("reason",
12051                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12052       uiout->field_string ("disp", bpdisp_text (b->disposition));
12053     }
12054   if (bp_temp)
12055     uiout->message ("Temporary breakpoint %pF, ",
12056                     signed_field ("bkptno", b->number));
12057   else
12058     uiout->message ("Breakpoint %pF, ",
12059                     signed_field ("bkptno", b->number));
12060
12061   return PRINT_SRC_AND_LOC;
12062 }
12063
12064 static void
12065 bkpt_print_mention (struct breakpoint *b)
12066 {
12067   if (current_uiout->is_mi_like_p ())
12068     return;
12069
12070   switch (b->type)
12071     {
12072     case bp_breakpoint:
12073     case bp_gnu_ifunc_resolver:
12074       if (b->disposition == disp_del)
12075         gdb_printf (_("Temporary breakpoint"));
12076       else
12077         gdb_printf (_("Breakpoint"));
12078       gdb_printf (_(" %d"), b->number);
12079       if (b->type == bp_gnu_ifunc_resolver)
12080         gdb_printf (_(" at gnu-indirect-function resolver"));
12081       break;
12082     case bp_hardware_breakpoint:
12083       gdb_printf (_("Hardware assisted breakpoint %d"), b->number);
12084       break;
12085     case bp_dprintf:
12086       gdb_printf (_("Dprintf %d"), b->number);
12087       break;
12088     }
12089
12090   say_where (b);
12091 }
12092
12093 static void
12094 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12095 {
12096   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12097     gdb_printf (fp, "tbreak");
12098   else if (tp->type == bp_breakpoint)
12099     gdb_printf (fp, "break");
12100   else if (tp->type == bp_hardware_breakpoint
12101            && tp->disposition == disp_del)
12102     gdb_printf (fp, "thbreak");
12103   else if (tp->type == bp_hardware_breakpoint)
12104     gdb_printf (fp, "hbreak");
12105   else
12106     internal_error (__FILE__, __LINE__,
12107                     _("unhandled breakpoint type %d"), (int) tp->type);
12108
12109   gdb_printf (fp, " %s",
12110               event_location_to_string (tp->location.get ()));
12111
12112   /* Print out extra_string if this breakpoint is pending.  It might
12113      contain, for example, conditions that were set by the user.  */
12114   if (tp->loc == NULL && tp->extra_string != NULL)
12115     gdb_printf (fp, " %s", tp->extra_string.get ());
12116
12117   print_recreate_thread (tp, fp);
12118 }
12119
12120 static void
12121 bkpt_create_sals_from_location (struct event_location *location,
12122                                 struct linespec_result *canonical,
12123                                 enum bptype type_wanted)
12124 {
12125   create_sals_from_location_default (location, canonical, type_wanted);
12126 }
12127
12128 static void
12129 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12130                              struct linespec_result *canonical,
12131                              gdb::unique_xmalloc_ptr<char> cond_string,
12132                              gdb::unique_xmalloc_ptr<char> extra_string,
12133                              enum bptype type_wanted,
12134                              enum bpdisp disposition,
12135                              int thread,
12136                              int task, int ignore_count,
12137                              const struct breakpoint_ops *ops,
12138                              int from_tty, int enabled,
12139                              int internal, unsigned flags)
12140 {
12141   create_breakpoints_sal_default (gdbarch, canonical,
12142                                   std::move (cond_string),
12143                                   std::move (extra_string),
12144                                   type_wanted,
12145                                   disposition, thread, task,
12146                                   ignore_count, ops, from_tty,
12147                                   enabled, internal, flags);
12148 }
12149
12150 static std::vector<symtab_and_line>
12151 bkpt_decode_location (struct breakpoint *b,
12152                       struct event_location *location,
12153                       struct program_space *search_pspace)
12154 {
12155   return decode_location_default (b, location, search_pspace);
12156 }
12157
12158 /* Virtual table for internal breakpoints.  */
12159
12160 static void
12161 internal_bkpt_re_set (struct breakpoint *b)
12162 {
12163   switch (b->type)
12164     {
12165       /* Delete overlay event and longjmp master breakpoints; they
12166          will be reset later by breakpoint_re_set.  */
12167     case bp_overlay_event:
12168     case bp_longjmp_master:
12169     case bp_std_terminate_master:
12170     case bp_exception_master:
12171       delete_breakpoint (b);
12172       break;
12173
12174       /* This breakpoint is special, it's set up when the inferior
12175          starts and we really don't want to touch it.  */
12176     case bp_shlib_event:
12177
12178       /* Like bp_shlib_event, this breakpoint type is special.  Once
12179          it is set up, we do not want to touch it.  */
12180     case bp_thread_event:
12181       break;
12182     }
12183 }
12184
12185 static void
12186 internal_bkpt_check_status (bpstat *bs)
12187 {
12188   if (bs->breakpoint_at->type == bp_shlib_event)
12189     {
12190       /* If requested, stop when the dynamic linker notifies GDB of
12191          events.  This allows the user to get control and place
12192          breakpoints in initializer routines for dynamically loaded
12193          objects (among other things).  */
12194       bs->stop = stop_on_solib_events;
12195       bs->print = stop_on_solib_events;
12196     }
12197   else
12198     bs->stop = 0;
12199 }
12200
12201 static enum print_stop_action
12202 internal_bkpt_print_it (bpstat *bs)
12203 {
12204   struct breakpoint *b;
12205
12206   b = bs->breakpoint_at;
12207
12208   switch (b->type)
12209     {
12210     case bp_shlib_event:
12211       /* Did we stop because the user set the stop_on_solib_events
12212          variable?  (If so, we report this as a generic, "Stopped due
12213          to shlib event" message.) */
12214       print_solib_event (0);
12215       break;
12216
12217     case bp_thread_event:
12218       /* Not sure how we will get here.
12219          GDB should not stop for these breakpoints.  */
12220       gdb_printf (_("Thread Event Breakpoint: gdb should not stop!\n"));
12221       break;
12222
12223     case bp_overlay_event:
12224       /* By analogy with the thread event, GDB should not stop for these.  */
12225       gdb_printf (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12226       break;
12227
12228     case bp_longjmp_master:
12229       /* These should never be enabled.  */
12230       gdb_printf (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12231       break;
12232
12233     case bp_std_terminate_master:
12234       /* These should never be enabled.  */
12235       gdb_printf (_("std::terminate Master Breakpoint: "
12236                     "gdb should not stop!\n"));
12237       break;
12238
12239     case bp_exception_master:
12240       /* These should never be enabled.  */
12241       gdb_printf (_("Exception Master Breakpoint: "
12242                     "gdb should not stop!\n"));
12243       break;
12244     }
12245
12246   return PRINT_NOTHING;
12247 }
12248
12249 static void
12250 internal_bkpt_print_mention (struct breakpoint *b)
12251 {
12252   /* Nothing to mention.  These breakpoints are internal.  */
12253 }
12254
12255 /* Virtual table for momentary breakpoints  */
12256
12257 static void
12258 momentary_bkpt_re_set (struct breakpoint *b)
12259 {
12260   /* Keep temporary breakpoints, which can be encountered when we step
12261      over a dlopen call and solib_add is resetting the breakpoints.
12262      Otherwise these should have been blown away via the cleanup chain
12263      or by breakpoint_init_inferior when we rerun the executable.  */
12264 }
12265
12266 static void
12267 momentary_bkpt_check_status (bpstat *bs)
12268 {
12269   /* Nothing.  The point of these breakpoints is causing a stop.  */
12270 }
12271
12272 static enum print_stop_action
12273 momentary_bkpt_print_it (bpstat *bs)
12274 {
12275   return PRINT_UNKNOWN;
12276 }
12277
12278 static void
12279 momentary_bkpt_print_mention (struct breakpoint *b)
12280 {
12281   /* Nothing to mention.  These breakpoints are internal.  */
12282 }
12283
12284 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12285
12286    It gets cleared already on the removal of the first one of such placed
12287    breakpoints.  This is OK as they get all removed altogether.  */
12288
12289 longjmp_breakpoint::~longjmp_breakpoint ()
12290 {
12291   thread_info *tp = find_thread_global_id (this->thread);
12292
12293   if (tp != NULL)
12294     tp->initiating_frame = null_frame_id;
12295 }
12296
12297 /* Specific methods for probe breakpoints.  */
12298
12299 static int
12300 bkpt_probe_insert_location (struct bp_location *bl)
12301 {
12302   int v = bkpt_insert_location (bl);
12303
12304   if (v == 0)
12305     {
12306       /* The insertion was successful, now let's set the probe's semaphore
12307          if needed.  */
12308       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12309     }
12310
12311   return v;
12312 }
12313
12314 static int
12315 bkpt_probe_remove_location (struct bp_location *bl,
12316                             enum remove_bp_reason reason)
12317 {
12318   /* Let's clear the semaphore before removing the location.  */
12319   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12320
12321   return bkpt_remove_location (bl, reason);
12322 }
12323
12324 static void
12325 bkpt_probe_create_sals_from_location (struct event_location *location,
12326                                       struct linespec_result *canonical,
12327                                       enum bptype type_wanted)
12328 {
12329   struct linespec_sals lsal;
12330
12331   lsal.sals = parse_probes (location, NULL, canonical);
12332   lsal.canonical
12333     = xstrdup (event_location_to_string (canonical->location.get ()));
12334   canonical->lsals.push_back (std::move (lsal));
12335 }
12336
12337 static std::vector<symtab_and_line>
12338 bkpt_probe_decode_location (struct breakpoint *b,
12339                             struct event_location *location,
12340                             struct program_space *search_pspace)
12341 {
12342   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12343   if (sals.empty ())
12344     error (_("probe not found"));
12345   return sals;
12346 }
12347
12348 /* The breakpoint_ops structure to be used in tracepoints.  */
12349
12350 static void
12351 tracepoint_re_set (struct breakpoint *b)
12352 {
12353   breakpoint_re_set_default (b);
12354 }
12355
12356 static int
12357 tracepoint_breakpoint_hit (const struct bp_location *bl,
12358                            const address_space *aspace, CORE_ADDR bp_addr,
12359                            const target_waitstatus &ws)
12360 {
12361   /* By definition, the inferior does not report stops at
12362      tracepoints.  */
12363   return 0;
12364 }
12365
12366 static void
12367 tracepoint_print_one_detail (const struct breakpoint *self,
12368                              struct ui_out *uiout)
12369 {
12370   struct tracepoint *tp = (struct tracepoint *) self;
12371   if (!tp->static_trace_marker_id.empty ())
12372     {
12373       gdb_assert (self->type == bp_static_tracepoint);
12374
12375       uiout->message ("\tmarker id is %pF\n",
12376                       string_field ("static-tracepoint-marker-string-id",
12377                                     tp->static_trace_marker_id.c_str ()));
12378     }
12379 }
12380
12381 static void
12382 tracepoint_print_mention (struct breakpoint *b)
12383 {
12384   if (current_uiout->is_mi_like_p ())
12385     return;
12386
12387   switch (b->type)
12388     {
12389     case bp_tracepoint:
12390       gdb_printf (_("Tracepoint"));
12391       gdb_printf (_(" %d"), b->number);
12392       break;
12393     case bp_fast_tracepoint:
12394       gdb_printf (_("Fast tracepoint"));
12395       gdb_printf (_(" %d"), b->number);
12396       break;
12397     case bp_static_tracepoint:
12398       gdb_printf (_("Static tracepoint"));
12399       gdb_printf (_(" %d"), b->number);
12400       break;
12401     default:
12402       internal_error (__FILE__, __LINE__,
12403                       _("unhandled tracepoint type %d"), (int) b->type);
12404     }
12405
12406   say_where (b);
12407 }
12408
12409 static void
12410 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12411 {
12412   struct tracepoint *tp = (struct tracepoint *) self;
12413
12414   if (self->type == bp_fast_tracepoint)
12415     gdb_printf (fp, "ftrace");
12416   else if (self->type == bp_static_tracepoint)
12417     gdb_printf (fp, "strace");
12418   else if (self->type == bp_tracepoint)
12419     gdb_printf (fp, "trace");
12420   else
12421     internal_error (__FILE__, __LINE__,
12422                     _("unhandled tracepoint type %d"), (int) self->type);
12423
12424   gdb_printf (fp, " %s",
12425               event_location_to_string (self->location.get ()));
12426   print_recreate_thread (self, fp);
12427
12428   if (tp->pass_count)
12429     gdb_printf (fp, "  passcount %d\n", tp->pass_count);
12430 }
12431
12432 static void
12433 tracepoint_create_sals_from_location (struct event_location *location,
12434                                       struct linespec_result *canonical,
12435                                       enum bptype type_wanted)
12436 {
12437   create_sals_from_location_default (location, canonical, type_wanted);
12438 }
12439
12440 static void
12441 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12442                                    struct linespec_result *canonical,
12443                                    gdb::unique_xmalloc_ptr<char> cond_string,
12444                                    gdb::unique_xmalloc_ptr<char> extra_string,
12445                                    enum bptype type_wanted,
12446                                    enum bpdisp disposition,
12447                                    int thread,
12448                                    int task, int ignore_count,
12449                                    const struct breakpoint_ops *ops,
12450                                    int from_tty, int enabled,
12451                                    int internal, unsigned flags)
12452 {
12453   create_breakpoints_sal_default (gdbarch, canonical,
12454                                   std::move (cond_string),
12455                                   std::move (extra_string),
12456                                   type_wanted,
12457                                   disposition, thread, task,
12458                                   ignore_count, ops, from_tty,
12459                                   enabled, internal, flags);
12460 }
12461
12462 static std::vector<symtab_and_line>
12463 tracepoint_decode_location (struct breakpoint *b,
12464                             struct event_location *location,
12465                             struct program_space *search_pspace)
12466 {
12467   return decode_location_default (b, location, search_pspace);
12468 }
12469
12470 struct breakpoint_ops tracepoint_breakpoint_ops;
12471
12472 /* Virtual table for tracepoints on static probes.  */
12473
12474 static void
12475 tracepoint_probe_create_sals_from_location
12476   (struct event_location *location,
12477    struct linespec_result *canonical,
12478    enum bptype type_wanted)
12479 {
12480   /* We use the same method for breakpoint on probes.  */
12481   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12482 }
12483
12484 static std::vector<symtab_and_line>
12485 tracepoint_probe_decode_location (struct breakpoint *b,
12486                                   struct event_location *location,
12487                                   struct program_space *search_pspace)
12488 {
12489   /* We use the same method for breakpoint on probes.  */
12490   return bkpt_probe_decode_location (b, location, search_pspace);
12491 }
12492
12493 /* Dprintf breakpoint_ops methods.  */
12494
12495 static void
12496 dprintf_re_set (struct breakpoint *b)
12497 {
12498   breakpoint_re_set_default (b);
12499
12500   /* extra_string should never be non-NULL for dprintf.  */
12501   gdb_assert (b->extra_string != NULL);
12502
12503   /* 1 - connect to target 1, that can run breakpoint commands.
12504      2 - create a dprintf, which resolves fine.
12505      3 - disconnect from target 1
12506      4 - connect to target 2, that can NOT run breakpoint commands.
12507
12508      After steps #3/#4, you'll want the dprintf command list to
12509      be updated, because target 1 and 2 may well return different
12510      answers for target_can_run_breakpoint_commands().
12511      Given absence of finer grained resetting, we get to do
12512      it all the time.  */
12513   if (b->extra_string != NULL)
12514     update_dprintf_command_list (b);
12515 }
12516
12517 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
12518
12519 static void
12520 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12521 {
12522   gdb_printf (fp, "dprintf %s,%s",
12523               event_location_to_string (tp->location.get ()),
12524               tp->extra_string.get ());
12525   print_recreate_thread (tp, fp);
12526 }
12527
12528 /* Implement the "after_condition_true" breakpoint_ops method for
12529    dprintf.
12530
12531    dprintf's are implemented with regular commands in their command
12532    list, but we run the commands here instead of before presenting the
12533    stop to the user, as dprintf's don't actually cause a stop.  This
12534    also makes it so that the commands of multiple dprintfs at the same
12535    address are all handled.  */
12536
12537 static void
12538 dprintf_after_condition_true (struct bpstat *bs)
12539 {
12540   /* dprintf's never cause a stop.  This wasn't set in the
12541      check_status hook instead because that would make the dprintf's
12542      condition not be evaluated.  */
12543   bs->stop = 0;
12544
12545   /* Run the command list here.  Take ownership of it instead of
12546      copying.  We never want these commands to run later in
12547      bpstat_do_actions, if a breakpoint that causes a stop happens to
12548      be set at same address as this dprintf, or even if running the
12549      commands here throws.  */
12550   counted_command_line cmds = std::move (bs->commands);
12551   gdb_assert (cmds != nullptr);
12552   execute_control_commands (cmds.get (), 0);
12553 }
12554
12555 /* The breakpoint_ops structure to be used on static tracepoints with
12556    markers (`-m').  */
12557
12558 static void
12559 strace_marker_create_sals_from_location (struct event_location *location,
12560                                          struct linespec_result *canonical,
12561                                          enum bptype type_wanted)
12562 {
12563   struct linespec_sals lsal;
12564   const char *arg_start, *arg;
12565
12566   arg = arg_start = get_linespec_location (location)->spec_string;
12567   lsal.sals = decode_static_tracepoint_spec (&arg);
12568
12569   std::string str (arg_start, arg - arg_start);
12570   const char *ptr = str.c_str ();
12571   canonical->location
12572     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
12573
12574   lsal.canonical
12575     = xstrdup (event_location_to_string (canonical->location.get ()));
12576   canonical->lsals.push_back (std::move (lsal));
12577 }
12578
12579 static void
12580 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12581                                       struct linespec_result *canonical,
12582                                       gdb::unique_xmalloc_ptr<char> cond_string,
12583                                       gdb::unique_xmalloc_ptr<char> extra_string,
12584                                       enum bptype type_wanted,
12585                                       enum bpdisp disposition,
12586                                       int thread,
12587                                       int task, int ignore_count,
12588                                       const struct breakpoint_ops *ops,
12589                                       int from_tty, int enabled,
12590                                       int internal, unsigned flags)
12591 {
12592   const linespec_sals &lsal = canonical->lsals[0];
12593
12594   /* If the user is creating a static tracepoint by marker id
12595      (strace -m MARKER_ID), then store the sals index, so that
12596      breakpoint_re_set can try to match up which of the newly
12597      found markers corresponds to this one, and, don't try to
12598      expand multiple locations for each sal, given than SALS
12599      already should contain all sals for MARKER_ID.  */
12600
12601   for (size_t i = 0; i < lsal.sals.size (); i++)
12602     {
12603       event_location_up location
12604         = copy_event_location (canonical->location.get ());
12605
12606       std::unique_ptr<tracepoint> tp (new tracepoint ());
12607       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
12608                            std::move (location), NULL,
12609                            std::move (cond_string),
12610                            std::move (extra_string),
12611                            type_wanted, disposition,
12612                            thread, task, ignore_count, ops,
12613                            from_tty, enabled, internal, flags,
12614                            canonical->special_display);
12615       /* Given that its possible to have multiple markers with
12616          the same string id, if the user is creating a static
12617          tracepoint by marker id ("strace -m MARKER_ID"), then
12618          store the sals index, so that breakpoint_re_set can
12619          try to match up which of the newly found markers
12620          corresponds to this one  */
12621       tp->static_trace_marker_id_idx = i;
12622
12623       install_breakpoint (internal, std::move (tp), 0);
12624     }
12625 }
12626
12627 static std::vector<symtab_and_line>
12628 strace_marker_decode_location (struct breakpoint *b,
12629                                struct event_location *location,
12630                                struct program_space *search_pspace)
12631 {
12632   struct tracepoint *tp = (struct tracepoint *) b;
12633   const char *s = get_linespec_location (location)->spec_string;
12634
12635   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
12636   if (sals.size () > tp->static_trace_marker_id_idx)
12637     {
12638       sals[0] = sals[tp->static_trace_marker_id_idx];
12639       sals.resize (1);
12640       return sals;
12641     }
12642   else
12643     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
12644 }
12645
12646 static struct breakpoint_ops strace_marker_breakpoint_ops;
12647
12648 static int
12649 strace_marker_p (struct breakpoint *b)
12650 {
12651   return b->ops == &strace_marker_breakpoint_ops;
12652 }
12653
12654 /* Delete a breakpoint and clean up all traces of it in the data
12655    structures.  */
12656
12657 void
12658 delete_breakpoint (struct breakpoint *bpt)
12659 {
12660   gdb_assert (bpt != NULL);
12661
12662   /* Has this bp already been deleted?  This can happen because
12663      multiple lists can hold pointers to bp's.  bpstat lists are
12664      especial culprits.
12665
12666      One example of this happening is a watchpoint's scope bp.  When
12667      the scope bp triggers, we notice that the watchpoint is out of
12668      scope, and delete it.  We also delete its scope bp.  But the
12669      scope bp is marked "auto-deleting", and is already on a bpstat.
12670      That bpstat is then checked for auto-deleting bp's, which are
12671      deleted.
12672
12673      A real solution to this problem might involve reference counts in
12674      bp's, and/or giving them pointers back to their referencing
12675      bpstat's, and teaching delete_breakpoint to only free a bp's
12676      storage when no more references were extent.  A cheaper bandaid
12677      was chosen.  */
12678   if (bpt->type == bp_none)
12679     return;
12680
12681   /* At least avoid this stale reference until the reference counting
12682      of breakpoints gets resolved.  */
12683   if (bpt->related_breakpoint != bpt)
12684     {
12685       struct breakpoint *related;
12686       struct watchpoint *w;
12687
12688       if (bpt->type == bp_watchpoint_scope)
12689         w = (struct watchpoint *) bpt->related_breakpoint;
12690       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12691         w = (struct watchpoint *) bpt;
12692       else
12693         w = NULL;
12694       if (w != NULL)
12695         watchpoint_del_at_next_stop (w);
12696
12697       /* Unlink bpt from the bpt->related_breakpoint ring.  */
12698       for (related = bpt; related->related_breakpoint != bpt;
12699            related = related->related_breakpoint);
12700       related->related_breakpoint = bpt->related_breakpoint;
12701       bpt->related_breakpoint = bpt;
12702     }
12703
12704   /* watch_command_1 creates a watchpoint but only sets its number if
12705      update_watchpoint succeeds in creating its bp_locations.  If there's
12706      a problem in that process, we'll be asked to delete the half-created
12707      watchpoint.  In that case, don't announce the deletion.  */
12708   if (bpt->number)
12709     gdb::observers::breakpoint_deleted.notify (bpt);
12710
12711   if (breakpoint_chain == bpt)
12712     breakpoint_chain = bpt->next;
12713
12714   for (breakpoint *b : all_breakpoints ())
12715     if (b->next == bpt)
12716       {
12717         b->next = bpt->next;
12718         break;
12719       }
12720
12721   /* Be sure no bpstat's are pointing at the breakpoint after it's
12722      been freed.  */
12723   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
12724      in all threads for now.  Note that we cannot just remove bpstats
12725      pointing at bpt from the stop_bpstat list entirely, as breakpoint
12726      commands are associated with the bpstat; if we remove it here,
12727      then the later call to bpstat_do_actions (&stop_bpstat); in
12728      event-top.c won't do anything, and temporary breakpoints with
12729      commands won't work.  */
12730
12731   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12732
12733   /* Now that breakpoint is removed from breakpoint list, update the
12734      global location list.  This will remove locations that used to
12735      belong to this breakpoint.  Do this before freeing the breakpoint
12736      itself, since remove_breakpoint looks at location's owner.  It
12737      might be better design to have location completely
12738      self-contained, but it's not the case now.  */
12739   update_global_location_list (UGLL_DONT_INSERT);
12740
12741   /* On the chance that someone will soon try again to delete this
12742      same bp, we mark it as deleted before freeing its storage.  */
12743   bpt->type = bp_none;
12744   delete bpt;
12745 }
12746
12747 /* Iterator function to call a user-provided callback function once
12748    for each of B and its related breakpoints.  */
12749
12750 static void
12751 iterate_over_related_breakpoints (struct breakpoint *b,
12752                                   gdb::function_view<void (breakpoint *)> function)
12753 {
12754   struct breakpoint *related;
12755
12756   related = b;
12757   do
12758     {
12759       struct breakpoint *next;
12760
12761       /* FUNCTION may delete RELATED.  */
12762       next = related->related_breakpoint;
12763
12764       if (next == related)
12765         {
12766           /* RELATED is the last ring entry.  */
12767           function (related);
12768
12769           /* FUNCTION may have deleted it, so we'd never reach back to
12770              B.  There's nothing left to do anyway, so just break
12771              out.  */
12772           break;
12773         }
12774       else
12775         function (related);
12776
12777       related = next;
12778     }
12779   while (related != b);
12780 }
12781
12782 static void
12783 delete_command (const char *arg, int from_tty)
12784 {
12785   dont_repeat ();
12786
12787   if (arg == 0)
12788     {
12789       int breaks_to_delete = 0;
12790
12791       /* Delete all breakpoints if no argument.  Do not delete
12792          internal breakpoints, these have to be deleted with an
12793          explicit breakpoint number argument.  */
12794       for (breakpoint *b : all_breakpoints ())
12795         if (user_breakpoint_p (b))
12796           {
12797             breaks_to_delete = 1;
12798             break;
12799           }
12800
12801       /* Ask user only if there are some breakpoints to delete.  */
12802       if (!from_tty
12803           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12804         for (breakpoint *b : all_breakpoints_safe ())
12805           if (user_breakpoint_p (b))
12806             delete_breakpoint (b);
12807     }
12808   else
12809     map_breakpoint_numbers
12810       (arg, [&] (breakpoint *br)
12811        {
12812          iterate_over_related_breakpoints (br, delete_breakpoint);
12813        });
12814 }
12815
12816 /* Return true if all locations of B bound to PSPACE are pending.  If
12817    PSPACE is NULL, all locations of all program spaces are
12818    considered.  */
12819
12820 static int
12821 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
12822 {
12823   for (bp_location *loc : b->locations ())
12824     if ((pspace == NULL
12825          || loc->pspace == pspace)
12826         && !loc->shlib_disabled
12827         && !loc->pspace->executing_startup)
12828       return 0;
12829   return 1;
12830 }
12831
12832 /* Subroutine of update_breakpoint_locations to simplify it.
12833    Return non-zero if multiple fns in list LOC have the same name.
12834    Null names are ignored.  */
12835
12836 static int
12837 ambiguous_names_p (struct bp_location *loc)
12838 {
12839   struct bp_location *l;
12840   htab_up htab (htab_create_alloc (13, htab_hash_string, htab_eq_string, NULL,
12841                                    xcalloc, xfree));
12842
12843   for (l = loc; l != NULL; l = l->next)
12844     {
12845       const char **slot;
12846       const char *name = l->function_name.get ();
12847
12848       /* Allow for some names to be NULL, ignore them.  */
12849       if (name == NULL)
12850         continue;
12851
12852       slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
12853                                              INSERT);
12854       /* NOTE: We can assume slot != NULL here because xcalloc never
12855          returns NULL.  */
12856       if (*slot != NULL)
12857         return 1;
12858       *slot = name;
12859     }
12860
12861   return 0;
12862 }
12863
12864 /* When symbols change, it probably means the sources changed as well,
12865    and it might mean the static tracepoint markers are no longer at
12866    the same address or line numbers they used to be at last we
12867    checked.  Losing your static tracepoints whenever you rebuild is
12868    undesirable.  This function tries to resync/rematch gdb static
12869    tracepoints with the markers on the target, for static tracepoints
12870    that have not been set by marker id.  Static tracepoint that have
12871    been set by marker id are reset by marker id in breakpoint_re_set.
12872    The heuristic is:
12873
12874    1) For a tracepoint set at a specific address, look for a marker at
12875    the old PC.  If one is found there, assume to be the same marker.
12876    If the name / string id of the marker found is different from the
12877    previous known name, assume that means the user renamed the marker
12878    in the sources, and output a warning.
12879
12880    2) For a tracepoint set at a given line number, look for a marker
12881    at the new address of the old line number.  If one is found there,
12882    assume to be the same marker.  If the name / string id of the
12883    marker found is different from the previous known name, assume that
12884    means the user renamed the marker in the sources, and output a
12885    warning.
12886
12887    3) If a marker is no longer found at the same address or line, it
12888    may mean the marker no longer exists.  But it may also just mean
12889    the code changed a bit.  Maybe the user added a few lines of code
12890    that made the marker move up or down (in line number terms).  Ask
12891    the target for info about the marker with the string id as we knew
12892    it.  If found, update line number and address in the matching
12893    static tracepoint.  This will get confused if there's more than one
12894    marker with the same ID (possible in UST, although unadvised
12895    precisely because it confuses tools).  */
12896
12897 static struct symtab_and_line
12898 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12899 {
12900   struct tracepoint *tp = (struct tracepoint *) b;
12901   struct static_tracepoint_marker marker;
12902   CORE_ADDR pc;
12903
12904   pc = sal.pc;
12905   if (sal.line)
12906     find_line_pc (sal.symtab, sal.line, &pc);
12907
12908   if (target_static_tracepoint_marker_at (pc, &marker))
12909     {
12910       if (tp->static_trace_marker_id != marker.str_id)
12911         warning (_("static tracepoint %d changed probed marker from %s to %s"),
12912                  b->number, tp->static_trace_marker_id.c_str (),
12913                  marker.str_id.c_str ());
12914
12915       tp->static_trace_marker_id = std::move (marker.str_id);
12916
12917       return sal;
12918     }
12919
12920   /* Old marker wasn't found on target at lineno.  Try looking it up
12921      by string ID.  */
12922   if (!sal.explicit_pc
12923       && sal.line != 0
12924       && sal.symtab != NULL
12925       && !tp->static_trace_marker_id.empty ())
12926     {
12927       std::vector<static_tracepoint_marker> markers
12928         = target_static_tracepoint_markers_by_strid
12929             (tp->static_trace_marker_id.c_str ());
12930
12931       if (!markers.empty ())
12932         {
12933           struct symbol *sym;
12934           struct static_tracepoint_marker *tpmarker;
12935           struct ui_out *uiout = current_uiout;
12936           struct explicit_location explicit_loc;
12937
12938           tpmarker = &markers[0];
12939
12940           tp->static_trace_marker_id = std::move (tpmarker->str_id);
12941
12942           warning (_("marker for static tracepoint %d (%s) not "
12943                      "found at previous line number"),
12944                    b->number, tp->static_trace_marker_id.c_str ());
12945
12946           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
12947           sym = find_pc_sect_function (tpmarker->address, NULL);
12948           uiout->text ("Now in ");
12949           if (sym)
12950             {
12951               uiout->field_string ("func", sym->print_name (),
12952                                    function_name_style.style ());
12953               uiout->text (" at ");
12954             }
12955           uiout->field_string ("file",
12956                                symtab_to_filename_for_display (sal2.symtab),
12957                                file_name_style.style ());
12958           uiout->text (":");
12959
12960           if (uiout->is_mi_like_p ())
12961             {
12962               const char *fullname = symtab_to_fullname (sal2.symtab);
12963
12964               uiout->field_string ("fullname", fullname);
12965             }
12966
12967           uiout->field_signed ("line", sal2.line);
12968           uiout->text ("\n");
12969
12970           b->loc->line_number = sal2.line;
12971           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
12972
12973           b->location.reset (NULL);
12974           initialize_explicit_location (&explicit_loc);
12975           explicit_loc.source_filename
12976             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
12977           explicit_loc.line_offset.offset = b->loc->line_number;
12978           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
12979           b->location = new_explicit_location (&explicit_loc);
12980
12981           /* Might be nice to check if function changed, and warn if
12982              so.  */
12983         }
12984     }
12985   return sal;
12986 }
12987
12988 /* Returns 1 iff locations A and B are sufficiently same that
12989    we don't need to report breakpoint as changed.  */
12990
12991 static int
12992 locations_are_equal (struct bp_location *a, struct bp_location *b)
12993 {
12994   while (a && b)
12995     {
12996       if (a->address != b->address)
12997         return 0;
12998
12999       if (a->shlib_disabled != b->shlib_disabled)
13000         return 0;
13001
13002       if (a->enabled != b->enabled)
13003         return 0;
13004
13005       if (a->disabled_by_cond != b->disabled_by_cond)
13006         return 0;
13007
13008       a = a->next;
13009       b = b->next;
13010     }
13011
13012   if ((a == NULL) != (b == NULL))
13013     return 0;
13014
13015   return 1;
13016 }
13017
13018 /* Split all locations of B that are bound to PSPACE out of B's
13019    location list to a separate list and return that list's head.  If
13020    PSPACE is NULL, hoist out all locations of B.  */
13021
13022 static struct bp_location *
13023 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13024 {
13025   struct bp_location head;
13026   struct bp_location *i = b->loc;
13027   struct bp_location **i_link = &b->loc;
13028   struct bp_location *hoisted = &head;
13029
13030   if (pspace == NULL)
13031     {
13032       i = b->loc;
13033       b->loc = NULL;
13034       return i;
13035     }
13036
13037   head.next = NULL;
13038
13039   while (i != NULL)
13040     {
13041       if (i->pspace == pspace)
13042         {
13043           *i_link = i->next;
13044           i->next = NULL;
13045           hoisted->next = i;
13046           hoisted = i;
13047         }
13048       else
13049         i_link = &i->next;
13050       i = *i_link;
13051     }
13052
13053   return head.next;
13054 }
13055
13056 /* Create new breakpoint locations for B (a hardware or software
13057    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13058    zero, then B is a ranged breakpoint.  Only recreates locations for
13059    FILTER_PSPACE.  Locations of other program spaces are left
13060    untouched.  */
13061
13062 void
13063 update_breakpoint_locations (struct breakpoint *b,
13064                              struct program_space *filter_pspace,
13065                              gdb::array_view<const symtab_and_line> sals,
13066                              gdb::array_view<const symtab_and_line> sals_end)
13067 {
13068   struct bp_location *existing_locations;
13069
13070   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13071     {
13072       /* Ranged breakpoints have only one start location and one end
13073          location.  */
13074       b->enable_state = bp_disabled;
13075       gdb_printf (gdb_stderr,
13076                   _("Could not reset ranged breakpoint %d: "
13077                     "multiple locations found\n"),
13078                   b->number);
13079       return;
13080     }
13081
13082   /* If there's no new locations, and all existing locations are
13083      pending, don't do anything.  This optimizes the common case where
13084      all locations are in the same shared library, that was unloaded.
13085      We'd like to retain the location, so that when the library is
13086      loaded again, we don't loose the enabled/disabled status of the
13087      individual locations.  */
13088   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13089     return;
13090
13091   existing_locations = hoist_existing_locations (b, filter_pspace);
13092
13093   for (const auto &sal : sals)
13094     {
13095       struct bp_location *new_loc;
13096
13097       switch_to_program_space_and_thread (sal.pspace);
13098
13099       new_loc = add_location_to_breakpoint (b, &sal);
13100
13101       /* Reparse conditions, they might contain references to the
13102          old symtab.  */
13103       if (b->cond_string != NULL)
13104         {
13105           const char *s;
13106
13107           s = b->cond_string.get ();
13108           try
13109             {
13110               new_loc->cond = parse_exp_1 (&s, sal.pc,
13111                                            block_for_pc (sal.pc),
13112                                            0);
13113             }
13114           catch (const gdb_exception_error &e)
13115             {
13116               new_loc->disabled_by_cond = true;
13117             }
13118         }
13119
13120       if (!sals_end.empty ())
13121         {
13122           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13123
13124           new_loc->length = end - sals[0].pc + 1;
13125         }
13126     }
13127
13128   /* If possible, carry over 'disable' status from existing
13129      breakpoints.  */
13130   {
13131     struct bp_location *e = existing_locations;
13132     /* If there are multiple breakpoints with the same function name,
13133        e.g. for inline functions, comparing function names won't work.
13134        Instead compare pc addresses; this is just a heuristic as things
13135        may have moved, but in practice it gives the correct answer
13136        often enough until a better solution is found.  */
13137     int have_ambiguous_names = ambiguous_names_p (b->loc);
13138
13139     for (; e; e = e->next)
13140       {
13141         if ((!e->enabled || e->disabled_by_cond) && e->function_name)
13142           {
13143             if (have_ambiguous_names)
13144               {
13145                 for (bp_location *l : b->locations ())
13146                   {
13147                     /* Ignore software vs hardware location type at
13148                        this point, because with "set breakpoint
13149                        auto-hw", after a re-set, locations that were
13150                        hardware can end up as software, or vice versa.
13151                        As mentioned above, this is an heuristic and in
13152                        practice should give the correct answer often
13153                        enough.  */
13154                     if (breakpoint_locations_match (e, l, true))
13155                       {
13156                         l->enabled = e->enabled;
13157                         l->disabled_by_cond = e->disabled_by_cond;
13158                         break;
13159                       }
13160                   }
13161               }
13162             else
13163               {
13164                 for (bp_location *l : b->locations ())
13165                   if (l->function_name
13166                       && strcmp (e->function_name.get (),
13167                                  l->function_name.get ()) == 0)
13168                     {
13169                       l->enabled = e->enabled;
13170                       l->disabled_by_cond = e->disabled_by_cond;
13171                       break;
13172                     }
13173               }
13174           }
13175       }
13176   }
13177
13178   if (!locations_are_equal (existing_locations, b->loc))
13179     gdb::observers::breakpoint_modified.notify (b);
13180 }
13181
13182 /* Find the SaL locations corresponding to the given LOCATION.
13183    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13184
13185 static std::vector<symtab_and_line>
13186 location_to_sals (struct breakpoint *b, struct event_location *location,
13187                   struct program_space *search_pspace, int *found)
13188 {
13189   struct gdb_exception exception;
13190
13191   gdb_assert (b->ops != NULL);
13192
13193   std::vector<symtab_and_line> sals;
13194
13195   try
13196     {
13197       sals = b->ops->decode_location (b, location, search_pspace);
13198     }
13199   catch (gdb_exception_error &e)
13200     {
13201       int not_found_and_ok = 0;
13202
13203       /* For pending breakpoints, it's expected that parsing will
13204          fail until the right shared library is loaded.  User has
13205          already told to create pending breakpoints and don't need
13206          extra messages.  If breakpoint is in bp_shlib_disabled
13207          state, then user already saw the message about that
13208          breakpoint being disabled, and don't want to see more
13209          errors.  */
13210       if (e.error == NOT_FOUND_ERROR
13211           && (b->condition_not_parsed
13212               || (b->loc != NULL
13213                   && search_pspace != NULL
13214                   && b->loc->pspace != search_pspace)
13215               || (b->loc && b->loc->shlib_disabled)
13216               || (b->loc && b->loc->pspace->executing_startup)
13217               || b->enable_state == bp_disabled))
13218         not_found_and_ok = 1;
13219
13220       if (!not_found_and_ok)
13221         {
13222           /* We surely don't want to warn about the same breakpoint
13223              10 times.  One solution, implemented here, is disable
13224              the breakpoint on error.  Another solution would be to
13225              have separate 'warning emitted' flag.  Since this
13226              happens only when a binary has changed, I don't know
13227              which approach is better.  */
13228           b->enable_state = bp_disabled;
13229           throw;
13230         }
13231
13232       exception = std::move (e);
13233     }
13234
13235   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13236     {
13237       for (auto &sal : sals)
13238         resolve_sal_pc (&sal);
13239       if (b->condition_not_parsed && b->extra_string != NULL)
13240         {
13241           gdb::unique_xmalloc_ptr<char> cond_string, extra_string;
13242           int thread, task;
13243
13244           find_condition_and_thread_for_sals (sals, b->extra_string.get (),
13245                                               &cond_string, &thread,
13246                                               &task, &extra_string);
13247           gdb_assert (b->cond_string == NULL);
13248           if (cond_string)
13249             b->cond_string = std::move (cond_string);
13250           b->thread = thread;
13251           b->task = task;
13252           if (extra_string)
13253             b->extra_string = std::move (extra_string);
13254           b->condition_not_parsed = 0;
13255         }
13256
13257       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13258         sals[0] = update_static_tracepoint (b, sals[0]);
13259
13260       *found = 1;
13261     }
13262   else
13263     *found = 0;
13264
13265   return sals;
13266 }
13267
13268 /* The default re_set method, for typical hardware or software
13269    breakpoints.  Reevaluate the breakpoint and recreate its
13270    locations.  */
13271
13272 static void
13273 breakpoint_re_set_default (struct breakpoint *b)
13274 {
13275   struct program_space *filter_pspace = current_program_space;
13276   std::vector<symtab_and_line> expanded, expanded_end;
13277
13278   int found;
13279   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13280                                                         filter_pspace, &found);
13281   if (found)
13282     expanded = std::move (sals);
13283
13284   if (b->location_range_end != NULL)
13285     {
13286       std::vector<symtab_and_line> sals_end
13287         = location_to_sals (b, b->location_range_end.get (),
13288                             filter_pspace, &found);
13289       if (found)
13290         expanded_end = std::move (sals_end);
13291     }
13292
13293   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13294 }
13295
13296 /* Default method for creating SALs from an address string.  It basically
13297    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13298
13299 static void
13300 create_sals_from_location_default (struct event_location *location,
13301                                    struct linespec_result *canonical,
13302                                    enum bptype type_wanted)
13303 {
13304   parse_breakpoint_sals (location, canonical);
13305 }
13306
13307 /* Call create_breakpoints_sal for the given arguments.  This is the default
13308    function for the `create_breakpoints_sal' method of
13309    breakpoint_ops.  */
13310
13311 static void
13312 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13313                                 struct linespec_result *canonical,
13314                                 gdb::unique_xmalloc_ptr<char> cond_string,
13315                                 gdb::unique_xmalloc_ptr<char> extra_string,
13316                                 enum bptype type_wanted,
13317                                 enum bpdisp disposition,
13318                                 int thread,
13319                                 int task, int ignore_count,
13320                                 const struct breakpoint_ops *ops,
13321                                 int from_tty, int enabled,
13322                                 int internal, unsigned flags)
13323 {
13324   create_breakpoints_sal (gdbarch, canonical,
13325                           std::move (cond_string),
13326                           std::move (extra_string),
13327                           type_wanted, disposition,
13328                           thread, task, ignore_count, ops, from_tty,
13329                           enabled, internal, flags);
13330 }
13331
13332 /* Decode the line represented by S by calling decode_line_full.  This is the
13333    default function for the `decode_location' method of breakpoint_ops.  */
13334
13335 static std::vector<symtab_and_line>
13336 decode_location_default (struct breakpoint *b,
13337                          struct event_location *location,
13338                          struct program_space *search_pspace)
13339 {
13340   struct linespec_result canonical;
13341
13342   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13343                     NULL, 0, &canonical, multiple_symbols_all,
13344                     b->filter.get ());
13345
13346   /* We should get 0 or 1 resulting SALs.  */
13347   gdb_assert (canonical.lsals.size () < 2);
13348
13349   if (!canonical.lsals.empty ())
13350     {
13351       const linespec_sals &lsal = canonical.lsals[0];
13352       return std::move (lsal.sals);
13353     }
13354   return {};
13355 }
13356
13357 /* Reset a breakpoint.  */
13358
13359 static void
13360 breakpoint_re_set_one (breakpoint *b)
13361 {
13362   input_radix = b->input_radix;
13363   set_language (b->language);
13364
13365   b->ops->re_set (b);
13366 }
13367
13368 /* Re-set breakpoint locations for the current program space.
13369    Locations bound to other program spaces are left untouched.  */
13370
13371 void
13372 breakpoint_re_set (void)
13373 {
13374   {
13375     scoped_restore_current_language save_language;
13376     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13377     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13378
13379     /* breakpoint_re_set_one sets the current_language to the language
13380        of the breakpoint it is resetting (see prepare_re_set_context)
13381        before re-evaluating the breakpoint's location.  This change can
13382        unfortunately get undone by accident if the language_mode is set
13383        to auto, and we either switch frames, or more likely in this context,
13384        we select the current frame.
13385
13386        We prevent this by temporarily turning the language_mode to
13387        language_mode_manual.  We restore it once all breakpoints
13388        have been reset.  */
13389     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13390     language_mode = language_mode_manual;
13391
13392     /* Note: we must not try to insert locations until after all
13393        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13394        breakpoint 1, we'd insert the locations of breakpoint 2, which
13395        hadn't been re-set yet, and thus may have stale locations.  */
13396
13397     for (breakpoint *b : all_breakpoints_safe ())
13398       {
13399         try
13400           {
13401             breakpoint_re_set_one (b);
13402           }
13403         catch (const gdb_exception &ex)
13404           {
13405             exception_fprintf (gdb_stderr, ex,
13406                                "Error in re-setting breakpoint %d: ",
13407                                b->number);
13408           }
13409       }
13410
13411     jit_breakpoint_re_set ();
13412   }
13413
13414   create_overlay_event_breakpoint ();
13415   create_longjmp_master_breakpoint ();
13416   create_std_terminate_master_breakpoint ();
13417   create_exception_master_breakpoint ();
13418
13419   /* Now we can insert.  */
13420   update_global_location_list (UGLL_MAY_INSERT);
13421 }
13422 \f
13423 /* Reset the thread number of this breakpoint:
13424
13425    - If the breakpoint is for all threads, leave it as-is.
13426    - Else, reset it to the current thread for inferior_ptid.  */
13427 void
13428 breakpoint_re_set_thread (struct breakpoint *b)
13429 {
13430   if (b->thread != -1)
13431     {
13432       b->thread = inferior_thread ()->global_num;
13433
13434       /* We're being called after following a fork.  The new fork is
13435          selected as current, and unless this was a vfork will have a
13436          different program space from the original thread.  Reset that
13437          as well.  */
13438       b->loc->pspace = current_program_space;
13439     }
13440 }
13441
13442 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13443    If from_tty is nonzero, it prints a message to that effect,
13444    which ends with a period (no newline).  */
13445
13446 void
13447 set_ignore_count (int bptnum, int count, int from_tty)
13448 {
13449   if (count < 0)
13450     count = 0;
13451
13452   for (breakpoint *b : all_breakpoints ())
13453     if (b->number == bptnum)
13454       {
13455         if (is_tracepoint (b))
13456           {
13457             if (from_tty && count != 0)
13458               gdb_printf (_("Ignore count ignored for tracepoint %d."),
13459                           bptnum);
13460             return;
13461           }
13462
13463         b->ignore_count = count;
13464         if (from_tty)
13465           {
13466             if (count == 0)
13467               gdb_printf (_("Will stop next time "
13468                             "breakpoint %d is reached."),
13469                           bptnum);
13470             else if (count == 1)
13471               gdb_printf (_("Will ignore next crossing of breakpoint %d."),
13472                           bptnum);
13473             else
13474               gdb_printf (_("Will ignore next %d "
13475                             "crossings of breakpoint %d."),
13476                           count, bptnum);
13477           }
13478         gdb::observers::breakpoint_modified.notify (b);
13479         return;
13480       }
13481
13482   error (_("No breakpoint number %d."), bptnum);
13483 }
13484
13485 /* Command to set ignore-count of breakpoint N to COUNT.  */
13486
13487 static void
13488 ignore_command (const char *args, int from_tty)
13489 {
13490   const char *p = args;
13491   int num;
13492
13493   if (p == 0)
13494     error_no_arg (_("a breakpoint number"));
13495
13496   num = get_number (&p);
13497   if (num == 0)
13498     error (_("bad breakpoint number: '%s'"), args);
13499   if (*p == 0)
13500     error (_("Second argument (specified ignore-count) is missing."));
13501
13502   set_ignore_count (num,
13503                     longest_to_int (value_as_long (parse_and_eval (p))),
13504                     from_tty);
13505   if (from_tty)
13506     gdb_printf ("\n");
13507 }
13508 \f
13509
13510 /* Call FUNCTION on each of the breakpoints with numbers in the range
13511    defined by BP_NUM_RANGE (an inclusive range).  */
13512
13513 static void
13514 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13515                              gdb::function_view<void (breakpoint *)> function)
13516 {
13517   if (bp_num_range.first == 0)
13518     {
13519       warning (_("bad breakpoint number at or near '%d'"),
13520                bp_num_range.first);
13521     }
13522   else
13523     {
13524       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
13525         {
13526           bool match = false;
13527
13528           for (breakpoint *b : all_breakpoints_safe ())
13529             if (b->number == i)
13530               {
13531                 match = true;
13532                 function (b);
13533                 break;
13534               }
13535           if (!match)
13536             gdb_printf (_("No breakpoint number %d.\n"), i);
13537         }
13538     }
13539 }
13540
13541 /* Call FUNCTION on each of the breakpoints whose numbers are given in
13542    ARGS.  */
13543
13544 static void
13545 map_breakpoint_numbers (const char *args,
13546                         gdb::function_view<void (breakpoint *)> function)
13547 {
13548   if (args == NULL || *args == '\0')
13549     error_no_arg (_("one or more breakpoint numbers"));
13550
13551   number_or_range_parser parser (args);
13552
13553   while (!parser.finished ())
13554     {
13555       int num = parser.get_number ();
13556       map_breakpoint_number_range (std::make_pair (num, num), function);
13557     }
13558 }
13559
13560 /* Return the breakpoint location structure corresponding to the
13561    BP_NUM and LOC_NUM values.  */
13562
13563 static struct bp_location *
13564 find_location_by_number (int bp_num, int loc_num)
13565 {
13566   breakpoint *b = get_breakpoint (bp_num);
13567
13568   if (!b || b->number != bp_num)
13569     error (_("Bad breakpoint number '%d'"), bp_num);
13570   
13571   if (loc_num == 0)
13572     error (_("Bad breakpoint location number '%d'"), loc_num);
13573
13574   int n = 0;
13575   for (bp_location *loc : b->locations ())
13576     if (++n == loc_num)
13577       return loc;
13578
13579   error (_("Bad breakpoint location number '%d'"), loc_num);
13580 }
13581
13582 /* Modes of operation for extract_bp_num.  */
13583 enum class extract_bp_kind
13584 {
13585   /* Extracting a breakpoint number.  */
13586   bp,
13587
13588   /* Extracting a location number.  */
13589   loc,
13590 };
13591
13592 /* Extract a breakpoint or location number (as determined by KIND)
13593    from the string starting at START.  TRAILER is a character which
13594    can be found after the number.  If you don't want a trailer, use
13595    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
13596    string.  This always returns a positive integer.  */
13597
13598 static int
13599 extract_bp_num (extract_bp_kind kind, const char *start,
13600                 int trailer, const char **end_out = NULL)
13601 {
13602   const char *end = start;
13603   int num = get_number_trailer (&end, trailer);
13604   if (num < 0)
13605     error (kind == extract_bp_kind::bp
13606            ? _("Negative breakpoint number '%.*s'")
13607            : _("Negative breakpoint location number '%.*s'"),
13608            int (end - start), start);
13609   if (num == 0)
13610     error (kind == extract_bp_kind::bp
13611            ? _("Bad breakpoint number '%.*s'")
13612            : _("Bad breakpoint location number '%.*s'"),
13613            int (end - start), start);
13614
13615   if (end_out != NULL)
13616     *end_out = end;
13617   return num;
13618 }
13619
13620 /* Extract a breakpoint or location range (as determined by KIND) in
13621    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
13622    representing the (inclusive) range.  The returned pair's elements
13623    are always positive integers.  */
13624
13625 static std::pair<int, int>
13626 extract_bp_or_bp_range (extract_bp_kind kind,
13627                         const std::string &arg,
13628                         std::string::size_type arg_offset)
13629 {
13630   std::pair<int, int> range;
13631   const char *bp_loc = &arg[arg_offset];
13632   std::string::size_type dash = arg.find ('-', arg_offset);
13633   if (dash != std::string::npos)
13634     {
13635       /* bp_loc is a range (x-z).  */
13636       if (arg.length () == dash + 1)
13637         error (kind == extract_bp_kind::bp
13638                ? _("Bad breakpoint number at or near: '%s'")
13639                : _("Bad breakpoint location number at or near: '%s'"),
13640                bp_loc);
13641
13642       const char *end;
13643       const char *start_first = bp_loc;
13644       const char *start_second = &arg[dash + 1];
13645       range.first = extract_bp_num (kind, start_first, '-');
13646       range.second = extract_bp_num (kind, start_second, '\0', &end);
13647
13648       if (range.first > range.second)
13649         error (kind == extract_bp_kind::bp
13650                ? _("Inverted breakpoint range at '%.*s'")
13651                : _("Inverted breakpoint location range at '%.*s'"),
13652                int (end - start_first), start_first);
13653     }
13654   else
13655     {
13656       /* bp_loc is a single value.  */
13657       range.first = extract_bp_num (kind, bp_loc, '\0');
13658       range.second = range.first;
13659     }
13660   return range;
13661 }
13662
13663 /* Extract the breakpoint/location range specified by ARG.  Returns
13664    the breakpoint range in BP_NUM_RANGE, and the location range in
13665    BP_LOC_RANGE.
13666
13667    ARG may be in any of the following forms:
13668
13669    x     where 'x' is a breakpoint number.
13670    x-y   where 'x' and 'y' specify a breakpoint numbers range.
13671    x.y   where 'x' is a breakpoint number and 'y' a location number.
13672    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
13673          location number range.
13674 */
13675
13676 static void
13677 extract_bp_number_and_location (const std::string &arg,
13678                                 std::pair<int, int> &bp_num_range,
13679                                 std::pair<int, int> &bp_loc_range)
13680 {
13681   std::string::size_type dot = arg.find ('.');
13682
13683   if (dot != std::string::npos)
13684     {
13685       /* Handle 'x.y' and 'x.y-z' cases.  */
13686
13687       if (arg.length () == dot + 1 || dot == 0)
13688         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
13689
13690       bp_num_range.first
13691         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
13692       bp_num_range.second = bp_num_range.first;
13693
13694       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
13695                                              arg, dot + 1);
13696     }
13697   else
13698     {
13699       /* Handle x and x-y cases.  */
13700
13701       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
13702       bp_loc_range.first = 0;
13703       bp_loc_range.second = 0;
13704     }
13705 }
13706
13707 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
13708    specifies whether to enable or disable.  */
13709
13710 static void
13711 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
13712 {
13713   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
13714   if (loc != NULL)
13715     {
13716       if (loc->disabled_by_cond && enable)
13717         error (_("Breakpoint %d's condition is invalid at location %d, "
13718                  "cannot enable."), bp_num, loc_num);
13719
13720       if (loc->enabled != enable)
13721         {
13722           loc->enabled = enable;
13723           mark_breakpoint_location_modified (loc);
13724         }
13725       if (target_supports_enable_disable_tracepoint ()
13726           && current_trace_status ()->running && loc->owner
13727           && is_tracepoint (loc->owner))
13728         target_disable_tracepoint (loc);
13729     }
13730   update_global_location_list (UGLL_DONT_INSERT);
13731
13732   gdb::observers::breakpoint_modified.notify (loc->owner);
13733 }
13734
13735 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
13736    number of the breakpoint, and BP_LOC_RANGE specifies the
13737    (inclusive) range of location numbers of that breakpoint to
13738    enable/disable.  ENABLE specifies whether to enable or disable the
13739    location.  */
13740
13741 static void
13742 enable_disable_breakpoint_location_range (int bp_num,
13743                                           std::pair<int, int> &bp_loc_range,
13744                                           bool enable)
13745 {
13746   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
13747     enable_disable_bp_num_loc (bp_num, i, enable);
13748 }
13749
13750 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13751    If from_tty is nonzero, it prints a message to that effect,
13752    which ends with a period (no newline).  */
13753
13754 void
13755 disable_breakpoint (struct breakpoint *bpt)
13756 {
13757   /* Never disable a watchpoint scope breakpoint; we want to
13758      hit them when we leave scope so we can delete both the
13759      watchpoint and its scope breakpoint at that time.  */
13760   if (bpt->type == bp_watchpoint_scope)
13761     return;
13762
13763   bpt->enable_state = bp_disabled;
13764
13765   /* Mark breakpoint locations modified.  */
13766   mark_breakpoint_modified (bpt);
13767
13768   if (target_supports_enable_disable_tracepoint ()
13769       && current_trace_status ()->running && is_tracepoint (bpt))
13770     {
13771       for (bp_location *location : bpt->locations ())
13772         target_disable_tracepoint (location);
13773     }
13774
13775   update_global_location_list (UGLL_DONT_INSERT);
13776
13777   gdb::observers::breakpoint_modified.notify (bpt);
13778 }
13779
13780 /* Enable or disable the breakpoint(s) or breakpoint location(s)
13781    specified in ARGS.  ARGS may be in any of the formats handled by
13782    extract_bp_number_and_location.  ENABLE specifies whether to enable
13783    or disable the breakpoints/locations.  */
13784
13785 static void
13786 enable_disable_command (const char *args, int from_tty, bool enable)
13787 {
13788   if (args == 0)
13789     {
13790       for (breakpoint *bpt : all_breakpoints ())
13791         if (user_breakpoint_p (bpt))
13792           {
13793             if (enable)
13794               enable_breakpoint (bpt);
13795             else
13796               disable_breakpoint (bpt);
13797           }
13798     }
13799   else
13800     {
13801       std::string num = extract_arg (&args);
13802
13803       while (!num.empty ())
13804         {
13805           std::pair<int, int> bp_num_range, bp_loc_range;
13806
13807           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
13808
13809           if (bp_loc_range.first == bp_loc_range.second
13810               && bp_loc_range.first == 0)
13811             {
13812               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
13813               map_breakpoint_number_range (bp_num_range,
13814                                            enable
13815                                            ? enable_breakpoint
13816                                            : disable_breakpoint);
13817             }
13818           else
13819             {
13820               /* Handle breakpoint ids with formats 'x.y' or
13821                  'x.y-z'.  */
13822               enable_disable_breakpoint_location_range
13823                 (bp_num_range.first, bp_loc_range, enable);
13824             }
13825           num = extract_arg (&args);
13826         }
13827     }
13828 }
13829
13830 /* The disable command disables the specified breakpoints/locations
13831    (or all defined breakpoints) so they're no longer effective in
13832    stopping the inferior.  ARGS may be in any of the forms defined in
13833    extract_bp_number_and_location.  */
13834
13835 static void
13836 disable_command (const char *args, int from_tty)
13837 {
13838   enable_disable_command (args, from_tty, false);
13839 }
13840
13841 static void
13842 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13843                         int count)
13844 {
13845   int target_resources_ok;
13846
13847   if (bpt->type == bp_hardware_breakpoint)
13848     {
13849       int i;
13850       i = hw_breakpoint_used_count ();
13851       target_resources_ok = 
13852         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
13853                                             i + 1, 0);
13854       if (target_resources_ok == 0)
13855         error (_("No hardware breakpoint support in the target."));
13856       else if (target_resources_ok < 0)
13857         error (_("Hardware breakpoints used exceeds limit."));
13858     }
13859
13860   if (is_watchpoint (bpt))
13861     {
13862       /* Initialize it just to avoid a GCC false warning.  */
13863       enum enable_state orig_enable_state = bp_disabled;
13864
13865       try
13866         {
13867           struct watchpoint *w = (struct watchpoint *) bpt;
13868
13869           orig_enable_state = bpt->enable_state;
13870           bpt->enable_state = bp_enabled;
13871           update_watchpoint (w, 1 /* reparse */);
13872         }
13873       catch (const gdb_exception &e)
13874         {
13875           bpt->enable_state = orig_enable_state;
13876           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13877                              bpt->number);
13878           return;
13879         }
13880     }
13881
13882   bpt->enable_state = bp_enabled;
13883
13884   /* Mark breakpoint locations modified.  */
13885   mark_breakpoint_modified (bpt);
13886
13887   if (target_supports_enable_disable_tracepoint ()
13888       && current_trace_status ()->running && is_tracepoint (bpt))
13889     {
13890       for (bp_location *location : bpt->locations ())
13891         target_enable_tracepoint (location);
13892     }
13893
13894   bpt->disposition = disposition;
13895   bpt->enable_count = count;
13896   update_global_location_list (UGLL_MAY_INSERT);
13897
13898   gdb::observers::breakpoint_modified.notify (bpt);
13899 }
13900
13901
13902 void
13903 enable_breakpoint (struct breakpoint *bpt)
13904 {
13905   enable_breakpoint_disp (bpt, bpt->disposition, 0);
13906 }
13907
13908 /* The enable command enables the specified breakpoints/locations (or
13909    all defined breakpoints) so they once again become (or continue to
13910    be) effective in stopping the inferior.  ARGS may be in any of the
13911    forms defined in extract_bp_number_and_location.  */
13912
13913 static void
13914 enable_command (const char *args, int from_tty)
13915 {
13916   enable_disable_command (args, from_tty, true);
13917 }
13918
13919 static void
13920 enable_once_command (const char *args, int from_tty)
13921 {
13922   map_breakpoint_numbers
13923     (args, [&] (breakpoint *b)
13924      {
13925        iterate_over_related_breakpoints
13926          (b, [&] (breakpoint *bpt)
13927           {
13928             enable_breakpoint_disp (bpt, disp_disable, 1);
13929           });
13930      });
13931 }
13932
13933 static void
13934 enable_count_command (const char *args, int from_tty)
13935 {
13936   int count;
13937
13938   if (args == NULL)
13939     error_no_arg (_("hit count"));
13940
13941   count = get_number (&args);
13942
13943   map_breakpoint_numbers
13944     (args, [&] (breakpoint *b)
13945      {
13946        iterate_over_related_breakpoints
13947          (b, [&] (breakpoint *bpt)
13948           {
13949             enable_breakpoint_disp (bpt, disp_disable, count);
13950           });
13951      });
13952 }
13953
13954 static void
13955 enable_delete_command (const char *args, int from_tty)
13956 {
13957   map_breakpoint_numbers
13958     (args, [&] (breakpoint *b)
13959      {
13960        iterate_over_related_breakpoints
13961          (b, [&] (breakpoint *bpt)
13962           {
13963             enable_breakpoint_disp (bpt, disp_del, 1);
13964           });
13965      });
13966 }
13967 \f
13968 /* Invalidate last known value of any hardware watchpoint if
13969    the memory which that value represents has been written to by
13970    GDB itself.  */
13971
13972 static void
13973 invalidate_bp_value_on_memory_change (struct inferior *inferior,
13974                                       CORE_ADDR addr, ssize_t len,
13975                                       const bfd_byte *data)
13976 {
13977   for (breakpoint *bp : all_breakpoints ())
13978     if (bp->enable_state == bp_enabled
13979         && bp->type == bp_hardware_watchpoint)
13980       {
13981         struct watchpoint *wp = (struct watchpoint *) bp;
13982
13983         if (wp->val_valid && wp->val != nullptr)
13984           {
13985             for (bp_location *loc : bp->locations ())
13986               if (loc->loc_type == bp_loc_hardware_watchpoint
13987                   && loc->address + loc->length > addr
13988                   && addr + len > loc->address)
13989                 {
13990                   wp->val = NULL;
13991                   wp->val_valid = false;
13992                 }
13993           }
13994       }
13995 }
13996
13997 /* Create and insert a breakpoint for software single step.  */
13998
13999 void
14000 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14001                                const address_space *aspace,
14002                                CORE_ADDR next_pc)
14003 {
14004   struct thread_info *tp = inferior_thread ();
14005   struct symtab_and_line sal;
14006   CORE_ADDR pc = next_pc;
14007
14008   if (tp->control.single_step_breakpoints == NULL)
14009     {
14010       tp->control.single_step_breakpoints
14011         = new_single_step_breakpoint (tp->global_num, gdbarch);
14012     }
14013
14014   sal = find_pc_line (pc, 0);
14015   sal.pc = pc;
14016   sal.section = find_pc_overlay (pc);
14017   sal.explicit_pc = 1;
14018   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14019
14020   update_global_location_list (UGLL_INSERT);
14021 }
14022
14023 /* Insert single step breakpoints according to the current state.  */
14024
14025 int
14026 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14027 {
14028   struct regcache *regcache = get_current_regcache ();
14029   std::vector<CORE_ADDR> next_pcs;
14030
14031   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14032
14033   if (!next_pcs.empty ())
14034     {
14035       struct frame_info *frame = get_current_frame ();
14036       const address_space *aspace = get_frame_address_space (frame);
14037
14038       for (CORE_ADDR pc : next_pcs)
14039         insert_single_step_breakpoint (gdbarch, aspace, pc);
14040
14041       return 1;
14042     }
14043   else
14044     return 0;
14045 }
14046
14047 /* See breakpoint.h.  */
14048
14049 int
14050 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14051                                        const address_space *aspace,
14052                                        CORE_ADDR pc)
14053 {
14054   for (bp_location *loc : bp->locations ())
14055     if (loc->inserted
14056         && breakpoint_location_address_match (loc, aspace, pc))
14057       return 1;
14058
14059   return 0;
14060 }
14061
14062 /* Check whether a software single-step breakpoint is inserted at
14063    PC.  */
14064
14065 int
14066 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14067                                         CORE_ADDR pc)
14068 {
14069   for (breakpoint *bpt : all_breakpoints ())
14070     {
14071       if (bpt->type == bp_single_step
14072           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14073         return 1;
14074     }
14075   return 0;
14076 }
14077
14078 /* Tracepoint-specific operations.  */
14079
14080 /* Set tracepoint count to NUM.  */
14081 static void
14082 set_tracepoint_count (int num)
14083 {
14084   tracepoint_count = num;
14085   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14086 }
14087
14088 static void
14089 trace_command (const char *arg, int from_tty)
14090 {
14091   event_location_up location = string_to_event_location (&arg,
14092                                                          current_language);
14093   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
14094     (location.get (), true /* is_tracepoint */);
14095
14096   create_breakpoint (get_current_arch (),
14097                      location.get (),
14098                      NULL, 0, arg, false, 1 /* parse arg */,
14099                      0 /* tempflag */,
14100                      bp_tracepoint /* type_wanted */,
14101                      0 /* Ignore count */,
14102                      pending_break_support,
14103                      ops,
14104                      from_tty,
14105                      1 /* enabled */,
14106                      0 /* internal */, 0);
14107 }
14108
14109 static void
14110 ftrace_command (const char *arg, int from_tty)
14111 {
14112   event_location_up location = string_to_event_location (&arg,
14113                                                          current_language);
14114   create_breakpoint (get_current_arch (),
14115                      location.get (),
14116                      NULL, 0, arg, false, 1 /* parse arg */,
14117                      0 /* tempflag */,
14118                      bp_fast_tracepoint /* type_wanted */,
14119                      0 /* Ignore count */,
14120                      pending_break_support,
14121                      &tracepoint_breakpoint_ops,
14122                      from_tty,
14123                      1 /* enabled */,
14124                      0 /* internal */, 0);
14125 }
14126
14127 /* strace command implementation.  Creates a static tracepoint.  */
14128
14129 static void
14130 strace_command (const char *arg, int from_tty)
14131 {
14132   struct breakpoint_ops *ops;
14133   event_location_up location;
14134
14135   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14136      or with a normal static tracepoint.  */
14137   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14138     {
14139       ops = &strace_marker_breakpoint_ops;
14140       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14141     }
14142   else
14143     {
14144       ops = &tracepoint_breakpoint_ops;
14145       location = string_to_event_location (&arg, current_language);
14146     }
14147
14148   create_breakpoint (get_current_arch (),
14149                      location.get (),
14150                      NULL, 0, arg, false, 1 /* parse arg */,
14151                      0 /* tempflag */,
14152                      bp_static_tracepoint /* type_wanted */,
14153                      0 /* Ignore count */,
14154                      pending_break_support,
14155                      ops,
14156                      from_tty,
14157                      1 /* enabled */,
14158                      0 /* internal */, 0);
14159 }
14160
14161 /* Set up a fake reader function that gets command lines from a linked
14162    list that was acquired during tracepoint uploading.  */
14163
14164 static struct uploaded_tp *this_utp;
14165 static int next_cmd;
14166
14167 static char *
14168 read_uploaded_action (void)
14169 {
14170   char *rslt = nullptr;
14171
14172   if (next_cmd < this_utp->cmd_strings.size ())
14173     {
14174       rslt = this_utp->cmd_strings[next_cmd].get ();
14175       next_cmd++;
14176     }
14177
14178   return rslt;
14179 }
14180
14181 /* Given information about a tracepoint as recorded on a target (which
14182    can be either a live system or a trace file), attempt to create an
14183    equivalent GDB tracepoint.  This is not a reliable process, since
14184    the target does not necessarily have all the information used when
14185    the tracepoint was originally defined.  */
14186   
14187 struct tracepoint *
14188 create_tracepoint_from_upload (struct uploaded_tp *utp)
14189 {
14190   const char *addr_str;
14191   char small_buf[100];
14192   struct tracepoint *tp;
14193
14194   if (utp->at_string)
14195     addr_str = utp->at_string.get ();
14196   else
14197     {
14198       /* In the absence of a source location, fall back to raw
14199          address.  Since there is no way to confirm that the address
14200          means the same thing as when the trace was started, warn the
14201          user.  */
14202       warning (_("Uploaded tracepoint %d has no "
14203                  "source location, using raw address"),
14204                utp->number);
14205       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14206       addr_str = small_buf;
14207     }
14208
14209   /* There's not much we can do with a sequence of bytecodes.  */
14210   if (utp->cond && !utp->cond_string)
14211     warning (_("Uploaded tracepoint %d condition "
14212                "has no source form, ignoring it"),
14213              utp->number);
14214
14215   event_location_up location = string_to_event_location (&addr_str,
14216                                                          current_language);
14217   if (!create_breakpoint (get_current_arch (),
14218                           location.get (),
14219                           utp->cond_string.get (), -1, addr_str,
14220                           false /* force_condition */,
14221                           0 /* parse cond/thread */,
14222                           0 /* tempflag */,
14223                           utp->type /* type_wanted */,
14224                           0 /* Ignore count */,
14225                           pending_break_support,
14226                           &tracepoint_breakpoint_ops,
14227                           0 /* from_tty */,
14228                           utp->enabled /* enabled */,
14229                           0 /* internal */,
14230                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14231     return NULL;
14232
14233   /* Get the tracepoint we just created.  */
14234   tp = get_tracepoint (tracepoint_count);
14235   gdb_assert (tp != NULL);
14236
14237   if (utp->pass > 0)
14238     {
14239       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14240                  tp->number);
14241
14242       trace_pass_command (small_buf, 0);
14243     }
14244
14245   /* If we have uploaded versions of the original commands, set up a
14246      special-purpose "reader" function and call the usual command line
14247      reader, then pass the result to the breakpoint command-setting
14248      function.  */
14249   if (!utp->cmd_strings.empty ())
14250     {
14251       counted_command_line cmd_list;
14252
14253       this_utp = utp;
14254       next_cmd = 0;
14255
14256       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14257
14258       breakpoint_set_commands (tp, std::move (cmd_list));
14259     }
14260   else if (!utp->actions.empty ()
14261            || !utp->step_actions.empty ())
14262     warning (_("Uploaded tracepoint %d actions "
14263                "have no source form, ignoring them"),
14264              utp->number);
14265
14266   /* Copy any status information that might be available.  */
14267   tp->hit_count = utp->hit_count;
14268   tp->traceframe_usage = utp->traceframe_usage;
14269
14270   return tp;
14271 }
14272   
14273 /* Print information on tracepoint number TPNUM_EXP, or all if
14274    omitted.  */
14275
14276 static void
14277 info_tracepoints_command (const char *args, int from_tty)
14278 {
14279   struct ui_out *uiout = current_uiout;
14280   int num_printed;
14281
14282   num_printed = breakpoint_1 (args, false, is_tracepoint);
14283
14284   if (num_printed == 0)
14285     {
14286       if (args == NULL || *args == '\0')
14287         uiout->message ("No tracepoints.\n");
14288       else
14289         uiout->message ("No tracepoint matching '%s'.\n", args);
14290     }
14291
14292   default_collect_info ();
14293 }
14294
14295 /* The 'enable trace' command enables tracepoints.
14296    Not supported by all targets.  */
14297 static void
14298 enable_trace_command (const char *args, int from_tty)
14299 {
14300   enable_command (args, from_tty);
14301 }
14302
14303 /* The 'disable trace' command disables tracepoints.
14304    Not supported by all targets.  */
14305 static void
14306 disable_trace_command (const char *args, int from_tty)
14307 {
14308   disable_command (args, from_tty);
14309 }
14310
14311 /* Remove a tracepoint (or all if no argument).  */
14312 static void
14313 delete_trace_command (const char *arg, int from_tty)
14314 {
14315   dont_repeat ();
14316
14317   if (arg == 0)
14318     {
14319       int breaks_to_delete = 0;
14320
14321       /* Delete all breakpoints if no argument.
14322          Do not delete internal or call-dummy breakpoints, these
14323          have to be deleted with an explicit breakpoint number 
14324          argument.  */
14325       for (breakpoint *tp : all_tracepoints ())
14326         if (is_tracepoint (tp) && user_breakpoint_p (tp))
14327           {
14328             breaks_to_delete = 1;
14329             break;
14330           }
14331
14332       /* Ask user only if there are some breakpoints to delete.  */
14333       if (!from_tty
14334           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14335         {
14336           for (breakpoint *b : all_breakpoints_safe ())
14337             if (is_tracepoint (b) && user_breakpoint_p (b))
14338               delete_breakpoint (b);
14339         }
14340     }
14341   else
14342     map_breakpoint_numbers
14343       (arg, [&] (breakpoint *br)
14344        {
14345          iterate_over_related_breakpoints (br, delete_breakpoint);
14346        });
14347 }
14348
14349 /* Helper function for trace_pass_command.  */
14350
14351 static void
14352 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14353 {
14354   tp->pass_count = count;
14355   gdb::observers::breakpoint_modified.notify (tp);
14356   if (from_tty)
14357     gdb_printf (_("Setting tracepoint %d's passcount to %d\n"),
14358                 tp->number, count);
14359 }
14360
14361 /* Set passcount for tracepoint.
14362
14363    First command argument is passcount, second is tracepoint number.
14364    If tracepoint number omitted, apply to most recently defined.
14365    Also accepts special argument "all".  */
14366
14367 static void
14368 trace_pass_command (const char *args, int from_tty)
14369 {
14370   struct tracepoint *t1;
14371   ULONGEST count;
14372
14373   if (args == 0 || *args == 0)
14374     error (_("passcount command requires an "
14375              "argument (count + optional TP num)"));
14376
14377   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14378
14379   args = skip_spaces (args);
14380   if (*args && strncasecmp (args, "all", 3) == 0)
14381     {
14382       args += 3;                        /* Skip special argument "all".  */
14383       if (*args)
14384         error (_("Junk at end of arguments."));
14385
14386       for (breakpoint *b : all_tracepoints ())
14387         {
14388           t1 = (struct tracepoint *) b;
14389           trace_pass_set_count (t1, count, from_tty);
14390         }
14391     }
14392   else if (*args == '\0')
14393     {
14394       t1 = get_tracepoint_by_number (&args, NULL);
14395       if (t1)
14396         trace_pass_set_count (t1, count, from_tty);
14397     }
14398   else
14399     {
14400       number_or_range_parser parser (args);
14401       while (!parser.finished ())
14402         {
14403           t1 = get_tracepoint_by_number (&args, &parser);
14404           if (t1)
14405             trace_pass_set_count (t1, count, from_tty);
14406         }
14407     }
14408 }
14409
14410 struct tracepoint *
14411 get_tracepoint (int num)
14412 {
14413   for (breakpoint *t : all_tracepoints ())
14414     if (t->number == num)
14415       return (struct tracepoint *) t;
14416
14417   return NULL;
14418 }
14419
14420 /* Find the tracepoint with the given target-side number (which may be
14421    different from the tracepoint number after disconnecting and
14422    reconnecting).  */
14423
14424 struct tracepoint *
14425 get_tracepoint_by_number_on_target (int num)
14426 {
14427   for (breakpoint *b : all_tracepoints ())
14428     {
14429       struct tracepoint *t = (struct tracepoint *) b;
14430
14431       if (t->number_on_target == num)
14432         return t;
14433     }
14434
14435   return NULL;
14436 }
14437
14438 /* Utility: parse a tracepoint number and look it up in the list.
14439    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14440    If the argument is missing, the most recent tracepoint
14441    (tracepoint_count) is returned.  */
14442
14443 struct tracepoint *
14444 get_tracepoint_by_number (const char **arg,
14445                           number_or_range_parser *parser)
14446 {
14447   int tpnum;
14448   const char *instring = arg == NULL ? NULL : *arg;
14449
14450   if (parser != NULL)
14451     {
14452       gdb_assert (!parser->finished ());
14453       tpnum = parser->get_number ();
14454     }
14455   else if (arg == NULL || *arg == NULL || ! **arg)
14456     tpnum = tracepoint_count;
14457   else
14458     tpnum = get_number (arg);
14459
14460   if (tpnum <= 0)
14461     {
14462       if (instring && *instring)
14463         gdb_printf (_("bad tracepoint number at or near '%s'\n"), 
14464                     instring);
14465       else
14466         gdb_printf (_("No previous tracepoint\n"));
14467       return NULL;
14468     }
14469
14470   for (breakpoint *t : all_tracepoints ())
14471     if (t->number == tpnum)
14472       return (struct tracepoint *) t;
14473
14474   gdb_printf ("No tracepoint number %d.\n", tpnum);
14475   return NULL;
14476 }
14477
14478 void
14479 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14480 {
14481   if (b->thread != -1)
14482     gdb_printf (fp, " thread %d", b->thread);
14483
14484   if (b->task != 0)
14485     gdb_printf (fp, " task %d", b->task);
14486
14487   gdb_printf (fp, "\n");
14488 }
14489
14490 /* Save information on user settable breakpoints (watchpoints, etc) to
14491    a new script file named FILENAME.  If FILTER is non-NULL, call it
14492    on each breakpoint and only include the ones for which it returns
14493    true.  */
14494
14495 static void
14496 save_breakpoints (const char *filename, int from_tty,
14497                   bool (*filter) (const struct breakpoint *))
14498 {
14499   int any = 0;
14500   int extra_trace_bits = 0;
14501
14502   if (filename == 0 || *filename == 0)
14503     error (_("Argument required (file name in which to save)"));
14504
14505   /* See if we have anything to save.  */
14506   for (breakpoint *tp : all_breakpoints ())
14507     {
14508       /* Skip internal and momentary breakpoints.  */
14509       if (!user_breakpoint_p (tp))
14510         continue;
14511
14512       /* If we have a filter, only save the breakpoints it accepts.  */
14513       if (filter && !filter (tp))
14514         continue;
14515
14516       any = 1;
14517
14518       if (is_tracepoint (tp))
14519         {
14520           extra_trace_bits = 1;
14521
14522           /* We can stop searching.  */
14523           break;
14524         }
14525     }
14526
14527   if (!any)
14528     {
14529       warning (_("Nothing to save."));
14530       return;
14531     }
14532
14533   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
14534
14535   stdio_file fp;
14536
14537   if (!fp.open (expanded_filename.get (), "w"))
14538     error (_("Unable to open file '%s' for saving (%s)"),
14539            expanded_filename.get (), safe_strerror (errno));
14540
14541   if (extra_trace_bits)
14542     save_trace_state_variables (&fp);
14543
14544   for (breakpoint *tp : all_breakpoints ())
14545     {
14546       /* Skip internal and momentary breakpoints.  */
14547       if (!user_breakpoint_p (tp))
14548         continue;
14549
14550       /* If we have a filter, only save the breakpoints it accepts.  */
14551       if (filter && !filter (tp))
14552         continue;
14553
14554       tp->ops->print_recreate (tp, &fp);
14555
14556       /* Note, we can't rely on tp->number for anything, as we can't
14557          assume the recreated breakpoint numbers will match.  Use $bpnum
14558          instead.  */
14559
14560       if (tp->cond_string)
14561         fp.printf ("  condition $bpnum %s\n", tp->cond_string.get ());
14562
14563       if (tp->ignore_count)
14564         fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
14565
14566       if (tp->type != bp_dprintf && tp->commands)
14567         {
14568           fp.puts ("  commands\n");
14569
14570           current_uiout->redirect (&fp);
14571           try
14572             {
14573               print_command_lines (current_uiout, tp->commands.get (), 2);
14574             }
14575           catch (const gdb_exception &ex)
14576             {
14577             current_uiout->redirect (NULL);
14578               throw;
14579             }
14580
14581           current_uiout->redirect (NULL);
14582           fp.puts ("  end\n");
14583         }
14584
14585       if (tp->enable_state == bp_disabled)
14586         fp.puts ("disable $bpnum\n");
14587
14588       /* If this is a multi-location breakpoint, check if the locations
14589          should be individually disabled.  Watchpoint locations are
14590          special, and not user visible.  */
14591       if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14592         {
14593           int n = 1;
14594
14595           for (bp_location *loc : tp->locations ())
14596             {
14597               if (!loc->enabled)
14598                 fp.printf ("disable $bpnum.%d\n", n);
14599
14600               n++;
14601             }
14602         }
14603     }
14604
14605   if (extra_trace_bits && !default_collect.empty ())
14606     fp.printf ("set default-collect %s\n", default_collect.c_str ());
14607
14608   if (from_tty)
14609     gdb_printf (_("Saved to file '%s'.\n"), expanded_filename.get ());
14610 }
14611
14612 /* The `save breakpoints' command.  */
14613
14614 static void
14615 save_breakpoints_command (const char *args, int from_tty)
14616 {
14617   save_breakpoints (args, from_tty, NULL);
14618 }
14619
14620 /* The `save tracepoints' command.  */
14621
14622 static void
14623 save_tracepoints_command (const char *args, int from_tty)
14624 {
14625   save_breakpoints (args, from_tty, is_tracepoint);
14626 }
14627
14628 \f
14629 /* This help string is used to consolidate all the help string for specifying
14630    locations used by several commands.  */
14631
14632 #define LOCATION_HELP_STRING \
14633 "Linespecs are colon-separated lists of location parameters, such as\n\
14634 source filename, function name, label name, and line number.\n\
14635 Example: To specify the start of a label named \"the_top\" in the\n\
14636 function \"fact\" in the file \"factorial.c\", use\n\
14637 \"factorial.c:fact:the_top\".\n\
14638 \n\
14639 Address locations begin with \"*\" and specify an exact address in the\n\
14640 program.  Example: To specify the fourth byte past the start function\n\
14641 \"main\", use \"*main + 4\".\n\
14642 \n\
14643 Explicit locations are similar to linespecs but use an option/argument\n\
14644 syntax to specify location parameters.\n\
14645 Example: To specify the start of the label named \"the_top\" in the\n\
14646 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
14647 -function fact -label the_top\".\n\
14648 \n\
14649 By default, a specified function is matched against the program's\n\
14650 functions in all scopes.  For C++, this means in all namespaces and\n\
14651 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
14652 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
14653 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
14654 specified name as a complete fully-qualified name instead."
14655
14656 /* This help string is used for the break, hbreak, tbreak and thbreak
14657    commands.  It is defined as a macro to prevent duplication.
14658    COMMAND should be a string constant containing the name of the
14659    command.  */
14660
14661 #define BREAK_ARGS_HELP(command) \
14662 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
14663 \t[-force-condition] [if CONDITION]\n\
14664 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
14665 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
14666 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
14667 `-probe-dtrace' (for a DTrace probe).\n\
14668 LOCATION may be a linespec, address, or explicit location as described\n\
14669 below.\n\
14670 \n\
14671 With no LOCATION, uses current execution address of the selected\n\
14672 stack frame.  This is useful for breaking on return to a stack frame.\n\
14673 \n\
14674 THREADNUM is the number from \"info threads\".\n\
14675 CONDITION is a boolean expression.\n\
14676 \n\
14677 With the \"-force-condition\" flag, the condition is defined even when\n\
14678 it is invalid for all current locations.\n\
14679 \n" LOCATION_HELP_STRING "\n\n\
14680 Multiple breakpoints at one place are permitted, and useful if their\n\
14681 conditions are different.\n\
14682 \n\
14683 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14684
14685 /* List of subcommands for "catch".  */
14686 static struct cmd_list_element *catch_cmdlist;
14687
14688 /* List of subcommands for "tcatch".  */
14689 static struct cmd_list_element *tcatch_cmdlist;
14690
14691 void
14692 add_catch_command (const char *name, const char *docstring,
14693                    cmd_func_ftype *func,
14694                    completer_ftype *completer,
14695                    void *user_data_catch,
14696                    void *user_data_tcatch)
14697 {
14698   struct cmd_list_element *command;
14699
14700   command = add_cmd (name, class_breakpoint, docstring,
14701                      &catch_cmdlist);
14702   command->func = func;
14703   command->set_context (user_data_catch);
14704   set_cmd_completer (command, completer);
14705
14706   command = add_cmd (name, class_breakpoint, docstring,
14707                      &tcatch_cmdlist);
14708   command->func = func;
14709   command->set_context (user_data_tcatch);
14710   set_cmd_completer (command, completer);
14711 }
14712
14713 /* Zero if any of the breakpoint's locations could be a location where
14714    functions have been inlined, nonzero otherwise.  */
14715
14716 static int
14717 is_non_inline_function (struct breakpoint *b)
14718 {
14719   /* The shared library event breakpoint is set on the address of a
14720      non-inline function.  */
14721   if (b->type == bp_shlib_event)
14722     return 1;
14723
14724   return 0;
14725 }
14726
14727 /* Nonzero if the specified PC cannot be a location where functions
14728    have been inlined.  */
14729
14730 int
14731 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
14732                            const target_waitstatus &ws)
14733 {
14734   for (breakpoint *b : all_breakpoints ())
14735     {
14736       if (!is_non_inline_function (b))
14737         continue;
14738
14739       for (bp_location *bl : b->locations ())
14740         {
14741           if (!bl->shlib_disabled
14742               && bpstat_check_location (bl, aspace, pc, ws))
14743             return 1;
14744         }
14745     }
14746
14747   return 0;
14748 }
14749
14750 /* Remove any references to OBJFILE which is going to be freed.  */
14751
14752 void
14753 breakpoint_free_objfile (struct objfile *objfile)
14754 {
14755   for (bp_location *loc : all_bp_locations ())
14756     if (loc->symtab != NULL && loc->symtab->objfile () == objfile)
14757       loc->symtab = NULL;
14758 }
14759
14760 void
14761 initialize_breakpoint_ops (void)
14762 {
14763   static int initialized = 0;
14764
14765   struct breakpoint_ops *ops;
14766
14767   if (initialized)
14768     return;
14769   initialized = 1;
14770
14771   /* The breakpoint_ops structure to be inherit by all kinds of
14772      breakpoints (real breakpoints, i.e., user "break" breakpoints,
14773      internal and momentary breakpoints, etc.).  */
14774   ops = &bkpt_base_breakpoint_ops;
14775   *ops = base_breakpoint_ops;
14776   ops->re_set = bkpt_re_set;
14777   ops->insert_location = bkpt_insert_location;
14778   ops->remove_location = bkpt_remove_location;
14779   ops->breakpoint_hit = bkpt_breakpoint_hit;
14780   ops->create_sals_from_location = bkpt_create_sals_from_location;
14781   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
14782   ops->decode_location = bkpt_decode_location;
14783
14784   /* The breakpoint_ops structure to be used in regular breakpoints.  */
14785   ops = &bkpt_breakpoint_ops;
14786   *ops = bkpt_base_breakpoint_ops;
14787   ops->re_set = bkpt_re_set;
14788   ops->resources_needed = bkpt_resources_needed;
14789   ops->print_it = bkpt_print_it;
14790   ops->print_mention = bkpt_print_mention;
14791   ops->print_recreate = bkpt_print_recreate;
14792
14793   /* Ranged breakpoints.  */
14794   ops = &ranged_breakpoint_ops;
14795   *ops = bkpt_breakpoint_ops;
14796   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
14797   ops->resources_needed = resources_needed_ranged_breakpoint;
14798   ops->print_it = print_it_ranged_breakpoint;
14799   ops->print_one = print_one_ranged_breakpoint;
14800   ops->print_one_detail = print_one_detail_ranged_breakpoint;
14801   ops->print_mention = print_mention_ranged_breakpoint;
14802   ops->print_recreate = print_recreate_ranged_breakpoint;
14803
14804   /* Internal breakpoints.  */
14805   ops = &internal_breakpoint_ops;
14806   *ops = bkpt_base_breakpoint_ops;
14807   ops->re_set = internal_bkpt_re_set;
14808   ops->check_status = internal_bkpt_check_status;
14809   ops->print_it = internal_bkpt_print_it;
14810   ops->print_mention = internal_bkpt_print_mention;
14811
14812   /* Momentary breakpoints.  */
14813   ops = &momentary_breakpoint_ops;
14814   *ops = bkpt_base_breakpoint_ops;
14815   ops->re_set = momentary_bkpt_re_set;
14816   ops->check_status = momentary_bkpt_check_status;
14817   ops->print_it = momentary_bkpt_print_it;
14818   ops->print_mention = momentary_bkpt_print_mention;
14819
14820   /* Probe breakpoints.  */
14821   ops = &bkpt_probe_breakpoint_ops;
14822   *ops = bkpt_breakpoint_ops;
14823   ops->insert_location = bkpt_probe_insert_location;
14824   ops->remove_location = bkpt_probe_remove_location;
14825   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
14826   ops->decode_location = bkpt_probe_decode_location;
14827
14828   /* Watchpoints.  */
14829   ops = &watchpoint_breakpoint_ops;
14830   *ops = base_breakpoint_ops;
14831   ops->re_set = re_set_watchpoint;
14832   ops->insert_location = insert_watchpoint;
14833   ops->remove_location = remove_watchpoint;
14834   ops->breakpoint_hit = breakpoint_hit_watchpoint;
14835   ops->check_status = check_status_watchpoint;
14836   ops->resources_needed = resources_needed_watchpoint;
14837   ops->works_in_software_mode = works_in_software_mode_watchpoint;
14838   ops->print_it = print_it_watchpoint;
14839   ops->print_mention = print_mention_watchpoint;
14840   ops->print_recreate = print_recreate_watchpoint;
14841   ops->explains_signal = explains_signal_watchpoint;
14842
14843   /* Masked watchpoints.  */
14844   ops = &masked_watchpoint_breakpoint_ops;
14845   *ops = watchpoint_breakpoint_ops;
14846   ops->insert_location = insert_masked_watchpoint;
14847   ops->remove_location = remove_masked_watchpoint;
14848   ops->resources_needed = resources_needed_masked_watchpoint;
14849   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
14850   ops->print_it = print_it_masked_watchpoint;
14851   ops->print_one_detail = print_one_detail_masked_watchpoint;
14852   ops->print_mention = print_mention_masked_watchpoint;
14853   ops->print_recreate = print_recreate_masked_watchpoint;
14854
14855   /* Tracepoints.  */
14856   ops = &tracepoint_breakpoint_ops;
14857   *ops = base_breakpoint_ops;
14858   ops->re_set = tracepoint_re_set;
14859   ops->breakpoint_hit = tracepoint_breakpoint_hit;
14860   ops->print_one_detail = tracepoint_print_one_detail;
14861   ops->print_mention = tracepoint_print_mention;
14862   ops->print_recreate = tracepoint_print_recreate;
14863   ops->create_sals_from_location = tracepoint_create_sals_from_location;
14864   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
14865   ops->decode_location = tracepoint_decode_location;
14866
14867   /* Probe tracepoints.  */
14868   ops = &tracepoint_probe_breakpoint_ops;
14869   *ops = tracepoint_breakpoint_ops;
14870   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
14871   ops->decode_location = tracepoint_probe_decode_location;
14872
14873   /* Static tracepoints with marker (`-m').  */
14874   ops = &strace_marker_breakpoint_ops;
14875   *ops = tracepoint_breakpoint_ops;
14876   ops->create_sals_from_location = strace_marker_create_sals_from_location;
14877   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
14878   ops->decode_location = strace_marker_decode_location;
14879
14880   /* Solib-related catchpoints.  */
14881   ops = &catch_solib_breakpoint_ops;
14882   *ops = base_breakpoint_ops;
14883   ops->insert_location = insert_catch_solib;
14884   ops->remove_location = remove_catch_solib;
14885   ops->breakpoint_hit = breakpoint_hit_catch_solib;
14886   ops->check_status = check_status_catch_solib;
14887   ops->print_it = print_it_catch_solib;
14888   ops->print_one = print_one_catch_solib;
14889   ops->print_mention = print_mention_catch_solib;
14890   ops->print_recreate = print_recreate_catch_solib;
14891
14892   ops = &dprintf_breakpoint_ops;
14893   *ops = bkpt_base_breakpoint_ops;
14894   ops->re_set = dprintf_re_set;
14895   ops->resources_needed = bkpt_resources_needed;
14896   ops->print_it = bkpt_print_it;
14897   ops->print_mention = bkpt_print_mention;
14898   ops->print_recreate = dprintf_print_recreate;
14899   ops->after_condition_true = dprintf_after_condition_true;
14900   ops->breakpoint_hit = dprintf_breakpoint_hit;
14901 }
14902
14903 /* Chain containing all defined "enable breakpoint" subcommands.  */
14904
14905 static struct cmd_list_element *enablebreaklist = NULL;
14906
14907 /* See breakpoint.h.  */
14908
14909 cmd_list_element *commands_cmd_element = nullptr;
14910
14911 void _initialize_breakpoint ();
14912 void
14913 _initialize_breakpoint ()
14914 {
14915   struct cmd_list_element *c;
14916
14917   initialize_breakpoint_ops ();
14918
14919   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
14920                                          "breakpoint");
14921   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
14922                                        "breakpoint");
14923   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
14924                                          "breakpoint");
14925
14926   breakpoint_chain = 0;
14927   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
14928      before a breakpoint is set.  */
14929   breakpoint_count = 0;
14930
14931   tracepoint_count = 0;
14932
14933   add_com ("ignore", class_breakpoint, ignore_command, _("\
14934 Set ignore-count of breakpoint number N to COUNT.\n\
14935 Usage is `ignore N COUNT'."));
14936
14937   commands_cmd_element = add_com ("commands", class_breakpoint,
14938                                   commands_command, _("\
14939 Set commands to be executed when the given breakpoints are hit.\n\
14940 Give a space-separated breakpoint list as argument after \"commands\".\n\
14941 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
14942 (e.g. `5-7').\n\
14943 With no argument, the targeted breakpoint is the last one set.\n\
14944 The commands themselves follow starting on the next line.\n\
14945 Type a line containing \"end\" to indicate the end of them.\n\
14946 Give \"silent\" as the first line to make the breakpoint silent;\n\
14947 then no output is printed when it is hit, except what the commands print."));
14948
14949   const auto cc_opts = make_condition_command_options_def_group (nullptr);
14950   static std::string condition_command_help
14951     = gdb::option::build_help (_("\
14952 Specify breakpoint number N to break only if COND is true.\n\
14953 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
14954 is an expression to be evaluated whenever breakpoint N is reached.\n\
14955 \n\
14956 Options:\n\
14957 %OPTIONS%"), cc_opts);
14958
14959   c = add_com ("condition", class_breakpoint, condition_command,
14960                condition_command_help.c_str ());
14961   set_cmd_completer_handle_brkchars (c, condition_completer);
14962
14963   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14964 Set a temporary breakpoint.\n\
14965 Like \"break\" except the breakpoint is only temporary,\n\
14966 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
14967 by using \"enable delete\" on the breakpoint number.\n\
14968 \n"
14969 BREAK_ARGS_HELP ("tbreak")));
14970   set_cmd_completer (c, location_completer);
14971
14972   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
14973 Set a hardware assisted breakpoint.\n\
14974 Like \"break\" except the breakpoint requires hardware support,\n\
14975 some target hardware may not have this support.\n\
14976 \n"
14977 BREAK_ARGS_HELP ("hbreak")));
14978   set_cmd_completer (c, location_completer);
14979
14980   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
14981 Set a temporary hardware assisted breakpoint.\n\
14982 Like \"hbreak\" except the breakpoint is only temporary,\n\
14983 so it will be deleted when hit.\n\
14984 \n"
14985 BREAK_ARGS_HELP ("thbreak")));
14986   set_cmd_completer (c, location_completer);
14987
14988   cmd_list_element *enable_cmd
14989     = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
14990 Enable all or some breakpoints.\n\
14991 Usage: enable [BREAKPOINTNUM]...\n\
14992 Give breakpoint numbers (separated by spaces) as arguments.\n\
14993 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14994 This is used to cancel the effect of the \"disable\" command.\n\
14995 With a subcommand you can enable temporarily."),
14996                       &enablelist, 1, &cmdlist);
14997
14998   add_com_alias ("en", enable_cmd, class_breakpoint, 1);
14999
15000   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15001 Enable all or some breakpoints.\n\
15002 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
15003 Give breakpoint numbers (separated by spaces) as arguments.\n\
15004 This is used to cancel the effect of the \"disable\" command.\n\
15005 May be abbreviated to simply \"enable\"."),
15006                    &enablebreaklist, 1, &enablelist);
15007
15008   add_cmd ("once", no_class, enable_once_command, _("\
15009 Enable some breakpoints for one hit.\n\
15010 Usage: enable breakpoints once BREAKPOINTNUM...\n\
15011 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15012            &enablebreaklist);
15013
15014   add_cmd ("delete", no_class, enable_delete_command, _("\
15015 Enable some breakpoints and delete when hit.\n\
15016 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
15017 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15018            &enablebreaklist);
15019
15020   add_cmd ("count", no_class, enable_count_command, _("\
15021 Enable some breakpoints for COUNT hits.\n\
15022 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
15023 If a breakpoint is hit while enabled in this fashion,\n\
15024 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15025            &enablebreaklist);
15026
15027   add_cmd ("delete", no_class, enable_delete_command, _("\
15028 Enable some breakpoints and delete when hit.\n\
15029 Usage: enable delete BREAKPOINTNUM...\n\
15030 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15031            &enablelist);
15032
15033   add_cmd ("once", no_class, enable_once_command, _("\
15034 Enable some breakpoints for one hit.\n\
15035 Usage: enable once BREAKPOINTNUM...\n\
15036 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15037            &enablelist);
15038
15039   add_cmd ("count", no_class, enable_count_command, _("\
15040 Enable some breakpoints for COUNT hits.\n\
15041 Usage: enable count COUNT BREAKPOINTNUM...\n\
15042 If a breakpoint is hit while enabled in this fashion,\n\
15043 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15044            &enablelist);
15045
15046   cmd_list_element *disable_cmd
15047     = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15048 Disable all or some breakpoints.\n\
15049 Usage: disable [BREAKPOINTNUM]...\n\
15050 Arguments are breakpoint numbers with spaces in between.\n\
15051 To disable all breakpoints, give no argument.\n\
15052 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15053                       &disablelist, 1, &cmdlist);
15054   add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
15055   add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
15056
15057   add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
15058 Disable all or some breakpoints.\n\
15059 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
15060 Arguments are breakpoint numbers with spaces in between.\n\
15061 To disable all breakpoints, give no argument.\n\
15062 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15063 This command may be abbreviated \"disable\"."),
15064            &disablelist);
15065
15066   cmd_list_element *delete_cmd
15067     = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15068 Delete all or some breakpoints.\n\
15069 Usage: delete [BREAKPOINTNUM]...\n\
15070 Arguments are breakpoint numbers with spaces in between.\n\
15071 To delete all breakpoints, give no argument.\n\
15072 \n\
15073 Also a prefix command for deletion of other GDB objects."),
15074                       &deletelist, 1, &cmdlist);
15075   add_com_alias ("d", delete_cmd, class_breakpoint, 1);
15076   add_com_alias ("del", delete_cmd, class_breakpoint, 1);
15077
15078   add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
15079 Delete all or some breakpoints or auto-display expressions.\n\
15080 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
15081 Arguments are breakpoint numbers with spaces in between.\n\
15082 To delete all breakpoints, give no argument.\n\
15083 This command may be abbreviated \"delete\"."),
15084            &deletelist);
15085
15086   cmd_list_element *clear_cmd
15087    = add_com ("clear", class_breakpoint, clear_command, _("\
15088 Clear breakpoint at specified location.\n\
15089 Argument may be a linespec, explicit, or address location as described below.\n\
15090 \n\
15091 With no argument, clears all breakpoints in the line that the selected frame\n\
15092 is executing in.\n"
15093 "\n" LOCATION_HELP_STRING "\n\n\
15094 See also the \"delete\" command which clears breakpoints by number."));
15095   add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
15096
15097   cmd_list_element *break_cmd
15098     = add_com ("break", class_breakpoint, break_command, _("\
15099 Set breakpoint at specified location.\n"
15100 BREAK_ARGS_HELP ("break")));
15101   set_cmd_completer (break_cmd, location_completer);
15102
15103   add_com_alias ("b", break_cmd, class_run, 1);
15104   add_com_alias ("br", break_cmd, class_run, 1);
15105   add_com_alias ("bre", break_cmd, class_run, 1);
15106   add_com_alias ("brea", break_cmd, class_run, 1);
15107
15108   if (dbx_commands)
15109     {
15110       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15111 Break in function/address or break at a line in the current file."),
15112                              &stoplist, 1, &cmdlist);
15113       add_cmd ("in", class_breakpoint, stopin_command,
15114                _("Break in function or address."), &stoplist);
15115       add_cmd ("at", class_breakpoint, stopat_command,
15116                _("Break at a line in the current file."), &stoplist);
15117       add_com ("status", class_info, info_breakpoints_command, _("\
15118 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15119 The \"Type\" column indicates one of:\n\
15120 \tbreakpoint     - normal breakpoint\n\
15121 \twatchpoint     - watchpoint\n\
15122 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15123 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15124 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15125 address and file/line number respectively.\n\
15126 \n\
15127 Convenience variable \"$_\" and default examine address for \"x\"\n\
15128 are set to the address of the last breakpoint listed unless the command\n\
15129 is prefixed with \"server \".\n\n\
15130 Convenience variable \"$bpnum\" contains the number of the last\n\
15131 breakpoint set."));
15132     }
15133
15134   cmd_list_element *info_breakpoints_cmd
15135     = add_info ("breakpoints", info_breakpoints_command, _("\
15136 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15137 The \"Type\" column indicates one of:\n\
15138 \tbreakpoint     - normal breakpoint\n\
15139 \twatchpoint     - watchpoint\n\
15140 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15141 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15142 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15143 address and file/line number respectively.\n\
15144 \n\
15145 Convenience variable \"$_\" and default examine address for \"x\"\n\
15146 are set to the address of the last breakpoint listed unless the command\n\
15147 is prefixed with \"server \".\n\n\
15148 Convenience variable \"$bpnum\" contains the number of the last\n\
15149 breakpoint set."));
15150
15151   add_info_alias ("b", info_breakpoints_cmd, 1);
15152
15153   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15154 Status of all breakpoints, or breakpoint number NUMBER.\n\
15155 The \"Type\" column indicates one of:\n\
15156 \tbreakpoint     - normal breakpoint\n\
15157 \twatchpoint     - watchpoint\n\
15158 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15159 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15160 \tuntil          - internal breakpoint used by the \"until\" command\n\
15161 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15162 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15163 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15164 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15165 address and file/line number respectively.\n\
15166 \n\
15167 Convenience variable \"$_\" and default examine address for \"x\"\n\
15168 are set to the address of the last breakpoint listed unless the command\n\
15169 is prefixed with \"server \".\n\n\
15170 Convenience variable \"$bpnum\" contains the number of the last\n\
15171 breakpoint set."),
15172            &maintenanceinfolist);
15173
15174   add_basic_prefix_cmd ("catch", class_breakpoint, _("\
15175 Set catchpoints to catch events."),
15176                         &catch_cmdlist,
15177                         0/*allow-unknown*/, &cmdlist);
15178
15179   add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
15180 Set temporary catchpoints to catch events."),
15181                         &tcatch_cmdlist,
15182                         0/*allow-unknown*/, &cmdlist);
15183
15184   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15185 Usage: catch load [REGEX]\n\
15186 If REGEX is given, only stop for libraries matching the regular expression."),
15187                      catch_load_command_1,
15188                      NULL,
15189                      CATCH_PERMANENT,
15190                      CATCH_TEMPORARY);
15191   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15192 Usage: catch unload [REGEX]\n\
15193 If REGEX is given, only stop for libraries matching the regular expression."),
15194                      catch_unload_command_1,
15195                      NULL,
15196                      CATCH_PERMANENT,
15197                      CATCH_TEMPORARY);
15198
15199   const auto opts = make_watch_options_def_group (nullptr);
15200
15201   static const std::string watch_help = gdb::option::build_help (_("\
15202 Set a watchpoint for EXPRESSION.\n\
15203 Usage: watch [-location] EXPRESSION\n\
15204 \n\
15205 Options:\n\
15206 %OPTIONS%\n\
15207 \n\
15208 A watchpoint stops execution of your program whenever the value of\n\
15209 an expression changes."), opts);
15210   c = add_com ("watch", class_breakpoint, watch_command,
15211                watch_help.c_str ());
15212   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15213
15214   static const std::string rwatch_help = gdb::option::build_help (_("\
15215 Set a read watchpoint for EXPRESSION.\n\
15216 Usage: rwatch [-location] EXPRESSION\n\
15217 \n\
15218 Options:\n\
15219 %OPTIONS%\n\
15220 \n\
15221 A read watchpoint stops execution of your program whenever the value of\n\
15222 an expression is read."), opts);
15223   c = add_com ("rwatch", class_breakpoint, rwatch_command,
15224                rwatch_help.c_str ());
15225   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15226
15227   static const std::string awatch_help = gdb::option::build_help (_("\
15228 Set an access watchpoint for EXPRESSION.\n\
15229 Usage: awatch [-location] EXPRESSION\n\
15230 \n\
15231 Options:\n\
15232 %OPTIONS%\n\
15233 \n\
15234 An access watchpoint stops execution of your program whenever the value\n\
15235 of an expression is either read or written."), opts);
15236   c = add_com ("awatch", class_breakpoint, awatch_command,
15237                awatch_help.c_str ());
15238   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15239
15240   add_info ("watchpoints", info_watchpoints_command, _("\
15241 Status of specified watchpoints (all watchpoints if no argument)."));
15242
15243   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15244      respond to changes - contrary to the description.  */
15245   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15246                             &can_use_hw_watchpoints, _("\
15247 Set debugger's willingness to use watchpoint hardware."), _("\
15248 Show debugger's willingness to use watchpoint hardware."), _("\
15249 If zero, gdb will not use hardware for new watchpoints, even if\n\
15250 such is available.  (However, any hardware watchpoints that were\n\
15251 created before setting this to nonzero, will continue to use watchpoint\n\
15252 hardware.)"),
15253                             NULL,
15254                             show_can_use_hw_watchpoints,
15255                             &setlist, &showlist);
15256
15257   can_use_hw_watchpoints = 1;
15258
15259   /* Tracepoint manipulation commands.  */
15260
15261   cmd_list_element *trace_cmd
15262     = add_com ("trace", class_breakpoint, trace_command, _("\
15263 Set a tracepoint at specified location.\n\
15264 \n"
15265 BREAK_ARGS_HELP ("trace") "\n\
15266 Do \"help tracepoints\" for info on other tracepoint commands."));
15267   set_cmd_completer (trace_cmd, location_completer);
15268
15269   add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
15270   add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
15271   add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
15272   add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
15273
15274   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15275 Set a fast tracepoint at specified location.\n\
15276 \n"
15277 BREAK_ARGS_HELP ("ftrace") "\n\
15278 Do \"help tracepoints\" for info on other tracepoint commands."));
15279   set_cmd_completer (c, location_completer);
15280
15281   c = add_com ("strace", class_breakpoint, strace_command, _("\
15282 Set a static tracepoint at location or marker.\n\
15283 \n\
15284 strace [LOCATION] [if CONDITION]\n\
15285 LOCATION may be a linespec, explicit, or address location (described below) \n\
15286 or -m MARKER_ID.\n\n\
15287 If a marker id is specified, probe the marker with that name.  With\n\
15288 no LOCATION, uses current execution address of the selected stack frame.\n\
15289 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15290 This collects arbitrary user data passed in the probe point call to the\n\
15291 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15292 by printing the $_sdata variable like any other convenience variable.\n\
15293 \n\
15294 CONDITION is a boolean expression.\n\
15295 \n" LOCATION_HELP_STRING "\n\n\
15296 Multiple tracepoints at one place are permitted, and useful if their\n\
15297 conditions are different.\n\
15298 \n\
15299 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15300 Do \"help tracepoints\" for info on other tracepoint commands."));
15301   set_cmd_completer (c, location_completer);
15302
15303   cmd_list_element *info_tracepoints_cmd
15304     = add_info ("tracepoints", info_tracepoints_command, _("\
15305 Status of specified tracepoints (all tracepoints if no argument).\n\
15306 Convenience variable \"$tpnum\" contains the number of the\n\
15307 last tracepoint set."));
15308
15309   add_info_alias ("tp", info_tracepoints_cmd, 1);
15310
15311   cmd_list_element *delete_tracepoints_cmd
15312     = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15313 Delete specified tracepoints.\n\
15314 Arguments are tracepoint numbers, separated by spaces.\n\
15315 No argument means delete all tracepoints."),
15316            &deletelist);
15317   add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
15318
15319   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15320 Disable specified tracepoints.\n\
15321 Arguments are tracepoint numbers, separated by spaces.\n\
15322 No argument means disable all tracepoints."),
15323            &disablelist);
15324   deprecate_cmd (c, "disable");
15325
15326   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15327 Enable specified tracepoints.\n\
15328 Arguments are tracepoint numbers, separated by spaces.\n\
15329 No argument means enable all tracepoints."),
15330            &enablelist);
15331   deprecate_cmd (c, "enable");
15332
15333   add_com ("passcount", class_trace, trace_pass_command, _("\
15334 Set the passcount for a tracepoint.\n\
15335 The trace will end when the tracepoint has been passed 'count' times.\n\
15336 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15337 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15338
15339   add_basic_prefix_cmd ("save", class_breakpoint,
15340                         _("Save breakpoint definitions as a script."),
15341                         &save_cmdlist,
15342                         0/*allow-unknown*/, &cmdlist);
15343
15344   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15345 Save current breakpoint definitions as a script.\n\
15346 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15347 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15348 session to restore them."),
15349                &save_cmdlist);
15350   set_cmd_completer (c, filename_completer);
15351
15352   cmd_list_element *save_tracepoints_cmd
15353     = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15354 Save current tracepoint definitions as a script.\n\
15355 Use the 'source' command in another debug session to restore them."),
15356                &save_cmdlist);
15357   set_cmd_completer (save_tracepoints_cmd, filename_completer);
15358
15359   c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
15360   deprecate_cmd (c, "save tracepoints");
15361
15362   add_setshow_prefix_cmd ("breakpoint", class_maintenance,
15363                           _("\
15364 Breakpoint specific settings.\n\
15365 Configure various breakpoint-specific variables such as\n\
15366 pending breakpoint behavior."),
15367                           _("\
15368 Breakpoint specific settings.\n\
15369 Configure various breakpoint-specific variables such as\n\
15370 pending breakpoint behavior."),
15371                           &breakpoint_set_cmdlist, &breakpoint_show_cmdlist,
15372                           &setlist, &showlist);
15373
15374   add_setshow_auto_boolean_cmd ("pending", no_class,
15375                                 &pending_break_support, _("\
15376 Set debugger's behavior regarding pending breakpoints."), _("\
15377 Show debugger's behavior regarding pending breakpoints."), _("\
15378 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15379 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15380 an error.  If auto, an unrecognized breakpoint location results in a\n\
15381 user-query to see if a pending breakpoint should be created."),
15382                                 NULL,
15383                                 show_pending_break_support,
15384                                 &breakpoint_set_cmdlist,
15385                                 &breakpoint_show_cmdlist);
15386
15387   pending_break_support = AUTO_BOOLEAN_AUTO;
15388
15389   add_setshow_boolean_cmd ("auto-hw", no_class,
15390                            &automatic_hardware_breakpoints, _("\
15391 Set automatic usage of hardware breakpoints."), _("\
15392 Show automatic usage of hardware breakpoints."), _("\
15393 If set, the debugger will automatically use hardware breakpoints for\n\
15394 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15395 a warning will be emitted for such breakpoints."),
15396                            NULL,
15397                            show_automatic_hardware_breakpoints,
15398                            &breakpoint_set_cmdlist,
15399                            &breakpoint_show_cmdlist);
15400
15401   add_setshow_boolean_cmd ("always-inserted", class_support,
15402                            &always_inserted_mode, _("\
15403 Set mode for inserting breakpoints."), _("\
15404 Show mode for inserting breakpoints."), _("\
15405 When this mode is on, breakpoints are inserted immediately as soon as\n\
15406 they're created, kept inserted even when execution stops, and removed\n\
15407 only when the user deletes them.  When this mode is off (the default),\n\
15408 breakpoints are inserted only when execution continues, and removed\n\
15409 when execution stops."),
15410                                 NULL,
15411                                 &show_always_inserted_mode,
15412                                 &breakpoint_set_cmdlist,
15413                                 &breakpoint_show_cmdlist);
15414
15415   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15416                         condition_evaluation_enums,
15417                         &condition_evaluation_mode_1, _("\
15418 Set mode of breakpoint condition evaluation."), _("\
15419 Show mode of breakpoint condition evaluation."), _("\
15420 When this is set to \"host\", breakpoint conditions will be\n\
15421 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15422 breakpoint conditions will be downloaded to the target (if the target\n\
15423 supports such feature) and conditions will be evaluated on the target's side.\n\
15424 If this is set to \"auto\" (default), this will be automatically set to\n\
15425 \"target\" if it supports condition evaluation, otherwise it will\n\
15426 be set to \"host\"."),
15427                            &set_condition_evaluation_mode,
15428                            &show_condition_evaluation_mode,
15429                            &breakpoint_set_cmdlist,
15430                            &breakpoint_show_cmdlist);
15431
15432   add_com ("break-range", class_breakpoint, break_range_command, _("\
15433 Set a breakpoint for an address range.\n\
15434 break-range START-LOCATION, END-LOCATION\n\
15435 where START-LOCATION and END-LOCATION can be one of the following:\n\
15436   LINENUM, for that line in the current file,\n\
15437   FILE:LINENUM, for that line in that file,\n\
15438   +OFFSET, for that number of lines after the current line\n\
15439            or the start of the range\n\
15440   FUNCTION, for the first line in that function,\n\
15441   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15442   *ADDRESS, for the instruction at that address.\n\
15443 \n\
15444 The breakpoint will stop execution of the inferior whenever it executes\n\
15445 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15446 range (including START-LOCATION and END-LOCATION)."));
15447
15448   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
15449 Set a dynamic printf at specified location.\n\
15450 dprintf location,format string,arg1,arg2,...\n\
15451 location may be a linespec, explicit, or address location.\n"
15452 "\n" LOCATION_HELP_STRING));
15453   set_cmd_completer (c, location_completer);
15454
15455   add_setshow_enum_cmd ("dprintf-style", class_support,
15456                         dprintf_style_enums, &dprintf_style, _("\
15457 Set the style of usage for dynamic printf."), _("\
15458 Show the style of usage for dynamic printf."), _("\
15459 This setting chooses how GDB will do a dynamic printf.\n\
15460 If the value is \"gdb\", then the printing is done by GDB to its own\n\
15461 console, as with the \"printf\" command.\n\
15462 If the value is \"call\", the print is done by calling a function in your\n\
15463 program; by default printf(), but you can choose a different function or\n\
15464 output stream by setting dprintf-function and dprintf-channel."),
15465                         update_dprintf_commands, NULL,
15466                         &setlist, &showlist);
15467
15468   add_setshow_string_cmd ("dprintf-function", class_support,
15469                           &dprintf_function, _("\
15470 Set the function to use for dynamic printf."), _("\
15471 Show the function to use for dynamic printf."), NULL,
15472                           update_dprintf_commands, NULL,
15473                           &setlist, &showlist);
15474
15475   add_setshow_string_cmd ("dprintf-channel", class_support,
15476                           &dprintf_channel, _("\
15477 Set the channel to use for dynamic printf."), _("\
15478 Show the channel to use for dynamic printf."), NULL,
15479                           update_dprintf_commands, NULL,
15480                           &setlist, &showlist);
15481
15482   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
15483                            &disconnected_dprintf, _("\
15484 Set whether dprintf continues after GDB disconnects."), _("\
15485 Show whether dprintf continues after GDB disconnects."), _("\
15486 Use this to let dprintf commands continue to hit and produce output\n\
15487 even if GDB disconnects or detaches from the target."),
15488                            NULL,
15489                            NULL,
15490                            &setlist, &showlist);
15491
15492   add_com ("agent-printf", class_vars, agent_printf_command, _("\
15493 Target agent only formatted printing, like the C \"printf\" function.\n\
15494 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
15495 This supports most C printf format specifications, like %s, %d, etc.\n\
15496 This is useful for formatted output in user-defined commands."));
15497
15498   automatic_hardware_breakpoints = true;
15499
15500   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
15501                                            "breakpoint");
15502   gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
15503                                       "breakpoint");
15504 }
This page took 0.910468 seconds and 4 git commands to generate.