]> Git Repo - binutils.git/blob - gdb/breakpoint.c
sim: unify bug & package settings
[binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2021 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observable.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "stack.h"
63 #include "ax-gdb.h"
64 #include "dummy-frame.h"
65 #include "interps.h"
66 #include "gdbsupport/format.h"
67 #include "thread-fsm.h"
68 #include "tid-parse.h"
69 #include "cli/cli-style.h"
70
71 /* readline include files */
72 #include "readline/tilde.h"
73
74 /* readline defines this.  */
75 #undef savestring
76
77 #include "mi/mi-common.h"
78 #include "extension.h"
79 #include <algorithm>
80 #include "progspace-and-thread.h"
81 #include "gdbsupport/array-view.h"
82 #include "gdbsupport/gdb_optional.h"
83
84 /* Prototypes for local functions.  */
85
86 static void map_breakpoint_numbers (const char *,
87                                     gdb::function_view<void (breakpoint *)>);
88
89 static void breakpoint_re_set_default (struct breakpoint *);
90
91 static void
92   create_sals_from_location_default (struct event_location *location,
93                                      struct linespec_result *canonical,
94                                      enum bptype type_wanted);
95
96 static void create_breakpoints_sal_default (struct gdbarch *,
97                                             struct linespec_result *,
98                                             gdb::unique_xmalloc_ptr<char>,
99                                             gdb::unique_xmalloc_ptr<char>,
100                                             enum bptype,
101                                             enum bpdisp, int, int,
102                                             int,
103                                             const struct breakpoint_ops *,
104                                             int, int, int, unsigned);
105
106 static std::vector<symtab_and_line> decode_location_default
107   (struct breakpoint *b, struct event_location *location,
108    struct program_space *search_pspace);
109
110 static int can_use_hardware_watchpoint
111     (const std::vector<value_ref_ptr> &vals);
112
113 static void mention (struct breakpoint *);
114
115 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
116                                                                enum bptype,
117                                                                const struct breakpoint_ops *);
118 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
119                                                        const struct symtab_and_line *);
120
121 /* This function is used in gdbtk sources and thus can not be made
122    static.  */
123 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
124                                        struct symtab_and_line,
125                                        enum bptype,
126                                        const struct breakpoint_ops *);
127
128 static struct breakpoint *
129   momentary_breakpoint_from_master (struct breakpoint *orig,
130                                     enum bptype type,
131                                     const struct breakpoint_ops *ops,
132                                     int loc_enabled);
133
134 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
135
136 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
137                                             CORE_ADDR bpaddr,
138                                             enum bptype bptype);
139
140 static void describe_other_breakpoints (struct gdbarch *,
141                                         struct program_space *, CORE_ADDR,
142                                         struct obj_section *, int);
143
144 static int watchpoint_locations_match (struct bp_location *loc1,
145                                        struct bp_location *loc2);
146
147 static int breakpoint_locations_match (struct bp_location *loc1,
148                                        struct bp_location *loc2,
149                                        bool sw_hw_bps_match = false);
150
151 static int breakpoint_location_address_match (struct bp_location *bl,
152                                               const struct address_space *aspace,
153                                               CORE_ADDR addr);
154
155 static int breakpoint_location_address_range_overlap (struct bp_location *,
156                                                       const address_space *,
157                                                       CORE_ADDR, int);
158
159 static int remove_breakpoint (struct bp_location *);
160 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
161
162 static enum print_stop_action print_bp_stop_message (bpstat bs);
163
164 static int hw_breakpoint_used_count (void);
165
166 static int hw_watchpoint_use_count (struct breakpoint *);
167
168 static int hw_watchpoint_used_count_others (struct breakpoint *except,
169                                             enum bptype type,
170                                             int *other_type_used);
171
172 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
173                                     int count);
174
175 static void decref_bp_location (struct bp_location **loc);
176
177 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
178
179 /* update_global_location_list's modes of operation wrt to whether to
180    insert locations now.  */
181 enum ugll_insert_mode
182 {
183   /* Don't insert any breakpoint locations into the inferior, only
184      remove already-inserted locations that no longer should be
185      inserted.  Functions that delete a breakpoint or breakpoints
186      should specify this mode, so that deleting a breakpoint doesn't
187      have the side effect of inserting the locations of other
188      breakpoints that are marked not-inserted, but should_be_inserted
189      returns true on them.
190
191      This behavior is useful is situations close to tear-down -- e.g.,
192      after an exec, while the target still has execution, but
193      breakpoint shadows of the previous executable image should *NOT*
194      be restored to the new image; or before detaching, where the
195      target still has execution and wants to delete breakpoints from
196      GDB's lists, and all breakpoints had already been removed from
197      the inferior.  */
198   UGLL_DONT_INSERT,
199
200   /* May insert breakpoints iff breakpoints_should_be_inserted_now
201      claims breakpoints should be inserted now.  */
202   UGLL_MAY_INSERT,
203
204   /* Insert locations now, irrespective of
205      breakpoints_should_be_inserted_now.  E.g., say all threads are
206      stopped right now, and the user did "continue".  We need to
207      insert breakpoints _before_ resuming the target, but
208      UGLL_MAY_INSERT wouldn't insert them, because
209      breakpoints_should_be_inserted_now returns false at that point,
210      as no thread is running yet.  */
211   UGLL_INSERT
212 };
213
214 static void update_global_location_list (enum ugll_insert_mode);
215
216 static void update_global_location_list_nothrow (enum ugll_insert_mode);
217
218 static void insert_breakpoint_locations (void);
219
220 static void trace_pass_command (const char *, int);
221
222 static void set_tracepoint_count (int num);
223
224 static bool is_masked_watchpoint (const struct breakpoint *b);
225
226 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
227    otherwise.  */
228
229 static int strace_marker_p (struct breakpoint *b);
230
231 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
232    that are implemented on top of software or hardware breakpoints
233    (user breakpoints, internal and momentary breakpoints, etc.).  */
234 static struct breakpoint_ops bkpt_base_breakpoint_ops;
235
236 /* Internal breakpoints class type.  */
237 static struct breakpoint_ops internal_breakpoint_ops;
238
239 /* Momentary breakpoints class type.  */
240 static struct breakpoint_ops momentary_breakpoint_ops;
241
242 /* The breakpoint_ops structure to be used in regular user created
243    breakpoints.  */
244 struct breakpoint_ops bkpt_breakpoint_ops;
245
246 /* Breakpoints set on probes.  */
247 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
248
249 /* Tracepoints set on probes.  */
250 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
251
252 /* Dynamic printf class type.  */
253 struct breakpoint_ops dprintf_breakpoint_ops;
254
255 /* The style in which to perform a dynamic printf.  This is a user
256    option because different output options have different tradeoffs;
257    if GDB does the printing, there is better error handling if there
258    is a problem with any of the arguments, but using an inferior
259    function lets you have special-purpose printers and sending of
260    output to the same place as compiled-in print functions.  */
261
262 static const char dprintf_style_gdb[] = "gdb";
263 static const char dprintf_style_call[] = "call";
264 static const char dprintf_style_agent[] = "agent";
265 static const char *const dprintf_style_enums[] = {
266   dprintf_style_gdb,
267   dprintf_style_call,
268   dprintf_style_agent,
269   NULL
270 };
271 static const char *dprintf_style = dprintf_style_gdb;
272
273 /* The function to use for dynamic printf if the preferred style is to
274    call into the inferior.  The value is simply a string that is
275    copied into the command, so it can be anything that GDB can
276    evaluate to a callable address, not necessarily a function name.  */
277
278 static char *dprintf_function;
279
280 /* The channel to use for dynamic printf if the preferred style is to
281    call into the inferior; if a nonempty string, it will be passed to
282    the call as the first argument, with the format string as the
283    second.  As with the dprintf function, this can be anything that
284    GDB knows how to evaluate, so in addition to common choices like
285    "stderr", this could be an app-specific expression like
286    "mystreams[curlogger]".  */
287
288 static char *dprintf_channel;
289
290 /* True if dprintf commands should continue to operate even if GDB
291    has disconnected.  */
292 static bool disconnected_dprintf = true;
293
294 struct command_line *
295 breakpoint_commands (struct breakpoint *b)
296 {
297   return b->commands ? b->commands.get () : NULL;
298 }
299
300 /* Flag indicating that a command has proceeded the inferior past the
301    current breakpoint.  */
302
303 static bool breakpoint_proceeded;
304
305 const char *
306 bpdisp_text (enum bpdisp disp)
307 {
308   /* NOTE: the following values are a part of MI protocol and
309      represent values of 'disp' field returned when inferior stops at
310      a breakpoint.  */
311   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
312
313   return bpdisps[(int) disp];
314 }
315
316 /* Prototypes for exported functions.  */
317 /* If FALSE, gdb will not use hardware support for watchpoints, even
318    if such is available.  */
319 static int can_use_hw_watchpoints;
320
321 static void
322 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
323                              struct cmd_list_element *c,
324                              const char *value)
325 {
326   fprintf_filtered (file,
327                     _("Debugger's willingness to use "
328                       "watchpoint hardware is %s.\n"),
329                     value);
330 }
331
332 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
333    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
334    for unrecognized breakpoint locations.
335    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
336 static enum auto_boolean pending_break_support;
337 static void
338 show_pending_break_support (struct ui_file *file, int from_tty,
339                             struct cmd_list_element *c,
340                             const char *value)
341 {
342   fprintf_filtered (file,
343                     _("Debugger's behavior regarding "
344                       "pending breakpoints is %s.\n"),
345                     value);
346 }
347
348 /* If true, gdb will automatically use hardware breakpoints for breakpoints
349    set with "break" but falling in read-only memory.
350    If false, gdb will warn about such breakpoints, but won't automatically
351    use hardware breakpoints.  */
352 static bool automatic_hardware_breakpoints;
353 static void
354 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
355                                      struct cmd_list_element *c,
356                                      const char *value)
357 {
358   fprintf_filtered (file,
359                     _("Automatic usage of hardware breakpoints is %s.\n"),
360                     value);
361 }
362
363 /* If on, GDB keeps breakpoints inserted even if the inferior is
364    stopped, and immediately inserts any new breakpoints as soon as
365    they're created.  If off (default), GDB keeps breakpoints off of
366    the target as long as possible.  That is, it delays inserting
367    breakpoints until the next resume, and removes them again when the
368    target fully stops.  This is a bit safer in case GDB crashes while
369    processing user input.  */
370 static bool always_inserted_mode = false;
371
372 static void
373 show_always_inserted_mode (struct ui_file *file, int from_tty,
374                      struct cmd_list_element *c, const char *value)
375 {
376   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
377                     value);
378 }
379
380 /* See breakpoint.h.  */
381
382 int
383 breakpoints_should_be_inserted_now (void)
384 {
385   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
386     {
387       /* If breakpoints are global, they should be inserted even if no
388          thread under gdb's control is running, or even if there are
389          no threads under GDB's control yet.  */
390       return 1;
391     }
392   else
393     {
394       if (always_inserted_mode)
395         {
396           /* The user wants breakpoints inserted even if all threads
397              are stopped.  */
398           return 1;
399         }
400
401       for (inferior *inf : all_inferiors ())
402         if (inf->has_execution ()
403             && threads_are_executing (inf->process_target ()))
404           return 1;
405
406       /* Don't remove breakpoints yet if, even though all threads are
407          stopped, we still have events to process.  */
408       for (thread_info *tp : all_non_exited_threads ())
409         if (tp->resumed
410             && tp->suspend.waitstatus_pending_p)
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 /* See declaration at breakpoint.h.  */
631
632 struct breakpoint *
633 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
634                     void *user_data)
635 {
636   for (breakpoint *b : all_breakpoints ())
637     if (func (b, user_data) != 0)
638       return b;
639
640   return nullptr;
641 }
642
643 /* Return whether a breakpoint is an active enabled breakpoint.  */
644 static int
645 breakpoint_enabled (struct breakpoint *b)
646 {
647   return (b->enable_state == bp_enabled);
648 }
649
650 /* Set breakpoint count to NUM.  */
651
652 static void
653 set_breakpoint_count (int num)
654 {
655   prev_breakpoint_count = breakpoint_count;
656   breakpoint_count = num;
657   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
658 }
659
660 /* Used by `start_rbreak_breakpoints' below, to record the current
661    breakpoint count before "rbreak" creates any breakpoint.  */
662 static int rbreak_start_breakpoint_count;
663
664 /* Called at the start an "rbreak" command to record the first
665    breakpoint made.  */
666
667 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
668 {
669   rbreak_start_breakpoint_count = breakpoint_count;
670 }
671
672 /* Called at the end of an "rbreak" command to record the last
673    breakpoint made.  */
674
675 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
676 {
677   prev_breakpoint_count = rbreak_start_breakpoint_count;
678 }
679
680 /* Used in run_command to zero the hit count when a new run starts.  */
681
682 void
683 clear_breakpoint_hit_counts (void)
684 {
685   for (breakpoint *b : all_breakpoints ())
686     b->hit_count = 0;
687 }
688
689 \f
690 /* Return the breakpoint with the specified number, or NULL
691    if the number does not refer to an existing breakpoint.  */
692
693 struct breakpoint *
694 get_breakpoint (int num)
695 {
696   for (breakpoint *b : all_breakpoints ())
697     if (b->number == num)
698       return b;
699   
700   return nullptr;
701 }
702
703 \f
704
705 /* Mark locations as "conditions have changed" in case the target supports
706    evaluating conditions on its side.  */
707
708 static void
709 mark_breakpoint_modified (struct breakpoint *b)
710 {
711   /* This is only meaningful if the target is
712      evaluating conditions and if the user has
713      opted for condition evaluation on the target's
714      side.  */
715   if (gdb_evaluates_breakpoint_condition_p ()
716       || !target_supports_evaluation_of_breakpoint_conditions ())
717     return;
718
719   if (!is_breakpoint (b))
720     return;
721
722   for (bp_location *loc : b->locations ())
723     loc->condition_changed = condition_modified;
724 }
725
726 /* Mark location as "conditions have changed" in case the target supports
727    evaluating conditions on its side.  */
728
729 static void
730 mark_breakpoint_location_modified (struct bp_location *loc)
731 {
732   /* This is only meaningful if the target is
733      evaluating conditions and if the user has
734      opted for condition evaluation on the target's
735      side.  */
736   if (gdb_evaluates_breakpoint_condition_p ()
737       || !target_supports_evaluation_of_breakpoint_conditions ())
738
739     return;
740
741   if (!is_breakpoint (loc->owner))
742     return;
743
744   loc->condition_changed = condition_modified;
745 }
746
747 /* Sets the condition-evaluation mode using the static global
748    condition_evaluation_mode.  */
749
750 static void
751 set_condition_evaluation_mode (const char *args, int from_tty,
752                                struct cmd_list_element *c)
753 {
754   const char *old_mode, *new_mode;
755
756   if ((condition_evaluation_mode_1 == condition_evaluation_target)
757       && !target_supports_evaluation_of_breakpoint_conditions ())
758     {
759       condition_evaluation_mode_1 = condition_evaluation_mode;
760       warning (_("Target does not support breakpoint condition evaluation.\n"
761                  "Using host evaluation mode instead."));
762       return;
763     }
764
765   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
766   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
767
768   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
769      settings was "auto".  */
770   condition_evaluation_mode = condition_evaluation_mode_1;
771
772   /* Only update the mode if the user picked a different one.  */
773   if (new_mode != old_mode)
774     {
775       /* If the user switched to a different evaluation mode, we
776          need to synch the changes with the target as follows:
777
778          "host" -> "target": Send all (valid) conditions to the target.
779          "target" -> "host": Remove all the conditions from the target.
780       */
781
782       if (new_mode == condition_evaluation_target)
783         {
784           /* Mark everything modified and synch conditions with the
785              target.  */
786           for (bp_location *loc : all_bp_locations ())
787             mark_breakpoint_location_modified (loc);
788         }
789       else
790         {
791           /* Manually mark non-duplicate locations to synch conditions
792              with the target.  We do this to remove all the conditions the
793              target knows about.  */
794           for (bp_location *loc : all_bp_locations ())
795             if (is_breakpoint (loc->owner) && loc->inserted)
796               loc->needs_update = 1;
797         }
798
799       /* Do the update.  */
800       update_global_location_list (UGLL_MAY_INSERT);
801     }
802
803   return;
804 }
805
806 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
807    what "auto" is translating to.  */
808
809 static void
810 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
811                                 struct cmd_list_element *c, const char *value)
812 {
813   if (condition_evaluation_mode == condition_evaluation_auto)
814     fprintf_filtered (file,
815                       _("Breakpoint condition evaluation "
816                         "mode is %s (currently %s).\n"),
817                       value,
818                       breakpoint_condition_evaluation_mode ());
819   else
820     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
821                       value);
822 }
823
824 /* Parse COND_STRING in the context of LOC and set as the condition
825    expression of LOC.  BP_NUM is the number of LOC's owner, LOC_NUM is
826    the number of LOC within its owner.  In case of parsing error, mark
827    LOC as DISABLED_BY_COND.  In case of success, unset DISABLED_BY_COND.  */
828
829 static void
830 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
831                                    int bp_num, int loc_num)
832 {
833   bool has_junk = false;
834   try
835     {
836       expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
837                                            block_for_pc (loc->address), 0);
838       if (*cond_string != 0)
839         has_junk = true;
840       else
841         {
842           loc->cond = std::move (new_exp);
843           if (loc->disabled_by_cond && loc->enabled)
844             printf_filtered (_("Breakpoint %d's condition is now valid at "
845                                "location %d, enabling.\n"),
846                              bp_num, loc_num);
847
848           loc->disabled_by_cond = false;
849         }
850     }
851   catch (const gdb_exception_error &e)
852     {
853       if (loc->enabled)
854         {
855           /* Warn if a user-enabled location is now becoming disabled-by-cond.
856              BP_NUM is 0 if the breakpoint is being defined for the first
857              time using the "break ... if ..." command, and non-zero if
858              already defined.  */
859           if (bp_num != 0)
860             warning (_("failed to validate condition at location %d.%d, "
861                        "disabling:\n  %s"), bp_num, loc_num, e.what ());
862           else
863             warning (_("failed to validate condition at location %d, "
864                        "disabling:\n  %s"), loc_num, e.what ());
865         }
866
867       loc->disabled_by_cond = true;
868     }
869
870   if (has_junk)
871     error (_("Garbage '%s' follows condition"), cond_string);
872 }
873
874 void
875 set_breakpoint_condition (struct breakpoint *b, const char *exp,
876                           int from_tty, bool force)
877 {
878   if (*exp == 0)
879     {
880       xfree (b->cond_string);
881       b->cond_string = nullptr;
882
883       if (is_watchpoint (b))
884         static_cast<watchpoint *> (b)->cond_exp.reset ();
885       else
886         {
887           int loc_num = 1;
888           for (bp_location *loc : b->locations ())
889             {
890               loc->cond.reset ();
891               if (loc->disabled_by_cond && loc->enabled)
892                 printf_filtered (_("Breakpoint %d's condition is now valid at "
893                                    "location %d, enabling.\n"),
894                                  b->number, loc_num);
895               loc->disabled_by_cond = false;
896               loc_num++;
897
898               /* No need to free the condition agent expression
899                  bytecode (if we have one).  We will handle this
900                  when we go through update_global_location_list.  */
901             }
902         }
903
904       if (from_tty)
905         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
906     }
907   else
908     {
909       if (is_watchpoint (b))
910         {
911           innermost_block_tracker tracker;
912           const char *arg = exp;
913           expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
914           if (*arg != 0)
915             error (_("Junk at end of expression"));
916           watchpoint *w = static_cast<watchpoint *> (b);
917           w->cond_exp = std::move (new_exp);
918           w->cond_exp_valid_block = tracker.block ();
919         }
920       else
921         {
922           /* Parse and set condition expressions.  We make two passes.
923              In the first, we parse the condition string to see if it
924              is valid in at least one location.  If so, the condition
925              would be accepted.  So we go ahead and set the locations'
926              conditions.  In case no valid case is found, we throw
927              the error and the condition string will be rejected.
928              This two-pass approach is taken to avoid setting the
929              state of locations in case of a reject.  */
930           for (bp_location *loc : b->locations ())
931             {
932               try
933                 {
934                   const char *arg = exp;
935                   parse_exp_1 (&arg, loc->address,
936                                block_for_pc (loc->address), 0);
937                   if (*arg != 0)
938                     error (_("Junk at end of expression"));
939                   break;
940                 }
941               catch (const gdb_exception_error &e)
942                 {
943                   /* Condition string is invalid.  If this happens to
944                      be the last loc, abandon (if not forced) or continue
945                      (if forced).  */
946                   if (loc->next == nullptr && !force)
947                     throw;
948                 }
949             }
950
951           /* If we reach here, the condition is valid at some locations.  */
952           int loc_num = 1;
953           for (bp_location *loc : b->locations ())
954             {
955               set_breakpoint_location_condition (exp, loc, b->number, loc_num);
956               loc_num++;
957             }
958         }
959
960       /* We know that the new condition parsed successfully.  The
961          condition string of the breakpoint can be safely updated.  */
962       xfree (b->cond_string);
963       b->cond_string = xstrdup (exp);
964       b->condition_not_parsed = 0;
965     }
966   mark_breakpoint_modified (b);
967
968   gdb::observers::breakpoint_modified.notify (b);
969 }
970
971 /* See breakpoint.h.  */
972
973 void
974 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
975                           bool force)
976 {
977   for (breakpoint *b : all_breakpoints ())
978     if (b->number == bpnum)
979       {
980         /* Check if this breakpoint has a "stop" method implemented in an
981            extension language.  This method and conditions entered into GDB
982            from the CLI are mutually exclusive.  */
983         const struct extension_language_defn *extlang
984           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
985
986         if (extlang != NULL)
987           {
988             error (_("Only one stop condition allowed.  There is currently"
989                      " a %s stop condition defined for this breakpoint."),
990                    ext_lang_capitalized_name (extlang));
991           }
992         set_breakpoint_condition (b, exp, from_tty, force);
993
994         if (is_breakpoint (b))
995           update_global_location_list (UGLL_MAY_INSERT);
996
997         return;
998       }
999
1000   error (_("No breakpoint number %d."), bpnum);
1001 }
1002
1003 /* The options for the "condition" command.  */
1004
1005 struct condition_command_opts
1006 {
1007   /* For "-force".  */
1008   bool force_condition = false;
1009 };
1010
1011 static const gdb::option::option_def condition_command_option_defs[] = {
1012
1013   gdb::option::flag_option_def<condition_command_opts> {
1014     "force",
1015     [] (condition_command_opts *opts) { return &opts->force_condition; },
1016     N_("Set the condition even if it is invalid for all current locations."),
1017   },
1018
1019 };
1020
1021 /* Create an option_def_group for the "condition" options, with
1022    CC_OPTS as context.  */
1023
1024 static inline gdb::option::option_def_group
1025 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1026 {
1027   return {{condition_command_option_defs}, cc_opts};
1028 }
1029
1030 /* Completion for the "condition" command.  */
1031
1032 static void
1033 condition_completer (struct cmd_list_element *cmd,
1034                      completion_tracker &tracker,
1035                      const char *text, const char * /*word*/)
1036 {
1037   bool has_no_arguments = (*text == '\0');
1038   condition_command_opts cc_opts;
1039   const auto group = make_condition_command_options_def_group (&cc_opts);
1040   if (gdb::option::complete_options
1041       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1042     return;
1043
1044   text = skip_spaces (text);
1045   const char *space = skip_to_space (text);
1046   if (*space == '\0')
1047     {
1048       int len;
1049
1050       if (text[0] == '$')
1051         {
1052           tracker.advance_custom_word_point_by (1);
1053           /* We don't support completion of history indices.  */
1054           if (!isdigit (text[1]))
1055             complete_internalvar (tracker, &text[1]);
1056           return;
1057         }
1058
1059       /* Suggest the "-force" flag if no arguments are given.  If
1060          arguments were passed, they either already include the flag,
1061          or we are beyond the point of suggesting it because it's
1062          positionally the first argument.  */
1063       if (has_no_arguments)
1064         gdb::option::complete_on_all_options (tracker, group);
1065
1066       /* We're completing the breakpoint number.  */
1067       len = strlen (text);
1068
1069       for (breakpoint *b : all_breakpoints ())
1070         {
1071           char number[50];
1072
1073           xsnprintf (number, sizeof (number), "%d", b->number);
1074
1075           if (strncmp (number, text, len) == 0)
1076             tracker.add_completion (make_unique_xstrdup (number));
1077         }
1078
1079       return;
1080     }
1081
1082   /* We're completing the expression part.  Skip the breakpoint num.  */
1083   const char *exp_start = skip_spaces (space);
1084   tracker.advance_custom_word_point_by (exp_start - text);
1085   text = exp_start;
1086   const char *word = advance_to_expression_complete_word_point (tracker, text);
1087   expression_completer (cmd, tracker, text, word);
1088 }
1089
1090 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1091
1092 static void
1093 condition_command (const char *arg, int from_tty)
1094 {
1095   const char *p;
1096   int bnum;
1097
1098   if (arg == 0)
1099     error_no_arg (_("breakpoint number"));
1100
1101   p = arg;
1102
1103   /* Check if the "-force" flag was passed.  */
1104   condition_command_opts cc_opts;
1105   const auto group = make_condition_command_options_def_group (&cc_opts);
1106   gdb::option::process_options
1107     (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1108
1109   bnum = get_number (&p);
1110   if (bnum == 0)
1111     error (_("Bad breakpoint argument: '%s'"), arg);
1112
1113   set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1114 }
1115
1116 /* Check that COMMAND do not contain commands that are suitable
1117    only for tracepoints and not suitable for ordinary breakpoints.
1118    Throw if any such commands is found.  */
1119
1120 static void
1121 check_no_tracepoint_commands (struct command_line *commands)
1122 {
1123   struct command_line *c;
1124
1125   for (c = commands; c; c = c->next)
1126     {
1127       if (c->control_type == while_stepping_control)
1128         error (_("The 'while-stepping' command can "
1129                  "only be used for tracepoints"));
1130
1131       check_no_tracepoint_commands (c->body_list_0.get ());
1132       check_no_tracepoint_commands (c->body_list_1.get ());
1133
1134       /* Not that command parsing removes leading whitespace and comment
1135          lines and also empty lines.  So, we only need to check for
1136          command directly.  */
1137       if (strstr (c->line, "collect ") == c->line)
1138         error (_("The 'collect' command can only be used for tracepoints"));
1139
1140       if (strstr (c->line, "teval ") == c->line)
1141         error (_("The 'teval' command can only be used for tracepoints"));
1142     }
1143 }
1144
1145 struct longjmp_breakpoint : public breakpoint
1146 {
1147   ~longjmp_breakpoint () override;
1148 };
1149
1150 /* Encapsulate tests for different types of tracepoints.  */
1151
1152 static bool
1153 is_tracepoint_type (bptype type)
1154 {
1155   return (type == bp_tracepoint
1156           || type == bp_fast_tracepoint
1157           || type == bp_static_tracepoint);
1158 }
1159
1160 static bool
1161 is_longjmp_type (bptype type)
1162 {
1163   return type == bp_longjmp || type == bp_exception;
1164 }
1165
1166 /* See breakpoint.h.  */
1167
1168 bool
1169 is_tracepoint (const struct breakpoint *b)
1170 {
1171   return is_tracepoint_type (b->type);
1172 }
1173
1174 /* Factory function to create an appropriate instance of breakpoint given
1175    TYPE.  */
1176
1177 static std::unique_ptr<breakpoint>
1178 new_breakpoint_from_type (bptype type)
1179 {
1180   breakpoint *b;
1181
1182   if (is_tracepoint_type (type))
1183     b = new tracepoint ();
1184   else if (is_longjmp_type (type))
1185     b = new longjmp_breakpoint ();
1186   else
1187     b = new breakpoint ();
1188
1189   return std::unique_ptr<breakpoint> (b);
1190 }
1191
1192 /* A helper function that validates that COMMANDS are valid for a
1193    breakpoint.  This function will throw an exception if a problem is
1194    found.  */
1195
1196 static void
1197 validate_commands_for_breakpoint (struct breakpoint *b,
1198                                   struct command_line *commands)
1199 {
1200   if (is_tracepoint (b))
1201     {
1202       struct tracepoint *t = (struct tracepoint *) b;
1203       struct command_line *c;
1204       struct command_line *while_stepping = 0;
1205
1206       /* Reset the while-stepping step count.  The previous commands
1207          might have included a while-stepping action, while the new
1208          ones might not.  */
1209       t->step_count = 0;
1210
1211       /* We need to verify that each top-level element of commands is
1212          valid for tracepoints, that there's at most one
1213          while-stepping element, and that the while-stepping's body
1214          has valid tracing commands excluding nested while-stepping.
1215          We also need to validate the tracepoint action line in the
1216          context of the tracepoint --- validate_actionline actually
1217          has side effects, like setting the tracepoint's
1218          while-stepping STEP_COUNT, in addition to checking if the
1219          collect/teval actions parse and make sense in the
1220          tracepoint's context.  */
1221       for (c = commands; c; c = c->next)
1222         {
1223           if (c->control_type == while_stepping_control)
1224             {
1225               if (b->type == bp_fast_tracepoint)
1226                 error (_("The 'while-stepping' command "
1227                          "cannot be used for fast tracepoint"));
1228               else if (b->type == bp_static_tracepoint)
1229                 error (_("The 'while-stepping' command "
1230                          "cannot be used for static tracepoint"));
1231
1232               if (while_stepping)
1233                 error (_("The 'while-stepping' command "
1234                          "can be used only once"));
1235               else
1236                 while_stepping = c;
1237             }
1238
1239           validate_actionline (c->line, b);
1240         }
1241       if (while_stepping)
1242         {
1243           struct command_line *c2;
1244
1245           gdb_assert (while_stepping->body_list_1 == nullptr);
1246           c2 = while_stepping->body_list_0.get ();
1247           for (; c2; c2 = c2->next)
1248             {
1249               if (c2->control_type == while_stepping_control)
1250                 error (_("The 'while-stepping' command cannot be nested"));
1251             }
1252         }
1253     }
1254   else
1255     {
1256       check_no_tracepoint_commands (commands);
1257     }
1258 }
1259
1260 /* Return a vector of all the static tracepoints set at ADDR.  The
1261    caller is responsible for releasing the vector.  */
1262
1263 std::vector<breakpoint *>
1264 static_tracepoints_here (CORE_ADDR addr)
1265 {
1266   std::vector<breakpoint *> found;
1267
1268   for (breakpoint *b : all_breakpoints ())
1269     if (b->type == bp_static_tracepoint)
1270       {
1271         for (bp_location *loc : b->locations ())
1272           if (loc->address == addr)
1273             found.push_back (b);
1274       }
1275
1276   return found;
1277 }
1278
1279 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1280    validate that only allowed commands are included.  */
1281
1282 void
1283 breakpoint_set_commands (struct breakpoint *b, 
1284                          counted_command_line &&commands)
1285 {
1286   validate_commands_for_breakpoint (b, commands.get ());
1287
1288   b->commands = std::move (commands);
1289   gdb::observers::breakpoint_modified.notify (b);
1290 }
1291
1292 /* Set the internal `silent' flag on the breakpoint.  Note that this
1293    is not the same as the "silent" that may appear in the breakpoint's
1294    commands.  */
1295
1296 void
1297 breakpoint_set_silent (struct breakpoint *b, int silent)
1298 {
1299   int old_silent = b->silent;
1300
1301   b->silent = silent;
1302   if (old_silent != silent)
1303     gdb::observers::breakpoint_modified.notify (b);
1304 }
1305
1306 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1307    breakpoint work for any thread.  */
1308
1309 void
1310 breakpoint_set_thread (struct breakpoint *b, int thread)
1311 {
1312   int old_thread = b->thread;
1313
1314   b->thread = thread;
1315   if (old_thread != thread)
1316     gdb::observers::breakpoint_modified.notify (b);
1317 }
1318
1319 /* Set the task for this breakpoint.  If TASK is 0, make the
1320    breakpoint work for any task.  */
1321
1322 void
1323 breakpoint_set_task (struct breakpoint *b, int task)
1324 {
1325   int old_task = b->task;
1326
1327   b->task = task;
1328   if (old_task != task)
1329     gdb::observers::breakpoint_modified.notify (b);
1330 }
1331
1332 static void
1333 commands_command_1 (const char *arg, int from_tty,
1334                     struct command_line *control)
1335 {
1336   counted_command_line cmd;
1337   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1338      NULL after the call to read_command_lines if the user provides an empty
1339      list of command by just typing "end".  */
1340   bool cmd_read = false;
1341
1342   std::string new_arg;
1343
1344   if (arg == NULL || !*arg)
1345     {
1346       /* Argument not explicitly given.  Synthesize it.  */
1347       if (breakpoint_count - prev_breakpoint_count > 1)
1348         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1349                                  breakpoint_count);
1350       else if (breakpoint_count > 0)
1351         new_arg = string_printf ("%d", breakpoint_count);
1352     }
1353   else
1354     {
1355       /* Create a copy of ARG.  This is needed because the "commands"
1356          command may be coming from a script.  In that case, the read
1357          line buffer is going to be overwritten in the lambda of
1358          'map_breakpoint_numbers' below when reading the next line
1359          before we are are done parsing the breakpoint numbers.  */
1360       new_arg = arg;
1361     }
1362   arg = new_arg.c_str ();
1363
1364   map_breakpoint_numbers
1365     (arg, [&] (breakpoint *b)
1366      {
1367        if (!cmd_read)
1368          {
1369            gdb_assert (cmd == NULL);
1370            if (control != NULL)
1371              cmd = control->body_list_0;
1372            else
1373              {
1374                std::string str
1375                  = string_printf (_("Type commands for breakpoint(s) "
1376                                     "%s, one per line."),
1377                                   arg);
1378
1379                auto do_validate = [=] (const char *line)
1380                                   {
1381                                     validate_actionline (line, b);
1382                                   };
1383                gdb::function_view<void (const char *)> validator;
1384                if (is_tracepoint (b))
1385                  validator = do_validate;
1386
1387                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1388              }
1389            cmd_read = true;
1390          }
1391
1392        /* If a breakpoint was on the list more than once, we don't need to
1393           do anything.  */
1394        if (b->commands != cmd)
1395          {
1396            validate_commands_for_breakpoint (b, cmd.get ());
1397            b->commands = cmd;
1398            gdb::observers::breakpoint_modified.notify (b);
1399          }
1400      });
1401 }
1402
1403 static void
1404 commands_command (const char *arg, int from_tty)
1405 {
1406   commands_command_1 (arg, from_tty, NULL);
1407 }
1408
1409 /* Like commands_command, but instead of reading the commands from
1410    input stream, takes them from an already parsed command structure.
1411
1412    This is used by cli-script.c to DTRT with breakpoint commands
1413    that are part of if and while bodies.  */
1414 enum command_control_type
1415 commands_from_control_command (const char *arg, struct command_line *cmd)
1416 {
1417   commands_command_1 (arg, 0, cmd);
1418   return simple_control;
1419 }
1420
1421 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1422
1423 static int
1424 bp_location_has_shadow (struct bp_location *bl)
1425 {
1426   if (bl->loc_type != bp_loc_software_breakpoint)
1427     return 0;
1428   if (!bl->inserted)
1429     return 0;
1430   if (bl->target_info.shadow_len == 0)
1431     /* BL isn't valid, or doesn't shadow memory.  */
1432     return 0;
1433   return 1;
1434 }
1435
1436 /* Update BUF, which is LEN bytes read from the target address
1437    MEMADDR, by replacing a memory breakpoint with its shadowed
1438    contents.
1439
1440    If READBUF is not NULL, this buffer must not overlap with the of
1441    the breakpoint location's shadow_contents buffer.  Otherwise, a
1442    failed assertion internal error will be raised.  */
1443
1444 static void
1445 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1446                             const gdb_byte *writebuf_org,
1447                             ULONGEST memaddr, LONGEST len,
1448                             struct bp_target_info *target_info,
1449                             struct gdbarch *gdbarch)
1450 {
1451   /* Now do full processing of the found relevant range of elements.  */
1452   CORE_ADDR bp_addr = 0;
1453   int bp_size = 0;
1454   int bptoffset = 0;
1455
1456   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1457                                  current_program_space->aspace, 0))
1458     {
1459       /* The breakpoint is inserted in a different address space.  */
1460       return;
1461     }
1462
1463   /* Addresses and length of the part of the breakpoint that
1464      we need to copy.  */
1465   bp_addr = target_info->placed_address;
1466   bp_size = target_info->shadow_len;
1467
1468   if (bp_addr + bp_size <= memaddr)
1469     {
1470       /* The breakpoint is entirely before the chunk of memory we are
1471          reading.  */
1472       return;
1473     }
1474
1475   if (bp_addr >= memaddr + len)
1476     {
1477       /* The breakpoint is entirely after the chunk of memory we are
1478          reading.  */
1479       return;
1480     }
1481
1482   /* Offset within shadow_contents.  */
1483   if (bp_addr < memaddr)
1484     {
1485       /* Only copy the second part of the breakpoint.  */
1486       bp_size -= memaddr - bp_addr;
1487       bptoffset = memaddr - bp_addr;
1488       bp_addr = memaddr;
1489     }
1490
1491   if (bp_addr + bp_size > memaddr + len)
1492     {
1493       /* Only copy the first part of the breakpoint.  */
1494       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1495     }
1496
1497   if (readbuf != NULL)
1498     {
1499       /* Verify that the readbuf buffer does not overlap with the
1500          shadow_contents buffer.  */
1501       gdb_assert (target_info->shadow_contents >= readbuf + len
1502                   || readbuf >= (target_info->shadow_contents
1503                                  + target_info->shadow_len));
1504
1505       /* Update the read buffer with this inserted breakpoint's
1506          shadow.  */
1507       memcpy (readbuf + bp_addr - memaddr,
1508               target_info->shadow_contents + bptoffset, bp_size);
1509     }
1510   else
1511     {
1512       const unsigned char *bp;
1513       CORE_ADDR addr = target_info->reqstd_address;
1514       int placed_size;
1515
1516       /* Update the shadow with what we want to write to memory.  */
1517       memcpy (target_info->shadow_contents + bptoffset,
1518               writebuf_org + bp_addr - memaddr, bp_size);
1519
1520       /* Determine appropriate breakpoint contents and size for this
1521          address.  */
1522       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1523
1524       /* Update the final write buffer with this inserted
1525          breakpoint's INSN.  */
1526       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1527     }
1528 }
1529
1530 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1531    by replacing any memory breakpoints with their shadowed contents.
1532
1533    If READBUF is not NULL, this buffer must not overlap with any of
1534    the breakpoint location's shadow_contents buffers.  Otherwise,
1535    a failed assertion internal error will be raised.
1536
1537    The range of shadowed area by each bp_location is:
1538      bl->address - bp_locations_placed_address_before_address_max
1539      up to bl->address + bp_locations_shadow_len_after_address_max
1540    The range we were requested to resolve shadows for is:
1541      memaddr ... memaddr + len
1542    Thus the safe cutoff boundaries for performance optimization are
1543      memaddr + len <= (bl->address
1544                        - bp_locations_placed_address_before_address_max)
1545    and:
1546      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1547
1548 void
1549 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1550                         const gdb_byte *writebuf_org,
1551                         ULONGEST memaddr, LONGEST len)
1552 {
1553   /* Left boundary, right boundary and median element of our binary
1554      search.  */
1555   unsigned bc_l, bc_r, bc;
1556
1557   /* Find BC_L which is a leftmost element which may affect BUF
1558      content.  It is safe to report lower value but a failure to
1559      report higher one.  */
1560
1561   bc_l = 0;
1562   bc_r = bp_locations.size ();
1563   while (bc_l + 1 < bc_r)
1564     {
1565       struct bp_location *bl;
1566
1567       bc = (bc_l + bc_r) / 2;
1568       bl = bp_locations[bc];
1569
1570       /* Check first BL->ADDRESS will not overflow due to the added
1571          constant.  Then advance the left boundary only if we are sure
1572          the BC element can in no way affect the BUF content (MEMADDR
1573          to MEMADDR + LEN range).
1574
1575          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1576          offset so that we cannot miss a breakpoint with its shadow
1577          range tail still reaching MEMADDR.  */
1578
1579       if ((bl->address + bp_locations_shadow_len_after_address_max
1580            >= bl->address)
1581           && (bl->address + bp_locations_shadow_len_after_address_max
1582               <= memaddr))
1583         bc_l = bc;
1584       else
1585         bc_r = bc;
1586     }
1587
1588   /* Due to the binary search above, we need to make sure we pick the
1589      first location that's at BC_L's address.  E.g., if there are
1590      multiple locations at the same address, BC_L may end up pointing
1591      at a duplicate location, and miss the "master"/"inserted"
1592      location.  Say, given locations L1, L2 and L3 at addresses A and
1593      B:
1594
1595       L1@A, L2@A, L3@B, ...
1596
1597      BC_L could end up pointing at location L2, while the "master"
1598      location could be L1.  Since the `loc->inserted' flag is only set
1599      on "master" locations, we'd forget to restore the shadow of L1
1600      and L2.  */
1601   while (bc_l > 0
1602          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1603     bc_l--;
1604
1605   /* Now do full processing of the found relevant range of elements.  */
1606
1607   for (bc = bc_l; bc < bp_locations.size (); bc++)
1608     {
1609       struct bp_location *bl = bp_locations[bc];
1610
1611       /* bp_location array has BL->OWNER always non-NULL.  */
1612       if (bl->owner->type == bp_none)
1613         warning (_("reading through apparently deleted breakpoint #%d?"),
1614                  bl->owner->number);
1615
1616       /* Performance optimization: any further element can no longer affect BUF
1617          content.  */
1618
1619       if (bl->address >= bp_locations_placed_address_before_address_max
1620           && (memaddr + len
1621               <= (bl->address
1622                   - bp_locations_placed_address_before_address_max)))
1623         break;
1624
1625       if (!bp_location_has_shadow (bl))
1626         continue;
1627
1628       one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1629                                   memaddr, len, &bl->target_info, bl->gdbarch);
1630     }
1631 }
1632
1633 /* See breakpoint.h.  */
1634
1635 bool
1636 is_breakpoint (const struct breakpoint *bpt)
1637 {
1638   return (bpt->type == bp_breakpoint
1639           || bpt->type == bp_hardware_breakpoint
1640           || bpt->type == bp_dprintf);
1641 }
1642
1643 /* Return true if BPT is of any hardware watchpoint kind.  */
1644
1645 static bool
1646 is_hardware_watchpoint (const struct breakpoint *bpt)
1647 {
1648   return (bpt->type == bp_hardware_watchpoint
1649           || bpt->type == bp_read_watchpoint
1650           || bpt->type == bp_access_watchpoint);
1651 }
1652
1653 /* See breakpoint.h.  */
1654
1655 bool
1656 is_watchpoint (const struct breakpoint *bpt)
1657 {
1658   return (is_hardware_watchpoint (bpt)
1659           || bpt->type == bp_watchpoint);
1660 }
1661
1662 /* Returns true if the current thread and its running state are safe
1663    to evaluate or update watchpoint B.  Watchpoints on local
1664    expressions need to be evaluated in the context of the thread that
1665    was current when the watchpoint was created, and, that thread needs
1666    to be stopped to be able to select the correct frame context.
1667    Watchpoints on global expressions can be evaluated on any thread,
1668    and in any state.  It is presently left to the target allowing
1669    memory accesses when threads are running.  */
1670
1671 static int
1672 watchpoint_in_thread_scope (struct watchpoint *b)
1673 {
1674   return (b->pspace == current_program_space
1675           && (b->watchpoint_thread == null_ptid
1676               || (inferior_ptid == b->watchpoint_thread
1677                   && !inferior_thread ()->executing)));
1678 }
1679
1680 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1681    associated bp_watchpoint_scope breakpoint.  */
1682
1683 static void
1684 watchpoint_del_at_next_stop (struct watchpoint *w)
1685 {
1686   if (w->related_breakpoint != w)
1687     {
1688       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1689       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1690       w->related_breakpoint->disposition = disp_del_at_next_stop;
1691       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1692       w->related_breakpoint = w;
1693     }
1694   w->disposition = disp_del_at_next_stop;
1695 }
1696
1697 /* Extract a bitfield value from value VAL using the bit parameters contained in
1698    watchpoint W.  */
1699
1700 static struct value *
1701 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1702 {
1703   struct value *bit_val;
1704
1705   if (val == NULL)
1706     return NULL;
1707
1708   bit_val = allocate_value (value_type (val));
1709
1710   unpack_value_bitfield (bit_val,
1711                          w->val_bitpos,
1712                          w->val_bitsize,
1713                          value_contents_for_printing (val),
1714                          value_offset (val),
1715                          val);
1716
1717   return bit_val;
1718 }
1719
1720 /* Allocate a dummy location and add it to B, which must be a software
1721    watchpoint.  This is required because even if a software watchpoint
1722    is not watching any memory, bpstat_stop_status requires a location
1723    to be able to report stops.  */
1724
1725 static void
1726 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1727                                             struct program_space *pspace)
1728 {
1729   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1730
1731   b->loc = allocate_bp_location (b);
1732   b->loc->pspace = pspace;
1733   b->loc->address = -1;
1734   b->loc->length = -1;
1735 }
1736
1737 /* Returns true if B is a software watchpoint that is not watching any
1738    memory (e.g., "watch $pc").  */
1739
1740 static bool
1741 is_no_memory_software_watchpoint (struct breakpoint *b)
1742 {
1743   return (b->type == bp_watchpoint
1744           && b->loc != NULL
1745           && b->loc->next == NULL
1746           && b->loc->address == -1
1747           && b->loc->length == -1);
1748 }
1749
1750 /* Assuming that B is a watchpoint:
1751    - Reparse watchpoint expression, if REPARSE is non-zero
1752    - Evaluate expression and store the result in B->val
1753    - Evaluate the condition if there is one, and store the result
1754      in b->loc->cond.
1755    - Update the list of values that must be watched in B->loc.
1756
1757    If the watchpoint disposition is disp_del_at_next_stop, then do
1758    nothing.  If this is local watchpoint that is out of scope, delete
1759    it.
1760
1761    Even with `set breakpoint always-inserted on' the watchpoints are
1762    removed + inserted on each stop here.  Normal breakpoints must
1763    never be removed because they might be missed by a running thread
1764    when debugging in non-stop mode.  On the other hand, hardware
1765    watchpoints (is_hardware_watchpoint; processed here) are specific
1766    to each LWP since they are stored in each LWP's hardware debug
1767    registers.  Therefore, such LWP must be stopped first in order to
1768    be able to modify its hardware watchpoints.
1769
1770    Hardware watchpoints must be reset exactly once after being
1771    presented to the user.  It cannot be done sooner, because it would
1772    reset the data used to present the watchpoint hit to the user.  And
1773    it must not be done later because it could display the same single
1774    watchpoint hit during multiple GDB stops.  Note that the latter is
1775    relevant only to the hardware watchpoint types bp_read_watchpoint
1776    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1777    not user-visible - its hit is suppressed if the memory content has
1778    not changed.
1779
1780    The following constraints influence the location where we can reset
1781    hardware watchpoints:
1782
1783    * target_stopped_by_watchpoint and target_stopped_data_address are
1784      called several times when GDB stops.
1785
1786    [linux] 
1787    * Multiple hardware watchpoints can be hit at the same time,
1788      causing GDB to stop.  GDB only presents one hardware watchpoint
1789      hit at a time as the reason for stopping, and all the other hits
1790      are presented later, one after the other, each time the user
1791      requests the execution to be resumed.  Execution is not resumed
1792      for the threads still having pending hit event stored in
1793      LWP_INFO->STATUS.  While the watchpoint is already removed from
1794      the inferior on the first stop the thread hit event is kept being
1795      reported from its cached value by linux_nat_stopped_data_address
1796      until the real thread resume happens after the watchpoint gets
1797      presented and thus its LWP_INFO->STATUS gets reset.
1798
1799    Therefore the hardware watchpoint hit can get safely reset on the
1800    watchpoint removal from inferior.  */
1801
1802 static void
1803 update_watchpoint (struct watchpoint *b, int reparse)
1804 {
1805   int within_current_scope;
1806   struct frame_id saved_frame_id;
1807   int frame_saved;
1808
1809   /* If this is a local watchpoint, we only want to check if the
1810      watchpoint frame is in scope if the current thread is the thread
1811      that was used to create the watchpoint.  */
1812   if (!watchpoint_in_thread_scope (b))
1813     return;
1814
1815   if (b->disposition == disp_del_at_next_stop)
1816     return;
1817  
1818   frame_saved = 0;
1819
1820   /* Determine if the watchpoint is within scope.  */
1821   if (b->exp_valid_block == NULL)
1822     within_current_scope = 1;
1823   else
1824     {
1825       struct frame_info *fi = get_current_frame ();
1826       struct gdbarch *frame_arch = get_frame_arch (fi);
1827       CORE_ADDR frame_pc = get_frame_pc (fi);
1828
1829       /* If we're at a point where the stack has been destroyed
1830          (e.g. in a function epilogue), unwinding may not work
1831          properly. Do not attempt to recreate locations at this
1832          point.  See similar comments in watchpoint_check.  */
1833       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1834         return;
1835
1836       /* Save the current frame's ID so we can restore it after
1837          evaluating the watchpoint expression on its own frame.  */
1838       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1839          took a frame parameter, so that we didn't have to change the
1840          selected frame.  */
1841       frame_saved = 1;
1842       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1843
1844       fi = frame_find_by_id (b->watchpoint_frame);
1845       within_current_scope = (fi != NULL);
1846       if (within_current_scope)
1847         select_frame (fi);
1848     }
1849
1850   /* We don't free locations.  They are stored in the bp_location array
1851      and update_global_location_list will eventually delete them and
1852      remove breakpoints if needed.  */
1853   b->loc = NULL;
1854
1855   if (within_current_scope && reparse)
1856     {
1857       const char *s;
1858
1859       b->exp.reset ();
1860       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1861       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1862       /* If the meaning of expression itself changed, the old value is
1863          no longer relevant.  We don't want to report a watchpoint hit
1864          to the user when the old value and the new value may actually
1865          be completely different objects.  */
1866       b->val = NULL;
1867       b->val_valid = false;
1868
1869       /* Note that unlike with breakpoints, the watchpoint's condition
1870          expression is stored in the breakpoint object, not in the
1871          locations (re)created below.  */
1872       if (b->cond_string != NULL)
1873         {
1874           b->cond_exp.reset ();
1875
1876           s = b->cond_string;
1877           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1878         }
1879     }
1880
1881   /* If we failed to parse the expression, for example because
1882      it refers to a global variable in a not-yet-loaded shared library,
1883      don't try to insert watchpoint.  We don't automatically delete
1884      such watchpoint, though, since failure to parse expression
1885      is different from out-of-scope watchpoint.  */
1886   if (!target_has_execution ())
1887     {
1888       /* Without execution, memory can't change.  No use to try and
1889          set watchpoint locations.  The watchpoint will be reset when
1890          the target gains execution, through breakpoint_re_set.  */
1891       if (!can_use_hw_watchpoints)
1892         {
1893           if (b->ops->works_in_software_mode (b))
1894             b->type = bp_watchpoint;
1895           else
1896             error (_("Can't set read/access watchpoint when "
1897                      "hardware watchpoints are disabled."));
1898         }
1899     }
1900   else if (within_current_scope && b->exp)
1901     {
1902       std::vector<value_ref_ptr> val_chain;
1903       struct value *v, *result;
1904       struct program_space *frame_pspace;
1905
1906       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
1907                           &val_chain, false);
1908
1909       /* Avoid setting b->val if it's already set.  The meaning of
1910          b->val is 'the last value' user saw, and we should update
1911          it only if we reported that last value to user.  As it
1912          happens, the code that reports it updates b->val directly.
1913          We don't keep track of the memory value for masked
1914          watchpoints.  */
1915       if (!b->val_valid && !is_masked_watchpoint (b))
1916         {
1917           if (b->val_bitsize != 0)
1918             v = extract_bitfield_from_watchpoint_value (b, v);
1919           b->val = release_value (v);
1920           b->val_valid = true;
1921         }
1922
1923       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1924
1925       /* Look at each value on the value chain.  */
1926       gdb_assert (!val_chain.empty ());
1927       for (const value_ref_ptr &iter : val_chain)
1928         {
1929           v = iter.get ();
1930
1931           /* If it's a memory location, and GDB actually needed
1932              its contents to evaluate the expression, then we
1933              must watch it.  If the first value returned is
1934              still lazy, that means an error occurred reading it;
1935              watch it anyway in case it becomes readable.  */
1936           if (VALUE_LVAL (v) == lval_memory
1937               && (v == val_chain[0] || ! value_lazy (v)))
1938             {
1939               struct type *vtype = check_typedef (value_type (v));
1940
1941               /* We only watch structs and arrays if user asked
1942                  for it explicitly, never if they just happen to
1943                  appear in the middle of some value chain.  */
1944               if (v == result
1945                   || (vtype->code () != TYPE_CODE_STRUCT
1946                       && vtype->code () != TYPE_CODE_ARRAY))
1947                 {
1948                   CORE_ADDR addr;
1949                   enum target_hw_bp_type type;
1950                   struct bp_location *loc, **tmp;
1951                   int bitpos = 0, bitsize = 0;
1952
1953                   if (value_bitsize (v) != 0)
1954                     {
1955                       /* Extract the bit parameters out from the bitfield
1956                          sub-expression.  */
1957                       bitpos = value_bitpos (v);
1958                       bitsize = value_bitsize (v);
1959                     }
1960                   else if (v == result && b->val_bitsize != 0)
1961                     {
1962                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1963                         lvalue whose bit parameters are saved in the fields
1964                         VAL_BITPOS and VAL_BITSIZE.  */
1965                       bitpos = b->val_bitpos;
1966                       bitsize = b->val_bitsize;
1967                     }
1968
1969                   addr = value_address (v);
1970                   if (bitsize != 0)
1971                     {
1972                       /* Skip the bytes that don't contain the bitfield.  */
1973                       addr += bitpos / 8;
1974                     }
1975
1976                   type = hw_write;
1977                   if (b->type == bp_read_watchpoint)
1978                     type = hw_read;
1979                   else if (b->type == bp_access_watchpoint)
1980                     type = hw_access;
1981
1982                   loc = allocate_bp_location (b);
1983                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1984                     ;
1985                   *tmp = loc;
1986                   loc->gdbarch = value_type (v)->arch ();
1987
1988                   loc->pspace = frame_pspace;
1989                   loc->address = address_significant (loc->gdbarch, addr);
1990
1991                   if (bitsize != 0)
1992                     {
1993                       /* Just cover the bytes that make up the bitfield.  */
1994                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1995                     }
1996                   else
1997                     loc->length = TYPE_LENGTH (value_type (v));
1998
1999                   loc->watchpoint_type = type;
2000                 }
2001             }
2002         }
2003
2004       /* Change the type of breakpoint between hardware assisted or
2005          an ordinary watchpoint depending on the hardware support
2006          and free hardware slots.  REPARSE is set when the inferior
2007          is started.  */
2008       if (reparse)
2009         {
2010           int reg_cnt;
2011           enum bp_loc_type loc_type;
2012
2013           reg_cnt = can_use_hardware_watchpoint (val_chain);
2014
2015           if (reg_cnt)
2016             {
2017               int i, target_resources_ok, other_type_used;
2018               enum bptype type;
2019
2020               /* Use an exact watchpoint when there's only one memory region to be
2021                  watched, and only one debug register is needed to watch it.  */
2022               b->exact = target_exact_watchpoints && reg_cnt == 1;
2023
2024               /* We need to determine how many resources are already
2025                  used for all other hardware watchpoints plus this one
2026                  to see if we still have enough resources to also fit
2027                  this watchpoint in as well.  */
2028
2029               /* If this is a software watchpoint, we try to turn it
2030                  to a hardware one -- count resources as if B was of
2031                  hardware watchpoint type.  */
2032               type = b->type;
2033               if (type == bp_watchpoint)
2034                 type = bp_hardware_watchpoint;
2035
2036               /* This watchpoint may or may not have been placed on
2037                  the list yet at this point (it won't be in the list
2038                  if we're trying to create it for the first time,
2039                  through watch_command), so always account for it
2040                  manually.  */
2041
2042               /* Count resources used by all watchpoints except B.  */
2043               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2044
2045               /* Add in the resources needed for B.  */
2046               i += hw_watchpoint_use_count (b);
2047
2048               target_resources_ok
2049                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2050               if (target_resources_ok <= 0)
2051                 {
2052                   int sw_mode = b->ops->works_in_software_mode (b);
2053
2054                   if (target_resources_ok == 0 && !sw_mode)
2055                     error (_("Target does not support this type of "
2056                              "hardware watchpoint."));
2057                   else if (target_resources_ok < 0 && !sw_mode)
2058                     error (_("There are not enough available hardware "
2059                              "resources for this watchpoint."));
2060
2061                   /* Downgrade to software watchpoint.  */
2062                   b->type = bp_watchpoint;
2063                 }
2064               else
2065                 {
2066                   /* If this was a software watchpoint, we've just
2067                      found we have enough resources to turn it to a
2068                      hardware watchpoint.  Otherwise, this is a
2069                      nop.  */
2070                   b->type = type;
2071                 }
2072             }
2073           else if (!b->ops->works_in_software_mode (b))
2074             {
2075               if (!can_use_hw_watchpoints)
2076                 error (_("Can't set read/access watchpoint when "
2077                          "hardware watchpoints are disabled."));
2078               else
2079                 error (_("Expression cannot be implemented with "
2080                          "read/access watchpoint."));
2081             }
2082           else
2083             b->type = bp_watchpoint;
2084
2085           loc_type = (b->type == bp_watchpoint? bp_loc_other
2086                       : bp_loc_hardware_watchpoint);
2087           for (bp_location *bl : b->locations ())
2088             bl->loc_type = loc_type;
2089         }
2090
2091       /* If a software watchpoint is not watching any memory, then the
2092          above left it without any location set up.  But,
2093          bpstat_stop_status requires a location to be able to report
2094          stops, so make sure there's at least a dummy one.  */
2095       if (b->type == bp_watchpoint && b->loc == NULL)
2096         software_watchpoint_add_no_memory_location (b, frame_pspace);
2097     }
2098   else if (!within_current_scope)
2099     {
2100       printf_filtered (_("\
2101 Watchpoint %d deleted because the program has left the block\n\
2102 in which its expression is valid.\n"),
2103                        b->number);
2104       watchpoint_del_at_next_stop (b);
2105     }
2106
2107   /* Restore the selected frame.  */
2108   if (frame_saved)
2109     select_frame (frame_find_by_id (saved_frame_id));
2110 }
2111
2112
2113 /* Returns 1 iff breakpoint location should be
2114    inserted in the inferior.  We don't differentiate the type of BL's owner
2115    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2116    breakpoint_ops is not defined, because in insert_bp_location,
2117    tracepoint's insert_location will not be called.  */
2118 static int
2119 should_be_inserted (struct bp_location *bl)
2120 {
2121   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2122     return 0;
2123
2124   if (bl->owner->disposition == disp_del_at_next_stop)
2125     return 0;
2126
2127   if (!bl->enabled || bl->disabled_by_cond
2128       || bl->shlib_disabled || bl->duplicate)
2129     return 0;
2130
2131   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2132     return 0;
2133
2134   /* This is set for example, when we're attached to the parent of a
2135      vfork, and have detached from the child.  The child is running
2136      free, and we expect it to do an exec or exit, at which point the
2137      OS makes the parent schedulable again (and the target reports
2138      that the vfork is done).  Until the child is done with the shared
2139      memory region, do not insert breakpoints in the parent, otherwise
2140      the child could still trip on the parent's breakpoints.  Since
2141      the parent is blocked anyway, it won't miss any breakpoint.  */
2142   if (bl->pspace->breakpoints_not_allowed)
2143     return 0;
2144
2145   /* Don't insert a breakpoint if we're trying to step past its
2146      location, except if the breakpoint is a single-step breakpoint,
2147      and the breakpoint's thread is the thread which is stepping past
2148      a breakpoint.  */
2149   if ((bl->loc_type == bp_loc_software_breakpoint
2150        || bl->loc_type == bp_loc_hardware_breakpoint)
2151       && stepping_past_instruction_at (bl->pspace->aspace,
2152                                        bl->address)
2153       /* The single-step breakpoint may be inserted at the location
2154          we're trying to step if the instruction branches to itself.
2155          However, the instruction won't be executed at all and it may
2156          break the semantics of the instruction, for example, the
2157          instruction is a conditional branch or updates some flags.
2158          We can't fix it unless GDB is able to emulate the instruction
2159          or switch to displaced stepping.  */
2160       && !(bl->owner->type == bp_single_step
2161            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2162     {
2163       infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2164                            paddress (bl->gdbarch, bl->address));
2165       return 0;
2166     }
2167
2168   /* Don't insert watchpoints if we're trying to step past the
2169      instruction that triggered one.  */
2170   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2171       && stepping_past_nonsteppable_watchpoint ())
2172     {
2173       infrun_debug_printf ("stepping past non-steppable watchpoint. "
2174                            "skipping watchpoint at %s:%d",
2175                            paddress (bl->gdbarch, bl->address), bl->length);
2176       return 0;
2177     }
2178
2179   return 1;
2180 }
2181
2182 /* Same as should_be_inserted but does the check assuming
2183    that the location is not duplicated.  */
2184
2185 static int
2186 unduplicated_should_be_inserted (struct bp_location *bl)
2187 {
2188   int result;
2189   const int save_duplicate = bl->duplicate;
2190
2191   bl->duplicate = 0;
2192   result = should_be_inserted (bl);
2193   bl->duplicate = save_duplicate;
2194   return result;
2195 }
2196
2197 /* Parses a conditional described by an expression COND into an
2198    agent expression bytecode suitable for evaluation
2199    by the bytecode interpreter.  Return NULL if there was
2200    any error during parsing.  */
2201
2202 static agent_expr_up
2203 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2204 {
2205   if (cond == NULL)
2206     return NULL;
2207
2208   agent_expr_up aexpr;
2209
2210   /* We don't want to stop processing, so catch any errors
2211      that may show up.  */
2212   try
2213     {
2214       aexpr = gen_eval_for_expr (scope, cond);
2215     }
2216
2217   catch (const gdb_exception_error &ex)
2218     {
2219       /* If we got here, it means the condition could not be parsed to a valid
2220          bytecode expression and thus can't be evaluated on the target's side.
2221          It's no use iterating through the conditions.  */
2222     }
2223
2224   /* We have a valid agent expression.  */
2225   return aexpr;
2226 }
2227
2228 /* Based on location BL, create a list of breakpoint conditions to be
2229    passed on to the target.  If we have duplicated locations with different
2230    conditions, we will add such conditions to the list.  The idea is that the
2231    target will evaluate the list of conditions and will only notify GDB when
2232    one of them is true.  */
2233
2234 static void
2235 build_target_condition_list (struct bp_location *bl)
2236 {
2237   int null_condition_or_parse_error = 0;
2238   int modified = bl->needs_update;
2239
2240   /* Release conditions left over from a previous insert.  */
2241   bl->target_info.conditions.clear ();
2242
2243   /* This is only meaningful if the target is
2244      evaluating conditions and if the user has
2245      opted for condition evaluation on the target's
2246      side.  */
2247   if (gdb_evaluates_breakpoint_condition_p ()
2248       || !target_supports_evaluation_of_breakpoint_conditions ())
2249     return;
2250
2251   auto loc_range = all_bp_locations_at_addr (bl->address);
2252
2253   /* Do a first pass to check for locations with no assigned
2254      conditions or conditions that fail to parse to a valid agent
2255      expression bytecode.  If any of these happen, then it's no use to
2256      send conditions to the target since this location will always
2257      trigger and generate a response back to GDB.  Note we consider
2258      all locations at the same address irrespective of type, i.e.,
2259      even if the locations aren't considered duplicates (e.g.,
2260      software breakpoint and hardware breakpoint at the same
2261      address).  */
2262   for (bp_location *loc : loc_range)
2263     {
2264       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2265         {
2266           if (modified)
2267             {
2268               /* Re-parse the conditions since something changed.  In that
2269                  case we already freed the condition bytecodes (see
2270                  force_breakpoint_reinsertion).  We just
2271                  need to parse the condition to bytecodes again.  */
2272               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2273                                                         loc->cond.get ());
2274             }
2275
2276           /* If we have a NULL bytecode expression, it means something
2277              went wrong or we have a null condition expression.  */
2278           if (!loc->cond_bytecode)
2279             {
2280               null_condition_or_parse_error = 1;
2281               break;
2282             }
2283         }
2284     }
2285
2286   /* If any of these happened, it means we will have to evaluate the conditions
2287      for the location's address on gdb's side.  It is no use keeping bytecodes
2288      for all the other duplicate locations, thus we free all of them here.
2289
2290      This is so we have a finer control over which locations' conditions are
2291      being evaluated by GDB or the remote stub.  */
2292   if (null_condition_or_parse_error)
2293     {
2294       for (bp_location *loc : loc_range)
2295         {
2296           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2297             {
2298               /* Only go as far as the first NULL bytecode is
2299                  located.  */
2300               if (!loc->cond_bytecode)
2301                 return;
2302
2303               loc->cond_bytecode.reset ();
2304             }
2305         }
2306     }
2307
2308   /* No NULL conditions or failed bytecode generation.  Build a
2309      condition list for this location's address.  If we have software
2310      and hardware locations at the same address, they aren't
2311      considered duplicates, but we still marge all the conditions
2312      anyway, as it's simpler, and doesn't really make a practical
2313      difference.  */
2314   for (bp_location *loc : loc_range)
2315     if (loc->cond
2316         && is_breakpoint (loc->owner)
2317         && loc->pspace->num == bl->pspace->num
2318         && loc->owner->enable_state == bp_enabled
2319         && loc->enabled
2320         && !loc->disabled_by_cond)
2321       {
2322         /* Add the condition to the vector.  This will be used later
2323            to send the conditions to the target.  */
2324         bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2325       }
2326
2327   return;
2328 }
2329
2330 /* Parses a command described by string CMD into an agent expression
2331    bytecode suitable for evaluation by the bytecode interpreter.
2332    Return NULL if there was any error during parsing.  */
2333
2334 static agent_expr_up
2335 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2336 {
2337   const char *cmdrest;
2338   const char *format_start, *format_end;
2339   struct gdbarch *gdbarch = get_current_arch ();
2340
2341   if (cmd == NULL)
2342     return NULL;
2343
2344   cmdrest = cmd;
2345
2346   if (*cmdrest == ',')
2347     ++cmdrest;
2348   cmdrest = skip_spaces (cmdrest);
2349
2350   if (*cmdrest++ != '"')
2351     error (_("No format string following the location"));
2352
2353   format_start = cmdrest;
2354
2355   format_pieces fpieces (&cmdrest);
2356
2357   format_end = cmdrest;
2358
2359   if (*cmdrest++ != '"')
2360     error (_("Bad format string, non-terminated '\"'."));
2361   
2362   cmdrest = skip_spaces (cmdrest);
2363
2364   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2365     error (_("Invalid argument syntax"));
2366
2367   if (*cmdrest == ',')
2368     cmdrest++;
2369   cmdrest = skip_spaces (cmdrest);
2370
2371   /* For each argument, make an expression.  */
2372
2373   std::vector<struct expression *> argvec;
2374   while (*cmdrest != '\0')
2375     {
2376       const char *cmd1;
2377
2378       cmd1 = cmdrest;
2379       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2380       argvec.push_back (expr.release ());
2381       cmdrest = cmd1;
2382       if (*cmdrest == ',')
2383         ++cmdrest;
2384     }
2385
2386   agent_expr_up aexpr;
2387
2388   /* We don't want to stop processing, so catch any errors
2389      that may show up.  */
2390   try
2391     {
2392       aexpr = gen_printf (scope, gdbarch, 0, 0,
2393                           format_start, format_end - format_start,
2394                           argvec.size (), argvec.data ());
2395     }
2396   catch (const gdb_exception_error &ex)
2397     {
2398       /* If we got here, it means the command could not be parsed to a valid
2399          bytecode expression and thus can't be evaluated on the target's side.
2400          It's no use iterating through the other commands.  */
2401     }
2402
2403   /* We have a valid agent expression, return it.  */
2404   return aexpr;
2405 }
2406
2407 /* Based on location BL, create a list of breakpoint commands to be
2408    passed on to the target.  If we have duplicated locations with
2409    different commands, we will add any such to the list.  */
2410
2411 static void
2412 build_target_command_list (struct bp_location *bl)
2413 {
2414   int null_command_or_parse_error = 0;
2415   int modified = bl->needs_update;
2416
2417   /* Clear commands left over from a previous insert.  */
2418   bl->target_info.tcommands.clear ();
2419
2420   if (!target_can_run_breakpoint_commands ())
2421     return;
2422
2423   /* For now, limit to agent-style dprintf breakpoints.  */
2424   if (dprintf_style != dprintf_style_agent)
2425     return;
2426
2427   auto loc_range = all_bp_locations_at_addr (bl->address);
2428
2429   /* For now, if we have any location at the same address that isn't a
2430      dprintf, don't install the target-side commands, as that would
2431      make the breakpoint not be reported to the core, and we'd lose
2432      control.  */
2433   for (bp_location *loc : loc_range)
2434     if (is_breakpoint (loc->owner)
2435         && loc->pspace->num == bl->pspace->num
2436         && loc->owner->type != bp_dprintf)
2437       return;
2438
2439   /* Do a first pass to check for locations with no assigned
2440      conditions or conditions that fail to parse to a valid agent expression
2441      bytecode.  If any of these happen, then it's no use to send conditions
2442      to the target since this location will always trigger and generate a
2443      response back to GDB.  */
2444   for (bp_location *loc : loc_range)
2445     {
2446       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2447         {
2448           if (modified)
2449             {
2450               /* Re-parse the commands since something changed.  In that
2451                  case we already freed the command bytecodes (see
2452                  force_breakpoint_reinsertion).  We just
2453                  need to parse the command to bytecodes again.  */
2454               loc->cmd_bytecode
2455                 = parse_cmd_to_aexpr (bl->address,
2456                                       loc->owner->extra_string);
2457             }
2458
2459           /* If we have a NULL bytecode expression, it means something
2460              went wrong or we have a null command expression.  */
2461           if (!loc->cmd_bytecode)
2462             {
2463               null_command_or_parse_error = 1;
2464               break;
2465             }
2466         }
2467     }
2468
2469   /* If anything failed, then we're not doing target-side commands,
2470      and so clean up.  */
2471   if (null_command_or_parse_error)
2472     {
2473       for (bp_location *loc : loc_range)
2474         if (is_breakpoint (loc->owner)
2475             && loc->pspace->num == bl->pspace->num)
2476           {
2477             /* Only go as far as the first NULL bytecode is
2478                located.  */
2479             if (loc->cmd_bytecode == NULL)
2480               return;
2481
2482             loc->cmd_bytecode.reset ();
2483           }
2484     }
2485
2486   /* No NULL commands or failed bytecode generation.  Build a command
2487      list for all duplicate locations at this location's address.
2488      Note that here we must care for whether the breakpoint location
2489      types are considered duplicates, otherwise, say, if we have a
2490      software and hardware location at the same address, the target
2491      could end up running the commands twice.  For the moment, we only
2492      support targets-side commands with dprintf, but it doesn't hurt
2493      to be pedantically correct in case that changes.  */
2494   for (bp_location *loc : loc_range)
2495     if (breakpoint_locations_match (bl, loc)
2496         && loc->owner->extra_string
2497         && is_breakpoint (loc->owner)
2498         && loc->pspace->num == bl->pspace->num
2499         && loc->owner->enable_state == bp_enabled
2500         && loc->enabled
2501         && !loc->disabled_by_cond)
2502       {
2503         /* Add the command to the vector.  This will be used later
2504            to send the commands to the target.  */
2505         bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2506       }
2507
2508   bl->target_info.persist = 0;
2509   /* Maybe flag this location as persistent.  */
2510   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2511     bl->target_info.persist = 1;
2512 }
2513
2514 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2515    of breakpoint according to ADDR except single-step breakpoint.
2516    Get the kind of single-step breakpoint according to the current
2517    registers state.  */
2518
2519 static int
2520 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2521 {
2522   if (bl->owner->type == bp_single_step)
2523     {
2524       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2525       struct regcache *regcache;
2526
2527       regcache = get_thread_regcache (thr);
2528
2529       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2530                                                          regcache, addr);
2531     }
2532   else
2533     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2534 }
2535
2536 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2537    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2538    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2539    Returns 0 for success, 1 if the bp_location type is not supported or
2540    -1 for failure.
2541
2542    NOTE drow/2003-09-09: This routine could be broken down to an
2543    object-style method for each breakpoint or catchpoint type.  */
2544 static int
2545 insert_bp_location (struct bp_location *bl,
2546                     struct ui_file *tmp_error_stream,
2547                     int *disabled_breaks,
2548                     int *hw_breakpoint_error,
2549                     int *hw_bp_error_explained_already)
2550 {
2551   gdb_exception bp_excpt;
2552
2553   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2554     return 0;
2555
2556   /* Note we don't initialize bl->target_info, as that wipes out
2557      the breakpoint location's shadow_contents if the breakpoint
2558      is still inserted at that location.  This in turn breaks
2559      target_read_memory which depends on these buffers when
2560      a memory read is requested at the breakpoint location:
2561      Once the target_info has been wiped, we fail to see that
2562      we have a breakpoint inserted at that address and thus
2563      read the breakpoint instead of returning the data saved in
2564      the breakpoint location's shadow contents.  */
2565   bl->target_info.reqstd_address = bl->address;
2566   bl->target_info.placed_address_space = bl->pspace->aspace;
2567   bl->target_info.length = bl->length;
2568
2569   /* When working with target-side conditions, we must pass all the conditions
2570      for the same breakpoint address down to the target since GDB will not
2571      insert those locations.  With a list of breakpoint conditions, the target
2572      can decide when to stop and notify GDB.  */
2573
2574   if (is_breakpoint (bl->owner))
2575     {
2576       build_target_condition_list (bl);
2577       build_target_command_list (bl);
2578       /* Reset the modification marker.  */
2579       bl->needs_update = 0;
2580     }
2581
2582   /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2583      set at a read-only address, then a breakpoint location will have
2584      been changed to hardware breakpoint before we get here.  If it is
2585      "off" however, error out before actually trying to insert the
2586      breakpoint, with a nicer error message.  */
2587   if (bl->loc_type == bp_loc_software_breakpoint
2588       && !automatic_hardware_breakpoints)
2589     {
2590       mem_region *mr = lookup_mem_region (bl->address);
2591
2592       if (mr != nullptr && mr->attrib.mode != MEM_RW)
2593         {
2594           fprintf_unfiltered (tmp_error_stream,
2595                               _("Cannot insert breakpoint %d.\n"
2596                                 "Cannot set software breakpoint "
2597                                 "at read-only address %s\n"),
2598                               bl->owner->number,
2599                               paddress (bl->gdbarch, bl->address));
2600           return 1;
2601         }
2602     }
2603
2604   if (bl->loc_type == bp_loc_software_breakpoint
2605       || bl->loc_type == bp_loc_hardware_breakpoint)
2606     {
2607       /* First check to see if we have to handle an overlay.  */
2608       if (overlay_debugging == ovly_off
2609           || bl->section == NULL
2610           || !(section_is_overlay (bl->section)))
2611         {
2612           /* No overlay handling: just set the breakpoint.  */
2613           try
2614             {
2615               int val;
2616
2617               val = bl->owner->ops->insert_location (bl);
2618               if (val)
2619                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2620             }
2621           catch (gdb_exception &e)
2622             {
2623               bp_excpt = std::move (e);
2624             }
2625         }
2626       else
2627         {
2628           /* This breakpoint is in an overlay section.
2629              Shall we set a breakpoint at the LMA?  */
2630           if (!overlay_events_enabled)
2631             {
2632               /* Yes -- overlay event support is not active, 
2633                  so we must try to set a breakpoint at the LMA.
2634                  This will not work for a hardware breakpoint.  */
2635               if (bl->loc_type == bp_loc_hardware_breakpoint)
2636                 warning (_("hardware breakpoint %d not supported in overlay!"),
2637                          bl->owner->number);
2638               else
2639                 {
2640                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2641                                                              bl->section);
2642                   /* Set a software (trap) breakpoint at the LMA.  */
2643                   bl->overlay_target_info = bl->target_info;
2644                   bl->overlay_target_info.reqstd_address = addr;
2645
2646                   /* No overlay handling: just set the breakpoint.  */
2647                   try
2648                     {
2649                       int val;
2650
2651                       bl->overlay_target_info.kind
2652                         = breakpoint_kind (bl, &addr);
2653                       bl->overlay_target_info.placed_address = addr;
2654                       val = target_insert_breakpoint (bl->gdbarch,
2655                                                       &bl->overlay_target_info);
2656                       if (val)
2657                         bp_excpt
2658                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2659                     }
2660                   catch (gdb_exception &e)
2661                     {
2662                       bp_excpt = std::move (e);
2663                     }
2664
2665                   if (bp_excpt.reason != 0)
2666                     fprintf_unfiltered (tmp_error_stream,
2667                                         "Overlay breakpoint %d "
2668                                         "failed: in ROM?\n",
2669                                         bl->owner->number);
2670                 }
2671             }
2672           /* Shall we set a breakpoint at the VMA? */
2673           if (section_is_mapped (bl->section))
2674             {
2675               /* Yes.  This overlay section is mapped into memory.  */
2676               try
2677                 {
2678                   int val;
2679
2680                   val = bl->owner->ops->insert_location (bl);
2681                   if (val)
2682                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2683                 }
2684               catch (gdb_exception &e)
2685                 {
2686                   bp_excpt = std::move (e);
2687                 }
2688             }
2689           else
2690             {
2691               /* No.  This breakpoint will not be inserted.  
2692                  No error, but do not mark the bp as 'inserted'.  */
2693               return 0;
2694             }
2695         }
2696
2697       if (bp_excpt.reason != 0)
2698         {
2699           /* Can't set the breakpoint.  */
2700
2701           /* In some cases, we might not be able to insert a
2702              breakpoint in a shared library that has already been
2703              removed, but we have not yet processed the shlib unload
2704              event.  Unfortunately, some targets that implement
2705              breakpoint insertion themselves can't tell why the
2706              breakpoint insertion failed (e.g., the remote target
2707              doesn't define error codes), so we must treat generic
2708              errors as memory errors.  */
2709           if (bp_excpt.reason == RETURN_ERROR
2710               && (bp_excpt.error == GENERIC_ERROR
2711                   || bp_excpt.error == MEMORY_ERROR)
2712               && bl->loc_type == bp_loc_software_breakpoint
2713               && (solib_name_from_address (bl->pspace, bl->address)
2714                   || shared_objfile_contains_address_p (bl->pspace,
2715                                                         bl->address)))
2716             {
2717               /* See also: disable_breakpoints_in_shlibs.  */
2718               bl->shlib_disabled = 1;
2719               gdb::observers::breakpoint_modified.notify (bl->owner);
2720               if (!*disabled_breaks)
2721                 {
2722                   fprintf_unfiltered (tmp_error_stream, 
2723                                       "Cannot insert breakpoint %d.\n", 
2724                                       bl->owner->number);
2725                   fprintf_unfiltered (tmp_error_stream, 
2726                                       "Temporarily disabling shared "
2727                                       "library breakpoints:\n");
2728                 }
2729               *disabled_breaks = 1;
2730               fprintf_unfiltered (tmp_error_stream,
2731                                   "breakpoint #%d\n", bl->owner->number);
2732               return 0;
2733             }
2734           else
2735             {
2736               if (bl->loc_type == bp_loc_hardware_breakpoint)
2737                 {
2738                   *hw_breakpoint_error = 1;
2739                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2740                   fprintf_unfiltered (tmp_error_stream,
2741                                       "Cannot insert hardware breakpoint %d%s",
2742                                       bl->owner->number,
2743                                       bp_excpt.message ? ":" : ".\n");
2744                   if (bp_excpt.message != NULL)
2745                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2746                                         bp_excpt.what ());
2747                 }
2748               else
2749                 {
2750                   if (bp_excpt.message == NULL)
2751                     {
2752                       std::string message
2753                         = memory_error_message (TARGET_XFER_E_IO,
2754                                                 bl->gdbarch, bl->address);
2755
2756                       fprintf_unfiltered (tmp_error_stream,
2757                                           "Cannot insert breakpoint %d.\n"
2758                                           "%s\n",
2759                                           bl->owner->number, message.c_str ());
2760                     }
2761                   else
2762                     {
2763                       fprintf_unfiltered (tmp_error_stream,
2764                                           "Cannot insert breakpoint %d: %s\n",
2765                                           bl->owner->number,
2766                                           bp_excpt.what ());
2767                     }
2768                 }
2769               return 1;
2770
2771             }
2772         }
2773       else
2774         bl->inserted = 1;
2775
2776       return 0;
2777     }
2778
2779   else if (bl->loc_type == bp_loc_hardware_watchpoint
2780            /* NOTE drow/2003-09-08: This state only exists for removing
2781               watchpoints.  It's not clear that it's necessary...  */
2782            && bl->owner->disposition != disp_del_at_next_stop)
2783     {
2784       int val;
2785
2786       gdb_assert (bl->owner->ops != NULL
2787                   && bl->owner->ops->insert_location != NULL);
2788
2789       val = bl->owner->ops->insert_location (bl);
2790
2791       /* If trying to set a read-watchpoint, and it turns out it's not
2792          supported, try emulating one with an access watchpoint.  */
2793       if (val == 1 && bl->watchpoint_type == hw_read)
2794         {
2795           /* But don't try to insert it, if there's already another
2796              hw_access location that would be considered a duplicate
2797              of this one.  */
2798           for (bp_location *loc : all_bp_locations ())
2799             if (loc != bl
2800                 && loc->watchpoint_type == hw_access
2801                 && watchpoint_locations_match (bl, loc))
2802               {
2803                 bl->duplicate = 1;
2804                 bl->inserted = 1;
2805                 bl->target_info = loc->target_info;
2806                 bl->watchpoint_type = hw_access;
2807                 val = 0;
2808                 break;
2809               }
2810
2811           if (val == 1)
2812             {
2813               bl->watchpoint_type = hw_access;
2814               val = bl->owner->ops->insert_location (bl);
2815
2816               if (val)
2817                 /* Back to the original value.  */
2818                 bl->watchpoint_type = hw_read;
2819             }
2820         }
2821
2822       bl->inserted = (val == 0);
2823     }
2824
2825   else if (bl->owner->type == bp_catchpoint)
2826     {
2827       int val;
2828
2829       gdb_assert (bl->owner->ops != NULL
2830                   && bl->owner->ops->insert_location != NULL);
2831
2832       val = bl->owner->ops->insert_location (bl);
2833       if (val)
2834         {
2835           bl->owner->enable_state = bp_disabled;
2836
2837           if (val == 1)
2838             warning (_("\
2839 Error inserting catchpoint %d: Your system does not support this type\n\
2840 of catchpoint."), bl->owner->number);
2841           else
2842             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2843         }
2844
2845       bl->inserted = (val == 0);
2846
2847       /* We've already printed an error message if there was a problem
2848          inserting this catchpoint, and we've disabled the catchpoint,
2849          so just return success.  */
2850       return 0;
2851     }
2852
2853   return 0;
2854 }
2855
2856 /* This function is called when program space PSPACE is about to be
2857    deleted.  It takes care of updating breakpoints to not reference
2858    PSPACE anymore.  */
2859
2860 void
2861 breakpoint_program_space_exit (struct program_space *pspace)
2862 {
2863   /* Remove any breakpoint that was set through this program space.  */
2864   for (breakpoint *b : all_breakpoints_safe ())
2865     if (b->pspace == pspace)
2866       delete_breakpoint (b);
2867
2868   /* Breakpoints set through other program spaces could have locations
2869      bound to PSPACE as well.  Remove those.  */
2870   for (bp_location *loc : all_bp_locations ())
2871     {
2872       struct bp_location *tmp;
2873
2874       if (loc->pspace == pspace)
2875         {
2876           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2877           if (loc->owner->loc == loc)
2878             loc->owner->loc = loc->next;
2879           else
2880             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2881               if (tmp->next == loc)
2882                 {
2883                   tmp->next = loc->next;
2884                   break;
2885                 }
2886         }
2887     }
2888
2889   /* Now update the global location list to permanently delete the
2890      removed locations above.  */
2891   update_global_location_list (UGLL_DONT_INSERT);
2892 }
2893
2894 /* Make sure all breakpoints are inserted in inferior.
2895    Throws exception on any error.
2896    A breakpoint that is already inserted won't be inserted
2897    again, so calling this function twice is safe.  */
2898 void
2899 insert_breakpoints (void)
2900 {
2901   for (breakpoint *bpt : all_breakpoints ())
2902     if (is_hardware_watchpoint (bpt))
2903       {
2904         struct watchpoint *w = (struct watchpoint *) bpt;
2905
2906         update_watchpoint (w, 0 /* don't reparse.  */);
2907       }
2908
2909   /* Updating watchpoints creates new locations, so update the global
2910      location list.  Explicitly tell ugll to insert locations and
2911      ignore breakpoints_always_inserted_mode.  Also,
2912      update_global_location_list tries to "upgrade" software
2913      breakpoints to hardware breakpoints to handle "set breakpoint
2914      auto-hw", so we need to call it even if we don't have new
2915      locations.  */
2916   update_global_location_list (UGLL_INSERT);
2917 }
2918
2919 /* This is used when we need to synch breakpoint conditions between GDB and the
2920    target.  It is the case with deleting and disabling of breakpoints when using
2921    always-inserted mode.  */
2922
2923 static void
2924 update_inserted_breakpoint_locations (void)
2925 {
2926   int error_flag = 0;
2927   int val = 0;
2928   int disabled_breaks = 0;
2929   int hw_breakpoint_error = 0;
2930   int hw_bp_details_reported = 0;
2931
2932   string_file tmp_error_stream;
2933
2934   /* Explicitly mark the warning -- this will only be printed if
2935      there was an error.  */
2936   tmp_error_stream.puts ("Warning:\n");
2937
2938   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2939
2940   for (bp_location *bl : all_bp_locations ())
2941     {
2942       /* We only want to update software breakpoints and hardware
2943          breakpoints.  */
2944       if (!is_breakpoint (bl->owner))
2945         continue;
2946
2947       /* We only want to update locations that are already inserted
2948          and need updating.  This is to avoid unwanted insertion during
2949          deletion of breakpoints.  */
2950       if (!bl->inserted || !bl->needs_update)
2951         continue;
2952
2953       switch_to_program_space_and_thread (bl->pspace);
2954
2955       /* For targets that support global breakpoints, there's no need
2956          to select an inferior to insert breakpoint to.  In fact, even
2957          if we aren't attached to any process yet, we should still
2958          insert breakpoints.  */
2959       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2960           && (inferior_ptid == null_ptid || !target_has_execution ()))
2961         continue;
2962
2963       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2964                                     &hw_breakpoint_error, &hw_bp_details_reported);
2965       if (val)
2966         error_flag = val;
2967     }
2968
2969   if (error_flag)
2970     {
2971       target_terminal::ours_for_output ();
2972       error_stream (tmp_error_stream);
2973     }
2974 }
2975
2976 /* Used when starting or continuing the program.  */
2977
2978 static void
2979 insert_breakpoint_locations (void)
2980 {
2981   int error_flag = 0;
2982   int val = 0;
2983   int disabled_breaks = 0;
2984   int hw_breakpoint_error = 0;
2985   int hw_bp_error_explained_already = 0;
2986
2987   string_file tmp_error_stream;
2988
2989   /* Explicitly mark the warning -- this will only be printed if
2990      there was an error.  */
2991   tmp_error_stream.puts ("Warning:\n");
2992
2993   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2994
2995   for (bp_location *bl : all_bp_locations ())
2996     {
2997       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2998         continue;
2999
3000       /* There is no point inserting thread-specific breakpoints if
3001          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3002          has BL->OWNER always non-NULL.  */
3003       if (bl->owner->thread != -1
3004           && !valid_global_thread_id (bl->owner->thread))
3005         continue;
3006
3007       switch_to_program_space_and_thread (bl->pspace);
3008
3009       /* For targets that support global breakpoints, there's no need
3010          to select an inferior to insert breakpoint to.  In fact, even
3011          if we aren't attached to any process yet, we should still
3012          insert breakpoints.  */
3013       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3014           && (inferior_ptid == null_ptid || !target_has_execution ()))
3015         continue;
3016
3017       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3018                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3019       if (val)
3020         error_flag = val;
3021     }
3022
3023   /* If we failed to insert all locations of a watchpoint, remove
3024      them, as half-inserted watchpoint is of limited use.  */
3025   for (breakpoint *bpt : all_breakpoints ())
3026     {
3027       int some_failed = 0;
3028
3029       if (!is_hardware_watchpoint (bpt))
3030         continue;
3031
3032       if (!breakpoint_enabled (bpt))
3033         continue;
3034
3035       if (bpt->disposition == disp_del_at_next_stop)
3036         continue;
3037       
3038       for (bp_location *loc : bpt->locations ())
3039         if (!loc->inserted && should_be_inserted (loc))
3040           {
3041             some_failed = 1;
3042             break;
3043           }
3044
3045       if (some_failed)
3046         {
3047           for (bp_location *loc : bpt->locations ())
3048             if (loc->inserted)
3049               remove_breakpoint (loc);
3050
3051           hw_breakpoint_error = 1;
3052           tmp_error_stream.printf ("Could not insert "
3053                                    "hardware watchpoint %d.\n",
3054                                    bpt->number);
3055           error_flag = -1;
3056         }
3057     }
3058
3059   if (error_flag)
3060     {
3061       /* If a hardware breakpoint or watchpoint was inserted, add a
3062          message about possibly exhausted resources.  */
3063       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3064         {
3065           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3066 You may have requested too many hardware breakpoints/watchpoints.\n");
3067         }
3068       target_terminal::ours_for_output ();
3069       error_stream (tmp_error_stream);
3070     }
3071 }
3072
3073 /* Used when the program stops.
3074    Returns zero if successful, or non-zero if there was a problem
3075    removing a breakpoint location.  */
3076
3077 int
3078 remove_breakpoints (void)
3079 {
3080   int val = 0;
3081
3082   for (bp_location *bl : all_bp_locations ())
3083     if (bl->inserted && !is_tracepoint (bl->owner))
3084       val |= remove_breakpoint (bl);
3085
3086   return val;
3087 }
3088
3089 /* When a thread exits, remove breakpoints that are related to
3090    that thread.  */
3091
3092 static void
3093 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3094 {
3095   for (breakpoint *b : all_breakpoints_safe ())
3096     {
3097       if (b->thread == tp->global_num && user_breakpoint_p (b))
3098         {
3099           b->disposition = disp_del_at_next_stop;
3100
3101           printf_filtered (_("\
3102 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3103                            b->number, print_thread_id (tp));
3104
3105           /* Hide it from the user.  */
3106           b->number = 0;
3107        }
3108     }
3109 }
3110
3111 /* See breakpoint.h.  */
3112
3113 void
3114 remove_breakpoints_inf (inferior *inf)
3115 {
3116   int val;
3117
3118   for (bp_location *bl : all_bp_locations ())
3119     {
3120       if (bl->pspace != inf->pspace)
3121         continue;
3122
3123       if (bl->inserted && !bl->target_info.persist)
3124         {
3125           val = remove_breakpoint (bl);
3126           if (val != 0)
3127             return;
3128         }
3129     }
3130 }
3131
3132 static int internal_breakpoint_number = -1;
3133
3134 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3135    If INTERNAL is non-zero, the breakpoint number will be populated
3136    from internal_breakpoint_number and that variable decremented.
3137    Otherwise the breakpoint number will be populated from
3138    breakpoint_count and that value incremented.  Internal breakpoints
3139    do not set the internal var bpnum.  */
3140 static void
3141 set_breakpoint_number (int internal, struct breakpoint *b)
3142 {
3143   if (internal)
3144     b->number = internal_breakpoint_number--;
3145   else
3146     {
3147       set_breakpoint_count (breakpoint_count + 1);
3148       b->number = breakpoint_count;
3149     }
3150 }
3151
3152 static struct breakpoint *
3153 create_internal_breakpoint (struct gdbarch *gdbarch,
3154                             CORE_ADDR address, enum bptype type,
3155                             const struct breakpoint_ops *ops)
3156 {
3157   symtab_and_line sal;
3158   sal.pc = address;
3159   sal.section = find_pc_overlay (sal.pc);
3160   sal.pspace = current_program_space;
3161
3162   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3163   b->number = internal_breakpoint_number--;
3164   b->disposition = disp_donttouch;
3165
3166   return b;
3167 }
3168
3169 static const char *const longjmp_names[] =
3170   {
3171     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3172   };
3173 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3174
3175 /* Per-objfile data private to breakpoint.c.  */
3176 struct breakpoint_objfile_data
3177 {
3178   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3179   struct bound_minimal_symbol overlay_msym {};
3180
3181   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3182   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3183
3184   /* True if we have looked for longjmp probes.  */
3185   int longjmp_searched = 0;
3186
3187   /* SystemTap probe points for longjmp (if any).  These are non-owning
3188      references.  */
3189   std::vector<probe *> longjmp_probes;
3190
3191   /* Minimal symbol for "std::terminate()" (if any).  */
3192   struct bound_minimal_symbol terminate_msym {};
3193
3194   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3195   struct bound_minimal_symbol exception_msym {};
3196
3197   /* True if we have looked for exception probes.  */
3198   int exception_searched = 0;
3199
3200   /* SystemTap probe points for unwinding (if any).  These are non-owning
3201      references.  */
3202   std::vector<probe *> exception_probes;
3203 };
3204
3205 static const struct objfile_key<breakpoint_objfile_data>
3206   breakpoint_objfile_key;
3207
3208 /* Minimal symbol not found sentinel.  */
3209 static struct minimal_symbol msym_not_found;
3210
3211 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3212
3213 static int
3214 msym_not_found_p (const struct minimal_symbol *msym)
3215 {
3216   return msym == &msym_not_found;
3217 }
3218
3219 /* Return per-objfile data needed by breakpoint.c.
3220    Allocate the data if necessary.  */
3221
3222 static struct breakpoint_objfile_data *
3223 get_breakpoint_objfile_data (struct objfile *objfile)
3224 {
3225   struct breakpoint_objfile_data *bp_objfile_data;
3226
3227   bp_objfile_data = breakpoint_objfile_key.get (objfile);
3228   if (bp_objfile_data == NULL)
3229     bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3230   return bp_objfile_data;
3231 }
3232
3233 static void
3234 create_overlay_event_breakpoint (void)
3235 {
3236   const char *const func_name = "_ovly_debug_event";
3237
3238   for (objfile *objfile : current_program_space->objfiles ())
3239     {
3240       struct breakpoint *b;
3241       struct breakpoint_objfile_data *bp_objfile_data;
3242       CORE_ADDR addr;
3243       struct explicit_location explicit_loc;
3244
3245       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3246
3247       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3248         continue;
3249
3250       if (bp_objfile_data->overlay_msym.minsym == NULL)
3251         {
3252           struct bound_minimal_symbol m;
3253
3254           m = lookup_minimal_symbol_text (func_name, objfile);
3255           if (m.minsym == NULL)
3256             {
3257               /* Avoid future lookups in this objfile.  */
3258               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3259               continue;
3260             }
3261           bp_objfile_data->overlay_msym = m;
3262         }
3263
3264       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3265       b = create_internal_breakpoint (objfile->arch (), addr,
3266                                       bp_overlay_event,
3267                                       &internal_breakpoint_ops);
3268       initialize_explicit_location (&explicit_loc);
3269       explicit_loc.function_name = ASTRDUP (func_name);
3270       b->location = new_explicit_location (&explicit_loc);
3271
3272       if (overlay_debugging == ovly_auto)
3273         {
3274           b->enable_state = bp_enabled;
3275           overlay_events_enabled = 1;
3276         }
3277       else
3278        {
3279          b->enable_state = bp_disabled;
3280          overlay_events_enabled = 0;
3281        }
3282     }
3283 }
3284
3285 /* Install a master longjmp breakpoint for OBJFILE using a probe.  Return
3286    true if a breakpoint was installed.  */
3287
3288 static bool
3289 create_longjmp_master_breakpoint_probe (objfile *objfile)
3290 {
3291   struct gdbarch *gdbarch = objfile->arch ();
3292   struct breakpoint_objfile_data *bp_objfile_data
3293     = get_breakpoint_objfile_data (objfile);
3294
3295   if (!bp_objfile_data->longjmp_searched)
3296     {
3297       std::vector<probe *> ret
3298         = find_probes_in_objfile (objfile, "libc", "longjmp");
3299
3300       if (!ret.empty ())
3301         {
3302           /* We are only interested in checking one element.  */
3303           probe *p = ret[0];
3304
3305           if (!p->can_evaluate_arguments ())
3306             {
3307               /* We cannot use the probe interface here,
3308                  because it does not know how to evaluate
3309                  arguments.  */
3310               ret.clear ();
3311             }
3312         }
3313       bp_objfile_data->longjmp_probes = ret;
3314       bp_objfile_data->longjmp_searched = 1;
3315     }
3316
3317   if (bp_objfile_data->longjmp_probes.empty ())
3318     return false;
3319
3320   for (probe *p : bp_objfile_data->longjmp_probes)
3321     {
3322       struct breakpoint *b;
3323
3324       b = create_internal_breakpoint (gdbarch,
3325                                       p->get_relocated_address (objfile),
3326                                       bp_longjmp_master,
3327                                       &internal_breakpoint_ops);
3328       b->location = new_probe_location ("-probe-stap libc:longjmp");
3329       b->enable_state = bp_disabled;
3330     }
3331
3332   return true;
3333 }
3334
3335 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3336    Return true if at least one breakpoint was installed.  */
3337
3338 static bool
3339 create_longjmp_master_breakpoint_names (objfile *objfile)
3340 {
3341   struct gdbarch *gdbarch = objfile->arch ();
3342   if (!gdbarch_get_longjmp_target_p (gdbarch))
3343     return false;
3344
3345   struct breakpoint_objfile_data *bp_objfile_data
3346     = get_breakpoint_objfile_data (objfile);
3347   unsigned int installed_bp = 0;
3348
3349   for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3350     {
3351       struct breakpoint *b;
3352       const char *func_name;
3353       CORE_ADDR addr;
3354       struct explicit_location explicit_loc;
3355
3356       if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3357         continue;
3358
3359       func_name = longjmp_names[i];
3360       if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3361         {
3362           struct bound_minimal_symbol m;
3363
3364           m = lookup_minimal_symbol_text (func_name, objfile);
3365           if (m.minsym == NULL)
3366             {
3367               /* Prevent future lookups in this objfile.  */
3368               bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3369               continue;
3370             }
3371           bp_objfile_data->longjmp_msym[i] = m;
3372         }
3373
3374       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3375       b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3376                                       &internal_breakpoint_ops);
3377       initialize_explicit_location (&explicit_loc);
3378       explicit_loc.function_name = ASTRDUP (func_name);
3379       b->location = new_explicit_location (&explicit_loc);
3380       b->enable_state = bp_disabled;
3381       installed_bp++;
3382     }
3383
3384   return installed_bp > 0;
3385 }
3386
3387 /* Create a master longjmp breakpoint.  */
3388
3389 static void
3390 create_longjmp_master_breakpoint (void)
3391 {
3392   scoped_restore_current_program_space restore_pspace;
3393
3394   for (struct program_space *pspace : program_spaces)
3395     {
3396       set_current_program_space (pspace);
3397
3398       for (objfile *obj : current_program_space->objfiles ())
3399         {
3400           /* Skip separate debug object, it's handled in the loop below.  */
3401           if (obj->separate_debug_objfile_backlink != nullptr)
3402             continue;
3403
3404           /* Try a probe kind breakpoint on main objfile.  */
3405           if (create_longjmp_master_breakpoint_probe (obj))
3406             continue;
3407
3408           /* Try longjmp_names kind breakpoints on main and separate_debug
3409              objfiles.  */
3410           for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3411             if (create_longjmp_master_breakpoint_names (debug_objfile))
3412               break;
3413         }
3414     }
3415 }
3416
3417 /* Create a master std::terminate breakpoint.  */
3418 static void
3419 create_std_terminate_master_breakpoint (void)
3420 {
3421   const char *const func_name = "std::terminate()";
3422
3423   scoped_restore_current_program_space restore_pspace;
3424
3425   for (struct program_space *pspace : program_spaces)
3426     {
3427       CORE_ADDR addr;
3428
3429       set_current_program_space (pspace);
3430
3431       for (objfile *objfile : current_program_space->objfiles ())
3432         {
3433           struct breakpoint *b;
3434           struct breakpoint_objfile_data *bp_objfile_data;
3435           struct explicit_location explicit_loc;
3436
3437           bp_objfile_data = get_breakpoint_objfile_data (objfile);
3438
3439           if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3440             continue;
3441
3442           if (bp_objfile_data->terminate_msym.minsym == NULL)
3443             {
3444               struct bound_minimal_symbol m;
3445
3446               m = lookup_minimal_symbol (func_name, NULL, objfile);
3447               if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3448                                        && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3449                 {
3450                   /* Prevent future lookups in this objfile.  */
3451                   bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3452                   continue;
3453                 }
3454               bp_objfile_data->terminate_msym = m;
3455             }
3456
3457           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3458           b = create_internal_breakpoint (objfile->arch (), addr,
3459                                           bp_std_terminate_master,
3460                                           &internal_breakpoint_ops);
3461           initialize_explicit_location (&explicit_loc);
3462           explicit_loc.function_name = ASTRDUP (func_name);
3463           b->location = new_explicit_location (&explicit_loc);
3464           b->enable_state = bp_disabled;
3465         }
3466     }
3467 }
3468
3469 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3470    probe.  Return true if a breakpoint was installed.  */
3471
3472 static bool
3473 create_exception_master_breakpoint_probe (objfile *objfile)
3474 {
3475   struct breakpoint *b;
3476   struct gdbarch *gdbarch;
3477   struct breakpoint_objfile_data *bp_objfile_data;
3478
3479   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3480
3481   /* We prefer the SystemTap probe point if it exists.  */
3482   if (!bp_objfile_data->exception_searched)
3483     {
3484       std::vector<probe *> ret
3485         = find_probes_in_objfile (objfile, "libgcc", "unwind");
3486
3487       if (!ret.empty ())
3488         {
3489           /* We are only interested in checking one element.  */
3490           probe *p = ret[0];
3491
3492           if (!p->can_evaluate_arguments ())
3493             {
3494               /* We cannot use the probe interface here, because it does
3495                  not know how to evaluate arguments.  */
3496               ret.clear ();
3497             }
3498         }
3499       bp_objfile_data->exception_probes = ret;
3500       bp_objfile_data->exception_searched = 1;
3501     }
3502
3503   if (bp_objfile_data->exception_probes.empty ())
3504     return false;
3505
3506   gdbarch = objfile->arch ();
3507
3508   for (probe *p : bp_objfile_data->exception_probes)
3509     {
3510       b = create_internal_breakpoint (gdbarch,
3511                                       p->get_relocated_address (objfile),
3512                                       bp_exception_master,
3513                                       &internal_breakpoint_ops);
3514       b->location = new_probe_location ("-probe-stap libgcc:unwind");
3515       b->enable_state = bp_disabled;
3516     }
3517
3518   return true;
3519 }
3520
3521 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3522    _Unwind_DebugHook.  Return true if a breakpoint was installed.  */
3523
3524 static bool
3525 create_exception_master_breakpoint_hook (objfile *objfile)
3526 {
3527   const char *const func_name = "_Unwind_DebugHook";
3528   struct breakpoint *b;
3529   struct gdbarch *gdbarch;
3530   struct breakpoint_objfile_data *bp_objfile_data;
3531   CORE_ADDR addr;
3532   struct explicit_location explicit_loc;
3533
3534   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3535
3536   if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3537     return false;
3538
3539   gdbarch = objfile->arch ();
3540
3541   if (bp_objfile_data->exception_msym.minsym == NULL)
3542     {
3543       struct bound_minimal_symbol debug_hook;
3544
3545       debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3546       if (debug_hook.minsym == NULL)
3547         {
3548           bp_objfile_data->exception_msym.minsym = &msym_not_found;
3549           return false;
3550         }
3551
3552       bp_objfile_data->exception_msym = debug_hook;
3553     }
3554
3555   addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3556   addr = gdbarch_convert_from_func_ptr_addr
3557     (gdbarch, addr, current_inferior ()->top_target ());
3558   b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3559                                   &internal_breakpoint_ops);
3560   initialize_explicit_location (&explicit_loc);
3561   explicit_loc.function_name = ASTRDUP (func_name);
3562   b->location = new_explicit_location (&explicit_loc);
3563   b->enable_state = bp_disabled;
3564
3565   return true;
3566 }
3567
3568 /* Install a master breakpoint on the unwinder's debug hook.  */
3569
3570 static void
3571 create_exception_master_breakpoint (void)
3572 {
3573   for (objfile *obj : current_program_space->objfiles ())
3574     {
3575       /* Skip separate debug object.  */
3576       if (obj->separate_debug_objfile_backlink)
3577         continue;
3578
3579       /* Try a probe kind breakpoint.  */
3580       if (create_exception_master_breakpoint_probe (obj))
3581         continue;
3582
3583       /* Iterate over main and separate debug objects and try an
3584          _Unwind_DebugHook kind breakpoint.  */
3585       for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3586         if (create_exception_master_breakpoint_hook (debug_objfile))
3587           break;
3588     }
3589 }
3590
3591 /* Does B have a location spec?  */
3592
3593 static int
3594 breakpoint_event_location_empty_p (const struct breakpoint *b)
3595 {
3596   return b->location != NULL && event_location_empty_p (b->location.get ());
3597 }
3598
3599 void
3600 update_breakpoints_after_exec (void)
3601 {
3602   /* We're about to delete breakpoints from GDB's lists.  If the
3603      INSERTED flag is true, GDB will try to lift the breakpoints by
3604      writing the breakpoints' "shadow contents" back into memory.  The
3605      "shadow contents" are NOT valid after an exec, so GDB should not
3606      do that.  Instead, the target is responsible from marking
3607      breakpoints out as soon as it detects an exec.  We don't do that
3608      here instead, because there may be other attempts to delete
3609      breakpoints after detecting an exec and before reaching here.  */
3610   for (bp_location *bploc : all_bp_locations ())
3611     if (bploc->pspace == current_program_space)
3612       gdb_assert (!bploc->inserted);
3613
3614   for (breakpoint *b : all_breakpoints_safe ())
3615     {
3616       if (b->pspace != current_program_space)
3617         continue;
3618
3619       /* Solib breakpoints must be explicitly reset after an exec().  */
3620       if (b->type == bp_shlib_event)
3621         {
3622           delete_breakpoint (b);
3623           continue;
3624         }
3625
3626       /* JIT breakpoints must be explicitly reset after an exec().  */
3627       if (b->type == bp_jit_event)
3628         {
3629           delete_breakpoint (b);
3630           continue;
3631         }
3632
3633       /* Thread event breakpoints must be set anew after an exec(),
3634          as must overlay event and longjmp master breakpoints.  */
3635       if (b->type == bp_thread_event || b->type == bp_overlay_event
3636           || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3637           || b->type == bp_exception_master)
3638         {
3639           delete_breakpoint (b);
3640           continue;
3641         }
3642
3643       /* Step-resume breakpoints are meaningless after an exec().  */
3644       if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3645         {
3646           delete_breakpoint (b);
3647           continue;
3648         }
3649
3650       /* Just like single-step breakpoints.  */
3651       if (b->type == bp_single_step)
3652         {
3653           delete_breakpoint (b);
3654           continue;
3655         }
3656
3657       /* Longjmp and longjmp-resume breakpoints are also meaningless
3658          after an exec.  */
3659       if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3660           || b->type == bp_longjmp_call_dummy
3661           || b->type == bp_exception || b->type == bp_exception_resume)
3662         {
3663           delete_breakpoint (b);
3664           continue;
3665         }
3666
3667       if (b->type == bp_catchpoint)
3668         {
3669           /* For now, none of the bp_catchpoint breakpoints need to
3670              do anything at this point.  In the future, if some of
3671              the catchpoints need to something, we will need to add
3672              a new method, and call this method from here.  */
3673           continue;
3674         }
3675
3676       /* bp_finish is a special case.  The only way we ought to be able
3677          to see one of these when an exec() has happened, is if the user
3678          caught a vfork, and then said "finish".  Ordinarily a finish just
3679          carries them to the call-site of the current callee, by setting
3680          a temporary bp there and resuming.  But in this case, the finish
3681          will carry them entirely through the vfork & exec.
3682
3683          We don't want to allow a bp_finish to remain inserted now.  But
3684          we can't safely delete it, 'cause finish_command has a handle to
3685          the bp on a bpstat, and will later want to delete it.  There's a
3686          chance (and I've seen it happen) that if we delete the bp_finish
3687          here, that its storage will get reused by the time finish_command
3688          gets 'round to deleting the "use to be a bp_finish" breakpoint.
3689          We really must allow finish_command to delete a bp_finish.
3690
3691          In the absence of a general solution for the "how do we know
3692          it's safe to delete something others may have handles to?"
3693          problem, what we'll do here is just uninsert the bp_finish, and
3694          let finish_command delete it.
3695
3696          (We know the bp_finish is "doomed" in the sense that it's
3697          momentary, and will be deleted as soon as finish_command sees
3698          the inferior stopped.  So it doesn't matter that the bp's
3699          address is probably bogus in the new a.out, unlike e.g., the
3700          solib breakpoints.)  */
3701
3702       if (b->type == bp_finish)
3703         {
3704           continue;
3705         }
3706
3707       /* Without a symbolic address, we have little hope of the
3708          pre-exec() address meaning the same thing in the post-exec()
3709          a.out.  */
3710       if (breakpoint_event_location_empty_p (b))
3711         {
3712           delete_breakpoint (b);
3713           continue;
3714         }
3715     }
3716 }
3717
3718 int
3719 detach_breakpoints (ptid_t ptid)
3720 {
3721   int val = 0;
3722   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3723   struct inferior *inf = current_inferior ();
3724
3725   if (ptid.pid () == inferior_ptid.pid ())
3726     error (_("Cannot detach breakpoints of inferior_ptid"));
3727
3728   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3729   inferior_ptid = ptid;
3730   for (bp_location *bl : all_bp_locations ())
3731     {
3732       if (bl->pspace != inf->pspace)
3733         continue;
3734
3735       /* This function must physically remove breakpoints locations
3736          from the specified ptid, without modifying the breakpoint
3737          package's state.  Locations of type bp_loc_other are only
3738          maintained at GDB side.  So, there is no need to remove
3739          these bp_loc_other locations.  Moreover, removing these
3740          would modify the breakpoint package's state.  */
3741       if (bl->loc_type == bp_loc_other)
3742         continue;
3743
3744       if (bl->inserted)
3745         val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3746     }
3747
3748   return val;
3749 }
3750
3751 /* Remove the breakpoint location BL from the current address space.
3752    Note that this is used to detach breakpoints from a child fork.
3753    When we get here, the child isn't in the inferior list, and neither
3754    do we have objects to represent its address space --- we should
3755    *not* look at bl->pspace->aspace here.  */
3756
3757 static int
3758 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3759 {
3760   int val;
3761
3762   /* BL is never in moribund_locations by our callers.  */
3763   gdb_assert (bl->owner != NULL);
3764
3765   /* The type of none suggests that owner is actually deleted.
3766      This should not ever happen.  */
3767   gdb_assert (bl->owner->type != bp_none);
3768
3769   if (bl->loc_type == bp_loc_software_breakpoint
3770       || bl->loc_type == bp_loc_hardware_breakpoint)
3771     {
3772       /* "Normal" instruction breakpoint: either the standard
3773          trap-instruction bp (bp_breakpoint), or a
3774          bp_hardware_breakpoint.  */
3775
3776       /* First check to see if we have to handle an overlay.  */
3777       if (overlay_debugging == ovly_off
3778           || bl->section == NULL
3779           || !(section_is_overlay (bl->section)))
3780         {
3781           /* No overlay handling: just remove the breakpoint.  */
3782
3783           /* If we're trying to uninsert a memory breakpoint that we
3784              know is set in a dynamic object that is marked
3785              shlib_disabled, then either the dynamic object was
3786              removed with "remove-symbol-file" or with
3787              "nosharedlibrary".  In the former case, we don't know
3788              whether another dynamic object might have loaded over the
3789              breakpoint's address -- the user might well let us know
3790              about it next with add-symbol-file (the whole point of
3791              add-symbol-file is letting the user manually maintain a
3792              list of dynamically loaded objects).  If we have the
3793              breakpoint's shadow memory, that is, this is a software
3794              breakpoint managed by GDB, check whether the breakpoint
3795              is still inserted in memory, to avoid overwriting wrong
3796              code with stale saved shadow contents.  Note that HW
3797              breakpoints don't have shadow memory, as they're
3798              implemented using a mechanism that is not dependent on
3799              being able to modify the target's memory, and as such
3800              they should always be removed.  */
3801           if (bl->shlib_disabled
3802               && bl->target_info.shadow_len != 0
3803               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3804             val = 0;
3805           else
3806             val = bl->owner->ops->remove_location (bl, reason);
3807         }
3808       else
3809         {
3810           /* This breakpoint is in an overlay section.
3811              Did we set a breakpoint at the LMA?  */
3812           if (!overlay_events_enabled)
3813               {
3814                 /* Yes -- overlay event support is not active, so we
3815                    should have set a breakpoint at the LMA.  Remove it.  
3816                 */
3817                 /* Ignore any failures: if the LMA is in ROM, we will
3818                    have already warned when we failed to insert it.  */
3819                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3820                   target_remove_hw_breakpoint (bl->gdbarch,
3821                                                &bl->overlay_target_info);
3822                 else
3823                   target_remove_breakpoint (bl->gdbarch,
3824                                             &bl->overlay_target_info,
3825                                             reason);
3826               }
3827           /* Did we set a breakpoint at the VMA? 
3828              If so, we will have marked the breakpoint 'inserted'.  */
3829           if (bl->inserted)
3830             {
3831               /* Yes -- remove it.  Previously we did not bother to
3832                  remove the breakpoint if the section had been
3833                  unmapped, but let's not rely on that being safe.  We
3834                  don't know what the overlay manager might do.  */
3835
3836               /* However, we should remove *software* breakpoints only
3837                  if the section is still mapped, or else we overwrite
3838                  wrong code with the saved shadow contents.  */
3839               if (bl->loc_type == bp_loc_hardware_breakpoint
3840                   || section_is_mapped (bl->section))
3841                 val = bl->owner->ops->remove_location (bl, reason);
3842               else
3843                 val = 0;
3844             }
3845           else
3846             {
3847               /* No -- not inserted, so no need to remove.  No error.  */
3848               val = 0;
3849             }
3850         }
3851
3852       /* In some cases, we might not be able to remove a breakpoint in
3853          a shared library that has already been removed, but we have
3854          not yet processed the shlib unload event.  Similarly for an
3855          unloaded add-symbol-file object - the user might not yet have
3856          had the chance to remove-symbol-file it.  shlib_disabled will
3857          be set if the library/object has already been removed, but
3858          the breakpoint hasn't been uninserted yet, e.g., after
3859          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3860          always-inserted mode.  */
3861       if (val
3862           && (bl->loc_type == bp_loc_software_breakpoint
3863               && (bl->shlib_disabled
3864                   || solib_name_from_address (bl->pspace, bl->address)
3865                   || shared_objfile_contains_address_p (bl->pspace,
3866                                                         bl->address))))
3867         val = 0;
3868
3869       if (val)
3870         return val;
3871       bl->inserted = (reason == DETACH_BREAKPOINT);
3872     }
3873   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3874     {
3875       gdb_assert (bl->owner->ops != NULL
3876                   && bl->owner->ops->remove_location != NULL);
3877
3878       bl->inserted = (reason == DETACH_BREAKPOINT);
3879       bl->owner->ops->remove_location (bl, reason);
3880
3881       /* Failure to remove any of the hardware watchpoints comes here.  */
3882       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3883         warning (_("Could not remove hardware watchpoint %d."),
3884                  bl->owner->number);
3885     }
3886   else if (bl->owner->type == bp_catchpoint
3887            && breakpoint_enabled (bl->owner)
3888            && !bl->duplicate)
3889     {
3890       gdb_assert (bl->owner->ops != NULL
3891                   && bl->owner->ops->remove_location != NULL);
3892
3893       val = bl->owner->ops->remove_location (bl, reason);
3894       if (val)
3895         return val;
3896
3897       bl->inserted = (reason == DETACH_BREAKPOINT);
3898     }
3899
3900   return 0;
3901 }
3902
3903 static int
3904 remove_breakpoint (struct bp_location *bl)
3905 {
3906   /* BL is never in moribund_locations by our callers.  */
3907   gdb_assert (bl->owner != NULL);
3908
3909   /* The type of none suggests that owner is actually deleted.
3910      This should not ever happen.  */
3911   gdb_assert (bl->owner->type != bp_none);
3912
3913   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3914
3915   switch_to_program_space_and_thread (bl->pspace);
3916
3917   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3918 }
3919
3920 /* Clear the "inserted" flag in all breakpoints.  */
3921
3922 void
3923 mark_breakpoints_out (void)
3924 {
3925   for (bp_location *bl : all_bp_locations ())
3926     if (bl->pspace == current_program_space)
3927       bl->inserted = 0;
3928 }
3929
3930 /* Clear the "inserted" flag in all breakpoints and delete any
3931    breakpoints which should go away between runs of the program.
3932
3933    Plus other such housekeeping that has to be done for breakpoints
3934    between runs.
3935
3936    Note: this function gets called at the end of a run (by
3937    generic_mourn_inferior) and when a run begins (by
3938    init_wait_for_inferior).  */
3939
3940
3941
3942 void
3943 breakpoint_init_inferior (enum inf_context context)
3944 {
3945   struct program_space *pspace = current_program_space;
3946
3947   /* If breakpoint locations are shared across processes, then there's
3948      nothing to do.  */
3949   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3950     return;
3951
3952   mark_breakpoints_out ();
3953
3954   for (breakpoint *b : all_breakpoints_safe ())
3955     {
3956       if (b->loc && b->loc->pspace != pspace)
3957         continue;
3958
3959       switch (b->type)
3960         {
3961         case bp_call_dummy:
3962         case bp_longjmp_call_dummy:
3963
3964           /* If the call dummy breakpoint is at the entry point it will
3965              cause problems when the inferior is rerun, so we better get
3966              rid of it.  */
3967
3968         case bp_watchpoint_scope:
3969
3970           /* Also get rid of scope breakpoints.  */
3971
3972         case bp_shlib_event:
3973
3974           /* Also remove solib event breakpoints.  Their addresses may
3975              have changed since the last time we ran the program.
3976              Actually we may now be debugging against different target;
3977              and so the solib backend that installed this breakpoint may
3978              not be used in by the target.  E.g.,
3979
3980              (gdb) file prog-linux
3981              (gdb) run               # native linux target
3982              ...
3983              (gdb) kill
3984              (gdb) file prog-win.exe
3985              (gdb) tar rem :9999     # remote Windows gdbserver.
3986           */
3987
3988         case bp_step_resume:
3989
3990           /* Also remove step-resume breakpoints.  */
3991
3992         case bp_single_step:
3993
3994           /* Also remove single-step breakpoints.  */
3995
3996           delete_breakpoint (b);
3997           break;
3998
3999         case bp_watchpoint:
4000         case bp_hardware_watchpoint:
4001         case bp_read_watchpoint:
4002         case bp_access_watchpoint:
4003           {
4004             struct watchpoint *w = (struct watchpoint *) b;
4005
4006             /* Likewise for watchpoints on local expressions.  */
4007             if (w->exp_valid_block != NULL)
4008               delete_breakpoint (b);
4009             else
4010               {
4011                 /* Get rid of existing locations, which are no longer
4012                    valid.  New ones will be created in
4013                    update_watchpoint, when the inferior is restarted.
4014                    The next update_global_location_list call will
4015                    garbage collect them.  */
4016                 b->loc = NULL;
4017
4018                 if (context == inf_starting)
4019                   {
4020                     /* Reset val field to force reread of starting value in
4021                        insert_breakpoints.  */
4022                     w->val.reset (nullptr);
4023                     w->val_valid = false;
4024                   }
4025               }
4026           }
4027           break;
4028         default:
4029           break;
4030         }
4031     }
4032
4033   /* Get rid of the moribund locations.  */
4034   for (bp_location *bl : moribund_locations)
4035     decref_bp_location (&bl);
4036   moribund_locations.clear ();
4037 }
4038
4039 /* These functions concern about actual breakpoints inserted in the
4040    target --- to e.g. check if we need to do decr_pc adjustment or if
4041    we need to hop over the bkpt --- so we check for address space
4042    match, not program space.  */
4043
4044 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4045    exists at PC.  It returns ordinary_breakpoint_here if it's an
4046    ordinary breakpoint, or permanent_breakpoint_here if it's a
4047    permanent breakpoint.
4048    - When continuing from a location with an ordinary breakpoint, we
4049      actually single step once before calling insert_breakpoints.
4050    - When continuing from a location with a permanent breakpoint, we
4051      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4052      the target, to advance the PC past the breakpoint.  */
4053
4054 enum breakpoint_here
4055 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4056 {
4057   int any_breakpoint_here = 0;
4058
4059   for (bp_location *bl : all_bp_locations ())
4060     {
4061       if (bl->loc_type != bp_loc_software_breakpoint
4062           && bl->loc_type != bp_loc_hardware_breakpoint)
4063         continue;
4064
4065       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4066       if ((breakpoint_enabled (bl->owner)
4067            || bl->permanent)
4068           && breakpoint_location_address_match (bl, aspace, pc))
4069         {
4070           if (overlay_debugging 
4071               && section_is_overlay (bl->section)
4072               && !section_is_mapped (bl->section))
4073             continue;           /* unmapped overlay -- can't be a match */
4074           else if (bl->permanent)
4075             return permanent_breakpoint_here;
4076           else
4077             any_breakpoint_here = 1;
4078         }
4079     }
4080
4081   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4082 }
4083
4084 /* See breakpoint.h.  */
4085
4086 int
4087 breakpoint_in_range_p (const address_space *aspace,
4088                        CORE_ADDR addr, ULONGEST len)
4089 {
4090   for (bp_location *bl : all_bp_locations ())
4091     {
4092       if (bl->loc_type != bp_loc_software_breakpoint
4093           && bl->loc_type != bp_loc_hardware_breakpoint)
4094         continue;
4095
4096       if ((breakpoint_enabled (bl->owner)
4097            || bl->permanent)
4098           && breakpoint_location_address_range_overlap (bl, aspace,
4099                                                         addr, len))
4100         {
4101           if (overlay_debugging
4102               && section_is_overlay (bl->section)
4103               && !section_is_mapped (bl->section))
4104             {
4105               /* Unmapped overlay -- can't be a match.  */
4106               continue;
4107             }
4108
4109           return 1;
4110         }
4111     }
4112
4113   return 0;
4114 }
4115
4116 /* Return true if there's a moribund breakpoint at PC.  */
4117
4118 int
4119 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4120 {
4121   for (bp_location *loc : moribund_locations)
4122     if (breakpoint_location_address_match (loc, aspace, pc))
4123       return 1;
4124
4125   return 0;
4126 }
4127
4128 /* Returns non-zero iff BL is inserted at PC, in address space
4129    ASPACE.  */
4130
4131 static int
4132 bp_location_inserted_here_p (struct bp_location *bl,
4133                              const address_space *aspace, CORE_ADDR pc)
4134 {
4135   if (bl->inserted
4136       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4137                                    aspace, pc))
4138     {
4139       if (overlay_debugging
4140           && section_is_overlay (bl->section)
4141           && !section_is_mapped (bl->section))
4142         return 0;               /* unmapped overlay -- can't be a match */
4143       else
4144         return 1;
4145     }
4146   return 0;
4147 }
4148
4149 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4150
4151 int
4152 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4153 {
4154   for (bp_location *bl : all_bp_locations_at_addr (pc))
4155     {
4156       if (bl->loc_type != bp_loc_software_breakpoint
4157           && bl->loc_type != bp_loc_hardware_breakpoint)
4158         continue;
4159
4160       if (bp_location_inserted_here_p (bl, aspace, pc))
4161         return 1;
4162     }
4163   return 0;
4164 }
4165
4166 /* This function returns non-zero iff there is a software breakpoint
4167    inserted at PC.  */
4168
4169 int
4170 software_breakpoint_inserted_here_p (const address_space *aspace,
4171                                      CORE_ADDR pc)
4172 {
4173   for (bp_location *bl : all_bp_locations_at_addr (pc))
4174     {
4175       if (bl->loc_type != bp_loc_software_breakpoint)
4176         continue;
4177
4178       if (bp_location_inserted_here_p (bl, aspace, pc))
4179         return 1;
4180     }
4181
4182   return 0;
4183 }
4184
4185 /* See breakpoint.h.  */
4186
4187 int
4188 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4189                                      CORE_ADDR pc)
4190 {
4191   for (bp_location *bl : all_bp_locations_at_addr (pc))
4192     {
4193       if (bl->loc_type != bp_loc_hardware_breakpoint)
4194         continue;
4195
4196       if (bp_location_inserted_here_p (bl, aspace, pc))
4197         return 1;
4198     }
4199
4200   return 0;
4201 }
4202
4203 int
4204 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4205                                        CORE_ADDR addr, ULONGEST len)
4206 {
4207   for (breakpoint *bpt : all_breakpoints ())
4208     {
4209       if (bpt->type != bp_hardware_watchpoint
4210           && bpt->type != bp_access_watchpoint)
4211         continue;
4212
4213       if (!breakpoint_enabled (bpt))
4214         continue;
4215
4216       for (bp_location *loc : bpt->locations ())
4217         if (loc->pspace->aspace == aspace && loc->inserted)
4218           {
4219             CORE_ADDR l, h;
4220
4221             /* Check for intersection.  */
4222             l = std::max<CORE_ADDR> (loc->address, addr);
4223             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4224             if (l < h)
4225               return 1;
4226           }
4227     }
4228   return 0;
4229 }
4230
4231 /* See breakpoint.h.  */
4232
4233 bool
4234 is_catchpoint (struct breakpoint *b)
4235 {
4236   return (b->type == bp_catchpoint);
4237 }
4238
4239 /* Clear a bpstat so that it says we are not at any breakpoint.
4240    Also free any storage that is part of a bpstat.  */
4241
4242 void
4243 bpstat_clear (bpstat *bsp)
4244 {
4245   bpstat p;
4246   bpstat q;
4247
4248   if (bsp == 0)
4249     return;
4250   p = *bsp;
4251   while (p != NULL)
4252     {
4253       q = p->next;
4254       delete p;
4255       p = q;
4256     }
4257   *bsp = NULL;
4258 }
4259
4260 bpstats::bpstats (const bpstats &other)
4261   : next (NULL),
4262     bp_location_at (other.bp_location_at),
4263     breakpoint_at (other.breakpoint_at),
4264     commands (other.commands),
4265     print (other.print),
4266     stop (other.stop),
4267     print_it (other.print_it)
4268 {
4269   if (other.old_val != NULL)
4270     old_val = release_value (value_copy (other.old_val.get ()));
4271 }
4272
4273 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4274    is part of the bpstat is copied as well.  */
4275
4276 bpstat
4277 bpstat_copy (bpstat bs)
4278 {
4279   bpstat p = NULL;
4280   bpstat tmp;
4281   bpstat retval = NULL;
4282
4283   if (bs == NULL)
4284     return bs;
4285
4286   for (; bs != NULL; bs = bs->next)
4287     {
4288       tmp = new bpstats (*bs);
4289
4290       if (p == NULL)
4291         /* This is the first thing in the chain.  */
4292         retval = tmp;
4293       else
4294         p->next = tmp;
4295       p = tmp;
4296     }
4297   p->next = NULL;
4298   return retval;
4299 }
4300
4301 /* Find the bpstat associated with this breakpoint.  */
4302
4303 bpstat
4304 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4305 {
4306   if (bsp == NULL)
4307     return NULL;
4308
4309   for (; bsp != NULL; bsp = bsp->next)
4310     {
4311       if (bsp->breakpoint_at == breakpoint)
4312         return bsp;
4313     }
4314   return NULL;
4315 }
4316
4317 /* See breakpoint.h.  */
4318
4319 bool
4320 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4321 {
4322   for (; bsp != NULL; bsp = bsp->next)
4323     {
4324       if (bsp->breakpoint_at == NULL)
4325         {
4326           /* A moribund location can never explain a signal other than
4327              GDB_SIGNAL_TRAP.  */
4328           if (sig == GDB_SIGNAL_TRAP)
4329             return true;
4330         }
4331       else
4332         {
4333           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4334                                                         sig))
4335             return true;
4336         }
4337     }
4338
4339   return false;
4340 }
4341
4342 /* Put in *NUM the breakpoint number of the first breakpoint we are
4343    stopped at.  *BSP upon return is a bpstat which points to the
4344    remaining breakpoints stopped at (but which is not guaranteed to be
4345    good for anything but further calls to bpstat_num).
4346
4347    Return 0 if passed a bpstat which does not indicate any breakpoints.
4348    Return -1 if stopped at a breakpoint that has been deleted since
4349    we set it.
4350    Return 1 otherwise.  */
4351
4352 int
4353 bpstat_num (bpstat *bsp, int *num)
4354 {
4355   struct breakpoint *b;
4356
4357   if ((*bsp) == NULL)
4358     return 0;                   /* No more breakpoint values */
4359
4360   /* We assume we'll never have several bpstats that correspond to a
4361      single breakpoint -- otherwise, this function might return the
4362      same number more than once and this will look ugly.  */
4363   b = (*bsp)->breakpoint_at;
4364   *bsp = (*bsp)->next;
4365   if (b == NULL)
4366     return -1;                  /* breakpoint that's been deleted since */
4367
4368   *num = b->number;             /* We have its number */
4369   return 1;
4370 }
4371
4372 /* See breakpoint.h.  */
4373
4374 void
4375 bpstat_clear_actions (void)
4376 {
4377   bpstat bs;
4378
4379   if (inferior_ptid == null_ptid)
4380     return;
4381
4382   thread_info *tp = inferior_thread ();
4383   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4384     {
4385       bs->commands = NULL;
4386       bs->old_val.reset (nullptr);
4387     }
4388 }
4389
4390 /* Called when a command is about to proceed the inferior.  */
4391
4392 static void
4393 breakpoint_about_to_proceed (void)
4394 {
4395   if (inferior_ptid != null_ptid)
4396     {
4397       struct thread_info *tp = inferior_thread ();
4398
4399       /* Allow inferior function calls in breakpoint commands to not
4400          interrupt the command list.  When the call finishes
4401          successfully, the inferior will be standing at the same
4402          breakpoint as if nothing happened.  */
4403       if (tp->control.in_infcall)
4404         return;
4405     }
4406
4407   breakpoint_proceeded = 1;
4408 }
4409
4410 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4411    or its equivalent.  */
4412
4413 static int
4414 command_line_is_silent (struct command_line *cmd)
4415 {
4416   return cmd && (strcmp ("silent", cmd->line) == 0);
4417 }
4418
4419 /* Execute all the commands associated with all the breakpoints at
4420    this location.  Any of these commands could cause the process to
4421    proceed beyond this point, etc.  We look out for such changes by
4422    checking the global "breakpoint_proceeded" after each command.
4423
4424    Returns true if a breakpoint command resumed the inferior.  In that
4425    case, it is the caller's responsibility to recall it again with the
4426    bpstat of the current thread.  */
4427
4428 static int
4429 bpstat_do_actions_1 (bpstat *bsp)
4430 {
4431   bpstat bs;
4432   int again = 0;
4433
4434   /* Avoid endless recursion if a `source' command is contained
4435      in bs->commands.  */
4436   if (executing_breakpoint_commands)
4437     return 0;
4438
4439   scoped_restore save_executing
4440     = make_scoped_restore (&executing_breakpoint_commands, 1);
4441
4442   scoped_restore preventer = prevent_dont_repeat ();
4443
4444   /* This pointer will iterate over the list of bpstat's.  */
4445   bs = *bsp;
4446
4447   breakpoint_proceeded = 0;
4448   for (; bs != NULL; bs = bs->next)
4449     {
4450       struct command_line *cmd = NULL;
4451
4452       /* Take ownership of the BSP's command tree, if it has one.
4453
4454          The command tree could legitimately contain commands like
4455          'step' and 'next', which call clear_proceed_status, which
4456          frees stop_bpstat's command tree.  To make sure this doesn't
4457          free the tree we're executing out from under us, we need to
4458          take ownership of the tree ourselves.  Since a given bpstat's
4459          commands are only executed once, we don't need to copy it; we
4460          can clear the pointer in the bpstat, and make sure we free
4461          the tree when we're done.  */
4462       counted_command_line ccmd = bs->commands;
4463       bs->commands = NULL;
4464       if (ccmd != NULL)
4465         cmd = ccmd.get ();
4466       if (command_line_is_silent (cmd))
4467         {
4468           /* The action has been already done by bpstat_stop_status.  */
4469           cmd = cmd->next;
4470         }
4471
4472       while (cmd != NULL)
4473         {
4474           execute_control_command (cmd);
4475
4476           if (breakpoint_proceeded)
4477             break;
4478           else
4479             cmd = cmd->next;
4480         }
4481
4482       if (breakpoint_proceeded)
4483         {
4484           if (current_ui->async)
4485             /* If we are in async mode, then the target might be still
4486                running, not stopped at any breakpoint, so nothing for
4487                us to do here -- just return to the event loop.  */
4488             ;
4489           else
4490             /* In sync mode, when execute_control_command returns
4491                we're already standing on the next breakpoint.
4492                Breakpoint commands for that stop were not run, since
4493                execute_command does not run breakpoint commands --
4494                only command_line_handler does, but that one is not
4495                involved in execution of breakpoint commands.  So, we
4496                can now execute breakpoint commands.  It should be
4497                noted that making execute_command do bpstat actions is
4498                not an option -- in this case we'll have recursive
4499                invocation of bpstat for each breakpoint with a
4500                command, and can easily blow up GDB stack.  Instead, we
4501                return true, which will trigger the caller to recall us
4502                with the new stop_bpstat.  */
4503             again = 1;
4504           break;
4505         }
4506     }
4507   return again;
4508 }
4509
4510 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4511    one, is alive and has execution.  Return NULL otherwise.  */
4512
4513 static thread_info *
4514 get_bpstat_thread ()
4515 {
4516   if (inferior_ptid == null_ptid || !target_has_execution ())
4517     return NULL;
4518
4519   thread_info *tp = inferior_thread ();
4520   if (tp->state == THREAD_EXITED || tp->executing)
4521     return NULL;
4522   return tp;
4523 }
4524
4525 void
4526 bpstat_do_actions (void)
4527 {
4528   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4529   thread_info *tp;
4530
4531   /* Do any commands attached to breakpoint we are stopped at.  */
4532   while ((tp = get_bpstat_thread ()) != NULL)
4533     {
4534       /* Since in sync mode, bpstat_do_actions may resume the
4535          inferior, and only return when it is stopped at the next
4536          breakpoint, we keep doing breakpoint actions until it returns
4537          false to indicate the inferior was not resumed.  */
4538       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4539         break;
4540     }
4541
4542   cleanup_if_error.release ();
4543 }
4544
4545 /* Print out the (old or new) value associated with a watchpoint.  */
4546
4547 static void
4548 watchpoint_value_print (struct value *val, struct ui_file *stream)
4549 {
4550   if (val == NULL)
4551     fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4552   else
4553     {
4554       struct value_print_options opts;
4555       get_user_print_options (&opts);
4556       value_print (val, stream, &opts);
4557     }
4558 }
4559
4560 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4561    debugging multiple threads.  */
4562
4563 void
4564 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4565 {
4566   if (uiout->is_mi_like_p ())
4567     return;
4568
4569   uiout->text ("\n");
4570
4571   if (show_thread_that_caused_stop ())
4572     {
4573       const char *name;
4574       struct thread_info *thr = inferior_thread ();
4575
4576       uiout->text ("Thread ");
4577       uiout->field_string ("thread-id", print_thread_id (thr));
4578
4579       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4580       if (name != NULL)
4581         {
4582           uiout->text (" \"");
4583           uiout->field_string ("name", name);
4584           uiout->text ("\"");
4585         }
4586
4587       uiout->text (" hit ");
4588     }
4589 }
4590
4591 /* Generic routine for printing messages indicating why we
4592    stopped.  The behavior of this function depends on the value
4593    'print_it' in the bpstat structure.  Under some circumstances we
4594    may decide not to print anything here and delegate the task to
4595    normal_stop().  */
4596
4597 static enum print_stop_action
4598 print_bp_stop_message (bpstat bs)
4599 {
4600   switch (bs->print_it)
4601     {
4602     case print_it_noop:
4603       /* Nothing should be printed for this bpstat entry.  */
4604       return PRINT_UNKNOWN;
4605       break;
4606
4607     case print_it_done:
4608       /* We still want to print the frame, but we already printed the
4609          relevant messages.  */
4610       return PRINT_SRC_AND_LOC;
4611       break;
4612
4613     case print_it_normal:
4614       {
4615         struct breakpoint *b = bs->breakpoint_at;
4616
4617         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4618            which has since been deleted.  */
4619         if (b == NULL)
4620           return PRINT_UNKNOWN;
4621
4622         /* Normal case.  Call the breakpoint's print_it method.  */
4623         return b->ops->print_it (bs);
4624       }
4625       break;
4626
4627     default:
4628       internal_error (__FILE__, __LINE__,
4629                       _("print_bp_stop_message: unrecognized enum value"));
4630       break;
4631     }
4632 }
4633
4634 /* A helper function that prints a shared library stopped event.  */
4635
4636 static void
4637 print_solib_event (int is_catchpoint)
4638 {
4639   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4640   bool any_added = !current_program_space->added_solibs.empty ();
4641
4642   if (!is_catchpoint)
4643     {
4644       if (any_added || any_deleted)
4645         current_uiout->text (_("Stopped due to shared library event:\n"));
4646       else
4647         current_uiout->text (_("Stopped due to shared library event (no "
4648                                "libraries added or removed)\n"));
4649     }
4650
4651   if (current_uiout->is_mi_like_p ())
4652     current_uiout->field_string ("reason",
4653                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4654
4655   if (any_deleted)
4656     {
4657       current_uiout->text (_("  Inferior unloaded "));
4658       ui_out_emit_list list_emitter (current_uiout, "removed");
4659       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4660         {
4661           const std::string &name = current_program_space->deleted_solibs[ix];
4662
4663           if (ix > 0)
4664             current_uiout->text ("    ");
4665           current_uiout->field_string ("library", name);
4666           current_uiout->text ("\n");
4667         }
4668     }
4669
4670   if (any_added)
4671     {
4672       current_uiout->text (_("  Inferior loaded "));
4673       ui_out_emit_list list_emitter (current_uiout, "added");
4674       bool first = true;
4675       for (so_list *iter : current_program_space->added_solibs)
4676         {
4677           if (!first)
4678             current_uiout->text ("    ");
4679           first = false;
4680           current_uiout->field_string ("library", iter->so_name);
4681           current_uiout->text ("\n");
4682         }
4683     }
4684 }
4685
4686 /* Print a message indicating what happened.  This is called from
4687    normal_stop().  The input to this routine is the head of the bpstat
4688    list - a list of the eventpoints that caused this stop.  KIND is
4689    the target_waitkind for the stopping event.  This
4690    routine calls the generic print routine for printing a message
4691    about reasons for stopping.  This will print (for example) the
4692    "Breakpoint n," part of the output.  The return value of this
4693    routine is one of:
4694
4695    PRINT_UNKNOWN: Means we printed nothing.
4696    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4697    code to print the location.  An example is 
4698    "Breakpoint 1, " which should be followed by
4699    the location.
4700    PRINT_SRC_ONLY: Means we printed something, but there is no need
4701    to also print the location part of the message.
4702    An example is the catch/throw messages, which
4703    don't require a location appended to the end.
4704    PRINT_NOTHING: We have done some printing and we don't need any 
4705    further info to be printed.  */
4706
4707 enum print_stop_action
4708 bpstat_print (bpstat bs, int kind)
4709 {
4710   enum print_stop_action val;
4711
4712   /* Maybe another breakpoint in the chain caused us to stop.
4713      (Currently all watchpoints go on the bpstat whether hit or not.
4714      That probably could (should) be changed, provided care is taken
4715      with respect to bpstat_explains_signal).  */
4716   for (; bs; bs = bs->next)
4717     {
4718       val = print_bp_stop_message (bs);
4719       if (val == PRINT_SRC_ONLY 
4720           || val == PRINT_SRC_AND_LOC 
4721           || val == PRINT_NOTHING)
4722         return val;
4723     }
4724
4725   /* If we had hit a shared library event breakpoint,
4726      print_bp_stop_message would print out this message.  If we hit an
4727      OS-level shared library event, do the same thing.  */
4728   if (kind == TARGET_WAITKIND_LOADED)
4729     {
4730       print_solib_event (0);
4731       return PRINT_NOTHING;
4732     }
4733
4734   /* We reached the end of the chain, or we got a null BS to start
4735      with and nothing was printed.  */
4736   return PRINT_UNKNOWN;
4737 }
4738
4739 /* Evaluate the boolean expression EXP and return the result.  */
4740
4741 static bool
4742 breakpoint_cond_eval (expression *exp)
4743 {
4744   struct value *mark = value_mark ();
4745   bool res = value_true (evaluate_expression (exp));
4746
4747   value_free_to_mark (mark);
4748   return res;
4749 }
4750
4751 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4752
4753 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4754   : next (NULL),
4755     bp_location_at (bp_location_ref_ptr::new_reference (bl)),
4756     breakpoint_at (bl->owner),
4757     commands (NULL),
4758     print (0),
4759     stop (0),
4760     print_it (print_it_normal)
4761 {
4762   **bs_link_pointer = this;
4763   *bs_link_pointer = &next;
4764 }
4765
4766 bpstats::bpstats ()
4767   : next (NULL),
4768     breakpoint_at (NULL),
4769     commands (NULL),
4770     print (0),
4771     stop (0),
4772     print_it (print_it_normal)
4773 {
4774 }
4775 \f
4776 /* The target has stopped with waitstatus WS.  Check if any hardware
4777    watchpoints have triggered, according to the target.  */
4778
4779 int
4780 watchpoints_triggered (struct target_waitstatus *ws)
4781 {
4782   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4783   CORE_ADDR addr;
4784
4785   if (!stopped_by_watchpoint)
4786     {
4787       /* We were not stopped by a watchpoint.  Mark all watchpoints
4788          as not triggered.  */
4789       for (breakpoint *b : all_breakpoints ())
4790         if (is_hardware_watchpoint (b))
4791           {
4792             struct watchpoint *w = (struct watchpoint *) b;
4793
4794             w->watchpoint_triggered = watch_triggered_no;
4795           }
4796
4797       return 0;
4798     }
4799
4800   if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
4801     {
4802       /* We were stopped by a watchpoint, but we don't know where.
4803          Mark all watchpoints as unknown.  */
4804       for (breakpoint *b : all_breakpoints ())
4805         if (is_hardware_watchpoint (b))
4806           {
4807             struct watchpoint *w = (struct watchpoint *) b;
4808
4809             w->watchpoint_triggered = watch_triggered_unknown;
4810           }
4811
4812       return 1;
4813     }
4814
4815   /* The target could report the data address.  Mark watchpoints
4816      affected by this data address as triggered, and all others as not
4817      triggered.  */
4818
4819   for (breakpoint *b : all_breakpoints ())
4820     if (is_hardware_watchpoint (b))
4821       {
4822         struct watchpoint *w = (struct watchpoint *) b;
4823
4824         w->watchpoint_triggered = watch_triggered_no;
4825         for (bp_location *loc : b->locations ())
4826           {
4827             if (is_masked_watchpoint (b))
4828               {
4829                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4830                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4831
4832                 if (newaddr == start)
4833                   {
4834                     w->watchpoint_triggered = watch_triggered_yes;
4835                     break;
4836                   }
4837               }
4838             /* Exact match not required.  Within range is sufficient.  */
4839             else if (target_watchpoint_addr_within_range
4840                        (current_inferior ()->top_target (), addr, loc->address,
4841                         loc->length))
4842               {
4843                 w->watchpoint_triggered = watch_triggered_yes;
4844                 break;
4845               }
4846           }
4847       }
4848
4849   return 1;
4850 }
4851
4852 /* Possible return values for watchpoint_check.  */
4853 enum wp_check_result
4854   {
4855     /* The watchpoint has been deleted.  */
4856     WP_DELETED = 1,
4857
4858     /* The value has changed.  */
4859     WP_VALUE_CHANGED = 2,
4860
4861     /* The value has not changed.  */
4862     WP_VALUE_NOT_CHANGED = 3,
4863
4864     /* Ignore this watchpoint, no matter if the value changed or not.  */
4865     WP_IGNORE = 4,
4866   };
4867
4868 #define BP_TEMPFLAG 1
4869 #define BP_HARDWAREFLAG 2
4870
4871 /* Evaluate watchpoint condition expression and check if its value
4872    changed.  */
4873
4874 static wp_check_result
4875 watchpoint_check (bpstat bs)
4876 {
4877   struct watchpoint *b;
4878   struct frame_info *fr;
4879   int within_current_scope;
4880
4881   /* BS is built from an existing struct breakpoint.  */
4882   gdb_assert (bs->breakpoint_at != NULL);
4883   b = (struct watchpoint *) bs->breakpoint_at;
4884
4885   /* If this is a local watchpoint, we only want to check if the
4886      watchpoint frame is in scope if the current thread is the thread
4887      that was used to create the watchpoint.  */
4888   if (!watchpoint_in_thread_scope (b))
4889     return WP_IGNORE;
4890
4891   if (b->exp_valid_block == NULL)
4892     within_current_scope = 1;
4893   else
4894     {
4895       struct frame_info *frame = get_current_frame ();
4896       struct gdbarch *frame_arch = get_frame_arch (frame);
4897       CORE_ADDR frame_pc = get_frame_pc (frame);
4898
4899       /* stack_frame_destroyed_p() returns a non-zero value if we're
4900          still in the function but the stack frame has already been
4901          invalidated.  Since we can't rely on the values of local
4902          variables after the stack has been destroyed, we are treating
4903          the watchpoint in that state as `not changed' without further
4904          checking.  Don't mark watchpoints as changed if the current
4905          frame is in an epilogue - even if they are in some other
4906          frame, our view of the stack is likely to be wrong and
4907          frame_find_by_id could error out.  */
4908       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4909         return WP_IGNORE;
4910
4911       fr = frame_find_by_id (b->watchpoint_frame);
4912       within_current_scope = (fr != NULL);
4913
4914       /* If we've gotten confused in the unwinder, we might have
4915          returned a frame that can't describe this variable.  */
4916       if (within_current_scope)
4917         {
4918           struct symbol *function;
4919
4920           function = get_frame_function (fr);
4921           if (function == NULL
4922               || !contained_in (b->exp_valid_block,
4923                                 SYMBOL_BLOCK_VALUE (function)))
4924             within_current_scope = 0;
4925         }
4926
4927       if (within_current_scope)
4928         /* If we end up stopping, the current frame will get selected
4929            in normal_stop.  So this call to select_frame won't affect
4930            the user.  */
4931         select_frame (fr);
4932     }
4933
4934   if (within_current_scope)
4935     {
4936       /* We use value_{,free_to_}mark because it could be a *long*
4937          time before we return to the command level and call
4938          free_all_values.  We can't call free_all_values because we
4939          might be in the middle of evaluating a function call.  */
4940
4941       struct value *mark;
4942       struct value *new_val;
4943
4944       if (is_masked_watchpoint (b))
4945         /* Since we don't know the exact trigger address (from
4946            stopped_data_address), just tell the user we've triggered
4947            a mask watchpoint.  */
4948         return WP_VALUE_CHANGED;
4949
4950       mark = value_mark ();
4951       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
4952                           NULL, NULL, false);
4953
4954       if (b->val_bitsize != 0)
4955         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4956
4957       /* We use value_equal_contents instead of value_equal because
4958          the latter coerces an array to a pointer, thus comparing just
4959          the address of the array instead of its contents.  This is
4960          not what we want.  */
4961       if ((b->val != NULL) != (new_val != NULL)
4962           || (b->val != NULL && !value_equal_contents (b->val.get (),
4963                                                        new_val)))
4964         {
4965           bs->old_val = b->val;
4966           b->val = release_value (new_val);
4967           b->val_valid = true;
4968           if (new_val != NULL)
4969             value_free_to_mark (mark);
4970           return WP_VALUE_CHANGED;
4971         }
4972       else
4973         {
4974           /* Nothing changed.  */
4975           value_free_to_mark (mark);
4976           return WP_VALUE_NOT_CHANGED;
4977         }
4978     }
4979   else
4980     {
4981       /* This seems like the only logical thing to do because
4982          if we temporarily ignored the watchpoint, then when
4983          we reenter the block in which it is valid it contains
4984          garbage (in the case of a function, it may have two
4985          garbage values, one before and one after the prologue).
4986          So we can't even detect the first assignment to it and
4987          watch after that (since the garbage may or may not equal
4988          the first value assigned).  */
4989       /* We print all the stop information in
4990          breakpoint_ops->print_it, but in this case, by the time we
4991          call breakpoint_ops->print_it this bp will be deleted
4992          already.  So we have no choice but print the information
4993          here.  */
4994
4995       SWITCH_THRU_ALL_UIS ()
4996         {
4997           struct ui_out *uiout = current_uiout;
4998
4999           if (uiout->is_mi_like_p ())
5000             uiout->field_string
5001               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5002           uiout->message ("\nWatchpoint %pF deleted because the program has "
5003                           "left the block in\n"
5004                           "which its expression is valid.\n",
5005                           signed_field ("wpnum", b->number));
5006         }
5007
5008       /* Make sure the watchpoint's commands aren't executed.  */
5009       b->commands = NULL;
5010       watchpoint_del_at_next_stop (b);
5011
5012       return WP_DELETED;
5013     }
5014 }
5015
5016 /* Return true if it looks like target has stopped due to hitting
5017    breakpoint location BL.  This function does not check if we should
5018    stop, only if BL explains the stop.  */
5019
5020 static int
5021 bpstat_check_location (const struct bp_location *bl,
5022                        const address_space *aspace, CORE_ADDR bp_addr,
5023                        const struct target_waitstatus *ws)
5024 {
5025   struct breakpoint *b = bl->owner;
5026
5027   /* BL is from an existing breakpoint.  */
5028   gdb_assert (b != NULL);
5029
5030   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5031 }
5032
5033 /* Determine if the watched values have actually changed, and we
5034    should stop.  If not, set BS->stop to 0.  */
5035
5036 static void
5037 bpstat_check_watchpoint (bpstat bs)
5038 {
5039   const struct bp_location *bl;
5040   struct watchpoint *b;
5041
5042   /* BS is built for existing struct breakpoint.  */
5043   bl = bs->bp_location_at.get ();
5044   gdb_assert (bl != NULL);
5045   b = (struct watchpoint *) bs->breakpoint_at;
5046   gdb_assert (b != NULL);
5047
5048     {
5049       int must_check_value = 0;
5050       
5051       if (b->type == bp_watchpoint)
5052         /* For a software watchpoint, we must always check the
5053            watched value.  */
5054         must_check_value = 1;
5055       else if (b->watchpoint_triggered == watch_triggered_yes)
5056         /* We have a hardware watchpoint (read, write, or access)
5057            and the target earlier reported an address watched by
5058            this watchpoint.  */
5059         must_check_value = 1;
5060       else if (b->watchpoint_triggered == watch_triggered_unknown
5061                && b->type == bp_hardware_watchpoint)
5062         /* We were stopped by a hardware watchpoint, but the target could
5063            not report the data address.  We must check the watchpoint's
5064            value.  Access and read watchpoints are out of luck; without
5065            a data address, we can't figure it out.  */
5066         must_check_value = 1;
5067
5068       if (must_check_value)
5069         {
5070           wp_check_result e;
5071
5072           try
5073             {
5074               e = watchpoint_check (bs);
5075             }
5076           catch (const gdb_exception &ex)
5077             {
5078               exception_fprintf (gdb_stderr, ex,
5079                                  "Error evaluating expression "
5080                                  "for watchpoint %d\n",
5081                                  b->number);
5082
5083               SWITCH_THRU_ALL_UIS ()
5084                 {
5085                   printf_filtered (_("Watchpoint %d deleted.\n"),
5086                                    b->number);
5087                 }
5088               watchpoint_del_at_next_stop (b);
5089               e = WP_DELETED;
5090             }
5091
5092           switch (e)
5093             {
5094             case WP_DELETED:
5095               /* We've already printed what needs to be printed.  */
5096               bs->print_it = print_it_done;
5097               /* Stop.  */
5098               break;
5099             case WP_IGNORE:
5100               bs->print_it = print_it_noop;
5101               bs->stop = 0;
5102               break;
5103             case WP_VALUE_CHANGED:
5104               if (b->type == bp_read_watchpoint)
5105                 {
5106                   /* There are two cases to consider here:
5107
5108                      1. We're watching the triggered memory for reads.
5109                      In that case, trust the target, and always report
5110                      the watchpoint hit to the user.  Even though
5111                      reads don't cause value changes, the value may
5112                      have changed since the last time it was read, and
5113                      since we're not trapping writes, we will not see
5114                      those, and as such we should ignore our notion of
5115                      old value.
5116
5117                      2. We're watching the triggered memory for both
5118                      reads and writes.  There are two ways this may
5119                      happen:
5120
5121                      2.1. This is a target that can't break on data
5122                      reads only, but can break on accesses (reads or
5123                      writes), such as e.g., x86.  We detect this case
5124                      at the time we try to insert read watchpoints.
5125
5126                      2.2. Otherwise, the target supports read
5127                      watchpoints, but, the user set an access or write
5128                      watchpoint watching the same memory as this read
5129                      watchpoint.
5130
5131                      If we're watching memory writes as well as reads,
5132                      ignore watchpoint hits when we find that the
5133                      value hasn't changed, as reads don't cause
5134                      changes.  This still gives false positives when
5135                      the program writes the same value to memory as
5136                      what there was already in memory (we will confuse
5137                      it for a read), but it's much better than
5138                      nothing.  */
5139
5140                   int other_write_watchpoint = 0;
5141
5142                   if (bl->watchpoint_type == hw_read)
5143                     {
5144                       for (breakpoint *other_b : all_breakpoints ())
5145                         if (other_b->type == bp_hardware_watchpoint
5146                             || other_b->type == bp_access_watchpoint)
5147                           {
5148                             struct watchpoint *other_w =
5149                               (struct watchpoint *) other_b;
5150
5151                             if (other_w->watchpoint_triggered
5152                                 == watch_triggered_yes)
5153                               {
5154                                 other_write_watchpoint = 1;
5155                                 break;
5156                               }
5157                           }
5158                     }
5159
5160                   if (other_write_watchpoint
5161                       || bl->watchpoint_type == hw_access)
5162                     {
5163                       /* We're watching the same memory for writes,
5164                          and the value changed since the last time we
5165                          updated it, so this trap must be for a write.
5166                          Ignore it.  */
5167                       bs->print_it = print_it_noop;
5168                       bs->stop = 0;
5169                     }
5170                 }
5171               break;
5172             case WP_VALUE_NOT_CHANGED:
5173               if (b->type == bp_hardware_watchpoint
5174                   || b->type == bp_watchpoint)
5175                 {
5176                   /* Don't stop: write watchpoints shouldn't fire if
5177                      the value hasn't changed.  */
5178                   bs->print_it = print_it_noop;
5179                   bs->stop = 0;
5180                 }
5181               /* Stop.  */
5182               break;
5183             default:
5184               /* Can't happen.  */
5185               break;
5186             }
5187         }
5188       else      /* must_check_value == 0 */
5189         {
5190           /* This is a case where some watchpoint(s) triggered, but
5191              not at the address of this watchpoint, or else no
5192              watchpoint triggered after all.  So don't print
5193              anything for this watchpoint.  */
5194           bs->print_it = print_it_noop;
5195           bs->stop = 0;
5196         }
5197     }
5198 }
5199
5200 /* For breakpoints that are currently marked as telling gdb to stop,
5201    check conditions (condition proper, frame, thread and ignore count)
5202    of breakpoint referred to by BS.  If we should not stop for this
5203    breakpoint, set BS->stop to 0.  */
5204
5205 static void
5206 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5207 {
5208   const struct bp_location *bl;
5209   struct breakpoint *b;
5210   /* Assume stop.  */
5211   bool condition_result = true;
5212   struct expression *cond;
5213
5214   gdb_assert (bs->stop);
5215
5216   /* BS is built for existing struct breakpoint.  */
5217   bl = bs->bp_location_at.get ();
5218   gdb_assert (bl != NULL);
5219   b = bs->breakpoint_at;
5220   gdb_assert (b != NULL);
5221
5222   /* Even if the target evaluated the condition on its end and notified GDB, we
5223      need to do so again since GDB does not know if we stopped due to a
5224      breakpoint or a single step breakpoint.  */
5225
5226   if (frame_id_p (b->frame_id)
5227       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5228     {
5229       bs->stop = 0;
5230       return;
5231     }
5232
5233   /* If this is a thread/task-specific breakpoint, don't waste cpu
5234      evaluating the condition if this isn't the specified
5235      thread/task.  */
5236   if ((b->thread != -1 && b->thread != thread->global_num)
5237       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5238     {
5239       bs->stop = 0;
5240       return;
5241     }
5242
5243   /* Evaluate extension language breakpoints that have a "stop" method
5244      implemented.  */
5245   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5246
5247   if (is_watchpoint (b))
5248     {
5249       struct watchpoint *w = (struct watchpoint *) b;
5250
5251       cond = w->cond_exp.get ();
5252     }
5253   else
5254     cond = bl->cond.get ();
5255
5256   if (cond && b->disposition != disp_del_at_next_stop)
5257     {
5258       int within_current_scope = 1;
5259       struct watchpoint * w;
5260
5261       /* We use value_mark and value_free_to_mark because it could
5262          be a long time before we return to the command level and
5263          call free_all_values.  We can't call free_all_values
5264          because we might be in the middle of evaluating a
5265          function call.  */
5266       struct value *mark = value_mark ();
5267
5268       if (is_watchpoint (b))
5269         w = (struct watchpoint *) b;
5270       else
5271         w = NULL;
5272
5273       /* Need to select the frame, with all that implies so that
5274          the conditions will have the right context.  Because we
5275          use the frame, we will not see an inlined function's
5276          variables when we arrive at a breakpoint at the start
5277          of the inlined function; the current frame will be the
5278          call site.  */
5279       if (w == NULL || w->cond_exp_valid_block == NULL)
5280         select_frame (get_current_frame ());
5281       else
5282         {
5283           struct frame_info *frame;
5284
5285           /* For local watchpoint expressions, which particular
5286              instance of a local is being watched matters, so we
5287              keep track of the frame to evaluate the expression
5288              in.  To evaluate the condition however, it doesn't
5289              really matter which instantiation of the function
5290              where the condition makes sense triggers the
5291              watchpoint.  This allows an expression like "watch
5292              global if q > 10" set in `func', catch writes to
5293              global on all threads that call `func', or catch
5294              writes on all recursive calls of `func' by a single
5295              thread.  We simply always evaluate the condition in
5296              the innermost frame that's executing where it makes
5297              sense to evaluate the condition.  It seems
5298              intuitive.  */
5299           frame = block_innermost_frame (w->cond_exp_valid_block);
5300           if (frame != NULL)
5301             select_frame (frame);
5302           else
5303             within_current_scope = 0;
5304         }
5305       if (within_current_scope)
5306         {
5307           try
5308             {
5309               condition_result = breakpoint_cond_eval (cond);
5310             }
5311           catch (const gdb_exception &ex)
5312             {
5313               exception_fprintf (gdb_stderr, ex,
5314                                  "Error in testing breakpoint condition:\n");
5315             }
5316         }
5317       else
5318         {
5319           warning (_("Watchpoint condition cannot be tested "
5320                      "in the current scope"));
5321           /* If we failed to set the right context for this
5322              watchpoint, unconditionally report it.  */
5323         }
5324       /* FIXME-someday, should give breakpoint #.  */
5325       value_free_to_mark (mark);
5326     }
5327
5328   if (cond && !condition_result)
5329     {
5330       bs->stop = 0;
5331     }
5332   else if (b->ignore_count > 0)
5333     {
5334       b->ignore_count--;
5335       bs->stop = 0;
5336       /* Increase the hit count even though we don't stop.  */
5337       ++(b->hit_count);
5338       gdb::observers::breakpoint_modified.notify (b);
5339     }   
5340 }
5341
5342 /* Returns true if we need to track moribund locations of LOC's type
5343    on the current target.  */
5344
5345 static int
5346 need_moribund_for_location_type (struct bp_location *loc)
5347 {
5348   return ((loc->loc_type == bp_loc_software_breakpoint
5349            && !target_supports_stopped_by_sw_breakpoint ())
5350           || (loc->loc_type == bp_loc_hardware_breakpoint
5351               && !target_supports_stopped_by_hw_breakpoint ()));
5352 }
5353
5354 /* See breakpoint.h.  */
5355
5356 bpstat
5357 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5358                     const struct target_waitstatus *ws)
5359 {
5360   bpstat bs_head = NULL, *bs_link = &bs_head;
5361
5362   for (breakpoint *b : all_breakpoints ())
5363     {
5364       if (!breakpoint_enabled (b))
5365         continue;
5366
5367       for (bp_location *bl : b->locations ())
5368         {
5369           /* For hardware watchpoints, we look only at the first
5370              location.  The watchpoint_check function will work on the
5371              entire expression, not the individual locations.  For
5372              read watchpoints, the watchpoints_triggered function has
5373              checked all locations already.  */
5374           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5375             break;
5376
5377           if (!bl->enabled || bl->disabled_by_cond || bl->shlib_disabled)
5378             continue;
5379
5380           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5381             continue;
5382
5383           /* Come here if it's a watchpoint, or if the break address
5384              matches.  */
5385
5386           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5387                                                            explain stop.  */
5388
5389           /* Assume we stop.  Should we find a watchpoint that is not
5390              actually triggered, or if the condition of the breakpoint
5391              evaluates as false, we'll reset 'stop' to 0.  */
5392           bs->stop = 1;
5393           bs->print = 1;
5394
5395           /* If this is a scope breakpoint, mark the associated
5396              watchpoint as triggered so that we will handle the
5397              out-of-scope event.  We'll get to the watchpoint next
5398              iteration.  */
5399           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5400             {
5401               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5402
5403               w->watchpoint_triggered = watch_triggered_yes;
5404             }
5405         }
5406     }
5407
5408   /* Check if a moribund breakpoint explains the stop.  */
5409   if (!target_supports_stopped_by_sw_breakpoint ()
5410       || !target_supports_stopped_by_hw_breakpoint ())
5411     {
5412       for (bp_location *loc : moribund_locations)
5413         {
5414           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5415               && need_moribund_for_location_type (loc))
5416             {
5417               bpstat bs = new bpstats (loc, &bs_link);
5418               /* For hits of moribund locations, we should just proceed.  */
5419               bs->stop = 0;
5420               bs->print = 0;
5421               bs->print_it = print_it_noop;
5422             }
5423         }
5424     }
5425
5426   return bs_head;
5427 }
5428
5429 /* See breakpoint.h.  */
5430
5431 bpstat
5432 bpstat_stop_status (const address_space *aspace,
5433                     CORE_ADDR bp_addr, thread_info *thread,
5434                     const struct target_waitstatus *ws,
5435                     bpstat stop_chain)
5436 {
5437   struct breakpoint *b = NULL;
5438   /* First item of allocated bpstat's.  */
5439   bpstat bs_head = stop_chain;
5440   bpstat bs;
5441   int need_remove_insert;
5442   int removed_any;
5443
5444   /* First, build the bpstat chain with locations that explain a
5445      target stop, while being careful to not set the target running,
5446      as that may invalidate locations (in particular watchpoint
5447      locations are recreated).  Resuming will happen here with
5448      breakpoint conditions or watchpoint expressions that include
5449      inferior function calls.  */
5450   if (bs_head == NULL)
5451     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5452
5453   /* A bit of special processing for shlib breakpoints.  We need to
5454      process solib loading here, so that the lists of loaded and
5455      unloaded libraries are correct before we handle "catch load" and
5456      "catch unload".  */
5457   for (bs = bs_head; bs != NULL; bs = bs->next)
5458     {
5459       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5460         {
5461           handle_solib_event ();
5462           break;
5463         }
5464     }
5465
5466   /* Now go through the locations that caused the target to stop, and
5467      check whether we're interested in reporting this stop to higher
5468      layers, or whether we should resume the target transparently.  */
5469
5470   removed_any = 0;
5471
5472   for (bs = bs_head; bs != NULL; bs = bs->next)
5473     {
5474       if (!bs->stop)
5475         continue;
5476
5477       b = bs->breakpoint_at;
5478       b->ops->check_status (bs);
5479       if (bs->stop)
5480         {
5481           bpstat_check_breakpoint_conditions (bs, thread);
5482
5483           if (bs->stop)
5484             {
5485               ++(b->hit_count);
5486               gdb::observers::breakpoint_modified.notify (b);
5487
5488               /* We will stop here.  */
5489               if (b->disposition == disp_disable)
5490                 {
5491                   --(b->enable_count);
5492                   if (b->enable_count <= 0)
5493                     b->enable_state = bp_disabled;
5494                   removed_any = 1;
5495                 }
5496               if (b->silent)
5497                 bs->print = 0;
5498               bs->commands = b->commands;
5499               if (command_line_is_silent (bs->commands
5500                                           ? bs->commands.get () : NULL))
5501                 bs->print = 0;
5502
5503               b->ops->after_condition_true (bs);
5504             }
5505
5506         }
5507
5508       /* Print nothing for this entry if we don't stop or don't
5509          print.  */
5510       if (!bs->stop || !bs->print)
5511         bs->print_it = print_it_noop;
5512     }
5513
5514   /* If we aren't stopping, the value of some hardware watchpoint may
5515      not have changed, but the intermediate memory locations we are
5516      watching may have.  Don't bother if we're stopping; this will get
5517      done later.  */
5518   need_remove_insert = 0;
5519   if (! bpstat_causes_stop (bs_head))
5520     for (bs = bs_head; bs != NULL; bs = bs->next)
5521       if (!bs->stop
5522           && bs->breakpoint_at
5523           && is_hardware_watchpoint (bs->breakpoint_at))
5524         {
5525           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5526
5527           update_watchpoint (w, 0 /* don't reparse.  */);
5528           need_remove_insert = 1;
5529         }
5530
5531   if (need_remove_insert)
5532     update_global_location_list (UGLL_MAY_INSERT);
5533   else if (removed_any)
5534     update_global_location_list (UGLL_DONT_INSERT);
5535
5536   return bs_head;
5537 }
5538
5539 static void
5540 handle_jit_event (CORE_ADDR address)
5541 {
5542   struct gdbarch *gdbarch;
5543
5544   infrun_debug_printf ("handling bp_jit_event");
5545
5546   /* Switch terminal for any messages produced by
5547      breakpoint_re_set.  */
5548   target_terminal::ours_for_output ();
5549
5550   gdbarch = get_frame_arch (get_current_frame ());
5551   /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5552      thus it is expected that its objectfile can be found through
5553      minimal symbol lookup.  If it doesn't work (and assert fails), it
5554      most likely means that `jit_breakpoint_re_set` was changes and this
5555      function needs to be updated too.  */
5556   bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5557   gdb_assert (jit_bp_sym.objfile != nullptr);
5558   jit_event_handler (gdbarch, jit_bp_sym.objfile);
5559
5560   target_terminal::inferior ();
5561 }
5562
5563 /* Prepare WHAT final decision for infrun.  */
5564
5565 /* Decide what infrun needs to do with this bpstat.  */
5566
5567 struct bpstat_what
5568 bpstat_what (bpstat bs_head)
5569 {
5570   struct bpstat_what retval;
5571   bpstat bs;
5572
5573   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5574   retval.call_dummy = STOP_NONE;
5575   retval.is_longjmp = false;
5576
5577   for (bs = bs_head; bs != NULL; bs = bs->next)
5578     {
5579       /* Extract this BS's action.  After processing each BS, we check
5580          if its action overrides all we've seem so far.  */
5581       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5582       enum bptype bptype;
5583
5584       if (bs->breakpoint_at == NULL)
5585         {
5586           /* I suspect this can happen if it was a momentary
5587              breakpoint which has since been deleted.  */
5588           bptype = bp_none;
5589         }
5590       else
5591         bptype = bs->breakpoint_at->type;
5592
5593       switch (bptype)
5594         {
5595         case bp_none:
5596           break;
5597         case bp_breakpoint:
5598         case bp_hardware_breakpoint:
5599         case bp_single_step:
5600         case bp_until:
5601         case bp_finish:
5602         case bp_shlib_event:
5603           if (bs->stop)
5604             {
5605               if (bs->print)
5606                 this_action = BPSTAT_WHAT_STOP_NOISY;
5607               else
5608                 this_action = BPSTAT_WHAT_STOP_SILENT;
5609             }
5610           else
5611             this_action = BPSTAT_WHAT_SINGLE;
5612           break;
5613         case bp_watchpoint:
5614         case bp_hardware_watchpoint:
5615         case bp_read_watchpoint:
5616         case bp_access_watchpoint:
5617           if (bs->stop)
5618             {
5619               if (bs->print)
5620                 this_action = BPSTAT_WHAT_STOP_NOISY;
5621               else
5622                 this_action = BPSTAT_WHAT_STOP_SILENT;
5623             }
5624           else
5625             {
5626               /* There was a watchpoint, but we're not stopping.
5627                  This requires no further action.  */
5628             }
5629           break;
5630         case bp_longjmp:
5631         case bp_longjmp_call_dummy:
5632         case bp_exception:
5633           if (bs->stop)
5634             {
5635               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5636               retval.is_longjmp = bptype != bp_exception;
5637             }
5638           else
5639             this_action = BPSTAT_WHAT_SINGLE;
5640           break;
5641         case bp_longjmp_resume:
5642         case bp_exception_resume:
5643           if (bs->stop)
5644             {
5645               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5646               retval.is_longjmp = bptype == bp_longjmp_resume;
5647             }
5648           else
5649             this_action = BPSTAT_WHAT_SINGLE;
5650           break;
5651         case bp_step_resume:
5652           if (bs->stop)
5653             this_action = BPSTAT_WHAT_STEP_RESUME;
5654           else
5655             {
5656               /* It is for the wrong frame.  */
5657               this_action = BPSTAT_WHAT_SINGLE;
5658             }
5659           break;
5660         case bp_hp_step_resume:
5661           if (bs->stop)
5662             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5663           else
5664             {
5665               /* It is for the wrong frame.  */
5666               this_action = BPSTAT_WHAT_SINGLE;
5667             }
5668           break;
5669         case bp_watchpoint_scope:
5670         case bp_thread_event:
5671         case bp_overlay_event:
5672         case bp_longjmp_master:
5673         case bp_std_terminate_master:
5674         case bp_exception_master:
5675           this_action = BPSTAT_WHAT_SINGLE;
5676           break;
5677         case bp_catchpoint:
5678           if (bs->stop)
5679             {
5680               if (bs->print)
5681                 this_action = BPSTAT_WHAT_STOP_NOISY;
5682               else
5683                 this_action = BPSTAT_WHAT_STOP_SILENT;
5684             }
5685           else
5686             {
5687               /* Some catchpoints are implemented with breakpoints.
5688                  For those, we need to step over the breakpoint.  */
5689               if (bs->bp_location_at->loc_type != bp_loc_other)
5690                 this_action = BPSTAT_WHAT_SINGLE;
5691             }
5692           break;
5693         case bp_jit_event:
5694           this_action = BPSTAT_WHAT_SINGLE;
5695           break;
5696         case bp_call_dummy:
5697           /* Make sure the action is stop (silent or noisy),
5698              so infrun.c pops the dummy frame.  */
5699           retval.call_dummy = STOP_STACK_DUMMY;
5700           this_action = BPSTAT_WHAT_STOP_SILENT;
5701           break;
5702         case bp_std_terminate:
5703           /* Make sure the action is stop (silent or noisy),
5704              so infrun.c pops the dummy frame.  */
5705           retval.call_dummy = STOP_STD_TERMINATE;
5706           this_action = BPSTAT_WHAT_STOP_SILENT;
5707           break;
5708         case bp_tracepoint:
5709         case bp_fast_tracepoint:
5710         case bp_static_tracepoint:
5711           /* Tracepoint hits should not be reported back to GDB, and
5712              if one got through somehow, it should have been filtered
5713              out already.  */
5714           internal_error (__FILE__, __LINE__,
5715                           _("bpstat_what: tracepoint encountered"));
5716           break;
5717         case bp_gnu_ifunc_resolver:
5718           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5719           this_action = BPSTAT_WHAT_SINGLE;
5720           break;
5721         case bp_gnu_ifunc_resolver_return:
5722           /* The breakpoint will be removed, execution will restart from the
5723              PC of the former breakpoint.  */
5724           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5725           break;
5726
5727         case bp_dprintf:
5728           if (bs->stop)
5729             this_action = BPSTAT_WHAT_STOP_SILENT;
5730           else
5731             this_action = BPSTAT_WHAT_SINGLE;
5732           break;
5733
5734         default:
5735           internal_error (__FILE__, __LINE__,
5736                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5737         }
5738
5739       retval.main_action = std::max (retval.main_action, this_action);
5740     }
5741
5742   return retval;
5743 }
5744
5745 void
5746 bpstat_run_callbacks (bpstat bs_head)
5747 {
5748   bpstat bs;
5749
5750   for (bs = bs_head; bs != NULL; bs = bs->next)
5751     {
5752       struct breakpoint *b = bs->breakpoint_at;
5753
5754       if (b == NULL)
5755         continue;
5756       switch (b->type)
5757         {
5758         case bp_jit_event:
5759           handle_jit_event (bs->bp_location_at->address);
5760           break;
5761         case bp_gnu_ifunc_resolver:
5762           gnu_ifunc_resolver_stop (b);
5763           break;
5764         case bp_gnu_ifunc_resolver_return:
5765           gnu_ifunc_resolver_return_stop (b);
5766           break;
5767         }
5768     }
5769 }
5770
5771 /* See breakpoint.h.  */
5772
5773 bool
5774 bpstat_should_step ()
5775 {
5776   for (breakpoint *b : all_breakpoints ())
5777     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5778       return true;
5779
5780   return false;
5781 }
5782
5783 /* See breakpoint.h.  */
5784
5785 bool
5786 bpstat_causes_stop (bpstat bs)
5787 {
5788   for (; bs != NULL; bs = bs->next)
5789     if (bs->stop)
5790       return true;
5791
5792   return false;
5793 }
5794
5795 \f
5796
5797 /* Compute a string of spaces suitable to indent the next line
5798    so it starts at the position corresponding to the table column
5799    named COL_NAME in the currently active table of UIOUT.  */
5800
5801 static char *
5802 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5803 {
5804   static char wrap_indent[80];
5805   int i, total_width, width, align;
5806   const char *text;
5807
5808   total_width = 0;
5809   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5810     {
5811       if (strcmp (text, col_name) == 0)
5812         {
5813           gdb_assert (total_width < sizeof wrap_indent);
5814           memset (wrap_indent, ' ', total_width);
5815           wrap_indent[total_width] = 0;
5816
5817           return wrap_indent;
5818         }
5819
5820       total_width += width + 1;
5821     }
5822
5823   return NULL;
5824 }
5825
5826 /* Determine if the locations of this breakpoint will have their conditions
5827    evaluated by the target, host or a mix of both.  Returns the following:
5828
5829     "host": Host evals condition.
5830     "host or target": Host or Target evals condition.
5831     "target": Target evals condition.
5832 */
5833
5834 static const char *
5835 bp_condition_evaluator (struct breakpoint *b)
5836 {
5837   char host_evals = 0;
5838   char target_evals = 0;
5839
5840   if (!b)
5841     return NULL;
5842
5843   if (!is_breakpoint (b))
5844     return NULL;
5845
5846   if (gdb_evaluates_breakpoint_condition_p ()
5847       || !target_supports_evaluation_of_breakpoint_conditions ())
5848     return condition_evaluation_host;
5849
5850   for (bp_location *bl : b->locations ())
5851     {
5852       if (bl->cond_bytecode)
5853         target_evals++;
5854       else
5855         host_evals++;
5856     }
5857
5858   if (host_evals && target_evals)
5859     return condition_evaluation_both;
5860   else if (target_evals)
5861     return condition_evaluation_target;
5862   else
5863     return condition_evaluation_host;
5864 }
5865
5866 /* Determine the breakpoint location's condition evaluator.  This is
5867    similar to bp_condition_evaluator, but for locations.  */
5868
5869 static const char *
5870 bp_location_condition_evaluator (struct bp_location *bl)
5871 {
5872   if (bl && !is_breakpoint (bl->owner))
5873     return NULL;
5874
5875   if (gdb_evaluates_breakpoint_condition_p ()
5876       || !target_supports_evaluation_of_breakpoint_conditions ())
5877     return condition_evaluation_host;
5878
5879   if (bl && bl->cond_bytecode)
5880     return condition_evaluation_target;
5881   else
5882     return condition_evaluation_host;
5883 }
5884
5885 /* Print the LOC location out of the list of B->LOC locations.  */
5886
5887 static void
5888 print_breakpoint_location (struct breakpoint *b,
5889                            struct bp_location *loc)
5890 {
5891   struct ui_out *uiout = current_uiout;
5892
5893   scoped_restore_current_program_space restore_pspace;
5894
5895   if (loc != NULL && loc->shlib_disabled)
5896     loc = NULL;
5897
5898   if (loc != NULL)
5899     set_current_program_space (loc->pspace);
5900
5901   if (b->display_canonical)
5902     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5903   else if (loc && loc->symtab)
5904     {
5905       const struct symbol *sym = loc->symbol;
5906
5907       if (sym)
5908         {
5909           uiout->text ("in ");
5910           uiout->field_string ("func", sym->print_name (),
5911                                function_name_style.style ());
5912           uiout->text (" ");
5913           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5914           uiout->text ("at ");
5915         }
5916       uiout->field_string ("file",
5917                            symtab_to_filename_for_display (loc->symtab),
5918                            file_name_style.style ());
5919       uiout->text (":");
5920
5921       if (uiout->is_mi_like_p ())
5922         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5923       
5924       uiout->field_signed ("line", loc->line_number);
5925     }
5926   else if (loc)
5927     {
5928       string_file stb;
5929
5930       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5931                               demangle, "");
5932       uiout->field_stream ("at", stb);
5933     }
5934   else
5935     {
5936       uiout->field_string ("pending",
5937                            event_location_to_string (b->location.get ()));
5938       /* If extra_string is available, it could be holding a condition
5939          or dprintf arguments.  In either case, make sure it is printed,
5940          too, but only for non-MI streams.  */
5941       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5942         {
5943           if (b->type == bp_dprintf)
5944             uiout->text (",");
5945           else
5946             uiout->text (" ");
5947           uiout->text (b->extra_string);
5948         }
5949     }
5950
5951   if (loc && is_breakpoint (b)
5952       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5953       && bp_condition_evaluator (b) == condition_evaluation_both)
5954     {
5955       uiout->text (" (");
5956       uiout->field_string ("evaluated-by",
5957                            bp_location_condition_evaluator (loc));
5958       uiout->text (")");
5959     }
5960 }
5961
5962 static const char *
5963 bptype_string (enum bptype type)
5964 {
5965   struct ep_type_description
5966     {
5967       enum bptype type;
5968       const char *description;
5969     };
5970   static struct ep_type_description bptypes[] =
5971   {
5972     {bp_none, "?deleted?"},
5973     {bp_breakpoint, "breakpoint"},
5974     {bp_hardware_breakpoint, "hw breakpoint"},
5975     {bp_single_step, "sw single-step"},
5976     {bp_until, "until"},
5977     {bp_finish, "finish"},
5978     {bp_watchpoint, "watchpoint"},
5979     {bp_hardware_watchpoint, "hw watchpoint"},
5980     {bp_read_watchpoint, "read watchpoint"},
5981     {bp_access_watchpoint, "acc watchpoint"},
5982     {bp_longjmp, "longjmp"},
5983     {bp_longjmp_resume, "longjmp resume"},
5984     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5985     {bp_exception, "exception"},
5986     {bp_exception_resume, "exception resume"},
5987     {bp_step_resume, "step resume"},
5988     {bp_hp_step_resume, "high-priority step resume"},
5989     {bp_watchpoint_scope, "watchpoint scope"},
5990     {bp_call_dummy, "call dummy"},
5991     {bp_std_terminate, "std::terminate"},
5992     {bp_shlib_event, "shlib events"},
5993     {bp_thread_event, "thread events"},
5994     {bp_overlay_event, "overlay events"},
5995     {bp_longjmp_master, "longjmp master"},
5996     {bp_std_terminate_master, "std::terminate master"},
5997     {bp_exception_master, "exception master"},
5998     {bp_catchpoint, "catchpoint"},
5999     {bp_tracepoint, "tracepoint"},
6000     {bp_fast_tracepoint, "fast tracepoint"},
6001     {bp_static_tracepoint, "static tracepoint"},
6002     {bp_dprintf, "dprintf"},
6003     {bp_jit_event, "jit events"},
6004     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6005     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6006   };
6007
6008   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6009       || ((int) type != bptypes[(int) type].type))
6010     internal_error (__FILE__, __LINE__,
6011                     _("bptypes table does not describe type #%d."),
6012                     (int) type);
6013
6014   return bptypes[(int) type].description;
6015 }
6016
6017 /* For MI, output a field named 'thread-groups' with a list as the value.
6018    For CLI, prefix the list with the string 'inf'. */
6019
6020 static void
6021 output_thread_groups (struct ui_out *uiout,
6022                       const char *field_name,
6023                       const std::vector<int> &inf_nums,
6024                       int mi_only)
6025 {
6026   int is_mi = uiout->is_mi_like_p ();
6027
6028   /* For backward compatibility, don't display inferiors in CLI unless
6029      there are several.  Always display them for MI. */
6030   if (!is_mi && mi_only)
6031     return;
6032
6033   ui_out_emit_list list_emitter (uiout, field_name);
6034
6035   for (size_t i = 0; i < inf_nums.size (); i++)
6036     {
6037       if (is_mi)
6038         {
6039           char mi_group[10];
6040
6041           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6042           uiout->field_string (NULL, mi_group);
6043         }
6044       else
6045         {
6046           if (i == 0)
6047             uiout->text (" inf ");
6048           else
6049             uiout->text (", ");
6050         
6051           uiout->text (plongest (inf_nums[i]));
6052         }
6053     }
6054 }
6055
6056 /* Print B to gdb_stdout.  If RAW_LOC, print raw breakpoint locations
6057    instead of going via breakpoint_ops::print_one.  This makes "maint
6058    info breakpoints" show the software breakpoint locations of
6059    catchpoints, which are considered internal implementation
6060    detail.  */
6061
6062 static void
6063 print_one_breakpoint_location (struct breakpoint *b,
6064                                struct bp_location *loc,
6065                                int loc_number,
6066                                struct bp_location **last_loc,
6067                                int allflag, bool raw_loc)
6068 {
6069   struct command_line *l;
6070   static char bpenables[] = "nynny";
6071
6072   struct ui_out *uiout = current_uiout;
6073   int header_of_multiple = 0;
6074   int part_of_multiple = (loc != NULL);
6075   struct value_print_options opts;
6076
6077   get_user_print_options (&opts);
6078
6079   gdb_assert (!loc || loc_number != 0);
6080   /* See comment in print_one_breakpoint concerning treatment of
6081      breakpoints with single disabled location.  */
6082   if (loc == NULL 
6083       && (b->loc != NULL 
6084           && (b->loc->next != NULL
6085               || !b->loc->enabled || b->loc->disabled_by_cond)))
6086     header_of_multiple = 1;
6087   if (loc == NULL)
6088     loc = b->loc;
6089
6090   annotate_record ();
6091
6092   /* 1 */
6093   annotate_field (0);
6094   if (part_of_multiple)
6095     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6096   else
6097     uiout->field_signed ("number", b->number);
6098
6099   /* 2 */
6100   annotate_field (1);
6101   if (part_of_multiple)
6102     uiout->field_skip ("type");
6103   else
6104     uiout->field_string ("type", bptype_string (b->type));
6105
6106   /* 3 */
6107   annotate_field (2);
6108   if (part_of_multiple)
6109     uiout->field_skip ("disp");
6110   else
6111     uiout->field_string ("disp", bpdisp_text (b->disposition));
6112
6113   /* 4 */
6114   annotate_field (3);
6115   /* For locations that are disabled because of an invalid condition,
6116      display "N*" on CLI, where "*" refers to a footnote below the
6117      table.  For MI, simply display a "N" without a footnote.  */
6118   const char *N = (uiout->is_mi_like_p ()) ? "N" : "N*";
6119   if (part_of_multiple)
6120     uiout->field_string ("enabled", (loc->disabled_by_cond ? N
6121                                      : (loc->enabled ? "y" : "n")));
6122   else
6123     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6124
6125   /* 5 and 6 */
6126   if (!raw_loc && b->ops != NULL && b->ops->print_one != NULL)
6127     b->ops->print_one (b, last_loc);
6128   else
6129     {
6130       if (is_watchpoint (b))
6131         {
6132           struct watchpoint *w = (struct watchpoint *) b;
6133
6134           /* Field 4, the address, is omitted (which makes the columns
6135              not line up too nicely with the headers, but the effect
6136              is relatively readable).  */
6137           if (opts.addressprint)
6138             uiout->field_skip ("addr");
6139           annotate_field (5);
6140           uiout->field_string ("what", w->exp_string);
6141         }
6142       else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6143                || is_ada_exception_catchpoint (b))
6144         {
6145           if (opts.addressprint)
6146             {
6147               annotate_field (4);
6148               if (header_of_multiple)
6149                 uiout->field_string ("addr", "<MULTIPLE>",
6150                                      metadata_style.style ());
6151               else if (b->loc == NULL || loc->shlib_disabled)
6152                 uiout->field_string ("addr", "<PENDING>",
6153                                      metadata_style.style ());
6154               else
6155                 uiout->field_core_addr ("addr",
6156                                         loc->gdbarch, loc->address);
6157             }
6158           annotate_field (5);
6159           if (!header_of_multiple)
6160             print_breakpoint_location (b, loc);
6161           if (b->loc)
6162             *last_loc = b->loc;
6163         }
6164     }
6165
6166   if (loc != NULL && !header_of_multiple)
6167     {
6168       std::vector<int> inf_nums;
6169       int mi_only = 1;
6170
6171       for (inferior *inf : all_inferiors ())
6172         {
6173           if (inf->pspace == loc->pspace)
6174             inf_nums.push_back (inf->num);
6175         }
6176
6177         /* For backward compatibility, don't display inferiors in CLI unless
6178            there are several.  Always display for MI. */
6179         if (allflag
6180             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6181                 && (program_spaces.size () > 1
6182                     || number_of_inferiors () > 1)
6183                 /* LOC is for existing B, it cannot be in
6184                    moribund_locations and thus having NULL OWNER.  */
6185                 && loc->owner->type != bp_catchpoint))
6186         mi_only = 0;
6187       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6188     }
6189
6190   if (!part_of_multiple)
6191     {
6192       if (b->thread != -1)
6193         {
6194           /* FIXME: This seems to be redundant and lost here; see the
6195              "stop only in" line a little further down.  */
6196           uiout->text (" thread ");
6197           uiout->field_signed ("thread", b->thread);
6198         }
6199       else if (b->task != 0)
6200         {
6201           uiout->text (" task ");
6202           uiout->field_signed ("task", b->task);
6203         }
6204     }
6205
6206   uiout->text ("\n");
6207
6208   if (!part_of_multiple)
6209     b->ops->print_one_detail (b, uiout);
6210
6211   if (part_of_multiple && frame_id_p (b->frame_id))
6212     {
6213       annotate_field (6);
6214       uiout->text ("\tstop only in stack frame at ");
6215       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6216          the frame ID.  */
6217       uiout->field_core_addr ("frame",
6218                               b->gdbarch, b->frame_id.stack_addr);
6219       uiout->text ("\n");
6220     }
6221   
6222   if (!part_of_multiple && b->cond_string)
6223     {
6224       annotate_field (7);
6225       if (is_tracepoint (b))
6226         uiout->text ("\ttrace only if ");
6227       else
6228         uiout->text ("\tstop only if ");
6229       uiout->field_string ("cond", b->cond_string);
6230
6231       /* Print whether the target is doing the breakpoint's condition
6232          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6233       if (is_breakpoint (b)
6234           && breakpoint_condition_evaluation_mode ()
6235           == condition_evaluation_target)
6236         {
6237           uiout->message (" (%pF evals)",
6238                           string_field ("evaluated-by",
6239                                         bp_condition_evaluator (b)));
6240         }
6241       uiout->text ("\n");
6242     }
6243
6244   if (!part_of_multiple && b->thread != -1)
6245     {
6246       /* FIXME should make an annotation for this.  */
6247       uiout->text ("\tstop only in thread ");
6248       if (uiout->is_mi_like_p ())
6249         uiout->field_signed ("thread", b->thread);
6250       else
6251         {
6252           struct thread_info *thr = find_thread_global_id (b->thread);
6253
6254           uiout->field_string ("thread", print_thread_id (thr));
6255         }
6256       uiout->text ("\n");
6257     }
6258   
6259   if (!part_of_multiple)
6260     {
6261       if (b->hit_count)
6262         {
6263           /* FIXME should make an annotation for this.  */
6264           if (is_catchpoint (b))
6265             uiout->text ("\tcatchpoint");
6266           else if (is_tracepoint (b))
6267             uiout->text ("\ttracepoint");
6268           else
6269             uiout->text ("\tbreakpoint");
6270           uiout->text (" already hit ");
6271           uiout->field_signed ("times", b->hit_count);
6272           if (b->hit_count == 1)
6273             uiout->text (" time\n");
6274           else
6275             uiout->text (" times\n");
6276         }
6277       else
6278         {
6279           /* Output the count also if it is zero, but only if this is mi.  */
6280           if (uiout->is_mi_like_p ())
6281             uiout->field_signed ("times", b->hit_count);
6282         }
6283     }
6284
6285   if (!part_of_multiple && b->ignore_count)
6286     {
6287       annotate_field (8);
6288       uiout->message ("\tignore next %pF hits\n",
6289                       signed_field ("ignore", b->ignore_count));
6290     }
6291
6292   /* Note that an enable count of 1 corresponds to "enable once"
6293      behavior, which is reported by the combination of enablement and
6294      disposition, so we don't need to mention it here.  */
6295   if (!part_of_multiple && b->enable_count > 1)
6296     {
6297       annotate_field (8);
6298       uiout->text ("\tdisable after ");
6299       /* Tweak the wording to clarify that ignore and enable counts
6300          are distinct, and have additive effect.  */
6301       if (b->ignore_count)
6302         uiout->text ("additional ");
6303       else
6304         uiout->text ("next ");
6305       uiout->field_signed ("enable", b->enable_count);
6306       uiout->text (" hits\n");
6307     }
6308
6309   if (!part_of_multiple && is_tracepoint (b))
6310     {
6311       struct tracepoint *tp = (struct tracepoint *) b;
6312
6313       if (tp->traceframe_usage)
6314         {
6315           uiout->text ("\ttrace buffer usage ");
6316           uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6317           uiout->text (" bytes\n");
6318         }
6319     }
6320
6321   l = b->commands ? b->commands.get () : NULL;
6322   if (!part_of_multiple && l)
6323     {
6324       annotate_field (9);
6325       ui_out_emit_tuple tuple_emitter (uiout, "script");
6326       print_command_lines (uiout, l, 4);
6327     }
6328
6329   if (is_tracepoint (b))
6330     {
6331       struct tracepoint *t = (struct tracepoint *) b;
6332
6333       if (!part_of_multiple && t->pass_count)
6334         {
6335           annotate_field (10);
6336           uiout->text ("\tpass count ");
6337           uiout->field_signed ("pass", t->pass_count);
6338           uiout->text (" \n");
6339         }
6340
6341       /* Don't display it when tracepoint or tracepoint location is
6342          pending.   */
6343       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6344         {
6345           annotate_field (11);
6346
6347           if (uiout->is_mi_like_p ())
6348             uiout->field_string ("installed",
6349                                  loc->inserted ? "y" : "n");
6350           else
6351             {
6352               if (loc->inserted)
6353                 uiout->text ("\t");
6354               else
6355                 uiout->text ("\tnot ");
6356               uiout->text ("installed on target\n");
6357             }
6358         }
6359     }
6360
6361   if (uiout->is_mi_like_p () && !part_of_multiple)
6362     {
6363       if (is_watchpoint (b))
6364         {
6365           struct watchpoint *w = (struct watchpoint *) b;
6366
6367           uiout->field_string ("original-location", w->exp_string);
6368         }
6369       else if (b->location != NULL
6370                && event_location_to_string (b->location.get ()) != NULL)
6371         uiout->field_string ("original-location",
6372                              event_location_to_string (b->location.get ()));
6373     }
6374 }
6375
6376 /* See breakpoint.h. */
6377
6378 bool fix_multi_location_breakpoint_output_globally = false;
6379
6380 static void
6381 print_one_breakpoint (struct breakpoint *b,
6382                       struct bp_location **last_loc, 
6383                       int allflag)
6384 {
6385   struct ui_out *uiout = current_uiout;
6386   bool use_fixed_output
6387     = (uiout->test_flags (fix_multi_location_breakpoint_output)
6388        || fix_multi_location_breakpoint_output_globally);
6389
6390   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6391   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag, false);
6392
6393   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6394      are outside.  */
6395   if (!use_fixed_output)
6396     bkpt_tuple_emitter.reset ();
6397
6398   /* If this breakpoint has custom print function,
6399      it's already printed.  Otherwise, print individual
6400      locations, if any.  */
6401   if (b->ops == NULL
6402       || b->ops->print_one == NULL
6403       || allflag)
6404     {
6405       /* If breakpoint has a single location that is disabled, we
6406          print it as if it had several locations, since otherwise it's
6407          hard to represent "breakpoint enabled, location disabled"
6408          situation.
6409
6410          Note that while hardware watchpoints have several locations
6411          internally, that's not a property exposed to users.
6412
6413          Likewise, while catchpoints may be implemented with
6414          breakpoints (e.g., catch throw), that's not a property
6415          exposed to users.  We do however display the internal
6416          breakpoint locations with "maint info breakpoints".  */
6417       if (!is_hardware_watchpoint (b)
6418           && (!is_catchpoint (b) || is_exception_catchpoint (b)
6419               || is_ada_exception_catchpoint (b))
6420           && (allflag
6421               || (b->loc && (b->loc->next
6422                              || !b->loc->enabled
6423                              || b->loc->disabled_by_cond))))
6424         {
6425           gdb::optional<ui_out_emit_list> locations_list;
6426
6427           /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6428              MI record.  For later versions, place breakpoint locations in a
6429              list.  */
6430           if (uiout->is_mi_like_p () && use_fixed_output)
6431             locations_list.emplace (uiout, "locations");
6432
6433           int n = 1;
6434           for (bp_location *loc : b->locations ())
6435             {
6436               ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6437               print_one_breakpoint_location (b, loc, n, last_loc,
6438                                              allflag, allflag);
6439               n++;
6440             }
6441         }
6442     }
6443 }
6444
6445 static int
6446 breakpoint_address_bits (struct breakpoint *b)
6447 {
6448   int print_address_bits = 0;
6449
6450   /* Software watchpoints that aren't watching memory don't have an
6451      address to print.  */
6452   if (is_no_memory_software_watchpoint (b))
6453     return 0;
6454
6455   for (bp_location *loc : b->locations ())
6456     {
6457       int addr_bit;
6458
6459       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6460       if (addr_bit > print_address_bits)
6461         print_address_bits = addr_bit;
6462     }
6463
6464   return print_address_bits;
6465 }
6466
6467 /* See breakpoint.h.  */
6468
6469 void
6470 print_breakpoint (breakpoint *b)
6471 {
6472   struct bp_location *dummy_loc = NULL;
6473   print_one_breakpoint (b, &dummy_loc, 0);
6474 }
6475
6476 /* Return true if this breakpoint was set by the user, false if it is
6477    internal or momentary.  */
6478
6479 int
6480 user_breakpoint_p (struct breakpoint *b)
6481 {
6482   return b->number > 0;
6483 }
6484
6485 /* See breakpoint.h.  */
6486
6487 int
6488 pending_breakpoint_p (struct breakpoint *b)
6489 {
6490   return b->loc == NULL;
6491 }
6492
6493 /* Print information on breakpoints (including watchpoints and tracepoints).
6494
6495    If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6496    understood by number_or_range_parser.  Only breakpoints included in this
6497    list are then printed.
6498
6499    If SHOW_INTERNAL is true, print internal breakpoints.
6500
6501    If FILTER is non-NULL, call it on each breakpoint and only include the
6502    ones for which it returns true.
6503
6504    Return the total number of breakpoints listed.  */
6505
6506 static int
6507 breakpoint_1 (const char *bp_num_list, bool show_internal,
6508               bool (*filter) (const struct breakpoint *))
6509 {
6510   struct bp_location *last_loc = NULL;
6511   int nr_printable_breakpoints;
6512   struct value_print_options opts;
6513   int print_address_bits = 0;
6514   int print_type_col_width = 14;
6515   struct ui_out *uiout = current_uiout;
6516   bool has_disabled_by_cond_location = false;
6517
6518   get_user_print_options (&opts);
6519
6520   /* Compute the number of rows in the table, as well as the size
6521      required for address fields.  */
6522   nr_printable_breakpoints = 0;
6523   for (breakpoint *b : all_breakpoints ())
6524     {
6525       /* If we have a filter, only list the breakpoints it accepts.  */
6526       if (filter && !filter (b))
6527         continue;
6528
6529       /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6530          accept.  Skip the others.  */
6531       if (bp_num_list != NULL && *bp_num_list != '\0')
6532         {
6533           if (show_internal && parse_and_eval_long (bp_num_list) != b->number)
6534             continue;
6535           if (!show_internal && !number_is_in_list (bp_num_list, b->number))
6536             continue;
6537         }
6538
6539       if (show_internal || user_breakpoint_p (b))
6540         {
6541           int addr_bit, type_len;
6542
6543           addr_bit = breakpoint_address_bits (b);
6544           if (addr_bit > print_address_bits)
6545             print_address_bits = addr_bit;
6546
6547           type_len = strlen (bptype_string (b->type));
6548           if (type_len > print_type_col_width)
6549             print_type_col_width = type_len;
6550
6551           nr_printable_breakpoints++;
6552         }
6553     }
6554
6555   {
6556     ui_out_emit_table table_emitter (uiout,
6557                                      opts.addressprint ? 6 : 5,
6558                                      nr_printable_breakpoints,
6559                                      "BreakpointTable");
6560
6561     if (nr_printable_breakpoints > 0)
6562       annotate_breakpoints_headers ();
6563     if (nr_printable_breakpoints > 0)
6564       annotate_field (0);
6565     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6566     if (nr_printable_breakpoints > 0)
6567       annotate_field (1);
6568     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6569     if (nr_printable_breakpoints > 0)
6570       annotate_field (2);
6571     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6572     if (nr_printable_breakpoints > 0)
6573       annotate_field (3);
6574     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6575     if (opts.addressprint)
6576       {
6577         if (nr_printable_breakpoints > 0)
6578           annotate_field (4);
6579         if (print_address_bits <= 32)
6580           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6581         else
6582           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6583       }
6584     if (nr_printable_breakpoints > 0)
6585       annotate_field (5);
6586     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6587     uiout->table_body ();
6588     if (nr_printable_breakpoints > 0)
6589       annotate_breakpoints_table ();
6590
6591     for (breakpoint *b : all_breakpoints ())
6592       {
6593         QUIT;
6594         /* If we have a filter, only list the breakpoints it accepts.  */
6595         if (filter && !filter (b))
6596           continue;
6597
6598         /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6599            accept.  Skip the others.  */
6600
6601         if (bp_num_list != NULL && *bp_num_list != '\0')
6602           {
6603             if (show_internal)  /* maintenance info breakpoint */
6604               {
6605                 if (parse_and_eval_long (bp_num_list) != b->number)
6606                   continue;
6607               }
6608             else                /* all others */
6609               {
6610                 if (!number_is_in_list (bp_num_list, b->number))
6611                   continue;
6612               }
6613           }
6614         /* We only print out user settable breakpoints unless the
6615            show_internal is set.  */
6616         if (show_internal || user_breakpoint_p (b))
6617           {
6618             print_one_breakpoint (b, &last_loc, show_internal);
6619             for (bp_location *loc : b->locations ())
6620               if (loc->disabled_by_cond)
6621                 has_disabled_by_cond_location = true;
6622           }
6623       }
6624   }
6625
6626   if (nr_printable_breakpoints == 0)
6627     {
6628       /* If there's a filter, let the caller decide how to report
6629          empty list.  */
6630       if (!filter)
6631         {
6632           if (bp_num_list == NULL || *bp_num_list == '\0')
6633             uiout->message ("No breakpoints or watchpoints.\n");
6634           else
6635             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6636                             bp_num_list);
6637         }
6638     }
6639   else
6640     {
6641       if (last_loc && !server_command)
6642         set_next_address (last_loc->gdbarch, last_loc->address);
6643
6644       if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
6645         uiout->message (_("(*): Breakpoint condition is invalid at this "
6646                           "location.\n"));
6647     }
6648
6649   /* FIXME?  Should this be moved up so that it is only called when
6650      there have been breakpoints? */
6651   annotate_breakpoints_table_end ();
6652
6653   return nr_printable_breakpoints;
6654 }
6655
6656 /* Display the value of default-collect in a way that is generally
6657    compatible with the breakpoint list.  */
6658
6659 static void
6660 default_collect_info (void)
6661 {
6662   struct ui_out *uiout = current_uiout;
6663
6664   /* If it has no value (which is frequently the case), say nothing; a
6665      message like "No default-collect." gets in user's face when it's
6666      not wanted.  */
6667   if (!*default_collect)
6668     return;
6669
6670   /* The following phrase lines up nicely with per-tracepoint collect
6671      actions.  */
6672   uiout->text ("default collect ");
6673   uiout->field_string ("default-collect", default_collect);
6674   uiout->text (" \n");
6675 }
6676   
6677 static void
6678 info_breakpoints_command (const char *args, int from_tty)
6679 {
6680   breakpoint_1 (args, false, NULL);
6681
6682   default_collect_info ();
6683 }
6684
6685 static void
6686 info_watchpoints_command (const char *args, int from_tty)
6687 {
6688   int num_printed = breakpoint_1 (args, false, is_watchpoint);
6689   struct ui_out *uiout = current_uiout;
6690
6691   if (num_printed == 0)
6692     {
6693       if (args == NULL || *args == '\0')
6694         uiout->message ("No watchpoints.\n");
6695       else
6696         uiout->message ("No watchpoint matching '%s'.\n", args);
6697     }
6698 }
6699
6700 static void
6701 maintenance_info_breakpoints (const char *args, int from_tty)
6702 {
6703   breakpoint_1 (args, true, NULL);
6704
6705   default_collect_info ();
6706 }
6707
6708 static int
6709 breakpoint_has_pc (struct breakpoint *b,
6710                    struct program_space *pspace,
6711                    CORE_ADDR pc, struct obj_section *section)
6712 {
6713   for (bp_location *bl : b->locations ())
6714     {
6715       if (bl->pspace == pspace
6716           && bl->address == pc
6717           && (!overlay_debugging || bl->section == section))
6718         return 1;         
6719     }
6720   return 0;
6721 }
6722
6723 /* Print a message describing any user-breakpoints set at PC.  This
6724    concerns with logical breakpoints, so we match program spaces, not
6725    address spaces.  */
6726
6727 static void
6728 describe_other_breakpoints (struct gdbarch *gdbarch,
6729                             struct program_space *pspace, CORE_ADDR pc,
6730                             struct obj_section *section, int thread)
6731 {
6732   int others = 0;
6733
6734   for (breakpoint *b : all_breakpoints ())
6735     others += (user_breakpoint_p (b)
6736                && breakpoint_has_pc (b, pspace, pc, section));
6737
6738   if (others > 0)
6739     {
6740       if (others == 1)
6741         printf_filtered (_("Note: breakpoint "));
6742       else /* if (others == ???) */
6743         printf_filtered (_("Note: breakpoints "));
6744       for (breakpoint *b : all_breakpoints ())
6745         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6746           {
6747             others--;
6748             printf_filtered ("%d", b->number);
6749             if (b->thread == -1 && thread != -1)
6750               printf_filtered (" (all threads)");
6751             else if (b->thread != -1)
6752               printf_filtered (" (thread %d)", b->thread);
6753             printf_filtered ("%s%s ",
6754                              ((b->enable_state == bp_disabled
6755                                || b->enable_state == bp_call_disabled)
6756                               ? " (disabled)"
6757                               : ""),
6758                              (others > 1) ? "," 
6759                              : ((others == 1) ? " and" : ""));
6760           }
6761       current_uiout->message (_("also set at pc %ps.\n"),
6762                               styled_string (address_style.style (),
6763                                              paddress (gdbarch, pc)));
6764     }
6765 }
6766 \f
6767
6768 /* Return true iff it is meaningful to use the address member of LOC.
6769    For some breakpoint types, the locations' address members are
6770    irrelevant and it makes no sense to attempt to compare them to
6771    other addresses (or use them for any other purpose either).
6772
6773    More specifically, software watchpoints and catchpoints that are
6774    not backed by breakpoints always have a zero valued location
6775    address and we don't want to mark breakpoints of any of these types
6776    to be a duplicate of an actual breakpoint location at address
6777    zero.  */
6778
6779 static bool
6780 bl_address_is_meaningful (bp_location *loc)
6781 {
6782   return loc->loc_type != bp_loc_other;
6783 }
6784
6785 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6786    true if LOC1 and LOC2 represent the same watchpoint location.  */
6787
6788 static int
6789 watchpoint_locations_match (struct bp_location *loc1, 
6790                             struct bp_location *loc2)
6791 {
6792   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6793   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6794
6795   /* Both of them must exist.  */
6796   gdb_assert (w1 != NULL);
6797   gdb_assert (w2 != NULL);
6798
6799   /* If the target can evaluate the condition expression in hardware,
6800      then we we need to insert both watchpoints even if they are at
6801      the same place.  Otherwise the watchpoint will only trigger when
6802      the condition of whichever watchpoint was inserted evaluates to
6803      true, not giving a chance for GDB to check the condition of the
6804      other watchpoint.  */
6805   if ((w1->cond_exp
6806        && target_can_accel_watchpoint_condition (loc1->address, 
6807                                                  loc1->length,
6808                                                  loc1->watchpoint_type,
6809                                                  w1->cond_exp.get ()))
6810       || (w2->cond_exp
6811           && target_can_accel_watchpoint_condition (loc2->address, 
6812                                                     loc2->length,
6813                                                     loc2->watchpoint_type,
6814                                                     w2->cond_exp.get ())))
6815     return 0;
6816
6817   /* Note that this checks the owner's type, not the location's.  In
6818      case the target does not support read watchpoints, but does
6819      support access watchpoints, we'll have bp_read_watchpoint
6820      watchpoints with hw_access locations.  Those should be considered
6821      duplicates of hw_read locations.  The hw_read locations will
6822      become hw_access locations later.  */
6823   return (loc1->owner->type == loc2->owner->type
6824           && loc1->pspace->aspace == loc2->pspace->aspace
6825           && loc1->address == loc2->address
6826           && loc1->length == loc2->length);
6827 }
6828
6829 /* See breakpoint.h.  */
6830
6831 int
6832 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6833                           const address_space *aspace2, CORE_ADDR addr2)
6834 {
6835   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6836            || aspace1 == aspace2)
6837           && addr1 == addr2);
6838 }
6839
6840 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6841    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6842    matches ASPACE2.  On targets that have global breakpoints, the address
6843    space doesn't really matter.  */
6844
6845 static int
6846 breakpoint_address_match_range (const address_space *aspace1,
6847                                 CORE_ADDR addr1,
6848                                 int len1, const address_space *aspace2,
6849                                 CORE_ADDR addr2)
6850 {
6851   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6852            || aspace1 == aspace2)
6853           && addr2 >= addr1 && addr2 < addr1 + len1);
6854 }
6855
6856 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6857    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6858    matches the breakpoint's address space.  On targets that have global
6859    breakpoints, the address space doesn't really matter.  */
6860
6861 static int
6862 breakpoint_location_address_match (struct bp_location *bl,
6863                                    const address_space *aspace,
6864                                    CORE_ADDR addr)
6865 {
6866   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6867                                     aspace, addr)
6868           || (bl->length
6869               && breakpoint_address_match_range (bl->pspace->aspace,
6870                                                  bl->address, bl->length,
6871                                                  aspace, addr)));
6872 }
6873
6874 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6875    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6876    match happens only if ASPACE matches the breakpoint's address
6877    space.  On targets that have global breakpoints, the address space
6878    doesn't really matter.  */
6879
6880 static int
6881 breakpoint_location_address_range_overlap (struct bp_location *bl,
6882                                            const address_space *aspace,
6883                                            CORE_ADDR addr, int len)
6884 {
6885   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6886       || bl->pspace->aspace == aspace)
6887     {
6888       int bl_len = bl->length != 0 ? bl->length : 1;
6889
6890       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6891         return 1;
6892     }
6893   return 0;
6894 }
6895
6896 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6897    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6898    true, otherwise returns false.  */
6899
6900 static int
6901 tracepoint_locations_match (struct bp_location *loc1,
6902                             struct bp_location *loc2)
6903 {
6904   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6905     /* Since tracepoint locations are never duplicated with others', tracepoint
6906        locations at the same address of different tracepoints are regarded as
6907        different locations.  */
6908     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6909   else
6910     return 0;
6911 }
6912
6913 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6914    (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
6915    the same location.  If SW_HW_BPS_MATCH is true, then software
6916    breakpoint locations and hardware breakpoint locations match,
6917    otherwise they don't.  */
6918
6919 static int
6920 breakpoint_locations_match (struct bp_location *loc1,
6921                             struct bp_location *loc2,
6922                             bool sw_hw_bps_match)
6923 {
6924   int hw_point1, hw_point2;
6925
6926   /* Both of them must not be in moribund_locations.  */
6927   gdb_assert (loc1->owner != NULL);
6928   gdb_assert (loc2->owner != NULL);
6929
6930   hw_point1 = is_hardware_watchpoint (loc1->owner);
6931   hw_point2 = is_hardware_watchpoint (loc2->owner);
6932
6933   if (hw_point1 != hw_point2)
6934     return 0;
6935   else if (hw_point1)
6936     return watchpoint_locations_match (loc1, loc2);
6937   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6938     return tracepoint_locations_match (loc1, loc2);
6939   else
6940     /* We compare bp_location.length in order to cover ranged
6941        breakpoints.  Keep this in sync with
6942        bp_location_is_less_than.  */
6943     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6944                                      loc2->pspace->aspace, loc2->address)
6945             && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
6946             && loc1->length == loc2->length);
6947 }
6948
6949 static void
6950 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6951                                int bnum, int have_bnum)
6952 {
6953   /* The longest string possibly returned by hex_string_custom
6954      is 50 chars.  These must be at least that big for safety.  */
6955   char astr1[64];
6956   char astr2[64];
6957
6958   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6959   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6960   if (have_bnum)
6961     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6962              bnum, astr1, astr2);
6963   else
6964     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6965 }
6966
6967 /* Adjust a breakpoint's address to account for architectural
6968    constraints on breakpoint placement.  Return the adjusted address.
6969    Note: Very few targets require this kind of adjustment.  For most
6970    targets, this function is simply the identity function.  */
6971
6972 static CORE_ADDR
6973 adjust_breakpoint_address (struct gdbarch *gdbarch,
6974                            CORE_ADDR bpaddr, enum bptype bptype)
6975 {
6976   if (bptype == bp_watchpoint
6977       || bptype == bp_hardware_watchpoint
6978       || bptype == bp_read_watchpoint
6979       || bptype == bp_access_watchpoint
6980       || bptype == bp_catchpoint)
6981     {
6982       /* Watchpoints and the various bp_catch_* eventpoints should not
6983          have their addresses modified.  */
6984       return bpaddr;
6985     }
6986   else if (bptype == bp_single_step)
6987     {
6988       /* Single-step breakpoints should not have their addresses
6989          modified.  If there's any architectural constrain that
6990          applies to this address, then it should have already been
6991          taken into account when the breakpoint was created in the
6992          first place.  If we didn't do this, stepping through e.g.,
6993          Thumb-2 IT blocks would break.  */
6994       return bpaddr;
6995     }
6996   else
6997     {
6998       CORE_ADDR adjusted_bpaddr = bpaddr;
6999
7000       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7001         {
7002           /* Some targets have architectural constraints on the placement
7003              of breakpoint instructions.  Obtain the adjusted address.  */
7004           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7005         }
7006
7007       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
7008
7009       /* An adjusted breakpoint address can significantly alter
7010          a user's expectations.  Print a warning if an adjustment
7011          is required.  */
7012       if (adjusted_bpaddr != bpaddr)
7013         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7014
7015       return adjusted_bpaddr;
7016     }
7017 }
7018
7019 static bp_loc_type
7020 bp_location_from_bp_type (bptype type)
7021 {
7022   switch (type)
7023     {
7024     case bp_breakpoint:
7025     case bp_single_step:
7026     case bp_until:
7027     case bp_finish:
7028     case bp_longjmp:
7029     case bp_longjmp_resume:
7030     case bp_longjmp_call_dummy:
7031     case bp_exception:
7032     case bp_exception_resume:
7033     case bp_step_resume:
7034     case bp_hp_step_resume:
7035     case bp_watchpoint_scope:
7036     case bp_call_dummy:
7037     case bp_std_terminate:
7038     case bp_shlib_event:
7039     case bp_thread_event:
7040     case bp_overlay_event:
7041     case bp_jit_event:
7042     case bp_longjmp_master:
7043     case bp_std_terminate_master:
7044     case bp_exception_master:
7045     case bp_gnu_ifunc_resolver:
7046     case bp_gnu_ifunc_resolver_return:
7047     case bp_dprintf:
7048       return bp_loc_software_breakpoint;
7049     case bp_hardware_breakpoint:
7050       return bp_loc_hardware_breakpoint;
7051     case bp_hardware_watchpoint:
7052     case bp_read_watchpoint:
7053     case bp_access_watchpoint:
7054       return bp_loc_hardware_watchpoint;
7055     case bp_watchpoint:
7056     case bp_catchpoint:
7057     case bp_tracepoint:
7058     case bp_fast_tracepoint:
7059     case bp_static_tracepoint:
7060       return bp_loc_other;
7061     default:
7062       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7063     }
7064 }
7065
7066 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7067 {
7068   this->owner = owner;
7069   this->cond_bytecode = NULL;
7070   this->shlib_disabled = 0;
7071   this->enabled = 1;
7072   this->disabled_by_cond = false;
7073
7074   this->loc_type = type;
7075
7076   if (this->loc_type == bp_loc_software_breakpoint
7077       || this->loc_type == bp_loc_hardware_breakpoint)
7078     mark_breakpoint_location_modified (this);
7079
7080   incref ();
7081 }
7082
7083 bp_location::bp_location (breakpoint *owner)
7084   : bp_location::bp_location (owner,
7085                               bp_location_from_bp_type (owner->type))
7086 {
7087 }
7088
7089 /* Allocate a struct bp_location.  */
7090
7091 static struct bp_location *
7092 allocate_bp_location (struct breakpoint *bpt)
7093 {
7094   return bpt->ops->allocate_location (bpt);
7095 }
7096
7097 /* Decrement reference count.  If the reference count reaches 0,
7098    destroy the bp_location.  Sets *BLP to NULL.  */
7099
7100 static void
7101 decref_bp_location (struct bp_location **blp)
7102 {
7103   bp_location_ref_policy::decref (*blp);
7104   *blp = NULL;
7105 }
7106
7107 /* Add breakpoint B at the end of the global breakpoint chain.  */
7108
7109 static breakpoint *
7110 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7111 {
7112   struct breakpoint *b1;
7113   struct breakpoint *result = b.get ();
7114
7115   /* Add this breakpoint to the end of the chain so that a list of
7116      breakpoints will come out in order of increasing numbers.  */
7117
7118   b1 = breakpoint_chain;
7119   if (b1 == 0)
7120     breakpoint_chain = b.release ();
7121   else
7122     {
7123       while (b1->next)
7124         b1 = b1->next;
7125       b1->next = b.release ();
7126     }
7127
7128   return result;
7129 }
7130
7131 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7132
7133 static void
7134 init_raw_breakpoint_without_location (struct breakpoint *b,
7135                                       struct gdbarch *gdbarch,
7136                                       enum bptype bptype,
7137                                       const struct breakpoint_ops *ops)
7138 {
7139   gdb_assert (ops != NULL);
7140
7141   b->ops = ops;
7142   b->type = bptype;
7143   b->gdbarch = gdbarch;
7144   b->language = current_language->la_language;
7145   b->input_radix = input_radix;
7146   b->related_breakpoint = b;
7147 }
7148
7149 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7150    that has type BPTYPE and has no locations as yet.  */
7151
7152 static struct breakpoint *
7153 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7154                                      enum bptype bptype,
7155                                      const struct breakpoint_ops *ops)
7156 {
7157   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7158
7159   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7160   return add_to_breakpoint_chain (std::move (b));
7161 }
7162
7163 /* Initialize loc->function_name.  */
7164
7165 static void
7166 set_breakpoint_location_function (struct bp_location *loc)
7167 {
7168   gdb_assert (loc->owner != NULL);
7169
7170   if (loc->owner->type == bp_breakpoint
7171       || loc->owner->type == bp_hardware_breakpoint
7172       || is_tracepoint (loc->owner))
7173     {
7174       const char *function_name;
7175
7176       if (loc->msymbol != NULL
7177           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7178               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc))
7179         {
7180           struct breakpoint *b = loc->owner;
7181
7182           function_name = loc->msymbol->linkage_name ();
7183
7184           if (b->type == bp_breakpoint && b->loc == loc
7185               && loc->next == NULL && b->related_breakpoint == b)
7186             {
7187               /* Create only the whole new breakpoint of this type but do not
7188                  mess more complicated breakpoints with multiple locations.  */
7189               b->type = bp_gnu_ifunc_resolver;
7190               /* Remember the resolver's address for use by the return
7191                  breakpoint.  */
7192               loc->related_address = loc->address;
7193             }
7194         }
7195       else
7196         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7197
7198       if (function_name)
7199         loc->function_name = xstrdup (function_name);
7200     }
7201 }
7202
7203 /* Attempt to determine architecture of location identified by SAL.  */
7204 struct gdbarch *
7205 get_sal_arch (struct symtab_and_line sal)
7206 {
7207   if (sal.section)
7208     return sal.section->objfile->arch ();
7209   if (sal.symtab)
7210     return SYMTAB_OBJFILE (sal.symtab)->arch ();
7211
7212   return NULL;
7213 }
7214
7215 /* Low level routine for partially initializing a breakpoint of type
7216    BPTYPE.  The newly created breakpoint's address, section, source
7217    file name, and line number are provided by SAL.
7218
7219    It is expected that the caller will complete the initialization of
7220    the newly created breakpoint struct as well as output any status
7221    information regarding the creation of a new breakpoint.  */
7222
7223 static void
7224 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7225                      struct symtab_and_line sal, enum bptype bptype,
7226                      const struct breakpoint_ops *ops)
7227 {
7228   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7229
7230   add_location_to_breakpoint (b, &sal);
7231
7232   if (bptype != bp_catchpoint)
7233     gdb_assert (sal.pspace != NULL);
7234
7235   /* Store the program space that was used to set the breakpoint,
7236      except for ordinary breakpoints, which are independent of the
7237      program space.  */
7238   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7239     b->pspace = sal.pspace;
7240 }
7241
7242 /* set_raw_breakpoint is a low level routine for allocating and
7243    partially initializing a breakpoint of type BPTYPE.  The newly
7244    created breakpoint's address, section, source file name, and line
7245    number are provided by SAL.  The newly created and partially
7246    initialized breakpoint is added to the breakpoint chain and
7247    is also returned as the value of this function.
7248
7249    It is expected that the caller will complete the initialization of
7250    the newly created breakpoint struct as well as output any status
7251    information regarding the creation of a new breakpoint.  In
7252    particular, set_raw_breakpoint does NOT set the breakpoint
7253    number!  Care should be taken to not allow an error to occur
7254    prior to completing the initialization of the breakpoint.  If this
7255    should happen, a bogus breakpoint will be left on the chain.  */
7256
7257 struct breakpoint *
7258 set_raw_breakpoint (struct gdbarch *gdbarch,
7259                     struct symtab_and_line sal, enum bptype bptype,
7260                     const struct breakpoint_ops *ops)
7261 {
7262   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7263
7264   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7265   return add_to_breakpoint_chain (std::move (b));
7266 }
7267
7268 /* Call this routine when stepping and nexting to enable a breakpoint
7269    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7270    initiated the operation.  */
7271
7272 void
7273 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7274 {
7275   int thread = tp->global_num;
7276
7277   /* To avoid having to rescan all objfile symbols at every step,
7278      we maintain a list of continually-inserted but always disabled
7279      longjmp "master" breakpoints.  Here, we simply create momentary
7280      clones of those and enable them for the requested thread.  */
7281   for (breakpoint *b : all_breakpoints_safe ())
7282     if (b->pspace == current_program_space
7283         && (b->type == bp_longjmp_master
7284             || b->type == bp_exception_master))
7285       {
7286         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7287         struct breakpoint *clone;
7288
7289         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7290            after their removal.  */
7291         clone = momentary_breakpoint_from_master (b, type,
7292                                                   &momentary_breakpoint_ops, 1);
7293         clone->thread = thread;
7294       }
7295
7296   tp->initiating_frame = frame;
7297 }
7298
7299 /* Delete all longjmp breakpoints from THREAD.  */
7300 void
7301 delete_longjmp_breakpoint (int thread)
7302 {
7303   for (breakpoint *b : all_breakpoints_safe ())
7304     if (b->type == bp_longjmp || b->type == bp_exception)
7305       {
7306         if (b->thread == thread)
7307           delete_breakpoint (b);
7308       }
7309 }
7310
7311 void
7312 delete_longjmp_breakpoint_at_next_stop (int thread)
7313 {
7314   for (breakpoint *b : all_breakpoints_safe ())
7315     if (b->type == bp_longjmp || b->type == bp_exception)
7316       {
7317         if (b->thread == thread)
7318           b->disposition = disp_del_at_next_stop;
7319       }
7320 }
7321
7322 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7323    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7324    pointer to any of them.  Return NULL if this system cannot place longjmp
7325    breakpoints.  */
7326
7327 struct breakpoint *
7328 set_longjmp_breakpoint_for_call_dummy (void)
7329 {
7330   breakpoint *retval = nullptr;
7331
7332   for (breakpoint *b : all_breakpoints ())
7333     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7334       {
7335         struct breakpoint *new_b;
7336
7337         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7338                                                   &momentary_breakpoint_ops,
7339                                                   1);
7340         new_b->thread = inferior_thread ()->global_num;
7341
7342         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7343
7344         gdb_assert (new_b->related_breakpoint == new_b);
7345         if (retval == NULL)
7346           retval = new_b;
7347         new_b->related_breakpoint = retval;
7348         while (retval->related_breakpoint != new_b->related_breakpoint)
7349           retval = retval->related_breakpoint;
7350         retval->related_breakpoint = new_b;
7351       }
7352
7353   return retval;
7354 }
7355
7356 /* Verify all existing dummy frames and their associated breakpoints for
7357    TP.  Remove those which can no longer be found in the current frame
7358    stack.
7359
7360    If the unwind fails then there is not sufficient information to discard
7361    dummy frames.  In this case, elide the clean up and the dummy frames will
7362    be cleaned up next time this function is called from a location where
7363    unwinding is possible.  */
7364
7365 void
7366 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7367 {
7368   struct breakpoint *b, *b_tmp;
7369
7370   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7371     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7372       {
7373         struct breakpoint *dummy_b = b->related_breakpoint;
7374
7375         /* Find the bp_call_dummy breakpoint in the list of breakpoints
7376            chained off b->related_breakpoint.  */
7377         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7378           dummy_b = dummy_b->related_breakpoint;
7379
7380         /* If there was no bp_call_dummy breakpoint then there's nothing
7381            more to do.  Or, if the dummy frame associated with the
7382            bp_call_dummy is still on the stack then we need to leave this
7383            bp_call_dummy in place.  */
7384         if (dummy_b->type != bp_call_dummy
7385             || frame_find_by_id (dummy_b->frame_id) != NULL)
7386           continue;
7387
7388         /* We didn't find the dummy frame on the stack, this could be
7389            because we have longjmp'd to a stack frame that is previous to
7390            the dummy frame, or it could be because the stack unwind is
7391            broken at some point between the longjmp frame and the dummy
7392            frame.
7393
7394            Next we figure out why the stack unwind stopped.  If it looks
7395            like the unwind is complete then we assume the dummy frame has
7396            been jumped over, however, if the unwind stopped for an
7397            unexpected reason then we assume the stack unwind is currently
7398            broken, and that we will (eventually) return to the dummy
7399            frame.
7400
7401            It might be tempting to consider using frame_id_inner here, but
7402            that is not safe.   There is no guarantee that the stack frames
7403            we are looking at here are even on the same stack as the
7404            original dummy frame, hence frame_id_inner can't be used.  See
7405            the comments on frame_id_inner for more details.  */
7406         bool unwind_finished_unexpectedly = false;
7407         for (struct frame_info *fi = get_current_frame (); fi != nullptr; )
7408           {
7409             struct frame_info *prev = get_prev_frame (fi);
7410             if (prev == nullptr)
7411               {
7412                 /* FI is the last stack frame.  Why did this frame not
7413                    unwind further?  */
7414                 auto stop_reason = get_frame_unwind_stop_reason (fi);
7415                 if (stop_reason != UNWIND_NO_REASON
7416                     && stop_reason != UNWIND_OUTERMOST)
7417                   unwind_finished_unexpectedly = true;
7418               }
7419             fi = prev;
7420           }
7421         if (unwind_finished_unexpectedly)
7422           continue;
7423
7424         dummy_frame_discard (dummy_b->frame_id, tp);
7425
7426         while (b->related_breakpoint != b)
7427           {
7428             if (b_tmp == b->related_breakpoint)
7429               b_tmp = b->related_breakpoint->next;
7430             delete_breakpoint (b->related_breakpoint);
7431           }
7432         delete_breakpoint (b);
7433       }
7434 }
7435
7436 void
7437 enable_overlay_breakpoints (void)
7438 {
7439   for (breakpoint *b : all_breakpoints ())
7440     if (b->type == bp_overlay_event)
7441       {
7442         b->enable_state = bp_enabled;
7443         update_global_location_list (UGLL_MAY_INSERT);
7444         overlay_events_enabled = 1;
7445       }
7446 }
7447
7448 void
7449 disable_overlay_breakpoints (void)
7450 {
7451   for (breakpoint *b : all_breakpoints ())
7452     if (b->type == bp_overlay_event)
7453       {
7454         b->enable_state = bp_disabled;
7455         update_global_location_list (UGLL_DONT_INSERT);
7456         overlay_events_enabled = 0;
7457       }
7458 }
7459
7460 /* Set an active std::terminate breakpoint for each std::terminate
7461    master breakpoint.  */
7462 void
7463 set_std_terminate_breakpoint (void)
7464 {
7465   for (breakpoint *b : all_breakpoints_safe ())
7466     if (b->pspace == current_program_space
7467         && b->type == bp_std_terminate_master)
7468       {
7469         momentary_breakpoint_from_master (b, bp_std_terminate,
7470                                           &momentary_breakpoint_ops, 1);
7471       }
7472 }
7473
7474 /* Delete all the std::terminate breakpoints.  */
7475 void
7476 delete_std_terminate_breakpoint (void)
7477 {
7478   for (breakpoint *b : all_breakpoints_safe ())
7479     if (b->type == bp_std_terminate)
7480       delete_breakpoint (b);
7481 }
7482
7483 struct breakpoint *
7484 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7485 {
7486   struct breakpoint *b;
7487
7488   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7489                                   &internal_breakpoint_ops);
7490
7491   b->enable_state = bp_enabled;
7492   /* location has to be used or breakpoint_re_set will delete me.  */
7493   b->location = new_address_location (b->loc->address, NULL, 0);
7494
7495   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7496
7497   return b;
7498 }
7499
7500 struct lang_and_radix
7501   {
7502     enum language lang;
7503     int radix;
7504   };
7505
7506 /* Create a breakpoint for JIT code registration and unregistration.  */
7507
7508 struct breakpoint *
7509 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7510 {
7511   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7512                                      &internal_breakpoint_ops);
7513 }
7514
7515 /* Remove JIT code registration and unregistration breakpoint(s).  */
7516
7517 void
7518 remove_jit_event_breakpoints (void)
7519 {
7520   for (breakpoint *b : all_breakpoints_safe ())
7521     if (b->type == bp_jit_event
7522         && b->loc->pspace == current_program_space)
7523       delete_breakpoint (b);
7524 }
7525
7526 void
7527 remove_solib_event_breakpoints (void)
7528 {
7529   for (breakpoint *b : all_breakpoints_safe ())
7530     if (b->type == bp_shlib_event
7531         && b->loc->pspace == current_program_space)
7532       delete_breakpoint (b);
7533 }
7534
7535 /* See breakpoint.h.  */
7536
7537 void
7538 remove_solib_event_breakpoints_at_next_stop (void)
7539 {
7540   for (breakpoint *b : all_breakpoints_safe ())
7541     if (b->type == bp_shlib_event
7542         && b->loc->pspace == current_program_space)
7543       b->disposition = disp_del_at_next_stop;
7544 }
7545
7546 /* Helper for create_solib_event_breakpoint /
7547    create_and_insert_solib_event_breakpoint.  Allows specifying which
7548    INSERT_MODE to pass through to update_global_location_list.  */
7549
7550 static struct breakpoint *
7551 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7552                                  enum ugll_insert_mode insert_mode)
7553 {
7554   struct breakpoint *b;
7555
7556   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7557                                   &internal_breakpoint_ops);
7558   update_global_location_list_nothrow (insert_mode);
7559   return b;
7560 }
7561
7562 struct breakpoint *
7563 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7564 {
7565   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7566 }
7567
7568 /* See breakpoint.h.  */
7569
7570 struct breakpoint *
7571 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7572 {
7573   struct breakpoint *b;
7574
7575   /* Explicitly tell update_global_location_list to insert
7576      locations.  */
7577   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7578   if (!b->loc->inserted)
7579     {
7580       delete_breakpoint (b);
7581       return NULL;
7582     }
7583   return b;
7584 }
7585
7586 /* Disable any breakpoints that are on code in shared libraries.  Only
7587    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7588
7589 void
7590 disable_breakpoints_in_shlibs (void)
7591 {
7592   for (bp_location *loc : all_bp_locations ())
7593     {
7594       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7595       struct breakpoint *b = loc->owner;
7596
7597       /* We apply the check to all breakpoints, including disabled for
7598          those with loc->duplicate set.  This is so that when breakpoint
7599          becomes enabled, or the duplicate is removed, gdb will try to
7600          insert all breakpoints.  If we don't set shlib_disabled here,
7601          we'll try to insert those breakpoints and fail.  */
7602       if (((b->type == bp_breakpoint)
7603            || (b->type == bp_jit_event)
7604            || (b->type == bp_hardware_breakpoint)
7605            || (is_tracepoint (b)))
7606           && loc->pspace == current_program_space
7607           && !loc->shlib_disabled
7608           && solib_name_from_address (loc->pspace, loc->address)
7609           )
7610         {
7611           loc->shlib_disabled = 1;
7612         }
7613     }
7614 }
7615
7616 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7617    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7618    disabled ones can just stay disabled.  */
7619
7620 static void
7621 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7622 {
7623   int disabled_shlib_breaks = 0;
7624
7625   for (bp_location *loc : all_bp_locations ())
7626     {
7627       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7628       struct breakpoint *b = loc->owner;
7629
7630       if (solib->pspace == loc->pspace
7631           && !loc->shlib_disabled
7632           && (((b->type == bp_breakpoint
7633                 || b->type == bp_jit_event
7634                 || b->type == bp_hardware_breakpoint)
7635                && (loc->loc_type == bp_loc_hardware_breakpoint
7636                    || loc->loc_type == bp_loc_software_breakpoint))
7637               || is_tracepoint (b))
7638           && solib_contains_address_p (solib, loc->address))
7639         {
7640           loc->shlib_disabled = 1;
7641           /* At this point, we cannot rely on remove_breakpoint
7642              succeeding so we must mark the breakpoint as not inserted
7643              to prevent future errors occurring in remove_breakpoints.  */
7644           loc->inserted = 0;
7645
7646           /* This may cause duplicate notifications for the same breakpoint.  */
7647           gdb::observers::breakpoint_modified.notify (b);
7648
7649           if (!disabled_shlib_breaks)
7650             {
7651               target_terminal::ours_for_output ();
7652               warning (_("Temporarily disabling breakpoints "
7653                          "for unloaded shared library \"%s\""),
7654                        solib->so_name);
7655             }
7656           disabled_shlib_breaks = 1;
7657         }
7658     }
7659 }
7660
7661 /* Disable any breakpoints and tracepoints in OBJFILE upon
7662    notification of free_objfile.  Only apply to enabled breakpoints,
7663    disabled ones can just stay disabled.  */
7664
7665 static void
7666 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7667 {
7668   if (objfile == NULL)
7669     return;
7670
7671   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7672      managed by the user with add-symbol-file/remove-symbol-file.
7673      Similarly to how breakpoints in shared libraries are handled in
7674      response to "nosharedlibrary", mark breakpoints in such modules
7675      shlib_disabled so they end up uninserted on the next global
7676      location list update.  Shared libraries not loaded by the user
7677      aren't handled here -- they're already handled in
7678      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7679      solib_unloaded observer.  We skip objfiles that are not
7680      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7681      main objfile).  */
7682   if ((objfile->flags & OBJF_SHARED) == 0
7683       || (objfile->flags & OBJF_USERLOADED) == 0)
7684     return;
7685
7686   for (breakpoint *b : all_breakpoints ())
7687     {
7688       int bp_modified = 0;
7689
7690       if (!is_breakpoint (b) && !is_tracepoint (b))
7691         continue;
7692
7693       for (bp_location *loc : b->locations ())
7694         {
7695           CORE_ADDR loc_addr = loc->address;
7696
7697           if (loc->loc_type != bp_loc_hardware_breakpoint
7698               && loc->loc_type != bp_loc_software_breakpoint)
7699             continue;
7700
7701           if (loc->shlib_disabled != 0)
7702             continue;
7703
7704           if (objfile->pspace != loc->pspace)
7705             continue;
7706
7707           if (loc->loc_type != bp_loc_hardware_breakpoint
7708               && loc->loc_type != bp_loc_software_breakpoint)
7709             continue;
7710
7711           if (is_addr_in_objfile (loc_addr, objfile))
7712             {
7713               loc->shlib_disabled = 1;
7714               /* At this point, we don't know whether the object was
7715                  unmapped from the inferior or not, so leave the
7716                  inserted flag alone.  We'll handle failure to
7717                  uninsert quietly, in case the object was indeed
7718                  unmapped.  */
7719
7720               mark_breakpoint_location_modified (loc);
7721
7722               bp_modified = 1;
7723             }
7724         }
7725
7726       if (bp_modified)
7727         gdb::observers::breakpoint_modified.notify (b);
7728     }
7729 }
7730
7731 /* FORK & VFORK catchpoints.  */
7732
7733 /* An instance of this type is used to represent a fork or vfork
7734    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7735    to CATCH_FORK_BREAKPOINT_OPS.  */
7736
7737 struct fork_catchpoint : public breakpoint
7738 {
7739   /* Process id of a child process whose forking triggered this
7740      catchpoint.  This field is only valid immediately after this
7741      catchpoint has triggered.  */
7742   ptid_t forked_inferior_pid;
7743 };
7744
7745 /* Implement the "insert" breakpoint_ops method for fork
7746    catchpoints.  */
7747
7748 static int
7749 insert_catch_fork (struct bp_location *bl)
7750 {
7751   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7752 }
7753
7754 /* Implement the "remove" breakpoint_ops method for fork
7755    catchpoints.  */
7756
7757 static int
7758 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7759 {
7760   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7761 }
7762
7763 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7764    catchpoints.  */
7765
7766 static int
7767 breakpoint_hit_catch_fork (const struct bp_location *bl,
7768                            const address_space *aspace, CORE_ADDR bp_addr,
7769                            const struct target_waitstatus *ws)
7770 {
7771   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7772
7773   if (ws->kind != TARGET_WAITKIND_FORKED)
7774     return 0;
7775
7776   c->forked_inferior_pid = ws->value.related_pid;
7777   return 1;
7778 }
7779
7780 /* Implement the "print_it" breakpoint_ops method for fork
7781    catchpoints.  */
7782
7783 static enum print_stop_action
7784 print_it_catch_fork (bpstat bs)
7785 {
7786   struct ui_out *uiout = current_uiout;
7787   struct breakpoint *b = bs->breakpoint_at;
7788   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7789
7790   annotate_catchpoint (b->number);
7791   maybe_print_thread_hit_breakpoint (uiout);
7792   if (b->disposition == disp_del)
7793     uiout->text ("Temporary catchpoint ");
7794   else
7795     uiout->text ("Catchpoint ");
7796   if (uiout->is_mi_like_p ())
7797     {
7798       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7799       uiout->field_string ("disp", bpdisp_text (b->disposition));
7800     }
7801   uiout->field_signed ("bkptno", b->number);
7802   uiout->text (" (forked process ");
7803   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7804   uiout->text ("), ");
7805   return PRINT_SRC_AND_LOC;
7806 }
7807
7808 /* Implement the "print_one" breakpoint_ops method for fork
7809    catchpoints.  */
7810
7811 static void
7812 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7813 {
7814   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7815   struct value_print_options opts;
7816   struct ui_out *uiout = current_uiout;
7817
7818   get_user_print_options (&opts);
7819
7820   /* Field 4, the address, is omitted (which makes the columns not
7821      line up too nicely with the headers, but the effect is relatively
7822      readable).  */
7823   if (opts.addressprint)
7824     uiout->field_skip ("addr");
7825   annotate_field (5);
7826   uiout->text ("fork");
7827   if (c->forked_inferior_pid != null_ptid)
7828     {
7829       uiout->text (", process ");
7830       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7831       uiout->spaces (1);
7832     }
7833
7834   if (uiout->is_mi_like_p ())
7835     uiout->field_string ("catch-type", "fork");
7836 }
7837
7838 /* Implement the "print_mention" breakpoint_ops method for fork
7839    catchpoints.  */
7840
7841 static void
7842 print_mention_catch_fork (struct breakpoint *b)
7843 {
7844   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7845 }
7846
7847 /* Implement the "print_recreate" breakpoint_ops method for fork
7848    catchpoints.  */
7849
7850 static void
7851 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7852 {
7853   fprintf_unfiltered (fp, "catch fork");
7854   print_recreate_thread (b, fp);
7855 }
7856
7857 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7858
7859 static struct breakpoint_ops catch_fork_breakpoint_ops;
7860
7861 /* Implement the "insert" breakpoint_ops method for vfork
7862    catchpoints.  */
7863
7864 static int
7865 insert_catch_vfork (struct bp_location *bl)
7866 {
7867   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7868 }
7869
7870 /* Implement the "remove" breakpoint_ops method for vfork
7871    catchpoints.  */
7872
7873 static int
7874 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7875 {
7876   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7877 }
7878
7879 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7880    catchpoints.  */
7881
7882 static int
7883 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7884                             const address_space *aspace, CORE_ADDR bp_addr,
7885                             const struct target_waitstatus *ws)
7886 {
7887   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7888
7889   if (ws->kind != TARGET_WAITKIND_VFORKED)
7890     return 0;
7891
7892   c->forked_inferior_pid = ws->value.related_pid;
7893   return 1;
7894 }
7895
7896 /* Implement the "print_it" breakpoint_ops method for vfork
7897    catchpoints.  */
7898
7899 static enum print_stop_action
7900 print_it_catch_vfork (bpstat bs)
7901 {
7902   struct ui_out *uiout = current_uiout;
7903   struct breakpoint *b = bs->breakpoint_at;
7904   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7905
7906   annotate_catchpoint (b->number);
7907   maybe_print_thread_hit_breakpoint (uiout);
7908   if (b->disposition == disp_del)
7909     uiout->text ("Temporary catchpoint ");
7910   else
7911     uiout->text ("Catchpoint ");
7912   if (uiout->is_mi_like_p ())
7913     {
7914       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7915       uiout->field_string ("disp", bpdisp_text (b->disposition));
7916     }
7917   uiout->field_signed ("bkptno", b->number);
7918   uiout->text (" (vforked process ");
7919   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7920   uiout->text ("), ");
7921   return PRINT_SRC_AND_LOC;
7922 }
7923
7924 /* Implement the "print_one" breakpoint_ops method for vfork
7925    catchpoints.  */
7926
7927 static void
7928 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7929 {
7930   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7931   struct value_print_options opts;
7932   struct ui_out *uiout = current_uiout;
7933
7934   get_user_print_options (&opts);
7935   /* Field 4, the address, is omitted (which makes the columns not
7936      line up too nicely with the headers, but the effect is relatively
7937      readable).  */
7938   if (opts.addressprint)
7939     uiout->field_skip ("addr");
7940   annotate_field (5);
7941   uiout->text ("vfork");
7942   if (c->forked_inferior_pid != null_ptid)
7943     {
7944       uiout->text (", process ");
7945       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7946       uiout->spaces (1);
7947     }
7948
7949   if (uiout->is_mi_like_p ())
7950     uiout->field_string ("catch-type", "vfork");
7951 }
7952
7953 /* Implement the "print_mention" breakpoint_ops method for vfork
7954    catchpoints.  */
7955
7956 static void
7957 print_mention_catch_vfork (struct breakpoint *b)
7958 {
7959   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7960 }
7961
7962 /* Implement the "print_recreate" breakpoint_ops method for vfork
7963    catchpoints.  */
7964
7965 static void
7966 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7967 {
7968   fprintf_unfiltered (fp, "catch vfork");
7969   print_recreate_thread (b, fp);
7970 }
7971
7972 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7973
7974 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7975
7976 /* An instance of this type is used to represent an solib catchpoint.
7977    A breakpoint is really of this type iff its ops pointer points to
7978    CATCH_SOLIB_BREAKPOINT_OPS.  */
7979
7980 struct solib_catchpoint : public breakpoint
7981 {
7982   ~solib_catchpoint () override;
7983
7984   /* True for "catch load", false for "catch unload".  */
7985   bool is_load;
7986
7987   /* Regular expression to match, if any.  COMPILED is only valid when
7988      REGEX is non-NULL.  */
7989   char *regex;
7990   std::unique_ptr<compiled_regex> compiled;
7991 };
7992
7993 solib_catchpoint::~solib_catchpoint ()
7994 {
7995   xfree (this->regex);
7996 }
7997
7998 static int
7999 insert_catch_solib (struct bp_location *ignore)
8000 {
8001   return 0;
8002 }
8003
8004 static int
8005 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8006 {
8007   return 0;
8008 }
8009
8010 static int
8011 breakpoint_hit_catch_solib (const struct bp_location *bl,
8012                             const address_space *aspace,
8013                             CORE_ADDR bp_addr,
8014                             const struct target_waitstatus *ws)
8015 {
8016   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8017
8018   if (ws->kind == TARGET_WAITKIND_LOADED)
8019     return 1;
8020
8021   for (breakpoint *other : all_breakpoints ())
8022     {
8023       if (other == bl->owner)
8024         continue;
8025
8026       if (other->type != bp_shlib_event)
8027         continue;
8028
8029       if (self->pspace != NULL && other->pspace != self->pspace)
8030         continue;
8031
8032       for (bp_location *other_bl : other->locations ())
8033         {
8034           if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8035             return 1;
8036         }
8037     }
8038
8039   return 0;
8040 }
8041
8042 static void
8043 check_status_catch_solib (struct bpstats *bs)
8044 {
8045   struct solib_catchpoint *self
8046     = (struct solib_catchpoint *) bs->breakpoint_at;
8047
8048   if (self->is_load)
8049     {
8050       for (so_list *iter : current_program_space->added_solibs)
8051         {
8052           if (!self->regex
8053               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8054             return;
8055         }
8056     }
8057   else
8058     {
8059       for (const std::string &iter : current_program_space->deleted_solibs)
8060         {
8061           if (!self->regex
8062               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8063             return;
8064         }
8065     }
8066
8067   bs->stop = 0;
8068   bs->print_it = print_it_noop;
8069 }
8070
8071 static enum print_stop_action
8072 print_it_catch_solib (bpstat bs)
8073 {
8074   struct breakpoint *b = bs->breakpoint_at;
8075   struct ui_out *uiout = current_uiout;
8076
8077   annotate_catchpoint (b->number);
8078   maybe_print_thread_hit_breakpoint (uiout);
8079   if (b->disposition == disp_del)
8080     uiout->text ("Temporary catchpoint ");
8081   else
8082     uiout->text ("Catchpoint ");
8083   uiout->field_signed ("bkptno", b->number);
8084   uiout->text ("\n");
8085   if (uiout->is_mi_like_p ())
8086     uiout->field_string ("disp", bpdisp_text (b->disposition));
8087   print_solib_event (1);
8088   return PRINT_SRC_AND_LOC;
8089 }
8090
8091 static void
8092 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8093 {
8094   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8095   struct value_print_options opts;
8096   struct ui_out *uiout = current_uiout;
8097
8098   get_user_print_options (&opts);
8099   /* Field 4, the address, is omitted (which makes the columns not
8100      line up too nicely with the headers, but the effect is relatively
8101      readable).  */
8102   if (opts.addressprint)
8103     {
8104       annotate_field (4);
8105       uiout->field_skip ("addr");
8106     }
8107
8108   std::string msg;
8109   annotate_field (5);
8110   if (self->is_load)
8111     {
8112       if (self->regex)
8113         msg = string_printf (_("load of library matching %s"), self->regex);
8114       else
8115         msg = _("load of library");
8116     }
8117   else
8118     {
8119       if (self->regex)
8120         msg = string_printf (_("unload of library matching %s"), self->regex);
8121       else
8122         msg = _("unload of library");
8123     }
8124   uiout->field_string ("what", msg);
8125
8126   if (uiout->is_mi_like_p ())
8127     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8128 }
8129
8130 static void
8131 print_mention_catch_solib (struct breakpoint *b)
8132 {
8133   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8134
8135   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8136                    self->is_load ? "load" : "unload");
8137 }
8138
8139 static void
8140 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8141 {
8142   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8143
8144   fprintf_unfiltered (fp, "%s %s",
8145                       b->disposition == disp_del ? "tcatch" : "catch",
8146                       self->is_load ? "load" : "unload");
8147   if (self->regex)
8148     fprintf_unfiltered (fp, " %s", self->regex);
8149   fprintf_unfiltered (fp, "\n");
8150 }
8151
8152 static struct breakpoint_ops catch_solib_breakpoint_ops;
8153
8154 /* See breakpoint.h.  */
8155
8156 void
8157 add_solib_catchpoint (const char *arg, bool is_load, bool is_temp, bool enabled)
8158 {
8159   struct gdbarch *gdbarch = get_current_arch ();
8160
8161   if (!arg)
8162     arg = "";
8163   arg = skip_spaces (arg);
8164
8165   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8166
8167   if (*arg != '\0')
8168     {
8169       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8170                                              _("Invalid regexp")));
8171       c->regex = xstrdup (arg);
8172     }
8173
8174   c->is_load = is_load;
8175   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8176                    &catch_solib_breakpoint_ops);
8177
8178   c->enable_state = enabled ? bp_enabled : bp_disabled;
8179
8180   install_breakpoint (0, std::move (c), 1);
8181 }
8182
8183 /* A helper function that does all the work for "catch load" and
8184    "catch unload".  */
8185
8186 static void
8187 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8188                       struct cmd_list_element *command)
8189 {
8190   const int enabled = 1;
8191   bool temp = get_cmd_context (command) == CATCH_TEMPORARY;
8192
8193   add_solib_catchpoint (arg, is_load, temp, enabled);
8194 }
8195
8196 static void
8197 catch_load_command_1 (const char *arg, int from_tty,
8198                       struct cmd_list_element *command)
8199 {
8200   catch_load_or_unload (arg, from_tty, 1, command);
8201 }
8202
8203 static void
8204 catch_unload_command_1 (const char *arg, int from_tty,
8205                         struct cmd_list_element *command)
8206 {
8207   catch_load_or_unload (arg, from_tty, 0, command);
8208 }
8209
8210 /* See breakpoint.h.  */
8211
8212 void
8213 init_catchpoint (struct breakpoint *b,
8214                  struct gdbarch *gdbarch, bool temp,
8215                  const char *cond_string,
8216                  const struct breakpoint_ops *ops)
8217 {
8218   symtab_and_line sal;
8219   sal.pspace = current_program_space;
8220
8221   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8222
8223   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8224   b->disposition = temp ? disp_del : disp_donttouch;
8225 }
8226
8227 void
8228 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8229 {
8230   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8231   set_breakpoint_number (internal, b);
8232   if (is_tracepoint (b))
8233     set_tracepoint_count (breakpoint_count);
8234   if (!internal)
8235     mention (b);
8236   gdb::observers::breakpoint_created.notify (b);
8237
8238   if (update_gll)
8239     update_global_location_list (UGLL_MAY_INSERT);
8240 }
8241
8242 static void
8243 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8244                                     bool temp, const char *cond_string,
8245                                     const struct breakpoint_ops *ops)
8246 {
8247   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8248
8249   init_catchpoint (c.get (), gdbarch, temp, cond_string, ops);
8250
8251   c->forked_inferior_pid = null_ptid;
8252
8253   install_breakpoint (0, std::move (c), 1);
8254 }
8255
8256 /* Exec catchpoints.  */
8257
8258 /* An instance of this type is used to represent an exec catchpoint.
8259    A breakpoint is really of this type iff its ops pointer points to
8260    CATCH_EXEC_BREAKPOINT_OPS.  */
8261
8262 struct exec_catchpoint : public breakpoint
8263 {
8264   ~exec_catchpoint () override;
8265
8266   /* Filename of a program whose exec triggered this catchpoint.
8267      This field is only valid immediately after this catchpoint has
8268      triggered.  */
8269   char *exec_pathname;
8270 };
8271
8272 /* Exec catchpoint destructor.  */
8273
8274 exec_catchpoint::~exec_catchpoint ()
8275 {
8276   xfree (this->exec_pathname);
8277 }
8278
8279 static int
8280 insert_catch_exec (struct bp_location *bl)
8281 {
8282   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8283 }
8284
8285 static int
8286 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8287 {
8288   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8289 }
8290
8291 static int
8292 breakpoint_hit_catch_exec (const struct bp_location *bl,
8293                            const address_space *aspace, CORE_ADDR bp_addr,
8294                            const struct target_waitstatus *ws)
8295 {
8296   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8297
8298   if (ws->kind != TARGET_WAITKIND_EXECD)
8299     return 0;
8300
8301   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8302   return 1;
8303 }
8304
8305 static enum print_stop_action
8306 print_it_catch_exec (bpstat bs)
8307 {
8308   struct ui_out *uiout = current_uiout;
8309   struct breakpoint *b = bs->breakpoint_at;
8310   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8311
8312   annotate_catchpoint (b->number);
8313   maybe_print_thread_hit_breakpoint (uiout);
8314   if (b->disposition == disp_del)
8315     uiout->text ("Temporary catchpoint ");
8316   else
8317     uiout->text ("Catchpoint ");
8318   if (uiout->is_mi_like_p ())
8319     {
8320       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8321       uiout->field_string ("disp", bpdisp_text (b->disposition));
8322     }
8323   uiout->field_signed ("bkptno", b->number);
8324   uiout->text (" (exec'd ");
8325   uiout->field_string ("new-exec", c->exec_pathname);
8326   uiout->text ("), ");
8327
8328   return PRINT_SRC_AND_LOC;
8329 }
8330
8331 static void
8332 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8333 {
8334   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8335   struct value_print_options opts;
8336   struct ui_out *uiout = current_uiout;
8337
8338   get_user_print_options (&opts);
8339
8340   /* Field 4, the address, is omitted (which makes the columns
8341      not line up too nicely with the headers, but the effect
8342      is relatively readable).  */
8343   if (opts.addressprint)
8344     uiout->field_skip ("addr");
8345   annotate_field (5);
8346   uiout->text ("exec");
8347   if (c->exec_pathname != NULL)
8348     {
8349       uiout->text (", program \"");
8350       uiout->field_string ("what", c->exec_pathname);
8351       uiout->text ("\" ");
8352     }
8353
8354   if (uiout->is_mi_like_p ())
8355     uiout->field_string ("catch-type", "exec");
8356 }
8357
8358 static void
8359 print_mention_catch_exec (struct breakpoint *b)
8360 {
8361   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8362 }
8363
8364 /* Implement the "print_recreate" breakpoint_ops method for exec
8365    catchpoints.  */
8366
8367 static void
8368 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8369 {
8370   fprintf_unfiltered (fp, "catch exec");
8371   print_recreate_thread (b, fp);
8372 }
8373
8374 static struct breakpoint_ops catch_exec_breakpoint_ops;
8375
8376 static int
8377 hw_breakpoint_used_count (void)
8378 {
8379   int i = 0;
8380
8381   for (breakpoint *b : all_breakpoints ())
8382     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8383       for (bp_location *bl : b->locations ())
8384         {
8385           /* Special types of hardware breakpoints may use more than
8386              one register.  */
8387           i += b->ops->resources_needed (bl);
8388         }
8389
8390   return i;
8391 }
8392
8393 /* Returns the resources B would use if it were a hardware
8394    watchpoint.  */
8395
8396 static int
8397 hw_watchpoint_use_count (struct breakpoint *b)
8398 {
8399   int i = 0;
8400
8401   if (!breakpoint_enabled (b))
8402     return 0;
8403
8404   for (bp_location *bl : b->locations ())
8405     {
8406       /* Special types of hardware watchpoints may use more than
8407          one register.  */
8408       i += b->ops->resources_needed (bl);
8409     }
8410
8411   return i;
8412 }
8413
8414 /* Returns the sum the used resources of all hardware watchpoints of
8415    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8416    the sum of the used resources of all hardware watchpoints of other
8417    types _not_ TYPE.  */
8418
8419 static int
8420 hw_watchpoint_used_count_others (struct breakpoint *except,
8421                                  enum bptype type, int *other_type_used)
8422 {
8423   int i = 0;
8424
8425   *other_type_used = 0;
8426   for (breakpoint *b : all_breakpoints ())
8427     {
8428       if (b == except)
8429         continue;
8430       if (!breakpoint_enabled (b))
8431         continue;
8432
8433       if (b->type == type)
8434         i += hw_watchpoint_use_count (b);
8435       else if (is_hardware_watchpoint (b))
8436         *other_type_used = 1;
8437     }
8438
8439   return i;
8440 }
8441
8442 void
8443 disable_watchpoints_before_interactive_call_start (void)
8444 {
8445   for (breakpoint *b : all_breakpoints ())
8446     if (is_watchpoint (b) && breakpoint_enabled (b))
8447       {
8448         b->enable_state = bp_call_disabled;
8449         update_global_location_list (UGLL_DONT_INSERT);
8450       }
8451 }
8452
8453 void
8454 enable_watchpoints_after_interactive_call_stop (void)
8455 {
8456   for (breakpoint *b : all_breakpoints ())
8457     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8458       {
8459         b->enable_state = bp_enabled;
8460         update_global_location_list (UGLL_MAY_INSERT);
8461       }
8462 }
8463
8464 void
8465 disable_breakpoints_before_startup (void)
8466 {
8467   current_program_space->executing_startup = 1;
8468   update_global_location_list (UGLL_DONT_INSERT);
8469 }
8470
8471 void
8472 enable_breakpoints_after_startup (void)
8473 {
8474   current_program_space->executing_startup = 0;
8475   breakpoint_re_set ();
8476 }
8477
8478 /* Create a new single-step breakpoint for thread THREAD, with no
8479    locations.  */
8480
8481 static struct breakpoint *
8482 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8483 {
8484   std::unique_ptr<breakpoint> b (new breakpoint ());
8485
8486   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8487                                         &momentary_breakpoint_ops);
8488
8489   b->disposition = disp_donttouch;
8490   b->frame_id = null_frame_id;
8491
8492   b->thread = thread;
8493   gdb_assert (b->thread != 0);
8494
8495   return add_to_breakpoint_chain (std::move (b));
8496 }
8497
8498 /* Set a momentary breakpoint of type TYPE at address specified by
8499    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8500    frame.  */
8501
8502 breakpoint_up
8503 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8504                           struct frame_id frame_id, enum bptype type)
8505 {
8506   struct breakpoint *b;
8507
8508   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8509      tail-called one.  */
8510   gdb_assert (!frame_id_artificial_p (frame_id));
8511
8512   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8513   b->enable_state = bp_enabled;
8514   b->disposition = disp_donttouch;
8515   b->frame_id = frame_id;
8516
8517   b->thread = inferior_thread ()->global_num;
8518
8519   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8520
8521   return breakpoint_up (b);
8522 }
8523
8524 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8525    The new breakpoint will have type TYPE, use OPS as its
8526    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8527
8528 static struct breakpoint *
8529 momentary_breakpoint_from_master (struct breakpoint *orig,
8530                                   enum bptype type,
8531                                   const struct breakpoint_ops *ops,
8532                                   int loc_enabled)
8533 {
8534   struct breakpoint *copy;
8535
8536   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8537   copy->loc = allocate_bp_location (copy);
8538   set_breakpoint_location_function (copy->loc);
8539
8540   copy->loc->gdbarch = orig->loc->gdbarch;
8541   copy->loc->requested_address = orig->loc->requested_address;
8542   copy->loc->address = orig->loc->address;
8543   copy->loc->section = orig->loc->section;
8544   copy->loc->pspace = orig->loc->pspace;
8545   copy->loc->probe = orig->loc->probe;
8546   copy->loc->line_number = orig->loc->line_number;
8547   copy->loc->symtab = orig->loc->symtab;
8548   copy->loc->enabled = loc_enabled;
8549   copy->frame_id = orig->frame_id;
8550   copy->thread = orig->thread;
8551   copy->pspace = orig->pspace;
8552
8553   copy->enable_state = bp_enabled;
8554   copy->disposition = disp_donttouch;
8555   copy->number = internal_breakpoint_number--;
8556
8557   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8558   return copy;
8559 }
8560
8561 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8562    ORIG is NULL.  */
8563
8564 struct breakpoint *
8565 clone_momentary_breakpoint (struct breakpoint *orig)
8566 {
8567   /* If there's nothing to clone, then return nothing.  */
8568   if (orig == NULL)
8569     return NULL;
8570
8571   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8572 }
8573
8574 breakpoint_up
8575 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8576                                 enum bptype type)
8577 {
8578   struct symtab_and_line sal;
8579
8580   sal = find_pc_line (pc, 0);
8581   sal.pc = pc;
8582   sal.section = find_pc_overlay (pc);
8583   sal.explicit_pc = 1;
8584
8585   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8586 }
8587 \f
8588
8589 /* Tell the user we have just set a breakpoint B.  */
8590
8591 static void
8592 mention (struct breakpoint *b)
8593 {
8594   b->ops->print_mention (b);
8595   current_uiout->text ("\n");
8596 }
8597 \f
8598
8599 static bool bp_loc_is_permanent (struct bp_location *loc);
8600
8601 /* Handle "set breakpoint auto-hw on".
8602
8603    If the explicitly specified breakpoint type is not hardware
8604    breakpoint, check the memory map to see whether the breakpoint
8605    address is in read-only memory.
8606
8607    - location type is not hardware breakpoint, memory is read-only.
8608    We change the type of the location to hardware breakpoint.
8609
8610    - location type is hardware breakpoint, memory is read-write.  This
8611    means we've previously made the location hardware one, but then the
8612    memory map changed, so we undo.
8613 */
8614
8615 static void
8616 handle_automatic_hardware_breakpoints (bp_location *bl)
8617 {
8618   if (automatic_hardware_breakpoints
8619       && bl->owner->type != bp_hardware_breakpoint
8620       && (bl->loc_type == bp_loc_software_breakpoint
8621           || bl->loc_type == bp_loc_hardware_breakpoint))
8622     {
8623       /* When breakpoints are removed, remove_breakpoints will use
8624          location types we've just set here, the only possible problem
8625          is that memory map has changed during running program, but
8626          it's not going to work anyway with current gdb.  */
8627       mem_region *mr = lookup_mem_region (bl->address);
8628
8629       if (mr != nullptr)
8630         {
8631           enum bp_loc_type new_type;
8632
8633           if (mr->attrib.mode != MEM_RW)
8634             new_type = bp_loc_hardware_breakpoint;
8635           else
8636             new_type = bp_loc_software_breakpoint;
8637
8638           if (new_type != bl->loc_type)
8639             {
8640               static bool said = false;
8641
8642               bl->loc_type = new_type;
8643               if (!said)
8644                 {
8645                   fprintf_filtered (gdb_stdout,
8646                                     _("Note: automatically using "
8647                                       "hardware breakpoints for "
8648                                       "read-only addresses.\n"));
8649                   said = true;
8650                 }
8651             }
8652         }
8653     }
8654 }
8655
8656 static struct bp_location *
8657 add_location_to_breakpoint (struct breakpoint *b,
8658                             const struct symtab_and_line *sal)
8659 {
8660   struct bp_location *loc, **tmp;
8661   CORE_ADDR adjusted_address;
8662   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8663
8664   if (loc_gdbarch == NULL)
8665     loc_gdbarch = b->gdbarch;
8666
8667   /* Adjust the breakpoint's address prior to allocating a location.
8668      Once we call allocate_bp_location(), that mostly uninitialized
8669      location will be placed on the location chain.  Adjustment of the
8670      breakpoint may cause target_read_memory() to be called and we do
8671      not want its scan of the location chain to find a breakpoint and
8672      location that's only been partially initialized.  */
8673   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8674                                                 sal->pc, b->type);
8675
8676   /* Sort the locations by their ADDRESS.  */
8677   loc = allocate_bp_location (b);
8678   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8679        tmp = &((*tmp)->next))
8680     ;
8681   loc->next = *tmp;
8682   *tmp = loc;
8683
8684   loc->requested_address = sal->pc;
8685   loc->address = adjusted_address;
8686   loc->pspace = sal->pspace;
8687   loc->probe.prob = sal->prob;
8688   loc->probe.objfile = sal->objfile;
8689   gdb_assert (loc->pspace != NULL);
8690   loc->section = sal->section;
8691   loc->gdbarch = loc_gdbarch;
8692   loc->line_number = sal->line;
8693   loc->symtab = sal->symtab;
8694   loc->symbol = sal->symbol;
8695   loc->msymbol = sal->msymbol;
8696   loc->objfile = sal->objfile;
8697
8698   set_breakpoint_location_function (loc);
8699
8700   /* While by definition, permanent breakpoints are already present in the
8701      code, we don't mark the location as inserted.  Normally one would expect
8702      that GDB could rely on that breakpoint instruction to stop the program,
8703      thus removing the need to insert its own breakpoint, except that executing
8704      the breakpoint instruction can kill the target instead of reporting a
8705      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8706      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8707      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8708      breakpoint be inserted normally results in QEMU knowing about the GDB
8709      breakpoint, and thus trap before the breakpoint instruction is executed.
8710      (If GDB later needs to continue execution past the permanent breakpoint,
8711      it manually increments the PC, thus avoiding executing the breakpoint
8712      instruction.)  */
8713   if (bp_loc_is_permanent (loc))
8714     loc->permanent = 1;
8715
8716   return loc;
8717 }
8718 \f
8719
8720 /* Return true if LOC is pointing to a permanent breakpoint,
8721    return false otherwise.  */
8722
8723 static bool
8724 bp_loc_is_permanent (struct bp_location *loc)
8725 {
8726   gdb_assert (loc != NULL);
8727
8728   /* If we have a non-breakpoint-backed catchpoint or a software
8729      watchpoint, just return 0.  We should not attempt to read from
8730      the addresses the locations of these breakpoint types point to.
8731      gdbarch_program_breakpoint_here_p, below, will attempt to read
8732      memory.  */
8733   if (!bl_address_is_meaningful (loc))
8734     return false;
8735
8736   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8737   switch_to_program_space_and_thread (loc->pspace);
8738   return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8739 }
8740
8741 /* Build a command list for the dprintf corresponding to the current
8742    settings of the dprintf style options.  */
8743
8744 static void
8745 update_dprintf_command_list (struct breakpoint *b)
8746 {
8747   char *dprintf_args = b->extra_string;
8748   char *printf_line = NULL;
8749
8750   if (!dprintf_args)
8751     return;
8752
8753   dprintf_args = skip_spaces (dprintf_args);
8754
8755   /* Allow a comma, as it may have terminated a location, but don't
8756      insist on it.  */
8757   if (*dprintf_args == ',')
8758     ++dprintf_args;
8759   dprintf_args = skip_spaces (dprintf_args);
8760
8761   if (*dprintf_args != '"')
8762     error (_("Bad format string, missing '\"'."));
8763
8764   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8765     printf_line = xstrprintf ("printf %s", dprintf_args);
8766   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8767     {
8768       if (!dprintf_function)
8769         error (_("No function supplied for dprintf call"));
8770
8771       if (dprintf_channel && strlen (dprintf_channel) > 0)
8772         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8773                                   dprintf_function,
8774                                   dprintf_channel,
8775                                   dprintf_args);
8776       else
8777         printf_line = xstrprintf ("call (void) %s (%s)",
8778                                   dprintf_function,
8779                                   dprintf_args);
8780     }
8781   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8782     {
8783       if (target_can_run_breakpoint_commands ())
8784         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8785       else
8786         {
8787           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8788           printf_line = xstrprintf ("printf %s", dprintf_args);
8789         }
8790     }
8791   else
8792     internal_error (__FILE__, __LINE__,
8793                     _("Invalid dprintf style."));
8794
8795   gdb_assert (printf_line != NULL);
8796
8797   /* Manufacture a printf sequence.  */
8798   struct command_line *printf_cmd_line
8799     = new struct command_line (simple_control, printf_line);
8800   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8801                                                     command_lines_deleter ()));
8802 }
8803
8804 /* Update all dprintf commands, making their command lists reflect
8805    current style settings.  */
8806
8807 static void
8808 update_dprintf_commands (const char *args, int from_tty,
8809                          struct cmd_list_element *c)
8810 {
8811   for (breakpoint *b : all_breakpoints ())
8812     if (b->type == bp_dprintf)
8813         update_dprintf_command_list (b);
8814 }
8815
8816 /* Create a breakpoint with SAL as location.  Use LOCATION
8817    as a description of the location, and COND_STRING
8818    as condition expression.  If LOCATION is NULL then create an
8819    "address location" from the address in the SAL.  */
8820
8821 static void
8822 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8823                      gdb::array_view<const symtab_and_line> sals,
8824                      event_location_up &&location,
8825                      gdb::unique_xmalloc_ptr<char> filter,
8826                      gdb::unique_xmalloc_ptr<char> cond_string,
8827                      gdb::unique_xmalloc_ptr<char> extra_string,
8828                      enum bptype type, enum bpdisp disposition,
8829                      int thread, int task, int ignore_count,
8830                      const struct breakpoint_ops *ops, int from_tty,
8831                      int enabled, int internal, unsigned flags,
8832                      int display_canonical)
8833 {
8834   int i;
8835
8836   if (type == bp_hardware_breakpoint)
8837     {
8838       int target_resources_ok;
8839
8840       i = hw_breakpoint_used_count ();
8841       target_resources_ok =
8842         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8843                                             i + 1, 0);
8844       if (target_resources_ok == 0)
8845         error (_("No hardware breakpoint support in the target."));
8846       else if (target_resources_ok < 0)
8847         error (_("Hardware breakpoints used exceeds limit."));
8848     }
8849
8850   gdb_assert (!sals.empty ());
8851
8852   for (const auto &sal : sals)
8853     {
8854       struct bp_location *loc;
8855
8856       if (from_tty)
8857         {
8858           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8859           if (!loc_gdbarch)
8860             loc_gdbarch = gdbarch;
8861
8862           describe_other_breakpoints (loc_gdbarch,
8863                                       sal.pspace, sal.pc, sal.section, thread);
8864         }
8865
8866       if (&sal == &sals[0])
8867         {
8868           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8869           b->thread = thread;
8870           b->task = task;
8871
8872           b->cond_string = cond_string.release ();
8873           b->extra_string = extra_string.release ();
8874           b->ignore_count = ignore_count;
8875           b->enable_state = enabled ? bp_enabled : bp_disabled;
8876           b->disposition = disposition;
8877
8878           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8879             b->loc->inserted = 1;
8880
8881           if (type == bp_static_tracepoint)
8882             {
8883               struct tracepoint *t = (struct tracepoint *) b;
8884               struct static_tracepoint_marker marker;
8885
8886               if (strace_marker_p (b))
8887                 {
8888                   /* We already know the marker exists, otherwise, we
8889                      wouldn't see a sal for it.  */
8890                   const char *p
8891                     = &event_location_to_string (b->location.get ())[3];
8892                   const char *endp;
8893
8894                   p = skip_spaces (p);
8895
8896                   endp = skip_to_space (p);
8897
8898                   t->static_trace_marker_id.assign (p, endp - p);
8899
8900                   printf_filtered (_("Probed static tracepoint "
8901                                      "marker \"%s\"\n"),
8902                                    t->static_trace_marker_id.c_str ());
8903                 }
8904               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8905                 {
8906                   t->static_trace_marker_id = std::move (marker.str_id);
8907
8908                   printf_filtered (_("Probed static tracepoint "
8909                                      "marker \"%s\"\n"),
8910                                    t->static_trace_marker_id.c_str ());
8911                 }
8912               else
8913                 warning (_("Couldn't determine the static "
8914                            "tracepoint marker to probe"));
8915             }
8916
8917           loc = b->loc;
8918         }
8919       else
8920         {
8921           loc = add_location_to_breakpoint (b, &sal);
8922           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8923             loc->inserted = 1;
8924         }
8925
8926       /* Do not set breakpoint locations conditions yet.  As locations
8927          are inserted, they get sorted based on their addresses.  Let
8928          the list stabilize to have reliable location numbers.  */
8929
8930       /* Dynamic printf requires and uses additional arguments on the
8931          command line, otherwise it's an error.  */
8932       if (type == bp_dprintf)
8933         {
8934           if (b->extra_string)
8935             update_dprintf_command_list (b);
8936           else
8937             error (_("Format string required"));
8938         }
8939       else if (b->extra_string)
8940         error (_("Garbage '%s' at end of command"), b->extra_string);
8941     }
8942
8943
8944   /* The order of the locations is now stable.  Set the location
8945      condition using the location's number.  */
8946   int loc_num = 1;
8947   for (bp_location *loc : b->locations ())
8948     {
8949       if (b->cond_string != nullptr)
8950         set_breakpoint_location_condition (b->cond_string, loc, b->number,
8951                                            loc_num);
8952
8953       ++loc_num;
8954     }
8955
8956   b->display_canonical = display_canonical;
8957   if (location != NULL)
8958     b->location = std::move (location);
8959   else
8960     b->location = new_address_location (b->loc->address, NULL, 0);
8961   b->filter = std::move (filter);
8962 }
8963
8964 static void
8965 create_breakpoint_sal (struct gdbarch *gdbarch,
8966                        gdb::array_view<const symtab_and_line> sals,
8967                        event_location_up &&location,
8968                        gdb::unique_xmalloc_ptr<char> filter,
8969                        gdb::unique_xmalloc_ptr<char> cond_string,
8970                        gdb::unique_xmalloc_ptr<char> extra_string,
8971                        enum bptype type, enum bpdisp disposition,
8972                        int thread, int task, int ignore_count,
8973                        const struct breakpoint_ops *ops, int from_tty,
8974                        int enabled, int internal, unsigned flags,
8975                        int display_canonical)
8976 {
8977   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8978
8979   init_breakpoint_sal (b.get (), gdbarch,
8980                        sals, std::move (location),
8981                        std::move (filter),
8982                        std::move (cond_string),
8983                        std::move (extra_string),
8984                        type, disposition,
8985                        thread, task, ignore_count,
8986                        ops, from_tty,
8987                        enabled, internal, flags,
8988                        display_canonical);
8989
8990   install_breakpoint (internal, std::move (b), 0);
8991 }
8992
8993 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8994    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8995    value.  COND_STRING, if not NULL, specified the condition to be
8996    used for all breakpoints.  Essentially the only case where
8997    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8998    function.  In that case, it's still not possible to specify
8999    separate conditions for different overloaded functions, so
9000    we take just a single condition string.
9001    
9002    NOTE: If the function succeeds, the caller is expected to cleanup
9003    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9004    array contents).  If the function fails (error() is called), the
9005    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9006    COND and SALS arrays and each of those arrays contents.  */
9007
9008 static void
9009 create_breakpoints_sal (struct gdbarch *gdbarch,
9010                         struct linespec_result *canonical,
9011                         gdb::unique_xmalloc_ptr<char> cond_string,
9012                         gdb::unique_xmalloc_ptr<char> extra_string,
9013                         enum bptype type, enum bpdisp disposition,
9014                         int thread, int task, int ignore_count,
9015                         const struct breakpoint_ops *ops, int from_tty,
9016                         int enabled, int internal, unsigned flags)
9017 {
9018   if (canonical->pre_expanded)
9019     gdb_assert (canonical->lsals.size () == 1);
9020
9021   for (const auto &lsal : canonical->lsals)
9022     {
9023       /* Note that 'location' can be NULL in the case of a plain
9024          'break', without arguments.  */
9025       event_location_up location
9026         = (canonical->location != NULL
9027            ? copy_event_location (canonical->location.get ()) : NULL);
9028       gdb::unique_xmalloc_ptr<char> filter_string
9029         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9030
9031       create_breakpoint_sal (gdbarch, lsal.sals,
9032                              std::move (location),
9033                              std::move (filter_string),
9034                              std::move (cond_string),
9035                              std::move (extra_string),
9036                              type, disposition,
9037                              thread, task, ignore_count, ops,
9038                              from_tty, enabled, internal, flags,
9039                              canonical->special_display);
9040     }
9041 }
9042
9043 /* Parse LOCATION which is assumed to be a SAL specification possibly
9044    followed by conditionals.  On return, SALS contains an array of SAL
9045    addresses found.  LOCATION points to the end of the SAL (for
9046    linespec locations).
9047
9048    The array and the line spec strings are allocated on the heap, it is
9049    the caller's responsibility to free them.  */
9050
9051 static void
9052 parse_breakpoint_sals (struct event_location *location,
9053                        struct linespec_result *canonical)
9054 {
9055   struct symtab_and_line cursal;
9056
9057   if (event_location_type (location) == LINESPEC_LOCATION)
9058     {
9059       const char *spec = get_linespec_location (location)->spec_string;
9060
9061       if (spec == NULL)
9062         {
9063           /* The last displayed codepoint, if it's valid, is our default
9064              breakpoint address.  */
9065           if (last_displayed_sal_is_valid ())
9066             {
9067               /* Set sal's pspace, pc, symtab, and line to the values
9068                  corresponding to the last call to print_frame_info.
9069                  Be sure to reinitialize LINE with NOTCURRENT == 0
9070                  as the breakpoint line number is inappropriate otherwise.
9071                  find_pc_line would adjust PC, re-set it back.  */
9072               symtab_and_line sal = get_last_displayed_sal ();
9073               CORE_ADDR pc = sal.pc;
9074
9075               sal = find_pc_line (pc, 0);
9076
9077               /* "break" without arguments is equivalent to "break *PC"
9078                  where PC is the last displayed codepoint's address.  So
9079                  make sure to set sal.explicit_pc to prevent GDB from
9080                  trying to expand the list of sals to include all other
9081                  instances with the same symtab and line.  */
9082               sal.pc = pc;
9083               sal.explicit_pc = 1;
9084
9085               struct linespec_sals lsal;
9086               lsal.sals = {sal};
9087               lsal.canonical = NULL;
9088
9089               canonical->lsals.push_back (std::move (lsal));
9090               return;
9091             }
9092           else
9093             error (_("No default breakpoint address now."));
9094         }
9095     }
9096
9097   /* Force almost all breakpoints to be in terms of the
9098      current_source_symtab (which is decode_line_1's default).
9099      This should produce the results we want almost all of the
9100      time while leaving default_breakpoint_* alone.
9101
9102      ObjC: However, don't match an Objective-C method name which
9103      may have a '+' or '-' succeeded by a '['.  */
9104   cursal = get_current_source_symtab_and_line ();
9105   if (last_displayed_sal_is_valid ())
9106     {
9107       const char *spec = NULL;
9108
9109       if (event_location_type (location) == LINESPEC_LOCATION)
9110         spec = get_linespec_location (location)->spec_string;
9111
9112       if (!cursal.symtab
9113           || (spec != NULL
9114               && strchr ("+-", spec[0]) != NULL
9115               && spec[1] != '['))
9116         {
9117           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9118                             get_last_displayed_symtab (),
9119                             get_last_displayed_line (),
9120                             canonical, NULL, NULL);
9121           return;
9122         }
9123     }
9124
9125   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9126                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9127 }
9128
9129
9130 /* Convert each SAL into a real PC.  Verify that the PC can be
9131    inserted as a breakpoint.  If it can't throw an error.  */
9132
9133 static void
9134 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9135 {    
9136   for (auto &sal : sals)
9137     resolve_sal_pc (&sal);
9138 }
9139
9140 /* Fast tracepoints may have restrictions on valid locations.  For
9141    instance, a fast tracepoint using a jump instead of a trap will
9142    likely have to overwrite more bytes than a trap would, and so can
9143    only be placed where the instruction is longer than the jump, or a
9144    multi-instruction sequence does not have a jump into the middle of
9145    it, etc.  */
9146
9147 static void
9148 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9149                             gdb::array_view<const symtab_and_line> sals)
9150 {
9151   for (const auto &sal : sals)
9152     {
9153       struct gdbarch *sarch;
9154
9155       sarch = get_sal_arch (sal);
9156       /* We fall back to GDBARCH if there is no architecture
9157          associated with SAL.  */
9158       if (sarch == NULL)
9159         sarch = gdbarch;
9160       std::string msg;
9161       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9162         error (_("May not have a fast tracepoint at %s%s"),
9163                paddress (sarch, sal.pc), msg.c_str ());
9164     }
9165 }
9166
9167 /* Given TOK, a string specification of condition and thread, as
9168    accepted by the 'break' command, extract the condition
9169    string and thread number and set *COND_STRING and *THREAD.
9170    PC identifies the context at which the condition should be parsed.
9171    If no condition is found, *COND_STRING is set to NULL.
9172    If no thread is found, *THREAD is set to -1.  */
9173
9174 static void
9175 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9176                            char **cond_string, int *thread, int *task,
9177                            char **rest)
9178 {
9179   *cond_string = NULL;
9180   *thread = -1;
9181   *task = 0;
9182   *rest = NULL;
9183   bool force = false;
9184
9185   while (tok && *tok)
9186     {
9187       const char *end_tok;
9188       int toklen;
9189       const char *cond_start = NULL;
9190       const char *cond_end = NULL;
9191
9192       tok = skip_spaces (tok);
9193
9194       if ((*tok == '"' || *tok == ',') && rest)
9195         {
9196           *rest = savestring (tok, strlen (tok));
9197           return;
9198         }
9199
9200       end_tok = skip_to_space (tok);
9201
9202       toklen = end_tok - tok;
9203
9204       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9205         {
9206           tok = cond_start = end_tok + 1;
9207           try
9208             {
9209               parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9210             }
9211           catch (const gdb_exception_error &)
9212             {
9213               if (!force)
9214                 throw;
9215               else
9216                 tok = tok + strlen (tok);
9217             }
9218           cond_end = tok;
9219           *cond_string = savestring (cond_start, cond_end - cond_start);
9220         }
9221       else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
9222         {
9223           tok = tok + toklen;
9224           force = true;
9225         }
9226       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9227         {
9228           const char *tmptok;
9229           struct thread_info *thr;
9230
9231           tok = end_tok + 1;
9232           thr = parse_thread_id (tok, &tmptok);
9233           if (tok == tmptok)
9234             error (_("Junk after thread keyword."));
9235           *thread = thr->global_num;
9236           tok = tmptok;
9237         }
9238       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9239         {
9240           char *tmptok;
9241
9242           tok = end_tok + 1;
9243           *task = strtol (tok, &tmptok, 0);
9244           if (tok == tmptok)
9245             error (_("Junk after task keyword."));
9246           if (!valid_task_id (*task))
9247             error (_("Unknown task %d."), *task);
9248           tok = tmptok;
9249         }
9250       else if (rest)
9251         {
9252           *rest = savestring (tok, strlen (tok));
9253           return;
9254         }
9255       else
9256         error (_("Junk at end of arguments."));
9257     }
9258 }
9259
9260 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
9261    succeeds.  The parsed values are written to COND_STRING, THREAD,
9262    TASK, and REST.  See the comment of 'find_condition_and_thread'
9263    for the description of these parameters and INPUT.  */
9264
9265 static void
9266 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
9267                                     const char *input, char **cond_string,
9268                                     int *thread, int *task, char **rest)
9269 {
9270   int num_failures = 0;
9271   for (auto &sal : sals)
9272     {
9273       char *cond = nullptr;
9274       int thread_id = 0;
9275       int task_id = 0;
9276       char *remaining = nullptr;
9277
9278       /* Here we want to parse 'arg' to separate condition from thread
9279          number.  But because parsing happens in a context and the
9280          contexts of sals might be different, try each until there is
9281          success.  Finding one successful parse is sufficient for our
9282          goal.  When setting the breakpoint we'll re-parse the
9283          condition in the context of each sal.  */
9284       try
9285         {
9286           find_condition_and_thread (input, sal.pc, &cond, &thread_id,
9287                                      &task_id, &remaining);
9288           *cond_string = cond;
9289           *thread = thread_id;
9290           *task = task_id;
9291           *rest = remaining;
9292           break;
9293         }
9294       catch (const gdb_exception_error &e)
9295         {
9296           num_failures++;
9297           /* If no sal remains, do not continue.  */
9298           if (num_failures == sals.size ())
9299             throw;
9300         }
9301     }
9302 }
9303
9304 /* Decode a static tracepoint marker spec.  */
9305
9306 static std::vector<symtab_and_line>
9307 decode_static_tracepoint_spec (const char **arg_p)
9308 {
9309   const char *p = &(*arg_p)[3];
9310   const char *endp;
9311
9312   p = skip_spaces (p);
9313
9314   endp = skip_to_space (p);
9315
9316   std::string marker_str (p, endp - p);
9317
9318   std::vector<static_tracepoint_marker> markers
9319     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9320   if (markers.empty ())
9321     error (_("No known static tracepoint marker named %s"),
9322            marker_str.c_str ());
9323
9324   std::vector<symtab_and_line> sals;
9325   sals.reserve (markers.size ());
9326
9327   for (const static_tracepoint_marker &marker : markers)
9328     {
9329       symtab_and_line sal = find_pc_line (marker.address, 0);
9330       sal.pc = marker.address;
9331       sals.push_back (sal);
9332    }
9333
9334   *arg_p = endp;
9335   return sals;
9336 }
9337
9338 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
9339    according to IS_TRACEPOINT.  */
9340
9341 static const struct breakpoint_ops *
9342 breakpoint_ops_for_event_location_type (enum event_location_type location_type,
9343                                         bool is_tracepoint)
9344 {
9345   if (is_tracepoint)
9346     {
9347       if (location_type == PROBE_LOCATION)
9348         return &tracepoint_probe_breakpoint_ops;
9349       else
9350         return &tracepoint_breakpoint_ops;
9351     }
9352   else
9353     {
9354       if (location_type == PROBE_LOCATION)
9355         return &bkpt_probe_breakpoint_ops;
9356       else
9357         return &bkpt_breakpoint_ops;
9358     }
9359 }
9360
9361 /* See breakpoint.h.  */
9362
9363 const struct breakpoint_ops *
9364 breakpoint_ops_for_event_location (const struct event_location *location,
9365                                    bool is_tracepoint)
9366 {
9367   if (location != nullptr)
9368     return breakpoint_ops_for_event_location_type
9369       (event_location_type (location), is_tracepoint);
9370   return is_tracepoint ? &tracepoint_breakpoint_ops : &bkpt_breakpoint_ops;
9371 }
9372
9373 /* See breakpoint.h.  */
9374
9375 int
9376 create_breakpoint (struct gdbarch *gdbarch,
9377                    struct event_location *location,
9378                    const char *cond_string,
9379                    int thread, const char *extra_string,
9380                    bool force_condition, int parse_extra,
9381                    int tempflag, enum bptype type_wanted,
9382                    int ignore_count,
9383                    enum auto_boolean pending_break_support,
9384                    const struct breakpoint_ops *ops,
9385                    int from_tty, int enabled, int internal,
9386                    unsigned flags)
9387 {
9388   struct linespec_result canonical;
9389   int pending = 0;
9390   int task = 0;
9391   int prev_bkpt_count = breakpoint_count;
9392
9393   gdb_assert (ops != NULL);
9394
9395   /* If extra_string isn't useful, set it to NULL.  */
9396   if (extra_string != NULL && *extra_string == '\0')
9397     extra_string = NULL;
9398
9399   try
9400     {
9401       ops->create_sals_from_location (location, &canonical, type_wanted);
9402     }
9403   catch (const gdb_exception_error &e)
9404     {
9405       /* If caller is interested in rc value from parse, set
9406          value.  */
9407       if (e.error == NOT_FOUND_ERROR)
9408         {
9409           /* If pending breakpoint support is turned off, throw
9410              error.  */
9411
9412           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9413             throw;
9414
9415           exception_print (gdb_stderr, e);
9416
9417           /* If pending breakpoint support is auto query and the user
9418              selects no, then simply return the error code.  */
9419           if (pending_break_support == AUTO_BOOLEAN_AUTO
9420               && !nquery (_("Make %s pending on future shared library load? "),
9421                           bptype_string (type_wanted)))
9422             return 0;
9423
9424           /* At this point, either the user was queried about setting
9425              a pending breakpoint and selected yes, or pending
9426              breakpoint behavior is on and thus a pending breakpoint
9427              is defaulted on behalf of the user.  */
9428           pending = 1;
9429         }
9430       else
9431         throw;
9432     }
9433
9434   if (!pending && canonical.lsals.empty ())
9435     return 0;
9436
9437   /* Resolve all line numbers to PC's and verify that the addresses
9438      are ok for the target.  */
9439   if (!pending)
9440     {
9441       for (auto &lsal : canonical.lsals)
9442         breakpoint_sals_to_pc (lsal.sals);
9443     }
9444
9445   /* Fast tracepoints may have additional restrictions on location.  */
9446   if (!pending && type_wanted == bp_fast_tracepoint)
9447     {
9448       for (const auto &lsal : canonical.lsals)
9449         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9450     }
9451
9452   /* Verify that condition can be parsed, before setting any
9453      breakpoints.  Allocate a separate condition expression for each
9454      breakpoint.  */
9455   if (!pending)
9456     {
9457       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9458       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9459
9460       if (parse_extra)
9461         {
9462           char *rest;
9463           char *cond;
9464
9465           const linespec_sals &lsal = canonical.lsals[0];
9466
9467           find_condition_and_thread_for_sals (lsal.sals, extra_string,
9468                                               &cond, &thread, &task, &rest);
9469           cond_string_copy.reset (cond);
9470           extra_string_copy.reset (rest);
9471         }
9472       else
9473         {
9474           if (type_wanted != bp_dprintf
9475               && extra_string != NULL && *extra_string != '\0')
9476                 error (_("Garbage '%s' at end of location"), extra_string);
9477
9478           /* Check the validity of the condition.  We should error out
9479              if the condition is invalid at all of the locations and
9480              if it is not forced.  In the PARSE_EXTRA case above, this
9481              check is done when parsing the EXTRA_STRING.  */
9482           if (cond_string != nullptr && !force_condition)
9483             {
9484               int num_failures = 0;
9485               const linespec_sals &lsal = canonical.lsals[0];
9486               for (const auto &sal : lsal.sals)
9487                 {
9488                   const char *cond = cond_string;
9489                   try
9490                     {
9491                       parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
9492                       /* One success is sufficient to keep going.  */
9493                       break;
9494                     }
9495                   catch (const gdb_exception_error &)
9496                     {
9497                       num_failures++;
9498                       /* If this is the last sal, error out.  */
9499                       if (num_failures == lsal.sals.size ())
9500                         throw;
9501                     }
9502                 }
9503             }
9504
9505           /* Create a private copy of condition string.  */
9506           if (cond_string)
9507             cond_string_copy.reset (xstrdup (cond_string));
9508           /* Create a private copy of any extra string.  */
9509           if (extra_string)
9510             extra_string_copy.reset (xstrdup (extra_string));
9511         }
9512
9513       ops->create_breakpoints_sal (gdbarch, &canonical,
9514                                    std::move (cond_string_copy),
9515                                    std::move (extra_string_copy),
9516                                    type_wanted,
9517                                    tempflag ? disp_del : disp_donttouch,
9518                                    thread, task, ignore_count, ops,
9519                                    from_tty, enabled, internal, flags);
9520     }
9521   else
9522     {
9523       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9524
9525       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9526       b->location = copy_event_location (location);
9527
9528       if (parse_extra)
9529         b->cond_string = NULL;
9530       else
9531         {
9532           /* Create a private copy of condition string.  */
9533           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9534           b->thread = thread;
9535         }
9536
9537       /* Create a private copy of any extra string.  */
9538       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9539       b->ignore_count = ignore_count;
9540       b->disposition = tempflag ? disp_del : disp_donttouch;
9541       b->condition_not_parsed = 1;
9542       b->enable_state = enabled ? bp_enabled : bp_disabled;
9543       if ((type_wanted != bp_breakpoint
9544            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9545         b->pspace = current_program_space;
9546
9547       install_breakpoint (internal, std::move (b), 0);
9548     }
9549   
9550   if (canonical.lsals.size () > 1)
9551     {
9552       warning (_("Multiple breakpoints were set.\nUse the "
9553                  "\"delete\" command to delete unwanted breakpoints."));
9554       prev_breakpoint_count = prev_bkpt_count;
9555     }
9556
9557   update_global_location_list (UGLL_MAY_INSERT);
9558
9559   return 1;
9560 }
9561
9562 /* Set a breakpoint.
9563    ARG is a string describing breakpoint address,
9564    condition, and thread.
9565    FLAG specifies if a breakpoint is hardware on,
9566    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9567    and BP_TEMPFLAG.  */
9568
9569 static void
9570 break_command_1 (const char *arg, int flag, int from_tty)
9571 {
9572   int tempflag = flag & BP_TEMPFLAG;
9573   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9574                              ? bp_hardware_breakpoint
9575                              : bp_breakpoint);
9576
9577   event_location_up location = string_to_event_location (&arg, current_language);
9578   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
9579     (location.get (), false /* is_tracepoint */);
9580
9581   create_breakpoint (get_current_arch (),
9582                      location.get (),
9583                      NULL, 0, arg, false, 1 /* parse arg */,
9584                      tempflag, type_wanted,
9585                      0 /* Ignore count */,
9586                      pending_break_support,
9587                      ops,
9588                      from_tty,
9589                      1 /* enabled */,
9590                      0 /* internal */,
9591                      0);
9592 }
9593
9594 /* Helper function for break_command_1 and disassemble_command.  */
9595
9596 void
9597 resolve_sal_pc (struct symtab_and_line *sal)
9598 {
9599   CORE_ADDR pc;
9600
9601   if (sal->pc == 0 && sal->symtab != NULL)
9602     {
9603       if (!find_line_pc (sal->symtab, sal->line, &pc))
9604         error (_("No line %d in file \"%s\"."),
9605                sal->line, symtab_to_filename_for_display (sal->symtab));
9606       sal->pc = pc;
9607
9608       /* If this SAL corresponds to a breakpoint inserted using a line
9609          number, then skip the function prologue if necessary.  */
9610       if (sal->explicit_line)
9611         skip_prologue_sal (sal);
9612     }
9613
9614   if (sal->section == 0 && sal->symtab != NULL)
9615     {
9616       const struct blockvector *bv;
9617       const struct block *b;
9618       struct symbol *sym;
9619
9620       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9621                                     SYMTAB_COMPUNIT (sal->symtab));
9622       if (bv != NULL)
9623         {
9624           sym = block_linkage_function (b);
9625           if (sym != NULL)
9626             {
9627               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9628               sal->section = sym->obj_section (SYMTAB_OBJFILE (sal->symtab));
9629             }
9630           else
9631             {
9632               /* It really is worthwhile to have the section, so we'll
9633                  just have to look harder. This case can be executed
9634                  if we have line numbers but no functions (as can
9635                  happen in assembly source).  */
9636
9637               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9638               switch_to_program_space_and_thread (sal->pspace);
9639
9640               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9641               if (msym.minsym)
9642                 sal->section = msym.obj_section ();
9643             }
9644         }
9645     }
9646 }
9647
9648 void
9649 break_command (const char *arg, int from_tty)
9650 {
9651   break_command_1 (arg, 0, from_tty);
9652 }
9653
9654 void
9655 tbreak_command (const char *arg, int from_tty)
9656 {
9657   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9658 }
9659
9660 static void
9661 hbreak_command (const char *arg, int from_tty)
9662 {
9663   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9664 }
9665
9666 static void
9667 thbreak_command (const char *arg, int from_tty)
9668 {
9669   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9670 }
9671
9672 static void
9673 stop_command (const char *arg, int from_tty)
9674 {
9675   printf_filtered (_("Specify the type of breakpoint to set.\n\
9676 Usage: stop in <function | address>\n\
9677        stop at <line>\n"));
9678 }
9679
9680 static void
9681 stopin_command (const char *arg, int from_tty)
9682 {
9683   int badInput = 0;
9684
9685   if (arg == NULL)
9686     badInput = 1;
9687   else if (*arg != '*')
9688     {
9689       const char *argptr = arg;
9690       int hasColon = 0;
9691
9692       /* Look for a ':'.  If this is a line number specification, then
9693          say it is bad, otherwise, it should be an address or
9694          function/method name.  */
9695       while (*argptr && !hasColon)
9696         {
9697           hasColon = (*argptr == ':');
9698           argptr++;
9699         }
9700
9701       if (hasColon)
9702         badInput = (*argptr != ':');    /* Not a class::method */
9703       else
9704         badInput = isdigit (*arg);      /* a simple line number */
9705     }
9706
9707   if (badInput)
9708     printf_filtered (_("Usage: stop in <function | address>\n"));
9709   else
9710     break_command_1 (arg, 0, from_tty);
9711 }
9712
9713 static void
9714 stopat_command (const char *arg, int from_tty)
9715 {
9716   int badInput = 0;
9717
9718   if (arg == NULL || *arg == '*')       /* no line number */
9719     badInput = 1;
9720   else
9721     {
9722       const char *argptr = arg;
9723       int hasColon = 0;
9724
9725       /* Look for a ':'.  If there is a '::' then get out, otherwise
9726          it is probably a line number.  */
9727       while (*argptr && !hasColon)
9728         {
9729           hasColon = (*argptr == ':');
9730           argptr++;
9731         }
9732
9733       if (hasColon)
9734         badInput = (*argptr == ':');    /* we have class::method */
9735       else
9736         badInput = !isdigit (*arg);     /* not a line number */
9737     }
9738
9739   if (badInput)
9740     printf_filtered (_("Usage: stop at LINE\n"));
9741   else
9742     break_command_1 (arg, 0, from_tty);
9743 }
9744
9745 /* The dynamic printf command is mostly like a regular breakpoint, but
9746    with a prewired command list consisting of a single output command,
9747    built from extra arguments supplied on the dprintf command
9748    line.  */
9749
9750 static void
9751 dprintf_command (const char *arg, int from_tty)
9752 {
9753   event_location_up location = string_to_event_location (&arg, current_language);
9754
9755   /* If non-NULL, ARG should have been advanced past the location;
9756      the next character must be ','.  */
9757   if (arg != NULL)
9758     {
9759       if (arg[0] != ',' || arg[1] == '\0')
9760         error (_("Format string required"));
9761       else
9762         {
9763           /* Skip the comma.  */
9764           ++arg;
9765         }
9766     }
9767
9768   create_breakpoint (get_current_arch (),
9769                      location.get (),
9770                      NULL, 0, arg, false, 1 /* parse arg */,
9771                      0, bp_dprintf,
9772                      0 /* Ignore count */,
9773                      pending_break_support,
9774                      &dprintf_breakpoint_ops,
9775                      from_tty,
9776                      1 /* enabled */,
9777                      0 /* internal */,
9778                      0);
9779 }
9780
9781 static void
9782 agent_printf_command (const char *arg, int from_tty)
9783 {
9784   error (_("May only run agent-printf on the target"));
9785 }
9786
9787 /* Implement the "breakpoint_hit" breakpoint_ops method for
9788    ranged breakpoints.  */
9789
9790 static int
9791 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9792                                   const address_space *aspace,
9793                                   CORE_ADDR bp_addr,
9794                                   const struct target_waitstatus *ws)
9795 {
9796   if (ws->kind != TARGET_WAITKIND_STOPPED
9797       || ws->value.sig != GDB_SIGNAL_TRAP)
9798     return 0;
9799
9800   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9801                                          bl->length, aspace, bp_addr);
9802 }
9803
9804 /* Implement the "resources_needed" breakpoint_ops method for
9805    ranged breakpoints.  */
9806
9807 static int
9808 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9809 {
9810   return target_ranged_break_num_registers ();
9811 }
9812
9813 /* Implement the "print_it" breakpoint_ops method for
9814    ranged breakpoints.  */
9815
9816 static enum print_stop_action
9817 print_it_ranged_breakpoint (bpstat bs)
9818 {
9819   struct breakpoint *b = bs->breakpoint_at;
9820   struct bp_location *bl = b->loc;
9821   struct ui_out *uiout = current_uiout;
9822
9823   gdb_assert (b->type == bp_hardware_breakpoint);
9824
9825   /* Ranged breakpoints have only one location.  */
9826   gdb_assert (bl && bl->next == NULL);
9827
9828   annotate_breakpoint (b->number);
9829
9830   maybe_print_thread_hit_breakpoint (uiout);
9831
9832   if (b->disposition == disp_del)
9833     uiout->text ("Temporary ranged breakpoint ");
9834   else
9835     uiout->text ("Ranged breakpoint ");
9836   if (uiout->is_mi_like_p ())
9837     {
9838       uiout->field_string ("reason",
9839                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9840       uiout->field_string ("disp", bpdisp_text (b->disposition));
9841     }
9842   uiout->field_signed ("bkptno", b->number);
9843   uiout->text (", ");
9844
9845   return PRINT_SRC_AND_LOC;
9846 }
9847
9848 /* Implement the "print_one" breakpoint_ops method for
9849    ranged breakpoints.  */
9850
9851 static void
9852 print_one_ranged_breakpoint (struct breakpoint *b,
9853                              struct bp_location **last_loc)
9854 {
9855   struct bp_location *bl = b->loc;
9856   struct value_print_options opts;
9857   struct ui_out *uiout = current_uiout;
9858
9859   /* Ranged breakpoints have only one location.  */
9860   gdb_assert (bl && bl->next == NULL);
9861
9862   get_user_print_options (&opts);
9863
9864   if (opts.addressprint)
9865     /* We don't print the address range here, it will be printed later
9866        by print_one_detail_ranged_breakpoint.  */
9867     uiout->field_skip ("addr");
9868   annotate_field (5);
9869   print_breakpoint_location (b, bl);
9870   *last_loc = bl;
9871 }
9872
9873 /* Implement the "print_one_detail" breakpoint_ops method for
9874    ranged breakpoints.  */
9875
9876 static void
9877 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9878                                     struct ui_out *uiout)
9879 {
9880   CORE_ADDR address_start, address_end;
9881   struct bp_location *bl = b->loc;
9882   string_file stb;
9883
9884   gdb_assert (bl);
9885
9886   address_start = bl->address;
9887   address_end = address_start + bl->length - 1;
9888
9889   uiout->text ("\taddress range: ");
9890   stb.printf ("[%s, %s]",
9891               print_core_address (bl->gdbarch, address_start),
9892               print_core_address (bl->gdbarch, address_end));
9893   uiout->field_stream ("addr", stb);
9894   uiout->text ("\n");
9895 }
9896
9897 /* Implement the "print_mention" breakpoint_ops method for
9898    ranged breakpoints.  */
9899
9900 static void
9901 print_mention_ranged_breakpoint (struct breakpoint *b)
9902 {
9903   struct bp_location *bl = b->loc;
9904   struct ui_out *uiout = current_uiout;
9905
9906   gdb_assert (bl);
9907   gdb_assert (b->type == bp_hardware_breakpoint);
9908
9909   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9910                   b->number, paddress (bl->gdbarch, bl->address),
9911                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9912 }
9913
9914 /* Implement the "print_recreate" breakpoint_ops method for
9915    ranged breakpoints.  */
9916
9917 static void
9918 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9919 {
9920   fprintf_unfiltered (fp, "break-range %s, %s",
9921                       event_location_to_string (b->location.get ()),
9922                       event_location_to_string (b->location_range_end.get ()));
9923   print_recreate_thread (b, fp);
9924 }
9925
9926 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9927
9928 static struct breakpoint_ops ranged_breakpoint_ops;
9929
9930 /* Find the address where the end of the breakpoint range should be
9931    placed, given the SAL of the end of the range.  This is so that if
9932    the user provides a line number, the end of the range is set to the
9933    last instruction of the given line.  */
9934
9935 static CORE_ADDR
9936 find_breakpoint_range_end (struct symtab_and_line sal)
9937 {
9938   CORE_ADDR end;
9939
9940   /* If the user provided a PC value, use it.  Otherwise,
9941      find the address of the end of the given location.  */
9942   if (sal.explicit_pc)
9943     end = sal.pc;
9944   else
9945     {
9946       int ret;
9947       CORE_ADDR start;
9948
9949       ret = find_line_pc_range (sal, &start, &end);
9950       if (!ret)
9951         error (_("Could not find location of the end of the range."));
9952
9953       /* find_line_pc_range returns the start of the next line.  */
9954       end--;
9955     }
9956
9957   return end;
9958 }
9959
9960 /* Implement the "break-range" CLI command.  */
9961
9962 static void
9963 break_range_command (const char *arg, int from_tty)
9964 {
9965   const char *arg_start;
9966   struct linespec_result canonical_start, canonical_end;
9967   int bp_count, can_use_bp, length;
9968   CORE_ADDR end;
9969   struct breakpoint *b;
9970
9971   /* We don't support software ranged breakpoints.  */
9972   if (target_ranged_break_num_registers () < 0)
9973     error (_("This target does not support hardware ranged breakpoints."));
9974
9975   bp_count = hw_breakpoint_used_count ();
9976   bp_count += target_ranged_break_num_registers ();
9977   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9978                                                    bp_count, 0);
9979   if (can_use_bp < 0)
9980     error (_("Hardware breakpoints used exceeds limit."));
9981
9982   arg = skip_spaces (arg);
9983   if (arg == NULL || arg[0] == '\0')
9984     error(_("No address range specified."));
9985
9986   arg_start = arg;
9987   event_location_up start_location = string_to_event_location (&arg,
9988                                                                current_language);
9989   parse_breakpoint_sals (start_location.get (), &canonical_start);
9990
9991   if (arg[0] != ',')
9992     error (_("Too few arguments."));
9993   else if (canonical_start.lsals.empty ())
9994     error (_("Could not find location of the beginning of the range."));
9995
9996   const linespec_sals &lsal_start = canonical_start.lsals[0];
9997
9998   if (canonical_start.lsals.size () > 1
9999       || lsal_start.sals.size () != 1)
10000     error (_("Cannot create a ranged breakpoint with multiple locations."));
10001
10002   const symtab_and_line &sal_start = lsal_start.sals[0];
10003   std::string addr_string_start (arg_start, arg - arg_start);
10004
10005   arg++;        /* Skip the comma.  */
10006   arg = skip_spaces (arg);
10007
10008   /* Parse the end location.  */
10009
10010   arg_start = arg;
10011
10012   /* We call decode_line_full directly here instead of using
10013      parse_breakpoint_sals because we need to specify the start location's
10014      symtab and line as the default symtab and line for the end of the
10015      range.  This makes it possible to have ranges like "foo.c:27, +14",
10016      where +14 means 14 lines from the start location.  */
10017   event_location_up end_location = string_to_event_location (&arg,
10018                                                              current_language);
10019   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10020                     sal_start.symtab, sal_start.line,
10021                     &canonical_end, NULL, NULL);
10022
10023   if (canonical_end.lsals.empty ())
10024     error (_("Could not find location of the end of the range."));
10025
10026   const linespec_sals &lsal_end = canonical_end.lsals[0];
10027   if (canonical_end.lsals.size () > 1
10028       || lsal_end.sals.size () != 1)
10029     error (_("Cannot create a ranged breakpoint with multiple locations."));
10030
10031   const symtab_and_line &sal_end = lsal_end.sals[0];
10032
10033   end = find_breakpoint_range_end (sal_end);
10034   if (sal_start.pc > end)
10035     error (_("Invalid address range, end precedes start."));
10036
10037   length = end - sal_start.pc + 1;
10038   if (length < 0)
10039     /* Length overflowed.  */
10040     error (_("Address range too large."));
10041   else if (length == 1)
10042     {
10043       /* This range is simple enough to be handled by
10044          the `hbreak' command.  */
10045       hbreak_command (&addr_string_start[0], 1);
10046
10047       return;
10048     }
10049
10050   /* Now set up the breakpoint.  */
10051   b = set_raw_breakpoint (get_current_arch (), sal_start,
10052                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10053   set_breakpoint_count (breakpoint_count + 1);
10054   b->number = breakpoint_count;
10055   b->disposition = disp_donttouch;
10056   b->location = std::move (start_location);
10057   b->location_range_end = std::move (end_location);
10058   b->loc->length = length;
10059
10060   mention (b);
10061   gdb::observers::breakpoint_created.notify (b);
10062   update_global_location_list (UGLL_MAY_INSERT);
10063 }
10064
10065 /*  Return non-zero if EXP is verified as constant.  Returned zero
10066     means EXP is variable.  Also the constant detection may fail for
10067     some constant expressions and in such case still falsely return
10068     zero.  */
10069
10070 static bool
10071 watchpoint_exp_is_const (const struct expression *exp)
10072 {
10073   return exp->op->constant_p ();
10074 }
10075
10076 /* Watchpoint destructor.  */
10077
10078 watchpoint::~watchpoint ()
10079 {
10080   xfree (this->exp_string);
10081   xfree (this->exp_string_reparse);
10082 }
10083
10084 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10085
10086 static void
10087 re_set_watchpoint (struct breakpoint *b)
10088 {
10089   struct watchpoint *w = (struct watchpoint *) b;
10090
10091   /* Watchpoint can be either on expression using entirely global
10092      variables, or it can be on local variables.
10093
10094      Watchpoints of the first kind are never auto-deleted, and even
10095      persist across program restarts.  Since they can use variables
10096      from shared libraries, we need to reparse expression as libraries
10097      are loaded and unloaded.
10098
10099      Watchpoints on local variables can also change meaning as result
10100      of solib event.  For example, if a watchpoint uses both a local
10101      and a global variables in expression, it's a local watchpoint,
10102      but unloading of a shared library will make the expression
10103      invalid.  This is not a very common use case, but we still
10104      re-evaluate expression, to avoid surprises to the user.
10105
10106      Note that for local watchpoints, we re-evaluate it only if
10107      watchpoints frame id is still valid.  If it's not, it means the
10108      watchpoint is out of scope and will be deleted soon.  In fact,
10109      I'm not sure we'll ever be called in this case.
10110
10111      If a local watchpoint's frame id is still valid, then
10112      w->exp_valid_block is likewise valid, and we can safely use it.
10113
10114      Don't do anything about disabled watchpoints, since they will be
10115      reevaluated again when enabled.  */
10116   update_watchpoint (w, 1 /* reparse */);
10117 }
10118
10119 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10120
10121 static int
10122 insert_watchpoint (struct bp_location *bl)
10123 {
10124   struct watchpoint *w = (struct watchpoint *) bl->owner;
10125   int length = w->exact ? 1 : bl->length;
10126
10127   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10128                                    w->cond_exp.get ());
10129 }
10130
10131 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10132
10133 static int
10134 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10135 {
10136   struct watchpoint *w = (struct watchpoint *) bl->owner;
10137   int length = w->exact ? 1 : bl->length;
10138
10139   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10140                                    w->cond_exp.get ());
10141 }
10142
10143 static int
10144 breakpoint_hit_watchpoint (const struct bp_location *bl,
10145                            const address_space *aspace, CORE_ADDR bp_addr,
10146                            const struct target_waitstatus *ws)
10147 {
10148   struct breakpoint *b = bl->owner;
10149   struct watchpoint *w = (struct watchpoint *) b;
10150
10151   /* Continuable hardware watchpoints are treated as non-existent if the
10152      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10153      some data address).  Otherwise gdb won't stop on a break instruction
10154      in the code (not from a breakpoint) when a hardware watchpoint has
10155      been defined.  Also skip watchpoints which we know did not trigger
10156      (did not match the data address).  */
10157   if (is_hardware_watchpoint (b)
10158       && w->watchpoint_triggered == watch_triggered_no)
10159     return 0;
10160
10161   return 1;
10162 }
10163
10164 static void
10165 check_status_watchpoint (bpstat bs)
10166 {
10167   gdb_assert (is_watchpoint (bs->breakpoint_at));
10168
10169   bpstat_check_watchpoint (bs);
10170 }
10171
10172 /* Implement the "resources_needed" breakpoint_ops method for
10173    hardware watchpoints.  */
10174
10175 static int
10176 resources_needed_watchpoint (const struct bp_location *bl)
10177 {
10178   struct watchpoint *w = (struct watchpoint *) bl->owner;
10179   int length = w->exact? 1 : bl->length;
10180
10181   return target_region_ok_for_hw_watchpoint (bl->address, length);
10182 }
10183
10184 /* Implement the "works_in_software_mode" breakpoint_ops method for
10185    hardware watchpoints.  */
10186
10187 static int
10188 works_in_software_mode_watchpoint (const struct breakpoint *b)
10189 {
10190   /* Read and access watchpoints only work with hardware support.  */
10191   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10192 }
10193
10194 static enum print_stop_action
10195 print_it_watchpoint (bpstat bs)
10196 {
10197   struct breakpoint *b;
10198   enum print_stop_action result;
10199   struct watchpoint *w;
10200   struct ui_out *uiout = current_uiout;
10201
10202   gdb_assert (bs->bp_location_at != NULL);
10203
10204   b = bs->breakpoint_at;
10205   w = (struct watchpoint *) b;
10206
10207   annotate_watchpoint (b->number);
10208   maybe_print_thread_hit_breakpoint (uiout);
10209
10210   string_file stb;
10211
10212   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10213   switch (b->type)
10214     {
10215     case bp_watchpoint:
10216     case bp_hardware_watchpoint:
10217       if (uiout->is_mi_like_p ())
10218         uiout->field_string
10219           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10220       mention (b);
10221       tuple_emitter.emplace (uiout, "value");
10222       uiout->text ("\nOld value = ");
10223       watchpoint_value_print (bs->old_val.get (), &stb);
10224       uiout->field_stream ("old", stb);
10225       uiout->text ("\nNew value = ");
10226       watchpoint_value_print (w->val.get (), &stb);
10227       uiout->field_stream ("new", stb);
10228       uiout->text ("\n");
10229       /* More than one watchpoint may have been triggered.  */
10230       result = PRINT_UNKNOWN;
10231       break;
10232
10233     case bp_read_watchpoint:
10234       if (uiout->is_mi_like_p ())
10235         uiout->field_string
10236           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10237       mention (b);
10238       tuple_emitter.emplace (uiout, "value");
10239       uiout->text ("\nValue = ");
10240       watchpoint_value_print (w->val.get (), &stb);
10241       uiout->field_stream ("value", stb);
10242       uiout->text ("\n");
10243       result = PRINT_UNKNOWN;
10244       break;
10245
10246     case bp_access_watchpoint:
10247       if (bs->old_val != NULL)
10248         {
10249           if (uiout->is_mi_like_p ())
10250             uiout->field_string
10251               ("reason",
10252                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10253           mention (b);
10254           tuple_emitter.emplace (uiout, "value");
10255           uiout->text ("\nOld value = ");
10256           watchpoint_value_print (bs->old_val.get (), &stb);
10257           uiout->field_stream ("old", stb);
10258           uiout->text ("\nNew value = ");
10259         }
10260       else
10261         {
10262           mention (b);
10263           if (uiout->is_mi_like_p ())
10264             uiout->field_string
10265               ("reason",
10266                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10267           tuple_emitter.emplace (uiout, "value");
10268           uiout->text ("\nValue = ");
10269         }
10270       watchpoint_value_print (w->val.get (), &stb);
10271       uiout->field_stream ("new", stb);
10272       uiout->text ("\n");
10273       result = PRINT_UNKNOWN;
10274       break;
10275     default:
10276       result = PRINT_UNKNOWN;
10277     }
10278
10279   return result;
10280 }
10281
10282 /* Implement the "print_mention" breakpoint_ops method for hardware
10283    watchpoints.  */
10284
10285 static void
10286 print_mention_watchpoint (struct breakpoint *b)
10287 {
10288   struct watchpoint *w = (struct watchpoint *) b;
10289   struct ui_out *uiout = current_uiout;
10290   const char *tuple_name;
10291
10292   switch (b->type)
10293     {
10294     case bp_watchpoint:
10295       uiout->text ("Watchpoint ");
10296       tuple_name = "wpt";
10297       break;
10298     case bp_hardware_watchpoint:
10299       uiout->text ("Hardware watchpoint ");
10300       tuple_name = "wpt";
10301       break;
10302     case bp_read_watchpoint:
10303       uiout->text ("Hardware read watchpoint ");
10304       tuple_name = "hw-rwpt";
10305       break;
10306     case bp_access_watchpoint:
10307       uiout->text ("Hardware access (read/write) watchpoint ");
10308       tuple_name = "hw-awpt";
10309       break;
10310     default:
10311       internal_error (__FILE__, __LINE__,
10312                       _("Invalid hardware watchpoint type."));
10313     }
10314
10315   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10316   uiout->field_signed ("number", b->number);
10317   uiout->text (": ");
10318   uiout->field_string ("exp", w->exp_string);
10319 }
10320
10321 /* Implement the "print_recreate" breakpoint_ops method for
10322    watchpoints.  */
10323
10324 static void
10325 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10326 {
10327   struct watchpoint *w = (struct watchpoint *) b;
10328
10329   switch (b->type)
10330     {
10331     case bp_watchpoint:
10332     case bp_hardware_watchpoint:
10333       fprintf_unfiltered (fp, "watch");
10334       break;
10335     case bp_read_watchpoint:
10336       fprintf_unfiltered (fp, "rwatch");
10337       break;
10338     case bp_access_watchpoint:
10339       fprintf_unfiltered (fp, "awatch");
10340       break;
10341     default:
10342       internal_error (__FILE__, __LINE__,
10343                       _("Invalid watchpoint type."));
10344     }
10345
10346   fprintf_unfiltered (fp, " %s", w->exp_string);
10347   print_recreate_thread (b, fp);
10348 }
10349
10350 /* Implement the "explains_signal" breakpoint_ops method for
10351    watchpoints.  */
10352
10353 static int
10354 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10355 {
10356   /* A software watchpoint cannot cause a signal other than
10357      GDB_SIGNAL_TRAP.  */
10358   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10359     return 0;
10360
10361   return 1;
10362 }
10363
10364 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10365
10366 static struct breakpoint_ops watchpoint_breakpoint_ops;
10367
10368 /* Implement the "insert" breakpoint_ops method for
10369    masked hardware watchpoints.  */
10370
10371 static int
10372 insert_masked_watchpoint (struct bp_location *bl)
10373 {
10374   struct watchpoint *w = (struct watchpoint *) bl->owner;
10375
10376   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10377                                         bl->watchpoint_type);
10378 }
10379
10380 /* Implement the "remove" breakpoint_ops method for
10381    masked hardware watchpoints.  */
10382
10383 static int
10384 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10385 {
10386   struct watchpoint *w = (struct watchpoint *) bl->owner;
10387
10388   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10389                                         bl->watchpoint_type);
10390 }
10391
10392 /* Implement the "resources_needed" breakpoint_ops method for
10393    masked hardware watchpoints.  */
10394
10395 static int
10396 resources_needed_masked_watchpoint (const struct bp_location *bl)
10397 {
10398   struct watchpoint *w = (struct watchpoint *) bl->owner;
10399
10400   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10401 }
10402
10403 /* Implement the "works_in_software_mode" breakpoint_ops method for
10404    masked hardware watchpoints.  */
10405
10406 static int
10407 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10408 {
10409   return 0;
10410 }
10411
10412 /* Implement the "print_it" breakpoint_ops method for
10413    masked hardware watchpoints.  */
10414
10415 static enum print_stop_action
10416 print_it_masked_watchpoint (bpstat bs)
10417 {
10418   struct breakpoint *b = bs->breakpoint_at;
10419   struct ui_out *uiout = current_uiout;
10420
10421   /* Masked watchpoints have only one location.  */
10422   gdb_assert (b->loc && b->loc->next == NULL);
10423
10424   annotate_watchpoint (b->number);
10425   maybe_print_thread_hit_breakpoint (uiout);
10426
10427   switch (b->type)
10428     {
10429     case bp_hardware_watchpoint:
10430       if (uiout->is_mi_like_p ())
10431         uiout->field_string
10432           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10433       break;
10434
10435     case bp_read_watchpoint:
10436       if (uiout->is_mi_like_p ())
10437         uiout->field_string
10438           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10439       break;
10440
10441     case bp_access_watchpoint:
10442       if (uiout->is_mi_like_p ())
10443         uiout->field_string
10444           ("reason",
10445            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10446       break;
10447     default:
10448       internal_error (__FILE__, __LINE__,
10449                       _("Invalid hardware watchpoint type."));
10450     }
10451
10452   mention (b);
10453   uiout->text (_("\n\
10454 Check the underlying instruction at PC for the memory\n\
10455 address and value which triggered this watchpoint.\n"));
10456   uiout->text ("\n");
10457
10458   /* More than one watchpoint may have been triggered.  */
10459   return PRINT_UNKNOWN;
10460 }
10461
10462 /* Implement the "print_one_detail" breakpoint_ops method for
10463    masked hardware watchpoints.  */
10464
10465 static void
10466 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10467                                     struct ui_out *uiout)
10468 {
10469   struct watchpoint *w = (struct watchpoint *) b;
10470
10471   /* Masked watchpoints have only one location.  */
10472   gdb_assert (b->loc && b->loc->next == NULL);
10473
10474   uiout->text ("\tmask ");
10475   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10476   uiout->text ("\n");
10477 }
10478
10479 /* Implement the "print_mention" breakpoint_ops method for
10480    masked hardware watchpoints.  */
10481
10482 static void
10483 print_mention_masked_watchpoint (struct breakpoint *b)
10484 {
10485   struct watchpoint *w = (struct watchpoint *) b;
10486   struct ui_out *uiout = current_uiout;
10487   const char *tuple_name;
10488
10489   switch (b->type)
10490     {
10491     case bp_hardware_watchpoint:
10492       uiout->text ("Masked hardware watchpoint ");
10493       tuple_name = "wpt";
10494       break;
10495     case bp_read_watchpoint:
10496       uiout->text ("Masked hardware read watchpoint ");
10497       tuple_name = "hw-rwpt";
10498       break;
10499     case bp_access_watchpoint:
10500       uiout->text ("Masked hardware access (read/write) watchpoint ");
10501       tuple_name = "hw-awpt";
10502       break;
10503     default:
10504       internal_error (__FILE__, __LINE__,
10505                       _("Invalid hardware watchpoint type."));
10506     }
10507
10508   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10509   uiout->field_signed ("number", b->number);
10510   uiout->text (": ");
10511   uiout->field_string ("exp", w->exp_string);
10512 }
10513
10514 /* Implement the "print_recreate" breakpoint_ops method for
10515    masked hardware watchpoints.  */
10516
10517 static void
10518 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10519 {
10520   struct watchpoint *w = (struct watchpoint *) b;
10521
10522   switch (b->type)
10523     {
10524     case bp_hardware_watchpoint:
10525       fprintf_unfiltered (fp, "watch");
10526       break;
10527     case bp_read_watchpoint:
10528       fprintf_unfiltered (fp, "rwatch");
10529       break;
10530     case bp_access_watchpoint:
10531       fprintf_unfiltered (fp, "awatch");
10532       break;
10533     default:
10534       internal_error (__FILE__, __LINE__,
10535                       _("Invalid hardware watchpoint type."));
10536     }
10537
10538   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string,
10539                       phex (w->hw_wp_mask, sizeof (CORE_ADDR)));
10540   print_recreate_thread (b, fp);
10541 }
10542
10543 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10544
10545 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10546
10547 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10548
10549 static bool
10550 is_masked_watchpoint (const struct breakpoint *b)
10551 {
10552   return b->ops == &masked_watchpoint_breakpoint_ops;
10553 }
10554
10555 /* accessflag:  hw_write:  watch write, 
10556                 hw_read:   watch read, 
10557                 hw_access: watch access (read or write) */
10558 static void
10559 watch_command_1 (const char *arg, int accessflag, int from_tty,
10560                  bool just_location, bool internal)
10561 {
10562   struct breakpoint *scope_breakpoint = NULL;
10563   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10564   struct value *result;
10565   int saved_bitpos = 0, saved_bitsize = 0;
10566   const char *exp_start = NULL;
10567   const char *exp_end = NULL;
10568   const char *tok, *end_tok;
10569   int toklen = -1;
10570   const char *cond_start = NULL;
10571   const char *cond_end = NULL;
10572   enum bptype bp_type;
10573   int thread = -1;
10574   /* Flag to indicate whether we are going to use masks for
10575      the hardware watchpoint.  */
10576   bool use_mask = false;
10577   CORE_ADDR mask = 0;
10578
10579   /* Make sure that we actually have parameters to parse.  */
10580   if (arg != NULL && arg[0] != '\0')
10581     {
10582       const char *value_start;
10583
10584       exp_end = arg + strlen (arg);
10585
10586       /* Look for "parameter value" pairs at the end
10587          of the arguments string.  */
10588       for (tok = exp_end - 1; tok > arg; tok--)
10589         {
10590           /* Skip whitespace at the end of the argument list.  */
10591           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10592             tok--;
10593
10594           /* Find the beginning of the last token.
10595              This is the value of the parameter.  */
10596           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10597             tok--;
10598           value_start = tok + 1;
10599
10600           /* Skip whitespace.  */
10601           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10602             tok--;
10603
10604           end_tok = tok;
10605
10606           /* Find the beginning of the second to last token.
10607              This is the parameter itself.  */
10608           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10609             tok--;
10610           tok++;
10611           toklen = end_tok - tok + 1;
10612
10613           if (toklen == 6 && startswith (tok, "thread"))
10614             {
10615               struct thread_info *thr;
10616               /* At this point we've found a "thread" token, which means
10617                  the user is trying to set a watchpoint that triggers
10618                  only in a specific thread.  */
10619               const char *endp;
10620
10621               if (thread != -1)
10622                 error(_("You can specify only one thread."));
10623
10624               /* Extract the thread ID from the next token.  */
10625               thr = parse_thread_id (value_start, &endp);
10626
10627               /* Check if the user provided a valid thread ID.  */
10628               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10629                 invalid_thread_id_error (value_start);
10630
10631               thread = thr->global_num;
10632             }
10633           else if (toklen == 4 && startswith (tok, "mask"))
10634             {
10635               /* We've found a "mask" token, which means the user wants to
10636                  create a hardware watchpoint that is going to have the mask
10637                  facility.  */
10638               struct value *mask_value, *mark;
10639
10640               if (use_mask)
10641                 error(_("You can specify only one mask."));
10642
10643               use_mask = just_location = true;
10644
10645               mark = value_mark ();
10646               mask_value = parse_to_comma_and_eval (&value_start);
10647               mask = value_as_address (mask_value);
10648               value_free_to_mark (mark);
10649             }
10650           else
10651             /* We didn't recognize what we found.  We should stop here.  */
10652             break;
10653
10654           /* Truncate the string and get rid of the "parameter value" pair before
10655              the arguments string is parsed by the parse_exp_1 function.  */
10656           exp_end = tok;
10657         }
10658     }
10659   else
10660     exp_end = arg;
10661
10662   /* Parse the rest of the arguments.  From here on out, everything
10663      is in terms of a newly allocated string instead of the original
10664      ARG.  */
10665   std::string expression (arg, exp_end - arg);
10666   exp_start = arg = expression.c_str ();
10667   innermost_block_tracker tracker;
10668   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10669   exp_end = arg;
10670   /* Remove trailing whitespace from the expression before saving it.
10671      This makes the eventual display of the expression string a bit
10672      prettier.  */
10673   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10674     --exp_end;
10675
10676   /* Checking if the expression is not constant.  */
10677   if (watchpoint_exp_is_const (exp.get ()))
10678     {
10679       int len;
10680
10681       len = exp_end - exp_start;
10682       while (len > 0 && isspace (exp_start[len - 1]))
10683         len--;
10684       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10685     }
10686
10687   exp_valid_block = tracker.block ();
10688   struct value *mark = value_mark ();
10689   struct value *val_as_value = nullptr;
10690   fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
10691                       just_location);
10692
10693   if (val_as_value != NULL && just_location)
10694     {
10695       saved_bitpos = value_bitpos (val_as_value);
10696       saved_bitsize = value_bitsize (val_as_value);
10697     }
10698
10699   value_ref_ptr val;
10700   if (just_location)
10701     {
10702       int ret;
10703
10704       exp_valid_block = NULL;
10705       val = release_value (value_addr (result));
10706       value_free_to_mark (mark);
10707
10708       if (use_mask)
10709         {
10710           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10711                                                    mask);
10712           if (ret == -1)
10713             error (_("This target does not support masked watchpoints."));
10714           else if (ret == -2)
10715             error (_("Invalid mask or memory region."));
10716         }
10717     }
10718   else if (val_as_value != NULL)
10719     val = release_value (val_as_value);
10720
10721   tok = skip_spaces (arg);
10722   end_tok = skip_to_space (tok);
10723
10724   toklen = end_tok - tok;
10725   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10726     {
10727       tok = cond_start = end_tok + 1;
10728       innermost_block_tracker if_tracker;
10729       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10730
10731       /* The watchpoint expression may not be local, but the condition
10732          may still be.  E.g.: `watch global if local > 0'.  */
10733       cond_exp_valid_block = if_tracker.block ();
10734
10735       cond_end = tok;
10736     }
10737   if (*tok)
10738     error (_("Junk at end of command."));
10739
10740   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10741
10742   /* Save this because create_internal_breakpoint below invalidates
10743      'wp_frame'.  */
10744   frame_id watchpoint_frame = get_frame_id (wp_frame);
10745
10746   /* If the expression is "local", then set up a "watchpoint scope"
10747      breakpoint at the point where we've left the scope of the watchpoint
10748      expression.  Create the scope breakpoint before the watchpoint, so
10749      that we will encounter it first in bpstat_stop_status.  */
10750   if (exp_valid_block != NULL && wp_frame != NULL)
10751     {
10752       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10753
10754       if (frame_id_p (caller_frame_id))
10755         {
10756           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10757           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10758
10759           scope_breakpoint
10760             = create_internal_breakpoint (caller_arch, caller_pc,
10761                                           bp_watchpoint_scope,
10762                                           &momentary_breakpoint_ops);
10763
10764           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10765           wp_frame = NULL;
10766
10767           scope_breakpoint->enable_state = bp_enabled;
10768
10769           /* Automatically delete the breakpoint when it hits.  */
10770           scope_breakpoint->disposition = disp_del;
10771
10772           /* Only break in the proper frame (help with recursion).  */
10773           scope_breakpoint->frame_id = caller_frame_id;
10774
10775           /* Set the address at which we will stop.  */
10776           scope_breakpoint->loc->gdbarch = caller_arch;
10777           scope_breakpoint->loc->requested_address = caller_pc;
10778           scope_breakpoint->loc->address
10779             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10780                                          scope_breakpoint->loc->requested_address,
10781                                          scope_breakpoint->type);
10782         }
10783     }
10784
10785   /* Now set up the breakpoint.  We create all watchpoints as hardware
10786      watchpoints here even if hardware watchpoints are turned off, a call
10787      to update_watchpoint later in this function will cause the type to
10788      drop back to bp_watchpoint (software watchpoint) if required.  */
10789
10790   if (accessflag == hw_read)
10791     bp_type = bp_read_watchpoint;
10792   else if (accessflag == hw_access)
10793     bp_type = bp_access_watchpoint;
10794   else
10795     bp_type = bp_hardware_watchpoint;
10796
10797   std::unique_ptr<watchpoint> w (new watchpoint ());
10798
10799   if (use_mask)
10800     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10801                                           &masked_watchpoint_breakpoint_ops);
10802   else
10803     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10804                                           &watchpoint_breakpoint_ops);
10805   w->thread = thread;
10806   w->disposition = disp_donttouch;
10807   w->pspace = current_program_space;
10808   w->exp = std::move (exp);
10809   w->exp_valid_block = exp_valid_block;
10810   w->cond_exp_valid_block = cond_exp_valid_block;
10811   if (just_location)
10812     {
10813       struct type *t = value_type (val.get ());
10814       CORE_ADDR addr = value_as_address (val.get ());
10815
10816       w->exp_string_reparse
10817         = current_language->watch_location_expression (t, addr).release ();
10818
10819       w->exp_string = xstrprintf ("-location %.*s",
10820                                   (int) (exp_end - exp_start), exp_start);
10821     }
10822   else
10823     w->exp_string = savestring (exp_start, exp_end - exp_start);
10824
10825   if (use_mask)
10826     {
10827       w->hw_wp_mask = mask;
10828     }
10829   else
10830     {
10831       w->val = val;
10832       w->val_bitpos = saved_bitpos;
10833       w->val_bitsize = saved_bitsize;
10834       w->val_valid = true;
10835     }
10836
10837   if (cond_start)
10838     w->cond_string = savestring (cond_start, cond_end - cond_start);
10839   else
10840     w->cond_string = 0;
10841
10842   if (frame_id_p (watchpoint_frame))
10843     {
10844       w->watchpoint_frame = watchpoint_frame;
10845       w->watchpoint_thread = inferior_ptid;
10846     }
10847   else
10848     {
10849       w->watchpoint_frame = null_frame_id;
10850       w->watchpoint_thread = null_ptid;
10851     }
10852
10853   if (scope_breakpoint != NULL)
10854     {
10855       /* The scope breakpoint is related to the watchpoint.  We will
10856          need to act on them together.  */
10857       w->related_breakpoint = scope_breakpoint;
10858       scope_breakpoint->related_breakpoint = w.get ();
10859     }
10860
10861   if (!just_location)
10862     value_free_to_mark (mark);
10863
10864   /* Finally update the new watchpoint.  This creates the locations
10865      that should be inserted.  */
10866   update_watchpoint (w.get (), 1);
10867
10868   install_breakpoint (internal, std::move (w), 1);
10869 }
10870
10871 /* Return count of debug registers needed to watch the given expression.
10872    If the watchpoint cannot be handled in hardware return zero.  */
10873
10874 static int
10875 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10876 {
10877   int found_memory_cnt = 0;
10878
10879   /* Did the user specifically forbid us to use hardware watchpoints? */
10880   if (!can_use_hw_watchpoints)
10881     return 0;
10882
10883   gdb_assert (!vals.empty ());
10884   struct value *head = vals[0].get ();
10885
10886   /* Make sure that the value of the expression depends only upon
10887      memory contents, and values computed from them within GDB.  If we
10888      find any register references or function calls, we can't use a
10889      hardware watchpoint.
10890
10891      The idea here is that evaluating an expression generates a series
10892      of values, one holding the value of every subexpression.  (The
10893      expression a*b+c has five subexpressions: a, b, a*b, c, and
10894      a*b+c.)  GDB's values hold almost enough information to establish
10895      the criteria given above --- they identify memory lvalues,
10896      register lvalues, computed values, etcetera.  So we can evaluate
10897      the expression, and then scan the chain of values that leaves
10898      behind to decide whether we can detect any possible change to the
10899      expression's final value using only hardware watchpoints.
10900
10901      However, I don't think that the values returned by inferior
10902      function calls are special in any way.  So this function may not
10903      notice that an expression involving an inferior function call
10904      can't be watched with hardware watchpoints.  FIXME.  */
10905   for (const value_ref_ptr &iter : vals)
10906     {
10907       struct value *v = iter.get ();
10908
10909       if (VALUE_LVAL (v) == lval_memory)
10910         {
10911           if (v != head && value_lazy (v))
10912             /* A lazy memory lvalue in the chain is one that GDB never
10913                needed to fetch; we either just used its address (e.g.,
10914                `a' in `a.b') or we never needed it at all (e.g., `a'
10915                in `a,b').  This doesn't apply to HEAD; if that is
10916                lazy then it was not readable, but watch it anyway.  */
10917             ;
10918           else
10919             {
10920               /* Ahh, memory we actually used!  Check if we can cover
10921                  it with hardware watchpoints.  */
10922               struct type *vtype = check_typedef (value_type (v));
10923
10924               /* We only watch structs and arrays if user asked for it
10925                  explicitly, never if they just happen to appear in a
10926                  middle of some value chain.  */
10927               if (v == head
10928                   || (vtype->code () != TYPE_CODE_STRUCT
10929                       && vtype->code () != TYPE_CODE_ARRAY))
10930                 {
10931                   CORE_ADDR vaddr = value_address (v);
10932                   int len;
10933                   int num_regs;
10934
10935                   len = (target_exact_watchpoints
10936                          && is_scalar_type_recursive (vtype))?
10937                     1 : TYPE_LENGTH (value_type (v));
10938
10939                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10940                   if (!num_regs)
10941                     return 0;
10942                   else
10943                     found_memory_cnt += num_regs;
10944                 }
10945             }
10946         }
10947       else if (VALUE_LVAL (v) != not_lval
10948                && deprecated_value_modifiable (v) == 0)
10949         return 0;       /* These are values from the history (e.g., $1).  */
10950       else if (VALUE_LVAL (v) == lval_register)
10951         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10952     }
10953
10954   /* The expression itself looks suitable for using a hardware
10955      watchpoint, but give the target machine a chance to reject it.  */
10956   return found_memory_cnt;
10957 }
10958
10959 void
10960 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10961 {
10962   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10963 }
10964
10965 /* Options for the watch, awatch, and rwatch commands.  */
10966
10967 struct watch_options
10968 {
10969   /* For -location.  */
10970   bool location = false;
10971 };
10972
10973 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10974
10975    Historically GDB always accepted both '-location' and '-l' flags for
10976    these commands (both flags being synonyms).  When converting to the
10977    newer option scheme only '-location' is added here.  That's fine (for
10978    backward compatibility) as any non-ambiguous prefix of a flag will be
10979    accepted, so '-l', '-loc', are now all accepted.
10980
10981    What this means is that, if in the future, we add any new flag here
10982    that starts with '-l' then this will break backward compatibility, so
10983    please, don't do that!  */
10984
10985 static const gdb::option::option_def watch_option_defs[] = {
10986   gdb::option::flag_option_def<watch_options> {
10987     "location",
10988     [] (watch_options *opt) { return &opt->location; },
10989     N_("\
10990 This evaluates EXPRESSION and watches the memory to which is refers.\n\
10991 -l can be used as a short form of -location."),
10992   },
10993 };
10994
10995 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
10996    commands.  */
10997
10998 static gdb::option::option_def_group
10999 make_watch_options_def_group (watch_options *opts)
11000 {
11001   return {{watch_option_defs}, opts};
11002 }
11003
11004 /* A helper function that looks for the "-location" argument and then
11005    calls watch_command_1.  */
11006
11007 static void
11008 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11009 {
11010   watch_options opts;
11011   auto grp = make_watch_options_def_group (&opts);
11012   gdb::option::process_options
11013     (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
11014   if (arg != nullptr && *arg == '\0')
11015     arg = nullptr;
11016
11017   watch_command_1 (arg, accessflag, from_tty, opts.location, false);
11018 }
11019
11020 /* Command completion for 'watch', 'awatch', and 'rwatch' commands.   */
11021 static void
11022 watch_command_completer (struct cmd_list_element *ignore,
11023                          completion_tracker &tracker,
11024                          const char *text, const char * /*word*/)
11025 {
11026   const auto group = make_watch_options_def_group (nullptr);
11027   if (gdb::option::complete_options
11028       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
11029     return;
11030
11031   const char *word = advance_to_expression_complete_word_point (tracker, text);
11032   expression_completer (ignore, tracker, text, word);
11033 }
11034
11035 static void
11036 watch_command (const char *arg, int from_tty)
11037 {
11038   watch_maybe_just_location (arg, hw_write, from_tty);
11039 }
11040
11041 void
11042 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
11043 {
11044   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11045 }
11046
11047 static void
11048 rwatch_command (const char *arg, int from_tty)
11049 {
11050   watch_maybe_just_location (arg, hw_read, from_tty);
11051 }
11052
11053 void
11054 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
11055 {
11056   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11057 }
11058
11059 static void
11060 awatch_command (const char *arg, int from_tty)
11061 {
11062   watch_maybe_just_location (arg, hw_access, from_tty);
11063 }
11064 \f
11065
11066 /* Data for the FSM that manages the until(location)/advance commands
11067    in infcmd.c.  Here because it uses the mechanisms of
11068    breakpoints.  */
11069
11070 struct until_break_fsm : public thread_fsm
11071 {
11072   /* The thread that was current when the command was executed.  */
11073   int thread;
11074
11075   /* The breakpoint set at the return address in the caller frame,
11076      plus breakpoints at all the destination locations.  */
11077   std::vector<breakpoint_up> breakpoints;
11078
11079   until_break_fsm (struct interp *cmd_interp, int thread,
11080                    std::vector<breakpoint_up> &&breakpoints)
11081     : thread_fsm (cmd_interp),
11082       thread (thread),
11083       breakpoints (std::move (breakpoints))
11084   {
11085   }
11086
11087   void clean_up (struct thread_info *thread) override;
11088   bool should_stop (struct thread_info *thread) override;
11089   enum async_reply_reason do_async_reply_reason () override;
11090 };
11091
11092 /* Implementation of the 'should_stop' FSM method for the
11093    until(location)/advance commands.  */
11094
11095 bool
11096 until_break_fsm::should_stop (struct thread_info *tp)
11097 {
11098   for (const breakpoint_up &bp : breakpoints)
11099     if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11100                                 bp.get ()) != NULL)
11101       {
11102         set_finished ();
11103         break;
11104       }
11105
11106   return true;
11107 }
11108
11109 /* Implementation of the 'clean_up' FSM method for the
11110    until(location)/advance commands.  */
11111
11112 void
11113 until_break_fsm::clean_up (struct thread_info *)
11114 {
11115   /* Clean up our temporary breakpoints.  */
11116   breakpoints.clear ();
11117   delete_longjmp_breakpoint (thread);
11118 }
11119
11120 /* Implementation of the 'async_reply_reason' FSM method for the
11121    until(location)/advance commands.  */
11122
11123 enum async_reply_reason
11124 until_break_fsm::do_async_reply_reason ()
11125 {
11126   return EXEC_ASYNC_LOCATION_REACHED;
11127 }
11128
11129 void
11130 until_break_command (const char *arg, int from_tty, int anywhere)
11131 {
11132   struct frame_info *frame;
11133   struct gdbarch *frame_gdbarch;
11134   struct frame_id stack_frame_id;
11135   struct frame_id caller_frame_id;
11136   int thread;
11137   struct thread_info *tp;
11138
11139   clear_proceed_status (0);
11140
11141   /* Set a breakpoint where the user wants it and at return from
11142      this function.  */
11143
11144   event_location_up location = string_to_event_location (&arg, current_language);
11145
11146   std::vector<symtab_and_line> sals
11147     = (last_displayed_sal_is_valid ()
11148        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11149                         get_last_displayed_symtab (),
11150                         get_last_displayed_line ())
11151        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11152                         NULL, NULL, 0));
11153
11154   if (sals.empty ())
11155     error (_("Couldn't get information on specified line."));
11156
11157   if (*arg)
11158     error (_("Junk at end of arguments."));
11159
11160   tp = inferior_thread ();
11161   thread = tp->global_num;
11162
11163   /* Note linespec handling above invalidates the frame chain.
11164      Installing a breakpoint also invalidates the frame chain (as it
11165      may need to switch threads), so do any frame handling before
11166      that.  */
11167
11168   frame = get_selected_frame (NULL);
11169   frame_gdbarch = get_frame_arch (frame);
11170   stack_frame_id = get_stack_frame_id (frame);
11171   caller_frame_id = frame_unwind_caller_id (frame);
11172
11173   /* Keep within the current frame, or in frames called by the current
11174      one.  */
11175
11176   std::vector<breakpoint_up> breakpoints;
11177
11178   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
11179
11180   if (frame_id_p (caller_frame_id))
11181     {
11182       struct symtab_and_line sal2;
11183       struct gdbarch *caller_gdbarch;
11184
11185       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11186       sal2.pc = frame_unwind_caller_pc (frame);
11187       caller_gdbarch = frame_unwind_caller_arch (frame);
11188
11189       breakpoint_up caller_breakpoint
11190         = set_momentary_breakpoint (caller_gdbarch, sal2,
11191                                     caller_frame_id, bp_until);
11192       breakpoints.emplace_back (std::move (caller_breakpoint));
11193
11194       set_longjmp_breakpoint (tp, caller_frame_id);
11195       lj_deleter.emplace (thread);
11196     }
11197
11198   /* set_momentary_breakpoint could invalidate FRAME.  */
11199   frame = NULL;
11200
11201   /* If the user told us to continue until a specified location, we
11202      don't specify a frame at which we need to stop.  Otherwise,
11203      specify the selected frame, because we want to stop only at the
11204      very same frame.  */
11205   frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
11206
11207   for (symtab_and_line &sal : sals)
11208     {
11209       resolve_sal_pc (&sal);
11210
11211       breakpoint_up location_breakpoint
11212         = set_momentary_breakpoint (frame_gdbarch, sal,
11213                                     stop_frame_id, bp_until);
11214       breakpoints.emplace_back (std::move (location_breakpoint));
11215     }
11216
11217   tp->thread_fsm = new until_break_fsm (command_interp (), tp->global_num,
11218                                         std::move (breakpoints));
11219
11220   if (lj_deleter)
11221     lj_deleter->release ();
11222
11223   proceed (-1, GDB_SIGNAL_DEFAULT);
11224 }
11225
11226 /* This function attempts to parse an optional "if <cond>" clause
11227    from the arg string.  If one is not found, it returns NULL.
11228
11229    Else, it returns a pointer to the condition string.  (It does not
11230    attempt to evaluate the string against a particular block.)  And,
11231    it updates arg to point to the first character following the parsed
11232    if clause in the arg string.  */
11233
11234 const char *
11235 ep_parse_optional_if_clause (const char **arg)
11236 {
11237   const char *cond_string;
11238
11239   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11240     return NULL;
11241
11242   /* Skip the "if" keyword.  */
11243   (*arg) += 2;
11244
11245   /* Skip any extra leading whitespace, and record the start of the
11246      condition string.  */
11247   *arg = skip_spaces (*arg);
11248   cond_string = *arg;
11249
11250   /* Assume that the condition occupies the remainder of the arg
11251      string.  */
11252   (*arg) += strlen (cond_string);
11253
11254   return cond_string;
11255 }
11256
11257 /* Commands to deal with catching events, such as signals, exceptions,
11258    process start/exit, etc.  */
11259
11260 typedef enum
11261 {
11262   catch_fork_temporary, catch_vfork_temporary,
11263   catch_fork_permanent, catch_vfork_permanent
11264 }
11265 catch_fork_kind;
11266
11267 static void
11268 catch_fork_command_1 (const char *arg, int from_tty,
11269                       struct cmd_list_element *command)
11270 {
11271   struct gdbarch *gdbarch = get_current_arch ();
11272   const char *cond_string = NULL;
11273   catch_fork_kind fork_kind;
11274
11275   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11276   bool temp = (fork_kind == catch_fork_temporary
11277                || fork_kind == catch_vfork_temporary);
11278
11279   if (!arg)
11280     arg = "";
11281   arg = skip_spaces (arg);
11282
11283   /* The allowed syntax is:
11284      catch [v]fork
11285      catch [v]fork if <cond>
11286
11287      First, check if there's an if clause.  */
11288   cond_string = ep_parse_optional_if_clause (&arg);
11289
11290   if ((*arg != '\0') && !isspace (*arg))
11291     error (_("Junk at end of arguments."));
11292
11293   /* If this target supports it, create a fork or vfork catchpoint
11294      and enable reporting of such events.  */
11295   switch (fork_kind)
11296     {
11297     case catch_fork_temporary:
11298     case catch_fork_permanent:
11299       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11300                                           &catch_fork_breakpoint_ops);
11301       break;
11302     case catch_vfork_temporary:
11303     case catch_vfork_permanent:
11304       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11305                                           &catch_vfork_breakpoint_ops);
11306       break;
11307     default:
11308       error (_("unsupported or unknown fork kind; cannot catch it"));
11309       break;
11310     }
11311 }
11312
11313 static void
11314 catch_exec_command_1 (const char *arg, int from_tty,
11315                       struct cmd_list_element *command)
11316 {
11317   struct gdbarch *gdbarch = get_current_arch ();
11318   const char *cond_string = NULL;
11319   bool temp = get_cmd_context (command) == CATCH_TEMPORARY;
11320
11321   if (!arg)
11322     arg = "";
11323   arg = skip_spaces (arg);
11324
11325   /* The allowed syntax is:
11326      catch exec
11327      catch exec if <cond>
11328
11329      First, check if there's an if clause.  */
11330   cond_string = ep_parse_optional_if_clause (&arg);
11331
11332   if ((*arg != '\0') && !isspace (*arg))
11333     error (_("Junk at end of arguments."));
11334
11335   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11336   init_catchpoint (c.get (), gdbarch, temp, cond_string,
11337                    &catch_exec_breakpoint_ops);
11338   c->exec_pathname = NULL;
11339
11340   install_breakpoint (0, std::move (c), 1);
11341 }
11342
11343 void
11344 init_ada_exception_breakpoint (struct breakpoint *b,
11345                                struct gdbarch *gdbarch,
11346                                struct symtab_and_line sal,
11347                                const char *addr_string,
11348                                const struct breakpoint_ops *ops,
11349                                int tempflag,
11350                                int enabled,
11351                                int from_tty)
11352 {
11353   if (from_tty)
11354     {
11355       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11356       if (!loc_gdbarch)
11357         loc_gdbarch = gdbarch;
11358
11359       describe_other_breakpoints (loc_gdbarch,
11360                                   sal.pspace, sal.pc, sal.section, -1);
11361       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11362          version for exception catchpoints, because two catchpoints
11363          used for different exception names will use the same address.
11364          In this case, a "breakpoint ... also set at..." warning is
11365          unproductive.  Besides, the warning phrasing is also a bit
11366          inappropriate, we should use the word catchpoint, and tell
11367          the user what type of catchpoint it is.  The above is good
11368          enough for now, though.  */
11369     }
11370
11371   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
11372
11373   b->enable_state = enabled ? bp_enabled : bp_disabled;
11374   b->disposition = tempflag ? disp_del : disp_donttouch;
11375   b->location = string_to_event_location (&addr_string,
11376                                           language_def (language_ada));
11377   b->language = language_ada;
11378 }
11379
11380 \f
11381
11382 /* Compare two breakpoints and return a strcmp-like result.  */
11383
11384 static int
11385 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11386 {
11387   uintptr_t ua = (uintptr_t) a;
11388   uintptr_t ub = (uintptr_t) b;
11389
11390   if (a->number < b->number)
11391     return -1;
11392   else if (a->number > b->number)
11393     return 1;
11394
11395   /* Now sort by address, in case we see, e..g, two breakpoints with
11396      the number 0.  */
11397   if (ua < ub)
11398     return -1;
11399   return ua > ub ? 1 : 0;
11400 }
11401
11402 /* Delete breakpoints by address or line.  */
11403
11404 static void
11405 clear_command (const char *arg, int from_tty)
11406 {
11407   int default_match;
11408
11409   std::vector<symtab_and_line> decoded_sals;
11410   symtab_and_line last_sal;
11411   gdb::array_view<symtab_and_line> sals;
11412   if (arg)
11413     {
11414       decoded_sals
11415         = decode_line_with_current_source (arg,
11416                                            (DECODE_LINE_FUNFIRSTLINE
11417                                             | DECODE_LINE_LIST_MODE));
11418       default_match = 0;
11419       sals = decoded_sals;
11420     }
11421   else
11422     {
11423       /* Set sal's line, symtab, pc, and pspace to the values
11424          corresponding to the last call to print_frame_info.  If the
11425          codepoint is not valid, this will set all the fields to 0.  */
11426       last_sal = get_last_displayed_sal ();
11427       if (last_sal.symtab == 0)
11428         error (_("No source file specified."));
11429
11430       default_match = 1;
11431       sals = last_sal;
11432     }
11433
11434   /* We don't call resolve_sal_pc here.  That's not as bad as it
11435      seems, because all existing breakpoints typically have both
11436      file/line and pc set.  So, if clear is given file/line, we can
11437      match this to existing breakpoint without obtaining pc at all.
11438
11439      We only support clearing given the address explicitly 
11440      present in breakpoint table.  Say, we've set breakpoint 
11441      at file:line.  There were several PC values for that file:line,
11442      due to optimization, all in one block.
11443
11444      We've picked one PC value.  If "clear" is issued with another
11445      PC corresponding to the same file:line, the breakpoint won't
11446      be cleared.  We probably can still clear the breakpoint, but 
11447      since the other PC value is never presented to user, user
11448      can only find it by guessing, and it does not seem important
11449      to support that.  */
11450
11451   /* For each line spec given, delete bps which correspond to it.  Do
11452      it in two passes, solely to preserve the current behavior that
11453      from_tty is forced true if we delete more than one
11454      breakpoint.  */
11455
11456   std::vector<struct breakpoint *> found;
11457   for (const auto &sal : sals)
11458     {
11459       const char *sal_fullname;
11460
11461       /* If exact pc given, clear bpts at that pc.
11462          If line given (pc == 0), clear all bpts on specified line.
11463          If defaulting, clear all bpts on default line
11464          or at default pc.
11465
11466          defaulting    sal.pc != 0    tests to do
11467
11468          0              1             pc
11469          1              1             pc _and_ line
11470          0              0             line
11471          1              0             <can't happen> */
11472
11473       sal_fullname = (sal.symtab == NULL
11474                       ? NULL : symtab_to_fullname (sal.symtab));
11475
11476       /* Find all matching breakpoints and add them to 'found'.  */
11477       for (breakpoint *b : all_breakpoints ())
11478         {
11479           int match = 0;
11480           /* Are we going to delete b?  */
11481           if (b->type != bp_none && !is_watchpoint (b))
11482             {
11483               for (bp_location *loc : b->locations ())
11484                 {
11485                   /* If the user specified file:line, don't allow a PC
11486                      match.  This matches historical gdb behavior.  */
11487                   int pc_match = (!sal.explicit_line
11488                                   && sal.pc
11489                                   && (loc->pspace == sal.pspace)
11490                                   && (loc->address == sal.pc)
11491                                   && (!section_is_overlay (loc->section)
11492                                       || loc->section == sal.section));
11493                   int line_match = 0;
11494
11495                   if ((default_match || sal.explicit_line)
11496                       && loc->symtab != NULL
11497                       && sal_fullname != NULL
11498                       && sal.pspace == loc->pspace
11499                       && loc->line_number == sal.line
11500                       && filename_cmp (symtab_to_fullname (loc->symtab),
11501                                        sal_fullname) == 0)
11502                     line_match = 1;
11503
11504                   if (pc_match || line_match)
11505                     {
11506                       match = 1;
11507                       break;
11508                     }
11509                 }
11510             }
11511
11512           if (match)
11513             found.push_back (b);
11514         }
11515     }
11516
11517   /* Now go thru the 'found' chain and delete them.  */
11518   if (found.empty ())
11519     {
11520       if (arg)
11521         error (_("No breakpoint at %s."), arg);
11522       else
11523         error (_("No breakpoint at this line."));
11524     }
11525
11526   /* Remove duplicates from the vec.  */
11527   std::sort (found.begin (), found.end (),
11528              [] (const breakpoint *bp_a, const breakpoint *bp_b)
11529              {
11530                return compare_breakpoints (bp_a, bp_b) < 0;
11531              });
11532   found.erase (std::unique (found.begin (), found.end (),
11533                             [] (const breakpoint *bp_a, const breakpoint *bp_b)
11534                             {
11535                               return compare_breakpoints (bp_a, bp_b) == 0;
11536                             }),
11537                found.end ());
11538
11539   if (found.size () > 1)
11540     from_tty = 1;       /* Always report if deleted more than one.  */
11541   if (from_tty)
11542     {
11543       if (found.size () == 1)
11544         printf_unfiltered (_("Deleted breakpoint "));
11545       else
11546         printf_unfiltered (_("Deleted breakpoints "));
11547     }
11548
11549   for (breakpoint *iter : found)
11550     {
11551       if (from_tty)
11552         printf_unfiltered ("%d ", iter->number);
11553       delete_breakpoint (iter);
11554     }
11555   if (from_tty)
11556     putchar_unfiltered ('\n');
11557 }
11558 \f
11559 /* Delete breakpoint in BS if they are `delete' breakpoints and
11560    all breakpoints that are marked for deletion, whether hit or not.
11561    This is called after any breakpoint is hit, or after errors.  */
11562
11563 void
11564 breakpoint_auto_delete (bpstat bs)
11565 {
11566   for (; bs; bs = bs->next)
11567     if (bs->breakpoint_at
11568         && bs->breakpoint_at->disposition == disp_del
11569         && bs->stop)
11570       delete_breakpoint (bs->breakpoint_at);
11571
11572   for (breakpoint *b : all_breakpoints_safe ())
11573     if (b->disposition == disp_del_at_next_stop)
11574       delete_breakpoint (b);
11575 }
11576
11577 /* A comparison function for bp_location AP and BP being interfaced to
11578    std::sort.  Sort elements primarily by their ADDRESS (no matter what
11579    bl_address_is_meaningful says), secondarily by ordering first
11580    permanent elements and terciarily just ensuring the array is sorted
11581    stable way despite std::sort being an unstable algorithm.  */
11582
11583 static int
11584 bp_location_is_less_than (const bp_location *a, const bp_location *b)
11585 {
11586   if (a->address != b->address)
11587     return a->address < b->address;
11588
11589   /* Sort locations at the same address by their pspace number, keeping
11590      locations of the same inferior (in a multi-inferior environment)
11591      grouped.  */
11592
11593   if (a->pspace->num != b->pspace->num)
11594     return a->pspace->num < b->pspace->num;
11595
11596   /* Sort permanent breakpoints first.  */
11597   if (a->permanent != b->permanent)
11598     return a->permanent > b->permanent;
11599
11600   /* Sort by type in order to make duplicate determination easier.
11601      See update_global_location_list.  This is kept in sync with
11602      breakpoint_locations_match.  */
11603   if (a->loc_type < b->loc_type)
11604     return true;
11605
11606   /* Likewise, for range-breakpoints, sort by length.  */
11607   if (a->loc_type == bp_loc_hardware_breakpoint
11608       && b->loc_type == bp_loc_hardware_breakpoint
11609       && a->length < b->length)
11610     return true;
11611
11612   /* Make the internal GDB representation stable across GDB runs
11613      where A and B memory inside GDB can differ.  Breakpoint locations of
11614      the same type at the same address can be sorted in arbitrary order.  */
11615
11616   if (a->owner->number != b->owner->number)
11617     return a->owner->number < b->owner->number;
11618
11619   return a < b;
11620 }
11621
11622 /* Set bp_locations_placed_address_before_address_max and
11623    bp_locations_shadow_len_after_address_max according to the current
11624    content of the bp_locations array.  */
11625
11626 static void
11627 bp_locations_target_extensions_update (void)
11628 {
11629   bp_locations_placed_address_before_address_max = 0;
11630   bp_locations_shadow_len_after_address_max = 0;
11631
11632   for (bp_location *bl : all_bp_locations ())
11633     {
11634       CORE_ADDR start, end, addr;
11635
11636       if (!bp_location_has_shadow (bl))
11637         continue;
11638
11639       start = bl->target_info.placed_address;
11640       end = start + bl->target_info.shadow_len;
11641
11642       gdb_assert (bl->address >= start);
11643       addr = bl->address - start;
11644       if (addr > bp_locations_placed_address_before_address_max)
11645         bp_locations_placed_address_before_address_max = addr;
11646
11647       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11648
11649       gdb_assert (bl->address < end);
11650       addr = end - bl->address;
11651       if (addr > bp_locations_shadow_len_after_address_max)
11652         bp_locations_shadow_len_after_address_max = addr;
11653     }
11654 }
11655
11656 /* Download tracepoint locations if they haven't been.  */
11657
11658 static void
11659 download_tracepoint_locations (void)
11660 {
11661   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11662
11663   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11664
11665   for (breakpoint *b : all_tracepoints ())
11666     {
11667       struct tracepoint *t;
11668       int bp_location_downloaded = 0;
11669
11670       if ((b->type == bp_fast_tracepoint
11671            ? !may_insert_fast_tracepoints
11672            : !may_insert_tracepoints))
11673         continue;
11674
11675       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11676         {
11677           if (target_can_download_tracepoint ())
11678             can_download_tracepoint = TRIBOOL_TRUE;
11679           else
11680             can_download_tracepoint = TRIBOOL_FALSE;
11681         }
11682
11683       if (can_download_tracepoint == TRIBOOL_FALSE)
11684         break;
11685
11686       for (bp_location *bl : b->locations ())
11687         {
11688           /* In tracepoint, locations are _never_ duplicated, so
11689              should_be_inserted is equivalent to
11690              unduplicated_should_be_inserted.  */
11691           if (!should_be_inserted (bl) || bl->inserted)
11692             continue;
11693
11694           switch_to_program_space_and_thread (bl->pspace);
11695
11696           target_download_tracepoint (bl);
11697
11698           bl->inserted = 1;
11699           bp_location_downloaded = 1;
11700         }
11701       t = (struct tracepoint *) b;
11702       t->number_on_target = b->number;
11703       if (bp_location_downloaded)
11704         gdb::observers::breakpoint_modified.notify (b);
11705     }
11706 }
11707
11708 /* Swap the insertion/duplication state between two locations.  */
11709
11710 static void
11711 swap_insertion (struct bp_location *left, struct bp_location *right)
11712 {
11713   const int left_inserted = left->inserted;
11714   const int left_duplicate = left->duplicate;
11715   const int left_needs_update = left->needs_update;
11716   const struct bp_target_info left_target_info = left->target_info;
11717
11718   /* Locations of tracepoints can never be duplicated.  */
11719   if (is_tracepoint (left->owner))
11720     gdb_assert (!left->duplicate);
11721   if (is_tracepoint (right->owner))
11722     gdb_assert (!right->duplicate);
11723
11724   left->inserted = right->inserted;
11725   left->duplicate = right->duplicate;
11726   left->needs_update = right->needs_update;
11727   left->target_info = right->target_info;
11728   right->inserted = left_inserted;
11729   right->duplicate = left_duplicate;
11730   right->needs_update = left_needs_update;
11731   right->target_info = left_target_info;
11732 }
11733
11734 /* Force the re-insertion of the locations at ADDRESS.  This is called
11735    once a new/deleted/modified duplicate location is found and we are evaluating
11736    conditions on the target's side.  Such conditions need to be updated on
11737    the target.  */
11738
11739 static void
11740 force_breakpoint_reinsertion (struct bp_location *bl)
11741 {
11742   CORE_ADDR address = 0;
11743   int pspace_num;
11744
11745   address = bl->address;
11746   pspace_num = bl->pspace->num;
11747
11748   /* This is only meaningful if the target is
11749      evaluating conditions and if the user has
11750      opted for condition evaluation on the target's
11751      side.  */
11752   if (gdb_evaluates_breakpoint_condition_p ()
11753       || !target_supports_evaluation_of_breakpoint_conditions ())
11754     return;
11755
11756   /* Flag all breakpoint locations with this address and
11757      the same program space as the location
11758      as "its condition has changed".  We need to
11759      update the conditions on the target's side.  */
11760   for (bp_location *loc : all_bp_locations_at_addr (address))
11761     {
11762       if (!is_breakpoint (loc->owner)
11763           || pspace_num != loc->pspace->num)
11764         continue;
11765
11766       /* Flag the location appropriately.  We use a different state to
11767          let everyone know that we already updated the set of locations
11768          with addr bl->address and program space bl->pspace.  This is so
11769          we don't have to keep calling these functions just to mark locations
11770          that have already been marked.  */
11771       loc->condition_changed = condition_updated;
11772
11773       /* Free the agent expression bytecode as well.  We will compute
11774          it later on.  */
11775       loc->cond_bytecode.reset ();
11776     }
11777 }
11778
11779 /* Called whether new breakpoints are created, or existing breakpoints
11780    deleted, to update the global location list and recompute which
11781    locations are duplicate of which.
11782
11783    The INSERT_MODE flag determines whether locations may not, may, or
11784    shall be inserted now.  See 'enum ugll_insert_mode' for more
11785    info.  */
11786
11787 static void
11788 update_global_location_list (enum ugll_insert_mode insert_mode)
11789 {
11790   /* Last breakpoint location address that was marked for update.  */
11791   CORE_ADDR last_addr = 0;
11792   /* Last breakpoint location program space that was marked for update.  */
11793   int last_pspace_num = -1;
11794
11795   /* Used in the duplicates detection below.  When iterating over all
11796      bp_locations, points to the first bp_location of a given address.
11797      Breakpoints and watchpoints of different types are never
11798      duplicates of each other.  Keep one pointer for each type of
11799      breakpoint/watchpoint, so we only need to loop over all locations
11800      once.  */
11801   struct bp_location *bp_loc_first;  /* breakpoint */
11802   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11803   struct bp_location *awp_loc_first; /* access watchpoint */
11804   struct bp_location *rwp_loc_first; /* read watchpoint */
11805
11806   /* Saved former bp_locations array which we compare against the newly
11807      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11808   std::vector<bp_location *> old_locations = std::move (bp_locations);
11809   bp_locations.clear ();
11810
11811   for (breakpoint *b : all_breakpoints ())
11812     for (bp_location *loc : b->locations ())
11813       bp_locations.push_back (loc);
11814
11815   /* See if we need to "upgrade" a software breakpoint to a hardware
11816      breakpoint.  Do this before deciding whether locations are
11817      duplicates.  Also do this before sorting because sorting order
11818      depends on location type.  */
11819   for (bp_location *loc : bp_locations)
11820     if (!loc->inserted && should_be_inserted (loc))
11821         handle_automatic_hardware_breakpoints (loc);
11822
11823   std::sort (bp_locations.begin (), bp_locations.end (),
11824              bp_location_is_less_than);
11825
11826   bp_locations_target_extensions_update ();
11827
11828   /* Identify bp_location instances that are no longer present in the
11829      new list, and therefore should be freed.  Note that it's not
11830      necessary that those locations should be removed from inferior --
11831      if there's another location at the same address (previously
11832      marked as duplicate), we don't need to remove/insert the
11833      location.
11834      
11835      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11836      and former bp_location array state respectively.  */
11837
11838   size_t loc_i = 0;
11839   for (bp_location *old_loc : old_locations)
11840     {
11841       /* Tells if 'old_loc' is found among the new locations.  If
11842          not, we have to free it.  */
11843       int found_object = 0;
11844       /* Tells if the location should remain inserted in the target.  */
11845       int keep_in_target = 0;
11846       int removed = 0;
11847
11848       /* Skip LOCP entries which will definitely never be needed.
11849          Stop either at or being the one matching OLD_LOC.  */
11850       while (loc_i < bp_locations.size ()
11851              && bp_locations[loc_i]->address < old_loc->address)
11852         loc_i++;
11853
11854       for (size_t loc2_i = loc_i;
11855            (loc2_i < bp_locations.size ()
11856             && bp_locations[loc2_i]->address == old_loc->address);
11857            loc2_i++)
11858         {
11859           /* Check if this is a new/duplicated location or a duplicated
11860              location that had its condition modified.  If so, we want to send
11861              its condition to the target if evaluation of conditions is taking
11862              place there.  */
11863           if (bp_locations[loc2_i]->condition_changed == condition_modified
11864               && (last_addr != old_loc->address
11865                   || last_pspace_num != old_loc->pspace->num))
11866             {
11867               force_breakpoint_reinsertion (bp_locations[loc2_i]);
11868               last_pspace_num = old_loc->pspace->num;
11869             }
11870
11871           if (bp_locations[loc2_i] == old_loc)
11872             found_object = 1;
11873         }
11874
11875       /* We have already handled this address, update it so that we don't
11876          have to go through updates again.  */
11877       last_addr = old_loc->address;
11878
11879       /* Target-side condition evaluation: Handle deleted locations.  */
11880       if (!found_object)
11881         force_breakpoint_reinsertion (old_loc);
11882
11883       /* If this location is no longer present, and inserted, look if
11884          there's maybe a new location at the same address.  If so,
11885          mark that one inserted, and don't remove this one.  This is
11886          needed so that we don't have a time window where a breakpoint
11887          at certain location is not inserted.  */
11888
11889       if (old_loc->inserted)
11890         {
11891           /* If the location is inserted now, we might have to remove
11892              it.  */
11893
11894           if (found_object && should_be_inserted (old_loc))
11895             {
11896               /* The location is still present in the location list,
11897                  and still should be inserted.  Don't do anything.  */
11898               keep_in_target = 1;
11899             }
11900           else
11901             {
11902               /* This location still exists, but it won't be kept in the
11903                  target since it may have been disabled.  We proceed to
11904                  remove its target-side condition.  */
11905
11906               /* The location is either no longer present, or got
11907                  disabled.  See if there's another location at the
11908                  same address, in which case we don't need to remove
11909                  this one from the target.  */
11910
11911               /* OLD_LOC comes from existing struct breakpoint.  */
11912               if (bl_address_is_meaningful (old_loc))
11913                 {
11914                   for (size_t loc2_i = loc_i;
11915                        (loc2_i < bp_locations.size ()
11916                         && bp_locations[loc2_i]->address == old_loc->address);
11917                        loc2_i++)
11918                     {
11919                       bp_location *loc2 = bp_locations[loc2_i];
11920
11921                       if (loc2 == old_loc)
11922                         continue;
11923
11924                       if (breakpoint_locations_match (loc2, old_loc))
11925                         {
11926                           /* Read watchpoint locations are switched to
11927                              access watchpoints, if the former are not
11928                              supported, but the latter are.  */
11929                           if (is_hardware_watchpoint (old_loc->owner))
11930                             {
11931                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11932                               loc2->watchpoint_type = old_loc->watchpoint_type;
11933                             }
11934
11935                           /* loc2 is a duplicated location. We need to check
11936                              if it should be inserted in case it will be
11937                              unduplicated.  */
11938                           if (unduplicated_should_be_inserted (loc2))
11939                             {
11940                               swap_insertion (old_loc, loc2);
11941                               keep_in_target = 1;
11942                               break;
11943                             }
11944                         }
11945                     }
11946                 }
11947             }
11948
11949           if (!keep_in_target)
11950             {
11951               if (remove_breakpoint (old_loc))
11952                 {
11953                   /* This is just about all we can do.  We could keep
11954                      this location on the global list, and try to
11955                      remove it next time, but there's no particular
11956                      reason why we will succeed next time.
11957                      
11958                      Note that at this point, old_loc->owner is still
11959                      valid, as delete_breakpoint frees the breakpoint
11960                      only after calling us.  */
11961                   printf_filtered (_("warning: Error removing "
11962                                      "breakpoint %d\n"), 
11963                                    old_loc->owner->number);
11964                 }
11965               removed = 1;
11966             }
11967         }
11968
11969       if (!found_object)
11970         {
11971           if (removed && target_is_non_stop_p ()
11972               && need_moribund_for_location_type (old_loc))
11973             {
11974               /* This location was removed from the target.  In
11975                  non-stop mode, a race condition is possible where
11976                  we've removed a breakpoint, but stop events for that
11977                  breakpoint are already queued and will arrive later.
11978                  We apply an heuristic to be able to distinguish such
11979                  SIGTRAPs from other random SIGTRAPs: we keep this
11980                  breakpoint location for a bit, and will retire it
11981                  after we see some number of events.  The theory here
11982                  is that reporting of events should, "on the average",
11983                  be fair, so after a while we'll see events from all
11984                  threads that have anything of interest, and no longer
11985                  need to keep this breakpoint location around.  We
11986                  don't hold locations forever so to reduce chances of
11987                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11988                  SIGTRAP.
11989
11990                  The heuristic failing can be disastrous on
11991                  decr_pc_after_break targets.
11992
11993                  On decr_pc_after_break targets, like e.g., x86-linux,
11994                  if we fail to recognize a late breakpoint SIGTRAP,
11995                  because events_till_retirement has reached 0 too
11996                  soon, we'll fail to do the PC adjustment, and report
11997                  a random SIGTRAP to the user.  When the user resumes
11998                  the inferior, it will most likely immediately crash
11999                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12000                  corrupted, because of being resumed e.g., in the
12001                  middle of a multi-byte instruction, or skipped a
12002                  one-byte instruction.  This was actually seen happen
12003                  on native x86-linux, and should be less rare on
12004                  targets that do not support new thread events, like
12005                  remote, due to the heuristic depending on
12006                  thread_count.
12007
12008                  Mistaking a random SIGTRAP for a breakpoint trap
12009                  causes similar symptoms (PC adjustment applied when
12010                  it shouldn't), but then again, playing with SIGTRAPs
12011                  behind the debugger's back is asking for trouble.
12012
12013                  Since hardware watchpoint traps are always
12014                  distinguishable from other traps, so we don't need to
12015                  apply keep hardware watchpoint moribund locations
12016                  around.  We simply always ignore hardware watchpoint
12017                  traps we can no longer explain.  */
12018
12019               process_stratum_target *proc_target = nullptr;
12020               for (inferior *inf : all_inferiors ())
12021                 if (inf->pspace == old_loc->pspace)
12022                   {
12023                     proc_target = inf->process_target ();
12024                     break;
12025                   }
12026               if (proc_target != nullptr)
12027                 old_loc->events_till_retirement
12028                   = 3 * (thread_count (proc_target) + 1);
12029               else
12030                 old_loc->events_till_retirement = 1;
12031               old_loc->owner = NULL;
12032
12033               moribund_locations.push_back (old_loc);
12034             }
12035           else
12036             {
12037               old_loc->owner = NULL;
12038               decref_bp_location (&old_loc);
12039             }
12040         }
12041     }
12042
12043   /* Rescan breakpoints at the same address and section, marking the
12044      first one as "first" and any others as "duplicates".  This is so
12045      that the bpt instruction is only inserted once.  If we have a
12046      permanent breakpoint at the same place as BPT, make that one the
12047      official one, and the rest as duplicates.  Permanent breakpoints
12048      are sorted first for the same address.
12049
12050      Do the same for hardware watchpoints, but also considering the
12051      watchpoint's type (regular/access/read) and length.  */
12052
12053   bp_loc_first = NULL;
12054   wp_loc_first = NULL;
12055   awp_loc_first = NULL;
12056   rwp_loc_first = NULL;
12057
12058   for (bp_location *loc : all_bp_locations ())
12059     {
12060       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12061          non-NULL.  */
12062       struct bp_location **loc_first_p;
12063       breakpoint *b = loc->owner;
12064
12065       if (!unduplicated_should_be_inserted (loc)
12066           || !bl_address_is_meaningful (loc)
12067           /* Don't detect duplicate for tracepoint locations because they are
12068            never duplicated.  See the comments in field `duplicate' of
12069            `struct bp_location'.  */
12070           || is_tracepoint (b))
12071         {
12072           /* Clear the condition modification flag.  */
12073           loc->condition_changed = condition_unchanged;
12074           continue;
12075         }
12076
12077       if (b->type == bp_hardware_watchpoint)
12078         loc_first_p = &wp_loc_first;
12079       else if (b->type == bp_read_watchpoint)
12080         loc_first_p = &rwp_loc_first;
12081       else if (b->type == bp_access_watchpoint)
12082         loc_first_p = &awp_loc_first;
12083       else
12084         loc_first_p = &bp_loc_first;
12085
12086       if (*loc_first_p == NULL
12087           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12088           || !breakpoint_locations_match (loc, *loc_first_p))
12089         {
12090           *loc_first_p = loc;
12091           loc->duplicate = 0;
12092
12093           if (is_breakpoint (loc->owner) && loc->condition_changed)
12094             {
12095               loc->needs_update = 1;
12096               /* Clear the condition modification flag.  */
12097               loc->condition_changed = condition_unchanged;
12098             }
12099           continue;
12100         }
12101
12102
12103       /* This and the above ensure the invariant that the first location
12104          is not duplicated, and is the inserted one.
12105          All following are marked as duplicated, and are not inserted.  */
12106       if (loc->inserted)
12107         swap_insertion (loc, *loc_first_p);
12108       loc->duplicate = 1;
12109
12110       /* Clear the condition modification flag.  */
12111       loc->condition_changed = condition_unchanged;
12112     }
12113
12114   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12115     {
12116       if (insert_mode != UGLL_DONT_INSERT)
12117         insert_breakpoint_locations ();
12118       else
12119         {
12120           /* Even though the caller told us to not insert new
12121              locations, we may still need to update conditions on the
12122              target's side of breakpoints that were already inserted
12123              if the target is evaluating breakpoint conditions.  We
12124              only update conditions for locations that are marked
12125              "needs_update".  */
12126           update_inserted_breakpoint_locations ();
12127         }
12128     }
12129
12130   if (insert_mode != UGLL_DONT_INSERT)
12131     download_tracepoint_locations ();
12132 }
12133
12134 void
12135 breakpoint_retire_moribund (void)
12136 {
12137   for (int ix = 0; ix < moribund_locations.size (); ++ix)
12138     {
12139       struct bp_location *loc = moribund_locations[ix];
12140       if (--(loc->events_till_retirement) == 0)
12141         {
12142           decref_bp_location (&loc);
12143           unordered_remove (moribund_locations, ix);
12144           --ix;
12145         }
12146     }
12147 }
12148
12149 static void
12150 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12151 {
12152
12153   try
12154     {
12155       update_global_location_list (insert_mode);
12156     }
12157   catch (const gdb_exception_error &e)
12158     {
12159     }
12160 }
12161
12162 /* Clear BKP from a BPS.  */
12163
12164 static void
12165 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12166 {
12167   bpstat bs;
12168
12169   for (bs = bps; bs; bs = bs->next)
12170     if (bs->breakpoint_at == bpt)
12171       {
12172         bs->breakpoint_at = NULL;
12173         bs->old_val = NULL;
12174         /* bs->commands will be freed later.  */
12175       }
12176 }
12177
12178 /* Callback for iterate_over_threads.  */
12179 static int
12180 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12181 {
12182   struct breakpoint *bpt = (struct breakpoint *) data;
12183
12184   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12185   return 0;
12186 }
12187
12188 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12189    callbacks.  */
12190
12191 static void
12192 say_where (struct breakpoint *b)
12193 {
12194   struct value_print_options opts;
12195
12196   get_user_print_options (&opts);
12197
12198   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12199      single string.  */
12200   if (b->loc == NULL)
12201     {
12202       /* For pending locations, the output differs slightly based
12203          on b->extra_string.  If this is non-NULL, it contains either
12204          a condition or dprintf arguments.  */
12205       if (b->extra_string == NULL)
12206         {
12207           printf_filtered (_(" (%s) pending."),
12208                            event_location_to_string (b->location.get ()));
12209         }
12210       else if (b->type == bp_dprintf)
12211         {
12212           printf_filtered (_(" (%s,%s) pending."),
12213                            event_location_to_string (b->location.get ()),
12214                            b->extra_string);
12215         }
12216       else
12217         {
12218           printf_filtered (_(" (%s %s) pending."),
12219                            event_location_to_string (b->location.get ()),
12220                            b->extra_string);
12221         }
12222     }
12223   else
12224     {
12225       if (opts.addressprint || b->loc->symtab == NULL)
12226         printf_filtered (" at %ps",
12227                          styled_string (address_style.style (),
12228                                         paddress (b->loc->gdbarch,
12229                                                   b->loc->address)));
12230       if (b->loc->symtab != NULL)
12231         {
12232           /* If there is a single location, we can print the location
12233              more nicely.  */
12234           if (b->loc->next == NULL)
12235             {
12236               const char *filename
12237                 = symtab_to_filename_for_display (b->loc->symtab);
12238               printf_filtered (": file %ps, line %d.",
12239                                styled_string (file_name_style.style (),
12240                                               filename),
12241                                b->loc->line_number);
12242             }
12243           else
12244             /* This is not ideal, but each location may have a
12245                different file name, and this at least reflects the
12246                real situation somewhat.  */
12247             printf_filtered (": %s.",
12248                              event_location_to_string (b->location.get ()));
12249         }
12250
12251       if (b->loc->next)
12252         {
12253           struct bp_location *loc = b->loc;
12254           int n = 0;
12255           for (; loc; loc = loc->next)
12256             ++n;
12257           printf_filtered (" (%d locations)", n);
12258         }
12259     }
12260 }
12261
12262 bp_location::~bp_location ()
12263 {
12264   xfree (function_name);
12265 }
12266
12267 /* Destructor for the breakpoint base class.  */
12268
12269 breakpoint::~breakpoint ()
12270 {
12271   xfree (this->cond_string);
12272   xfree (this->extra_string);
12273 }
12274
12275 /* See breakpoint.h.  */
12276
12277 bp_locations_range breakpoint::locations ()
12278 {
12279   return bp_locations_range (this->loc);
12280 }
12281
12282 static struct bp_location *
12283 base_breakpoint_allocate_location (struct breakpoint *self)
12284 {
12285   return new bp_location (self);
12286 }
12287
12288 static void
12289 base_breakpoint_re_set (struct breakpoint *b)
12290 {
12291   /* Nothing to re-set. */
12292 }
12293
12294 #define internal_error_pure_virtual_called() \
12295   gdb_assert_not_reached ("pure virtual function called")
12296
12297 static int
12298 base_breakpoint_insert_location (struct bp_location *bl)
12299 {
12300   internal_error_pure_virtual_called ();
12301 }
12302
12303 static int
12304 base_breakpoint_remove_location (struct bp_location *bl,
12305                                  enum remove_bp_reason reason)
12306 {
12307   internal_error_pure_virtual_called ();
12308 }
12309
12310 static int
12311 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12312                                 const address_space *aspace,
12313                                 CORE_ADDR bp_addr,
12314                                 const struct target_waitstatus *ws)
12315 {
12316   internal_error_pure_virtual_called ();
12317 }
12318
12319 static void
12320 base_breakpoint_check_status (bpstat bs)
12321 {
12322   /* Always stop.   */
12323 }
12324
12325 /* A "works_in_software_mode" breakpoint_ops method that just internal
12326    errors.  */
12327
12328 static int
12329 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12330 {
12331   internal_error_pure_virtual_called ();
12332 }
12333
12334 /* A "resources_needed" breakpoint_ops method that just internal
12335    errors.  */
12336
12337 static int
12338 base_breakpoint_resources_needed (const struct bp_location *bl)
12339 {
12340   internal_error_pure_virtual_called ();
12341 }
12342
12343 static enum print_stop_action
12344 base_breakpoint_print_it (bpstat bs)
12345 {
12346   internal_error_pure_virtual_called ();
12347 }
12348
12349 static void
12350 base_breakpoint_print_one_detail (const struct breakpoint *self,
12351                                   struct ui_out *uiout)
12352 {
12353   /* nothing */
12354 }
12355
12356 static void
12357 base_breakpoint_print_mention (struct breakpoint *b)
12358 {
12359   internal_error_pure_virtual_called ();
12360 }
12361
12362 static void
12363 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12364 {
12365   internal_error_pure_virtual_called ();
12366 }
12367
12368 static void
12369 base_breakpoint_create_sals_from_location
12370   (struct event_location *location,
12371    struct linespec_result *canonical,
12372    enum bptype type_wanted)
12373 {
12374   internal_error_pure_virtual_called ();
12375 }
12376
12377 static void
12378 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12379                                         struct linespec_result *c,
12380                                         gdb::unique_xmalloc_ptr<char> cond_string,
12381                                         gdb::unique_xmalloc_ptr<char> extra_string,
12382                                         enum bptype type_wanted,
12383                                         enum bpdisp disposition,
12384                                         int thread,
12385                                         int task, int ignore_count,
12386                                         const struct breakpoint_ops *o,
12387                                         int from_tty, int enabled,
12388                                         int internal, unsigned flags)
12389 {
12390   internal_error_pure_virtual_called ();
12391 }
12392
12393 static std::vector<symtab_and_line>
12394 base_breakpoint_decode_location (struct breakpoint *b,
12395                                  struct event_location *location,
12396                                  struct program_space *search_pspace)
12397 {
12398   internal_error_pure_virtual_called ();
12399 }
12400
12401 /* The default 'explains_signal' method.  */
12402
12403 static int
12404 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12405 {
12406   return 1;
12407 }
12408
12409 /* The default "after_condition_true" method.  */
12410
12411 static void
12412 base_breakpoint_after_condition_true (struct bpstats *bs)
12413 {
12414   /* Nothing to do.   */
12415 }
12416
12417 struct breakpoint_ops base_breakpoint_ops =
12418 {
12419   base_breakpoint_allocate_location,
12420   base_breakpoint_re_set,
12421   base_breakpoint_insert_location,
12422   base_breakpoint_remove_location,
12423   base_breakpoint_breakpoint_hit,
12424   base_breakpoint_check_status,
12425   base_breakpoint_resources_needed,
12426   base_breakpoint_works_in_software_mode,
12427   base_breakpoint_print_it,
12428   NULL,
12429   base_breakpoint_print_one_detail,
12430   base_breakpoint_print_mention,
12431   base_breakpoint_print_recreate,
12432   base_breakpoint_create_sals_from_location,
12433   base_breakpoint_create_breakpoints_sal,
12434   base_breakpoint_decode_location,
12435   base_breakpoint_explains_signal,
12436   base_breakpoint_after_condition_true,
12437 };
12438
12439 /* Default breakpoint_ops methods.  */
12440
12441 static void
12442 bkpt_re_set (struct breakpoint *b)
12443 {
12444   /* FIXME: is this still reachable?  */
12445   if (breakpoint_event_location_empty_p (b))
12446     {
12447       /* Anything without a location can't be re-set.  */
12448       delete_breakpoint (b);
12449       return;
12450     }
12451
12452   breakpoint_re_set_default (b);
12453 }
12454
12455 static int
12456 bkpt_insert_location (struct bp_location *bl)
12457 {
12458   CORE_ADDR addr = bl->target_info.reqstd_address;
12459
12460   bl->target_info.kind = breakpoint_kind (bl, &addr);
12461   bl->target_info.placed_address = addr;
12462
12463   if (bl->loc_type == bp_loc_hardware_breakpoint)
12464     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12465   else
12466     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12467 }
12468
12469 static int
12470 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12471 {
12472   if (bl->loc_type == bp_loc_hardware_breakpoint)
12473     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12474   else
12475     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12476 }
12477
12478 static int
12479 bkpt_breakpoint_hit (const struct bp_location *bl,
12480                      const address_space *aspace, CORE_ADDR bp_addr,
12481                      const struct target_waitstatus *ws)
12482 {
12483   if (ws->kind != TARGET_WAITKIND_STOPPED
12484       || ws->value.sig != GDB_SIGNAL_TRAP)
12485     return 0;
12486
12487   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12488                                  aspace, bp_addr))
12489     return 0;
12490
12491   if (overlay_debugging         /* unmapped overlay section */
12492       && section_is_overlay (bl->section)
12493       && !section_is_mapped (bl->section))
12494     return 0;
12495
12496   return 1;
12497 }
12498
12499 static int
12500 dprintf_breakpoint_hit (const struct bp_location *bl,
12501                         const address_space *aspace, CORE_ADDR bp_addr,
12502                         const struct target_waitstatus *ws)
12503 {
12504   if (dprintf_style == dprintf_style_agent
12505       && target_can_run_breakpoint_commands ())
12506     {
12507       /* An agent-style dprintf never causes a stop.  If we see a trap
12508          for this address it must be for a breakpoint that happens to
12509          be set at the same address.  */
12510       return 0;
12511     }
12512
12513   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12514 }
12515
12516 static int
12517 bkpt_resources_needed (const struct bp_location *bl)
12518 {
12519   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12520
12521   return 1;
12522 }
12523
12524 static enum print_stop_action
12525 bkpt_print_it (bpstat bs)
12526 {
12527   struct breakpoint *b;
12528   const struct bp_location *bl;
12529   int bp_temp;
12530   struct ui_out *uiout = current_uiout;
12531
12532   gdb_assert (bs->bp_location_at != NULL);
12533
12534   bl = bs->bp_location_at.get ();
12535   b = bs->breakpoint_at;
12536
12537   bp_temp = b->disposition == disp_del;
12538   if (bl->address != bl->requested_address)
12539     breakpoint_adjustment_warning (bl->requested_address,
12540                                    bl->address,
12541                                    b->number, 1);
12542   annotate_breakpoint (b->number);
12543   maybe_print_thread_hit_breakpoint (uiout);
12544
12545   if (uiout->is_mi_like_p ())
12546     {
12547       uiout->field_string ("reason",
12548                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12549       uiout->field_string ("disp", bpdisp_text (b->disposition));
12550     }
12551   if (bp_temp)
12552     uiout->message ("Temporary breakpoint %pF, ",
12553                     signed_field ("bkptno", b->number));
12554   else
12555     uiout->message ("Breakpoint %pF, ",
12556                     signed_field ("bkptno", b->number));
12557
12558   return PRINT_SRC_AND_LOC;
12559 }
12560
12561 static void
12562 bkpt_print_mention (struct breakpoint *b)
12563 {
12564   if (current_uiout->is_mi_like_p ())
12565     return;
12566
12567   switch (b->type)
12568     {
12569     case bp_breakpoint:
12570     case bp_gnu_ifunc_resolver:
12571       if (b->disposition == disp_del)
12572         printf_filtered (_("Temporary breakpoint"));
12573       else
12574         printf_filtered (_("Breakpoint"));
12575       printf_filtered (_(" %d"), b->number);
12576       if (b->type == bp_gnu_ifunc_resolver)
12577         printf_filtered (_(" at gnu-indirect-function resolver"));
12578       break;
12579     case bp_hardware_breakpoint:
12580       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12581       break;
12582     case bp_dprintf:
12583       printf_filtered (_("Dprintf %d"), b->number);
12584       break;
12585     }
12586
12587   say_where (b);
12588 }
12589
12590 static void
12591 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12592 {
12593   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12594     fprintf_unfiltered (fp, "tbreak");
12595   else if (tp->type == bp_breakpoint)
12596     fprintf_unfiltered (fp, "break");
12597   else if (tp->type == bp_hardware_breakpoint
12598            && tp->disposition == disp_del)
12599     fprintf_unfiltered (fp, "thbreak");
12600   else if (tp->type == bp_hardware_breakpoint)
12601     fprintf_unfiltered (fp, "hbreak");
12602   else
12603     internal_error (__FILE__, __LINE__,
12604                     _("unhandled breakpoint type %d"), (int) tp->type);
12605
12606   fprintf_unfiltered (fp, " %s",
12607                       event_location_to_string (tp->location.get ()));
12608
12609   /* Print out extra_string if this breakpoint is pending.  It might
12610      contain, for example, conditions that were set by the user.  */
12611   if (tp->loc == NULL && tp->extra_string != NULL)
12612     fprintf_unfiltered (fp, " %s", tp->extra_string);
12613
12614   print_recreate_thread (tp, fp);
12615 }
12616
12617 static void
12618 bkpt_create_sals_from_location (struct event_location *location,
12619                                 struct linespec_result *canonical,
12620                                 enum bptype type_wanted)
12621 {
12622   create_sals_from_location_default (location, canonical, type_wanted);
12623 }
12624
12625 static void
12626 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12627                              struct linespec_result *canonical,
12628                              gdb::unique_xmalloc_ptr<char> cond_string,
12629                              gdb::unique_xmalloc_ptr<char> extra_string,
12630                              enum bptype type_wanted,
12631                              enum bpdisp disposition,
12632                              int thread,
12633                              int task, int ignore_count,
12634                              const struct breakpoint_ops *ops,
12635                              int from_tty, int enabled,
12636                              int internal, unsigned flags)
12637 {
12638   create_breakpoints_sal_default (gdbarch, canonical,
12639                                   std::move (cond_string),
12640                                   std::move (extra_string),
12641                                   type_wanted,
12642                                   disposition, thread, task,
12643                                   ignore_count, ops, from_tty,
12644                                   enabled, internal, flags);
12645 }
12646
12647 static std::vector<symtab_and_line>
12648 bkpt_decode_location (struct breakpoint *b,
12649                       struct event_location *location,
12650                       struct program_space *search_pspace)
12651 {
12652   return decode_location_default (b, location, search_pspace);
12653 }
12654
12655 /* Virtual table for internal breakpoints.  */
12656
12657 static void
12658 internal_bkpt_re_set (struct breakpoint *b)
12659 {
12660   switch (b->type)
12661     {
12662       /* Delete overlay event and longjmp master breakpoints; they
12663          will be reset later by breakpoint_re_set.  */
12664     case bp_overlay_event:
12665     case bp_longjmp_master:
12666     case bp_std_terminate_master:
12667     case bp_exception_master:
12668       delete_breakpoint (b);
12669       break;
12670
12671       /* This breakpoint is special, it's set up when the inferior
12672          starts and we really don't want to touch it.  */
12673     case bp_shlib_event:
12674
12675       /* Like bp_shlib_event, this breakpoint type is special.  Once
12676          it is set up, we do not want to touch it.  */
12677     case bp_thread_event:
12678       break;
12679     }
12680 }
12681
12682 static void
12683 internal_bkpt_check_status (bpstat bs)
12684 {
12685   if (bs->breakpoint_at->type == bp_shlib_event)
12686     {
12687       /* If requested, stop when the dynamic linker notifies GDB of
12688          events.  This allows the user to get control and place
12689          breakpoints in initializer routines for dynamically loaded
12690          objects (among other things).  */
12691       bs->stop = stop_on_solib_events;
12692       bs->print = stop_on_solib_events;
12693     }
12694   else
12695     bs->stop = 0;
12696 }
12697
12698 static enum print_stop_action
12699 internal_bkpt_print_it (bpstat bs)
12700 {
12701   struct breakpoint *b;
12702
12703   b = bs->breakpoint_at;
12704
12705   switch (b->type)
12706     {
12707     case bp_shlib_event:
12708       /* Did we stop because the user set the stop_on_solib_events
12709          variable?  (If so, we report this as a generic, "Stopped due
12710          to shlib event" message.) */
12711       print_solib_event (0);
12712       break;
12713
12714     case bp_thread_event:
12715       /* Not sure how we will get here.
12716          GDB should not stop for these breakpoints.  */
12717       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12718       break;
12719
12720     case bp_overlay_event:
12721       /* By analogy with the thread event, GDB should not stop for these.  */
12722       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12723       break;
12724
12725     case bp_longjmp_master:
12726       /* These should never be enabled.  */
12727       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12728       break;
12729
12730     case bp_std_terminate_master:
12731       /* These should never be enabled.  */
12732       printf_filtered (_("std::terminate Master Breakpoint: "
12733                          "gdb should not stop!\n"));
12734       break;
12735
12736     case bp_exception_master:
12737       /* These should never be enabled.  */
12738       printf_filtered (_("Exception Master Breakpoint: "
12739                          "gdb should not stop!\n"));
12740       break;
12741     }
12742
12743   return PRINT_NOTHING;
12744 }
12745
12746 static void
12747 internal_bkpt_print_mention (struct breakpoint *b)
12748 {
12749   /* Nothing to mention.  These breakpoints are internal.  */
12750 }
12751
12752 /* Virtual table for momentary breakpoints  */
12753
12754 static void
12755 momentary_bkpt_re_set (struct breakpoint *b)
12756 {
12757   /* Keep temporary breakpoints, which can be encountered when we step
12758      over a dlopen call and solib_add is resetting the breakpoints.
12759      Otherwise these should have been blown away via the cleanup chain
12760      or by breakpoint_init_inferior when we rerun the executable.  */
12761 }
12762
12763 static void
12764 momentary_bkpt_check_status (bpstat bs)
12765 {
12766   /* Nothing.  The point of these breakpoints is causing a stop.  */
12767 }
12768
12769 static enum print_stop_action
12770 momentary_bkpt_print_it (bpstat bs)
12771 {
12772   return PRINT_UNKNOWN;
12773 }
12774
12775 static void
12776 momentary_bkpt_print_mention (struct breakpoint *b)
12777 {
12778   /* Nothing to mention.  These breakpoints are internal.  */
12779 }
12780
12781 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12782
12783    It gets cleared already on the removal of the first one of such placed
12784    breakpoints.  This is OK as they get all removed altogether.  */
12785
12786 longjmp_breakpoint::~longjmp_breakpoint ()
12787 {
12788   thread_info *tp = find_thread_global_id (this->thread);
12789
12790   if (tp != NULL)
12791     tp->initiating_frame = null_frame_id;
12792 }
12793
12794 /* Specific methods for probe breakpoints.  */
12795
12796 static int
12797 bkpt_probe_insert_location (struct bp_location *bl)
12798 {
12799   int v = bkpt_insert_location (bl);
12800
12801   if (v == 0)
12802     {
12803       /* The insertion was successful, now let's set the probe's semaphore
12804          if needed.  */
12805       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12806     }
12807
12808   return v;
12809 }
12810
12811 static int
12812 bkpt_probe_remove_location (struct bp_location *bl,
12813                             enum remove_bp_reason reason)
12814 {
12815   /* Let's clear the semaphore before removing the location.  */
12816   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12817
12818   return bkpt_remove_location (bl, reason);
12819 }
12820
12821 static void
12822 bkpt_probe_create_sals_from_location (struct event_location *location,
12823                                       struct linespec_result *canonical,
12824                                       enum bptype type_wanted)
12825 {
12826   struct linespec_sals lsal;
12827
12828   lsal.sals = parse_probes (location, NULL, canonical);
12829   lsal.canonical
12830     = xstrdup (event_location_to_string (canonical->location.get ()));
12831   canonical->lsals.push_back (std::move (lsal));
12832 }
12833
12834 static std::vector<symtab_and_line>
12835 bkpt_probe_decode_location (struct breakpoint *b,
12836                             struct event_location *location,
12837                             struct program_space *search_pspace)
12838 {
12839   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12840   if (sals.empty ())
12841     error (_("probe not found"));
12842   return sals;
12843 }
12844
12845 /* The breakpoint_ops structure to be used in tracepoints.  */
12846
12847 static void
12848 tracepoint_re_set (struct breakpoint *b)
12849 {
12850   breakpoint_re_set_default (b);
12851 }
12852
12853 static int
12854 tracepoint_breakpoint_hit (const struct bp_location *bl,
12855                            const address_space *aspace, CORE_ADDR bp_addr,
12856                            const struct target_waitstatus *ws)
12857 {
12858   /* By definition, the inferior does not report stops at
12859      tracepoints.  */
12860   return 0;
12861 }
12862
12863 static void
12864 tracepoint_print_one_detail (const struct breakpoint *self,
12865                              struct ui_out *uiout)
12866 {
12867   struct tracepoint *tp = (struct tracepoint *) self;
12868   if (!tp->static_trace_marker_id.empty ())
12869     {
12870       gdb_assert (self->type == bp_static_tracepoint);
12871
12872       uiout->message ("\tmarker id is %pF\n",
12873                       string_field ("static-tracepoint-marker-string-id",
12874                                     tp->static_trace_marker_id.c_str ()));
12875     }
12876 }
12877
12878 static void
12879 tracepoint_print_mention (struct breakpoint *b)
12880 {
12881   if (current_uiout->is_mi_like_p ())
12882     return;
12883
12884   switch (b->type)
12885     {
12886     case bp_tracepoint:
12887       printf_filtered (_("Tracepoint"));
12888       printf_filtered (_(" %d"), b->number);
12889       break;
12890     case bp_fast_tracepoint:
12891       printf_filtered (_("Fast tracepoint"));
12892       printf_filtered (_(" %d"), b->number);
12893       break;
12894     case bp_static_tracepoint:
12895       printf_filtered (_("Static tracepoint"));
12896       printf_filtered (_(" %d"), b->number);
12897       break;
12898     default:
12899       internal_error (__FILE__, __LINE__,
12900                       _("unhandled tracepoint type %d"), (int) b->type);
12901     }
12902
12903   say_where (b);
12904 }
12905
12906 static void
12907 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12908 {
12909   struct tracepoint *tp = (struct tracepoint *) self;
12910
12911   if (self->type == bp_fast_tracepoint)
12912     fprintf_unfiltered (fp, "ftrace");
12913   else if (self->type == bp_static_tracepoint)
12914     fprintf_unfiltered (fp, "strace");
12915   else if (self->type == bp_tracepoint)
12916     fprintf_unfiltered (fp, "trace");
12917   else
12918     internal_error (__FILE__, __LINE__,
12919                     _("unhandled tracepoint type %d"), (int) self->type);
12920
12921   fprintf_unfiltered (fp, " %s",
12922                       event_location_to_string (self->location.get ()));
12923   print_recreate_thread (self, fp);
12924
12925   if (tp->pass_count)
12926     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12927 }
12928
12929 static void
12930 tracepoint_create_sals_from_location (struct event_location *location,
12931                                       struct linespec_result *canonical,
12932                                       enum bptype type_wanted)
12933 {
12934   create_sals_from_location_default (location, canonical, type_wanted);
12935 }
12936
12937 static void
12938 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12939                                    struct linespec_result *canonical,
12940                                    gdb::unique_xmalloc_ptr<char> cond_string,
12941                                    gdb::unique_xmalloc_ptr<char> extra_string,
12942                                    enum bptype type_wanted,
12943                                    enum bpdisp disposition,
12944                                    int thread,
12945                                    int task, int ignore_count,
12946                                    const struct breakpoint_ops *ops,
12947                                    int from_tty, int enabled,
12948                                    int internal, unsigned flags)
12949 {
12950   create_breakpoints_sal_default (gdbarch, canonical,
12951                                   std::move (cond_string),
12952                                   std::move (extra_string),
12953                                   type_wanted,
12954                                   disposition, thread, task,
12955                                   ignore_count, ops, from_tty,
12956                                   enabled, internal, flags);
12957 }
12958
12959 static std::vector<symtab_and_line>
12960 tracepoint_decode_location (struct breakpoint *b,
12961                             struct event_location *location,
12962                             struct program_space *search_pspace)
12963 {
12964   return decode_location_default (b, location, search_pspace);
12965 }
12966
12967 struct breakpoint_ops tracepoint_breakpoint_ops;
12968
12969 /* Virtual table for tracepoints on static probes.  */
12970
12971 static void
12972 tracepoint_probe_create_sals_from_location
12973   (struct event_location *location,
12974    struct linespec_result *canonical,
12975    enum bptype type_wanted)
12976 {
12977   /* We use the same method for breakpoint on probes.  */
12978   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12979 }
12980
12981 static std::vector<symtab_and_line>
12982 tracepoint_probe_decode_location (struct breakpoint *b,
12983                                   struct event_location *location,
12984                                   struct program_space *search_pspace)
12985 {
12986   /* We use the same method for breakpoint on probes.  */
12987   return bkpt_probe_decode_location (b, location, search_pspace);
12988 }
12989
12990 /* Dprintf breakpoint_ops methods.  */
12991
12992 static void
12993 dprintf_re_set (struct breakpoint *b)
12994 {
12995   breakpoint_re_set_default (b);
12996
12997   /* extra_string should never be non-NULL for dprintf.  */
12998   gdb_assert (b->extra_string != NULL);
12999
13000   /* 1 - connect to target 1, that can run breakpoint commands.
13001      2 - create a dprintf, which resolves fine.
13002      3 - disconnect from target 1
13003      4 - connect to target 2, that can NOT run breakpoint commands.
13004
13005      After steps #3/#4, you'll want the dprintf command list to
13006      be updated, because target 1 and 2 may well return different
13007      answers for target_can_run_breakpoint_commands().
13008      Given absence of finer grained resetting, we get to do
13009      it all the time.  */
13010   if (b->extra_string != NULL)
13011     update_dprintf_command_list (b);
13012 }
13013
13014 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13015
13016 static void
13017 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13018 {
13019   fprintf_unfiltered (fp, "dprintf %s,%s",
13020                       event_location_to_string (tp->location.get ()),
13021                       tp->extra_string);
13022   print_recreate_thread (tp, fp);
13023 }
13024
13025 /* Implement the "after_condition_true" breakpoint_ops method for
13026    dprintf.
13027
13028    dprintf's are implemented with regular commands in their command
13029    list, but we run the commands here instead of before presenting the
13030    stop to the user, as dprintf's don't actually cause a stop.  This
13031    also makes it so that the commands of multiple dprintfs at the same
13032    address are all handled.  */
13033
13034 static void
13035 dprintf_after_condition_true (struct bpstats *bs)
13036 {
13037   struct bpstats tmp_bs;
13038   struct bpstats *tmp_bs_p = &tmp_bs;
13039
13040   /* dprintf's never cause a stop.  This wasn't set in the
13041      check_status hook instead because that would make the dprintf's
13042      condition not be evaluated.  */
13043   bs->stop = 0;
13044
13045   /* Run the command list here.  Take ownership of it instead of
13046      copying.  We never want these commands to run later in
13047      bpstat_do_actions, if a breakpoint that causes a stop happens to
13048      be set at same address as this dprintf, or even if running the
13049      commands here throws.  */
13050   tmp_bs.commands = bs->commands;
13051   bs->commands = NULL;
13052
13053   bpstat_do_actions_1 (&tmp_bs_p);
13054
13055   /* 'tmp_bs.commands' will usually be NULL by now, but
13056      bpstat_do_actions_1 may return early without processing the whole
13057      list.  */
13058 }
13059
13060 /* The breakpoint_ops structure to be used on static tracepoints with
13061    markers (`-m').  */
13062
13063 static void
13064 strace_marker_create_sals_from_location (struct event_location *location,
13065                                          struct linespec_result *canonical,
13066                                          enum bptype type_wanted)
13067 {
13068   struct linespec_sals lsal;
13069   const char *arg_start, *arg;
13070
13071   arg = arg_start = get_linespec_location (location)->spec_string;
13072   lsal.sals = decode_static_tracepoint_spec (&arg);
13073
13074   std::string str (arg_start, arg - arg_start);
13075   const char *ptr = str.c_str ();
13076   canonical->location
13077     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13078
13079   lsal.canonical
13080     = xstrdup (event_location_to_string (canonical->location.get ()));
13081   canonical->lsals.push_back (std::move (lsal));
13082 }
13083
13084 static void
13085 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13086                                       struct linespec_result *canonical,
13087                                       gdb::unique_xmalloc_ptr<char> cond_string,
13088                                       gdb::unique_xmalloc_ptr<char> extra_string,
13089                                       enum bptype type_wanted,
13090                                       enum bpdisp disposition,
13091                                       int thread,
13092                                       int task, int ignore_count,
13093                                       const struct breakpoint_ops *ops,
13094                                       int from_tty, int enabled,
13095                                       int internal, unsigned flags)
13096 {
13097   const linespec_sals &lsal = canonical->lsals[0];
13098
13099   /* If the user is creating a static tracepoint by marker id
13100      (strace -m MARKER_ID), then store the sals index, so that
13101      breakpoint_re_set can try to match up which of the newly
13102      found markers corresponds to this one, and, don't try to
13103      expand multiple locations for each sal, given than SALS
13104      already should contain all sals for MARKER_ID.  */
13105
13106   for (size_t i = 0; i < lsal.sals.size (); i++)
13107     {
13108       event_location_up location
13109         = copy_event_location (canonical->location.get ());
13110
13111       std::unique_ptr<tracepoint> tp (new tracepoint ());
13112       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13113                            std::move (location), NULL,
13114                            std::move (cond_string),
13115                            std::move (extra_string),
13116                            type_wanted, disposition,
13117                            thread, task, ignore_count, ops,
13118                            from_tty, enabled, internal, flags,
13119                            canonical->special_display);
13120       /* Given that its possible to have multiple markers with
13121          the same string id, if the user is creating a static
13122          tracepoint by marker id ("strace -m MARKER_ID"), then
13123          store the sals index, so that breakpoint_re_set can
13124          try to match up which of the newly found markers
13125          corresponds to this one  */
13126       tp->static_trace_marker_id_idx = i;
13127
13128       install_breakpoint (internal, std::move (tp), 0);
13129     }
13130 }
13131
13132 static std::vector<symtab_and_line>
13133 strace_marker_decode_location (struct breakpoint *b,
13134                                struct event_location *location,
13135                                struct program_space *search_pspace)
13136 {
13137   struct tracepoint *tp = (struct tracepoint *) b;
13138   const char *s = get_linespec_location (location)->spec_string;
13139
13140   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13141   if (sals.size () > tp->static_trace_marker_id_idx)
13142     {
13143       sals[0] = sals[tp->static_trace_marker_id_idx];
13144       sals.resize (1);
13145       return sals;
13146     }
13147   else
13148     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13149 }
13150
13151 static struct breakpoint_ops strace_marker_breakpoint_ops;
13152
13153 static int
13154 strace_marker_p (struct breakpoint *b)
13155 {
13156   return b->ops == &strace_marker_breakpoint_ops;
13157 }
13158
13159 /* Delete a breakpoint and clean up all traces of it in the data
13160    structures.  */
13161
13162 void
13163 delete_breakpoint (struct breakpoint *bpt)
13164 {
13165   gdb_assert (bpt != NULL);
13166
13167   /* Has this bp already been deleted?  This can happen because
13168      multiple lists can hold pointers to bp's.  bpstat lists are
13169      especial culprits.
13170
13171      One example of this happening is a watchpoint's scope bp.  When
13172      the scope bp triggers, we notice that the watchpoint is out of
13173      scope, and delete it.  We also delete its scope bp.  But the
13174      scope bp is marked "auto-deleting", and is already on a bpstat.
13175      That bpstat is then checked for auto-deleting bp's, which are
13176      deleted.
13177
13178      A real solution to this problem might involve reference counts in
13179      bp's, and/or giving them pointers back to their referencing
13180      bpstat's, and teaching delete_breakpoint to only free a bp's
13181      storage when no more references were extent.  A cheaper bandaid
13182      was chosen.  */
13183   if (bpt->type == bp_none)
13184     return;
13185
13186   /* At least avoid this stale reference until the reference counting
13187      of breakpoints gets resolved.  */
13188   if (bpt->related_breakpoint != bpt)
13189     {
13190       struct breakpoint *related;
13191       struct watchpoint *w;
13192
13193       if (bpt->type == bp_watchpoint_scope)
13194         w = (struct watchpoint *) bpt->related_breakpoint;
13195       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13196         w = (struct watchpoint *) bpt;
13197       else
13198         w = NULL;
13199       if (w != NULL)
13200         watchpoint_del_at_next_stop (w);
13201
13202       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13203       for (related = bpt; related->related_breakpoint != bpt;
13204            related = related->related_breakpoint);
13205       related->related_breakpoint = bpt->related_breakpoint;
13206       bpt->related_breakpoint = bpt;
13207     }
13208
13209   /* watch_command_1 creates a watchpoint but only sets its number if
13210      update_watchpoint succeeds in creating its bp_locations.  If there's
13211      a problem in that process, we'll be asked to delete the half-created
13212      watchpoint.  In that case, don't announce the deletion.  */
13213   if (bpt->number)
13214     gdb::observers::breakpoint_deleted.notify (bpt);
13215
13216   if (breakpoint_chain == bpt)
13217     breakpoint_chain = bpt->next;
13218
13219   for (breakpoint *b : all_breakpoints ())
13220     if (b->next == bpt)
13221       {
13222         b->next = bpt->next;
13223         break;
13224       }
13225
13226   /* Be sure no bpstat's are pointing at the breakpoint after it's
13227      been freed.  */
13228   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13229      in all threads for now.  Note that we cannot just remove bpstats
13230      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13231      commands are associated with the bpstat; if we remove it here,
13232      then the later call to bpstat_do_actions (&stop_bpstat); in
13233      event-top.c won't do anything, and temporary breakpoints with
13234      commands won't work.  */
13235
13236   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13237
13238   /* Now that breakpoint is removed from breakpoint list, update the
13239      global location list.  This will remove locations that used to
13240      belong to this breakpoint.  Do this before freeing the breakpoint
13241      itself, since remove_breakpoint looks at location's owner.  It
13242      might be better design to have location completely
13243      self-contained, but it's not the case now.  */
13244   update_global_location_list (UGLL_DONT_INSERT);
13245
13246   /* On the chance that someone will soon try again to delete this
13247      same bp, we mark it as deleted before freeing its storage.  */
13248   bpt->type = bp_none;
13249   delete bpt;
13250 }
13251
13252 /* Iterator function to call a user-provided callback function once
13253    for each of B and its related breakpoints.  */
13254
13255 static void
13256 iterate_over_related_breakpoints (struct breakpoint *b,
13257                                   gdb::function_view<void (breakpoint *)> function)
13258 {
13259   struct breakpoint *related;
13260
13261   related = b;
13262   do
13263     {
13264       struct breakpoint *next;
13265
13266       /* FUNCTION may delete RELATED.  */
13267       next = related->related_breakpoint;
13268
13269       if (next == related)
13270         {
13271           /* RELATED is the last ring entry.  */
13272           function (related);
13273
13274           /* FUNCTION may have deleted it, so we'd never reach back to
13275              B.  There's nothing left to do anyway, so just break
13276              out.  */
13277           break;
13278         }
13279       else
13280         function (related);
13281
13282       related = next;
13283     }
13284   while (related != b);
13285 }
13286
13287 static void
13288 delete_command (const char *arg, int from_tty)
13289 {
13290   dont_repeat ();
13291
13292   if (arg == 0)
13293     {
13294       int breaks_to_delete = 0;
13295
13296       /* Delete all breakpoints if no argument.  Do not delete
13297          internal breakpoints, these have to be deleted with an
13298          explicit breakpoint number argument.  */
13299       for (breakpoint *b : all_breakpoints ())
13300         if (user_breakpoint_p (b))
13301           {
13302             breaks_to_delete = 1;
13303             break;
13304           }
13305
13306       /* Ask user only if there are some breakpoints to delete.  */
13307       if (!from_tty
13308           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13309         for (breakpoint *b : all_breakpoints_safe ())
13310           if (user_breakpoint_p (b))
13311             delete_breakpoint (b);
13312     }
13313   else
13314     map_breakpoint_numbers
13315       (arg, [&] (breakpoint *br)
13316        {
13317          iterate_over_related_breakpoints (br, delete_breakpoint);
13318        });
13319 }
13320
13321 /* Return true if all locations of B bound to PSPACE are pending.  If
13322    PSPACE is NULL, all locations of all program spaces are
13323    considered.  */
13324
13325 static int
13326 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13327 {
13328   for (bp_location *loc : b->locations ())
13329     if ((pspace == NULL
13330          || loc->pspace == pspace)
13331         && !loc->shlib_disabled
13332         && !loc->pspace->executing_startup)
13333       return 0;
13334   return 1;
13335 }
13336
13337 /* Subroutine of update_breakpoint_locations to simplify it.
13338    Return non-zero if multiple fns in list LOC have the same name.
13339    Null names are ignored.  */
13340
13341 static int
13342 ambiguous_names_p (struct bp_location *loc)
13343 {
13344   struct bp_location *l;
13345   htab_up htab (htab_create_alloc (13, htab_hash_string, htab_eq_string, NULL,
13346                                    xcalloc, xfree));
13347
13348   for (l = loc; l != NULL; l = l->next)
13349     {
13350       const char **slot;
13351       const char *name = l->function_name;
13352
13353       /* Allow for some names to be NULL, ignore them.  */
13354       if (name == NULL)
13355         continue;
13356
13357       slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
13358                                              INSERT);
13359       /* NOTE: We can assume slot != NULL here because xcalloc never
13360          returns NULL.  */
13361       if (*slot != NULL)
13362         return 1;
13363       *slot = name;
13364     }
13365
13366   return 0;
13367 }
13368
13369 /* When symbols change, it probably means the sources changed as well,
13370    and it might mean the static tracepoint markers are no longer at
13371    the same address or line numbers they used to be at last we
13372    checked.  Losing your static tracepoints whenever you rebuild is
13373    undesirable.  This function tries to resync/rematch gdb static
13374    tracepoints with the markers on the target, for static tracepoints
13375    that have not been set by marker id.  Static tracepoint that have
13376    been set by marker id are reset by marker id in breakpoint_re_set.
13377    The heuristic is:
13378
13379    1) For a tracepoint set at a specific address, look for a marker at
13380    the old PC.  If one is found there, assume to be the same marker.
13381    If the name / string id of the marker found is different from the
13382    previous known name, assume that means the user renamed the marker
13383    in the sources, and output a warning.
13384
13385    2) For a tracepoint set at a given line number, look for a marker
13386    at the new address of the old line number.  If one is found there,
13387    assume to be the same marker.  If the name / string id of the
13388    marker found is different from the previous known name, assume that
13389    means the user renamed the marker in the sources, and output a
13390    warning.
13391
13392    3) If a marker is no longer found at the same address or line, it
13393    may mean the marker no longer exists.  But it may also just mean
13394    the code changed a bit.  Maybe the user added a few lines of code
13395    that made the marker move up or down (in line number terms).  Ask
13396    the target for info about the marker with the string id as we knew
13397    it.  If found, update line number and address in the matching
13398    static tracepoint.  This will get confused if there's more than one
13399    marker with the same ID (possible in UST, although unadvised
13400    precisely because it confuses tools).  */
13401
13402 static struct symtab_and_line
13403 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13404 {
13405   struct tracepoint *tp = (struct tracepoint *) b;
13406   struct static_tracepoint_marker marker;
13407   CORE_ADDR pc;
13408
13409   pc = sal.pc;
13410   if (sal.line)
13411     find_line_pc (sal.symtab, sal.line, &pc);
13412
13413   if (target_static_tracepoint_marker_at (pc, &marker))
13414     {
13415       if (tp->static_trace_marker_id != marker.str_id)
13416         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13417                  b->number, tp->static_trace_marker_id.c_str (),
13418                  marker.str_id.c_str ());
13419
13420       tp->static_trace_marker_id = std::move (marker.str_id);
13421
13422       return sal;
13423     }
13424
13425   /* Old marker wasn't found on target at lineno.  Try looking it up
13426      by string ID.  */
13427   if (!sal.explicit_pc
13428       && sal.line != 0
13429       && sal.symtab != NULL
13430       && !tp->static_trace_marker_id.empty ())
13431     {
13432       std::vector<static_tracepoint_marker> markers
13433         = target_static_tracepoint_markers_by_strid
13434             (tp->static_trace_marker_id.c_str ());
13435
13436       if (!markers.empty ())
13437         {
13438           struct symbol *sym;
13439           struct static_tracepoint_marker *tpmarker;
13440           struct ui_out *uiout = current_uiout;
13441           struct explicit_location explicit_loc;
13442
13443           tpmarker = &markers[0];
13444
13445           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13446
13447           warning (_("marker for static tracepoint %d (%s) not "
13448                      "found at previous line number"),
13449                    b->number, tp->static_trace_marker_id.c_str ());
13450
13451           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13452           sym = find_pc_sect_function (tpmarker->address, NULL);
13453           uiout->text ("Now in ");
13454           if (sym)
13455             {
13456               uiout->field_string ("func", sym->print_name (),
13457                                    function_name_style.style ());
13458               uiout->text (" at ");
13459             }
13460           uiout->field_string ("file",
13461                                symtab_to_filename_for_display (sal2.symtab),
13462                                file_name_style.style ());
13463           uiout->text (":");
13464
13465           if (uiout->is_mi_like_p ())
13466             {
13467               const char *fullname = symtab_to_fullname (sal2.symtab);
13468
13469               uiout->field_string ("fullname", fullname);
13470             }
13471
13472           uiout->field_signed ("line", sal2.line);
13473           uiout->text ("\n");
13474
13475           b->loc->line_number = sal2.line;
13476           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13477
13478           b->location.reset (NULL);
13479           initialize_explicit_location (&explicit_loc);
13480           explicit_loc.source_filename
13481             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13482           explicit_loc.line_offset.offset = b->loc->line_number;
13483           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13484           b->location = new_explicit_location (&explicit_loc);
13485
13486           /* Might be nice to check if function changed, and warn if
13487              so.  */
13488         }
13489     }
13490   return sal;
13491 }
13492
13493 /* Returns 1 iff locations A and B are sufficiently same that
13494    we don't need to report breakpoint as changed.  */
13495
13496 static int
13497 locations_are_equal (struct bp_location *a, struct bp_location *b)
13498 {
13499   while (a && b)
13500     {
13501       if (a->address != b->address)
13502         return 0;
13503
13504       if (a->shlib_disabled != b->shlib_disabled)
13505         return 0;
13506
13507       if (a->enabled != b->enabled)
13508         return 0;
13509
13510       if (a->disabled_by_cond != b->disabled_by_cond)
13511         return 0;
13512
13513       a = a->next;
13514       b = b->next;
13515     }
13516
13517   if ((a == NULL) != (b == NULL))
13518     return 0;
13519
13520   return 1;
13521 }
13522
13523 /* Split all locations of B that are bound to PSPACE out of B's
13524    location list to a separate list and return that list's head.  If
13525    PSPACE is NULL, hoist out all locations of B.  */
13526
13527 static struct bp_location *
13528 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13529 {
13530   struct bp_location head;
13531   struct bp_location *i = b->loc;
13532   struct bp_location **i_link = &b->loc;
13533   struct bp_location *hoisted = &head;
13534
13535   if (pspace == NULL)
13536     {
13537       i = b->loc;
13538       b->loc = NULL;
13539       return i;
13540     }
13541
13542   head.next = NULL;
13543
13544   while (i != NULL)
13545     {
13546       if (i->pspace == pspace)
13547         {
13548           *i_link = i->next;
13549           i->next = NULL;
13550           hoisted->next = i;
13551           hoisted = i;
13552         }
13553       else
13554         i_link = &i->next;
13555       i = *i_link;
13556     }
13557
13558   return head.next;
13559 }
13560
13561 /* Create new breakpoint locations for B (a hardware or software
13562    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13563    zero, then B is a ranged breakpoint.  Only recreates locations for
13564    FILTER_PSPACE.  Locations of other program spaces are left
13565    untouched.  */
13566
13567 void
13568 update_breakpoint_locations (struct breakpoint *b,
13569                              struct program_space *filter_pspace,
13570                              gdb::array_view<const symtab_and_line> sals,
13571                              gdb::array_view<const symtab_and_line> sals_end)
13572 {
13573   struct bp_location *existing_locations;
13574
13575   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13576     {
13577       /* Ranged breakpoints have only one start location and one end
13578          location.  */
13579       b->enable_state = bp_disabled;
13580       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13581                            "multiple locations found\n"),
13582                          b->number);
13583       return;
13584     }
13585
13586   /* If there's no new locations, and all existing locations are
13587      pending, don't do anything.  This optimizes the common case where
13588      all locations are in the same shared library, that was unloaded.
13589      We'd like to retain the location, so that when the library is
13590      loaded again, we don't loose the enabled/disabled status of the
13591      individual locations.  */
13592   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13593     return;
13594
13595   existing_locations = hoist_existing_locations (b, filter_pspace);
13596
13597   for (const auto &sal : sals)
13598     {
13599       struct bp_location *new_loc;
13600
13601       switch_to_program_space_and_thread (sal.pspace);
13602
13603       new_loc = add_location_to_breakpoint (b, &sal);
13604
13605       /* Reparse conditions, they might contain references to the
13606          old symtab.  */
13607       if (b->cond_string != NULL)
13608         {
13609           const char *s;
13610
13611           s = b->cond_string;
13612           try
13613             {
13614               new_loc->cond = parse_exp_1 (&s, sal.pc,
13615                                            block_for_pc (sal.pc),
13616                                            0);
13617             }
13618           catch (const gdb_exception_error &e)
13619             {
13620               new_loc->disabled_by_cond = true;
13621             }
13622         }
13623
13624       if (!sals_end.empty ())
13625         {
13626           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13627
13628           new_loc->length = end - sals[0].pc + 1;
13629         }
13630     }
13631
13632   /* If possible, carry over 'disable' status from existing
13633      breakpoints.  */
13634   {
13635     struct bp_location *e = existing_locations;
13636     /* If there are multiple breakpoints with the same function name,
13637        e.g. for inline functions, comparing function names won't work.
13638        Instead compare pc addresses; this is just a heuristic as things
13639        may have moved, but in practice it gives the correct answer
13640        often enough until a better solution is found.  */
13641     int have_ambiguous_names = ambiguous_names_p (b->loc);
13642
13643     for (; e; e = e->next)
13644       {
13645         if ((!e->enabled || e->disabled_by_cond) && e->function_name)
13646           {
13647             if (have_ambiguous_names)
13648               {
13649                 for (bp_location *l : b->locations ())
13650                   {
13651                     /* Ignore software vs hardware location type at
13652                        this point, because with "set breakpoint
13653                        auto-hw", after a re-set, locations that were
13654                        hardware can end up as software, or vice versa.
13655                        As mentioned above, this is an heuristic and in
13656                        practice should give the correct answer often
13657                        enough.  */
13658                     if (breakpoint_locations_match (e, l, true))
13659                       {
13660                         l->enabled = e->enabled;
13661                         l->disabled_by_cond = e->disabled_by_cond;
13662                         break;
13663                       }
13664                   }
13665               }
13666             else
13667               {
13668                 for (bp_location *l : b->locations ())
13669                   if (l->function_name
13670                       && strcmp (e->function_name, l->function_name) == 0)
13671                     {
13672                       l->enabled = e->enabled;
13673                       l->disabled_by_cond = e->disabled_by_cond;
13674                       break;
13675                     }
13676               }
13677           }
13678       }
13679   }
13680
13681   if (!locations_are_equal (existing_locations, b->loc))
13682     gdb::observers::breakpoint_modified.notify (b);
13683 }
13684
13685 /* Find the SaL locations corresponding to the given LOCATION.
13686    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13687
13688 static std::vector<symtab_and_line>
13689 location_to_sals (struct breakpoint *b, struct event_location *location,
13690                   struct program_space *search_pspace, int *found)
13691 {
13692   struct gdb_exception exception;
13693
13694   gdb_assert (b->ops != NULL);
13695
13696   std::vector<symtab_and_line> sals;
13697
13698   try
13699     {
13700       sals = b->ops->decode_location (b, location, search_pspace);
13701     }
13702   catch (gdb_exception_error &e)
13703     {
13704       int not_found_and_ok = 0;
13705
13706       /* For pending breakpoints, it's expected that parsing will
13707          fail until the right shared library is loaded.  User has
13708          already told to create pending breakpoints and don't need
13709          extra messages.  If breakpoint is in bp_shlib_disabled
13710          state, then user already saw the message about that
13711          breakpoint being disabled, and don't want to see more
13712          errors.  */
13713       if (e.error == NOT_FOUND_ERROR
13714           && (b->condition_not_parsed
13715               || (b->loc != NULL
13716                   && search_pspace != NULL
13717                   && b->loc->pspace != search_pspace)
13718               || (b->loc && b->loc->shlib_disabled)
13719               || (b->loc && b->loc->pspace->executing_startup)
13720               || b->enable_state == bp_disabled))
13721         not_found_and_ok = 1;
13722
13723       if (!not_found_and_ok)
13724         {
13725           /* We surely don't want to warn about the same breakpoint
13726              10 times.  One solution, implemented here, is disable
13727              the breakpoint on error.  Another solution would be to
13728              have separate 'warning emitted' flag.  Since this
13729              happens only when a binary has changed, I don't know
13730              which approach is better.  */
13731           b->enable_state = bp_disabled;
13732           throw;
13733         }
13734
13735       exception = std::move (e);
13736     }
13737
13738   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13739     {
13740       for (auto &sal : sals)
13741         resolve_sal_pc (&sal);
13742       if (b->condition_not_parsed && b->extra_string != NULL)
13743         {
13744           char *cond_string, *extra_string;
13745           int thread, task;
13746
13747           find_condition_and_thread_for_sals (sals, b->extra_string,
13748                                               &cond_string, &thread,
13749                                               &task, &extra_string);
13750           gdb_assert (b->cond_string == NULL);
13751           if (cond_string)
13752             b->cond_string = cond_string;
13753           b->thread = thread;
13754           b->task = task;
13755           if (extra_string)
13756             {
13757               xfree (b->extra_string);
13758               b->extra_string = extra_string;
13759             }
13760           b->condition_not_parsed = 0;
13761         }
13762
13763       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13764         sals[0] = update_static_tracepoint (b, sals[0]);
13765
13766       *found = 1;
13767     }
13768   else
13769     *found = 0;
13770
13771   return sals;
13772 }
13773
13774 /* The default re_set method, for typical hardware or software
13775    breakpoints.  Reevaluate the breakpoint and recreate its
13776    locations.  */
13777
13778 static void
13779 breakpoint_re_set_default (struct breakpoint *b)
13780 {
13781   struct program_space *filter_pspace = current_program_space;
13782   std::vector<symtab_and_line> expanded, expanded_end;
13783
13784   int found;
13785   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13786                                                         filter_pspace, &found);
13787   if (found)
13788     expanded = std::move (sals);
13789
13790   if (b->location_range_end != NULL)
13791     {
13792       std::vector<symtab_and_line> sals_end
13793         = location_to_sals (b, b->location_range_end.get (),
13794                             filter_pspace, &found);
13795       if (found)
13796         expanded_end = std::move (sals_end);
13797     }
13798
13799   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13800 }
13801
13802 /* Default method for creating SALs from an address string.  It basically
13803    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13804
13805 static void
13806 create_sals_from_location_default (struct event_location *location,
13807                                    struct linespec_result *canonical,
13808                                    enum bptype type_wanted)
13809 {
13810   parse_breakpoint_sals (location, canonical);
13811 }
13812
13813 /* Call create_breakpoints_sal for the given arguments.  This is the default
13814    function for the `create_breakpoints_sal' method of
13815    breakpoint_ops.  */
13816
13817 static void
13818 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13819                                 struct linespec_result *canonical,
13820                                 gdb::unique_xmalloc_ptr<char> cond_string,
13821                                 gdb::unique_xmalloc_ptr<char> extra_string,
13822                                 enum bptype type_wanted,
13823                                 enum bpdisp disposition,
13824                                 int thread,
13825                                 int task, int ignore_count,
13826                                 const struct breakpoint_ops *ops,
13827                                 int from_tty, int enabled,
13828                                 int internal, unsigned flags)
13829 {
13830   create_breakpoints_sal (gdbarch, canonical,
13831                           std::move (cond_string),
13832                           std::move (extra_string),
13833                           type_wanted, disposition,
13834                           thread, task, ignore_count, ops, from_tty,
13835                           enabled, internal, flags);
13836 }
13837
13838 /* Decode the line represented by S by calling decode_line_full.  This is the
13839    default function for the `decode_location' method of breakpoint_ops.  */
13840
13841 static std::vector<symtab_and_line>
13842 decode_location_default (struct breakpoint *b,
13843                          struct event_location *location,
13844                          struct program_space *search_pspace)
13845 {
13846   struct linespec_result canonical;
13847
13848   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13849                     NULL, 0, &canonical, multiple_symbols_all,
13850                     b->filter.get ());
13851
13852   /* We should get 0 or 1 resulting SALs.  */
13853   gdb_assert (canonical.lsals.size () < 2);
13854
13855   if (!canonical.lsals.empty ())
13856     {
13857       const linespec_sals &lsal = canonical.lsals[0];
13858       return std::move (lsal.sals);
13859     }
13860   return {};
13861 }
13862
13863 /* Reset a breakpoint.  */
13864
13865 static void
13866 breakpoint_re_set_one (breakpoint *b)
13867 {
13868   input_radix = b->input_radix;
13869   set_language (b->language);
13870
13871   b->ops->re_set (b);
13872 }
13873
13874 /* Re-set breakpoint locations for the current program space.
13875    Locations bound to other program spaces are left untouched.  */
13876
13877 void
13878 breakpoint_re_set (void)
13879 {
13880   {
13881     scoped_restore_current_language save_language;
13882     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13883     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13884
13885     /* breakpoint_re_set_one sets the current_language to the language
13886        of the breakpoint it is resetting (see prepare_re_set_context)
13887        before re-evaluating the breakpoint's location.  This change can
13888        unfortunately get undone by accident if the language_mode is set
13889        to auto, and we either switch frames, or more likely in this context,
13890        we select the current frame.
13891
13892        We prevent this by temporarily turning the language_mode to
13893        language_mode_manual.  We restore it once all breakpoints
13894        have been reset.  */
13895     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13896     language_mode = language_mode_manual;
13897
13898     /* Note: we must not try to insert locations until after all
13899        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13900        breakpoint 1, we'd insert the locations of breakpoint 2, which
13901        hadn't been re-set yet, and thus may have stale locations.  */
13902
13903     for (breakpoint *b : all_breakpoints_safe ())
13904       {
13905         try
13906           {
13907             breakpoint_re_set_one (b);
13908           }
13909         catch (const gdb_exception &ex)
13910           {
13911             exception_fprintf (gdb_stderr, ex,
13912                                "Error in re-setting breakpoint %d: ",
13913                                b->number);
13914           }
13915       }
13916
13917     jit_breakpoint_re_set ();
13918   }
13919
13920   create_overlay_event_breakpoint ();
13921   create_longjmp_master_breakpoint ();
13922   create_std_terminate_master_breakpoint ();
13923   create_exception_master_breakpoint ();
13924
13925   /* Now we can insert.  */
13926   update_global_location_list (UGLL_MAY_INSERT);
13927 }
13928 \f
13929 /* Reset the thread number of this breakpoint:
13930
13931    - If the breakpoint is for all threads, leave it as-is.
13932    - Else, reset it to the current thread for inferior_ptid.  */
13933 void
13934 breakpoint_re_set_thread (struct breakpoint *b)
13935 {
13936   if (b->thread != -1)
13937     {
13938       b->thread = inferior_thread ()->global_num;
13939
13940       /* We're being called after following a fork.  The new fork is
13941          selected as current, and unless this was a vfork will have a
13942          different program space from the original thread.  Reset that
13943          as well.  */
13944       b->loc->pspace = current_program_space;
13945     }
13946 }
13947
13948 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13949    If from_tty is nonzero, it prints a message to that effect,
13950    which ends with a period (no newline).  */
13951
13952 void
13953 set_ignore_count (int bptnum, int count, int from_tty)
13954 {
13955   if (count < 0)
13956     count = 0;
13957
13958   for (breakpoint *b : all_breakpoints ())
13959     if (b->number == bptnum)
13960       {
13961         if (is_tracepoint (b))
13962           {
13963             if (from_tty && count != 0)
13964               printf_filtered (_("Ignore count ignored for tracepoint %d."),
13965                                bptnum);
13966             return;
13967           }
13968
13969         b->ignore_count = count;
13970         if (from_tty)
13971           {
13972             if (count == 0)
13973               printf_filtered (_("Will stop next time "
13974                                  "breakpoint %d is reached."),
13975                                bptnum);
13976             else if (count == 1)
13977               printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13978                                bptnum);
13979             else
13980               printf_filtered (_("Will ignore next %d "
13981                                  "crossings of breakpoint %d."),
13982                                count, bptnum);
13983           }
13984         gdb::observers::breakpoint_modified.notify (b);
13985         return;
13986       }
13987
13988   error (_("No breakpoint number %d."), bptnum);
13989 }
13990
13991 /* Command to set ignore-count of breakpoint N to COUNT.  */
13992
13993 static void
13994 ignore_command (const char *args, int from_tty)
13995 {
13996   const char *p = args;
13997   int num;
13998
13999   if (p == 0)
14000     error_no_arg (_("a breakpoint number"));
14001
14002   num = get_number (&p);
14003   if (num == 0)
14004     error (_("bad breakpoint number: '%s'"), args);
14005   if (*p == 0)
14006     error (_("Second argument (specified ignore-count) is missing."));
14007
14008   set_ignore_count (num,
14009                     longest_to_int (value_as_long (parse_and_eval (p))),
14010                     from_tty);
14011   if (from_tty)
14012     printf_filtered ("\n");
14013 }
14014 \f
14015
14016 /* Call FUNCTION on each of the breakpoints with numbers in the range
14017    defined by BP_NUM_RANGE (an inclusive range).  */
14018
14019 static void
14020 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14021                              gdb::function_view<void (breakpoint *)> function)
14022 {
14023   if (bp_num_range.first == 0)
14024     {
14025       warning (_("bad breakpoint number at or near '%d'"),
14026                bp_num_range.first);
14027     }
14028   else
14029     {
14030       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14031         {
14032           bool match = false;
14033
14034           for (breakpoint *b : all_breakpoints_safe ())
14035             if (b->number == i)
14036               {
14037                 match = true;
14038                 function (b);
14039                 break;
14040               }
14041           if (!match)
14042             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14043         }
14044     }
14045 }
14046
14047 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14048    ARGS.  */
14049
14050 static void
14051 map_breakpoint_numbers (const char *args,
14052                         gdb::function_view<void (breakpoint *)> function)
14053 {
14054   if (args == NULL || *args == '\0')
14055     error_no_arg (_("one or more breakpoint numbers"));
14056
14057   number_or_range_parser parser (args);
14058
14059   while (!parser.finished ())
14060     {
14061       int num = parser.get_number ();
14062       map_breakpoint_number_range (std::make_pair (num, num), function);
14063     }
14064 }
14065
14066 /* Return the breakpoint location structure corresponding to the
14067    BP_NUM and LOC_NUM values.  */
14068
14069 static struct bp_location *
14070 find_location_by_number (int bp_num, int loc_num)
14071 {
14072   breakpoint *b = get_breakpoint (bp_num);
14073
14074   if (!b || b->number != bp_num)
14075     error (_("Bad breakpoint number '%d'"), bp_num);
14076   
14077   if (loc_num == 0)
14078     error (_("Bad breakpoint location number '%d'"), loc_num);
14079
14080   int n = 0;
14081   for (bp_location *loc : b->locations ())
14082     if (++n == loc_num)
14083       return loc;
14084
14085   error (_("Bad breakpoint location number '%d'"), loc_num);
14086 }
14087
14088 /* Modes of operation for extract_bp_num.  */
14089 enum class extract_bp_kind
14090 {
14091   /* Extracting a breakpoint number.  */
14092   bp,
14093
14094   /* Extracting a location number.  */
14095   loc,
14096 };
14097
14098 /* Extract a breakpoint or location number (as determined by KIND)
14099    from the string starting at START.  TRAILER is a character which
14100    can be found after the number.  If you don't want a trailer, use
14101    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14102    string.  This always returns a positive integer.  */
14103
14104 static int
14105 extract_bp_num (extract_bp_kind kind, const char *start,
14106                 int trailer, const char **end_out = NULL)
14107 {
14108   const char *end = start;
14109   int num = get_number_trailer (&end, trailer);
14110   if (num < 0)
14111     error (kind == extract_bp_kind::bp
14112            ? _("Negative breakpoint number '%.*s'")
14113            : _("Negative breakpoint location number '%.*s'"),
14114            int (end - start), start);
14115   if (num == 0)
14116     error (kind == extract_bp_kind::bp
14117            ? _("Bad breakpoint number '%.*s'")
14118            : _("Bad breakpoint location number '%.*s'"),
14119            int (end - start), start);
14120
14121   if (end_out != NULL)
14122     *end_out = end;
14123   return num;
14124 }
14125
14126 /* Extract a breakpoint or location range (as determined by KIND) in
14127    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14128    representing the (inclusive) range.  The returned pair's elements
14129    are always positive integers.  */
14130
14131 static std::pair<int, int>
14132 extract_bp_or_bp_range (extract_bp_kind kind,
14133                         const std::string &arg,
14134                         std::string::size_type arg_offset)
14135 {
14136   std::pair<int, int> range;
14137   const char *bp_loc = &arg[arg_offset];
14138   std::string::size_type dash = arg.find ('-', arg_offset);
14139   if (dash != std::string::npos)
14140     {
14141       /* bp_loc is a range (x-z).  */
14142       if (arg.length () == dash + 1)
14143         error (kind == extract_bp_kind::bp
14144                ? _("Bad breakpoint number at or near: '%s'")
14145                : _("Bad breakpoint location number at or near: '%s'"),
14146                bp_loc);
14147
14148       const char *end;
14149       const char *start_first = bp_loc;
14150       const char *start_second = &arg[dash + 1];
14151       range.first = extract_bp_num (kind, start_first, '-');
14152       range.second = extract_bp_num (kind, start_second, '\0', &end);
14153
14154       if (range.first > range.second)
14155         error (kind == extract_bp_kind::bp
14156                ? _("Inverted breakpoint range at '%.*s'")
14157                : _("Inverted breakpoint location range at '%.*s'"),
14158                int (end - start_first), start_first);
14159     }
14160   else
14161     {
14162       /* bp_loc is a single value.  */
14163       range.first = extract_bp_num (kind, bp_loc, '\0');
14164       range.second = range.first;
14165     }
14166   return range;
14167 }
14168
14169 /* Extract the breakpoint/location range specified by ARG.  Returns
14170    the breakpoint range in BP_NUM_RANGE, and the location range in
14171    BP_LOC_RANGE.
14172
14173    ARG may be in any of the following forms:
14174
14175    x     where 'x' is a breakpoint number.
14176    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14177    x.y   where 'x' is a breakpoint number and 'y' a location number.
14178    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14179          location number range.
14180 */
14181
14182 static void
14183 extract_bp_number_and_location (const std::string &arg,
14184                                 std::pair<int, int> &bp_num_range,
14185                                 std::pair<int, int> &bp_loc_range)
14186 {
14187   std::string::size_type dot = arg.find ('.');
14188
14189   if (dot != std::string::npos)
14190     {
14191       /* Handle 'x.y' and 'x.y-z' cases.  */
14192
14193       if (arg.length () == dot + 1 || dot == 0)
14194         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14195
14196       bp_num_range.first
14197         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14198       bp_num_range.second = bp_num_range.first;
14199
14200       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14201                                              arg, dot + 1);
14202     }
14203   else
14204     {
14205       /* Handle x and x-y cases.  */
14206
14207       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14208       bp_loc_range.first = 0;
14209       bp_loc_range.second = 0;
14210     }
14211 }
14212
14213 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14214    specifies whether to enable or disable.  */
14215
14216 static void
14217 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14218 {
14219   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14220   if (loc != NULL)
14221     {
14222       if (loc->disabled_by_cond && enable)
14223         error (_("Breakpoint %d's condition is invalid at location %d, "
14224                  "cannot enable."), bp_num, loc_num);
14225
14226       if (loc->enabled != enable)
14227         {
14228           loc->enabled = enable;
14229           mark_breakpoint_location_modified (loc);
14230         }
14231       if (target_supports_enable_disable_tracepoint ()
14232           && current_trace_status ()->running && loc->owner
14233           && is_tracepoint (loc->owner))
14234         target_disable_tracepoint (loc);
14235     }
14236   update_global_location_list (UGLL_DONT_INSERT);
14237
14238   gdb::observers::breakpoint_modified.notify (loc->owner);
14239 }
14240
14241 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14242    number of the breakpoint, and BP_LOC_RANGE specifies the
14243    (inclusive) range of location numbers of that breakpoint to
14244    enable/disable.  ENABLE specifies whether to enable or disable the
14245    location.  */
14246
14247 static void
14248 enable_disable_breakpoint_location_range (int bp_num,
14249                                           std::pair<int, int> &bp_loc_range,
14250                                           bool enable)
14251 {
14252   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14253     enable_disable_bp_num_loc (bp_num, i, enable);
14254 }
14255
14256 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14257    If from_tty is nonzero, it prints a message to that effect,
14258    which ends with a period (no newline).  */
14259
14260 void
14261 disable_breakpoint (struct breakpoint *bpt)
14262 {
14263   /* Never disable a watchpoint scope breakpoint; we want to
14264      hit them when we leave scope so we can delete both the
14265      watchpoint and its scope breakpoint at that time.  */
14266   if (bpt->type == bp_watchpoint_scope)
14267     return;
14268
14269   bpt->enable_state = bp_disabled;
14270
14271   /* Mark breakpoint locations modified.  */
14272   mark_breakpoint_modified (bpt);
14273
14274   if (target_supports_enable_disable_tracepoint ()
14275       && current_trace_status ()->running && is_tracepoint (bpt))
14276     {
14277       for (bp_location *location : bpt->locations ())
14278         target_disable_tracepoint (location);
14279     }
14280
14281   update_global_location_list (UGLL_DONT_INSERT);
14282
14283   gdb::observers::breakpoint_modified.notify (bpt);
14284 }
14285
14286 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14287    specified in ARGS.  ARGS may be in any of the formats handled by
14288    extract_bp_number_and_location.  ENABLE specifies whether to enable
14289    or disable the breakpoints/locations.  */
14290
14291 static void
14292 enable_disable_command (const char *args, int from_tty, bool enable)
14293 {
14294   if (args == 0)
14295     {
14296       for (breakpoint *bpt : all_breakpoints ())
14297         if (user_breakpoint_p (bpt))
14298           {
14299             if (enable)
14300               enable_breakpoint (bpt);
14301             else
14302               disable_breakpoint (bpt);
14303           }
14304     }
14305   else
14306     {
14307       std::string num = extract_arg (&args);
14308
14309       while (!num.empty ())
14310         {
14311           std::pair<int, int> bp_num_range, bp_loc_range;
14312
14313           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14314
14315           if (bp_loc_range.first == bp_loc_range.second
14316               && bp_loc_range.first == 0)
14317             {
14318               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14319               map_breakpoint_number_range (bp_num_range,
14320                                            enable
14321                                            ? enable_breakpoint
14322                                            : disable_breakpoint);
14323             }
14324           else
14325             {
14326               /* Handle breakpoint ids with formats 'x.y' or
14327                  'x.y-z'.  */
14328               enable_disable_breakpoint_location_range
14329                 (bp_num_range.first, bp_loc_range, enable);
14330             }
14331           num = extract_arg (&args);
14332         }
14333     }
14334 }
14335
14336 /* The disable command disables the specified breakpoints/locations
14337    (or all defined breakpoints) so they're no longer effective in
14338    stopping the inferior.  ARGS may be in any of the forms defined in
14339    extract_bp_number_and_location.  */
14340
14341 static void
14342 disable_command (const char *args, int from_tty)
14343 {
14344   enable_disable_command (args, from_tty, false);
14345 }
14346
14347 static void
14348 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14349                         int count)
14350 {
14351   int target_resources_ok;
14352
14353   if (bpt->type == bp_hardware_breakpoint)
14354     {
14355       int i;
14356       i = hw_breakpoint_used_count ();
14357       target_resources_ok = 
14358         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14359                                             i + 1, 0);
14360       if (target_resources_ok == 0)
14361         error (_("No hardware breakpoint support in the target."));
14362       else if (target_resources_ok < 0)
14363         error (_("Hardware breakpoints used exceeds limit."));
14364     }
14365
14366   if (is_watchpoint (bpt))
14367     {
14368       /* Initialize it just to avoid a GCC false warning.  */
14369       enum enable_state orig_enable_state = bp_disabled;
14370
14371       try
14372         {
14373           struct watchpoint *w = (struct watchpoint *) bpt;
14374
14375           orig_enable_state = bpt->enable_state;
14376           bpt->enable_state = bp_enabled;
14377           update_watchpoint (w, 1 /* reparse */);
14378         }
14379       catch (const gdb_exception &e)
14380         {
14381           bpt->enable_state = orig_enable_state;
14382           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14383                              bpt->number);
14384           return;
14385         }
14386     }
14387
14388   bpt->enable_state = bp_enabled;
14389
14390   /* Mark breakpoint locations modified.  */
14391   mark_breakpoint_modified (bpt);
14392
14393   if (target_supports_enable_disable_tracepoint ()
14394       && current_trace_status ()->running && is_tracepoint (bpt))
14395     {
14396       for (bp_location *location : bpt->locations ())
14397         target_enable_tracepoint (location);
14398     }
14399
14400   bpt->disposition = disposition;
14401   bpt->enable_count = count;
14402   update_global_location_list (UGLL_MAY_INSERT);
14403
14404   gdb::observers::breakpoint_modified.notify (bpt);
14405 }
14406
14407
14408 void
14409 enable_breakpoint (struct breakpoint *bpt)
14410 {
14411   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14412 }
14413
14414 /* The enable command enables the specified breakpoints/locations (or
14415    all defined breakpoints) so they once again become (or continue to
14416    be) effective in stopping the inferior.  ARGS may be in any of the
14417    forms defined in extract_bp_number_and_location.  */
14418
14419 static void
14420 enable_command (const char *args, int from_tty)
14421 {
14422   enable_disable_command (args, from_tty, true);
14423 }
14424
14425 static void
14426 enable_once_command (const char *args, int from_tty)
14427 {
14428   map_breakpoint_numbers
14429     (args, [&] (breakpoint *b)
14430      {
14431        iterate_over_related_breakpoints
14432          (b, [&] (breakpoint *bpt)
14433           {
14434             enable_breakpoint_disp (bpt, disp_disable, 1);
14435           });
14436      });
14437 }
14438
14439 static void
14440 enable_count_command (const char *args, int from_tty)
14441 {
14442   int count;
14443
14444   if (args == NULL)
14445     error_no_arg (_("hit count"));
14446
14447   count = get_number (&args);
14448
14449   map_breakpoint_numbers
14450     (args, [&] (breakpoint *b)
14451      {
14452        iterate_over_related_breakpoints
14453          (b, [&] (breakpoint *bpt)
14454           {
14455             enable_breakpoint_disp (bpt, disp_disable, count);
14456           });
14457      });
14458 }
14459
14460 static void
14461 enable_delete_command (const char *args, int from_tty)
14462 {
14463   map_breakpoint_numbers
14464     (args, [&] (breakpoint *b)
14465      {
14466        iterate_over_related_breakpoints
14467          (b, [&] (breakpoint *bpt)
14468           {
14469             enable_breakpoint_disp (bpt, disp_del, 1);
14470           });
14471      });
14472 }
14473 \f
14474 /* Invalidate last known value of any hardware watchpoint if
14475    the memory which that value represents has been written to by
14476    GDB itself.  */
14477
14478 static void
14479 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14480                                       CORE_ADDR addr, ssize_t len,
14481                                       const bfd_byte *data)
14482 {
14483   for (breakpoint *bp : all_breakpoints ())
14484     if (bp->enable_state == bp_enabled
14485         && bp->type == bp_hardware_watchpoint)
14486       {
14487         struct watchpoint *wp = (struct watchpoint *) bp;
14488
14489         if (wp->val_valid && wp->val != nullptr)
14490           {
14491             for (bp_location *loc : bp->locations ())
14492               if (loc->loc_type == bp_loc_hardware_watchpoint
14493                   && loc->address + loc->length > addr
14494                   && addr + len > loc->address)
14495                 {
14496                   wp->val = NULL;
14497                   wp->val_valid = false;
14498                 }
14499           }
14500       }
14501 }
14502
14503 /* Create and insert a breakpoint for software single step.  */
14504
14505 void
14506 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14507                                const address_space *aspace,
14508                                CORE_ADDR next_pc)
14509 {
14510   struct thread_info *tp = inferior_thread ();
14511   struct symtab_and_line sal;
14512   CORE_ADDR pc = next_pc;
14513
14514   if (tp->control.single_step_breakpoints == NULL)
14515     {
14516       tp->control.single_step_breakpoints
14517         = new_single_step_breakpoint (tp->global_num, gdbarch);
14518     }
14519
14520   sal = find_pc_line (pc, 0);
14521   sal.pc = pc;
14522   sal.section = find_pc_overlay (pc);
14523   sal.explicit_pc = 1;
14524   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14525
14526   update_global_location_list (UGLL_INSERT);
14527 }
14528
14529 /* Insert single step breakpoints according to the current state.  */
14530
14531 int
14532 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14533 {
14534   struct regcache *regcache = get_current_regcache ();
14535   std::vector<CORE_ADDR> next_pcs;
14536
14537   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14538
14539   if (!next_pcs.empty ())
14540     {
14541       struct frame_info *frame = get_current_frame ();
14542       const address_space *aspace = get_frame_address_space (frame);
14543
14544       for (CORE_ADDR pc : next_pcs)
14545         insert_single_step_breakpoint (gdbarch, aspace, pc);
14546
14547       return 1;
14548     }
14549   else
14550     return 0;
14551 }
14552
14553 /* See breakpoint.h.  */
14554
14555 int
14556 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14557                                        const address_space *aspace,
14558                                        CORE_ADDR pc)
14559 {
14560   for (bp_location *loc : bp->locations ())
14561     if (loc->inserted
14562         && breakpoint_location_address_match (loc, aspace, pc))
14563       return 1;
14564
14565   return 0;
14566 }
14567
14568 /* Check whether a software single-step breakpoint is inserted at
14569    PC.  */
14570
14571 int
14572 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14573                                         CORE_ADDR pc)
14574 {
14575   for (breakpoint *bpt : all_breakpoints ())
14576     {
14577       if (bpt->type == bp_single_step
14578           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14579         return 1;
14580     }
14581   return 0;
14582 }
14583
14584 /* Tracepoint-specific operations.  */
14585
14586 /* Set tracepoint count to NUM.  */
14587 static void
14588 set_tracepoint_count (int num)
14589 {
14590   tracepoint_count = num;
14591   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14592 }
14593
14594 static void
14595 trace_command (const char *arg, int from_tty)
14596 {
14597   event_location_up location = string_to_event_location (&arg,
14598                                                          current_language);
14599   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
14600     (location.get (), true /* is_tracepoint */);
14601
14602   create_breakpoint (get_current_arch (),
14603                      location.get (),
14604                      NULL, 0, arg, false, 1 /* parse arg */,
14605                      0 /* tempflag */,
14606                      bp_tracepoint /* type_wanted */,
14607                      0 /* Ignore count */,
14608                      pending_break_support,
14609                      ops,
14610                      from_tty,
14611                      1 /* enabled */,
14612                      0 /* internal */, 0);
14613 }
14614
14615 static void
14616 ftrace_command (const char *arg, int from_tty)
14617 {
14618   event_location_up location = string_to_event_location (&arg,
14619                                                          current_language);
14620   create_breakpoint (get_current_arch (),
14621                      location.get (),
14622                      NULL, 0, arg, false, 1 /* parse arg */,
14623                      0 /* tempflag */,
14624                      bp_fast_tracepoint /* type_wanted */,
14625                      0 /* Ignore count */,
14626                      pending_break_support,
14627                      &tracepoint_breakpoint_ops,
14628                      from_tty,
14629                      1 /* enabled */,
14630                      0 /* internal */, 0);
14631 }
14632
14633 /* strace command implementation.  Creates a static tracepoint.  */
14634
14635 static void
14636 strace_command (const char *arg, int from_tty)
14637 {
14638   struct breakpoint_ops *ops;
14639   event_location_up location;
14640
14641   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14642      or with a normal static tracepoint.  */
14643   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14644     {
14645       ops = &strace_marker_breakpoint_ops;
14646       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14647     }
14648   else
14649     {
14650       ops = &tracepoint_breakpoint_ops;
14651       location = string_to_event_location (&arg, current_language);
14652     }
14653
14654   create_breakpoint (get_current_arch (),
14655                      location.get (),
14656                      NULL, 0, arg, false, 1 /* parse arg */,
14657                      0 /* tempflag */,
14658                      bp_static_tracepoint /* type_wanted */,
14659                      0 /* Ignore count */,
14660                      pending_break_support,
14661                      ops,
14662                      from_tty,
14663                      1 /* enabled */,
14664                      0 /* internal */, 0);
14665 }
14666
14667 /* Set up a fake reader function that gets command lines from a linked
14668    list that was acquired during tracepoint uploading.  */
14669
14670 static struct uploaded_tp *this_utp;
14671 static int next_cmd;
14672
14673 static char *
14674 read_uploaded_action (void)
14675 {
14676   char *rslt = nullptr;
14677
14678   if (next_cmd < this_utp->cmd_strings.size ())
14679     {
14680       rslt = this_utp->cmd_strings[next_cmd].get ();
14681       next_cmd++;
14682     }
14683
14684   return rslt;
14685 }
14686
14687 /* Given information about a tracepoint as recorded on a target (which
14688    can be either a live system or a trace file), attempt to create an
14689    equivalent GDB tracepoint.  This is not a reliable process, since
14690    the target does not necessarily have all the information used when
14691    the tracepoint was originally defined.  */
14692   
14693 struct tracepoint *
14694 create_tracepoint_from_upload (struct uploaded_tp *utp)
14695 {
14696   const char *addr_str;
14697   char small_buf[100];
14698   struct tracepoint *tp;
14699
14700   if (utp->at_string)
14701     addr_str = utp->at_string.get ();
14702   else
14703     {
14704       /* In the absence of a source location, fall back to raw
14705          address.  Since there is no way to confirm that the address
14706          means the same thing as when the trace was started, warn the
14707          user.  */
14708       warning (_("Uploaded tracepoint %d has no "
14709                  "source location, using raw address"),
14710                utp->number);
14711       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14712       addr_str = small_buf;
14713     }
14714
14715   /* There's not much we can do with a sequence of bytecodes.  */
14716   if (utp->cond && !utp->cond_string)
14717     warning (_("Uploaded tracepoint %d condition "
14718                "has no source form, ignoring it"),
14719              utp->number);
14720
14721   event_location_up location = string_to_event_location (&addr_str,
14722                                                          current_language);
14723   if (!create_breakpoint (get_current_arch (),
14724                           location.get (),
14725                           utp->cond_string.get (), -1, addr_str,
14726                           false /* force_condition */,
14727                           0 /* parse cond/thread */,
14728                           0 /* tempflag */,
14729                           utp->type /* type_wanted */,
14730                           0 /* Ignore count */,
14731                           pending_break_support,
14732                           &tracepoint_breakpoint_ops,
14733                           0 /* from_tty */,
14734                           utp->enabled /* enabled */,
14735                           0 /* internal */,
14736                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14737     return NULL;
14738
14739   /* Get the tracepoint we just created.  */
14740   tp = get_tracepoint (tracepoint_count);
14741   gdb_assert (tp != NULL);
14742
14743   if (utp->pass > 0)
14744     {
14745       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14746                  tp->number);
14747
14748       trace_pass_command (small_buf, 0);
14749     }
14750
14751   /* If we have uploaded versions of the original commands, set up a
14752      special-purpose "reader" function and call the usual command line
14753      reader, then pass the result to the breakpoint command-setting
14754      function.  */
14755   if (!utp->cmd_strings.empty ())
14756     {
14757       counted_command_line cmd_list;
14758
14759       this_utp = utp;
14760       next_cmd = 0;
14761
14762       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14763
14764       breakpoint_set_commands (tp, std::move (cmd_list));
14765     }
14766   else if (!utp->actions.empty ()
14767            || !utp->step_actions.empty ())
14768     warning (_("Uploaded tracepoint %d actions "
14769                "have no source form, ignoring them"),
14770              utp->number);
14771
14772   /* Copy any status information that might be available.  */
14773   tp->hit_count = utp->hit_count;
14774   tp->traceframe_usage = utp->traceframe_usage;
14775
14776   return tp;
14777 }
14778   
14779 /* Print information on tracepoint number TPNUM_EXP, or all if
14780    omitted.  */
14781
14782 static void
14783 info_tracepoints_command (const char *args, int from_tty)
14784 {
14785   struct ui_out *uiout = current_uiout;
14786   int num_printed;
14787
14788   num_printed = breakpoint_1 (args, false, is_tracepoint);
14789
14790   if (num_printed == 0)
14791     {
14792       if (args == NULL || *args == '\0')
14793         uiout->message ("No tracepoints.\n");
14794       else
14795         uiout->message ("No tracepoint matching '%s'.\n", args);
14796     }
14797
14798   default_collect_info ();
14799 }
14800
14801 /* The 'enable trace' command enables tracepoints.
14802    Not supported by all targets.  */
14803 static void
14804 enable_trace_command (const char *args, int from_tty)
14805 {
14806   enable_command (args, from_tty);
14807 }
14808
14809 /* The 'disable trace' command disables tracepoints.
14810    Not supported by all targets.  */
14811 static void
14812 disable_trace_command (const char *args, int from_tty)
14813 {
14814   disable_command (args, from_tty);
14815 }
14816
14817 /* Remove a tracepoint (or all if no argument).  */
14818 static void
14819 delete_trace_command (const char *arg, int from_tty)
14820 {
14821   dont_repeat ();
14822
14823   if (arg == 0)
14824     {
14825       int breaks_to_delete = 0;
14826
14827       /* Delete all breakpoints if no argument.
14828          Do not delete internal or call-dummy breakpoints, these
14829          have to be deleted with an explicit breakpoint number 
14830          argument.  */
14831       for (breakpoint *tp : all_tracepoints ())
14832         if (is_tracepoint (tp) && user_breakpoint_p (tp))
14833           {
14834             breaks_to_delete = 1;
14835             break;
14836           }
14837
14838       /* Ask user only if there are some breakpoints to delete.  */
14839       if (!from_tty
14840           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14841         {
14842           for (breakpoint *b : all_breakpoints_safe ())
14843             if (is_tracepoint (b) && user_breakpoint_p (b))
14844               delete_breakpoint (b);
14845         }
14846     }
14847   else
14848     map_breakpoint_numbers
14849       (arg, [&] (breakpoint *br)
14850        {
14851          iterate_over_related_breakpoints (br, delete_breakpoint);
14852        });
14853 }
14854
14855 /* Helper function for trace_pass_command.  */
14856
14857 static void
14858 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14859 {
14860   tp->pass_count = count;
14861   gdb::observers::breakpoint_modified.notify (tp);
14862   if (from_tty)
14863     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14864                      tp->number, count);
14865 }
14866
14867 /* Set passcount for tracepoint.
14868
14869    First command argument is passcount, second is tracepoint number.
14870    If tracepoint number omitted, apply to most recently defined.
14871    Also accepts special argument "all".  */
14872
14873 static void
14874 trace_pass_command (const char *args, int from_tty)
14875 {
14876   struct tracepoint *t1;
14877   ULONGEST count;
14878
14879   if (args == 0 || *args == 0)
14880     error (_("passcount command requires an "
14881              "argument (count + optional TP num)"));
14882
14883   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
14884
14885   args = skip_spaces (args);
14886   if (*args && strncasecmp (args, "all", 3) == 0)
14887     {
14888       args += 3;                        /* Skip special argument "all".  */
14889       if (*args)
14890         error (_("Junk at end of arguments."));
14891
14892       for (breakpoint *b : all_tracepoints ())
14893         {
14894           t1 = (struct tracepoint *) b;
14895           trace_pass_set_count (t1, count, from_tty);
14896         }
14897     }
14898   else if (*args == '\0')
14899     {
14900       t1 = get_tracepoint_by_number (&args, NULL);
14901       if (t1)
14902         trace_pass_set_count (t1, count, from_tty);
14903     }
14904   else
14905     {
14906       number_or_range_parser parser (args);
14907       while (!parser.finished ())
14908         {
14909           t1 = get_tracepoint_by_number (&args, &parser);
14910           if (t1)
14911             trace_pass_set_count (t1, count, from_tty);
14912         }
14913     }
14914 }
14915
14916 struct tracepoint *
14917 get_tracepoint (int num)
14918 {
14919   for (breakpoint *t : all_tracepoints ())
14920     if (t->number == num)
14921       return (struct tracepoint *) t;
14922
14923   return NULL;
14924 }
14925
14926 /* Find the tracepoint with the given target-side number (which may be
14927    different from the tracepoint number after disconnecting and
14928    reconnecting).  */
14929
14930 struct tracepoint *
14931 get_tracepoint_by_number_on_target (int num)
14932 {
14933   for (breakpoint *b : all_tracepoints ())
14934     {
14935       struct tracepoint *t = (struct tracepoint *) b;
14936
14937       if (t->number_on_target == num)
14938         return t;
14939     }
14940
14941   return NULL;
14942 }
14943
14944 /* Utility: parse a tracepoint number and look it up in the list.
14945    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14946    If the argument is missing, the most recent tracepoint
14947    (tracepoint_count) is returned.  */
14948
14949 struct tracepoint *
14950 get_tracepoint_by_number (const char **arg,
14951                           number_or_range_parser *parser)
14952 {
14953   int tpnum;
14954   const char *instring = arg == NULL ? NULL : *arg;
14955
14956   if (parser != NULL)
14957     {
14958       gdb_assert (!parser->finished ());
14959       tpnum = parser->get_number ();
14960     }
14961   else if (arg == NULL || *arg == NULL || ! **arg)
14962     tpnum = tracepoint_count;
14963   else
14964     tpnum = get_number (arg);
14965
14966   if (tpnum <= 0)
14967     {
14968       if (instring && *instring)
14969         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14970                          instring);
14971       else
14972         printf_filtered (_("No previous tracepoint\n"));
14973       return NULL;
14974     }
14975
14976   for (breakpoint *t : all_tracepoints ())
14977     if (t->number == tpnum)
14978       return (struct tracepoint *) t;
14979
14980   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14981   return NULL;
14982 }
14983
14984 void
14985 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14986 {
14987   if (b->thread != -1)
14988     fprintf_unfiltered (fp, " thread %d", b->thread);
14989
14990   if (b->task != 0)
14991     fprintf_unfiltered (fp, " task %d", b->task);
14992
14993   fprintf_unfiltered (fp, "\n");
14994 }
14995
14996 /* Save information on user settable breakpoints (watchpoints, etc) to
14997    a new script file named FILENAME.  If FILTER is non-NULL, call it
14998    on each breakpoint and only include the ones for which it returns
14999    true.  */
15000
15001 static void
15002 save_breakpoints (const char *filename, int from_tty,
15003                   bool (*filter) (const struct breakpoint *))
15004 {
15005   int any = 0;
15006   int extra_trace_bits = 0;
15007
15008   if (filename == 0 || *filename == 0)
15009     error (_("Argument required (file name in which to save)"));
15010
15011   /* See if we have anything to save.  */
15012   for (breakpoint *tp : all_breakpoints ())
15013     {
15014       /* Skip internal and momentary breakpoints.  */
15015       if (!user_breakpoint_p (tp))
15016         continue;
15017
15018       /* If we have a filter, only save the breakpoints it accepts.  */
15019       if (filter && !filter (tp))
15020         continue;
15021
15022       any = 1;
15023
15024       if (is_tracepoint (tp))
15025         {
15026           extra_trace_bits = 1;
15027
15028           /* We can stop searching.  */
15029           break;
15030         }
15031     }
15032
15033   if (!any)
15034     {
15035       warning (_("Nothing to save."));
15036       return;
15037     }
15038
15039   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15040
15041   stdio_file fp;
15042
15043   if (!fp.open (expanded_filename.get (), "w"))
15044     error (_("Unable to open file '%s' for saving (%s)"),
15045            expanded_filename.get (), safe_strerror (errno));
15046
15047   if (extra_trace_bits)
15048     save_trace_state_variables (&fp);
15049
15050   for (breakpoint *tp : all_breakpoints ())
15051     {
15052       /* Skip internal and momentary breakpoints.  */
15053       if (!user_breakpoint_p (tp))
15054         continue;
15055
15056       /* If we have a filter, only save the breakpoints it accepts.  */
15057       if (filter && !filter (tp))
15058         continue;
15059
15060       tp->ops->print_recreate (tp, &fp);
15061
15062       /* Note, we can't rely on tp->number for anything, as we can't
15063          assume the recreated breakpoint numbers will match.  Use $bpnum
15064          instead.  */
15065
15066       if (tp->cond_string)
15067         fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15068
15069       if (tp->ignore_count)
15070         fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15071
15072       if (tp->type != bp_dprintf && tp->commands)
15073         {
15074           fp.puts ("  commands\n");
15075
15076           current_uiout->redirect (&fp);
15077           try
15078             {
15079               print_command_lines (current_uiout, tp->commands.get (), 2);
15080             }
15081           catch (const gdb_exception &ex)
15082             {
15083             current_uiout->redirect (NULL);
15084               throw;
15085             }
15086
15087           current_uiout->redirect (NULL);
15088           fp.puts ("  end\n");
15089         }
15090
15091       if (tp->enable_state == bp_disabled)
15092         fp.puts ("disable $bpnum\n");
15093
15094       /* If this is a multi-location breakpoint, check if the locations
15095          should be individually disabled.  Watchpoint locations are
15096          special, and not user visible.  */
15097       if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15098         {
15099           int n = 1;
15100
15101           for (bp_location *loc : tp->locations ())
15102             {
15103               if (!loc->enabled)
15104                 fp.printf ("disable $bpnum.%d\n", n);
15105
15106               n++;
15107             }
15108         }
15109     }
15110
15111   if (extra_trace_bits && *default_collect)
15112     fp.printf ("set default-collect %s\n", default_collect);
15113
15114   if (from_tty)
15115     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15116 }
15117
15118 /* The `save breakpoints' command.  */
15119
15120 static void
15121 save_breakpoints_command (const char *args, int from_tty)
15122 {
15123   save_breakpoints (args, from_tty, NULL);
15124 }
15125
15126 /* The `save tracepoints' command.  */
15127
15128 static void
15129 save_tracepoints_command (const char *args, int from_tty)
15130 {
15131   save_breakpoints (args, from_tty, is_tracepoint);
15132 }
15133
15134 \f
15135 /* This help string is used to consolidate all the help string for specifying
15136    locations used by several commands.  */
15137
15138 #define LOCATION_HELP_STRING \
15139 "Linespecs are colon-separated lists of location parameters, such as\n\
15140 source filename, function name, label name, and line number.\n\
15141 Example: To specify the start of a label named \"the_top\" in the\n\
15142 function \"fact\" in the file \"factorial.c\", use\n\
15143 \"factorial.c:fact:the_top\".\n\
15144 \n\
15145 Address locations begin with \"*\" and specify an exact address in the\n\
15146 program.  Example: To specify the fourth byte past the start function\n\
15147 \"main\", use \"*main + 4\".\n\
15148 \n\
15149 Explicit locations are similar to linespecs but use an option/argument\n\
15150 syntax to specify location parameters.\n\
15151 Example: To specify the start of the label named \"the_top\" in the\n\
15152 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15153 -function fact -label the_top\".\n\
15154 \n\
15155 By default, a specified function is matched against the program's\n\
15156 functions in all scopes.  For C++, this means in all namespaces and\n\
15157 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15158 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15159 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15160 specified name as a complete fully-qualified name instead."
15161
15162 /* This help string is used for the break, hbreak, tbreak and thbreak
15163    commands.  It is defined as a macro to prevent duplication.
15164    COMMAND should be a string constant containing the name of the
15165    command.  */
15166
15167 #define BREAK_ARGS_HELP(command) \
15168 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
15169 \t[-force-condition] [if CONDITION]\n\
15170 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15171 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15172 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15173 `-probe-dtrace' (for a DTrace probe).\n\
15174 LOCATION may be a linespec, address, or explicit location as described\n\
15175 below.\n\
15176 \n\
15177 With no LOCATION, uses current execution address of the selected\n\
15178 stack frame.  This is useful for breaking on return to a stack frame.\n\
15179 \n\
15180 THREADNUM is the number from \"info threads\".\n\
15181 CONDITION is a boolean expression.\n\
15182 \n\
15183 With the \"-force-condition\" flag, the condition is defined even when\n\
15184 it is invalid for all current locations.\n\
15185 \n" LOCATION_HELP_STRING "\n\n\
15186 Multiple breakpoints at one place are permitted, and useful if their\n\
15187 conditions are different.\n\
15188 \n\
15189 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15190
15191 /* List of subcommands for "catch".  */
15192 static struct cmd_list_element *catch_cmdlist;
15193
15194 /* List of subcommands for "tcatch".  */
15195 static struct cmd_list_element *tcatch_cmdlist;
15196
15197 void
15198 add_catch_command (const char *name, const char *docstring,
15199                    cmd_const_sfunc_ftype *sfunc,
15200                    completer_ftype *completer,
15201                    void *user_data_catch,
15202                    void *user_data_tcatch)
15203 {
15204   struct cmd_list_element *command;
15205
15206   command = add_cmd (name, class_breakpoint, docstring,
15207                      &catch_cmdlist);
15208   set_cmd_sfunc (command, sfunc);
15209   set_cmd_context (command, user_data_catch);
15210   set_cmd_completer (command, completer);
15211
15212   command = add_cmd (name, class_breakpoint, docstring,
15213                      &tcatch_cmdlist);
15214   set_cmd_sfunc (command, sfunc);
15215   set_cmd_context (command, user_data_tcatch);
15216   set_cmd_completer (command, completer);
15217 }
15218
15219 /* Zero if any of the breakpoint's locations could be a location where
15220    functions have been inlined, nonzero otherwise.  */
15221
15222 static int
15223 is_non_inline_function (struct breakpoint *b)
15224 {
15225   /* The shared library event breakpoint is set on the address of a
15226      non-inline function.  */
15227   if (b->type == bp_shlib_event)
15228     return 1;
15229
15230   return 0;
15231 }
15232
15233 /* Nonzero if the specified PC cannot be a location where functions
15234    have been inlined.  */
15235
15236 int
15237 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15238                            const struct target_waitstatus *ws)
15239 {
15240   for (breakpoint *b : all_breakpoints ())
15241     {
15242       if (!is_non_inline_function (b))
15243         continue;
15244
15245       for (bp_location *bl : b->locations ())
15246         {
15247           if (!bl->shlib_disabled
15248               && bpstat_check_location (bl, aspace, pc, ws))
15249             return 1;
15250         }
15251     }
15252
15253   return 0;
15254 }
15255
15256 /* Remove any references to OBJFILE which is going to be freed.  */
15257
15258 void
15259 breakpoint_free_objfile (struct objfile *objfile)
15260 {
15261   for (bp_location *loc : all_bp_locations ())
15262     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15263       loc->symtab = NULL;
15264 }
15265
15266 void
15267 initialize_breakpoint_ops (void)
15268 {
15269   static int initialized = 0;
15270
15271   struct breakpoint_ops *ops;
15272
15273   if (initialized)
15274     return;
15275   initialized = 1;
15276
15277   /* The breakpoint_ops structure to be inherit by all kinds of
15278      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15279      internal and momentary breakpoints, etc.).  */
15280   ops = &bkpt_base_breakpoint_ops;
15281   *ops = base_breakpoint_ops;
15282   ops->re_set = bkpt_re_set;
15283   ops->insert_location = bkpt_insert_location;
15284   ops->remove_location = bkpt_remove_location;
15285   ops->breakpoint_hit = bkpt_breakpoint_hit;
15286   ops->create_sals_from_location = bkpt_create_sals_from_location;
15287   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15288   ops->decode_location = bkpt_decode_location;
15289
15290   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15291   ops = &bkpt_breakpoint_ops;
15292   *ops = bkpt_base_breakpoint_ops;
15293   ops->re_set = bkpt_re_set;
15294   ops->resources_needed = bkpt_resources_needed;
15295   ops->print_it = bkpt_print_it;
15296   ops->print_mention = bkpt_print_mention;
15297   ops->print_recreate = bkpt_print_recreate;
15298
15299   /* Ranged breakpoints.  */
15300   ops = &ranged_breakpoint_ops;
15301   *ops = bkpt_breakpoint_ops;
15302   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15303   ops->resources_needed = resources_needed_ranged_breakpoint;
15304   ops->print_it = print_it_ranged_breakpoint;
15305   ops->print_one = print_one_ranged_breakpoint;
15306   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15307   ops->print_mention = print_mention_ranged_breakpoint;
15308   ops->print_recreate = print_recreate_ranged_breakpoint;
15309
15310   /* Internal breakpoints.  */
15311   ops = &internal_breakpoint_ops;
15312   *ops = bkpt_base_breakpoint_ops;
15313   ops->re_set = internal_bkpt_re_set;
15314   ops->check_status = internal_bkpt_check_status;
15315   ops->print_it = internal_bkpt_print_it;
15316   ops->print_mention = internal_bkpt_print_mention;
15317
15318   /* Momentary breakpoints.  */
15319   ops = &momentary_breakpoint_ops;
15320   *ops = bkpt_base_breakpoint_ops;
15321   ops->re_set = momentary_bkpt_re_set;
15322   ops->check_status = momentary_bkpt_check_status;
15323   ops->print_it = momentary_bkpt_print_it;
15324   ops->print_mention = momentary_bkpt_print_mention;
15325
15326   /* Probe breakpoints.  */
15327   ops = &bkpt_probe_breakpoint_ops;
15328   *ops = bkpt_breakpoint_ops;
15329   ops->insert_location = bkpt_probe_insert_location;
15330   ops->remove_location = bkpt_probe_remove_location;
15331   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15332   ops->decode_location = bkpt_probe_decode_location;
15333
15334   /* Watchpoints.  */
15335   ops = &watchpoint_breakpoint_ops;
15336   *ops = base_breakpoint_ops;
15337   ops->re_set = re_set_watchpoint;
15338   ops->insert_location = insert_watchpoint;
15339   ops->remove_location = remove_watchpoint;
15340   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15341   ops->check_status = check_status_watchpoint;
15342   ops->resources_needed = resources_needed_watchpoint;
15343   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15344   ops->print_it = print_it_watchpoint;
15345   ops->print_mention = print_mention_watchpoint;
15346   ops->print_recreate = print_recreate_watchpoint;
15347   ops->explains_signal = explains_signal_watchpoint;
15348
15349   /* Masked watchpoints.  */
15350   ops = &masked_watchpoint_breakpoint_ops;
15351   *ops = watchpoint_breakpoint_ops;
15352   ops->insert_location = insert_masked_watchpoint;
15353   ops->remove_location = remove_masked_watchpoint;
15354   ops->resources_needed = resources_needed_masked_watchpoint;
15355   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15356   ops->print_it = print_it_masked_watchpoint;
15357   ops->print_one_detail = print_one_detail_masked_watchpoint;
15358   ops->print_mention = print_mention_masked_watchpoint;
15359   ops->print_recreate = print_recreate_masked_watchpoint;
15360
15361   /* Tracepoints.  */
15362   ops = &tracepoint_breakpoint_ops;
15363   *ops = base_breakpoint_ops;
15364   ops->re_set = tracepoint_re_set;
15365   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15366   ops->print_one_detail = tracepoint_print_one_detail;
15367   ops->print_mention = tracepoint_print_mention;
15368   ops->print_recreate = tracepoint_print_recreate;
15369   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15370   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15371   ops->decode_location = tracepoint_decode_location;
15372
15373   /* Probe tracepoints.  */
15374   ops = &tracepoint_probe_breakpoint_ops;
15375   *ops = tracepoint_breakpoint_ops;
15376   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15377   ops->decode_location = tracepoint_probe_decode_location;
15378
15379   /* Static tracepoints with marker (`-m').  */
15380   ops = &strace_marker_breakpoint_ops;
15381   *ops = tracepoint_breakpoint_ops;
15382   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15383   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15384   ops->decode_location = strace_marker_decode_location;
15385
15386   /* Fork catchpoints.  */
15387   ops = &catch_fork_breakpoint_ops;
15388   *ops = base_breakpoint_ops;
15389   ops->insert_location = insert_catch_fork;
15390   ops->remove_location = remove_catch_fork;
15391   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15392   ops->print_it = print_it_catch_fork;
15393   ops->print_one = print_one_catch_fork;
15394   ops->print_mention = print_mention_catch_fork;
15395   ops->print_recreate = print_recreate_catch_fork;
15396
15397   /* Vfork catchpoints.  */
15398   ops = &catch_vfork_breakpoint_ops;
15399   *ops = base_breakpoint_ops;
15400   ops->insert_location = insert_catch_vfork;
15401   ops->remove_location = remove_catch_vfork;
15402   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15403   ops->print_it = print_it_catch_vfork;
15404   ops->print_one = print_one_catch_vfork;
15405   ops->print_mention = print_mention_catch_vfork;
15406   ops->print_recreate = print_recreate_catch_vfork;
15407
15408   /* Exec catchpoints.  */
15409   ops = &catch_exec_breakpoint_ops;
15410   *ops = base_breakpoint_ops;
15411   ops->insert_location = insert_catch_exec;
15412   ops->remove_location = remove_catch_exec;
15413   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15414   ops->print_it = print_it_catch_exec;
15415   ops->print_one = print_one_catch_exec;
15416   ops->print_mention = print_mention_catch_exec;
15417   ops->print_recreate = print_recreate_catch_exec;
15418
15419   /* Solib-related catchpoints.  */
15420   ops = &catch_solib_breakpoint_ops;
15421   *ops = base_breakpoint_ops;
15422   ops->insert_location = insert_catch_solib;
15423   ops->remove_location = remove_catch_solib;
15424   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15425   ops->check_status = check_status_catch_solib;
15426   ops->print_it = print_it_catch_solib;
15427   ops->print_one = print_one_catch_solib;
15428   ops->print_mention = print_mention_catch_solib;
15429   ops->print_recreate = print_recreate_catch_solib;
15430
15431   ops = &dprintf_breakpoint_ops;
15432   *ops = bkpt_base_breakpoint_ops;
15433   ops->re_set = dprintf_re_set;
15434   ops->resources_needed = bkpt_resources_needed;
15435   ops->print_it = bkpt_print_it;
15436   ops->print_mention = bkpt_print_mention;
15437   ops->print_recreate = dprintf_print_recreate;
15438   ops->after_condition_true = dprintf_after_condition_true;
15439   ops->breakpoint_hit = dprintf_breakpoint_hit;
15440 }
15441
15442 /* Chain containing all defined "enable breakpoint" subcommands.  */
15443
15444 static struct cmd_list_element *enablebreaklist = NULL;
15445
15446 /* See breakpoint.h.  */
15447
15448 cmd_list_element *commands_cmd_element = nullptr;
15449
15450 void _initialize_breakpoint ();
15451 void
15452 _initialize_breakpoint ()
15453 {
15454   struct cmd_list_element *c;
15455
15456   initialize_breakpoint_ops ();
15457
15458   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
15459                                          "breakpoint");
15460   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
15461                                        "breakpoint");
15462   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
15463                                          "breakpoint");
15464
15465   breakpoint_chain = 0;
15466   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15467      before a breakpoint is set.  */
15468   breakpoint_count = 0;
15469
15470   tracepoint_count = 0;
15471
15472   add_com ("ignore", class_breakpoint, ignore_command, _("\
15473 Set ignore-count of breakpoint number N to COUNT.\n\
15474 Usage is `ignore N COUNT'."));
15475
15476   commands_cmd_element = add_com ("commands", class_breakpoint,
15477                                   commands_command, _("\
15478 Set commands to be executed when the given breakpoints are hit.\n\
15479 Give a space-separated breakpoint list as argument after \"commands\".\n\
15480 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15481 (e.g. `5-7').\n\
15482 With no argument, the targeted breakpoint is the last one set.\n\
15483 The commands themselves follow starting on the next line.\n\
15484 Type a line containing \"end\" to indicate the end of them.\n\
15485 Give \"silent\" as the first line to make the breakpoint silent;\n\
15486 then no output is printed when it is hit, except what the commands print."));
15487
15488   const auto cc_opts = make_condition_command_options_def_group (nullptr);
15489   static std::string condition_command_help
15490     = gdb::option::build_help (_("\
15491 Specify breakpoint number N to break only if COND is true.\n\
15492 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
15493 is an expression to be evaluated whenever breakpoint N is reached.\n\
15494 \n\
15495 Options:\n\
15496 %OPTIONS%"), cc_opts);
15497
15498   c = add_com ("condition", class_breakpoint, condition_command,
15499                condition_command_help.c_str ());
15500   set_cmd_completer_handle_brkchars (c, condition_completer);
15501
15502   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15503 Set a temporary breakpoint.\n\
15504 Like \"break\" except the breakpoint is only temporary,\n\
15505 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15506 by using \"enable delete\" on the breakpoint number.\n\
15507 \n"
15508 BREAK_ARGS_HELP ("tbreak")));
15509   set_cmd_completer (c, location_completer);
15510
15511   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15512 Set a hardware assisted breakpoint.\n\
15513 Like \"break\" except the breakpoint requires hardware support,\n\
15514 some target hardware may not have this support.\n\
15515 \n"
15516 BREAK_ARGS_HELP ("hbreak")));
15517   set_cmd_completer (c, location_completer);
15518
15519   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15520 Set a temporary hardware assisted breakpoint.\n\
15521 Like \"hbreak\" except the breakpoint is only temporary,\n\
15522 so it will be deleted when hit.\n\
15523 \n"
15524 BREAK_ARGS_HELP ("thbreak")));
15525   set_cmd_completer (c, location_completer);
15526
15527   cmd_list_element *enable_cmd
15528     = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15529 Enable all or some breakpoints.\n\
15530 Usage: enable [BREAKPOINTNUM]...\n\
15531 Give breakpoint numbers (separated by spaces) as arguments.\n\
15532 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15533 This is used to cancel the effect of the \"disable\" command.\n\
15534 With a subcommand you can enable temporarily."),
15535                       &enablelist, 1, &cmdlist);
15536
15537   add_com_alias ("en", enable_cmd, class_breakpoint, 1);
15538
15539   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15540 Enable all or some breakpoints.\n\
15541 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
15542 Give breakpoint numbers (separated by spaces) as arguments.\n\
15543 This is used to cancel the effect of the \"disable\" command.\n\
15544 May be abbreviated to simply \"enable\"."),
15545                    &enablebreaklist, 1, &enablelist);
15546
15547   add_cmd ("once", no_class, enable_once_command, _("\
15548 Enable some breakpoints for one hit.\n\
15549 Usage: enable breakpoints once BREAKPOINTNUM...\n\
15550 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15551            &enablebreaklist);
15552
15553   add_cmd ("delete", no_class, enable_delete_command, _("\
15554 Enable some breakpoints and delete when hit.\n\
15555 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
15556 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15557            &enablebreaklist);
15558
15559   add_cmd ("count", no_class, enable_count_command, _("\
15560 Enable some breakpoints for COUNT hits.\n\
15561 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
15562 If a breakpoint is hit while enabled in this fashion,\n\
15563 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15564            &enablebreaklist);
15565
15566   add_cmd ("delete", no_class, enable_delete_command, _("\
15567 Enable some breakpoints and delete when hit.\n\
15568 Usage: enable delete BREAKPOINTNUM...\n\
15569 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15570            &enablelist);
15571
15572   add_cmd ("once", no_class, enable_once_command, _("\
15573 Enable some breakpoints for one hit.\n\
15574 Usage: enable once BREAKPOINTNUM...\n\
15575 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15576            &enablelist);
15577
15578   add_cmd ("count", no_class, enable_count_command, _("\
15579 Enable some breakpoints for COUNT hits.\n\
15580 Usage: enable count COUNT BREAKPOINTNUM...\n\
15581 If a breakpoint is hit while enabled in this fashion,\n\
15582 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15583            &enablelist);
15584
15585   cmd_list_element *disable_cmd
15586     = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15587 Disable all or some breakpoints.\n\
15588 Usage: disable [BREAKPOINTNUM]...\n\
15589 Arguments are breakpoint numbers with spaces in between.\n\
15590 To disable all breakpoints, give no argument.\n\
15591 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15592                       &disablelist, 1, &cmdlist);
15593   add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
15594   add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
15595
15596   add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
15597 Disable all or some breakpoints.\n\
15598 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
15599 Arguments are breakpoint numbers with spaces in between.\n\
15600 To disable all breakpoints, give no argument.\n\
15601 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15602 This command may be abbreviated \"disable\"."),
15603            &disablelist);
15604
15605   cmd_list_element *delete_cmd
15606     = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15607 Delete all or some breakpoints.\n\
15608 Usage: delete [BREAKPOINTNUM]...\n\
15609 Arguments are breakpoint numbers with spaces in between.\n\
15610 To delete all breakpoints, give no argument.\n\
15611 \n\
15612 Also a prefix command for deletion of other GDB objects."),
15613                       &deletelist, 1, &cmdlist);
15614   add_com_alias ("d", delete_cmd, class_breakpoint, 1);
15615   add_com_alias ("del", delete_cmd, class_breakpoint, 1);
15616
15617   add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
15618 Delete all or some breakpoints or auto-display expressions.\n\
15619 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
15620 Arguments are breakpoint numbers with spaces in between.\n\
15621 To delete all breakpoints, give no argument.\n\
15622 This command may be abbreviated \"delete\"."),
15623            &deletelist);
15624
15625   cmd_list_element *clear_cmd
15626    = add_com ("clear", class_breakpoint, clear_command, _("\
15627 Clear breakpoint at specified location.\n\
15628 Argument may be a linespec, explicit, or address location as described below.\n\
15629 \n\
15630 With no argument, clears all breakpoints in the line that the selected frame\n\
15631 is executing in.\n"
15632 "\n" LOCATION_HELP_STRING "\n\n\
15633 See also the \"delete\" command which clears breakpoints by number."));
15634   add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
15635
15636   cmd_list_element *break_cmd
15637     = add_com ("break", class_breakpoint, break_command, _("\
15638 Set breakpoint at specified location.\n"
15639 BREAK_ARGS_HELP ("break")));
15640   set_cmd_completer (break_cmd, location_completer);
15641
15642   add_com_alias ("b", break_cmd, class_run, 1);
15643   add_com_alias ("br", break_cmd, class_run, 1);
15644   add_com_alias ("bre", break_cmd, class_run, 1);
15645   add_com_alias ("brea", break_cmd, class_run, 1);
15646
15647   if (dbx_commands)
15648     {
15649       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15650 Break in function/address or break at a line in the current file."),
15651                              &stoplist, 1, &cmdlist);
15652       add_cmd ("in", class_breakpoint, stopin_command,
15653                _("Break in function or address."), &stoplist);
15654       add_cmd ("at", class_breakpoint, stopat_command,
15655                _("Break at a line in the current file."), &stoplist);
15656       add_com ("status", class_info, info_breakpoints_command, _("\
15657 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15658 The \"Type\" column indicates one of:\n\
15659 \tbreakpoint     - normal breakpoint\n\
15660 \twatchpoint     - watchpoint\n\
15661 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15662 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15663 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15664 address and file/line number respectively.\n\
15665 \n\
15666 Convenience variable \"$_\" and default examine address for \"x\"\n\
15667 are set to the address of the last breakpoint listed unless the command\n\
15668 is prefixed with \"server \".\n\n\
15669 Convenience variable \"$bpnum\" contains the number of the last\n\
15670 breakpoint set."));
15671     }
15672
15673   cmd_list_element *info_breakpoints_cmd
15674     = add_info ("breakpoints", info_breakpoints_command, _("\
15675 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15676 The \"Type\" column indicates one of:\n\
15677 \tbreakpoint     - normal breakpoint\n\
15678 \twatchpoint     - watchpoint\n\
15679 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15680 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15681 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15682 address and file/line number respectively.\n\
15683 \n\
15684 Convenience variable \"$_\" and default examine address for \"x\"\n\
15685 are set to the address of the last breakpoint listed unless the command\n\
15686 is prefixed with \"server \".\n\n\
15687 Convenience variable \"$bpnum\" contains the number of the last\n\
15688 breakpoint set."));
15689
15690   add_info_alias ("b", info_breakpoints_cmd, 1);
15691
15692   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15693 Status of all breakpoints, or breakpoint number NUMBER.\n\
15694 The \"Type\" column indicates one of:\n\
15695 \tbreakpoint     - normal breakpoint\n\
15696 \twatchpoint     - watchpoint\n\
15697 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15698 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15699 \tuntil          - internal breakpoint used by the \"until\" command\n\
15700 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15701 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15702 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15703 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15704 address and file/line number respectively.\n\
15705 \n\
15706 Convenience variable \"$_\" and default examine address for \"x\"\n\
15707 are set to the address of the last breakpoint listed unless the command\n\
15708 is prefixed with \"server \".\n\n\
15709 Convenience variable \"$bpnum\" contains the number of the last\n\
15710 breakpoint set."),
15711            &maintenanceinfolist);
15712
15713   add_basic_prefix_cmd ("catch", class_breakpoint, _("\
15714 Set catchpoints to catch events."),
15715                         &catch_cmdlist,
15716                         0/*allow-unknown*/, &cmdlist);
15717
15718   add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
15719 Set temporary catchpoints to catch events."),
15720                         &tcatch_cmdlist,
15721                         0/*allow-unknown*/, &cmdlist);
15722
15723   add_catch_command ("fork", _("Catch calls to fork."),
15724                      catch_fork_command_1,
15725                      NULL,
15726                      (void *) (uintptr_t) catch_fork_permanent,
15727                      (void *) (uintptr_t) catch_fork_temporary);
15728   add_catch_command ("vfork", _("Catch calls to vfork."),
15729                      catch_fork_command_1,
15730                      NULL,
15731                      (void *) (uintptr_t) catch_vfork_permanent,
15732                      (void *) (uintptr_t) catch_vfork_temporary);
15733   add_catch_command ("exec", _("Catch calls to exec."),
15734                      catch_exec_command_1,
15735                      NULL,
15736                      CATCH_PERMANENT,
15737                      CATCH_TEMPORARY);
15738   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15739 Usage: catch load [REGEX]\n\
15740 If REGEX is given, only stop for libraries matching the regular expression."),
15741                      catch_load_command_1,
15742                      NULL,
15743                      CATCH_PERMANENT,
15744                      CATCH_TEMPORARY);
15745   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15746 Usage: catch unload [REGEX]\n\
15747 If REGEX is given, only stop for libraries matching the regular expression."),
15748                      catch_unload_command_1,
15749                      NULL,
15750                      CATCH_PERMANENT,
15751                      CATCH_TEMPORARY);
15752
15753   const auto opts = make_watch_options_def_group (nullptr);
15754
15755   static const std::string watch_help = gdb::option::build_help (_("\
15756 Set a watchpoint for EXPRESSION.\n\
15757 Usage: watch [-location] EXPRESSION\n\
15758 \n\
15759 Options:\n\
15760 %OPTIONS%\n\
15761 \n\
15762 A watchpoint stops execution of your program whenever the value of\n\
15763 an expression changes."), opts);
15764   c = add_com ("watch", class_breakpoint, watch_command,
15765                watch_help.c_str ());
15766   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15767
15768   static const std::string rwatch_help = gdb::option::build_help (_("\
15769 Set a read watchpoint for EXPRESSION.\n\
15770 Usage: rwatch [-location] EXPRESSION\n\
15771 \n\
15772 Options:\n\
15773 %OPTIONS%\n\
15774 \n\
15775 A read watchpoint stops execution of your program whenever the value of\n\
15776 an expression is read."), opts);
15777   c = add_com ("rwatch", class_breakpoint, rwatch_command,
15778                rwatch_help.c_str ());
15779   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15780
15781   static const std::string awatch_help = gdb::option::build_help (_("\
15782 Set an access watchpoint for EXPRESSION.\n\
15783 Usage: awatch [-location] EXPRESSION\n\
15784 \n\
15785 Options:\n\
15786 %OPTIONS%\n\
15787 \n\
15788 An access watchpoint stops execution of your program whenever the value\n\
15789 of an expression is either read or written."), opts);
15790   c = add_com ("awatch", class_breakpoint, awatch_command,
15791                awatch_help.c_str ());
15792   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15793
15794   add_info ("watchpoints", info_watchpoints_command, _("\
15795 Status of specified watchpoints (all watchpoints if no argument)."));
15796
15797   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15798      respond to changes - contrary to the description.  */
15799   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15800                             &can_use_hw_watchpoints, _("\
15801 Set debugger's willingness to use watchpoint hardware."), _("\
15802 Show debugger's willingness to use watchpoint hardware."), _("\
15803 If zero, gdb will not use hardware for new watchpoints, even if\n\
15804 such is available.  (However, any hardware watchpoints that were\n\
15805 created before setting this to nonzero, will continue to use watchpoint\n\
15806 hardware.)"),
15807                             NULL,
15808                             show_can_use_hw_watchpoints,
15809                             &setlist, &showlist);
15810
15811   can_use_hw_watchpoints = 1;
15812
15813   /* Tracepoint manipulation commands.  */
15814
15815   cmd_list_element *trace_cmd
15816     = add_com ("trace", class_breakpoint, trace_command, _("\
15817 Set a tracepoint at specified location.\n\
15818 \n"
15819 BREAK_ARGS_HELP ("trace") "\n\
15820 Do \"help tracepoints\" for info on other tracepoint commands."));
15821   set_cmd_completer (trace_cmd, location_completer);
15822
15823   add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
15824   add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
15825   add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
15826   add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
15827
15828   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15829 Set a fast tracepoint at specified location.\n\
15830 \n"
15831 BREAK_ARGS_HELP ("ftrace") "\n\
15832 Do \"help tracepoints\" for info on other tracepoint commands."));
15833   set_cmd_completer (c, location_completer);
15834
15835   c = add_com ("strace", class_breakpoint, strace_command, _("\
15836 Set a static tracepoint at location or marker.\n\
15837 \n\
15838 strace [LOCATION] [if CONDITION]\n\
15839 LOCATION may be a linespec, explicit, or address location (described below) \n\
15840 or -m MARKER_ID.\n\n\
15841 If a marker id is specified, probe the marker with that name.  With\n\
15842 no LOCATION, uses current execution address of the selected stack frame.\n\
15843 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15844 This collects arbitrary user data passed in the probe point call to the\n\
15845 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15846 by printing the $_sdata variable like any other convenience variable.\n\
15847 \n\
15848 CONDITION is a boolean expression.\n\
15849 \n" LOCATION_HELP_STRING "\n\n\
15850 Multiple tracepoints at one place are permitted, and useful if their\n\
15851 conditions are different.\n\
15852 \n\
15853 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15854 Do \"help tracepoints\" for info on other tracepoint commands."));
15855   set_cmd_completer (c, location_completer);
15856
15857   cmd_list_element *info_tracepoints_cmd
15858     = add_info ("tracepoints", info_tracepoints_command, _("\
15859 Status of specified tracepoints (all tracepoints if no argument).\n\
15860 Convenience variable \"$tpnum\" contains the number of the\n\
15861 last tracepoint set."));
15862
15863   add_info_alias ("tp", info_tracepoints_cmd, 1);
15864
15865   cmd_list_element *delete_tracepoints_cmd
15866     = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15867 Delete specified tracepoints.\n\
15868 Arguments are tracepoint numbers, separated by spaces.\n\
15869 No argument means delete all tracepoints."),
15870            &deletelist);
15871   add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
15872
15873   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15874 Disable specified tracepoints.\n\
15875 Arguments are tracepoint numbers, separated by spaces.\n\
15876 No argument means disable all tracepoints."),
15877            &disablelist);
15878   deprecate_cmd (c, "disable");
15879
15880   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15881 Enable specified tracepoints.\n\
15882 Arguments are tracepoint numbers, separated by spaces.\n\
15883 No argument means enable all tracepoints."),
15884            &enablelist);
15885   deprecate_cmd (c, "enable");
15886
15887   add_com ("passcount", class_trace, trace_pass_command, _("\
15888 Set the passcount for a tracepoint.\n\
15889 The trace will end when the tracepoint has been passed 'count' times.\n\
15890 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15891 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15892
15893   add_basic_prefix_cmd ("save", class_breakpoint,
15894                         _("Save breakpoint definitions as a script."),
15895                         &save_cmdlist,
15896                         0/*allow-unknown*/, &cmdlist);
15897
15898   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15899 Save current breakpoint definitions as a script.\n\
15900 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15901 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15902 session to restore them."),
15903                &save_cmdlist);
15904   set_cmd_completer (c, filename_completer);
15905
15906   cmd_list_element *save_tracepoints_cmd
15907     = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15908 Save current tracepoint definitions as a script.\n\
15909 Use the 'source' command in another debug session to restore them."),
15910                &save_cmdlist);
15911   set_cmd_completer (save_tracepoints_cmd, filename_completer);
15912
15913   c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
15914   deprecate_cmd (c, "save tracepoints");
15915
15916   add_basic_prefix_cmd ("breakpoint", class_maintenance, _("\
15917 Breakpoint specific settings.\n\
15918 Configure various breakpoint-specific variables such as\n\
15919 pending breakpoint behavior."),
15920                         &breakpoint_set_cmdlist,
15921                         0/*allow-unknown*/, &setlist);
15922   add_show_prefix_cmd ("breakpoint", class_maintenance, _("\
15923 Breakpoint specific settings.\n\
15924 Configure various breakpoint-specific variables such as\n\
15925 pending breakpoint behavior."),
15926                        &breakpoint_show_cmdlist,
15927                        0/*allow-unknown*/, &showlist);
15928
15929   add_setshow_auto_boolean_cmd ("pending", no_class,
15930                                 &pending_break_support, _("\
15931 Set debugger's behavior regarding pending breakpoints."), _("\
15932 Show debugger's behavior regarding pending breakpoints."), _("\
15933 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15934 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15935 an error.  If auto, an unrecognized breakpoint location results in a\n\
15936 user-query to see if a pending breakpoint should be created."),
15937                                 NULL,
15938                                 show_pending_break_support,
15939                                 &breakpoint_set_cmdlist,
15940                                 &breakpoint_show_cmdlist);
15941
15942   pending_break_support = AUTO_BOOLEAN_AUTO;
15943
15944   add_setshow_boolean_cmd ("auto-hw", no_class,
15945                            &automatic_hardware_breakpoints, _("\
15946 Set automatic usage of hardware breakpoints."), _("\
15947 Show automatic usage of hardware breakpoints."), _("\
15948 If set, the debugger will automatically use hardware breakpoints for\n\
15949 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15950 a warning will be emitted for such breakpoints."),
15951                            NULL,
15952                            show_automatic_hardware_breakpoints,
15953                            &breakpoint_set_cmdlist,
15954                            &breakpoint_show_cmdlist);
15955
15956   add_setshow_boolean_cmd ("always-inserted", class_support,
15957                            &always_inserted_mode, _("\
15958 Set mode for inserting breakpoints."), _("\
15959 Show mode for inserting breakpoints."), _("\
15960 When this mode is on, breakpoints are inserted immediately as soon as\n\
15961 they're created, kept inserted even when execution stops, and removed\n\
15962 only when the user deletes them.  When this mode is off (the default),\n\
15963 breakpoints are inserted only when execution continues, and removed\n\
15964 when execution stops."),
15965                                 NULL,
15966                                 &show_always_inserted_mode,
15967                                 &breakpoint_set_cmdlist,
15968                                 &breakpoint_show_cmdlist);
15969
15970   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15971                         condition_evaluation_enums,
15972                         &condition_evaluation_mode_1, _("\
15973 Set mode of breakpoint condition evaluation."), _("\
15974 Show mode of breakpoint condition evaluation."), _("\
15975 When this is set to \"host\", breakpoint conditions will be\n\
15976 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15977 breakpoint conditions will be downloaded to the target (if the target\n\
15978 supports such feature) and conditions will be evaluated on the target's side.\n\
15979 If this is set to \"auto\" (default), this will be automatically set to\n\
15980 \"target\" if it supports condition evaluation, otherwise it will\n\
15981 be set to \"host\"."),
15982                            &set_condition_evaluation_mode,
15983                            &show_condition_evaluation_mode,
15984                            &breakpoint_set_cmdlist,
15985                            &breakpoint_show_cmdlist);
15986
15987   add_com ("break-range", class_breakpoint, break_range_command, _("\
15988 Set a breakpoint for an address range.\n\
15989 break-range START-LOCATION, END-LOCATION\n\
15990 where START-LOCATION and END-LOCATION can be one of the following:\n\
15991   LINENUM, for that line in the current file,\n\
15992   FILE:LINENUM, for that line in that file,\n\
15993   +OFFSET, for that number of lines after the current line\n\
15994            or the start of the range\n\
15995   FUNCTION, for the first line in that function,\n\
15996   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15997   *ADDRESS, for the instruction at that address.\n\
15998 \n\
15999 The breakpoint will stop execution of the inferior whenever it executes\n\
16000 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16001 range (including START-LOCATION and END-LOCATION)."));
16002
16003   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16004 Set a dynamic printf at specified location.\n\
16005 dprintf location,format string,arg1,arg2,...\n\
16006 location may be a linespec, explicit, or address location.\n"
16007 "\n" LOCATION_HELP_STRING));
16008   set_cmd_completer (c, location_completer);
16009
16010   add_setshow_enum_cmd ("dprintf-style", class_support,
16011                         dprintf_style_enums, &dprintf_style, _("\
16012 Set the style of usage for dynamic printf."), _("\
16013 Show the style of usage for dynamic printf."), _("\
16014 This setting chooses how GDB will do a dynamic printf.\n\
16015 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16016 console, as with the \"printf\" command.\n\
16017 If the value is \"call\", the print is done by calling a function in your\n\
16018 program; by default printf(), but you can choose a different function or\n\
16019 output stream by setting dprintf-function and dprintf-channel."),
16020                         update_dprintf_commands, NULL,
16021                         &setlist, &showlist);
16022
16023   dprintf_function = xstrdup ("printf");
16024   add_setshow_string_cmd ("dprintf-function", class_support,
16025                           &dprintf_function, _("\
16026 Set the function to use for dynamic printf."), _("\
16027 Show the function to use for dynamic printf."), NULL,
16028                           update_dprintf_commands, NULL,
16029                           &setlist, &showlist);
16030
16031   dprintf_channel = xstrdup ("");
16032   add_setshow_string_cmd ("dprintf-channel", class_support,
16033                           &dprintf_channel, _("\
16034 Set the channel to use for dynamic printf."), _("\
16035 Show the channel to use for dynamic printf."), NULL,
16036                           update_dprintf_commands, NULL,
16037                           &setlist, &showlist);
16038
16039   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16040                            &disconnected_dprintf, _("\
16041 Set whether dprintf continues after GDB disconnects."), _("\
16042 Show whether dprintf continues after GDB disconnects."), _("\
16043 Use this to let dprintf commands continue to hit and produce output\n\
16044 even if GDB disconnects or detaches from the target."),
16045                            NULL,
16046                            NULL,
16047                            &setlist, &showlist);
16048
16049   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16050 Target agent only formatted printing, like the C \"printf\" function.\n\
16051 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
16052 This supports most C printf format specifications, like %s, %d, etc.\n\
16053 This is useful for formatted output in user-defined commands."));
16054
16055   automatic_hardware_breakpoints = true;
16056
16057   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
16058                                            "breakpoint");
16059   gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
16060                                       "breakpoint");
16061 }
This page took 0.945022 seconds and 4 git commands to generate.