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 #include "cli/cli-decode.h"
71 
72 /* readline include files */
73 #include "readline/tilde.h"
74 
75 /* readline defines this.  */
76 #undef savestring
77 
78 #include "mi/mi-common.h"
79 #include "extension.h"
80 #include <algorithm>
81 #include "progspace-and-thread.h"
82 #include "gdbsupport/array-view.h"
83 #include "gdbsupport/gdb_optional.h"
84 
85 /* Prototypes for local functions.  */
86 
87 static void map_breakpoint_numbers (const char *,
88 				    gdb::function_view<void (breakpoint *)>);
89 
90 static void breakpoint_re_set_default (struct breakpoint *);
91 
92 static void
93   create_sals_from_location_default (struct event_location *location,
94 				     struct linespec_result *canonical,
95 				     enum bptype type_wanted);
96 
97 static void create_breakpoints_sal_default (struct gdbarch *,
98 					    struct linespec_result *,
99 					    gdb::unique_xmalloc_ptr<char>,
100 					    gdb::unique_xmalloc_ptr<char>,
101 					    enum bptype,
102 					    enum bpdisp, int, int,
103 					    int,
104 					    const struct breakpoint_ops *,
105 					    int, int, int, unsigned);
106 
107 static std::vector<symtab_and_line> decode_location_default
108   (struct breakpoint *b, struct event_location *location,
109    struct program_space *search_pspace);
110 
111 static int can_use_hardware_watchpoint
112     (const std::vector<value_ref_ptr> &vals);
113 
114 static void mention (struct breakpoint *);
115 
116 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
117 							       enum bptype,
118 							       const struct breakpoint_ops *);
119 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
120 						       const struct symtab_and_line *);
121 
122 /* This function is used in gdbtk sources and thus can not be made
123    static.  */
124 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
125 				       struct symtab_and_line,
126 				       enum bptype,
127 				       const struct breakpoint_ops *);
128 
129 static struct breakpoint *
130   momentary_breakpoint_from_master (struct breakpoint *orig,
131 				    enum bptype type,
132 				    const struct breakpoint_ops *ops,
133 				    int loc_enabled);
134 
135 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
136 
137 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
138 					    CORE_ADDR bpaddr,
139 					    enum bptype bptype);
140 
141 static void describe_other_breakpoints (struct gdbarch *,
142 					struct program_space *, CORE_ADDR,
143 					struct obj_section *, int);
144 
145 static int watchpoint_locations_match (struct bp_location *loc1,
146 				       struct bp_location *loc2);
147 
148 static int breakpoint_locations_match (struct bp_location *loc1,
149 				       struct bp_location *loc2,
150 				       bool sw_hw_bps_match = false);
151 
152 static int breakpoint_location_address_match (struct bp_location *bl,
153 					      const struct address_space *aspace,
154 					      CORE_ADDR addr);
155 
156 static int breakpoint_location_address_range_overlap (struct bp_location *,
157 						      const address_space *,
158 						      CORE_ADDR, int);
159 
160 static int remove_breakpoint (struct bp_location *);
161 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
162 
163 static enum print_stop_action print_bp_stop_message (bpstat bs);
164 
165 static int hw_breakpoint_used_count (void);
166 
167 static int hw_watchpoint_use_count (struct breakpoint *);
168 
169 static int hw_watchpoint_used_count_others (struct breakpoint *except,
170 					    enum bptype type,
171 					    int *other_type_used);
172 
173 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
174 				    int count);
175 
176 static void decref_bp_location (struct bp_location **loc);
177 
178 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
179 
180 /* update_global_location_list's modes of operation wrt to whether to
181    insert locations now.  */
182 enum ugll_insert_mode
183 {
184   /* Don't insert any breakpoint locations into the inferior, only
185      remove already-inserted locations that no longer should be
186      inserted.  Functions that delete a breakpoint or breakpoints
187      should specify this mode, so that deleting a breakpoint doesn't
188      have the side effect of inserting the locations of other
189      breakpoints that are marked not-inserted, but should_be_inserted
190      returns true on them.
191 
192      This behavior is useful is situations close to tear-down -- e.g.,
193      after an exec, while the target still has execution, but
194      breakpoint shadows of the previous executable image should *NOT*
195      be restored to the new image; or before detaching, where the
196      target still has execution and wants to delete breakpoints from
197      GDB's lists, and all breakpoints had already been removed from
198      the inferior.  */
199   UGLL_DONT_INSERT,
200 
201   /* May insert breakpoints iff breakpoints_should_be_inserted_now
202      claims breakpoints should be inserted now.  */
203   UGLL_MAY_INSERT,
204 
205   /* Insert locations now, irrespective of
206      breakpoints_should_be_inserted_now.  E.g., say all threads are
207      stopped right now, and the user did "continue".  We need to
208      insert breakpoints _before_ resuming the target, but
209      UGLL_MAY_INSERT wouldn't insert them, because
210      breakpoints_should_be_inserted_now returns false at that point,
211      as no thread is running yet.  */
212   UGLL_INSERT
213 };
214 
215 static void update_global_location_list (enum ugll_insert_mode);
216 
217 static void update_global_location_list_nothrow (enum ugll_insert_mode);
218 
219 static void insert_breakpoint_locations (void);
220 
221 static void trace_pass_command (const char *, int);
222 
223 static void set_tracepoint_count (int num);
224 
225 static bool is_masked_watchpoint (const struct breakpoint *b);
226 
227 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
228    otherwise.  */
229 
230 static int strace_marker_p (struct breakpoint *b);
231 
232 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
233    that are implemented on top of software or hardware breakpoints
234    (user breakpoints, internal and momentary breakpoints, etc.).  */
235 static struct breakpoint_ops bkpt_base_breakpoint_ops;
236 
237 /* Internal breakpoints class type.  */
238 static struct breakpoint_ops internal_breakpoint_ops;
239 
240 /* Momentary breakpoints class type.  */
241 static struct breakpoint_ops momentary_breakpoint_ops;
242 
243 /* The breakpoint_ops structure to be used in regular user created
244    breakpoints.  */
245 struct breakpoint_ops bkpt_breakpoint_ops;
246 
247 /* Breakpoints set on probes.  */
248 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
249 
250 /* Tracepoints set on probes.  */
251 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
252 
253 /* Dynamic printf class type.  */
254 struct breakpoint_ops dprintf_breakpoint_ops;
255 
256 /* The style in which to perform a dynamic printf.  This is a user
257    option because different output options have different tradeoffs;
258    if GDB does the printing, there is better error handling if there
259    is a problem with any of the arguments, but using an inferior
260    function lets you have special-purpose printers and sending of
261    output to the same place as compiled-in print functions.  */
262 
263 static const char dprintf_style_gdb[] = "gdb";
264 static const char dprintf_style_call[] = "call";
265 static const char dprintf_style_agent[] = "agent";
266 static const char *const dprintf_style_enums[] = {
267   dprintf_style_gdb,
268   dprintf_style_call,
269   dprintf_style_agent,
270   NULL
271 };
272 static const char *dprintf_style = dprintf_style_gdb;
273 
274 /* The function to use for dynamic printf if the preferred style is to
275    call into the inferior.  The value is simply a string that is
276    copied into the command, so it can be anything that GDB can
277    evaluate to a callable address, not necessarily a function name.  */
278 
279 static char *dprintf_function;
280 
281 /* The channel to use for dynamic printf if the preferred style is to
282    call into the inferior; if a nonempty string, it will be passed to
283    the call as the first argument, with the format string as the
284    second.  As with the dprintf function, this can be anything that
285    GDB knows how to evaluate, so in addition to common choices like
286    "stderr", this could be an app-specific expression like
287    "mystreams[curlogger]".  */
288 
289 static char *dprintf_channel;
290 
291 /* True if dprintf commands should continue to operate even if GDB
292    has disconnected.  */
293 static bool disconnected_dprintf = true;
294 
295 struct command_line *
breakpoint_commands(struct breakpoint * b)296 breakpoint_commands (struct breakpoint *b)
297 {
298   return b->commands ? b->commands.get () : NULL;
299 }
300 
301 /* Flag indicating that a command has proceeded the inferior past the
302    current breakpoint.  */
303 
304 static bool breakpoint_proceeded;
305 
306 const char *
bpdisp_text(enum bpdisp disp)307 bpdisp_text (enum bpdisp disp)
308 {
309   /* NOTE: the following values are a part of MI protocol and
310      represent values of 'disp' field returned when inferior stops at
311      a breakpoint.  */
312   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
313 
314   return bpdisps[(int) disp];
315 }
316 
317 /* Prototypes for exported functions.  */
318 /* If FALSE, gdb will not use hardware support for watchpoints, even
319    if such is available.  */
320 static int can_use_hw_watchpoints;
321 
322 static void
show_can_use_hw_watchpoints(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)323 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
324 			     struct cmd_list_element *c,
325 			     const char *value)
326 {
327   fprintf_filtered (file,
328 		    _("Debugger's willingness to use "
329 		      "watchpoint hardware is %s.\n"),
330 		    value);
331 }
332 
333 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
334    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
335    for unrecognized breakpoint locations.
336    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
337 static enum auto_boolean pending_break_support;
338 static void
show_pending_break_support(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)339 show_pending_break_support (struct ui_file *file, int from_tty,
340 			    struct cmd_list_element *c,
341 			    const char *value)
342 {
343   fprintf_filtered (file,
344 		    _("Debugger's behavior regarding "
345 		      "pending breakpoints is %s.\n"),
346 		    value);
347 }
348 
349 /* If true, gdb will automatically use hardware breakpoints for breakpoints
350    set with "break" but falling in read-only memory.
351    If false, gdb will warn about such breakpoints, but won't automatically
352    use hardware breakpoints.  */
353 static bool automatic_hardware_breakpoints;
354 static void
show_automatic_hardware_breakpoints(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)355 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
356 				     struct cmd_list_element *c,
357 				     const char *value)
358 {
359   fprintf_filtered (file,
360 		    _("Automatic usage of hardware breakpoints is %s.\n"),
361 		    value);
362 }
363 
364 /* If on, GDB keeps breakpoints inserted even if the inferior is
365    stopped, and immediately inserts any new breakpoints as soon as
366    they're created.  If off (default), GDB keeps breakpoints off of
367    the target as long as possible.  That is, it delays inserting
368    breakpoints until the next resume, and removes them again when the
369    target fully stops.  This is a bit safer in case GDB crashes while
370    processing user input.  */
371 static bool always_inserted_mode = false;
372 
373 static void
show_always_inserted_mode(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)374 show_always_inserted_mode (struct ui_file *file, int from_tty,
375 		     struct cmd_list_element *c, const char *value)
376 {
377   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
378 		    value);
379 }
380 
381 /* See breakpoint.h.  */
382 
383 int
breakpoints_should_be_inserted_now(void)384 breakpoints_should_be_inserted_now (void)
385 {
386   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
387     {
388       /* If breakpoints are global, they should be inserted even if no
389 	 thread under gdb's control is running, or even if there are
390 	 no threads under GDB's control yet.  */
391       return 1;
392     }
393   else
394     {
395       if (always_inserted_mode)
396 	{
397 	  /* The user wants breakpoints inserted even if all threads
398 	     are stopped.  */
399 	  return 1;
400 	}
401 
402       for (inferior *inf : all_inferiors ())
403 	if (inf->has_execution ()
404 	    && threads_are_executing (inf->process_target ()))
405 	  return 1;
406 
407       /* Don't remove breakpoints yet if, even though all threads are
408 	 stopped, we still have events to process.  */
409       for (thread_info *tp : all_non_exited_threads ())
410 	if (tp->resumed
411 	    && tp->suspend.waitstatus_pending_p)
412 	  return 1;
413     }
414   return 0;
415 }
416 
417 static const char condition_evaluation_both[] = "host or target";
418 
419 /* Modes for breakpoint condition evaluation.  */
420 static const char condition_evaluation_auto[] = "auto";
421 static const char condition_evaluation_host[] = "host";
422 static const char condition_evaluation_target[] = "target";
423 static const char *const condition_evaluation_enums[] = {
424   condition_evaluation_auto,
425   condition_evaluation_host,
426   condition_evaluation_target,
427   NULL
428 };
429 
430 /* Global that holds the current mode for breakpoint condition evaluation.  */
431 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
432 
433 /* Global that we use to display information to the user (gets its value from
434    condition_evaluation_mode_1.  */
435 static const char *condition_evaluation_mode = condition_evaluation_auto;
436 
437 /* Translate a condition evaluation mode MODE into either "host"
438    or "target".  This is used mostly to translate from "auto" to the
439    real setting that is being used.  It returns the translated
440    evaluation mode.  */
441 
442 static const char *
translate_condition_evaluation_mode(const char * mode)443 translate_condition_evaluation_mode (const char *mode)
444 {
445   if (mode == condition_evaluation_auto)
446     {
447       if (target_supports_evaluation_of_breakpoint_conditions ())
448 	return condition_evaluation_target;
449       else
450 	return condition_evaluation_host;
451     }
452   else
453     return mode;
454 }
455 
456 /* Discovers what condition_evaluation_auto translates to.  */
457 
458 static const char *
breakpoint_condition_evaluation_mode(void)459 breakpoint_condition_evaluation_mode (void)
460 {
461   return translate_condition_evaluation_mode (condition_evaluation_mode);
462 }
463 
464 /* Return true if GDB should evaluate breakpoint conditions or false
465    otherwise.  */
466 
467 static int
gdb_evaluates_breakpoint_condition_p(void)468 gdb_evaluates_breakpoint_condition_p (void)
469 {
470   const char *mode = breakpoint_condition_evaluation_mode ();
471 
472   return (mode == condition_evaluation_host);
473 }
474 
475 /* Are we executing breakpoint commands?  */
476 static int executing_breakpoint_commands;
477 
478 /* Are overlay event breakpoints enabled? */
479 static int overlay_events_enabled;
480 
481 /* See description in breakpoint.h. */
482 bool target_exact_watchpoints = false;
483 
484 /* Walk the following statement or block through all breakpoints.
485    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
486    current breakpoint.  */
487 
488 #define ALL_BREAKPOINTS_SAFE(B,TMP)	\
489 	for (B = breakpoint_chain;	\
490 	     B ? (TMP=B->next, 1): 0;	\
491 	     B = TMP)
492 
493 /* Chains of all breakpoints defined.  */
494 
495 static struct breakpoint *breakpoint_chain;
496 
497 /* See breakpoint.h.  */
498 
499 breakpoint_range
all_breakpoints()500 all_breakpoints ()
501 {
502   return breakpoint_range (breakpoint_chain);
503 }
504 
505 /* See breakpoint.h.  */
506 
507 breakpoint_safe_range
all_breakpoints_safe()508 all_breakpoints_safe ()
509 {
510   return breakpoint_safe_range (all_breakpoints ());
511 }
512 
513 /* See breakpoint.h.  */
514 
515 tracepoint_range
all_tracepoints()516 all_tracepoints ()
517 {
518   return tracepoint_range (breakpoint_chain);
519 }
520 
521 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS.  */
522 
523 static std::vector<bp_location *> bp_locations;
524 
525 /* See breakpoint.h.  */
526 
527 const std::vector<bp_location *> &
all_bp_locations()528 all_bp_locations ()
529 {
530   return bp_locations;
531 }
532 
533 /* Range to iterate over breakpoint locations at a given address.  */
534 
535 struct bp_locations_at_addr_range
536 {
537   using iterator = std::vector<bp_location *>::iterator;
538 
bp_locations_at_addr_rangebp_locations_at_addr_range539   bp_locations_at_addr_range (CORE_ADDR addr)
540   {
541     struct compare
542     {
543       bool operator() (const bp_location *loc, CORE_ADDR addr_) const
544       { return loc->address < addr_; }
545 
546       bool operator() (CORE_ADDR addr_, const bp_location *loc) const
547       { return addr_ < loc->address; }
548     };
549 
550     auto it_pair = std::equal_range (bp_locations.begin (), bp_locations.end (),
551 				     addr, compare ());
552 
553     m_begin = it_pair.first;
554     m_end = it_pair.second;
555   }
556 
beginbp_locations_at_addr_range557   iterator begin () const
558   { return m_begin; }
559 
endbp_locations_at_addr_range560   iterator end () const
561   { return m_end; }
562 
563 private:
564   iterator m_begin;
565   iterator m_end;
566 };
567 
568 /* Return a range to iterate over all breakpoint locations exactly at address
569    ADDR.
570 
571    If it's needed to iterate multiple times on the same range, it's possible
572    to save the range in a local variable and use it multiple times:
573 
574      auto range = all_bp_locations_at_addr (addr);
575 
576      for (bp_location *loc : range)
577        // use loc
578 
579      for (bp_location *loc : range)
580        // use loc
581 
582    This saves a bit of time, as it avoids re-doing the binary searches to find
583    the range's boundaries.  Just remember not to change the bp_locations vector
584    in the mean time, as it could make the range's iterators stale.  */
585 
586 static bp_locations_at_addr_range
all_bp_locations_at_addr(CORE_ADDR addr)587 all_bp_locations_at_addr (CORE_ADDR addr)
588 {
589   return bp_locations_at_addr_range (addr);
590 }
591 
592 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
593    ADDRESS for the current elements of BP_LOCATIONS which get a valid
594    result from bp_location_has_shadow.  You can use it for roughly
595    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
596    an address you need to read.  */
597 
598 static CORE_ADDR bp_locations_placed_address_before_address_max;
599 
600 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
601    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
602    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
603    You can use it for roughly limiting the subrange of BP_LOCATIONS to
604    scan for shadow bytes for an address you need to read.  */
605 
606 static CORE_ADDR bp_locations_shadow_len_after_address_max;
607 
608 /* The locations that no longer correspond to any breakpoint, unlinked
609    from the bp_locations array, but for which a hit may still be
610    reported by a target.  */
611 static std::vector<bp_location *> moribund_locations;
612 
613 /* Number of last breakpoint made.  */
614 
615 static int breakpoint_count;
616 
617 /* The value of `breakpoint_count' before the last command that
618    created breakpoints.  If the last (break-like) command created more
619    than one breakpoint, then the difference between BREAKPOINT_COUNT
620    and PREV_BREAKPOINT_COUNT is more than one.  */
621 static int prev_breakpoint_count;
622 
623 /* Number of last tracepoint made.  */
624 
625 static int tracepoint_count;
626 
627 static struct cmd_list_element *breakpoint_set_cmdlist;
628 static struct cmd_list_element *breakpoint_show_cmdlist;
629 struct cmd_list_element *save_cmdlist;
630 
631 /* See declaration at breakpoint.h.  */
632 
633 struct breakpoint *
breakpoint_find_if(int (* func)(struct breakpoint * b,void * d),void * user_data)634 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
635 		    void *user_data)
636 {
637   for (breakpoint *b : all_breakpoints ())
638     if (func (b, user_data) != 0)
639       return b;
640 
641   return nullptr;
642 }
643 
644 /* Return whether a breakpoint is an active enabled breakpoint.  */
645 static int
breakpoint_enabled(struct breakpoint * b)646 breakpoint_enabled (struct breakpoint *b)
647 {
648   return (b->enable_state == bp_enabled);
649 }
650 
651 /* Set breakpoint count to NUM.  */
652 
653 static void
set_breakpoint_count(int num)654 set_breakpoint_count (int num)
655 {
656   prev_breakpoint_count = breakpoint_count;
657   breakpoint_count = num;
658   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
659 }
660 
661 /* Used by `start_rbreak_breakpoints' below, to record the current
662    breakpoint count before "rbreak" creates any breakpoint.  */
663 static int rbreak_start_breakpoint_count;
664 
665 /* Called at the start an "rbreak" command to record the first
666    breakpoint made.  */
667 
scoped_rbreak_breakpoints()668 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
669 {
670   rbreak_start_breakpoint_count = breakpoint_count;
671 }
672 
673 /* Called at the end of an "rbreak" command to record the last
674    breakpoint made.  */
675 
~scoped_rbreak_breakpoints()676 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
677 {
678   prev_breakpoint_count = rbreak_start_breakpoint_count;
679 }
680 
681 /* Used in run_command to zero the hit count when a new run starts.  */
682 
683 void
clear_breakpoint_hit_counts(void)684 clear_breakpoint_hit_counts (void)
685 {
686   for (breakpoint *b : all_breakpoints ())
687     b->hit_count = 0;
688 }
689 
690 
691 /* Return the breakpoint with the specified number, or NULL
692    if the number does not refer to an existing breakpoint.  */
693 
694 struct breakpoint *
get_breakpoint(int num)695 get_breakpoint (int num)
696 {
697   for (breakpoint *b : all_breakpoints ())
698     if (b->number == num)
699       return b;
700 
701   return nullptr;
702 }
703 
704 
705 
706 /* Mark locations as "conditions have changed" in case the target supports
707    evaluating conditions on its side.  */
708 
709 static void
mark_breakpoint_modified(struct breakpoint * b)710 mark_breakpoint_modified (struct breakpoint *b)
711 {
712   /* This is only meaningful if the target is
713      evaluating conditions and if the user has
714      opted for condition evaluation on the target's
715      side.  */
716   if (gdb_evaluates_breakpoint_condition_p ()
717       || !target_supports_evaluation_of_breakpoint_conditions ())
718     return;
719 
720   if (!is_breakpoint (b))
721     return;
722 
723   for (bp_location *loc : b->locations ())
724     loc->condition_changed = condition_modified;
725 }
726 
727 /* Mark location as "conditions have changed" in case the target supports
728    evaluating conditions on its side.  */
729 
730 static void
mark_breakpoint_location_modified(struct bp_location * loc)731 mark_breakpoint_location_modified (struct bp_location *loc)
732 {
733   /* This is only meaningful if the target is
734      evaluating conditions and if the user has
735      opted for condition evaluation on the target's
736      side.  */
737   if (gdb_evaluates_breakpoint_condition_p ()
738       || !target_supports_evaluation_of_breakpoint_conditions ())
739 
740     return;
741 
742   if (!is_breakpoint (loc->owner))
743     return;
744 
745   loc->condition_changed = condition_modified;
746 }
747 
748 /* Sets the condition-evaluation mode using the static global
749    condition_evaluation_mode.  */
750 
751 static void
set_condition_evaluation_mode(const char * args,int from_tty,struct cmd_list_element * c)752 set_condition_evaluation_mode (const char *args, int from_tty,
753 			       struct cmd_list_element *c)
754 {
755   const char *old_mode, *new_mode;
756 
757   if ((condition_evaluation_mode_1 == condition_evaluation_target)
758       && !target_supports_evaluation_of_breakpoint_conditions ())
759     {
760       condition_evaluation_mode_1 = condition_evaluation_mode;
761       warning (_("Target does not support breakpoint condition evaluation.\n"
762 		 "Using host evaluation mode instead."));
763       return;
764     }
765 
766   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
767   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
768 
769   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
770      settings was "auto".  */
771   condition_evaluation_mode = condition_evaluation_mode_1;
772 
773   /* Only update the mode if the user picked a different one.  */
774   if (new_mode != old_mode)
775     {
776       /* If the user switched to a different evaluation mode, we
777 	 need to synch the changes with the target as follows:
778 
779 	 "host" -> "target": Send all (valid) conditions to the target.
780 	 "target" -> "host": Remove all the conditions from the target.
781       */
782 
783       if (new_mode == condition_evaluation_target)
784 	{
785 	  /* Mark everything modified and synch conditions with the
786 	     target.  */
787 	  for (bp_location *loc : all_bp_locations ())
788 	    mark_breakpoint_location_modified (loc);
789 	}
790       else
791 	{
792 	  /* Manually mark non-duplicate locations to synch conditions
793 	     with the target.  We do this to remove all the conditions the
794 	     target knows about.  */
795 	  for (bp_location *loc : all_bp_locations ())
796 	    if (is_breakpoint (loc->owner) && loc->inserted)
797 	      loc->needs_update = 1;
798 	}
799 
800       /* Do the update.  */
801       update_global_location_list (UGLL_MAY_INSERT);
802     }
803 
804   return;
805 }
806 
807 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
808    what "auto" is translating to.  */
809 
810 static void
show_condition_evaluation_mode(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)811 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
812 				struct cmd_list_element *c, const char *value)
813 {
814   if (condition_evaluation_mode == condition_evaluation_auto)
815     fprintf_filtered (file,
816 		      _("Breakpoint condition evaluation "
817 			"mode is %s (currently %s).\n"),
818 		      value,
819 		      breakpoint_condition_evaluation_mode ());
820   else
821     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
822 		      value);
823 }
824 
825 /* Parse COND_STRING in the context of LOC and set as the condition
826    expression of LOC.  BP_NUM is the number of LOC's owner, LOC_NUM is
827    the number of LOC within its owner.  In case of parsing error, mark
828    LOC as DISABLED_BY_COND.  In case of success, unset DISABLED_BY_COND.  */
829 
830 static void
set_breakpoint_location_condition(const char * cond_string,bp_location * loc,int bp_num,int loc_num)831 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
832 				   int bp_num, int loc_num)
833 {
834   bool has_junk = false;
835   try
836     {
837       expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
838 					   block_for_pc (loc->address), 0);
839       if (*cond_string != 0)
840 	has_junk = true;
841       else
842 	{
843 	  loc->cond = std::move (new_exp);
844 	  if (loc->disabled_by_cond && loc->enabled)
845 	    printf_filtered (_("Breakpoint %d's condition is now valid at "
846 			       "location %d, enabling.\n"),
847 			     bp_num, loc_num);
848 
849 	  loc->disabled_by_cond = false;
850 	}
851     }
852   catch (const gdb_exception_error &e)
853     {
854       if (loc->enabled)
855 	{
856 	  /* Warn if a user-enabled location is now becoming disabled-by-cond.
857 	     BP_NUM is 0 if the breakpoint is being defined for the first
858 	     time using the "break ... if ..." command, and non-zero if
859 	     already defined.  */
860 	  if (bp_num != 0)
861 	    warning (_("failed to validate condition at location %d.%d, "
862 		       "disabling:\n  %s"), bp_num, loc_num, e.what ());
863 	  else
864 	    warning (_("failed to validate condition at location %d, "
865 		       "disabling:\n  %s"), loc_num, e.what ());
866 	}
867 
868       loc->disabled_by_cond = true;
869     }
870 
871   if (has_junk)
872     error (_("Garbage '%s' follows condition"), cond_string);
873 }
874 
875 void
set_breakpoint_condition(struct breakpoint * b,const char * exp,int from_tty,bool force)876 set_breakpoint_condition (struct breakpoint *b, const char *exp,
877 			  int from_tty, bool force)
878 {
879   if (*exp == 0)
880     {
881       xfree (b->cond_string);
882       b->cond_string = nullptr;
883 
884       if (is_watchpoint (b))
885 	static_cast<watchpoint *> (b)->cond_exp.reset ();
886       else
887 	{
888 	  int loc_num = 1;
889 	  for (bp_location *loc : b->locations ())
890 	    {
891 	      loc->cond.reset ();
892 	      if (loc->disabled_by_cond && loc->enabled)
893 		printf_filtered (_("Breakpoint %d's condition is now valid at "
894 				   "location %d, enabling.\n"),
895 				 b->number, loc_num);
896 	      loc->disabled_by_cond = false;
897 	      loc_num++;
898 
899 	      /* No need to free the condition agent expression
900 		 bytecode (if we have one).  We will handle this
901 		 when we go through update_global_location_list.  */
902 	    }
903 	}
904 
905       if (from_tty)
906 	printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
907     }
908   else
909     {
910       if (is_watchpoint (b))
911 	{
912 	  innermost_block_tracker tracker;
913 	  const char *arg = exp;
914 	  expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
915 	  if (*arg != 0)
916 	    error (_("Junk at end of expression"));
917 	  watchpoint *w = static_cast<watchpoint *> (b);
918 	  w->cond_exp = std::move (new_exp);
919 	  w->cond_exp_valid_block = tracker.block ();
920 	}
921       else
922 	{
923 	  /* Parse and set condition expressions.  We make two passes.
924 	     In the first, we parse the condition string to see if it
925 	     is valid in at least one location.  If so, the condition
926 	     would be accepted.  So we go ahead and set the locations'
927 	     conditions.  In case no valid case is found, we throw
928 	     the error and the condition string will be rejected.
929 	     This two-pass approach is taken to avoid setting the
930 	     state of locations in case of a reject.  */
931 	  for (bp_location *loc : b->locations ())
932 	    {
933 	      try
934 		{
935 		  const char *arg = exp;
936 		  parse_exp_1 (&arg, loc->address,
937 			       block_for_pc (loc->address), 0);
938 		  if (*arg != 0)
939 		    error (_("Junk at end of expression"));
940 		  break;
941 		}
942 	      catch (const gdb_exception_error &e)
943 		{
944 		  /* Condition string is invalid.  If this happens to
945 		     be the last loc, abandon (if not forced) or continue
946 		     (if forced).  */
947 		  if (loc->next == nullptr && !force)
948 		    throw;
949 		}
950 	    }
951 
952 	  /* If we reach here, the condition is valid at some locations.  */
953 	  int loc_num = 1;
954 	  for (bp_location *loc : b->locations ())
955 	    {
956 	      set_breakpoint_location_condition (exp, loc, b->number, loc_num);
957 	      loc_num++;
958 	    }
959 	}
960 
961       /* We know that the new condition parsed successfully.  The
962 	 condition string of the breakpoint can be safely updated.  */
963       xfree (b->cond_string);
964       b->cond_string = xstrdup (exp);
965       b->condition_not_parsed = 0;
966     }
967   mark_breakpoint_modified (b);
968 
969   gdb::observers::breakpoint_modified.notify (b);
970 }
971 
972 /* See breakpoint.h.  */
973 
974 void
set_breakpoint_condition(int bpnum,const char * exp,int from_tty,bool force)975 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
976 			  bool force)
977 {
978   for (breakpoint *b : all_breakpoints ())
979     if (b->number == bpnum)
980       {
981 	/* Check if this breakpoint has a "stop" method implemented in an
982 	   extension language.  This method and conditions entered into GDB
983 	   from the CLI are mutually exclusive.  */
984 	const struct extension_language_defn *extlang
985 	  = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
986 
987 	if (extlang != NULL)
988 	  {
989 	    error (_("Only one stop condition allowed.  There is currently"
990 		     " a %s stop condition defined for this breakpoint."),
991 		   ext_lang_capitalized_name (extlang));
992 	  }
993 	set_breakpoint_condition (b, exp, from_tty, force);
994 
995 	if (is_breakpoint (b))
996 	  update_global_location_list (UGLL_MAY_INSERT);
997 
998 	return;
999       }
1000 
1001   error (_("No breakpoint number %d."), bpnum);
1002 }
1003 
1004 /* The options for the "condition" command.  */
1005 
1006 struct condition_command_opts
1007 {
1008   /* For "-force".  */
1009   bool force_condition = false;
1010 };
1011 
1012 static const gdb::option::option_def condition_command_option_defs[] = {
1013 
1014   gdb::option::flag_option_def<condition_command_opts> {
1015     "force",
1016     [] (condition_command_opts *opts) { return &opts->force_condition; },
1017     N_("Set the condition even if it is invalid for all current locations."),
1018   },
1019 
1020 };
1021 
1022 /* Create an option_def_group for the "condition" options, with
1023    CC_OPTS as context.  */
1024 
1025 static inline gdb::option::option_def_group
make_condition_command_options_def_group(condition_command_opts * cc_opts)1026 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1027 {
1028   return {{condition_command_option_defs}, cc_opts};
1029 }
1030 
1031 /* Completion for the "condition" command.  */
1032 
1033 static void
condition_completer(struct cmd_list_element * cmd,completion_tracker & tracker,const char * text,const char *)1034 condition_completer (struct cmd_list_element *cmd,
1035 		     completion_tracker &tracker,
1036 		     const char *text, const char * /*word*/)
1037 {
1038   bool has_no_arguments = (*text == '\0');
1039   condition_command_opts cc_opts;
1040   const auto group = make_condition_command_options_def_group (&cc_opts);
1041   if (gdb::option::complete_options
1042       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1043     return;
1044 
1045   text = skip_spaces (text);
1046   const char *space = skip_to_space (text);
1047   if (*space == '\0')
1048     {
1049       int len;
1050 
1051       if (text[0] == '$')
1052 	{
1053 	  tracker.advance_custom_word_point_by (1);
1054 	  /* We don't support completion of history indices.  */
1055 	  if (!isdigit (text[1]))
1056 	    complete_internalvar (tracker, &text[1]);
1057 	  return;
1058 	}
1059 
1060       /* Suggest the "-force" flag if no arguments are given.  If
1061 	 arguments were passed, they either already include the flag,
1062 	 or we are beyond the point of suggesting it because it's
1063 	 positionally the first argument.  */
1064       if (has_no_arguments)
1065 	gdb::option::complete_on_all_options (tracker, group);
1066 
1067       /* We're completing the breakpoint number.  */
1068       len = strlen (text);
1069 
1070       for (breakpoint *b : all_breakpoints ())
1071 	{
1072 	  char number[50];
1073 
1074 	  xsnprintf (number, sizeof (number), "%d", b->number);
1075 
1076 	  if (strncmp (number, text, len) == 0)
1077 	    tracker.add_completion (make_unique_xstrdup (number));
1078 	}
1079 
1080       return;
1081     }
1082 
1083   /* We're completing the expression part.  Skip the breakpoint num.  */
1084   const char *exp_start = skip_spaces (space);
1085   tracker.advance_custom_word_point_by (exp_start - text);
1086   text = exp_start;
1087   const char *word = advance_to_expression_complete_word_point (tracker, text);
1088   expression_completer (cmd, tracker, text, word);
1089 }
1090 
1091 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1092 
1093 static void
condition_command(const char * arg,int from_tty)1094 condition_command (const char *arg, int from_tty)
1095 {
1096   const char *p;
1097   int bnum;
1098 
1099   if (arg == 0)
1100     error_no_arg (_("breakpoint number"));
1101 
1102   p = arg;
1103 
1104   /* Check if the "-force" flag was passed.  */
1105   condition_command_opts cc_opts;
1106   const auto group = make_condition_command_options_def_group (&cc_opts);
1107   gdb::option::process_options
1108     (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1109 
1110   bnum = get_number (&p);
1111   if (bnum == 0)
1112     error (_("Bad breakpoint argument: '%s'"), arg);
1113 
1114   set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1115 }
1116 
1117 /* Check that COMMAND do not contain commands that are suitable
1118    only for tracepoints and not suitable for ordinary breakpoints.
1119    Throw if any such commands is found.  */
1120 
1121 static void
check_no_tracepoint_commands(struct command_line * commands)1122 check_no_tracepoint_commands (struct command_line *commands)
1123 {
1124   struct command_line *c;
1125 
1126   for (c = commands; c; c = c->next)
1127     {
1128       if (c->control_type == while_stepping_control)
1129 	error (_("The 'while-stepping' command can "
1130 		 "only be used for tracepoints"));
1131 
1132       check_no_tracepoint_commands (c->body_list_0.get ());
1133       check_no_tracepoint_commands (c->body_list_1.get ());
1134 
1135       /* Not that command parsing removes leading whitespace and comment
1136 	 lines and also empty lines.  So, we only need to check for
1137 	 command directly.  */
1138       if (strstr (c->line, "collect ") == c->line)
1139 	error (_("The 'collect' command can only be used for tracepoints"));
1140 
1141       if (strstr (c->line, "teval ") == c->line)
1142 	error (_("The 'teval' command can only be used for tracepoints"));
1143     }
1144 }
1145 
1146 struct longjmp_breakpoint : public breakpoint
1147 {
1148   ~longjmp_breakpoint () override;
1149 };
1150 
1151 /* Encapsulate tests for different types of tracepoints.  */
1152 
1153 static bool
is_tracepoint_type(bptype type)1154 is_tracepoint_type (bptype type)
1155 {
1156   return (type == bp_tracepoint
1157 	  || type == bp_fast_tracepoint
1158 	  || type == bp_static_tracepoint);
1159 }
1160 
1161 static bool
is_longjmp_type(bptype type)1162 is_longjmp_type (bptype type)
1163 {
1164   return type == bp_longjmp || type == bp_exception;
1165 }
1166 
1167 /* See breakpoint.h.  */
1168 
1169 bool
is_tracepoint(const struct breakpoint * b)1170 is_tracepoint (const struct breakpoint *b)
1171 {
1172   return is_tracepoint_type (b->type);
1173 }
1174 
1175 /* Factory function to create an appropriate instance of breakpoint given
1176    TYPE.  */
1177 
1178 static std::unique_ptr<breakpoint>
new_breakpoint_from_type(bptype type)1179 new_breakpoint_from_type (bptype type)
1180 {
1181   breakpoint *b;
1182 
1183   if (is_tracepoint_type (type))
1184     b = new tracepoint ();
1185   else if (is_longjmp_type (type))
1186     b = new longjmp_breakpoint ();
1187   else
1188     b = new breakpoint ();
1189 
1190   return std::unique_ptr<breakpoint> (b);
1191 }
1192 
1193 /* A helper function that validates that COMMANDS are valid for a
1194    breakpoint.  This function will throw an exception if a problem is
1195    found.  */
1196 
1197 static void
validate_commands_for_breakpoint(struct breakpoint * b,struct command_line * commands)1198 validate_commands_for_breakpoint (struct breakpoint *b,
1199 				  struct command_line *commands)
1200 {
1201   if (is_tracepoint (b))
1202     {
1203       struct tracepoint *t = (struct tracepoint *) b;
1204       struct command_line *c;
1205       struct command_line *while_stepping = 0;
1206 
1207       /* Reset the while-stepping step count.  The previous commands
1208 	 might have included a while-stepping action, while the new
1209 	 ones might not.  */
1210       t->step_count = 0;
1211 
1212       /* We need to verify that each top-level element of commands is
1213 	 valid for tracepoints, that there's at most one
1214 	 while-stepping element, and that the while-stepping's body
1215 	 has valid tracing commands excluding nested while-stepping.
1216 	 We also need to validate the tracepoint action line in the
1217 	 context of the tracepoint --- validate_actionline actually
1218 	 has side effects, like setting the tracepoint's
1219 	 while-stepping STEP_COUNT, in addition to checking if the
1220 	 collect/teval actions parse and make sense in the
1221 	 tracepoint's context.  */
1222       for (c = commands; c; c = c->next)
1223 	{
1224 	  if (c->control_type == while_stepping_control)
1225 	    {
1226 	      if (b->type == bp_fast_tracepoint)
1227 		error (_("The 'while-stepping' command "
1228 			 "cannot be used for fast tracepoint"));
1229 	      else if (b->type == bp_static_tracepoint)
1230 		error (_("The 'while-stepping' command "
1231 			 "cannot be used for static tracepoint"));
1232 
1233 	      if (while_stepping)
1234 		error (_("The 'while-stepping' command "
1235 			 "can be used only once"));
1236 	      else
1237 		while_stepping = c;
1238 	    }
1239 
1240 	  validate_actionline (c->line, b);
1241 	}
1242       if (while_stepping)
1243 	{
1244 	  struct command_line *c2;
1245 
1246 	  gdb_assert (while_stepping->body_list_1 == nullptr);
1247 	  c2 = while_stepping->body_list_0.get ();
1248 	  for (; c2; c2 = c2->next)
1249 	    {
1250 	      if (c2->control_type == while_stepping_control)
1251 		error (_("The 'while-stepping' command cannot be nested"));
1252 	    }
1253 	}
1254     }
1255   else
1256     {
1257       check_no_tracepoint_commands (commands);
1258     }
1259 }
1260 
1261 /* Return a vector of all the static tracepoints set at ADDR.  The
1262    caller is responsible for releasing the vector.  */
1263 
1264 std::vector<breakpoint *>
static_tracepoints_here(CORE_ADDR addr)1265 static_tracepoints_here (CORE_ADDR addr)
1266 {
1267   std::vector<breakpoint *> found;
1268 
1269   for (breakpoint *b : all_breakpoints ())
1270     if (b->type == bp_static_tracepoint)
1271       {
1272 	for (bp_location *loc : b->locations ())
1273 	  if (loc->address == addr)
1274 	    found.push_back (b);
1275       }
1276 
1277   return found;
1278 }
1279 
1280 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1281    validate that only allowed commands are included.  */
1282 
1283 void
breakpoint_set_commands(struct breakpoint * b,counted_command_line && commands)1284 breakpoint_set_commands (struct breakpoint *b,
1285 			 counted_command_line &&commands)
1286 {
1287   validate_commands_for_breakpoint (b, commands.get ());
1288 
1289   b->commands = std::move (commands);
1290   gdb::observers::breakpoint_modified.notify (b);
1291 }
1292 
1293 /* Set the internal `silent' flag on the breakpoint.  Note that this
1294    is not the same as the "silent" that may appear in the breakpoint's
1295    commands.  */
1296 
1297 void
breakpoint_set_silent(struct breakpoint * b,int silent)1298 breakpoint_set_silent (struct breakpoint *b, int silent)
1299 {
1300   int old_silent = b->silent;
1301 
1302   b->silent = silent;
1303   if (old_silent != silent)
1304     gdb::observers::breakpoint_modified.notify (b);
1305 }
1306 
1307 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1308    breakpoint work for any thread.  */
1309 
1310 void
breakpoint_set_thread(struct breakpoint * b,int thread)1311 breakpoint_set_thread (struct breakpoint *b, int thread)
1312 {
1313   int old_thread = b->thread;
1314 
1315   b->thread = thread;
1316   if (old_thread != thread)
1317     gdb::observers::breakpoint_modified.notify (b);
1318 }
1319 
1320 /* Set the task for this breakpoint.  If TASK is 0, make the
1321    breakpoint work for any task.  */
1322 
1323 void
breakpoint_set_task(struct breakpoint * b,int task)1324 breakpoint_set_task (struct breakpoint *b, int task)
1325 {
1326   int old_task = b->task;
1327 
1328   b->task = task;
1329   if (old_task != task)
1330     gdb::observers::breakpoint_modified.notify (b);
1331 }
1332 
1333 static void
commands_command_1(const char * arg,int from_tty,struct command_line * control)1334 commands_command_1 (const char *arg, int from_tty,
1335 		    struct command_line *control)
1336 {
1337   counted_command_line cmd;
1338   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1339      NULL after the call to read_command_lines if the user provides an empty
1340      list of command by just typing "end".  */
1341   bool cmd_read = false;
1342 
1343   std::string new_arg;
1344 
1345   if (arg == NULL || !*arg)
1346     {
1347       /* Argument not explicitly given.  Synthesize it.  */
1348       if (breakpoint_count - prev_breakpoint_count > 1)
1349 	new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1350 				 breakpoint_count);
1351       else if (breakpoint_count > 0)
1352 	new_arg = string_printf ("%d", breakpoint_count);
1353     }
1354   else
1355     {
1356       /* Create a copy of ARG.  This is needed because the "commands"
1357 	 command may be coming from a script.  In that case, the read
1358 	 line buffer is going to be overwritten in the lambda of
1359 	 'map_breakpoint_numbers' below when reading the next line
1360 	 before we are are done parsing the breakpoint numbers.  */
1361       new_arg = arg;
1362     }
1363   arg = new_arg.c_str ();
1364 
1365   map_breakpoint_numbers
1366     (arg, [&] (breakpoint *b)
1367      {
1368        if (!cmd_read)
1369 	 {
1370 	   gdb_assert (cmd == NULL);
1371 	   if (control != NULL)
1372 	     cmd = control->body_list_0;
1373 	   else
1374 	     {
1375 	       std::string str
1376 		 = string_printf (_("Type commands for breakpoint(s) "
1377 				    "%s, one per line."),
1378 				  arg);
1379 
1380 	       auto do_validate = [=] (const char *line)
1381 				  {
1382 				    validate_actionline (line, b);
1383 				  };
1384 	       gdb::function_view<void (const char *)> validator;
1385 	       if (is_tracepoint (b))
1386 		 validator = do_validate;
1387 
1388 	       cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1389 	     }
1390 	   cmd_read = true;
1391 	 }
1392 
1393        /* If a breakpoint was on the list more than once, we don't need to
1394 	  do anything.  */
1395        if (b->commands != cmd)
1396 	 {
1397 	   validate_commands_for_breakpoint (b, cmd.get ());
1398 	   b->commands = cmd;
1399 	   gdb::observers::breakpoint_modified.notify (b);
1400 	 }
1401      });
1402 }
1403 
1404 static void
commands_command(const char * arg,int from_tty)1405 commands_command (const char *arg, int from_tty)
1406 {
1407   commands_command_1 (arg, from_tty, NULL);
1408 }
1409 
1410 /* Like commands_command, but instead of reading the commands from
1411    input stream, takes them from an already parsed command structure.
1412 
1413    This is used by cli-script.c to DTRT with breakpoint commands
1414    that are part of if and while bodies.  */
1415 enum command_control_type
commands_from_control_command(const char * arg,struct command_line * cmd)1416 commands_from_control_command (const char *arg, struct command_line *cmd)
1417 {
1418   commands_command_1 (arg, 0, cmd);
1419   return simple_control;
1420 }
1421 
1422 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1423 
1424 static int
bp_location_has_shadow(struct bp_location * bl)1425 bp_location_has_shadow (struct bp_location *bl)
1426 {
1427   if (bl->loc_type != bp_loc_software_breakpoint)
1428     return 0;
1429   if (!bl->inserted)
1430     return 0;
1431   if (bl->target_info.shadow_len == 0)
1432     /* BL isn't valid, or doesn't shadow memory.  */
1433     return 0;
1434   return 1;
1435 }
1436 
1437 /* Update BUF, which is LEN bytes read from the target address
1438    MEMADDR, by replacing a memory breakpoint with its shadowed
1439    contents.
1440 
1441    If READBUF is not NULL, this buffer must not overlap with the of
1442    the breakpoint location's shadow_contents buffer.  Otherwise, a
1443    failed assertion internal error will be raised.  */
1444 
1445 static void
one_breakpoint_xfer_memory(gdb_byte * readbuf,gdb_byte * writebuf,const gdb_byte * writebuf_org,ULONGEST memaddr,LONGEST len,struct bp_target_info * target_info,struct gdbarch * gdbarch)1446 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1447 			    const gdb_byte *writebuf_org,
1448 			    ULONGEST memaddr, LONGEST len,
1449 			    struct bp_target_info *target_info,
1450 			    struct gdbarch *gdbarch)
1451 {
1452   /* Now do full processing of the found relevant range of elements.  */
1453   CORE_ADDR bp_addr = 0;
1454   int bp_size = 0;
1455   int bptoffset = 0;
1456 
1457   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1458 				 current_program_space->aspace, 0))
1459     {
1460       /* The breakpoint is inserted in a different address space.  */
1461       return;
1462     }
1463 
1464   /* Addresses and length of the part of the breakpoint that
1465      we need to copy.  */
1466   bp_addr = target_info->placed_address;
1467   bp_size = target_info->shadow_len;
1468 
1469   if (bp_addr + bp_size <= memaddr)
1470     {
1471       /* The breakpoint is entirely before the chunk of memory we are
1472 	 reading.  */
1473       return;
1474     }
1475 
1476   if (bp_addr >= memaddr + len)
1477     {
1478       /* The breakpoint is entirely after the chunk of memory we are
1479 	 reading.  */
1480       return;
1481     }
1482 
1483   /* Offset within shadow_contents.  */
1484   if (bp_addr < memaddr)
1485     {
1486       /* Only copy the second part of the breakpoint.  */
1487       bp_size -= memaddr - bp_addr;
1488       bptoffset = memaddr - bp_addr;
1489       bp_addr = memaddr;
1490     }
1491 
1492   if (bp_addr + bp_size > memaddr + len)
1493     {
1494       /* Only copy the first part of the breakpoint.  */
1495       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1496     }
1497 
1498   if (readbuf != NULL)
1499     {
1500       /* Verify that the readbuf buffer does not overlap with the
1501 	 shadow_contents buffer.  */
1502       gdb_assert (target_info->shadow_contents >= readbuf + len
1503 		  || readbuf >= (target_info->shadow_contents
1504 				 + target_info->shadow_len));
1505 
1506       /* Update the read buffer with this inserted breakpoint's
1507 	 shadow.  */
1508       memcpy (readbuf + bp_addr - memaddr,
1509 	      target_info->shadow_contents + bptoffset, bp_size);
1510     }
1511   else
1512     {
1513       const unsigned char *bp;
1514       CORE_ADDR addr = target_info->reqstd_address;
1515       int placed_size;
1516 
1517       /* Update the shadow with what we want to write to memory.  */
1518       memcpy (target_info->shadow_contents + bptoffset,
1519 	      writebuf_org + bp_addr - memaddr, bp_size);
1520 
1521       /* Determine appropriate breakpoint contents and size for this
1522 	 address.  */
1523       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1524 
1525       /* Update the final write buffer with this inserted
1526 	 breakpoint's INSN.  */
1527       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1528     }
1529 }
1530 
1531 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1532    by replacing any memory breakpoints with their shadowed contents.
1533 
1534    If READBUF is not NULL, this buffer must not overlap with any of
1535    the breakpoint location's shadow_contents buffers.  Otherwise,
1536    a failed assertion internal error will be raised.
1537 
1538    The range of shadowed area by each bp_location is:
1539      bl->address - bp_locations_placed_address_before_address_max
1540      up to bl->address + bp_locations_shadow_len_after_address_max
1541    The range we were requested to resolve shadows for is:
1542      memaddr ... memaddr + len
1543    Thus the safe cutoff boundaries for performance optimization are
1544      memaddr + len <= (bl->address
1545 		       - bp_locations_placed_address_before_address_max)
1546    and:
1547      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1548 
1549 void
breakpoint_xfer_memory(gdb_byte * readbuf,gdb_byte * writebuf,const gdb_byte * writebuf_org,ULONGEST memaddr,LONGEST len)1550 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1551 			const gdb_byte *writebuf_org,
1552 			ULONGEST memaddr, LONGEST len)
1553 {
1554   /* Left boundary, right boundary and median element of our binary
1555      search.  */
1556   unsigned bc_l, bc_r, bc;
1557 
1558   /* Find BC_L which is a leftmost element which may affect BUF
1559      content.  It is safe to report lower value but a failure to
1560      report higher one.  */
1561 
1562   bc_l = 0;
1563   bc_r = bp_locations.size ();
1564   while (bc_l + 1 < bc_r)
1565     {
1566       struct bp_location *bl;
1567 
1568       bc = (bc_l + bc_r) / 2;
1569       bl = bp_locations[bc];
1570 
1571       /* Check first BL->ADDRESS will not overflow due to the added
1572 	 constant.  Then advance the left boundary only if we are sure
1573 	 the BC element can in no way affect the BUF content (MEMADDR
1574 	 to MEMADDR + LEN range).
1575 
1576 	 Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1577 	 offset so that we cannot miss a breakpoint with its shadow
1578 	 range tail still reaching MEMADDR.  */
1579 
1580       if ((bl->address + bp_locations_shadow_len_after_address_max
1581 	   >= bl->address)
1582 	  && (bl->address + bp_locations_shadow_len_after_address_max
1583 	      <= memaddr))
1584 	bc_l = bc;
1585       else
1586 	bc_r = bc;
1587     }
1588 
1589   /* Due to the binary search above, we need to make sure we pick the
1590      first location that's at BC_L's address.  E.g., if there are
1591      multiple locations at the same address, BC_L may end up pointing
1592      at a duplicate location, and miss the "master"/"inserted"
1593      location.  Say, given locations L1, L2 and L3 at addresses A and
1594      B:
1595 
1596       L1@A, L2@A, L3@B, ...
1597 
1598      BC_L could end up pointing at location L2, while the "master"
1599      location could be L1.  Since the `loc->inserted' flag is only set
1600      on "master" locations, we'd forget to restore the shadow of L1
1601      and L2.  */
1602   while (bc_l > 0
1603 	 && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1604     bc_l--;
1605 
1606   /* Now do full processing of the found relevant range of elements.  */
1607 
1608   for (bc = bc_l; bc < bp_locations.size (); bc++)
1609     {
1610       struct bp_location *bl = bp_locations[bc];
1611 
1612       /* bp_location array has BL->OWNER always non-NULL.  */
1613       if (bl->owner->type == bp_none)
1614 	warning (_("reading through apparently deleted breakpoint #%d?"),
1615 		 bl->owner->number);
1616 
1617       /* Performance optimization: any further element can no longer affect BUF
1618 	 content.  */
1619 
1620       if (bl->address >= bp_locations_placed_address_before_address_max
1621 	  && (memaddr + len
1622 	      <= (bl->address
1623 		  - bp_locations_placed_address_before_address_max)))
1624 	break;
1625 
1626       if (!bp_location_has_shadow (bl))
1627 	continue;
1628 
1629       one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1630 				  memaddr, len, &bl->target_info, bl->gdbarch);
1631     }
1632 }
1633 
1634 /* See breakpoint.h.  */
1635 
1636 bool
is_breakpoint(const struct breakpoint * bpt)1637 is_breakpoint (const struct breakpoint *bpt)
1638 {
1639   return (bpt->type == bp_breakpoint
1640 	  || bpt->type == bp_hardware_breakpoint
1641 	  || bpt->type == bp_dprintf);
1642 }
1643 
1644 /* Return true if BPT is of any hardware watchpoint kind.  */
1645 
1646 static bool
is_hardware_watchpoint(const struct breakpoint * bpt)1647 is_hardware_watchpoint (const struct breakpoint *bpt)
1648 {
1649   return (bpt->type == bp_hardware_watchpoint
1650 	  || bpt->type == bp_read_watchpoint
1651 	  || bpt->type == bp_access_watchpoint);
1652 }
1653 
1654 /* See breakpoint.h.  */
1655 
1656 bool
is_watchpoint(const struct breakpoint * bpt)1657 is_watchpoint (const struct breakpoint *bpt)
1658 {
1659   return (is_hardware_watchpoint (bpt)
1660 	  || bpt->type == bp_watchpoint);
1661 }
1662 
1663 /* Returns true if the current thread and its running state are safe
1664    to evaluate or update watchpoint B.  Watchpoints on local
1665    expressions need to be evaluated in the context of the thread that
1666    was current when the watchpoint was created, and, that thread needs
1667    to be stopped to be able to select the correct frame context.
1668    Watchpoints on global expressions can be evaluated on any thread,
1669    and in any state.  It is presently left to the target allowing
1670    memory accesses when threads are running.  */
1671 
1672 static int
watchpoint_in_thread_scope(struct watchpoint * b)1673 watchpoint_in_thread_scope (struct watchpoint *b)
1674 {
1675   return (b->pspace == current_program_space
1676 	  && (b->watchpoint_thread == null_ptid
1677 	      || (inferior_ptid == b->watchpoint_thread
1678 		  && !inferior_thread ()->executing)));
1679 }
1680 
1681 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1682    associated bp_watchpoint_scope breakpoint.  */
1683 
1684 static void
watchpoint_del_at_next_stop(struct watchpoint * w)1685 watchpoint_del_at_next_stop (struct watchpoint *w)
1686 {
1687   if (w->related_breakpoint != w)
1688     {
1689       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1690       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1691       w->related_breakpoint->disposition = disp_del_at_next_stop;
1692       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1693       w->related_breakpoint = w;
1694     }
1695   w->disposition = disp_del_at_next_stop;
1696 }
1697 
1698 /* Extract a bitfield value from value VAL using the bit parameters contained in
1699    watchpoint W.  */
1700 
1701 static struct value *
extract_bitfield_from_watchpoint_value(struct watchpoint * w,struct value * val)1702 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1703 {
1704   struct value *bit_val;
1705 
1706   if (val == NULL)
1707     return NULL;
1708 
1709   bit_val = allocate_value (value_type (val));
1710 
1711   unpack_value_bitfield (bit_val,
1712 			 w->val_bitpos,
1713 			 w->val_bitsize,
1714 			 value_contents_for_printing (val),
1715 			 value_offset (val),
1716 			 val);
1717 
1718   return bit_val;
1719 }
1720 
1721 /* Allocate a dummy location and add it to B, which must be a software
1722    watchpoint.  This is required because even if a software watchpoint
1723    is not watching any memory, bpstat_stop_status requires a location
1724    to be able to report stops.  */
1725 
1726 static void
software_watchpoint_add_no_memory_location(struct breakpoint * b,struct program_space * pspace)1727 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1728 					    struct program_space *pspace)
1729 {
1730   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1731 
1732   b->loc = allocate_bp_location (b);
1733   b->loc->pspace = pspace;
1734   b->loc->address = -1;
1735   b->loc->length = -1;
1736 }
1737 
1738 /* Returns true if B is a software watchpoint that is not watching any
1739    memory (e.g., "watch $pc").  */
1740 
1741 static bool
is_no_memory_software_watchpoint(struct breakpoint * b)1742 is_no_memory_software_watchpoint (struct breakpoint *b)
1743 {
1744   return (b->type == bp_watchpoint
1745 	  && b->loc != NULL
1746 	  && b->loc->next == NULL
1747 	  && b->loc->address == -1
1748 	  && b->loc->length == -1);
1749 }
1750 
1751 /* Assuming that B is a watchpoint:
1752    - Reparse watchpoint expression, if REPARSE is non-zero
1753    - Evaluate expression and store the result in B->val
1754    - Evaluate the condition if there is one, and store the result
1755      in b->loc->cond.
1756    - Update the list of values that must be watched in B->loc.
1757 
1758    If the watchpoint disposition is disp_del_at_next_stop, then do
1759    nothing.  If this is local watchpoint that is out of scope, delete
1760    it.
1761 
1762    Even with `set breakpoint always-inserted on' the watchpoints are
1763    removed + inserted on each stop here.  Normal breakpoints must
1764    never be removed because they might be missed by a running thread
1765    when debugging in non-stop mode.  On the other hand, hardware
1766    watchpoints (is_hardware_watchpoint; processed here) are specific
1767    to each LWP since they are stored in each LWP's hardware debug
1768    registers.  Therefore, such LWP must be stopped first in order to
1769    be able to modify its hardware watchpoints.
1770 
1771    Hardware watchpoints must be reset exactly once after being
1772    presented to the user.  It cannot be done sooner, because it would
1773    reset the data used to present the watchpoint hit to the user.  And
1774    it must not be done later because it could display the same single
1775    watchpoint hit during multiple GDB stops.  Note that the latter is
1776    relevant only to the hardware watchpoint types bp_read_watchpoint
1777    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1778    not user-visible - its hit is suppressed if the memory content has
1779    not changed.
1780 
1781    The following constraints influence the location where we can reset
1782    hardware watchpoints:
1783 
1784    * target_stopped_by_watchpoint and target_stopped_data_address are
1785      called several times when GDB stops.
1786 
1787    [linux]
1788    * Multiple hardware watchpoints can be hit at the same time,
1789      causing GDB to stop.  GDB only presents one hardware watchpoint
1790      hit at a time as the reason for stopping, and all the other hits
1791      are presented later, one after the other, each time the user
1792      requests the execution to be resumed.  Execution is not resumed
1793      for the threads still having pending hit event stored in
1794      LWP_INFO->STATUS.  While the watchpoint is already removed from
1795      the inferior on the first stop the thread hit event is kept being
1796      reported from its cached value by linux_nat_stopped_data_address
1797      until the real thread resume happens after the watchpoint gets
1798      presented and thus its LWP_INFO->STATUS gets reset.
1799 
1800    Therefore the hardware watchpoint hit can get safely reset on the
1801    watchpoint removal from inferior.  */
1802 
1803 static void
update_watchpoint(struct watchpoint * b,int reparse)1804 update_watchpoint (struct watchpoint *b, int reparse)
1805 {
1806   int within_current_scope;
1807   struct frame_id saved_frame_id;
1808   int frame_saved;
1809 
1810   /* If this is a local watchpoint, we only want to check if the
1811      watchpoint frame is in scope if the current thread is the thread
1812      that was used to create the watchpoint.  */
1813   if (!watchpoint_in_thread_scope (b))
1814     return;
1815 
1816   if (b->disposition == disp_del_at_next_stop)
1817     return;
1818 
1819   frame_saved = 0;
1820 
1821   /* Determine if the watchpoint is within scope.  */
1822   if (b->exp_valid_block == NULL)
1823     within_current_scope = 1;
1824   else
1825     {
1826       struct frame_info *fi = get_current_frame ();
1827       struct gdbarch *frame_arch = get_frame_arch (fi);
1828       CORE_ADDR frame_pc = get_frame_pc (fi);
1829 
1830       /* If we're at a point where the stack has been destroyed
1831 	 (e.g. in a function epilogue), unwinding may not work
1832 	 properly. Do not attempt to recreate locations at this
1833 	 point.  See similar comments in watchpoint_check.  */
1834       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1835 	return;
1836 
1837       /* Save the current frame's ID so we can restore it after
1838 	 evaluating the watchpoint expression on its own frame.  */
1839       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1840 	 took a frame parameter, so that we didn't have to change the
1841 	 selected frame.  */
1842       frame_saved = 1;
1843       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1844 
1845       fi = frame_find_by_id (b->watchpoint_frame);
1846       within_current_scope = (fi != NULL);
1847       if (within_current_scope)
1848 	select_frame (fi);
1849     }
1850 
1851   /* We don't free locations.  They are stored in the bp_location array
1852      and update_global_location_list will eventually delete them and
1853      remove breakpoints if needed.  */
1854   b->loc = NULL;
1855 
1856   if (within_current_scope && reparse)
1857     {
1858       const char *s;
1859 
1860       b->exp.reset ();
1861       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1862       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1863       /* If the meaning of expression itself changed, the old value is
1864 	 no longer relevant.  We don't want to report a watchpoint hit
1865 	 to the user when the old value and the new value may actually
1866 	 be completely different objects.  */
1867       b->val = NULL;
1868       b->val_valid = false;
1869 
1870       /* Note that unlike with breakpoints, the watchpoint's condition
1871 	 expression is stored in the breakpoint object, not in the
1872 	 locations (re)created below.  */
1873       if (b->cond_string != NULL)
1874 	{
1875 	  b->cond_exp.reset ();
1876 
1877 	  s = b->cond_string;
1878 	  b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1879 	}
1880     }
1881 
1882   /* If we failed to parse the expression, for example because
1883      it refers to a global variable in a not-yet-loaded shared library,
1884      don't try to insert watchpoint.  We don't automatically delete
1885      such watchpoint, though, since failure to parse expression
1886      is different from out-of-scope watchpoint.  */
1887   if (!target_has_execution ())
1888     {
1889       /* Without execution, memory can't change.  No use to try and
1890 	 set watchpoint locations.  The watchpoint will be reset when
1891 	 the target gains execution, through breakpoint_re_set.  */
1892       if (!can_use_hw_watchpoints)
1893 	{
1894 	  if (b->ops->works_in_software_mode (b))
1895 	    b->type = bp_watchpoint;
1896 	  else
1897 	    error (_("Can't set read/access watchpoint when "
1898 		     "hardware watchpoints are disabled."));
1899 	}
1900     }
1901   else if (within_current_scope && b->exp)
1902     {
1903       std::vector<value_ref_ptr> val_chain;
1904       struct value *v, *result;
1905       struct program_space *frame_pspace;
1906 
1907       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
1908 			  &val_chain, false);
1909 
1910       /* Avoid setting b->val if it's already set.  The meaning of
1911 	 b->val is 'the last value' user saw, and we should update
1912 	 it only if we reported that last value to user.  As it
1913 	 happens, the code that reports it updates b->val directly.
1914 	 We don't keep track of the memory value for masked
1915 	 watchpoints.  */
1916       if (!b->val_valid && !is_masked_watchpoint (b))
1917 	{
1918 	  if (b->val_bitsize != 0)
1919 	    v = extract_bitfield_from_watchpoint_value (b, v);
1920 	  b->val = release_value (v);
1921 	  b->val_valid = true;
1922 	}
1923 
1924       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1925 
1926       /* Look at each value on the value chain.  */
1927       gdb_assert (!val_chain.empty ());
1928       for (const value_ref_ptr &iter : val_chain)
1929 	{
1930 	  v = iter.get ();
1931 
1932 	  /* If it's a memory location, and GDB actually needed
1933 	     its contents to evaluate the expression, then we
1934 	     must watch it.  If the first value returned is
1935 	     still lazy, that means an error occurred reading it;
1936 	     watch it anyway in case it becomes readable.  */
1937 	  if (VALUE_LVAL (v) == lval_memory
1938 	      && (v == val_chain[0] || ! value_lazy (v)))
1939 	    {
1940 	      struct type *vtype = check_typedef (value_type (v));
1941 
1942 	      /* We only watch structs and arrays if user asked
1943 		 for it explicitly, never if they just happen to
1944 		 appear in the middle of some value chain.  */
1945 	      if (v == result
1946 		  || (vtype->code () != TYPE_CODE_STRUCT
1947 		      && vtype->code () != TYPE_CODE_ARRAY))
1948 		{
1949 		  CORE_ADDR addr;
1950 		  enum target_hw_bp_type type;
1951 		  struct bp_location *loc, **tmp;
1952 		  int bitpos = 0, bitsize = 0;
1953 
1954 		  if (value_bitsize (v) != 0)
1955 		    {
1956 		      /* Extract the bit parameters out from the bitfield
1957 			 sub-expression.  */
1958 		      bitpos = value_bitpos (v);
1959 		      bitsize = value_bitsize (v);
1960 		    }
1961 		  else if (v == result && b->val_bitsize != 0)
1962 		    {
1963 		     /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1964 			lvalue whose bit parameters are saved in the fields
1965 			VAL_BITPOS and VAL_BITSIZE.  */
1966 		      bitpos = b->val_bitpos;
1967 		      bitsize = b->val_bitsize;
1968 		    }
1969 
1970 		  addr = value_address (v);
1971 		  if (bitsize != 0)
1972 		    {
1973 		      /* Skip the bytes that don't contain the bitfield.  */
1974 		      addr += bitpos / 8;
1975 		    }
1976 
1977 		  type = hw_write;
1978 		  if (b->type == bp_read_watchpoint)
1979 		    type = hw_read;
1980 		  else if (b->type == bp_access_watchpoint)
1981 		    type = hw_access;
1982 
1983 		  loc = allocate_bp_location (b);
1984 		  for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1985 		    ;
1986 		  *tmp = loc;
1987 		  loc->gdbarch = value_type (v)->arch ();
1988 
1989 		  loc->pspace = frame_pspace;
1990 		  loc->address = address_significant (loc->gdbarch, addr);
1991 
1992 		  if (bitsize != 0)
1993 		    {
1994 		      /* Just cover the bytes that make up the bitfield.  */
1995 		      loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1996 		    }
1997 		  else
1998 		    loc->length = TYPE_LENGTH (value_type (v));
1999 
2000 		  loc->watchpoint_type = type;
2001 		}
2002 	    }
2003 	}
2004 
2005       /* Change the type of breakpoint between hardware assisted or
2006 	 an ordinary watchpoint depending on the hardware support
2007 	 and free hardware slots.  REPARSE is set when the inferior
2008 	 is started.  */
2009       if (reparse)
2010 	{
2011 	  int reg_cnt;
2012 	  enum bp_loc_type loc_type;
2013 
2014 	  reg_cnt = can_use_hardware_watchpoint (val_chain);
2015 
2016 	  if (reg_cnt)
2017 	    {
2018 	      int i, target_resources_ok, other_type_used;
2019 	      enum bptype type;
2020 
2021 	      /* Use an exact watchpoint when there's only one memory region to be
2022 		 watched, and only one debug register is needed to watch it.  */
2023 	      b->exact = target_exact_watchpoints && reg_cnt == 1;
2024 
2025 	      /* We need to determine how many resources are already
2026 		 used for all other hardware watchpoints plus this one
2027 		 to see if we still have enough resources to also fit
2028 		 this watchpoint in as well.  */
2029 
2030 	      /* If this is a software watchpoint, we try to turn it
2031 		 to a hardware one -- count resources as if B was of
2032 		 hardware watchpoint type.  */
2033 	      type = b->type;
2034 	      if (type == bp_watchpoint)
2035 		type = bp_hardware_watchpoint;
2036 
2037 	      /* This watchpoint may or may not have been placed on
2038 		 the list yet at this point (it won't be in the list
2039 		 if we're trying to create it for the first time,
2040 		 through watch_command), so always account for it
2041 		 manually.  */
2042 
2043 	      /* Count resources used by all watchpoints except B.  */
2044 	      i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2045 
2046 	      /* Add in the resources needed for B.  */
2047 	      i += hw_watchpoint_use_count (b);
2048 
2049 	      target_resources_ok
2050 		= target_can_use_hardware_watchpoint (type, i, other_type_used);
2051 	      if (target_resources_ok <= 0)
2052 		{
2053 		  int sw_mode = b->ops->works_in_software_mode (b);
2054 
2055 		  if (target_resources_ok == 0 && !sw_mode)
2056 		    error (_("Target does not support this type of "
2057 			     "hardware watchpoint."));
2058 		  else if (target_resources_ok < 0 && !sw_mode)
2059 		    error (_("There are not enough available hardware "
2060 			     "resources for this watchpoint."));
2061 
2062 		  /* Downgrade to software watchpoint.  */
2063 		  b->type = bp_watchpoint;
2064 		}
2065 	      else
2066 		{
2067 		  /* If this was a software watchpoint, we've just
2068 		     found we have enough resources to turn it to a
2069 		     hardware watchpoint.  Otherwise, this is a
2070 		     nop.  */
2071 		  b->type = type;
2072 		}
2073 	    }
2074 	  else if (!b->ops->works_in_software_mode (b))
2075 	    {
2076 	      if (!can_use_hw_watchpoints)
2077 		error (_("Can't set read/access watchpoint when "
2078 			 "hardware watchpoints are disabled."));
2079 	      else
2080 		error (_("Expression cannot be implemented with "
2081 			 "read/access watchpoint."));
2082 	    }
2083 	  else
2084 	    b->type = bp_watchpoint;
2085 
2086 	  loc_type = (b->type == bp_watchpoint? bp_loc_other
2087 		      : bp_loc_hardware_watchpoint);
2088 	  for (bp_location *bl : b->locations ())
2089 	    bl->loc_type = loc_type;
2090 	}
2091 
2092       /* If a software watchpoint is not watching any memory, then the
2093 	 above left it without any location set up.  But,
2094 	 bpstat_stop_status requires a location to be able to report
2095 	 stops, so make sure there's at least a dummy one.  */
2096       if (b->type == bp_watchpoint && b->loc == NULL)
2097 	software_watchpoint_add_no_memory_location (b, frame_pspace);
2098     }
2099   else if (!within_current_scope)
2100     {
2101       printf_filtered (_("\
2102 Watchpoint %d deleted because the program has left the block\n\
2103 in which its expression is valid.\n"),
2104 		       b->number);
2105       watchpoint_del_at_next_stop (b);
2106     }
2107 
2108   /* Restore the selected frame.  */
2109   if (frame_saved)
2110     select_frame (frame_find_by_id (saved_frame_id));
2111 }
2112 
2113 
2114 /* Returns 1 iff breakpoint location should be
2115    inserted in the inferior.  We don't differentiate the type of BL's owner
2116    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2117    breakpoint_ops is not defined, because in insert_bp_location,
2118    tracepoint's insert_location will not be called.  */
2119 static int
should_be_inserted(struct bp_location * bl)2120 should_be_inserted (struct bp_location *bl)
2121 {
2122   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2123     return 0;
2124 
2125   if (bl->owner->disposition == disp_del_at_next_stop)
2126     return 0;
2127 
2128   if (!bl->enabled || bl->disabled_by_cond
2129       || bl->shlib_disabled || bl->duplicate)
2130     return 0;
2131 
2132   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2133     return 0;
2134 
2135   /* This is set for example, when we're attached to the parent of a
2136      vfork, and have detached from the child.  The child is running
2137      free, and we expect it to do an exec or exit, at which point the
2138      OS makes the parent schedulable again (and the target reports
2139      that the vfork is done).  Until the child is done with the shared
2140      memory region, do not insert breakpoints in the parent, otherwise
2141      the child could still trip on the parent's breakpoints.  Since
2142      the parent is blocked anyway, it won't miss any breakpoint.  */
2143   if (bl->pspace->breakpoints_not_allowed)
2144     return 0;
2145 
2146   /* Don't insert a breakpoint if we're trying to step past its
2147      location, except if the breakpoint is a single-step breakpoint,
2148      and the breakpoint's thread is the thread which is stepping past
2149      a breakpoint.  */
2150   if ((bl->loc_type == bp_loc_software_breakpoint
2151        || bl->loc_type == bp_loc_hardware_breakpoint)
2152       && stepping_past_instruction_at (bl->pspace->aspace,
2153 				       bl->address)
2154       /* The single-step breakpoint may be inserted at the location
2155 	 we're trying to step if the instruction branches to itself.
2156 	 However, the instruction won't be executed at all and it may
2157 	 break the semantics of the instruction, for example, the
2158 	 instruction is a conditional branch or updates some flags.
2159 	 We can't fix it unless GDB is able to emulate the instruction
2160 	 or switch to displaced stepping.  */
2161       && !(bl->owner->type == bp_single_step
2162 	   && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2163     {
2164       infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2165 			   paddress (bl->gdbarch, bl->address));
2166       return 0;
2167     }
2168 
2169   /* Don't insert watchpoints if we're trying to step past the
2170      instruction that triggered one.  */
2171   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2172       && stepping_past_nonsteppable_watchpoint ())
2173     {
2174       infrun_debug_printf ("stepping past non-steppable watchpoint. "
2175 			   "skipping watchpoint at %s:%d",
2176 			   paddress (bl->gdbarch, bl->address), bl->length);
2177       return 0;
2178     }
2179 
2180   return 1;
2181 }
2182 
2183 /* Same as should_be_inserted but does the check assuming
2184    that the location is not duplicated.  */
2185 
2186 static int
unduplicated_should_be_inserted(struct bp_location * bl)2187 unduplicated_should_be_inserted (struct bp_location *bl)
2188 {
2189   int result;
2190   const int save_duplicate = bl->duplicate;
2191 
2192   bl->duplicate = 0;
2193   result = should_be_inserted (bl);
2194   bl->duplicate = save_duplicate;
2195   return result;
2196 }
2197 
2198 /* Parses a conditional described by an expression COND into an
2199    agent expression bytecode suitable for evaluation
2200    by the bytecode interpreter.  Return NULL if there was
2201    any error during parsing.  */
2202 
2203 static agent_expr_up
parse_cond_to_aexpr(CORE_ADDR scope,struct expression * cond)2204 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2205 {
2206   if (cond == NULL)
2207     return NULL;
2208 
2209   agent_expr_up aexpr;
2210 
2211   /* We don't want to stop processing, so catch any errors
2212      that may show up.  */
2213   try
2214     {
2215       aexpr = gen_eval_for_expr (scope, cond);
2216     }
2217 
2218   catch (const gdb_exception_error &ex)
2219     {
2220       /* If we got here, it means the condition could not be parsed to a valid
2221 	 bytecode expression and thus can't be evaluated on the target's side.
2222 	 It's no use iterating through the conditions.  */
2223     }
2224 
2225   /* We have a valid agent expression.  */
2226   return aexpr;
2227 }
2228 
2229 /* Based on location BL, create a list of breakpoint conditions to be
2230    passed on to the target.  If we have duplicated locations with different
2231    conditions, we will add such conditions to the list.  The idea is that the
2232    target will evaluate the list of conditions and will only notify GDB when
2233    one of them is true.  */
2234 
2235 static void
build_target_condition_list(struct bp_location * bl)2236 build_target_condition_list (struct bp_location *bl)
2237 {
2238   int null_condition_or_parse_error = 0;
2239   int modified = bl->needs_update;
2240 
2241   /* Release conditions left over from a previous insert.  */
2242   bl->target_info.conditions.clear ();
2243 
2244   /* This is only meaningful if the target is
2245      evaluating conditions and if the user has
2246      opted for condition evaluation on the target's
2247      side.  */
2248   if (gdb_evaluates_breakpoint_condition_p ()
2249       || !target_supports_evaluation_of_breakpoint_conditions ())
2250     return;
2251 
2252   auto loc_range = all_bp_locations_at_addr (bl->address);
2253 
2254   /* Do a first pass to check for locations with no assigned
2255      conditions or conditions that fail to parse to a valid agent
2256      expression bytecode.  If any of these happen, then it's no use to
2257      send conditions to the target since this location will always
2258      trigger and generate a response back to GDB.  Note we consider
2259      all locations at the same address irrespective of type, i.e.,
2260      even if the locations aren't considered duplicates (e.g.,
2261      software breakpoint and hardware breakpoint at the same
2262      address).  */
2263   for (bp_location *loc : loc_range)
2264     {
2265       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2266 	{
2267 	  if (modified)
2268 	    {
2269 	      /* Re-parse the conditions since something changed.  In that
2270 		 case we already freed the condition bytecodes (see
2271 		 force_breakpoint_reinsertion).  We just
2272 		 need to parse the condition to bytecodes again.  */
2273 	      loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2274 							loc->cond.get ());
2275 	    }
2276 
2277 	  /* If we have a NULL bytecode expression, it means something
2278 	     went wrong or we have a null condition expression.  */
2279 	  if (!loc->cond_bytecode)
2280 	    {
2281 	      null_condition_or_parse_error = 1;
2282 	      break;
2283 	    }
2284 	}
2285     }
2286 
2287   /* If any of these happened, it means we will have to evaluate the conditions
2288      for the location's address on gdb's side.  It is no use keeping bytecodes
2289      for all the other duplicate locations, thus we free all of them here.
2290 
2291      This is so we have a finer control over which locations' conditions are
2292      being evaluated by GDB or the remote stub.  */
2293   if (null_condition_or_parse_error)
2294     {
2295       for (bp_location *loc : loc_range)
2296 	{
2297 	  if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2298 	    {
2299 	      /* Only go as far as the first NULL bytecode is
2300 		 located.  */
2301 	      if (!loc->cond_bytecode)
2302 		return;
2303 
2304 	      loc->cond_bytecode.reset ();
2305 	    }
2306 	}
2307     }
2308 
2309   /* No NULL conditions or failed bytecode generation.  Build a
2310      condition list for this location's address.  If we have software
2311      and hardware locations at the same address, they aren't
2312      considered duplicates, but we still marge all the conditions
2313      anyway, as it's simpler, and doesn't really make a practical
2314      difference.  */
2315   for (bp_location *loc : loc_range)
2316     if (loc->cond
2317 	&& is_breakpoint (loc->owner)
2318 	&& loc->pspace->num == bl->pspace->num
2319 	&& loc->owner->enable_state == bp_enabled
2320 	&& loc->enabled
2321 	&& !loc->disabled_by_cond)
2322       {
2323 	/* Add the condition to the vector.  This will be used later
2324 	   to send the conditions to the target.  */
2325 	bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2326       }
2327 
2328   return;
2329 }
2330 
2331 /* Parses a command described by string CMD into an agent expression
2332    bytecode suitable for evaluation by the bytecode interpreter.
2333    Return NULL if there was any error during parsing.  */
2334 
2335 static agent_expr_up
parse_cmd_to_aexpr(CORE_ADDR scope,char * cmd)2336 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2337 {
2338   const char *cmdrest;
2339   const char *format_start, *format_end;
2340   struct gdbarch *gdbarch = get_current_arch ();
2341 
2342   if (cmd == NULL)
2343     return NULL;
2344 
2345   cmdrest = cmd;
2346 
2347   if (*cmdrest == ',')
2348     ++cmdrest;
2349   cmdrest = skip_spaces (cmdrest);
2350 
2351   if (*cmdrest++ != '"')
2352     error (_("No format string following the location"));
2353 
2354   format_start = cmdrest;
2355 
2356   format_pieces fpieces (&cmdrest);
2357 
2358   format_end = cmdrest;
2359 
2360   if (*cmdrest++ != '"')
2361     error (_("Bad format string, non-terminated '\"'."));
2362 
2363   cmdrest = skip_spaces (cmdrest);
2364 
2365   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2366     error (_("Invalid argument syntax"));
2367 
2368   if (*cmdrest == ',')
2369     cmdrest++;
2370   cmdrest = skip_spaces (cmdrest);
2371 
2372   /* For each argument, make an expression.  */
2373 
2374   std::vector<struct expression *> argvec;
2375   while (*cmdrest != '\0')
2376     {
2377       const char *cmd1;
2378 
2379       cmd1 = cmdrest;
2380       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2381       argvec.push_back (expr.release ());
2382       cmdrest = cmd1;
2383       if (*cmdrest == ',')
2384 	++cmdrest;
2385     }
2386 
2387   agent_expr_up aexpr;
2388 
2389   /* We don't want to stop processing, so catch any errors
2390      that may show up.  */
2391   try
2392     {
2393       aexpr = gen_printf (scope, gdbarch, 0, 0,
2394 			  format_start, format_end - format_start,
2395 			  argvec.size (), argvec.data ());
2396     }
2397   catch (const gdb_exception_error &ex)
2398     {
2399       /* If we got here, it means the command could not be parsed to a valid
2400 	 bytecode expression and thus can't be evaluated on the target's side.
2401 	 It's no use iterating through the other commands.  */
2402     }
2403 
2404   /* We have a valid agent expression, return it.  */
2405   return aexpr;
2406 }
2407 
2408 /* Based on location BL, create a list of breakpoint commands to be
2409    passed on to the target.  If we have duplicated locations with
2410    different commands, we will add any such to the list.  */
2411 
2412 static void
build_target_command_list(struct bp_location * bl)2413 build_target_command_list (struct bp_location *bl)
2414 {
2415   int null_command_or_parse_error = 0;
2416   int modified = bl->needs_update;
2417 
2418   /* Clear commands left over from a previous insert.  */
2419   bl->target_info.tcommands.clear ();
2420 
2421   if (!target_can_run_breakpoint_commands ())
2422     return;
2423 
2424   /* For now, limit to agent-style dprintf breakpoints.  */
2425   if (dprintf_style != dprintf_style_agent)
2426     return;
2427 
2428   auto loc_range = all_bp_locations_at_addr (bl->address);
2429 
2430   /* For now, if we have any location at the same address that isn't a
2431      dprintf, don't install the target-side commands, as that would
2432      make the breakpoint not be reported to the core, and we'd lose
2433      control.  */
2434   for (bp_location *loc : loc_range)
2435     if (is_breakpoint (loc->owner)
2436 	&& loc->pspace->num == bl->pspace->num
2437 	&& loc->owner->type != bp_dprintf)
2438       return;
2439 
2440   /* Do a first pass to check for locations with no assigned
2441      conditions or conditions that fail to parse to a valid agent expression
2442      bytecode.  If any of these happen, then it's no use to send conditions
2443      to the target since this location will always trigger and generate a
2444      response back to GDB.  */
2445   for (bp_location *loc : loc_range)
2446     {
2447       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2448 	{
2449 	  if (modified)
2450 	    {
2451 	      /* Re-parse the commands since something changed.  In that
2452 		 case we already freed the command bytecodes (see
2453 		 force_breakpoint_reinsertion).  We just
2454 		 need to parse the command to bytecodes again.  */
2455 	      loc->cmd_bytecode
2456 		= parse_cmd_to_aexpr (bl->address,
2457 				      loc->owner->extra_string);
2458 	    }
2459 
2460 	  /* If we have a NULL bytecode expression, it means something
2461 	     went wrong or we have a null command expression.  */
2462 	  if (!loc->cmd_bytecode)
2463 	    {
2464 	      null_command_or_parse_error = 1;
2465 	      break;
2466 	    }
2467 	}
2468     }
2469 
2470   /* If anything failed, then we're not doing target-side commands,
2471      and so clean up.  */
2472   if (null_command_or_parse_error)
2473     {
2474       for (bp_location *loc : loc_range)
2475 	if (is_breakpoint (loc->owner)
2476 	    && loc->pspace->num == bl->pspace->num)
2477 	  {
2478 	    /* Only go as far as the first NULL bytecode is
2479 	       located.  */
2480 	    if (loc->cmd_bytecode == NULL)
2481 	      return;
2482 
2483 	    loc->cmd_bytecode.reset ();
2484 	  }
2485     }
2486 
2487   /* No NULL commands or failed bytecode generation.  Build a command
2488      list for all duplicate locations at this location's address.
2489      Note that here we must care for whether the breakpoint location
2490      types are considered duplicates, otherwise, say, if we have a
2491      software and hardware location at the same address, the target
2492      could end up running the commands twice.  For the moment, we only
2493      support targets-side commands with dprintf, but it doesn't hurt
2494      to be pedantically correct in case that changes.  */
2495   for (bp_location *loc : loc_range)
2496     if (breakpoint_locations_match (bl, loc)
2497 	&& loc->owner->extra_string
2498 	&& is_breakpoint (loc->owner)
2499 	&& loc->pspace->num == bl->pspace->num
2500 	&& loc->owner->enable_state == bp_enabled
2501 	&& loc->enabled
2502 	&& !loc->disabled_by_cond)
2503       {
2504 	/* Add the command to the vector.  This will be used later
2505 	   to send the commands to the target.  */
2506 	bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2507       }
2508 
2509   bl->target_info.persist = 0;
2510   /* Maybe flag this location as persistent.  */
2511   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2512     bl->target_info.persist = 1;
2513 }
2514 
2515 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2516    of breakpoint according to ADDR except single-step breakpoint.
2517    Get the kind of single-step breakpoint according to the current
2518    registers state.  */
2519 
2520 static int
breakpoint_kind(struct bp_location * bl,CORE_ADDR * addr)2521 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2522 {
2523   if (bl->owner->type == bp_single_step)
2524     {
2525       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2526       struct regcache *regcache;
2527 
2528       regcache = get_thread_regcache (thr);
2529 
2530       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2531 							 regcache, addr);
2532     }
2533   else
2534     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2535 }
2536 
2537 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2538    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2539    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2540    Returns 0 for success, 1 if the bp_location type is not supported or
2541    -1 for failure.
2542 
2543    NOTE drow/2003-09-09: This routine could be broken down to an
2544    object-style method for each breakpoint or catchpoint type.  */
2545 static int
insert_bp_location(struct bp_location * bl,struct ui_file * tmp_error_stream,int * disabled_breaks,int * hw_breakpoint_error,int * hw_bp_error_explained_already)2546 insert_bp_location (struct bp_location *bl,
2547 		    struct ui_file *tmp_error_stream,
2548 		    int *disabled_breaks,
2549 		    int *hw_breakpoint_error,
2550 		    int *hw_bp_error_explained_already)
2551 {
2552   gdb_exception bp_excpt;
2553 
2554   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2555     return 0;
2556 
2557   /* Note we don't initialize bl->target_info, as that wipes out
2558      the breakpoint location's shadow_contents if the breakpoint
2559      is still inserted at that location.  This in turn breaks
2560      target_read_memory which depends on these buffers when
2561      a memory read is requested at the breakpoint location:
2562      Once the target_info has been wiped, we fail to see that
2563      we have a breakpoint inserted at that address and thus
2564      read the breakpoint instead of returning the data saved in
2565      the breakpoint location's shadow contents.  */
2566   bl->target_info.reqstd_address = bl->address;
2567   bl->target_info.placed_address_space = bl->pspace->aspace;
2568   bl->target_info.length = bl->length;
2569 
2570   /* When working with target-side conditions, we must pass all the conditions
2571      for the same breakpoint address down to the target since GDB will not
2572      insert those locations.  With a list of breakpoint conditions, the target
2573      can decide when to stop and notify GDB.  */
2574 
2575   if (is_breakpoint (bl->owner))
2576     {
2577       build_target_condition_list (bl);
2578       build_target_command_list (bl);
2579       /* Reset the modification marker.  */
2580       bl->needs_update = 0;
2581     }
2582 
2583   /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2584      set at a read-only address, then a breakpoint location will have
2585      been changed to hardware breakpoint before we get here.  If it is
2586      "off" however, error out before actually trying to insert the
2587      breakpoint, with a nicer error message.  */
2588   if (bl->loc_type == bp_loc_software_breakpoint
2589       && !automatic_hardware_breakpoints)
2590     {
2591       mem_region *mr = lookup_mem_region (bl->address);
2592 
2593       if (mr != nullptr && mr->attrib.mode != MEM_RW)
2594 	{
2595 	  fprintf_unfiltered (tmp_error_stream,
2596 			      _("Cannot insert breakpoint %d.\n"
2597 				"Cannot set software breakpoint "
2598 				"at read-only address %s\n"),
2599 			      bl->owner->number,
2600 			      paddress (bl->gdbarch, bl->address));
2601 	  return 1;
2602 	}
2603     }
2604 
2605   if (bl->loc_type == bp_loc_software_breakpoint
2606       || bl->loc_type == bp_loc_hardware_breakpoint)
2607     {
2608       /* First check to see if we have to handle an overlay.  */
2609       if (overlay_debugging == ovly_off
2610 	  || bl->section == NULL
2611 	  || !(section_is_overlay (bl->section)))
2612 	{
2613 	  /* No overlay handling: just set the breakpoint.  */
2614 	  try
2615 	    {
2616 	      int val;
2617 
2618 	      val = bl->owner->ops->insert_location (bl);
2619 	      if (val)
2620 		bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2621 	    }
2622 	  catch (gdb_exception &e)
2623 	    {
2624 	      bp_excpt = std::move (e);
2625 	    }
2626 	}
2627       else
2628 	{
2629 	  /* This breakpoint is in an overlay section.
2630 	     Shall we set a breakpoint at the LMA?  */
2631 	  if (!overlay_events_enabled)
2632 	    {
2633 	      /* Yes -- overlay event support is not active,
2634 		 so we must try to set a breakpoint at the LMA.
2635 		 This will not work for a hardware breakpoint.  */
2636 	      if (bl->loc_type == bp_loc_hardware_breakpoint)
2637 		warning (_("hardware breakpoint %d not supported in overlay!"),
2638 			 bl->owner->number);
2639 	      else
2640 		{
2641 		  CORE_ADDR addr = overlay_unmapped_address (bl->address,
2642 							     bl->section);
2643 		  /* Set a software (trap) breakpoint at the LMA.  */
2644 		  bl->overlay_target_info = bl->target_info;
2645 		  bl->overlay_target_info.reqstd_address = addr;
2646 
2647 		  /* No overlay handling: just set the breakpoint.  */
2648 		  try
2649 		    {
2650 		      int val;
2651 
2652 		      bl->overlay_target_info.kind
2653 			= breakpoint_kind (bl, &addr);
2654 		      bl->overlay_target_info.placed_address = addr;
2655 		      val = target_insert_breakpoint (bl->gdbarch,
2656 						      &bl->overlay_target_info);
2657 		      if (val)
2658 			bp_excpt
2659 			  = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2660 		    }
2661 		  catch (gdb_exception &e)
2662 		    {
2663 		      bp_excpt = std::move (e);
2664 		    }
2665 
2666 		  if (bp_excpt.reason != 0)
2667 		    fprintf_unfiltered (tmp_error_stream,
2668 					"Overlay breakpoint %d "
2669 					"failed: in ROM?\n",
2670 					bl->owner->number);
2671 		}
2672 	    }
2673 	  /* Shall we set a breakpoint at the VMA? */
2674 	  if (section_is_mapped (bl->section))
2675 	    {
2676 	      /* Yes.  This overlay section is mapped into memory.  */
2677 	      try
2678 		{
2679 		  int val;
2680 
2681 		  val = bl->owner->ops->insert_location (bl);
2682 		  if (val)
2683 		    bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2684 		}
2685 	      catch (gdb_exception &e)
2686 		{
2687 		  bp_excpt = std::move (e);
2688 		}
2689 	    }
2690 	  else
2691 	    {
2692 	      /* No.  This breakpoint will not be inserted.
2693 		 No error, but do not mark the bp as 'inserted'.  */
2694 	      return 0;
2695 	    }
2696 	}
2697 
2698       if (bp_excpt.reason != 0)
2699 	{
2700 	  /* Can't set the breakpoint.  */
2701 
2702 	  /* If the target has closed then it will have deleted any
2703 	     breakpoints inserted within the target inferior, as a result
2704 	     any further attempts to interact with the breakpoint objects
2705 	     is not possible.  Just rethrow the error.  */
2706 	  if (bp_excpt.error == TARGET_CLOSE_ERROR)
2707 	    throw bp_excpt;
2708 	  gdb_assert (bl->owner != nullptr);
2709 
2710 	  /* In some cases, we might not be able to insert a
2711 	     breakpoint in a shared library that has already been
2712 	     removed, but we have not yet processed the shlib unload
2713 	     event.  Unfortunately, some targets that implement
2714 	     breakpoint insertion themselves can't tell why the
2715 	     breakpoint insertion failed (e.g., the remote target
2716 	     doesn't define error codes), so we must treat generic
2717 	     errors as memory errors.  */
2718 	  if (bp_excpt.reason == RETURN_ERROR
2719 	      && (bp_excpt.error == GENERIC_ERROR
2720 		  || bp_excpt.error == MEMORY_ERROR)
2721 	      && bl->loc_type == bp_loc_software_breakpoint
2722 	      && (solib_name_from_address (bl->pspace, bl->address)
2723 		  || shared_objfile_contains_address_p (bl->pspace,
2724 							bl->address)))
2725 	    {
2726 	      /* See also: disable_breakpoints_in_shlibs.  */
2727 	      bl->shlib_disabled = 1;
2728 	      gdb::observers::breakpoint_modified.notify (bl->owner);
2729 	      if (!*disabled_breaks)
2730 		{
2731 		  fprintf_unfiltered (tmp_error_stream,
2732 				      "Cannot insert breakpoint %d.\n",
2733 				      bl->owner->number);
2734 		  fprintf_unfiltered (tmp_error_stream,
2735 				      "Temporarily disabling shared "
2736 				      "library breakpoints:\n");
2737 		}
2738 	      *disabled_breaks = 1;
2739 	      fprintf_unfiltered (tmp_error_stream,
2740 				  "breakpoint #%d\n", bl->owner->number);
2741 	      return 0;
2742 	    }
2743 	  else
2744 	    {
2745 	      if (bl->loc_type == bp_loc_hardware_breakpoint)
2746 		{
2747 		  *hw_breakpoint_error = 1;
2748 		  *hw_bp_error_explained_already = bp_excpt.message != NULL;
2749 		  fprintf_unfiltered (tmp_error_stream,
2750 				      "Cannot insert hardware breakpoint %d%s",
2751 				      bl->owner->number,
2752 				      bp_excpt.message ? ":" : ".\n");
2753 		  if (bp_excpt.message != NULL)
2754 		    fprintf_unfiltered (tmp_error_stream, "%s.\n",
2755 					bp_excpt.what ());
2756 		}
2757 	      else
2758 		{
2759 		  if (bp_excpt.message == NULL)
2760 		    {
2761 		      std::string message
2762 			= memory_error_message (TARGET_XFER_E_IO,
2763 						bl->gdbarch, bl->address);
2764 
2765 		      fprintf_unfiltered (tmp_error_stream,
2766 					  "Cannot insert breakpoint %d.\n"
2767 					  "%s\n",
2768 					  bl->owner->number, message.c_str ());
2769 		    }
2770 		  else
2771 		    {
2772 		      fprintf_unfiltered (tmp_error_stream,
2773 					  "Cannot insert breakpoint %d: %s\n",
2774 					  bl->owner->number,
2775 					  bp_excpt.what ());
2776 		    }
2777 		}
2778 	      return 1;
2779 
2780 	    }
2781 	}
2782       else
2783 	bl->inserted = 1;
2784 
2785       return 0;
2786     }
2787 
2788   else if (bl->loc_type == bp_loc_hardware_watchpoint
2789 	   /* NOTE drow/2003-09-08: This state only exists for removing
2790 	      watchpoints.  It's not clear that it's necessary...  */
2791 	   && bl->owner->disposition != disp_del_at_next_stop)
2792     {
2793       int val;
2794 
2795       gdb_assert (bl->owner->ops != NULL
2796 		  && bl->owner->ops->insert_location != NULL);
2797 
2798       val = bl->owner->ops->insert_location (bl);
2799 
2800       /* If trying to set a read-watchpoint, and it turns out it's not
2801 	 supported, try emulating one with an access watchpoint.  */
2802       if (val == 1 && bl->watchpoint_type == hw_read)
2803 	{
2804 	  /* But don't try to insert it, if there's already another
2805 	     hw_access location that would be considered a duplicate
2806 	     of this one.  */
2807 	  for (bp_location *loc : all_bp_locations ())
2808 	    if (loc != bl
2809 		&& loc->watchpoint_type == hw_access
2810 		&& watchpoint_locations_match (bl, loc))
2811 	      {
2812 		bl->duplicate = 1;
2813 		bl->inserted = 1;
2814 		bl->target_info = loc->target_info;
2815 		bl->watchpoint_type = hw_access;
2816 		val = 0;
2817 		break;
2818 	      }
2819 
2820 	  if (val == 1)
2821 	    {
2822 	      bl->watchpoint_type = hw_access;
2823 	      val = bl->owner->ops->insert_location (bl);
2824 
2825 	      if (val)
2826 		/* Back to the original value.  */
2827 		bl->watchpoint_type = hw_read;
2828 	    }
2829 	}
2830 
2831       bl->inserted = (val == 0);
2832     }
2833 
2834   else if (bl->owner->type == bp_catchpoint)
2835     {
2836       int val;
2837 
2838       gdb_assert (bl->owner->ops != NULL
2839 		  && bl->owner->ops->insert_location != NULL);
2840 
2841       val = bl->owner->ops->insert_location (bl);
2842       if (val)
2843 	{
2844 	  bl->owner->enable_state = bp_disabled;
2845 
2846 	  if (val == 1)
2847 	    warning (_("\
2848 Error inserting catchpoint %d: Your system does not support this type\n\
2849 of catchpoint."), bl->owner->number);
2850 	  else
2851 	    warning (_("Error inserting catchpoint %d."), bl->owner->number);
2852 	}
2853 
2854       bl->inserted = (val == 0);
2855 
2856       /* We've already printed an error message if there was a problem
2857 	 inserting this catchpoint, and we've disabled the catchpoint,
2858 	 so just return success.  */
2859       return 0;
2860     }
2861 
2862   return 0;
2863 }
2864 
2865 /* This function is called when program space PSPACE is about to be
2866    deleted.  It takes care of updating breakpoints to not reference
2867    PSPACE anymore.  */
2868 
2869 void
breakpoint_program_space_exit(struct program_space * pspace)2870 breakpoint_program_space_exit (struct program_space *pspace)
2871 {
2872   /* Remove any breakpoint that was set through this program space.  */
2873   for (breakpoint *b : all_breakpoints_safe ())
2874     if (b->pspace == pspace)
2875       delete_breakpoint (b);
2876 
2877   /* Breakpoints set through other program spaces could have locations
2878      bound to PSPACE as well.  Remove those.  */
2879   for (bp_location *loc : all_bp_locations ())
2880     {
2881       struct bp_location *tmp;
2882 
2883       if (loc->pspace == pspace)
2884 	{
2885 	  /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2886 	  if (loc->owner->loc == loc)
2887 	    loc->owner->loc = loc->next;
2888 	  else
2889 	    for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2890 	      if (tmp->next == loc)
2891 		{
2892 		  tmp->next = loc->next;
2893 		  break;
2894 		}
2895 	}
2896     }
2897 
2898   /* Now update the global location list to permanently delete the
2899      removed locations above.  */
2900   update_global_location_list (UGLL_DONT_INSERT);
2901 }
2902 
2903 /* Make sure all breakpoints are inserted in inferior.
2904    Throws exception on any error.
2905    A breakpoint that is already inserted won't be inserted
2906    again, so calling this function twice is safe.  */
2907 void
insert_breakpoints(void)2908 insert_breakpoints (void)
2909 {
2910   for (breakpoint *bpt : all_breakpoints ())
2911     if (is_hardware_watchpoint (bpt))
2912       {
2913 	struct watchpoint *w = (struct watchpoint *) bpt;
2914 
2915 	update_watchpoint (w, 0 /* don't reparse.  */);
2916       }
2917 
2918   /* Updating watchpoints creates new locations, so update the global
2919      location list.  Explicitly tell ugll to insert locations and
2920      ignore breakpoints_always_inserted_mode.  Also,
2921      update_global_location_list tries to "upgrade" software
2922      breakpoints to hardware breakpoints to handle "set breakpoint
2923      auto-hw", so we need to call it even if we don't have new
2924      locations.  */
2925   update_global_location_list (UGLL_INSERT);
2926 }
2927 
2928 /* This is used when we need to synch breakpoint conditions between GDB and the
2929    target.  It is the case with deleting and disabling of breakpoints when using
2930    always-inserted mode.  */
2931 
2932 static void
update_inserted_breakpoint_locations(void)2933 update_inserted_breakpoint_locations (void)
2934 {
2935   int error_flag = 0;
2936   int val = 0;
2937   int disabled_breaks = 0;
2938   int hw_breakpoint_error = 0;
2939   int hw_bp_details_reported = 0;
2940 
2941   string_file tmp_error_stream;
2942 
2943   /* Explicitly mark the warning -- this will only be printed if
2944      there was an error.  */
2945   tmp_error_stream.puts ("Warning:\n");
2946 
2947   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2948 
2949   for (bp_location *bl : all_bp_locations ())
2950     {
2951       /* We only want to update software breakpoints and hardware
2952 	 breakpoints.  */
2953       if (!is_breakpoint (bl->owner))
2954 	continue;
2955 
2956       /* We only want to update locations that are already inserted
2957 	 and need updating.  This is to avoid unwanted insertion during
2958 	 deletion of breakpoints.  */
2959       if (!bl->inserted || !bl->needs_update)
2960 	continue;
2961 
2962       switch_to_program_space_and_thread (bl->pspace);
2963 
2964       /* For targets that support global breakpoints, there's no need
2965 	 to select an inferior to insert breakpoint to.  In fact, even
2966 	 if we aren't attached to any process yet, we should still
2967 	 insert breakpoints.  */
2968       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2969 	  && (inferior_ptid == null_ptid || !target_has_execution ()))
2970 	continue;
2971 
2972       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
2973 				    &hw_breakpoint_error, &hw_bp_details_reported);
2974       if (val)
2975 	error_flag = val;
2976     }
2977 
2978   if (error_flag)
2979     {
2980       target_terminal::ours_for_output ();
2981       error_stream (tmp_error_stream);
2982     }
2983 }
2984 
2985 /* Used when starting or continuing the program.  */
2986 
2987 static void
insert_breakpoint_locations(void)2988 insert_breakpoint_locations (void)
2989 {
2990   int error_flag = 0;
2991   int val = 0;
2992   int disabled_breaks = 0;
2993   int hw_breakpoint_error = 0;
2994   int hw_bp_error_explained_already = 0;
2995 
2996   string_file tmp_error_stream;
2997 
2998   /* Explicitly mark the warning -- this will only be printed if
2999      there was an error.  */
3000   tmp_error_stream.puts ("Warning:\n");
3001 
3002   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3003 
3004   for (bp_location *bl : all_bp_locations ())
3005     {
3006       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3007 	continue;
3008 
3009       /* There is no point inserting thread-specific breakpoints if
3010 	 the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3011 	 has BL->OWNER always non-NULL.  */
3012       if (bl->owner->thread != -1
3013 	  && !valid_global_thread_id (bl->owner->thread))
3014 	continue;
3015 
3016       switch_to_program_space_and_thread (bl->pspace);
3017 
3018       /* For targets that support global breakpoints, there's no need
3019 	 to select an inferior to insert breakpoint to.  In fact, even
3020 	 if we aren't attached to any process yet, we should still
3021 	 insert breakpoints.  */
3022       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3023 	  && (inferior_ptid == null_ptid || !target_has_execution ()))
3024 	continue;
3025 
3026       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3027 				    &hw_breakpoint_error, &hw_bp_error_explained_already);
3028       if (val)
3029 	error_flag = val;
3030     }
3031 
3032   /* If we failed to insert all locations of a watchpoint, remove
3033      them, as half-inserted watchpoint is of limited use.  */
3034   for (breakpoint *bpt : all_breakpoints ())
3035     {
3036       int some_failed = 0;
3037 
3038       if (!is_hardware_watchpoint (bpt))
3039 	continue;
3040 
3041       if (!breakpoint_enabled (bpt))
3042 	continue;
3043 
3044       if (bpt->disposition == disp_del_at_next_stop)
3045 	continue;
3046 
3047       for (bp_location *loc : bpt->locations ())
3048 	if (!loc->inserted && should_be_inserted (loc))
3049 	  {
3050 	    some_failed = 1;
3051 	    break;
3052 	  }
3053 
3054       if (some_failed)
3055 	{
3056 	  for (bp_location *loc : bpt->locations ())
3057 	    if (loc->inserted)
3058 	      remove_breakpoint (loc);
3059 
3060 	  hw_breakpoint_error = 1;
3061 	  tmp_error_stream.printf ("Could not insert "
3062 				   "hardware watchpoint %d.\n",
3063 				   bpt->number);
3064 	  error_flag = -1;
3065 	}
3066     }
3067 
3068   if (error_flag)
3069     {
3070       /* If a hardware breakpoint or watchpoint was inserted, add a
3071 	 message about possibly exhausted resources.  */
3072       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3073 	{
3074 	  tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3075 You may have requested too many hardware breakpoints/watchpoints.\n");
3076 	}
3077       target_terminal::ours_for_output ();
3078       error_stream (tmp_error_stream);
3079     }
3080 }
3081 
3082 /* Used when the program stops.
3083    Returns zero if successful, or non-zero if there was a problem
3084    removing a breakpoint location.  */
3085 
3086 int
remove_breakpoints(void)3087 remove_breakpoints (void)
3088 {
3089   int val = 0;
3090 
3091   for (bp_location *bl : all_bp_locations ())
3092     if (bl->inserted && !is_tracepoint (bl->owner))
3093       val |= remove_breakpoint (bl);
3094 
3095   return val;
3096 }
3097 
3098 /* When a thread exits, remove breakpoints that are related to
3099    that thread.  */
3100 
3101 static void
remove_threaded_breakpoints(struct thread_info * tp,int silent)3102 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3103 {
3104   for (breakpoint *b : all_breakpoints_safe ())
3105     {
3106       if (b->thread == tp->global_num && user_breakpoint_p (b))
3107 	{
3108 	  b->disposition = disp_del_at_next_stop;
3109 
3110 	  printf_filtered (_("\
3111 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3112 			   b->number, print_thread_id (tp));
3113 
3114 	  /* Hide it from the user.  */
3115 	  b->number = 0;
3116        }
3117     }
3118 }
3119 
3120 /* See breakpoint.h.  */
3121 
3122 void
remove_breakpoints_inf(inferior * inf)3123 remove_breakpoints_inf (inferior *inf)
3124 {
3125   int val;
3126 
3127   for (bp_location *bl : all_bp_locations ())
3128     {
3129       if (bl->pspace != inf->pspace)
3130 	continue;
3131 
3132       if (bl->inserted && !bl->target_info.persist)
3133 	{
3134 	  val = remove_breakpoint (bl);
3135 	  if (val != 0)
3136 	    return;
3137 	}
3138     }
3139 }
3140 
3141 static int internal_breakpoint_number = -1;
3142 
3143 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3144    If INTERNAL is non-zero, the breakpoint number will be populated
3145    from internal_breakpoint_number and that variable decremented.
3146    Otherwise the breakpoint number will be populated from
3147    breakpoint_count and that value incremented.  Internal breakpoints
3148    do not set the internal var bpnum.  */
3149 static void
set_breakpoint_number(int internal,struct breakpoint * b)3150 set_breakpoint_number (int internal, struct breakpoint *b)
3151 {
3152   if (internal)
3153     b->number = internal_breakpoint_number--;
3154   else
3155     {
3156       set_breakpoint_count (breakpoint_count + 1);
3157       b->number = breakpoint_count;
3158     }
3159 }
3160 
3161 static struct breakpoint *
create_internal_breakpoint(struct gdbarch * gdbarch,CORE_ADDR address,enum bptype type,const struct breakpoint_ops * ops)3162 create_internal_breakpoint (struct gdbarch *gdbarch,
3163 			    CORE_ADDR address, enum bptype type,
3164 			    const struct breakpoint_ops *ops)
3165 {
3166   symtab_and_line sal;
3167   sal.pc = address;
3168   sal.section = find_pc_overlay (sal.pc);
3169   sal.pspace = current_program_space;
3170 
3171   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3172   b->number = internal_breakpoint_number--;
3173   b->disposition = disp_donttouch;
3174 
3175   return b;
3176 }
3177 
3178 static const char *const longjmp_names[] =
3179   {
3180     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3181   };
3182 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3183 
3184 /* Per-objfile data private to breakpoint.c.  */
3185 struct breakpoint_objfile_data
3186 {
3187   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3188   struct bound_minimal_symbol overlay_msym {};
3189 
3190   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3191   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3192 
3193   /* True if we have looked for longjmp probes.  */
3194   int longjmp_searched = 0;
3195 
3196   /* SystemTap probe points for longjmp (if any).  These are non-owning
3197      references.  */
3198   std::vector<probe *> longjmp_probes;
3199 
3200   /* Minimal symbol for "std::terminate()" (if any).  */
3201   struct bound_minimal_symbol terminate_msym {};
3202 
3203   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3204   struct bound_minimal_symbol exception_msym {};
3205 
3206   /* True if we have looked for exception probes.  */
3207   int exception_searched = 0;
3208 
3209   /* SystemTap probe points for unwinding (if any).  These are non-owning
3210      references.  */
3211   std::vector<probe *> exception_probes;
3212 };
3213 
3214 static const struct objfile_key<breakpoint_objfile_data>
3215   breakpoint_objfile_key;
3216 
3217 /* Minimal symbol not found sentinel.  */
3218 static struct minimal_symbol msym_not_found;
3219 
3220 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3221 
3222 static int
3223 msym_not_found_p (const struct minimal_symbol *msym)
3224 {
3225   return msym == &msym_not_found;
3226 }
3227 
3228 /* Return per-objfile data needed by breakpoint.c.
3229    Allocate the data if necessary.  */
3230 
3231 static struct breakpoint_objfile_data *
3232 get_breakpoint_objfile_data (struct objfile *objfile)
3233 {
3234   struct breakpoint_objfile_data *bp_objfile_data;
3235 
3236   bp_objfile_data = breakpoint_objfile_key.get (objfile);
3237   if (bp_objfile_data == NULL)
3238     bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3239   return bp_objfile_data;
3240 }
3241 
3242 static void
3243 create_overlay_event_breakpoint (void)
3244 {
3245   const char *const func_name = "_ovly_debug_event";
3246 
3247   for (objfile *objfile : current_program_space->objfiles ())
3248     {
3249       struct breakpoint *b;
3250       struct breakpoint_objfile_data *bp_objfile_data;
3251       CORE_ADDR addr;
3252       struct explicit_location explicit_loc;
3253 
3254       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3255 
3256       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3257 	continue;
3258 
3259       if (bp_objfile_data->overlay_msym.minsym == NULL)
3260 	{
3261 	  struct bound_minimal_symbol m;
3262 
3263 	  m = lookup_minimal_symbol_text (func_name, objfile);
3264 	  if (m.minsym == NULL)
3265 	    {
3266 	      /* Avoid future lookups in this objfile.  */
3267 	      bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3268 	      continue;
3269 	    }
3270 	  bp_objfile_data->overlay_msym = m;
3271 	}
3272 
3273       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3274       b = create_internal_breakpoint (objfile->arch (), addr,
3275 				      bp_overlay_event,
3276 				      &internal_breakpoint_ops);
3277       initialize_explicit_location (&explicit_loc);
3278       explicit_loc.function_name = ASTRDUP (func_name);
3279       b->location = new_explicit_location (&explicit_loc);
3280 
3281       if (overlay_debugging == ovly_auto)
3282 	{
3283 	  b->enable_state = bp_enabled;
3284 	  overlay_events_enabled = 1;
3285 	}
3286       else
3287        {
3288 	 b->enable_state = bp_disabled;
3289 	 overlay_events_enabled = 0;
3290        }
3291     }
3292 }
3293 
3294 /* Install a master longjmp breakpoint for OBJFILE using a probe.  Return
3295    true if a breakpoint was installed.  */
3296 
3297 static bool
3298 create_longjmp_master_breakpoint_probe (objfile *objfile)
3299 {
3300   struct gdbarch *gdbarch = objfile->arch ();
3301   struct breakpoint_objfile_data *bp_objfile_data
3302     = get_breakpoint_objfile_data (objfile);
3303 
3304   if (!bp_objfile_data->longjmp_searched)
3305     {
3306       std::vector<probe *> ret
3307 	= find_probes_in_objfile (objfile, "libc", "longjmp");
3308 
3309       if (!ret.empty ())
3310 	{
3311 	  /* We are only interested in checking one element.  */
3312 	  probe *p = ret[0];
3313 
3314 	  if (!p->can_evaluate_arguments ())
3315 	    {
3316 	      /* We cannot use the probe interface here,
3317 		 because it does not know how to evaluate
3318 		 arguments.  */
3319 	      ret.clear ();
3320 	    }
3321 	}
3322       bp_objfile_data->longjmp_probes = ret;
3323       bp_objfile_data->longjmp_searched = 1;
3324     }
3325 
3326   if (bp_objfile_data->longjmp_probes.empty ())
3327     return false;
3328 
3329   for (probe *p : bp_objfile_data->longjmp_probes)
3330     {
3331       struct breakpoint *b;
3332 
3333       b = create_internal_breakpoint (gdbarch,
3334 				      p->get_relocated_address (objfile),
3335 				      bp_longjmp_master,
3336 				      &internal_breakpoint_ops);
3337       b->location = new_probe_location ("-probe-stap libc:longjmp");
3338       b->enable_state = bp_disabled;
3339     }
3340 
3341   return true;
3342 }
3343 
3344 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3345    Return true if at least one breakpoint was installed.  */
3346 
3347 static bool
3348 create_longjmp_master_breakpoint_names (objfile *objfile)
3349 {
3350   struct gdbarch *gdbarch = objfile->arch ();
3351   if (!gdbarch_get_longjmp_target_p (gdbarch))
3352     return false;
3353 
3354   struct breakpoint_objfile_data *bp_objfile_data
3355     = get_breakpoint_objfile_data (objfile);
3356   unsigned int installed_bp = 0;
3357 
3358   for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3359     {
3360       struct breakpoint *b;
3361       const char *func_name;
3362       CORE_ADDR addr;
3363       struct explicit_location explicit_loc;
3364 
3365       if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3366 	continue;
3367 
3368       func_name = longjmp_names[i];
3369       if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3370 	{
3371 	  struct bound_minimal_symbol m;
3372 
3373 	  m = lookup_minimal_symbol_text (func_name, objfile);
3374 	  if (m.minsym == NULL)
3375 	    {
3376 	      /* Prevent future lookups in this objfile.  */
3377 	      bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3378 	      continue;
3379 	    }
3380 	  bp_objfile_data->longjmp_msym[i] = m;
3381 	}
3382 
3383       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3384       b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3385 				      &internal_breakpoint_ops);
3386       initialize_explicit_location (&explicit_loc);
3387       explicit_loc.function_name = ASTRDUP (func_name);
3388       b->location = new_explicit_location (&explicit_loc);
3389       b->enable_state = bp_disabled;
3390       installed_bp++;
3391     }
3392 
3393   return installed_bp > 0;
3394 }
3395 
3396 /* Create a master longjmp breakpoint.  */
3397 
3398 static void
3399 create_longjmp_master_breakpoint (void)
3400 {
3401   scoped_restore_current_program_space restore_pspace;
3402 
3403   for (struct program_space *pspace : program_spaces)
3404     {
3405       set_current_program_space (pspace);
3406 
3407       for (objfile *obj : current_program_space->objfiles ())
3408 	{
3409 	  /* Skip separate debug object, it's handled in the loop below.  */
3410 	  if (obj->separate_debug_objfile_backlink != nullptr)
3411 	    continue;
3412 
3413 	  /* Try a probe kind breakpoint on main objfile.  */
3414 	  if (create_longjmp_master_breakpoint_probe (obj))
3415 	    continue;
3416 
3417 	  /* Try longjmp_names kind breakpoints on main and separate_debug
3418 	     objfiles.  */
3419 	  for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3420 	    if (create_longjmp_master_breakpoint_names (debug_objfile))
3421 	      break;
3422 	}
3423     }
3424 }
3425 
3426 /* Create a master std::terminate breakpoint.  */
3427 static void
3428 create_std_terminate_master_breakpoint (void)
3429 {
3430   const char *const func_name = "std::terminate()";
3431 
3432   scoped_restore_current_program_space restore_pspace;
3433 
3434   for (struct program_space *pspace : program_spaces)
3435     {
3436       CORE_ADDR addr;
3437 
3438       set_current_program_space (pspace);
3439 
3440       for (objfile *objfile : current_program_space->objfiles ())
3441 	{
3442 	  struct breakpoint *b;
3443 	  struct breakpoint_objfile_data *bp_objfile_data;
3444 	  struct explicit_location explicit_loc;
3445 
3446 	  bp_objfile_data = get_breakpoint_objfile_data (objfile);
3447 
3448 	  if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3449 	    continue;
3450 
3451 	  if (bp_objfile_data->terminate_msym.minsym == NULL)
3452 	    {
3453 	      struct bound_minimal_symbol m;
3454 
3455 	      m = lookup_minimal_symbol (func_name, NULL, objfile);
3456 	      if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3457 				       && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3458 		{
3459 		  /* Prevent future lookups in this objfile.  */
3460 		  bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3461 		  continue;
3462 		}
3463 	      bp_objfile_data->terminate_msym = m;
3464 	    }
3465 
3466 	  addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3467 	  b = create_internal_breakpoint (objfile->arch (), addr,
3468 					  bp_std_terminate_master,
3469 					  &internal_breakpoint_ops);
3470 	  initialize_explicit_location (&explicit_loc);
3471 	  explicit_loc.function_name = ASTRDUP (func_name);
3472 	  b->location = new_explicit_location (&explicit_loc);
3473 	  b->enable_state = bp_disabled;
3474 	}
3475     }
3476 }
3477 
3478 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3479    probe.  Return true if a breakpoint was installed.  */
3480 
3481 static bool
3482 create_exception_master_breakpoint_probe (objfile *objfile)
3483 {
3484   struct breakpoint *b;
3485   struct gdbarch *gdbarch;
3486   struct breakpoint_objfile_data *bp_objfile_data;
3487 
3488   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3489 
3490   /* We prefer the SystemTap probe point if it exists.  */
3491   if (!bp_objfile_data->exception_searched)
3492     {
3493       std::vector<probe *> ret
3494 	= find_probes_in_objfile (objfile, "libgcc", "unwind");
3495 
3496       if (!ret.empty ())
3497 	{
3498 	  /* We are only interested in checking one element.  */
3499 	  probe *p = ret[0];
3500 
3501 	  if (!p->can_evaluate_arguments ())
3502 	    {
3503 	      /* We cannot use the probe interface here, because it does
3504 		 not know how to evaluate arguments.  */
3505 	      ret.clear ();
3506 	    }
3507 	}
3508       bp_objfile_data->exception_probes = ret;
3509       bp_objfile_data->exception_searched = 1;
3510     }
3511 
3512   if (bp_objfile_data->exception_probes.empty ())
3513     return false;
3514 
3515   gdbarch = objfile->arch ();
3516 
3517   for (probe *p : bp_objfile_data->exception_probes)
3518     {
3519       b = create_internal_breakpoint (gdbarch,
3520 				      p->get_relocated_address (objfile),
3521 				      bp_exception_master,
3522 				      &internal_breakpoint_ops);
3523       b->location = new_probe_location ("-probe-stap libgcc:unwind");
3524       b->enable_state = bp_disabled;
3525     }
3526 
3527   return true;
3528 }
3529 
3530 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3531    _Unwind_DebugHook.  Return true if a breakpoint was installed.  */
3532 
3533 static bool
3534 create_exception_master_breakpoint_hook (objfile *objfile)
3535 {
3536   const char *const func_name = "_Unwind_DebugHook";
3537   struct breakpoint *b;
3538   struct gdbarch *gdbarch;
3539   struct breakpoint_objfile_data *bp_objfile_data;
3540   CORE_ADDR addr;
3541   struct explicit_location explicit_loc;
3542 
3543   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3544 
3545   if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3546     return false;
3547 
3548   gdbarch = objfile->arch ();
3549 
3550   if (bp_objfile_data->exception_msym.minsym == NULL)
3551     {
3552       struct bound_minimal_symbol debug_hook;
3553 
3554       debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3555       if (debug_hook.minsym == NULL)
3556 	{
3557 	  bp_objfile_data->exception_msym.minsym = &msym_not_found;
3558 	  return false;
3559 	}
3560 
3561       bp_objfile_data->exception_msym = debug_hook;
3562     }
3563 
3564   addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3565   addr = gdbarch_convert_from_func_ptr_addr
3566     (gdbarch, addr, current_inferior ()->top_target ());
3567   b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3568 				  &internal_breakpoint_ops);
3569   initialize_explicit_location (&explicit_loc);
3570   explicit_loc.function_name = ASTRDUP (func_name);
3571   b->location = new_explicit_location (&explicit_loc);
3572   b->enable_state = bp_disabled;
3573 
3574   return true;
3575 }
3576 
3577 /* Install a master breakpoint on the unwinder's debug hook.  */
3578 
3579 static void
3580 create_exception_master_breakpoint (void)
3581 {
3582   for (objfile *obj : current_program_space->objfiles ())
3583     {
3584       /* Skip separate debug object.  */
3585       if (obj->separate_debug_objfile_backlink)
3586 	continue;
3587 
3588       /* Try a probe kind breakpoint.  */
3589       if (create_exception_master_breakpoint_probe (obj))
3590 	continue;
3591 
3592       /* Iterate over main and separate debug objects and try an
3593 	 _Unwind_DebugHook kind breakpoint.  */
3594       for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3595 	if (create_exception_master_breakpoint_hook (debug_objfile))
3596 	  break;
3597     }
3598 }
3599 
3600 /* Does B have a location spec?  */
3601 
3602 static int
3603 breakpoint_event_location_empty_p (const struct breakpoint *b)
3604 {
3605   return b->location != NULL && event_location_empty_p (b->location.get ());
3606 }
3607 
3608 void
3609 update_breakpoints_after_exec (void)
3610 {
3611   /* We're about to delete breakpoints from GDB's lists.  If the
3612      INSERTED flag is true, GDB will try to lift the breakpoints by
3613      writing the breakpoints' "shadow contents" back into memory.  The
3614      "shadow contents" are NOT valid after an exec, so GDB should not
3615      do that.  Instead, the target is responsible from marking
3616      breakpoints out as soon as it detects an exec.  We don't do that
3617      here instead, because there may be other attempts to delete
3618      breakpoints after detecting an exec and before reaching here.  */
3619   for (bp_location *bploc : all_bp_locations ())
3620     if (bploc->pspace == current_program_space)
3621       gdb_assert (!bploc->inserted);
3622 
3623   for (breakpoint *b : all_breakpoints_safe ())
3624     {
3625       if (b->pspace != current_program_space)
3626 	continue;
3627 
3628       /* Solib breakpoints must be explicitly reset after an exec().  */
3629       if (b->type == bp_shlib_event)
3630 	{
3631 	  delete_breakpoint (b);
3632 	  continue;
3633 	}
3634 
3635       /* JIT breakpoints must be explicitly reset after an exec().  */
3636       if (b->type == bp_jit_event)
3637 	{
3638 	  delete_breakpoint (b);
3639 	  continue;
3640 	}
3641 
3642       /* Thread event breakpoints must be set anew after an exec(),
3643 	 as must overlay event and longjmp master breakpoints.  */
3644       if (b->type == bp_thread_event || b->type == bp_overlay_event
3645 	  || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3646 	  || b->type == bp_exception_master)
3647 	{
3648 	  delete_breakpoint (b);
3649 	  continue;
3650 	}
3651 
3652       /* Step-resume breakpoints are meaningless after an exec().  */
3653       if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3654 	{
3655 	  delete_breakpoint (b);
3656 	  continue;
3657 	}
3658 
3659       /* Just like single-step breakpoints.  */
3660       if (b->type == bp_single_step)
3661 	{
3662 	  delete_breakpoint (b);
3663 	  continue;
3664 	}
3665 
3666       /* Longjmp and longjmp-resume breakpoints are also meaningless
3667 	 after an exec.  */
3668       if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3669 	  || b->type == bp_longjmp_call_dummy
3670 	  || b->type == bp_exception || b->type == bp_exception_resume)
3671 	{
3672 	  delete_breakpoint (b);
3673 	  continue;
3674 	}
3675 
3676       if (b->type == bp_catchpoint)
3677 	{
3678 	  /* For now, none of the bp_catchpoint breakpoints need to
3679 	     do anything at this point.  In the future, if some of
3680 	     the catchpoints need to something, we will need to add
3681 	     a new method, and call this method from here.  */
3682 	  continue;
3683 	}
3684 
3685       /* bp_finish is a special case.  The only way we ought to be able
3686 	 to see one of these when an exec() has happened, is if the user
3687 	 caught a vfork, and then said "finish".  Ordinarily a finish just
3688 	 carries them to the call-site of the current callee, by setting
3689 	 a temporary bp there and resuming.  But in this case, the finish
3690 	 will carry them entirely through the vfork & exec.
3691 
3692 	 We don't want to allow a bp_finish to remain inserted now.  But
3693 	 we can't safely delete it, 'cause finish_command has a handle to
3694 	 the bp on a bpstat, and will later want to delete it.  There's a
3695 	 chance (and I've seen it happen) that if we delete the bp_finish
3696 	 here, that its storage will get reused by the time finish_command
3697 	 gets 'round to deleting the "use to be a bp_finish" breakpoint.
3698 	 We really must allow finish_command to delete a bp_finish.
3699 
3700 	 In the absence of a general solution for the "how do we know
3701 	 it's safe to delete something others may have handles to?"
3702 	 problem, what we'll do here is just uninsert the bp_finish, and
3703 	 let finish_command delete it.
3704 
3705 	 (We know the bp_finish is "doomed" in the sense that it's
3706 	 momentary, and will be deleted as soon as finish_command sees
3707 	 the inferior stopped.  So it doesn't matter that the bp's
3708 	 address is probably bogus in the new a.out, unlike e.g., the
3709 	 solib breakpoints.)  */
3710 
3711       if (b->type == bp_finish)
3712 	{
3713 	  continue;
3714 	}
3715 
3716       /* Without a symbolic address, we have little hope of the
3717 	 pre-exec() address meaning the same thing in the post-exec()
3718 	 a.out.  */
3719       if (breakpoint_event_location_empty_p (b))
3720 	{
3721 	  delete_breakpoint (b);
3722 	  continue;
3723 	}
3724     }
3725 }
3726 
3727 int
3728 detach_breakpoints (ptid_t ptid)
3729 {
3730   int val = 0;
3731   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3732   struct inferior *inf = current_inferior ();
3733 
3734   if (ptid.pid () == inferior_ptid.pid ())
3735     error (_("Cannot detach breakpoints of inferior_ptid"));
3736 
3737   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3738   inferior_ptid = ptid;
3739   for (bp_location *bl : all_bp_locations ())
3740     {
3741       if (bl->pspace != inf->pspace)
3742 	continue;
3743 
3744       /* This function must physically remove breakpoints locations
3745 	 from the specified ptid, without modifying the breakpoint
3746 	 package's state.  Locations of type bp_loc_other are only
3747 	 maintained at GDB side.  So, there is no need to remove
3748 	 these bp_loc_other locations.  Moreover, removing these
3749 	 would modify the breakpoint package's state.  */
3750       if (bl->loc_type == bp_loc_other)
3751 	continue;
3752 
3753       if (bl->inserted)
3754 	val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3755     }
3756 
3757   return val;
3758 }
3759 
3760 /* Remove the breakpoint location BL from the current address space.
3761    Note that this is used to detach breakpoints from a child fork.
3762    When we get here, the child isn't in the inferior list, and neither
3763    do we have objects to represent its address space --- we should
3764    *not* look at bl->pspace->aspace here.  */
3765 
3766 static int
3767 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3768 {
3769   int val;
3770 
3771   /* BL is never in moribund_locations by our callers.  */
3772   gdb_assert (bl->owner != NULL);
3773 
3774   /* The type of none suggests that owner is actually deleted.
3775      This should not ever happen.  */
3776   gdb_assert (bl->owner->type != bp_none);
3777 
3778   if (bl->loc_type == bp_loc_software_breakpoint
3779       || bl->loc_type == bp_loc_hardware_breakpoint)
3780     {
3781       /* "Normal" instruction breakpoint: either the standard
3782 	 trap-instruction bp (bp_breakpoint), or a
3783 	 bp_hardware_breakpoint.  */
3784 
3785       /* First check to see if we have to handle an overlay.  */
3786       if (overlay_debugging == ovly_off
3787 	  || bl->section == NULL
3788 	  || !(section_is_overlay (bl->section)))
3789 	{
3790 	  /* No overlay handling: just remove the breakpoint.  */
3791 
3792 	  /* If we're trying to uninsert a memory breakpoint that we
3793 	     know is set in a dynamic object that is marked
3794 	     shlib_disabled, then either the dynamic object was
3795 	     removed with "remove-symbol-file" or with
3796 	     "nosharedlibrary".  In the former case, we don't know
3797 	     whether another dynamic object might have loaded over the
3798 	     breakpoint's address -- the user might well let us know
3799 	     about it next with add-symbol-file (the whole point of
3800 	     add-symbol-file is letting the user manually maintain a
3801 	     list of dynamically loaded objects).  If we have the
3802 	     breakpoint's shadow memory, that is, this is a software
3803 	     breakpoint managed by GDB, check whether the breakpoint
3804 	     is still inserted in memory, to avoid overwriting wrong
3805 	     code with stale saved shadow contents.  Note that HW
3806 	     breakpoints don't have shadow memory, as they're
3807 	     implemented using a mechanism that is not dependent on
3808 	     being able to modify the target's memory, and as such
3809 	     they should always be removed.  */
3810 	  if (bl->shlib_disabled
3811 	      && bl->target_info.shadow_len != 0
3812 	      && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3813 	    val = 0;
3814 	  else
3815 	    val = bl->owner->ops->remove_location (bl, reason);
3816 	}
3817       else
3818 	{
3819 	  /* This breakpoint is in an overlay section.
3820 	     Did we set a breakpoint at the LMA?  */
3821 	  if (!overlay_events_enabled)
3822 	      {
3823 		/* Yes -- overlay event support is not active, so we
3824 		   should have set a breakpoint at the LMA.  Remove it.
3825 		*/
3826 		/* Ignore any failures: if the LMA is in ROM, we will
3827 		   have already warned when we failed to insert it.  */
3828 		if (bl->loc_type == bp_loc_hardware_breakpoint)
3829 		  target_remove_hw_breakpoint (bl->gdbarch,
3830 					       &bl->overlay_target_info);
3831 		else
3832 		  target_remove_breakpoint (bl->gdbarch,
3833 					    &bl->overlay_target_info,
3834 					    reason);
3835 	      }
3836 	  /* Did we set a breakpoint at the VMA?
3837 	     If so, we will have marked the breakpoint 'inserted'.  */
3838 	  if (bl->inserted)
3839 	    {
3840 	      /* Yes -- remove it.  Previously we did not bother to
3841 		 remove the breakpoint if the section had been
3842 		 unmapped, but let's not rely on that being safe.  We
3843 		 don't know what the overlay manager might do.  */
3844 
3845 	      /* However, we should remove *software* breakpoints only
3846 		 if the section is still mapped, or else we overwrite
3847 		 wrong code with the saved shadow contents.  */
3848 	      if (bl->loc_type == bp_loc_hardware_breakpoint
3849 		  || section_is_mapped (bl->section))
3850 		val = bl->owner->ops->remove_location (bl, reason);
3851 	      else
3852 		val = 0;
3853 	    }
3854 	  else
3855 	    {
3856 	      /* No -- not inserted, so no need to remove.  No error.  */
3857 	      val = 0;
3858 	    }
3859 	}
3860 
3861       /* In some cases, we might not be able to remove a breakpoint in
3862 	 a shared library that has already been removed, but we have
3863 	 not yet processed the shlib unload event.  Similarly for an
3864 	 unloaded add-symbol-file object - the user might not yet have
3865 	 had the chance to remove-symbol-file it.  shlib_disabled will
3866 	 be set if the library/object has already been removed, but
3867 	 the breakpoint hasn't been uninserted yet, e.g., after
3868 	 "nosharedlibrary" or "remove-symbol-file" with breakpoints
3869 	 always-inserted mode.  */
3870       if (val
3871 	  && (bl->loc_type == bp_loc_software_breakpoint
3872 	      && (bl->shlib_disabled
3873 		  || solib_name_from_address (bl->pspace, bl->address)
3874 		  || shared_objfile_contains_address_p (bl->pspace,
3875 							bl->address))))
3876 	val = 0;
3877 
3878       if (val)
3879 	return val;
3880       bl->inserted = (reason == DETACH_BREAKPOINT);
3881     }
3882   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3883     {
3884       gdb_assert (bl->owner->ops != NULL
3885 		  && bl->owner->ops->remove_location != NULL);
3886 
3887       bl->inserted = (reason == DETACH_BREAKPOINT);
3888       bl->owner->ops->remove_location (bl, reason);
3889 
3890       /* Failure to remove any of the hardware watchpoints comes here.  */
3891       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3892 	warning (_("Could not remove hardware watchpoint %d."),
3893 		 bl->owner->number);
3894     }
3895   else if (bl->owner->type == bp_catchpoint
3896 	   && breakpoint_enabled (bl->owner)
3897 	   && !bl->duplicate)
3898     {
3899       gdb_assert (bl->owner->ops != NULL
3900 		  && bl->owner->ops->remove_location != NULL);
3901 
3902       val = bl->owner->ops->remove_location (bl, reason);
3903       if (val)
3904 	return val;
3905 
3906       bl->inserted = (reason == DETACH_BREAKPOINT);
3907     }
3908 
3909   return 0;
3910 }
3911 
3912 static int
3913 remove_breakpoint (struct bp_location *bl)
3914 {
3915   /* BL is never in moribund_locations by our callers.  */
3916   gdb_assert (bl->owner != NULL);
3917 
3918   /* The type of none suggests that owner is actually deleted.
3919      This should not ever happen.  */
3920   gdb_assert (bl->owner->type != bp_none);
3921 
3922   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3923 
3924   switch_to_program_space_and_thread (bl->pspace);
3925 
3926   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3927 }
3928 
3929 /* Clear the "inserted" flag in all breakpoints.  */
3930 
3931 void
3932 mark_breakpoints_out (void)
3933 {
3934   for (bp_location *bl : all_bp_locations ())
3935     if (bl->pspace == current_program_space)
3936       bl->inserted = 0;
3937 }
3938 
3939 /* Clear the "inserted" flag in all breakpoints and delete any
3940    breakpoints which should go away between runs of the program.
3941 
3942    Plus other such housekeeping that has to be done for breakpoints
3943    between runs.
3944 
3945    Note: this function gets called at the end of a run (by
3946    generic_mourn_inferior) and when a run begins (by
3947    init_wait_for_inferior).  */
3948 
3949 
3950 
3951 void
3952 breakpoint_init_inferior (enum inf_context context)
3953 {
3954   struct program_space *pspace = current_program_space;
3955 
3956   /* If breakpoint locations are shared across processes, then there's
3957      nothing to do.  */
3958   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3959     return;
3960 
3961   mark_breakpoints_out ();
3962 
3963   for (breakpoint *b : all_breakpoints_safe ())
3964     {
3965       if (b->loc && b->loc->pspace != pspace)
3966 	continue;
3967 
3968       switch (b->type)
3969 	{
3970 	case bp_call_dummy:
3971 	case bp_longjmp_call_dummy:
3972 
3973 	  /* If the call dummy breakpoint is at the entry point it will
3974 	     cause problems when the inferior is rerun, so we better get
3975 	     rid of it.  */
3976 
3977 	case bp_watchpoint_scope:
3978 
3979 	  /* Also get rid of scope breakpoints.  */
3980 
3981 	case bp_shlib_event:
3982 
3983 	  /* Also remove solib event breakpoints.  Their addresses may
3984 	     have changed since the last time we ran the program.
3985 	     Actually we may now be debugging against different target;
3986 	     and so the solib backend that installed this breakpoint may
3987 	     not be used in by the target.  E.g.,
3988 
3989 	     (gdb) file prog-linux
3990 	     (gdb) run               # native linux target
3991 	     ...
3992 	     (gdb) kill
3993 	     (gdb) file prog-win.exe
3994 	     (gdb) tar rem :9999     # remote Windows gdbserver.
3995 	  */
3996 
3997 	case bp_step_resume:
3998 
3999 	  /* Also remove step-resume breakpoints.  */
4000 
4001 	case bp_single_step:
4002 
4003 	  /* Also remove single-step breakpoints.  */
4004 
4005 	  delete_breakpoint (b);
4006 	  break;
4007 
4008 	case bp_watchpoint:
4009 	case bp_hardware_watchpoint:
4010 	case bp_read_watchpoint:
4011 	case bp_access_watchpoint:
4012 	  {
4013 	    struct watchpoint *w = (struct watchpoint *) b;
4014 
4015 	    /* Likewise for watchpoints on local expressions.  */
4016 	    if (w->exp_valid_block != NULL)
4017 	      delete_breakpoint (b);
4018 	    else
4019 	      {
4020 		/* Get rid of existing locations, which are no longer
4021 		   valid.  New ones will be created in
4022 		   update_watchpoint, when the inferior is restarted.
4023 		   The next update_global_location_list call will
4024 		   garbage collect them.  */
4025 		b->loc = NULL;
4026 
4027 		if (context == inf_starting)
4028 		  {
4029 		    /* Reset val field to force reread of starting value in
4030 		       insert_breakpoints.  */
4031 		    w->val.reset (nullptr);
4032 		    w->val_valid = false;
4033 		  }
4034 	      }
4035 	  }
4036 	  break;
4037 	default:
4038 	  break;
4039 	}
4040     }
4041 
4042   /* Get rid of the moribund locations.  */
4043   for (bp_location *bl : moribund_locations)
4044     decref_bp_location (&bl);
4045   moribund_locations.clear ();
4046 }
4047 
4048 /* These functions concern about actual breakpoints inserted in the
4049    target --- to e.g. check if we need to do decr_pc adjustment or if
4050    we need to hop over the bkpt --- so we check for address space
4051    match, not program space.  */
4052 
4053 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4054    exists at PC.  It returns ordinary_breakpoint_here if it's an
4055    ordinary breakpoint, or permanent_breakpoint_here if it's a
4056    permanent breakpoint.
4057    - When continuing from a location with an ordinary breakpoint, we
4058      actually single step once before calling insert_breakpoints.
4059    - When continuing from a location with a permanent breakpoint, we
4060      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4061      the target, to advance the PC past the breakpoint.  */
4062 
4063 enum breakpoint_here
4064 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4065 {
4066   int any_breakpoint_here = 0;
4067 
4068   for (bp_location *bl : all_bp_locations ())
4069     {
4070       if (bl->loc_type != bp_loc_software_breakpoint
4071 	  && bl->loc_type != bp_loc_hardware_breakpoint)
4072 	continue;
4073 
4074       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4075       if ((breakpoint_enabled (bl->owner)
4076 	   || bl->permanent)
4077 	  && breakpoint_location_address_match (bl, aspace, pc))
4078 	{
4079 	  if (overlay_debugging
4080 	      && section_is_overlay (bl->section)
4081 	      && !section_is_mapped (bl->section))
4082 	    continue;		/* unmapped overlay -- can't be a match */
4083 	  else if (bl->permanent)
4084 	    return permanent_breakpoint_here;
4085 	  else
4086 	    any_breakpoint_here = 1;
4087 	}
4088     }
4089 
4090   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4091 }
4092 
4093 /* See breakpoint.h.  */
4094 
4095 int
4096 breakpoint_in_range_p (const address_space *aspace,
4097 		       CORE_ADDR addr, ULONGEST len)
4098 {
4099   for (bp_location *bl : all_bp_locations ())
4100     {
4101       if (bl->loc_type != bp_loc_software_breakpoint
4102 	  && bl->loc_type != bp_loc_hardware_breakpoint)
4103 	continue;
4104 
4105       if ((breakpoint_enabled (bl->owner)
4106 	   || bl->permanent)
4107 	  && breakpoint_location_address_range_overlap (bl, aspace,
4108 							addr, len))
4109 	{
4110 	  if (overlay_debugging
4111 	      && section_is_overlay (bl->section)
4112 	      && !section_is_mapped (bl->section))
4113 	    {
4114 	      /* Unmapped overlay -- can't be a match.  */
4115 	      continue;
4116 	    }
4117 
4118 	  return 1;
4119 	}
4120     }
4121 
4122   return 0;
4123 }
4124 
4125 /* Return true if there's a moribund breakpoint at PC.  */
4126 
4127 int
4128 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4129 {
4130   for (bp_location *loc : moribund_locations)
4131     if (breakpoint_location_address_match (loc, aspace, pc))
4132       return 1;
4133 
4134   return 0;
4135 }
4136 
4137 /* Returns non-zero iff BL is inserted at PC, in address space
4138    ASPACE.  */
4139 
4140 static int
4141 bp_location_inserted_here_p (struct bp_location *bl,
4142 			     const address_space *aspace, CORE_ADDR pc)
4143 {
4144   if (bl->inserted
4145       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4146 				   aspace, pc))
4147     {
4148       if (overlay_debugging
4149 	  && section_is_overlay (bl->section)
4150 	  && !section_is_mapped (bl->section))
4151 	return 0;		/* unmapped overlay -- can't be a match */
4152       else
4153 	return 1;
4154     }
4155   return 0;
4156 }
4157 
4158 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4159 
4160 int
4161 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4162 {
4163   for (bp_location *bl : all_bp_locations_at_addr (pc))
4164     {
4165       if (bl->loc_type != bp_loc_software_breakpoint
4166 	  && bl->loc_type != bp_loc_hardware_breakpoint)
4167 	continue;
4168 
4169       if (bp_location_inserted_here_p (bl, aspace, pc))
4170 	return 1;
4171     }
4172   return 0;
4173 }
4174 
4175 /* This function returns non-zero iff there is a software breakpoint
4176    inserted at PC.  */
4177 
4178 int
4179 software_breakpoint_inserted_here_p (const address_space *aspace,
4180 				     CORE_ADDR pc)
4181 {
4182   for (bp_location *bl : all_bp_locations_at_addr (pc))
4183     {
4184       if (bl->loc_type != bp_loc_software_breakpoint)
4185 	continue;
4186 
4187       if (bp_location_inserted_here_p (bl, aspace, pc))
4188 	return 1;
4189     }
4190 
4191   return 0;
4192 }
4193 
4194 /* See breakpoint.h.  */
4195 
4196 int
4197 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4198 				     CORE_ADDR pc)
4199 {
4200   for (bp_location *bl : all_bp_locations_at_addr (pc))
4201     {
4202       if (bl->loc_type != bp_loc_hardware_breakpoint)
4203 	continue;
4204 
4205       if (bp_location_inserted_here_p (bl, aspace, pc))
4206 	return 1;
4207     }
4208 
4209   return 0;
4210 }
4211 
4212 int
4213 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4214 				       CORE_ADDR addr, ULONGEST len)
4215 {
4216   for (breakpoint *bpt : all_breakpoints ())
4217     {
4218       if (bpt->type != bp_hardware_watchpoint
4219 	  && bpt->type != bp_access_watchpoint)
4220 	continue;
4221 
4222       if (!breakpoint_enabled (bpt))
4223 	continue;
4224 
4225       for (bp_location *loc : bpt->locations ())
4226 	if (loc->pspace->aspace == aspace && loc->inserted)
4227 	  {
4228 	    CORE_ADDR l, h;
4229 
4230 	    /* Check for intersection.  */
4231 	    l = std::max<CORE_ADDR> (loc->address, addr);
4232 	    h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4233 	    if (l < h)
4234 	      return 1;
4235 	  }
4236     }
4237   return 0;
4238 }
4239 
4240 /* See breakpoint.h.  */
4241 
4242 bool
4243 is_catchpoint (struct breakpoint *b)
4244 {
4245   return (b->type == bp_catchpoint);
4246 }
4247 
4248 /* Clear a bpstat so that it says we are not at any breakpoint.
4249    Also free any storage that is part of a bpstat.  */
4250 
4251 void
4252 bpstat_clear (bpstat *bsp)
4253 {
4254   bpstat p;
4255   bpstat q;
4256 
4257   if (bsp == 0)
4258     return;
4259   p = *bsp;
4260   while (p != NULL)
4261     {
4262       q = p->next;
4263       delete p;
4264       p = q;
4265     }
4266   *bsp = NULL;
4267 }
4268 
4269 bpstats::bpstats (const bpstats &other)
4270   : next (NULL),
4271     bp_location_at (other.bp_location_at),
4272     breakpoint_at (other.breakpoint_at),
4273     commands (other.commands),
4274     print (other.print),
4275     stop (other.stop),
4276     print_it (other.print_it)
4277 {
4278   if (other.old_val != NULL)
4279     old_val = release_value (value_copy (other.old_val.get ()));
4280 }
4281 
4282 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4283    is part of the bpstat is copied as well.  */
4284 
4285 bpstat
4286 bpstat_copy (bpstat bs)
4287 {
4288   bpstat p = NULL;
4289   bpstat tmp;
4290   bpstat retval = NULL;
4291 
4292   if (bs == NULL)
4293     return bs;
4294 
4295   for (; bs != NULL; bs = bs->next)
4296     {
4297       tmp = new bpstats (*bs);
4298 
4299       if (p == NULL)
4300 	/* This is the first thing in the chain.  */
4301 	retval = tmp;
4302       else
4303 	p->next = tmp;
4304       p = tmp;
4305     }
4306   p->next = NULL;
4307   return retval;
4308 }
4309 
4310 /* Find the bpstat associated with this breakpoint.  */
4311 
4312 bpstat
4313 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4314 {
4315   if (bsp == NULL)
4316     return NULL;
4317 
4318   for (; bsp != NULL; bsp = bsp->next)
4319     {
4320       if (bsp->breakpoint_at == breakpoint)
4321 	return bsp;
4322     }
4323   return NULL;
4324 }
4325 
4326 /* See breakpoint.h.  */
4327 
4328 bool
4329 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4330 {
4331   for (; bsp != NULL; bsp = bsp->next)
4332     {
4333       if (bsp->breakpoint_at == NULL)
4334 	{
4335 	  /* A moribund location can never explain a signal other than
4336 	     GDB_SIGNAL_TRAP.  */
4337 	  if (sig == GDB_SIGNAL_TRAP)
4338 	    return true;
4339 	}
4340       else
4341 	{
4342 	  if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4343 							sig))
4344 	    return true;
4345 	}
4346     }
4347 
4348   return false;
4349 }
4350 
4351 /* Put in *NUM the breakpoint number of the first breakpoint we are
4352    stopped at.  *BSP upon return is a bpstat which points to the
4353    remaining breakpoints stopped at (but which is not guaranteed to be
4354    good for anything but further calls to bpstat_num).
4355 
4356    Return 0 if passed a bpstat which does not indicate any breakpoints.
4357    Return -1 if stopped at a breakpoint that has been deleted since
4358    we set it.
4359    Return 1 otherwise.  */
4360 
4361 int
4362 bpstat_num (bpstat *bsp, int *num)
4363 {
4364   struct breakpoint *b;
4365 
4366   if ((*bsp) == NULL)
4367     return 0;			/* No more breakpoint values */
4368 
4369   /* We assume we'll never have several bpstats that correspond to a
4370      single breakpoint -- otherwise, this function might return the
4371      same number more than once and this will look ugly.  */
4372   b = (*bsp)->breakpoint_at;
4373   *bsp = (*bsp)->next;
4374   if (b == NULL)
4375     return -1;			/* breakpoint that's been deleted since */
4376 
4377   *num = b->number;		/* We have its number */
4378   return 1;
4379 }
4380 
4381 /* See breakpoint.h.  */
4382 
4383 void
4384 bpstat_clear_actions (void)
4385 {
4386   bpstat bs;
4387 
4388   if (inferior_ptid == null_ptid)
4389     return;
4390 
4391   thread_info *tp = inferior_thread ();
4392   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4393     {
4394       bs->commands = NULL;
4395       bs->old_val.reset (nullptr);
4396     }
4397 }
4398 
4399 /* Called when a command is about to proceed the inferior.  */
4400 
4401 static void
4402 breakpoint_about_to_proceed (void)
4403 {
4404   if (inferior_ptid != null_ptid)
4405     {
4406       struct thread_info *tp = inferior_thread ();
4407 
4408       /* Allow inferior function calls in breakpoint commands to not
4409 	 interrupt the command list.  When the call finishes
4410 	 successfully, the inferior will be standing at the same
4411 	 breakpoint as if nothing happened.  */
4412       if (tp->control.in_infcall)
4413 	return;
4414     }
4415 
4416   breakpoint_proceeded = 1;
4417 }
4418 
4419 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4420    or its equivalent.  */
4421 
4422 static int
4423 command_line_is_silent (struct command_line *cmd)
4424 {
4425   return cmd && (strcmp ("silent", cmd->line) == 0);
4426 }
4427 
4428 /* Execute all the commands associated with all the breakpoints at
4429    this location.  Any of these commands could cause the process to
4430    proceed beyond this point, etc.  We look out for such changes by
4431    checking the global "breakpoint_proceeded" after each command.
4432 
4433    Returns true if a breakpoint command resumed the inferior.  In that
4434    case, it is the caller's responsibility to recall it again with the
4435    bpstat of the current thread.  */
4436 
4437 static int
4438 bpstat_do_actions_1 (bpstat *bsp)
4439 {
4440   bpstat bs;
4441   int again = 0;
4442 
4443   /* Avoid endless recursion if a `source' command is contained
4444      in bs->commands.  */
4445   if (executing_breakpoint_commands)
4446     return 0;
4447 
4448   scoped_restore save_executing
4449     = make_scoped_restore (&executing_breakpoint_commands, 1);
4450 
4451   scoped_restore preventer = prevent_dont_repeat ();
4452 
4453   /* This pointer will iterate over the list of bpstat's.  */
4454   bs = *bsp;
4455 
4456   breakpoint_proceeded = 0;
4457   for (; bs != NULL; bs = bs->next)
4458     {
4459       struct command_line *cmd = NULL;
4460 
4461       /* Take ownership of the BSP's command tree, if it has one.
4462 
4463 	 The command tree could legitimately contain commands like
4464 	 'step' and 'next', which call clear_proceed_status, which
4465 	 frees stop_bpstat's command tree.  To make sure this doesn't
4466 	 free the tree we're executing out from under us, we need to
4467 	 take ownership of the tree ourselves.  Since a given bpstat's
4468 	 commands are only executed once, we don't need to copy it; we
4469 	 can clear the pointer in the bpstat, and make sure we free
4470 	 the tree when we're done.  */
4471       counted_command_line ccmd = bs->commands;
4472       bs->commands = NULL;
4473       if (ccmd != NULL)
4474 	cmd = ccmd.get ();
4475       if (command_line_is_silent (cmd))
4476 	{
4477 	  /* The action has been already done by bpstat_stop_status.  */
4478 	  cmd = cmd->next;
4479 	}
4480 
4481       while (cmd != NULL)
4482 	{
4483 	  execute_control_command (cmd);
4484 
4485 	  if (breakpoint_proceeded)
4486 	    break;
4487 	  else
4488 	    cmd = cmd->next;
4489 	}
4490 
4491       if (breakpoint_proceeded)
4492 	{
4493 	  if (current_ui->async)
4494 	    /* If we are in async mode, then the target might be still
4495 	       running, not stopped at any breakpoint, so nothing for
4496 	       us to do here -- just return to the event loop.  */
4497 	    ;
4498 	  else
4499 	    /* In sync mode, when execute_control_command returns
4500 	       we're already standing on the next breakpoint.
4501 	       Breakpoint commands for that stop were not run, since
4502 	       execute_command does not run breakpoint commands --
4503 	       only command_line_handler does, but that one is not
4504 	       involved in execution of breakpoint commands.  So, we
4505 	       can now execute breakpoint commands.  It should be
4506 	       noted that making execute_command do bpstat actions is
4507 	       not an option -- in this case we'll have recursive
4508 	       invocation of bpstat for each breakpoint with a
4509 	       command, and can easily blow up GDB stack.  Instead, we
4510 	       return true, which will trigger the caller to recall us
4511 	       with the new stop_bpstat.  */
4512 	    again = 1;
4513 	  break;
4514 	}
4515     }
4516   return again;
4517 }
4518 
4519 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4520    one, is alive and has execution.  Return NULL otherwise.  */
4521 
4522 static thread_info *
4523 get_bpstat_thread ()
4524 {
4525   if (inferior_ptid == null_ptid || !target_has_execution ())
4526     return NULL;
4527 
4528   thread_info *tp = inferior_thread ();
4529   if (tp->state == THREAD_EXITED || tp->executing)
4530     return NULL;
4531   return tp;
4532 }
4533 
4534 void
4535 bpstat_do_actions (void)
4536 {
4537   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4538   thread_info *tp;
4539 
4540   /* Do any commands attached to breakpoint we are stopped at.  */
4541   while ((tp = get_bpstat_thread ()) != NULL)
4542     {
4543       /* Since in sync mode, bpstat_do_actions may resume the
4544 	 inferior, and only return when it is stopped at the next
4545 	 breakpoint, we keep doing breakpoint actions until it returns
4546 	 false to indicate the inferior was not resumed.  */
4547       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4548 	break;
4549     }
4550 
4551   cleanup_if_error.release ();
4552 }
4553 
4554 /* Print out the (old or new) value associated with a watchpoint.  */
4555 
4556 static void
4557 watchpoint_value_print (struct value *val, struct ui_file *stream)
4558 {
4559   if (val == NULL)
4560     fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4561   else
4562     {
4563       struct value_print_options opts;
4564       get_user_print_options (&opts);
4565       value_print (val, stream, &opts);
4566     }
4567 }
4568 
4569 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4570    debugging multiple threads.  */
4571 
4572 void
4573 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4574 {
4575   if (uiout->is_mi_like_p ())
4576     return;
4577 
4578   uiout->text ("\n");
4579 
4580   if (show_thread_that_caused_stop ())
4581     {
4582       const char *name;
4583       struct thread_info *thr = inferior_thread ();
4584 
4585       uiout->text ("Thread ");
4586       uiout->field_string ("thread-id", print_thread_id (thr));
4587 
4588       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4589       if (name != NULL)
4590 	{
4591 	  uiout->text (" \"");
4592 	  uiout->field_string ("name", name);
4593 	  uiout->text ("\"");
4594 	}
4595 
4596       uiout->text (" hit ");
4597     }
4598 }
4599 
4600 /* Generic routine for printing messages indicating why we
4601    stopped.  The behavior of this function depends on the value
4602    'print_it' in the bpstat structure.  Under some circumstances we
4603    may decide not to print anything here and delegate the task to
4604    normal_stop().  */
4605 
4606 static enum print_stop_action
4607 print_bp_stop_message (bpstat bs)
4608 {
4609   switch (bs->print_it)
4610     {
4611     case print_it_noop:
4612       /* Nothing should be printed for this bpstat entry.  */
4613       return PRINT_UNKNOWN;
4614       break;
4615 
4616     case print_it_done:
4617       /* We still want to print the frame, but we already printed the
4618 	 relevant messages.  */
4619       return PRINT_SRC_AND_LOC;
4620       break;
4621 
4622     case print_it_normal:
4623       {
4624 	struct breakpoint *b = bs->breakpoint_at;
4625 
4626 	/* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4627 	   which has since been deleted.  */
4628 	if (b == NULL)
4629 	  return PRINT_UNKNOWN;
4630 
4631 	/* Normal case.  Call the breakpoint's print_it method.  */
4632 	return b->ops->print_it (bs);
4633       }
4634       break;
4635 
4636     default:
4637       internal_error (__FILE__, __LINE__,
4638 		      _("print_bp_stop_message: unrecognized enum value"));
4639       break;
4640     }
4641 }
4642 
4643 /* A helper function that prints a shared library stopped event.  */
4644 
4645 static void
4646 print_solib_event (int is_catchpoint)
4647 {
4648   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4649   bool any_added = !current_program_space->added_solibs.empty ();
4650 
4651   if (!is_catchpoint)
4652     {
4653       if (any_added || any_deleted)
4654 	current_uiout->text (_("Stopped due to shared library event:\n"));
4655       else
4656 	current_uiout->text (_("Stopped due to shared library event (no "
4657 			       "libraries added or removed)\n"));
4658     }
4659 
4660   if (current_uiout->is_mi_like_p ())
4661     current_uiout->field_string ("reason",
4662 				 async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4663 
4664   if (any_deleted)
4665     {
4666       current_uiout->text (_("  Inferior unloaded "));
4667       ui_out_emit_list list_emitter (current_uiout, "removed");
4668       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4669 	{
4670 	  const std::string &name = current_program_space->deleted_solibs[ix];
4671 
4672 	  if (ix > 0)
4673 	    current_uiout->text ("    ");
4674 	  current_uiout->field_string ("library", name);
4675 	  current_uiout->text ("\n");
4676 	}
4677     }
4678 
4679   if (any_added)
4680     {
4681       current_uiout->text (_("  Inferior loaded "));
4682       ui_out_emit_list list_emitter (current_uiout, "added");
4683       bool first = true;
4684       for (so_list *iter : current_program_space->added_solibs)
4685 	{
4686 	  if (!first)
4687 	    current_uiout->text ("    ");
4688 	  first = false;
4689 	  current_uiout->field_string ("library", iter->so_name);
4690 	  current_uiout->text ("\n");
4691 	}
4692     }
4693 }
4694 
4695 /* Print a message indicating what happened.  This is called from
4696    normal_stop().  The input to this routine is the head of the bpstat
4697    list - a list of the eventpoints that caused this stop.  KIND is
4698    the target_waitkind for the stopping event.  This
4699    routine calls the generic print routine for printing a message
4700    about reasons for stopping.  This will print (for example) the
4701    "Breakpoint n," part of the output.  The return value of this
4702    routine is one of:
4703 
4704    PRINT_UNKNOWN: Means we printed nothing.
4705    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4706    code to print the location.  An example is
4707    "Breakpoint 1, " which should be followed by
4708    the location.
4709    PRINT_SRC_ONLY: Means we printed something, but there is no need
4710    to also print the location part of the message.
4711    An example is the catch/throw messages, which
4712    don't require a location appended to the end.
4713    PRINT_NOTHING: We have done some printing and we don't need any
4714    further info to be printed.  */
4715 
4716 enum print_stop_action
4717 bpstat_print (bpstat bs, int kind)
4718 {
4719   enum print_stop_action val;
4720 
4721   /* Maybe another breakpoint in the chain caused us to stop.
4722      (Currently all watchpoints go on the bpstat whether hit or not.
4723      That probably could (should) be changed, provided care is taken
4724      with respect to bpstat_explains_signal).  */
4725   for (; bs; bs = bs->next)
4726     {
4727       val = print_bp_stop_message (bs);
4728       if (val == PRINT_SRC_ONLY
4729 	  || val == PRINT_SRC_AND_LOC
4730 	  || val == PRINT_NOTHING)
4731 	return val;
4732     }
4733 
4734   /* If we had hit a shared library event breakpoint,
4735      print_bp_stop_message would print out this message.  If we hit an
4736      OS-level shared library event, do the same thing.  */
4737   if (kind == TARGET_WAITKIND_LOADED)
4738     {
4739       print_solib_event (0);
4740       return PRINT_NOTHING;
4741     }
4742 
4743   /* We reached the end of the chain, or we got a null BS to start
4744      with and nothing was printed.  */
4745   return PRINT_UNKNOWN;
4746 }
4747 
4748 /* Evaluate the boolean expression EXP and return the result.  */
4749 
4750 static bool
4751 breakpoint_cond_eval (expression *exp)
4752 {
4753   struct value *mark = value_mark ();
4754   bool res = value_true (evaluate_expression (exp));
4755 
4756   value_free_to_mark (mark);
4757   return res;
4758 }
4759 
4760 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4761 
4762 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4763   : next (NULL),
4764     bp_location_at (bp_location_ref_ptr::new_reference (bl)),
4765     breakpoint_at (bl->owner),
4766     commands (NULL),
4767     print (0),
4768     stop (0),
4769     print_it (print_it_normal)
4770 {
4771   **bs_link_pointer = this;
4772   *bs_link_pointer = &next;
4773 }
4774 
4775 bpstats::bpstats ()
4776   : next (NULL),
4777     breakpoint_at (NULL),
4778     commands (NULL),
4779     print (0),
4780     stop (0),
4781     print_it (print_it_normal)
4782 {
4783 }
4784 
4785 /* The target has stopped with waitstatus WS.  Check if any hardware
4786    watchpoints have triggered, according to the target.  */
4787 
4788 int
4789 watchpoints_triggered (struct target_waitstatus *ws)
4790 {
4791   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4792   CORE_ADDR addr;
4793 
4794   if (!stopped_by_watchpoint)
4795     {
4796       /* We were not stopped by a watchpoint.  Mark all watchpoints
4797 	 as not triggered.  */
4798       for (breakpoint *b : all_breakpoints ())
4799 	if (is_hardware_watchpoint (b))
4800 	  {
4801 	    struct watchpoint *w = (struct watchpoint *) b;
4802 
4803 	    w->watchpoint_triggered = watch_triggered_no;
4804 	  }
4805 
4806       return 0;
4807     }
4808 
4809   if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
4810     {
4811       /* We were stopped by a watchpoint, but we don't know where.
4812 	 Mark all watchpoints as unknown.  */
4813       for (breakpoint *b : all_breakpoints ())
4814 	if (is_hardware_watchpoint (b))
4815 	  {
4816 	    struct watchpoint *w = (struct watchpoint *) b;
4817 
4818 	    w->watchpoint_triggered = watch_triggered_unknown;
4819 	  }
4820 
4821       return 1;
4822     }
4823 
4824   /* The target could report the data address.  Mark watchpoints
4825      affected by this data address as triggered, and all others as not
4826      triggered.  */
4827 
4828   for (breakpoint *b : all_breakpoints ())
4829     if (is_hardware_watchpoint (b))
4830       {
4831 	struct watchpoint *w = (struct watchpoint *) b;
4832 
4833 	w->watchpoint_triggered = watch_triggered_no;
4834 	for (bp_location *loc : b->locations ())
4835 	  {
4836 	    if (is_masked_watchpoint (b))
4837 	      {
4838 		CORE_ADDR newaddr = addr & w->hw_wp_mask;
4839 		CORE_ADDR start = loc->address & w->hw_wp_mask;
4840 
4841 		if (newaddr == start)
4842 		  {
4843 		    w->watchpoint_triggered = watch_triggered_yes;
4844 		    break;
4845 		  }
4846 	      }
4847 	    /* Exact match not required.  Within range is sufficient.  */
4848 	    else if (target_watchpoint_addr_within_range
4849 		       (current_inferior ()->top_target (), addr, loc->address,
4850 			loc->length))
4851 	      {
4852 		w->watchpoint_triggered = watch_triggered_yes;
4853 		break;
4854 	      }
4855 	  }
4856       }
4857 
4858   return 1;
4859 }
4860 
4861 /* Possible return values for watchpoint_check.  */
4862 enum wp_check_result
4863   {
4864     /* The watchpoint has been deleted.  */
4865     WP_DELETED = 1,
4866 
4867     /* The value has changed.  */
4868     WP_VALUE_CHANGED = 2,
4869 
4870     /* The value has not changed.  */
4871     WP_VALUE_NOT_CHANGED = 3,
4872 
4873     /* Ignore this watchpoint, no matter if the value changed or not.  */
4874     WP_IGNORE = 4,
4875   };
4876 
4877 #define BP_TEMPFLAG 1
4878 #define BP_HARDWAREFLAG 2
4879 
4880 /* Evaluate watchpoint condition expression and check if its value
4881    changed.  */
4882 
4883 static wp_check_result
4884 watchpoint_check (bpstat bs)
4885 {
4886   struct watchpoint *b;
4887   struct frame_info *fr;
4888   int within_current_scope;
4889 
4890   /* BS is built from an existing struct breakpoint.  */
4891   gdb_assert (bs->breakpoint_at != NULL);
4892   b = (struct watchpoint *) bs->breakpoint_at;
4893 
4894   /* If this is a local watchpoint, we only want to check if the
4895      watchpoint frame is in scope if the current thread is the thread
4896      that was used to create the watchpoint.  */
4897   if (!watchpoint_in_thread_scope (b))
4898     return WP_IGNORE;
4899 
4900   if (b->exp_valid_block == NULL)
4901     within_current_scope = 1;
4902   else
4903     {
4904       struct frame_info *frame = get_current_frame ();
4905       struct gdbarch *frame_arch = get_frame_arch (frame);
4906       CORE_ADDR frame_pc = get_frame_pc (frame);
4907 
4908       /* stack_frame_destroyed_p() returns a non-zero value if we're
4909 	 still in the function but the stack frame has already been
4910 	 invalidated.  Since we can't rely on the values of local
4911 	 variables after the stack has been destroyed, we are treating
4912 	 the watchpoint in that state as `not changed' without further
4913 	 checking.  Don't mark watchpoints as changed if the current
4914 	 frame is in an epilogue - even if they are in some other
4915 	 frame, our view of the stack is likely to be wrong and
4916 	 frame_find_by_id could error out.  */
4917       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4918 	return WP_IGNORE;
4919 
4920       fr = frame_find_by_id (b->watchpoint_frame);
4921       within_current_scope = (fr != NULL);
4922 
4923       /* If we've gotten confused in the unwinder, we might have
4924 	 returned a frame that can't describe this variable.  */
4925       if (within_current_scope)
4926 	{
4927 	  struct symbol *function;
4928 
4929 	  function = get_frame_function (fr);
4930 	  if (function == NULL
4931 	      || !contained_in (b->exp_valid_block,
4932 				SYMBOL_BLOCK_VALUE (function)))
4933 	    within_current_scope = 0;
4934 	}
4935 
4936       if (within_current_scope)
4937 	/* If we end up stopping, the current frame will get selected
4938 	   in normal_stop.  So this call to select_frame won't affect
4939 	   the user.  */
4940 	select_frame (fr);
4941     }
4942 
4943   if (within_current_scope)
4944     {
4945       /* We use value_{,free_to_}mark because it could be a *long*
4946 	 time before we return to the command level and call
4947 	 free_all_values.  We can't call free_all_values because we
4948 	 might be in the middle of evaluating a function call.  */
4949 
4950       struct value *mark;
4951       struct value *new_val;
4952 
4953       if (is_masked_watchpoint (b))
4954 	/* Since we don't know the exact trigger address (from
4955 	   stopped_data_address), just tell the user we've triggered
4956 	   a mask watchpoint.  */
4957 	return WP_VALUE_CHANGED;
4958 
4959       mark = value_mark ();
4960       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
4961 			  NULL, NULL, false);
4962 
4963       if (b->val_bitsize != 0)
4964 	new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4965 
4966       /* We use value_equal_contents instead of value_equal because
4967 	 the latter coerces an array to a pointer, thus comparing just
4968 	 the address of the array instead of its contents.  This is
4969 	 not what we want.  */
4970       if ((b->val != NULL) != (new_val != NULL)
4971 	  || (b->val != NULL && !value_equal_contents (b->val.get (),
4972 						       new_val)))
4973 	{
4974 	  bs->old_val = b->val;
4975 	  b->val = release_value (new_val);
4976 	  b->val_valid = true;
4977 	  if (new_val != NULL)
4978 	    value_free_to_mark (mark);
4979 	  return WP_VALUE_CHANGED;
4980 	}
4981       else
4982 	{
4983 	  /* Nothing changed.  */
4984 	  value_free_to_mark (mark);
4985 	  return WP_VALUE_NOT_CHANGED;
4986 	}
4987     }
4988   else
4989     {
4990       /* This seems like the only logical thing to do because
4991 	 if we temporarily ignored the watchpoint, then when
4992 	 we reenter the block in which it is valid it contains
4993 	 garbage (in the case of a function, it may have two
4994 	 garbage values, one before and one after the prologue).
4995 	 So we can't even detect the first assignment to it and
4996 	 watch after that (since the garbage may or may not equal
4997 	 the first value assigned).  */
4998       /* We print all the stop information in
4999 	 breakpoint_ops->print_it, but in this case, by the time we
5000 	 call breakpoint_ops->print_it this bp will be deleted
5001 	 already.  So we have no choice but print the information
5002 	 here.  */
5003 
5004       SWITCH_THRU_ALL_UIS ()
5005 	{
5006 	  struct ui_out *uiout = current_uiout;
5007 
5008 	  if (uiout->is_mi_like_p ())
5009 	    uiout->field_string
5010 	      ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5011 	  uiout->message ("\nWatchpoint %pF deleted because the program has "
5012 			  "left the block in\n"
5013 			  "which its expression is valid.\n",
5014 			  signed_field ("wpnum", b->number));
5015 	}
5016 
5017       /* Make sure the watchpoint's commands aren't executed.  */
5018       b->commands = NULL;
5019       watchpoint_del_at_next_stop (b);
5020 
5021       return WP_DELETED;
5022     }
5023 }
5024 
5025 /* Return true if it looks like target has stopped due to hitting
5026    breakpoint location BL.  This function does not check if we should
5027    stop, only if BL explains the stop.  */
5028 
5029 static int
5030 bpstat_check_location (const struct bp_location *bl,
5031 		       const address_space *aspace, CORE_ADDR bp_addr,
5032 		       const struct target_waitstatus *ws)
5033 {
5034   struct breakpoint *b = bl->owner;
5035 
5036   /* BL is from an existing breakpoint.  */
5037   gdb_assert (b != NULL);
5038 
5039   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5040 }
5041 
5042 /* Determine if the watched values have actually changed, and we
5043    should stop.  If not, set BS->stop to 0.  */
5044 
5045 static void
5046 bpstat_check_watchpoint (bpstat bs)
5047 {
5048   const struct bp_location *bl;
5049   struct watchpoint *b;
5050 
5051   /* BS is built for existing struct breakpoint.  */
5052   bl = bs->bp_location_at.get ();
5053   gdb_assert (bl != NULL);
5054   b = (struct watchpoint *) bs->breakpoint_at;
5055   gdb_assert (b != NULL);
5056 
5057     {
5058       int must_check_value = 0;
5059 
5060       if (b->type == bp_watchpoint)
5061 	/* For a software watchpoint, we must always check the
5062 	   watched value.  */
5063 	must_check_value = 1;
5064       else if (b->watchpoint_triggered == watch_triggered_yes)
5065 	/* We have a hardware watchpoint (read, write, or access)
5066 	   and the target earlier reported an address watched by
5067 	   this watchpoint.  */
5068 	must_check_value = 1;
5069       else if (b->watchpoint_triggered == watch_triggered_unknown
5070 	       && b->type == bp_hardware_watchpoint)
5071 	/* We were stopped by a hardware watchpoint, but the target could
5072 	   not report the data address.  We must check the watchpoint's
5073 	   value.  Access and read watchpoints are out of luck; without
5074 	   a data address, we can't figure it out.  */
5075 	must_check_value = 1;
5076 
5077       if (must_check_value)
5078 	{
5079 	  wp_check_result e;
5080 
5081 	  try
5082 	    {
5083 	      e = watchpoint_check (bs);
5084 	    }
5085 	  catch (const gdb_exception &ex)
5086 	    {
5087 	      exception_fprintf (gdb_stderr, ex,
5088 				 "Error evaluating expression "
5089 				 "for watchpoint %d\n",
5090 				 b->number);
5091 
5092 	      SWITCH_THRU_ALL_UIS ()
5093 		{
5094 		  printf_filtered (_("Watchpoint %d deleted.\n"),
5095 				   b->number);
5096 		}
5097 	      watchpoint_del_at_next_stop (b);
5098 	      e = WP_DELETED;
5099 	    }
5100 
5101 	  switch (e)
5102 	    {
5103 	    case WP_DELETED:
5104 	      /* We've already printed what needs to be printed.  */
5105 	      bs->print_it = print_it_done;
5106 	      /* Stop.  */
5107 	      break;
5108 	    case WP_IGNORE:
5109 	      bs->print_it = print_it_noop;
5110 	      bs->stop = 0;
5111 	      break;
5112 	    case WP_VALUE_CHANGED:
5113 	      if (b->type == bp_read_watchpoint)
5114 		{
5115 		  /* There are two cases to consider here:
5116 
5117 		     1. We're watching the triggered memory for reads.
5118 		     In that case, trust the target, and always report
5119 		     the watchpoint hit to the user.  Even though
5120 		     reads don't cause value changes, the value may
5121 		     have changed since the last time it was read, and
5122 		     since we're not trapping writes, we will not see
5123 		     those, and as such we should ignore our notion of
5124 		     old value.
5125 
5126 		     2. We're watching the triggered memory for both
5127 		     reads and writes.  There are two ways this may
5128 		     happen:
5129 
5130 		     2.1. This is a target that can't break on data
5131 		     reads only, but can break on accesses (reads or
5132 		     writes), such as e.g., x86.  We detect this case
5133 		     at the time we try to insert read watchpoints.
5134 
5135 		     2.2. Otherwise, the target supports read
5136 		     watchpoints, but, the user set an access or write
5137 		     watchpoint watching the same memory as this read
5138 		     watchpoint.
5139 
5140 		     If we're watching memory writes as well as reads,
5141 		     ignore watchpoint hits when we find that the
5142 		     value hasn't changed, as reads don't cause
5143 		     changes.  This still gives false positives when
5144 		     the program writes the same value to memory as
5145 		     what there was already in memory (we will confuse
5146 		     it for a read), but it's much better than
5147 		     nothing.  */
5148 
5149 		  int other_write_watchpoint = 0;
5150 
5151 		  if (bl->watchpoint_type == hw_read)
5152 		    {
5153 		      for (breakpoint *other_b : all_breakpoints ())
5154 			if (other_b->type == bp_hardware_watchpoint
5155 			    || other_b->type == bp_access_watchpoint)
5156 			  {
5157 			    struct watchpoint *other_w =
5158 			      (struct watchpoint *) other_b;
5159 
5160 			    if (other_w->watchpoint_triggered
5161 				== watch_triggered_yes)
5162 			      {
5163 				other_write_watchpoint = 1;
5164 				break;
5165 			      }
5166 			  }
5167 		    }
5168 
5169 		  if (other_write_watchpoint
5170 		      || bl->watchpoint_type == hw_access)
5171 		    {
5172 		      /* We're watching the same memory for writes,
5173 			 and the value changed since the last time we
5174 			 updated it, so this trap must be for a write.
5175 			 Ignore it.  */
5176 		      bs->print_it = print_it_noop;
5177 		      bs->stop = 0;
5178 		    }
5179 		}
5180 	      break;
5181 	    case WP_VALUE_NOT_CHANGED:
5182 	      if (b->type == bp_hardware_watchpoint
5183 		  || b->type == bp_watchpoint)
5184 		{
5185 		  /* Don't stop: write watchpoints shouldn't fire if
5186 		     the value hasn't changed.  */
5187 		  bs->print_it = print_it_noop;
5188 		  bs->stop = 0;
5189 		}
5190 	      /* Stop.  */
5191 	      break;
5192 	    default:
5193 	      /* Can't happen.  */
5194 	      break;
5195 	    }
5196 	}
5197       else	/* must_check_value == 0 */
5198 	{
5199 	  /* This is a case where some watchpoint(s) triggered, but
5200 	     not at the address of this watchpoint, or else no
5201 	     watchpoint triggered after all.  So don't print
5202 	     anything for this watchpoint.  */
5203 	  bs->print_it = print_it_noop;
5204 	  bs->stop = 0;
5205 	}
5206     }
5207 }
5208 
5209 /* For breakpoints that are currently marked as telling gdb to stop,
5210    check conditions (condition proper, frame, thread and ignore count)
5211    of breakpoint referred to by BS.  If we should not stop for this
5212    breakpoint, set BS->stop to 0.  */
5213 
5214 static void
5215 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5216 {
5217   const struct bp_location *bl;
5218   struct breakpoint *b;
5219   /* Assume stop.  */
5220   bool condition_result = true;
5221   struct expression *cond;
5222 
5223   gdb_assert (bs->stop);
5224 
5225   /* BS is built for existing struct breakpoint.  */
5226   bl = bs->bp_location_at.get ();
5227   gdb_assert (bl != NULL);
5228   b = bs->breakpoint_at;
5229   gdb_assert (b != NULL);
5230 
5231   /* Even if the target evaluated the condition on its end and notified GDB, we
5232      need to do so again since GDB does not know if we stopped due to a
5233      breakpoint or a single step breakpoint.  */
5234 
5235   if (frame_id_p (b->frame_id)
5236       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5237     {
5238       bs->stop = 0;
5239       return;
5240     }
5241 
5242   /* If this is a thread/task-specific breakpoint, don't waste cpu
5243      evaluating the condition if this isn't the specified
5244      thread/task.  */
5245   if ((b->thread != -1 && b->thread != thread->global_num)
5246       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5247     {
5248       bs->stop = 0;
5249       return;
5250     }
5251 
5252   /* Evaluate extension language breakpoints that have a "stop" method
5253      implemented.  */
5254   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5255 
5256   if (is_watchpoint (b))
5257     {
5258       struct watchpoint *w = (struct watchpoint *) b;
5259 
5260       cond = w->cond_exp.get ();
5261     }
5262   else
5263     cond = bl->cond.get ();
5264 
5265   if (cond && b->disposition != disp_del_at_next_stop)
5266     {
5267       int within_current_scope = 1;
5268       struct watchpoint * w;
5269 
5270       /* We use value_mark and value_free_to_mark because it could
5271 	 be a long time before we return to the command level and
5272 	 call free_all_values.  We can't call free_all_values
5273 	 because we might be in the middle of evaluating a
5274 	 function call.  */
5275       struct value *mark = value_mark ();
5276 
5277       if (is_watchpoint (b))
5278 	w = (struct watchpoint *) b;
5279       else
5280 	w = NULL;
5281 
5282       /* Need to select the frame, with all that implies so that
5283 	 the conditions will have the right context.  Because we
5284 	 use the frame, we will not see an inlined function's
5285 	 variables when we arrive at a breakpoint at the start
5286 	 of the inlined function; the current frame will be the
5287 	 call site.  */
5288       if (w == NULL || w->cond_exp_valid_block == NULL)
5289 	select_frame (get_current_frame ());
5290       else
5291 	{
5292 	  struct frame_info *frame;
5293 
5294 	  /* For local watchpoint expressions, which particular
5295 	     instance of a local is being watched matters, so we
5296 	     keep track of the frame to evaluate the expression
5297 	     in.  To evaluate the condition however, it doesn't
5298 	     really matter which instantiation of the function
5299 	     where the condition makes sense triggers the
5300 	     watchpoint.  This allows an expression like "watch
5301 	     global if q > 10" set in `func', catch writes to
5302 	     global on all threads that call `func', or catch
5303 	     writes on all recursive calls of `func' by a single
5304 	     thread.  We simply always evaluate the condition in
5305 	     the innermost frame that's executing where it makes
5306 	     sense to evaluate the condition.  It seems
5307 	     intuitive.  */
5308 	  frame = block_innermost_frame (w->cond_exp_valid_block);
5309 	  if (frame != NULL)
5310 	    select_frame (frame);
5311 	  else
5312 	    within_current_scope = 0;
5313 	}
5314       if (within_current_scope)
5315 	{
5316 	  try
5317 	    {
5318 	      condition_result = breakpoint_cond_eval (cond);
5319 	    }
5320 	  catch (const gdb_exception &ex)
5321 	    {
5322 	      exception_fprintf (gdb_stderr, ex,
5323 				 "Error in testing breakpoint condition:\n");
5324 	    }
5325 	}
5326       else
5327 	{
5328 	  warning (_("Watchpoint condition cannot be tested "
5329 		     "in the current scope"));
5330 	  /* If we failed to set the right context for this
5331 	     watchpoint, unconditionally report it.  */
5332 	}
5333       /* FIXME-someday, should give breakpoint #.  */
5334       value_free_to_mark (mark);
5335     }
5336 
5337   if (cond && !condition_result)
5338     {
5339       bs->stop = 0;
5340     }
5341   else if (b->ignore_count > 0)
5342     {
5343       b->ignore_count--;
5344       bs->stop = 0;
5345       /* Increase the hit count even though we don't stop.  */
5346       ++(b->hit_count);
5347       gdb::observers::breakpoint_modified.notify (b);
5348     }
5349 }
5350 
5351 /* Returns true if we need to track moribund locations of LOC's type
5352    on the current target.  */
5353 
5354 static int
5355 need_moribund_for_location_type (struct bp_location *loc)
5356 {
5357   return ((loc->loc_type == bp_loc_software_breakpoint
5358 	   && !target_supports_stopped_by_sw_breakpoint ())
5359 	  || (loc->loc_type == bp_loc_hardware_breakpoint
5360 	      && !target_supports_stopped_by_hw_breakpoint ()));
5361 }
5362 
5363 /* See breakpoint.h.  */
5364 
5365 bpstat
5366 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5367 		    const struct target_waitstatus *ws)
5368 {
5369   bpstat bs_head = NULL, *bs_link = &bs_head;
5370 
5371   for (breakpoint *b : all_breakpoints ())
5372     {
5373       if (!breakpoint_enabled (b))
5374 	continue;
5375 
5376       for (bp_location *bl : b->locations ())
5377 	{
5378 	  /* For hardware watchpoints, we look only at the first
5379 	     location.  The watchpoint_check function will work on the
5380 	     entire expression, not the individual locations.  For
5381 	     read watchpoints, the watchpoints_triggered function has
5382 	     checked all locations already.  */
5383 	  if (b->type == bp_hardware_watchpoint && bl != b->loc)
5384 	    break;
5385 
5386 	  if (!bl->enabled || bl->disabled_by_cond || bl->shlib_disabled)
5387 	    continue;
5388 
5389 	  if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5390 	    continue;
5391 
5392 	  /* Come here if it's a watchpoint, or if the break address
5393 	     matches.  */
5394 
5395 	  bpstat bs = new bpstats (bl, &bs_link);	/* Alloc a bpstat to
5396 							   explain stop.  */
5397 
5398 	  /* Assume we stop.  Should we find a watchpoint that is not
5399 	     actually triggered, or if the condition of the breakpoint
5400 	     evaluates as false, we'll reset 'stop' to 0.  */
5401 	  bs->stop = 1;
5402 	  bs->print = 1;
5403 
5404 	  /* If this is a scope breakpoint, mark the associated
5405 	     watchpoint as triggered so that we will handle the
5406 	     out-of-scope event.  We'll get to the watchpoint next
5407 	     iteration.  */
5408 	  if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5409 	    {
5410 	      struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5411 
5412 	      w->watchpoint_triggered = watch_triggered_yes;
5413 	    }
5414 	}
5415     }
5416 
5417   /* Check if a moribund breakpoint explains the stop.  */
5418   if (!target_supports_stopped_by_sw_breakpoint ()
5419       || !target_supports_stopped_by_hw_breakpoint ())
5420     {
5421       for (bp_location *loc : moribund_locations)
5422 	{
5423 	  if (breakpoint_location_address_match (loc, aspace, bp_addr)
5424 	      && need_moribund_for_location_type (loc))
5425 	    {
5426 	      bpstat bs = new bpstats (loc, &bs_link);
5427 	      /* For hits of moribund locations, we should just proceed.  */
5428 	      bs->stop = 0;
5429 	      bs->print = 0;
5430 	      bs->print_it = print_it_noop;
5431 	    }
5432 	}
5433     }
5434 
5435   return bs_head;
5436 }
5437 
5438 /* See breakpoint.h.  */
5439 
5440 bpstat
5441 bpstat_stop_status (const address_space *aspace,
5442 		    CORE_ADDR bp_addr, thread_info *thread,
5443 		    const struct target_waitstatus *ws,
5444 		    bpstat stop_chain)
5445 {
5446   struct breakpoint *b = NULL;
5447   /* First item of allocated bpstat's.  */
5448   bpstat bs_head = stop_chain;
5449   bpstat bs;
5450   int need_remove_insert;
5451   int removed_any;
5452 
5453   /* First, build the bpstat chain with locations that explain a
5454      target stop, while being careful to not set the target running,
5455      as that may invalidate locations (in particular watchpoint
5456      locations are recreated).  Resuming will happen here with
5457      breakpoint conditions or watchpoint expressions that include
5458      inferior function calls.  */
5459   if (bs_head == NULL)
5460     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5461 
5462   /* A bit of special processing for shlib breakpoints.  We need to
5463      process solib loading here, so that the lists of loaded and
5464      unloaded libraries are correct before we handle "catch load" and
5465      "catch unload".  */
5466   for (bs = bs_head; bs != NULL; bs = bs->next)
5467     {
5468       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5469 	{
5470 	  handle_solib_event ();
5471 	  break;
5472 	}
5473     }
5474 
5475   /* Now go through the locations that caused the target to stop, and
5476      check whether we're interested in reporting this stop to higher
5477      layers, or whether we should resume the target transparently.  */
5478 
5479   removed_any = 0;
5480 
5481   for (bs = bs_head; bs != NULL; bs = bs->next)
5482     {
5483       if (!bs->stop)
5484 	continue;
5485 
5486       b = bs->breakpoint_at;
5487       b->ops->check_status (bs);
5488       if (bs->stop)
5489 	{
5490 	  bpstat_check_breakpoint_conditions (bs, thread);
5491 
5492 	  if (bs->stop)
5493 	    {
5494 	      ++(b->hit_count);
5495 	      gdb::observers::breakpoint_modified.notify (b);
5496 
5497 	      /* We will stop here.  */
5498 	      if (b->disposition == disp_disable)
5499 		{
5500 		  --(b->enable_count);
5501 		  if (b->enable_count <= 0)
5502 		    b->enable_state = bp_disabled;
5503 		  removed_any = 1;
5504 		}
5505 	      if (b->silent)
5506 		bs->print = 0;
5507 	      bs->commands = b->commands;
5508 	      if (command_line_is_silent (bs->commands
5509 					  ? bs->commands.get () : NULL))
5510 		bs->print = 0;
5511 
5512 	      b->ops->after_condition_true (bs);
5513 	    }
5514 
5515 	}
5516 
5517       /* Print nothing for this entry if we don't stop or don't
5518 	 print.  */
5519       if (!bs->stop || !bs->print)
5520 	bs->print_it = print_it_noop;
5521     }
5522 
5523   /* If we aren't stopping, the value of some hardware watchpoint may
5524      not have changed, but the intermediate memory locations we are
5525      watching may have.  Don't bother if we're stopping; this will get
5526      done later.  */
5527   need_remove_insert = 0;
5528   if (! bpstat_causes_stop (bs_head))
5529     for (bs = bs_head; bs != NULL; bs = bs->next)
5530       if (!bs->stop
5531 	  && bs->breakpoint_at
5532 	  && is_hardware_watchpoint (bs->breakpoint_at))
5533 	{
5534 	  struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5535 
5536 	  update_watchpoint (w, 0 /* don't reparse.  */);
5537 	  need_remove_insert = 1;
5538 	}
5539 
5540   if (need_remove_insert)
5541     update_global_location_list (UGLL_MAY_INSERT);
5542   else if (removed_any)
5543     update_global_location_list (UGLL_DONT_INSERT);
5544 
5545   return bs_head;
5546 }
5547 
5548 static void
5549 handle_jit_event (CORE_ADDR address)
5550 {
5551   struct gdbarch *gdbarch;
5552 
5553   infrun_debug_printf ("handling bp_jit_event");
5554 
5555   /* Switch terminal for any messages produced by
5556      breakpoint_re_set.  */
5557   target_terminal::ours_for_output ();
5558 
5559   gdbarch = get_frame_arch (get_current_frame ());
5560   /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5561      thus it is expected that its objectfile can be found through
5562      minimal symbol lookup.  If it doesn't work (and assert fails), it
5563      most likely means that `jit_breakpoint_re_set` was changes and this
5564      function needs to be updated too.  */
5565   bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5566   gdb_assert (jit_bp_sym.objfile != nullptr);
5567   jit_event_handler (gdbarch, jit_bp_sym.objfile);
5568 
5569   target_terminal::inferior ();
5570 }
5571 
5572 /* Prepare WHAT final decision for infrun.  */
5573 
5574 /* Decide what infrun needs to do with this bpstat.  */
5575 
5576 struct bpstat_what
5577 bpstat_what (bpstat bs_head)
5578 {
5579   struct bpstat_what retval;
5580   bpstat bs;
5581 
5582   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5583   retval.call_dummy = STOP_NONE;
5584   retval.is_longjmp = false;
5585 
5586   for (bs = bs_head; bs != NULL; bs = bs->next)
5587     {
5588       /* Extract this BS's action.  After processing each BS, we check
5589 	 if its action overrides all we've seem so far.  */
5590       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5591       enum bptype bptype;
5592 
5593       if (bs->breakpoint_at == NULL)
5594 	{
5595 	  /* I suspect this can happen if it was a momentary
5596 	     breakpoint which has since been deleted.  */
5597 	  bptype = bp_none;
5598 	}
5599       else
5600 	bptype = bs->breakpoint_at->type;
5601 
5602       switch (bptype)
5603 	{
5604 	case bp_none:
5605 	  break;
5606 	case bp_breakpoint:
5607 	case bp_hardware_breakpoint:
5608 	case bp_single_step:
5609 	case bp_until:
5610 	case bp_finish:
5611 	case bp_shlib_event:
5612 	  if (bs->stop)
5613 	    {
5614 	      if (bs->print)
5615 		this_action = BPSTAT_WHAT_STOP_NOISY;
5616 	      else
5617 		this_action = BPSTAT_WHAT_STOP_SILENT;
5618 	    }
5619 	  else
5620 	    this_action = BPSTAT_WHAT_SINGLE;
5621 	  break;
5622 	case bp_watchpoint:
5623 	case bp_hardware_watchpoint:
5624 	case bp_read_watchpoint:
5625 	case bp_access_watchpoint:
5626 	  if (bs->stop)
5627 	    {
5628 	      if (bs->print)
5629 		this_action = BPSTAT_WHAT_STOP_NOISY;
5630 	      else
5631 		this_action = BPSTAT_WHAT_STOP_SILENT;
5632 	    }
5633 	  else
5634 	    {
5635 	      /* There was a watchpoint, but we're not stopping.
5636 		 This requires no further action.  */
5637 	    }
5638 	  break;
5639 	case bp_longjmp:
5640 	case bp_longjmp_call_dummy:
5641 	case bp_exception:
5642 	  if (bs->stop)
5643 	    {
5644 	      this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5645 	      retval.is_longjmp = bptype != bp_exception;
5646 	    }
5647 	  else
5648 	    this_action = BPSTAT_WHAT_SINGLE;
5649 	  break;
5650 	case bp_longjmp_resume:
5651 	case bp_exception_resume:
5652 	  if (bs->stop)
5653 	    {
5654 	      this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5655 	      retval.is_longjmp = bptype == bp_longjmp_resume;
5656 	    }
5657 	  else
5658 	    this_action = BPSTAT_WHAT_SINGLE;
5659 	  break;
5660 	case bp_step_resume:
5661 	  if (bs->stop)
5662 	    this_action = BPSTAT_WHAT_STEP_RESUME;
5663 	  else
5664 	    {
5665 	      /* It is for the wrong frame.  */
5666 	      this_action = BPSTAT_WHAT_SINGLE;
5667 	    }
5668 	  break;
5669 	case bp_hp_step_resume:
5670 	  if (bs->stop)
5671 	    this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5672 	  else
5673 	    {
5674 	      /* It is for the wrong frame.  */
5675 	      this_action = BPSTAT_WHAT_SINGLE;
5676 	    }
5677 	  break;
5678 	case bp_watchpoint_scope:
5679 	case bp_thread_event:
5680 	case bp_overlay_event:
5681 	case bp_longjmp_master:
5682 	case bp_std_terminate_master:
5683 	case bp_exception_master:
5684 	  this_action = BPSTAT_WHAT_SINGLE;
5685 	  break;
5686 	case bp_catchpoint:
5687 	  if (bs->stop)
5688 	    {
5689 	      if (bs->print)
5690 		this_action = BPSTAT_WHAT_STOP_NOISY;
5691 	      else
5692 		this_action = BPSTAT_WHAT_STOP_SILENT;
5693 	    }
5694 	  else
5695 	    {
5696 	      /* Some catchpoints are implemented with breakpoints.
5697 		 For those, we need to step over the breakpoint.  */
5698 	      if (bs->bp_location_at->loc_type != bp_loc_other)
5699 		this_action = BPSTAT_WHAT_SINGLE;
5700 	    }
5701 	  break;
5702 	case bp_jit_event:
5703 	  this_action = BPSTAT_WHAT_SINGLE;
5704 	  break;
5705 	case bp_call_dummy:
5706 	  /* Make sure the action is stop (silent or noisy),
5707 	     so infrun.c pops the dummy frame.  */
5708 	  retval.call_dummy = STOP_STACK_DUMMY;
5709 	  this_action = BPSTAT_WHAT_STOP_SILENT;
5710 	  break;
5711 	case bp_std_terminate:
5712 	  /* Make sure the action is stop (silent or noisy),
5713 	     so infrun.c pops the dummy frame.  */
5714 	  retval.call_dummy = STOP_STD_TERMINATE;
5715 	  this_action = BPSTAT_WHAT_STOP_SILENT;
5716 	  break;
5717 	case bp_tracepoint:
5718 	case bp_fast_tracepoint:
5719 	case bp_static_tracepoint:
5720 	  /* Tracepoint hits should not be reported back to GDB, and
5721 	     if one got through somehow, it should have been filtered
5722 	     out already.  */
5723 	  internal_error (__FILE__, __LINE__,
5724 			  _("bpstat_what: tracepoint encountered"));
5725 	  break;
5726 	case bp_gnu_ifunc_resolver:
5727 	  /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5728 	  this_action = BPSTAT_WHAT_SINGLE;
5729 	  break;
5730 	case bp_gnu_ifunc_resolver_return:
5731 	  /* The breakpoint will be removed, execution will restart from the
5732 	     PC of the former breakpoint.  */
5733 	  this_action = BPSTAT_WHAT_KEEP_CHECKING;
5734 	  break;
5735 
5736 	case bp_dprintf:
5737 	  if (bs->stop)
5738 	    this_action = BPSTAT_WHAT_STOP_SILENT;
5739 	  else
5740 	    this_action = BPSTAT_WHAT_SINGLE;
5741 	  break;
5742 
5743 	default:
5744 	  internal_error (__FILE__, __LINE__,
5745 			  _("bpstat_what: unhandled bptype %d"), (int) bptype);
5746 	}
5747 
5748       retval.main_action = std::max (retval.main_action, this_action);
5749     }
5750 
5751   return retval;
5752 }
5753 
5754 void
5755 bpstat_run_callbacks (bpstat bs_head)
5756 {
5757   bpstat bs;
5758 
5759   for (bs = bs_head; bs != NULL; bs = bs->next)
5760     {
5761       struct breakpoint *b = bs->breakpoint_at;
5762 
5763       if (b == NULL)
5764 	continue;
5765       switch (b->type)
5766 	{
5767 	case bp_jit_event:
5768 	  handle_jit_event (bs->bp_location_at->address);
5769 	  break;
5770 	case bp_gnu_ifunc_resolver:
5771 	  gnu_ifunc_resolver_stop (b);
5772 	  break;
5773 	case bp_gnu_ifunc_resolver_return:
5774 	  gnu_ifunc_resolver_return_stop (b);
5775 	  break;
5776 	}
5777     }
5778 }
5779 
5780 /* See breakpoint.h.  */
5781 
5782 bool
5783 bpstat_should_step ()
5784 {
5785   for (breakpoint *b : all_breakpoints ())
5786     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5787       return true;
5788 
5789   return false;
5790 }
5791 
5792 /* See breakpoint.h.  */
5793 
5794 bool
5795 bpstat_causes_stop (bpstat bs)
5796 {
5797   for (; bs != NULL; bs = bs->next)
5798     if (bs->stop)
5799       return true;
5800 
5801   return false;
5802 }
5803 
5804 
5805 
5806 /* Compute a string of spaces suitable to indent the next line
5807    so it starts at the position corresponding to the table column
5808    named COL_NAME in the currently active table of UIOUT.  */
5809 
5810 static char *
5811 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5812 {
5813   static char wrap_indent[80];
5814   int i, total_width, width, align;
5815   const char *text;
5816 
5817   total_width = 0;
5818   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5819     {
5820       if (strcmp (text, col_name) == 0)
5821 	{
5822 	  gdb_assert (total_width < sizeof wrap_indent);
5823 	  memset (wrap_indent, ' ', total_width);
5824 	  wrap_indent[total_width] = 0;
5825 
5826 	  return wrap_indent;
5827 	}
5828 
5829       total_width += width + 1;
5830     }
5831 
5832   return NULL;
5833 }
5834 
5835 /* Determine if the locations of this breakpoint will have their conditions
5836    evaluated by the target, host or a mix of both.  Returns the following:
5837 
5838     "host": Host evals condition.
5839     "host or target": Host or Target evals condition.
5840     "target": Target evals condition.
5841 */
5842 
5843 static const char *
5844 bp_condition_evaluator (struct breakpoint *b)
5845 {
5846   char host_evals = 0;
5847   char target_evals = 0;
5848 
5849   if (!b)
5850     return NULL;
5851 
5852   if (!is_breakpoint (b))
5853     return NULL;
5854 
5855   if (gdb_evaluates_breakpoint_condition_p ()
5856       || !target_supports_evaluation_of_breakpoint_conditions ())
5857     return condition_evaluation_host;
5858 
5859   for (bp_location *bl : b->locations ())
5860     {
5861       if (bl->cond_bytecode)
5862 	target_evals++;
5863       else
5864 	host_evals++;
5865     }
5866 
5867   if (host_evals && target_evals)
5868     return condition_evaluation_both;
5869   else if (target_evals)
5870     return condition_evaluation_target;
5871   else
5872     return condition_evaluation_host;
5873 }
5874 
5875 /* Determine the breakpoint location's condition evaluator.  This is
5876    similar to bp_condition_evaluator, but for locations.  */
5877 
5878 static const char *
5879 bp_location_condition_evaluator (struct bp_location *bl)
5880 {
5881   if (bl && !is_breakpoint (bl->owner))
5882     return NULL;
5883 
5884   if (gdb_evaluates_breakpoint_condition_p ()
5885       || !target_supports_evaluation_of_breakpoint_conditions ())
5886     return condition_evaluation_host;
5887 
5888   if (bl && bl->cond_bytecode)
5889     return condition_evaluation_target;
5890   else
5891     return condition_evaluation_host;
5892 }
5893 
5894 /* Print the LOC location out of the list of B->LOC locations.  */
5895 
5896 static void
5897 print_breakpoint_location (struct breakpoint *b,
5898 			   struct bp_location *loc)
5899 {
5900   struct ui_out *uiout = current_uiout;
5901 
5902   scoped_restore_current_program_space restore_pspace;
5903 
5904   if (loc != NULL && loc->shlib_disabled)
5905     loc = NULL;
5906 
5907   if (loc != NULL)
5908     set_current_program_space (loc->pspace);
5909 
5910   if (b->display_canonical)
5911     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5912   else if (loc && loc->symtab)
5913     {
5914       const struct symbol *sym = loc->symbol;
5915 
5916       if (sym)
5917 	{
5918 	  uiout->text ("in ");
5919 	  uiout->field_string ("func", sym->print_name (),
5920 			       function_name_style.style ());
5921 	  uiout->text (" ");
5922 	  uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5923 	  uiout->text ("at ");
5924 	}
5925       uiout->field_string ("file",
5926 			   symtab_to_filename_for_display (loc->symtab),
5927 			   file_name_style.style ());
5928       uiout->text (":");
5929 
5930       if (uiout->is_mi_like_p ())
5931 	uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5932 
5933       uiout->field_signed ("line", loc->line_number);
5934     }
5935   else if (loc)
5936     {
5937       string_file stb;
5938 
5939       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5940 			      demangle, "");
5941       uiout->field_stream ("at", stb);
5942     }
5943   else
5944     {
5945       uiout->field_string ("pending",
5946 			   event_location_to_string (b->location.get ()));
5947       /* If extra_string is available, it could be holding a condition
5948 	 or dprintf arguments.  In either case, make sure it is printed,
5949 	 too, but only for non-MI streams.  */
5950       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5951 	{
5952 	  if (b->type == bp_dprintf)
5953 	    uiout->text (",");
5954 	  else
5955 	    uiout->text (" ");
5956 	  uiout->text (b->extra_string);
5957 	}
5958     }
5959 
5960   if (loc && is_breakpoint (b)
5961       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5962       && bp_condition_evaluator (b) == condition_evaluation_both)
5963     {
5964       uiout->text (" (");
5965       uiout->field_string ("evaluated-by",
5966 			   bp_location_condition_evaluator (loc));
5967       uiout->text (")");
5968     }
5969 }
5970 
5971 static const char *
5972 bptype_string (enum bptype type)
5973 {
5974   struct ep_type_description
5975     {
5976       enum bptype type;
5977       const char *description;
5978     };
5979   static struct ep_type_description bptypes[] =
5980   {
5981     {bp_none, "?deleted?"},
5982     {bp_breakpoint, "breakpoint"},
5983     {bp_hardware_breakpoint, "hw breakpoint"},
5984     {bp_single_step, "sw single-step"},
5985     {bp_until, "until"},
5986     {bp_finish, "finish"},
5987     {bp_watchpoint, "watchpoint"},
5988     {bp_hardware_watchpoint, "hw watchpoint"},
5989     {bp_read_watchpoint, "read watchpoint"},
5990     {bp_access_watchpoint, "acc watchpoint"},
5991     {bp_longjmp, "longjmp"},
5992     {bp_longjmp_resume, "longjmp resume"},
5993     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5994     {bp_exception, "exception"},
5995     {bp_exception_resume, "exception resume"},
5996     {bp_step_resume, "step resume"},
5997     {bp_hp_step_resume, "high-priority step resume"},
5998     {bp_watchpoint_scope, "watchpoint scope"},
5999     {bp_call_dummy, "call dummy"},
6000     {bp_std_terminate, "std::terminate"},
6001     {bp_shlib_event, "shlib events"},
6002     {bp_thread_event, "thread events"},
6003     {bp_overlay_event, "overlay events"},
6004     {bp_longjmp_master, "longjmp master"},
6005     {bp_std_terminate_master, "std::terminate master"},
6006     {bp_exception_master, "exception master"},
6007     {bp_catchpoint, "catchpoint"},
6008     {bp_tracepoint, "tracepoint"},
6009     {bp_fast_tracepoint, "fast tracepoint"},
6010     {bp_static_tracepoint, "static tracepoint"},
6011     {bp_dprintf, "dprintf"},
6012     {bp_jit_event, "jit events"},
6013     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6014     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6015   };
6016 
6017   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6018       || ((int) type != bptypes[(int) type].type))
6019     internal_error (__FILE__, __LINE__,
6020 		    _("bptypes table does not describe type #%d."),
6021 		    (int) type);
6022 
6023   return bptypes[(int) type].description;
6024 }
6025 
6026 /* For MI, output a field named 'thread-groups' with a list as the value.
6027    For CLI, prefix the list with the string 'inf'. */
6028 
6029 static void
6030 output_thread_groups (struct ui_out *uiout,
6031 		      const char *field_name,
6032 		      const std::vector<int> &inf_nums,
6033 		      int mi_only)
6034 {
6035   int is_mi = uiout->is_mi_like_p ();
6036 
6037   /* For backward compatibility, don't display inferiors in CLI unless
6038      there are several.  Always display them for MI. */
6039   if (!is_mi && mi_only)
6040     return;
6041 
6042   ui_out_emit_list list_emitter (uiout, field_name);
6043 
6044   for (size_t i = 0; i < inf_nums.size (); i++)
6045     {
6046       if (is_mi)
6047 	{
6048 	  char mi_group[10];
6049 
6050 	  xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6051 	  uiout->field_string (NULL, mi_group);
6052 	}
6053       else
6054 	{
6055 	  if (i == 0)
6056 	    uiout->text (" inf ");
6057 	  else
6058 	    uiout->text (", ");
6059 
6060 	  uiout->text (plongest (inf_nums[i]));
6061 	}
6062     }
6063 }
6064 
6065 /* Print B to gdb_stdout.  If RAW_LOC, print raw breakpoint locations
6066    instead of going via breakpoint_ops::print_one.  This makes "maint
6067    info breakpoints" show the software breakpoint locations of
6068    catchpoints, which are considered internal implementation
6069    detail.  */
6070 
6071 static void
6072 print_one_breakpoint_location (struct breakpoint *b,
6073 			       struct bp_location *loc,
6074 			       int loc_number,
6075 			       struct bp_location **last_loc,
6076 			       int allflag, bool raw_loc)
6077 {
6078   struct command_line *l;
6079   static char bpenables[] = "nynny";
6080 
6081   struct ui_out *uiout = current_uiout;
6082   int header_of_multiple = 0;
6083   int part_of_multiple = (loc != NULL);
6084   struct value_print_options opts;
6085 
6086   get_user_print_options (&opts);
6087 
6088   gdb_assert (!loc || loc_number != 0);
6089   /* See comment in print_one_breakpoint concerning treatment of
6090      breakpoints with single disabled location.  */
6091   if (loc == NULL
6092       && (b->loc != NULL
6093 	  && (b->loc->next != NULL
6094 	      || !b->loc->enabled || b->loc->disabled_by_cond)))
6095     header_of_multiple = 1;
6096   if (loc == NULL)
6097     loc = b->loc;
6098 
6099   annotate_record ();
6100 
6101   /* 1 */
6102   annotate_field (0);
6103   if (part_of_multiple)
6104     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6105   else
6106     uiout->field_signed ("number", b->number);
6107 
6108   /* 2 */
6109   annotate_field (1);
6110   if (part_of_multiple)
6111     uiout->field_skip ("type");
6112   else
6113     uiout->field_string ("type", bptype_string (b->type));
6114 
6115   /* 3 */
6116   annotate_field (2);
6117   if (part_of_multiple)
6118     uiout->field_skip ("disp");
6119   else
6120     uiout->field_string ("disp", bpdisp_text (b->disposition));
6121 
6122   /* 4 */
6123   annotate_field (3);
6124   /* For locations that are disabled because of an invalid condition,
6125      display "N*" on CLI, where "*" refers to a footnote below the
6126      table.  For MI, simply display a "N" without a footnote.  */
6127   const char *N = (uiout->is_mi_like_p ()) ? "N" : "N*";
6128   if (part_of_multiple)
6129     uiout->field_string ("enabled", (loc->disabled_by_cond ? N
6130 				     : (loc->enabled ? "y" : "n")));
6131   else
6132     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6133 
6134   /* 5 and 6 */
6135   if (!raw_loc && b->ops != NULL && b->ops->print_one != NULL)
6136     b->ops->print_one (b, last_loc);
6137   else
6138     {
6139       if (is_watchpoint (b))
6140 	{
6141 	  struct watchpoint *w = (struct watchpoint *) b;
6142 
6143 	  /* Field 4, the address, is omitted (which makes the columns
6144 	     not line up too nicely with the headers, but the effect
6145 	     is relatively readable).  */
6146 	  if (opts.addressprint)
6147 	    uiout->field_skip ("addr");
6148 	  annotate_field (5);
6149 	  uiout->field_string ("what", w->exp_string);
6150 	}
6151       else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6152 	       || is_ada_exception_catchpoint (b))
6153 	{
6154 	  if (opts.addressprint)
6155 	    {
6156 	      annotate_field (4);
6157 	      if (header_of_multiple)
6158 		uiout->field_string ("addr", "<MULTIPLE>",
6159 				     metadata_style.style ());
6160 	      else if (b->loc == NULL || loc->shlib_disabled)
6161 		uiout->field_string ("addr", "<PENDING>",
6162 				     metadata_style.style ());
6163 	      else
6164 		uiout->field_core_addr ("addr",
6165 					loc->gdbarch, loc->address);
6166 	    }
6167 	  annotate_field (5);
6168 	  if (!header_of_multiple)
6169 	    print_breakpoint_location (b, loc);
6170 	  if (b->loc)
6171 	    *last_loc = b->loc;
6172 	}
6173     }
6174 
6175   if (loc != NULL && !header_of_multiple)
6176     {
6177       std::vector<int> inf_nums;
6178       int mi_only = 1;
6179 
6180       for (inferior *inf : all_inferiors ())
6181 	{
6182 	  if (inf->pspace == loc->pspace)
6183 	    inf_nums.push_back (inf->num);
6184 	}
6185 
6186 	/* For backward compatibility, don't display inferiors in CLI unless
6187 	   there are several.  Always display for MI. */
6188 	if (allflag
6189 	    || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6190 		&& (program_spaces.size () > 1
6191 		    || number_of_inferiors () > 1)
6192 		/* LOC is for existing B, it cannot be in
6193 		   moribund_locations and thus having NULL OWNER.  */
6194 		&& loc->owner->type != bp_catchpoint))
6195 	mi_only = 0;
6196       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6197     }
6198 
6199   if (!part_of_multiple)
6200     {
6201       if (b->thread != -1)
6202 	{
6203 	  /* FIXME: This seems to be redundant and lost here; see the
6204 	     "stop only in" line a little further down.  */
6205 	  uiout->text (" thread ");
6206 	  uiout->field_signed ("thread", b->thread);
6207 	}
6208       else if (b->task != 0)
6209 	{
6210 	  uiout->text (" task ");
6211 	  uiout->field_signed ("task", b->task);
6212 	}
6213     }
6214 
6215   uiout->text ("\n");
6216 
6217   if (!part_of_multiple)
6218     b->ops->print_one_detail (b, uiout);
6219 
6220   if (part_of_multiple && frame_id_p (b->frame_id))
6221     {
6222       annotate_field (6);
6223       uiout->text ("\tstop only in stack frame at ");
6224       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6225 	 the frame ID.  */
6226       uiout->field_core_addr ("frame",
6227 			      b->gdbarch, b->frame_id.stack_addr);
6228       uiout->text ("\n");
6229     }
6230 
6231   if (!part_of_multiple && b->cond_string)
6232     {
6233       annotate_field (7);
6234       if (is_tracepoint (b))
6235 	uiout->text ("\ttrace only if ");
6236       else
6237 	uiout->text ("\tstop only if ");
6238       uiout->field_string ("cond", b->cond_string);
6239 
6240       /* Print whether the target is doing the breakpoint's condition
6241 	 evaluation.  If GDB is doing the evaluation, don't print anything.  */
6242       if (is_breakpoint (b)
6243 	  && breakpoint_condition_evaluation_mode ()
6244 	  == condition_evaluation_target)
6245 	{
6246 	  uiout->message (" (%pF evals)",
6247 			  string_field ("evaluated-by",
6248 					bp_condition_evaluator (b)));
6249 	}
6250       uiout->text ("\n");
6251     }
6252 
6253   if (!part_of_multiple && b->thread != -1)
6254     {
6255       /* FIXME should make an annotation for this.  */
6256       uiout->text ("\tstop only in thread ");
6257       if (uiout->is_mi_like_p ())
6258 	uiout->field_signed ("thread", b->thread);
6259       else
6260 	{
6261 	  struct thread_info *thr = find_thread_global_id (b->thread);
6262 
6263 	  uiout->field_string ("thread", print_thread_id (thr));
6264 	}
6265       uiout->text ("\n");
6266     }
6267 
6268   if (!part_of_multiple)
6269     {
6270       if (b->hit_count)
6271 	{
6272 	  /* FIXME should make an annotation for this.  */
6273 	  if (is_catchpoint (b))
6274 	    uiout->text ("\tcatchpoint");
6275 	  else if (is_tracepoint (b))
6276 	    uiout->text ("\ttracepoint");
6277 	  else
6278 	    uiout->text ("\tbreakpoint");
6279 	  uiout->text (" already hit ");
6280 	  uiout->field_signed ("times", b->hit_count);
6281 	  if (b->hit_count == 1)
6282 	    uiout->text (" time\n");
6283 	  else
6284 	    uiout->text (" times\n");
6285 	}
6286       else
6287 	{
6288 	  /* Output the count also if it is zero, but only if this is mi.  */
6289 	  if (uiout->is_mi_like_p ())
6290 	    uiout->field_signed ("times", b->hit_count);
6291 	}
6292     }
6293 
6294   if (!part_of_multiple && b->ignore_count)
6295     {
6296       annotate_field (8);
6297       uiout->message ("\tignore next %pF hits\n",
6298 		      signed_field ("ignore", b->ignore_count));
6299     }
6300 
6301   /* Note that an enable count of 1 corresponds to "enable once"
6302      behavior, which is reported by the combination of enablement and
6303      disposition, so we don't need to mention it here.  */
6304   if (!part_of_multiple && b->enable_count > 1)
6305     {
6306       annotate_field (8);
6307       uiout->text ("\tdisable after ");
6308       /* Tweak the wording to clarify that ignore and enable counts
6309 	 are distinct, and have additive effect.  */
6310       if (b->ignore_count)
6311 	uiout->text ("additional ");
6312       else
6313 	uiout->text ("next ");
6314       uiout->field_signed ("enable", b->enable_count);
6315       uiout->text (" hits\n");
6316     }
6317 
6318   if (!part_of_multiple && is_tracepoint (b))
6319     {
6320       struct tracepoint *tp = (struct tracepoint *) b;
6321 
6322       if (tp->traceframe_usage)
6323 	{
6324 	  uiout->text ("\ttrace buffer usage ");
6325 	  uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6326 	  uiout->text (" bytes\n");
6327 	}
6328     }
6329 
6330   l = b->commands ? b->commands.get () : NULL;
6331   if (!part_of_multiple && l)
6332     {
6333       annotate_field (9);
6334       ui_out_emit_tuple tuple_emitter (uiout, "script");
6335       print_command_lines (uiout, l, 4);
6336     }
6337 
6338   if (is_tracepoint (b))
6339     {
6340       struct tracepoint *t = (struct tracepoint *) b;
6341 
6342       if (!part_of_multiple && t->pass_count)
6343 	{
6344 	  annotate_field (10);
6345 	  uiout->text ("\tpass count ");
6346 	  uiout->field_signed ("pass", t->pass_count);
6347 	  uiout->text (" \n");
6348 	}
6349 
6350       /* Don't display it when tracepoint or tracepoint location is
6351 	 pending.   */
6352       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6353 	{
6354 	  annotate_field (11);
6355 
6356 	  if (uiout->is_mi_like_p ())
6357 	    uiout->field_string ("installed",
6358 				 loc->inserted ? "y" : "n");
6359 	  else
6360 	    {
6361 	      if (loc->inserted)
6362 		uiout->text ("\t");
6363 	      else
6364 		uiout->text ("\tnot ");
6365 	      uiout->text ("installed on target\n");
6366 	    }
6367 	}
6368     }
6369 
6370   if (uiout->is_mi_like_p () && !part_of_multiple)
6371     {
6372       if (is_watchpoint (b))
6373 	{
6374 	  struct watchpoint *w = (struct watchpoint *) b;
6375 
6376 	  uiout->field_string ("original-location", w->exp_string);
6377 	}
6378       else if (b->location != NULL
6379 	       && event_location_to_string (b->location.get ()) != NULL)
6380 	uiout->field_string ("original-location",
6381 			     event_location_to_string (b->location.get ()));
6382     }
6383 }
6384 
6385 /* See breakpoint.h. */
6386 
6387 bool fix_multi_location_breakpoint_output_globally = false;
6388 
6389 static void
6390 print_one_breakpoint (struct breakpoint *b,
6391 		      struct bp_location **last_loc,
6392 		      int allflag)
6393 {
6394   struct ui_out *uiout = current_uiout;
6395   bool use_fixed_output
6396     = (uiout->test_flags (fix_multi_location_breakpoint_output)
6397        || fix_multi_location_breakpoint_output_globally);
6398 
6399   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6400   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag, false);
6401 
6402   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6403      are outside.  */
6404   if (!use_fixed_output)
6405     bkpt_tuple_emitter.reset ();
6406 
6407   /* If this breakpoint has custom print function,
6408      it's already printed.  Otherwise, print individual
6409      locations, if any.  */
6410   if (b->ops == NULL
6411       || b->ops->print_one == NULL
6412       || allflag)
6413     {
6414       /* If breakpoint has a single location that is disabled, we
6415 	 print it as if it had several locations, since otherwise it's
6416 	 hard to represent "breakpoint enabled, location disabled"
6417 	 situation.
6418 
6419 	 Note that while hardware watchpoints have several locations
6420 	 internally, that's not a property exposed to users.
6421 
6422 	 Likewise, while catchpoints may be implemented with
6423 	 breakpoints (e.g., catch throw), that's not a property
6424 	 exposed to users.  We do however display the internal
6425 	 breakpoint locations with "maint info breakpoints".  */
6426       if (!is_hardware_watchpoint (b)
6427 	  && (!is_catchpoint (b) || is_exception_catchpoint (b)
6428 	      || is_ada_exception_catchpoint (b))
6429 	  && (allflag
6430 	      || (b->loc && (b->loc->next
6431 			     || !b->loc->enabled
6432 			     || b->loc->disabled_by_cond))))
6433 	{
6434 	  gdb::optional<ui_out_emit_list> locations_list;
6435 
6436 	  /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6437 	     MI record.  For later versions, place breakpoint locations in a
6438 	     list.  */
6439 	  if (uiout->is_mi_like_p () && use_fixed_output)
6440 	    locations_list.emplace (uiout, "locations");
6441 
6442 	  int n = 1;
6443 	  for (bp_location *loc : b->locations ())
6444 	    {
6445 	      ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6446 	      print_one_breakpoint_location (b, loc, n, last_loc,
6447 					     allflag, allflag);
6448 	      n++;
6449 	    }
6450 	}
6451     }
6452 }
6453 
6454 static int
6455 breakpoint_address_bits (struct breakpoint *b)
6456 {
6457   int print_address_bits = 0;
6458 
6459   /* Software watchpoints that aren't watching memory don't have an
6460      address to print.  */
6461   if (is_no_memory_software_watchpoint (b))
6462     return 0;
6463 
6464   for (bp_location *loc : b->locations ())
6465     {
6466       int addr_bit;
6467 
6468       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6469       if (addr_bit > print_address_bits)
6470 	print_address_bits = addr_bit;
6471     }
6472 
6473   return print_address_bits;
6474 }
6475 
6476 /* See breakpoint.h.  */
6477 
6478 void
6479 print_breakpoint (breakpoint *b)
6480 {
6481   struct bp_location *dummy_loc = NULL;
6482   print_one_breakpoint (b, &dummy_loc, 0);
6483 }
6484 
6485 /* Return true if this breakpoint was set by the user, false if it is
6486    internal or momentary.  */
6487 
6488 int
6489 user_breakpoint_p (struct breakpoint *b)
6490 {
6491   return b->number > 0;
6492 }
6493 
6494 /* See breakpoint.h.  */
6495 
6496 int
6497 pending_breakpoint_p (struct breakpoint *b)
6498 {
6499   return b->loc == NULL;
6500 }
6501 
6502 /* Print information on breakpoints (including watchpoints and tracepoints).
6503 
6504    If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6505    understood by number_or_range_parser.  Only breakpoints included in this
6506    list are then printed.
6507 
6508    If SHOW_INTERNAL is true, print internal breakpoints.
6509 
6510    If FILTER is non-NULL, call it on each breakpoint and only include the
6511    ones for which it returns true.
6512 
6513    Return the total number of breakpoints listed.  */
6514 
6515 static int
6516 breakpoint_1 (const char *bp_num_list, bool show_internal,
6517 	      bool (*filter) (const struct breakpoint *))
6518 {
6519   struct bp_location *last_loc = NULL;
6520   int nr_printable_breakpoints;
6521   struct value_print_options opts;
6522   int print_address_bits = 0;
6523   int print_type_col_width = 14;
6524   struct ui_out *uiout = current_uiout;
6525   bool has_disabled_by_cond_location = false;
6526 
6527   get_user_print_options (&opts);
6528 
6529   /* Compute the number of rows in the table, as well as the size
6530      required for address fields.  */
6531   nr_printable_breakpoints = 0;
6532   for (breakpoint *b : all_breakpoints ())
6533     {
6534       /* If we have a filter, only list the breakpoints it accepts.  */
6535       if (filter && !filter (b))
6536 	continue;
6537 
6538       /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6539 	 accept.  Skip the others.  */
6540       if (bp_num_list != NULL && *bp_num_list != '\0')
6541 	{
6542 	  if (show_internal && parse_and_eval_long (bp_num_list) != b->number)
6543 	    continue;
6544 	  if (!show_internal && !number_is_in_list (bp_num_list, b->number))
6545 	    continue;
6546 	}
6547 
6548       if (show_internal || user_breakpoint_p (b))
6549 	{
6550 	  int addr_bit, type_len;
6551 
6552 	  addr_bit = breakpoint_address_bits (b);
6553 	  if (addr_bit > print_address_bits)
6554 	    print_address_bits = addr_bit;
6555 
6556 	  type_len = strlen (bptype_string (b->type));
6557 	  if (type_len > print_type_col_width)
6558 	    print_type_col_width = type_len;
6559 
6560 	  nr_printable_breakpoints++;
6561 	}
6562     }
6563 
6564   {
6565     ui_out_emit_table table_emitter (uiout,
6566 				     opts.addressprint ? 6 : 5,
6567 				     nr_printable_breakpoints,
6568 				     "BreakpointTable");
6569 
6570     if (nr_printable_breakpoints > 0)
6571       annotate_breakpoints_headers ();
6572     if (nr_printable_breakpoints > 0)
6573       annotate_field (0);
6574     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6575     if (nr_printable_breakpoints > 0)
6576       annotate_field (1);
6577     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6578     if (nr_printable_breakpoints > 0)
6579       annotate_field (2);
6580     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6581     if (nr_printable_breakpoints > 0)
6582       annotate_field (3);
6583     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6584     if (opts.addressprint)
6585       {
6586 	if (nr_printable_breakpoints > 0)
6587 	  annotate_field (4);
6588 	if (print_address_bits <= 32)
6589 	  uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6590 	else
6591 	  uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6592       }
6593     if (nr_printable_breakpoints > 0)
6594       annotate_field (5);
6595     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6596     uiout->table_body ();
6597     if (nr_printable_breakpoints > 0)
6598       annotate_breakpoints_table ();
6599 
6600     for (breakpoint *b : all_breakpoints ())
6601       {
6602 	QUIT;
6603 	/* If we have a filter, only list the breakpoints it accepts.  */
6604 	if (filter && !filter (b))
6605 	  continue;
6606 
6607 	/* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6608 	   accept.  Skip the others.  */
6609 
6610 	if (bp_num_list != NULL && *bp_num_list != '\0')
6611 	  {
6612 	    if (show_internal)	/* maintenance info breakpoint */
6613 	      {
6614 		if (parse_and_eval_long (bp_num_list) != b->number)
6615 		  continue;
6616 	      }
6617 	    else		/* all others */
6618 	      {
6619 		if (!number_is_in_list (bp_num_list, b->number))
6620 		  continue;
6621 	      }
6622 	  }
6623 	/* We only print out user settable breakpoints unless the
6624 	   show_internal is set.  */
6625 	if (show_internal || user_breakpoint_p (b))
6626 	  {
6627 	    print_one_breakpoint (b, &last_loc, show_internal);
6628 	    for (bp_location *loc : b->locations ())
6629 	      if (loc->disabled_by_cond)
6630 		has_disabled_by_cond_location = true;
6631 	  }
6632       }
6633   }
6634 
6635   if (nr_printable_breakpoints == 0)
6636     {
6637       /* If there's a filter, let the caller decide how to report
6638 	 empty list.  */
6639       if (!filter)
6640 	{
6641 	  if (bp_num_list == NULL || *bp_num_list == '\0')
6642 	    uiout->message ("No breakpoints or watchpoints.\n");
6643 	  else
6644 	    uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6645 			    bp_num_list);
6646 	}
6647     }
6648   else
6649     {
6650       if (last_loc && !server_command)
6651 	set_next_address (last_loc->gdbarch, last_loc->address);
6652 
6653       if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
6654 	uiout->message (_("(*): Breakpoint condition is invalid at this "
6655 			  "location.\n"));
6656     }
6657 
6658   /* FIXME?  Should this be moved up so that it is only called when
6659      there have been breakpoints? */
6660   annotate_breakpoints_table_end ();
6661 
6662   return nr_printable_breakpoints;
6663 }
6664 
6665 /* Display the value of default-collect in a way that is generally
6666    compatible with the breakpoint list.  */
6667 
6668 static void
6669 default_collect_info (void)
6670 {
6671   struct ui_out *uiout = current_uiout;
6672 
6673   /* If it has no value (which is frequently the case), say nothing; a
6674      message like "No default-collect." gets in user's face when it's
6675      not wanted.  */
6676   if (!*default_collect)
6677     return;
6678 
6679   /* The following phrase lines up nicely with per-tracepoint collect
6680      actions.  */
6681   uiout->text ("default collect ");
6682   uiout->field_string ("default-collect", default_collect);
6683   uiout->text (" \n");
6684 }
6685 
6686 static void
6687 info_breakpoints_command (const char *args, int from_tty)
6688 {
6689   breakpoint_1 (args, false, NULL);
6690 
6691   default_collect_info ();
6692 }
6693 
6694 static void
6695 info_watchpoints_command (const char *args, int from_tty)
6696 {
6697   int num_printed = breakpoint_1 (args, false, is_watchpoint);
6698   struct ui_out *uiout = current_uiout;
6699 
6700   if (num_printed == 0)
6701     {
6702       if (args == NULL || *args == '\0')
6703 	uiout->message ("No watchpoints.\n");
6704       else
6705 	uiout->message ("No watchpoint matching '%s'.\n", args);
6706     }
6707 }
6708 
6709 static void
6710 maintenance_info_breakpoints (const char *args, int from_tty)
6711 {
6712   breakpoint_1 (args, true, NULL);
6713 
6714   default_collect_info ();
6715 }
6716 
6717 static int
6718 breakpoint_has_pc (struct breakpoint *b,
6719 		   struct program_space *pspace,
6720 		   CORE_ADDR pc, struct obj_section *section)
6721 {
6722   for (bp_location *bl : b->locations ())
6723     {
6724       if (bl->pspace == pspace
6725 	  && bl->address == pc
6726 	  && (!overlay_debugging || bl->section == section))
6727 	return 1;
6728     }
6729   return 0;
6730 }
6731 
6732 /* Print a message describing any user-breakpoints set at PC.  This
6733    concerns with logical breakpoints, so we match program spaces, not
6734    address spaces.  */
6735 
6736 static void
6737 describe_other_breakpoints (struct gdbarch *gdbarch,
6738 			    struct program_space *pspace, CORE_ADDR pc,
6739 			    struct obj_section *section, int thread)
6740 {
6741   int others = 0;
6742 
6743   for (breakpoint *b : all_breakpoints ())
6744     others += (user_breakpoint_p (b)
6745 	       && breakpoint_has_pc (b, pspace, pc, section));
6746 
6747   if (others > 0)
6748     {
6749       if (others == 1)
6750 	printf_filtered (_("Note: breakpoint "));
6751       else /* if (others == ???) */
6752 	printf_filtered (_("Note: breakpoints "));
6753       for (breakpoint *b : all_breakpoints ())
6754 	if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6755 	  {
6756 	    others--;
6757 	    printf_filtered ("%d", b->number);
6758 	    if (b->thread == -1 && thread != -1)
6759 	      printf_filtered (" (all threads)");
6760 	    else if (b->thread != -1)
6761 	      printf_filtered (" (thread %d)", b->thread);
6762 	    printf_filtered ("%s%s ",
6763 			     ((b->enable_state == bp_disabled
6764 			       || b->enable_state == bp_call_disabled)
6765 			      ? " (disabled)"
6766 			      : ""),
6767 			     (others > 1) ? ","
6768 			     : ((others == 1) ? " and" : ""));
6769 	  }
6770       current_uiout->message (_("also set at pc %ps.\n"),
6771 			      styled_string (address_style.style (),
6772 					     paddress (gdbarch, pc)));
6773     }
6774 }
6775 
6776 
6777 /* Return true iff it is meaningful to use the address member of LOC.
6778    For some breakpoint types, the locations' address members are
6779    irrelevant and it makes no sense to attempt to compare them to
6780    other addresses (or use them for any other purpose either).
6781 
6782    More specifically, software watchpoints and catchpoints that are
6783    not backed by breakpoints always have a zero valued location
6784    address and we don't want to mark breakpoints of any of these types
6785    to be a duplicate of an actual breakpoint location at address
6786    zero.  */
6787 
6788 static bool
6789 bl_address_is_meaningful (bp_location *loc)
6790 {
6791   return loc->loc_type != bp_loc_other;
6792 }
6793 
6794 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6795    true if LOC1 and LOC2 represent the same watchpoint location.  */
6796 
6797 static int
6798 watchpoint_locations_match (struct bp_location *loc1,
6799 			    struct bp_location *loc2)
6800 {
6801   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6802   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6803 
6804   /* Both of them must exist.  */
6805   gdb_assert (w1 != NULL);
6806   gdb_assert (w2 != NULL);
6807 
6808   /* If the target can evaluate the condition expression in hardware,
6809      then we we need to insert both watchpoints even if they are at
6810      the same place.  Otherwise the watchpoint will only trigger when
6811      the condition of whichever watchpoint was inserted evaluates to
6812      true, not giving a chance for GDB to check the condition of the
6813      other watchpoint.  */
6814   if ((w1->cond_exp
6815        && target_can_accel_watchpoint_condition (loc1->address,
6816 						 loc1->length,
6817 						 loc1->watchpoint_type,
6818 						 w1->cond_exp.get ()))
6819       || (w2->cond_exp
6820 	  && target_can_accel_watchpoint_condition (loc2->address,
6821 						    loc2->length,
6822 						    loc2->watchpoint_type,
6823 						    w2->cond_exp.get ())))
6824     return 0;
6825 
6826   /* Note that this checks the owner's type, not the location's.  In
6827      case the target does not support read watchpoints, but does
6828      support access watchpoints, we'll have bp_read_watchpoint
6829      watchpoints with hw_access locations.  Those should be considered
6830      duplicates of hw_read locations.  The hw_read locations will
6831      become hw_access locations later.  */
6832   return (loc1->owner->type == loc2->owner->type
6833 	  && loc1->pspace->aspace == loc2->pspace->aspace
6834 	  && loc1->address == loc2->address
6835 	  && loc1->length == loc2->length);
6836 }
6837 
6838 /* See breakpoint.h.  */
6839 
6840 int
6841 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6842 			  const address_space *aspace2, CORE_ADDR addr2)
6843 {
6844   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6845 	   || aspace1 == aspace2)
6846 	  && addr1 == addr2);
6847 }
6848 
6849 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6850    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6851    matches ASPACE2.  On targets that have global breakpoints, the address
6852    space doesn't really matter.  */
6853 
6854 static int
6855 breakpoint_address_match_range (const address_space *aspace1,
6856 				CORE_ADDR addr1,
6857 				int len1, const address_space *aspace2,
6858 				CORE_ADDR addr2)
6859 {
6860   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6861 	   || aspace1 == aspace2)
6862 	  && addr2 >= addr1 && addr2 < addr1 + len1);
6863 }
6864 
6865 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6866    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6867    matches the breakpoint's address space.  On targets that have global
6868    breakpoints, the address space doesn't really matter.  */
6869 
6870 static int
6871 breakpoint_location_address_match (struct bp_location *bl,
6872 				   const address_space *aspace,
6873 				   CORE_ADDR addr)
6874 {
6875   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6876 				    aspace, addr)
6877 	  || (bl->length
6878 	      && breakpoint_address_match_range (bl->pspace->aspace,
6879 						 bl->address, bl->length,
6880 						 aspace, addr)));
6881 }
6882 
6883 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6884    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6885    match happens only if ASPACE matches the breakpoint's address
6886    space.  On targets that have global breakpoints, the address space
6887    doesn't really matter.  */
6888 
6889 static int
6890 breakpoint_location_address_range_overlap (struct bp_location *bl,
6891 					   const address_space *aspace,
6892 					   CORE_ADDR addr, int len)
6893 {
6894   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6895       || bl->pspace->aspace == aspace)
6896     {
6897       int bl_len = bl->length != 0 ? bl->length : 1;
6898 
6899       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6900 	return 1;
6901     }
6902   return 0;
6903 }
6904 
6905 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6906    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6907    true, otherwise returns false.  */
6908 
6909 static int
6910 tracepoint_locations_match (struct bp_location *loc1,
6911 			    struct bp_location *loc2)
6912 {
6913   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6914     /* Since tracepoint locations are never duplicated with others', tracepoint
6915        locations at the same address of different tracepoints are regarded as
6916        different locations.  */
6917     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6918   else
6919     return 0;
6920 }
6921 
6922 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6923    (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
6924    the same location.  If SW_HW_BPS_MATCH is true, then software
6925    breakpoint locations and hardware breakpoint locations match,
6926    otherwise they don't.  */
6927 
6928 static int
6929 breakpoint_locations_match (struct bp_location *loc1,
6930 			    struct bp_location *loc2,
6931 			    bool sw_hw_bps_match)
6932 {
6933   int hw_point1, hw_point2;
6934 
6935   /* Both of them must not be in moribund_locations.  */
6936   gdb_assert (loc1->owner != NULL);
6937   gdb_assert (loc2->owner != NULL);
6938 
6939   hw_point1 = is_hardware_watchpoint (loc1->owner);
6940   hw_point2 = is_hardware_watchpoint (loc2->owner);
6941 
6942   if (hw_point1 != hw_point2)
6943     return 0;
6944   else if (hw_point1)
6945     return watchpoint_locations_match (loc1, loc2);
6946   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6947     return tracepoint_locations_match (loc1, loc2);
6948   else
6949     /* We compare bp_location.length in order to cover ranged
6950        breakpoints.  Keep this in sync with
6951        bp_location_is_less_than.  */
6952     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6953 				     loc2->pspace->aspace, loc2->address)
6954 	    && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
6955 	    && loc1->length == loc2->length);
6956 }
6957 
6958 static void
6959 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6960 			       int bnum, int have_bnum)
6961 {
6962   /* The longest string possibly returned by hex_string_custom
6963      is 50 chars.  These must be at least that big for safety.  */
6964   char astr1[64];
6965   char astr2[64];
6966 
6967   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6968   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6969   if (have_bnum)
6970     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6971 	     bnum, astr1, astr2);
6972   else
6973     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6974 }
6975 
6976 /* Adjust a breakpoint's address to account for architectural
6977    constraints on breakpoint placement.  Return the adjusted address.
6978    Note: Very few targets require this kind of adjustment.  For most
6979    targets, this function is simply the identity function.  */
6980 
6981 static CORE_ADDR
6982 adjust_breakpoint_address (struct gdbarch *gdbarch,
6983 			   CORE_ADDR bpaddr, enum bptype bptype)
6984 {
6985   if (bptype == bp_watchpoint
6986       || bptype == bp_hardware_watchpoint
6987       || bptype == bp_read_watchpoint
6988       || bptype == bp_access_watchpoint
6989       || bptype == bp_catchpoint)
6990     {
6991       /* Watchpoints and the various bp_catch_* eventpoints should not
6992 	 have their addresses modified.  */
6993       return bpaddr;
6994     }
6995   else if (bptype == bp_single_step)
6996     {
6997       /* Single-step breakpoints should not have their addresses
6998 	 modified.  If there's any architectural constrain that
6999 	 applies to this address, then it should have already been
7000 	 taken into account when the breakpoint was created in the
7001 	 first place.  If we didn't do this, stepping through e.g.,
7002 	 Thumb-2 IT blocks would break.  */
7003       return bpaddr;
7004     }
7005   else
7006     {
7007       CORE_ADDR adjusted_bpaddr = bpaddr;
7008 
7009       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7010 	{
7011 	  /* Some targets have architectural constraints on the placement
7012 	     of breakpoint instructions.  Obtain the adjusted address.  */
7013 	  adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7014 	}
7015 
7016       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
7017 
7018       /* An adjusted breakpoint address can significantly alter
7019 	 a user's expectations.  Print a warning if an adjustment
7020 	 is required.  */
7021       if (adjusted_bpaddr != bpaddr)
7022 	breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7023 
7024       return adjusted_bpaddr;
7025     }
7026 }
7027 
7028 static bp_loc_type
7029 bp_location_from_bp_type (bptype type)
7030 {
7031   switch (type)
7032     {
7033     case bp_breakpoint:
7034     case bp_single_step:
7035     case bp_until:
7036     case bp_finish:
7037     case bp_longjmp:
7038     case bp_longjmp_resume:
7039     case bp_longjmp_call_dummy:
7040     case bp_exception:
7041     case bp_exception_resume:
7042     case bp_step_resume:
7043     case bp_hp_step_resume:
7044     case bp_watchpoint_scope:
7045     case bp_call_dummy:
7046     case bp_std_terminate:
7047     case bp_shlib_event:
7048     case bp_thread_event:
7049     case bp_overlay_event:
7050     case bp_jit_event:
7051     case bp_longjmp_master:
7052     case bp_std_terminate_master:
7053     case bp_exception_master:
7054     case bp_gnu_ifunc_resolver:
7055     case bp_gnu_ifunc_resolver_return:
7056     case bp_dprintf:
7057       return bp_loc_software_breakpoint;
7058     case bp_hardware_breakpoint:
7059       return bp_loc_hardware_breakpoint;
7060     case bp_hardware_watchpoint:
7061     case bp_read_watchpoint:
7062     case bp_access_watchpoint:
7063       return bp_loc_hardware_watchpoint;
7064     case bp_watchpoint:
7065     case bp_catchpoint:
7066     case bp_tracepoint:
7067     case bp_fast_tracepoint:
7068     case bp_static_tracepoint:
7069       return bp_loc_other;
7070     default:
7071       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7072     }
7073 }
7074 
7075 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7076 {
7077   this->owner = owner;
7078   this->cond_bytecode = NULL;
7079   this->shlib_disabled = 0;
7080   this->enabled = 1;
7081   this->disabled_by_cond = false;
7082 
7083   this->loc_type = type;
7084 
7085   if (this->loc_type == bp_loc_software_breakpoint
7086       || this->loc_type == bp_loc_hardware_breakpoint)
7087     mark_breakpoint_location_modified (this);
7088 
7089   incref ();
7090 }
7091 
7092 bp_location::bp_location (breakpoint *owner)
7093   : bp_location::bp_location (owner,
7094 			      bp_location_from_bp_type (owner->type))
7095 {
7096 }
7097 
7098 /* Allocate a struct bp_location.  */
7099 
7100 static struct bp_location *
7101 allocate_bp_location (struct breakpoint *bpt)
7102 {
7103   return bpt->ops->allocate_location (bpt);
7104 }
7105 
7106 /* Decrement reference count.  If the reference count reaches 0,
7107    destroy the bp_location.  Sets *BLP to NULL.  */
7108 
7109 static void
7110 decref_bp_location (struct bp_location **blp)
7111 {
7112   bp_location_ref_policy::decref (*blp);
7113   *blp = NULL;
7114 }
7115 
7116 /* Add breakpoint B at the end of the global breakpoint chain.  */
7117 
7118 static breakpoint *
7119 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7120 {
7121   struct breakpoint *b1;
7122   struct breakpoint *result = b.get ();
7123 
7124   /* Add this breakpoint to the end of the chain so that a list of
7125      breakpoints will come out in order of increasing numbers.  */
7126 
7127   b1 = breakpoint_chain;
7128   if (b1 == 0)
7129     breakpoint_chain = b.release ();
7130   else
7131     {
7132       while (b1->next)
7133 	b1 = b1->next;
7134       b1->next = b.release ();
7135     }
7136 
7137   return result;
7138 }
7139 
7140 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7141 
7142 static void
7143 init_raw_breakpoint_without_location (struct breakpoint *b,
7144 				      struct gdbarch *gdbarch,
7145 				      enum bptype bptype,
7146 				      const struct breakpoint_ops *ops)
7147 {
7148   gdb_assert (ops != NULL);
7149 
7150   b->ops = ops;
7151   b->type = bptype;
7152   b->gdbarch = gdbarch;
7153   b->language = current_language->la_language;
7154   b->input_radix = input_radix;
7155   b->related_breakpoint = b;
7156 }
7157 
7158 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7159    that has type BPTYPE and has no locations as yet.  */
7160 
7161 static struct breakpoint *
7162 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7163 				     enum bptype bptype,
7164 				     const struct breakpoint_ops *ops)
7165 {
7166   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7167 
7168   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7169   return add_to_breakpoint_chain (std::move (b));
7170 }
7171 
7172 /* Initialize loc->function_name.  */
7173 
7174 static void
7175 set_breakpoint_location_function (struct bp_location *loc)
7176 {
7177   gdb_assert (loc->owner != NULL);
7178 
7179   if (loc->owner->type == bp_breakpoint
7180       || loc->owner->type == bp_hardware_breakpoint
7181       || is_tracepoint (loc->owner))
7182     {
7183       const char *function_name;
7184 
7185       if (loc->msymbol != NULL
7186 	  && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7187 	      || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc))
7188 	{
7189 	  struct breakpoint *b = loc->owner;
7190 
7191 	  function_name = loc->msymbol->linkage_name ();
7192 
7193 	  if (b->type == bp_breakpoint && b->loc == loc
7194 	      && loc->next == NULL && b->related_breakpoint == b)
7195 	    {
7196 	      /* Create only the whole new breakpoint of this type but do not
7197 		 mess more complicated breakpoints with multiple locations.  */
7198 	      b->type = bp_gnu_ifunc_resolver;
7199 	      /* Remember the resolver's address for use by the return
7200 		 breakpoint.  */
7201 	      loc->related_address = loc->address;
7202 	    }
7203 	}
7204       else
7205 	find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7206 
7207       if (function_name)
7208 	loc->function_name = xstrdup (function_name);
7209     }
7210 }
7211 
7212 /* Attempt to determine architecture of location identified by SAL.  */
7213 struct gdbarch *
7214 get_sal_arch (struct symtab_and_line sal)
7215 {
7216   if (sal.section)
7217     return sal.section->objfile->arch ();
7218   if (sal.symtab)
7219     return SYMTAB_OBJFILE (sal.symtab)->arch ();
7220 
7221   return NULL;
7222 }
7223 
7224 /* Low level routine for partially initializing a breakpoint of type
7225    BPTYPE.  The newly created breakpoint's address, section, source
7226    file name, and line number are provided by SAL.
7227 
7228    It is expected that the caller will complete the initialization of
7229    the newly created breakpoint struct as well as output any status
7230    information regarding the creation of a new breakpoint.  */
7231 
7232 static void
7233 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7234 		     struct symtab_and_line sal, enum bptype bptype,
7235 		     const struct breakpoint_ops *ops)
7236 {
7237   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7238 
7239   add_location_to_breakpoint (b, &sal);
7240 
7241   if (bptype != bp_catchpoint)
7242     gdb_assert (sal.pspace != NULL);
7243 
7244   /* Store the program space that was used to set the breakpoint,
7245      except for ordinary breakpoints, which are independent of the
7246      program space.  */
7247   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7248     b->pspace = sal.pspace;
7249 }
7250 
7251 /* set_raw_breakpoint is a low level routine for allocating and
7252    partially initializing a breakpoint of type BPTYPE.  The newly
7253    created breakpoint's address, section, source file name, and line
7254    number are provided by SAL.  The newly created and partially
7255    initialized breakpoint is added to the breakpoint chain and
7256    is also returned as the value of this function.
7257 
7258    It is expected that the caller will complete the initialization of
7259    the newly created breakpoint struct as well as output any status
7260    information regarding the creation of a new breakpoint.  In
7261    particular, set_raw_breakpoint does NOT set the breakpoint
7262    number!  Care should be taken to not allow an error to occur
7263    prior to completing the initialization of the breakpoint.  If this
7264    should happen, a bogus breakpoint will be left on the chain.  */
7265 
7266 struct breakpoint *
7267 set_raw_breakpoint (struct gdbarch *gdbarch,
7268 		    struct symtab_and_line sal, enum bptype bptype,
7269 		    const struct breakpoint_ops *ops)
7270 {
7271   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7272 
7273   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7274   return add_to_breakpoint_chain (std::move (b));
7275 }
7276 
7277 /* Call this routine when stepping and nexting to enable a breakpoint
7278    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7279    initiated the operation.  */
7280 
7281 void
7282 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7283 {
7284   int thread = tp->global_num;
7285 
7286   /* To avoid having to rescan all objfile symbols at every step,
7287      we maintain a list of continually-inserted but always disabled
7288      longjmp "master" breakpoints.  Here, we simply create momentary
7289      clones of those and enable them for the requested thread.  */
7290   for (breakpoint *b : all_breakpoints_safe ())
7291     if (b->pspace == current_program_space
7292 	&& (b->type == bp_longjmp_master
7293 	    || b->type == bp_exception_master))
7294       {
7295 	enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7296 	struct breakpoint *clone;
7297 
7298 	/* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7299 	   after their removal.  */
7300 	clone = momentary_breakpoint_from_master (b, type,
7301 						  &momentary_breakpoint_ops, 1);
7302 	clone->thread = thread;
7303       }
7304 
7305   tp->initiating_frame = frame;
7306 }
7307 
7308 /* Delete all longjmp breakpoints from THREAD.  */
7309 void
7310 delete_longjmp_breakpoint (int thread)
7311 {
7312   for (breakpoint *b : all_breakpoints_safe ())
7313     if (b->type == bp_longjmp || b->type == bp_exception)
7314       {
7315 	if (b->thread == thread)
7316 	  delete_breakpoint (b);
7317       }
7318 }
7319 
7320 void
7321 delete_longjmp_breakpoint_at_next_stop (int thread)
7322 {
7323   for (breakpoint *b : all_breakpoints_safe ())
7324     if (b->type == bp_longjmp || b->type == bp_exception)
7325       {
7326 	if (b->thread == thread)
7327 	  b->disposition = disp_del_at_next_stop;
7328       }
7329 }
7330 
7331 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7332    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7333    pointer to any of them.  Return NULL if this system cannot place longjmp
7334    breakpoints.  */
7335 
7336 struct breakpoint *
7337 set_longjmp_breakpoint_for_call_dummy (void)
7338 {
7339   breakpoint *retval = nullptr;
7340 
7341   for (breakpoint *b : all_breakpoints ())
7342     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7343       {
7344 	struct breakpoint *new_b;
7345 
7346 	new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7347 						  &momentary_breakpoint_ops,
7348 						  1);
7349 	new_b->thread = inferior_thread ()->global_num;
7350 
7351 	/* Link NEW_B into the chain of RETVAL breakpoints.  */
7352 
7353 	gdb_assert (new_b->related_breakpoint == new_b);
7354 	if (retval == NULL)
7355 	  retval = new_b;
7356 	new_b->related_breakpoint = retval;
7357 	while (retval->related_breakpoint != new_b->related_breakpoint)
7358 	  retval = retval->related_breakpoint;
7359 	retval->related_breakpoint = new_b;
7360       }
7361 
7362   return retval;
7363 }
7364 
7365 /* Verify all existing dummy frames and their associated breakpoints for
7366    TP.  Remove those which can no longer be found in the current frame
7367    stack.
7368 
7369    If the unwind fails then there is not sufficient information to discard
7370    dummy frames.  In this case, elide the clean up and the dummy frames will
7371    be cleaned up next time this function is called from a location where
7372    unwinding is possible.  */
7373 
7374 void
7375 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7376 {
7377   struct breakpoint *b, *b_tmp;
7378 
7379   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7380     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7381       {
7382 	struct breakpoint *dummy_b = b->related_breakpoint;
7383 
7384 	/* Find the bp_call_dummy breakpoint in the list of breakpoints
7385 	   chained off b->related_breakpoint.  */
7386 	while (dummy_b != b && dummy_b->type != bp_call_dummy)
7387 	  dummy_b = dummy_b->related_breakpoint;
7388 
7389 	/* If there was no bp_call_dummy breakpoint then there's nothing
7390 	   more to do.  Or, if the dummy frame associated with the
7391 	   bp_call_dummy is still on the stack then we need to leave this
7392 	   bp_call_dummy in place.  */
7393 	if (dummy_b->type != bp_call_dummy
7394 	    || frame_find_by_id (dummy_b->frame_id) != NULL)
7395 	  continue;
7396 
7397 	/* We didn't find the dummy frame on the stack, this could be
7398 	   because we have longjmp'd to a stack frame that is previous to
7399 	   the dummy frame, or it could be because the stack unwind is
7400 	   broken at some point between the longjmp frame and the dummy
7401 	   frame.
7402 
7403 	   Next we figure out why the stack unwind stopped.  If it looks
7404 	   like the unwind is complete then we assume the dummy frame has
7405 	   been jumped over, however, if the unwind stopped for an
7406 	   unexpected reason then we assume the stack unwind is currently
7407 	   broken, and that we will (eventually) return to the dummy
7408 	   frame.
7409 
7410 	   It might be tempting to consider using frame_id_inner here, but
7411 	   that is not safe.   There is no guarantee that the stack frames
7412 	   we are looking at here are even on the same stack as the
7413 	   original dummy frame, hence frame_id_inner can't be used.  See
7414 	   the comments on frame_id_inner for more details.  */
7415 	bool unwind_finished_unexpectedly = false;
7416 	for (struct frame_info *fi = get_current_frame (); fi != nullptr; )
7417 	  {
7418 	    struct frame_info *prev = get_prev_frame (fi);
7419 	    if (prev == nullptr)
7420 	      {
7421 		/* FI is the last stack frame.  Why did this frame not
7422 		   unwind further?  */
7423 		auto stop_reason = get_frame_unwind_stop_reason (fi);
7424 		if (stop_reason != UNWIND_NO_REASON
7425 		    && stop_reason != UNWIND_OUTERMOST)
7426 		  unwind_finished_unexpectedly = true;
7427 	      }
7428 	    fi = prev;
7429 	  }
7430 	if (unwind_finished_unexpectedly)
7431 	  continue;
7432 
7433 	dummy_frame_discard (dummy_b->frame_id, tp);
7434 
7435 	while (b->related_breakpoint != b)
7436 	  {
7437 	    if (b_tmp == b->related_breakpoint)
7438 	      b_tmp = b->related_breakpoint->next;
7439 	    delete_breakpoint (b->related_breakpoint);
7440 	  }
7441 	delete_breakpoint (b);
7442       }
7443 }
7444 
7445 void
7446 enable_overlay_breakpoints (void)
7447 {
7448   for (breakpoint *b : all_breakpoints ())
7449     if (b->type == bp_overlay_event)
7450       {
7451 	b->enable_state = bp_enabled;
7452 	update_global_location_list (UGLL_MAY_INSERT);
7453 	overlay_events_enabled = 1;
7454       }
7455 }
7456 
7457 void
7458 disable_overlay_breakpoints (void)
7459 {
7460   for (breakpoint *b : all_breakpoints ())
7461     if (b->type == bp_overlay_event)
7462       {
7463 	b->enable_state = bp_disabled;
7464 	update_global_location_list (UGLL_DONT_INSERT);
7465 	overlay_events_enabled = 0;
7466       }
7467 }
7468 
7469 /* Set an active std::terminate breakpoint for each std::terminate
7470    master breakpoint.  */
7471 void
7472 set_std_terminate_breakpoint (void)
7473 {
7474   for (breakpoint *b : all_breakpoints_safe ())
7475     if (b->pspace == current_program_space
7476 	&& b->type == bp_std_terminate_master)
7477       {
7478 	momentary_breakpoint_from_master (b, bp_std_terminate,
7479 					  &momentary_breakpoint_ops, 1);
7480       }
7481 }
7482 
7483 /* Delete all the std::terminate breakpoints.  */
7484 void
7485 delete_std_terminate_breakpoint (void)
7486 {
7487   for (breakpoint *b : all_breakpoints_safe ())
7488     if (b->type == bp_std_terminate)
7489       delete_breakpoint (b);
7490 }
7491 
7492 struct breakpoint *
7493 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7494 {
7495   struct breakpoint *b;
7496 
7497   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7498 				  &internal_breakpoint_ops);
7499 
7500   b->enable_state = bp_enabled;
7501   /* location has to be used or breakpoint_re_set will delete me.  */
7502   b->location = new_address_location (b->loc->address, NULL, 0);
7503 
7504   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7505 
7506   return b;
7507 }
7508 
7509 struct lang_and_radix
7510   {
7511     enum language lang;
7512     int radix;
7513   };
7514 
7515 /* Create a breakpoint for JIT code registration and unregistration.  */
7516 
7517 struct breakpoint *
7518 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7519 {
7520   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7521 				     &internal_breakpoint_ops);
7522 }
7523 
7524 /* Remove JIT code registration and unregistration breakpoint(s).  */
7525 
7526 void
7527 remove_jit_event_breakpoints (void)
7528 {
7529   for (breakpoint *b : all_breakpoints_safe ())
7530     if (b->type == bp_jit_event
7531 	&& b->loc->pspace == current_program_space)
7532       delete_breakpoint (b);
7533 }
7534 
7535 void
7536 remove_solib_event_breakpoints (void)
7537 {
7538   for (breakpoint *b : all_breakpoints_safe ())
7539     if (b->type == bp_shlib_event
7540 	&& b->loc->pspace == current_program_space)
7541       delete_breakpoint (b);
7542 }
7543 
7544 /* See breakpoint.h.  */
7545 
7546 void
7547 remove_solib_event_breakpoints_at_next_stop (void)
7548 {
7549   for (breakpoint *b : all_breakpoints_safe ())
7550     if (b->type == bp_shlib_event
7551 	&& b->loc->pspace == current_program_space)
7552       b->disposition = disp_del_at_next_stop;
7553 }
7554 
7555 /* Helper for create_solib_event_breakpoint /
7556    create_and_insert_solib_event_breakpoint.  Allows specifying which
7557    INSERT_MODE to pass through to update_global_location_list.  */
7558 
7559 static struct breakpoint *
7560 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7561 				 enum ugll_insert_mode insert_mode)
7562 {
7563   struct breakpoint *b;
7564 
7565   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7566 				  &internal_breakpoint_ops);
7567   update_global_location_list_nothrow (insert_mode);
7568   return b;
7569 }
7570 
7571 struct breakpoint *
7572 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7573 {
7574   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7575 }
7576 
7577 /* See breakpoint.h.  */
7578 
7579 struct breakpoint *
7580 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7581 {
7582   struct breakpoint *b;
7583 
7584   /* Explicitly tell update_global_location_list to insert
7585      locations.  */
7586   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7587   if (!b->loc->inserted)
7588     {
7589       delete_breakpoint (b);
7590       return NULL;
7591     }
7592   return b;
7593 }
7594 
7595 /* Disable any breakpoints that are on code in shared libraries.  Only
7596    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7597 
7598 void
7599 disable_breakpoints_in_shlibs (void)
7600 {
7601   for (bp_location *loc : all_bp_locations ())
7602     {
7603       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7604       struct breakpoint *b = loc->owner;
7605 
7606       /* We apply the check to all breakpoints, including disabled for
7607 	 those with loc->duplicate set.  This is so that when breakpoint
7608 	 becomes enabled, or the duplicate is removed, gdb will try to
7609 	 insert all breakpoints.  If we don't set shlib_disabled here,
7610 	 we'll try to insert those breakpoints and fail.  */
7611       if (((b->type == bp_breakpoint)
7612 	   || (b->type == bp_jit_event)
7613 	   || (b->type == bp_hardware_breakpoint)
7614 	   || (is_tracepoint (b)))
7615 	  && loc->pspace == current_program_space
7616 	  && !loc->shlib_disabled
7617 	  && solib_name_from_address (loc->pspace, loc->address)
7618 	  )
7619 	{
7620 	  loc->shlib_disabled = 1;
7621 	}
7622     }
7623 }
7624 
7625 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7626    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7627    disabled ones can just stay disabled.  */
7628 
7629 static void
7630 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7631 {
7632   int disabled_shlib_breaks = 0;
7633 
7634   for (bp_location *loc : all_bp_locations ())
7635     {
7636       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7637       struct breakpoint *b = loc->owner;
7638 
7639       if (solib->pspace == loc->pspace
7640 	  && !loc->shlib_disabled
7641 	  && (((b->type == bp_breakpoint
7642 		|| b->type == bp_jit_event
7643 		|| b->type == bp_hardware_breakpoint)
7644 	       && (loc->loc_type == bp_loc_hardware_breakpoint
7645 		   || loc->loc_type == bp_loc_software_breakpoint))
7646 	      || is_tracepoint (b))
7647 	  && solib_contains_address_p (solib, loc->address))
7648 	{
7649 	  loc->shlib_disabled = 1;
7650 	  /* At this point, we cannot rely on remove_breakpoint
7651 	     succeeding so we must mark the breakpoint as not inserted
7652 	     to prevent future errors occurring in remove_breakpoints.  */
7653 	  loc->inserted = 0;
7654 
7655 	  /* This may cause duplicate notifications for the same breakpoint.  */
7656 	  gdb::observers::breakpoint_modified.notify (b);
7657 
7658 	  if (!disabled_shlib_breaks)
7659 	    {
7660 	      target_terminal::ours_for_output ();
7661 	      warning (_("Temporarily disabling breakpoints "
7662 			 "for unloaded shared library \"%s\""),
7663 		       solib->so_name);
7664 	    }
7665 	  disabled_shlib_breaks = 1;
7666 	}
7667     }
7668 }
7669 
7670 /* Disable any breakpoints and tracepoints in OBJFILE upon
7671    notification of free_objfile.  Only apply to enabled breakpoints,
7672    disabled ones can just stay disabled.  */
7673 
7674 static void
7675 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7676 {
7677   if (objfile == NULL)
7678     return;
7679 
7680   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7681      managed by the user with add-symbol-file/remove-symbol-file.
7682      Similarly to how breakpoints in shared libraries are handled in
7683      response to "nosharedlibrary", mark breakpoints in such modules
7684      shlib_disabled so they end up uninserted on the next global
7685      location list update.  Shared libraries not loaded by the user
7686      aren't handled here -- they're already handled in
7687      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7688      solib_unloaded observer.  We skip objfiles that are not
7689      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7690      main objfile).  */
7691   if ((objfile->flags & OBJF_SHARED) == 0
7692       || (objfile->flags & OBJF_USERLOADED) == 0)
7693     return;
7694 
7695   for (breakpoint *b : all_breakpoints ())
7696     {
7697       int bp_modified = 0;
7698 
7699       if (!is_breakpoint (b) && !is_tracepoint (b))
7700 	continue;
7701 
7702       for (bp_location *loc : b->locations ())
7703 	{
7704 	  CORE_ADDR loc_addr = loc->address;
7705 
7706 	  if (loc->loc_type != bp_loc_hardware_breakpoint
7707 	      && loc->loc_type != bp_loc_software_breakpoint)
7708 	    continue;
7709 
7710 	  if (loc->shlib_disabled != 0)
7711 	    continue;
7712 
7713 	  if (objfile->pspace != loc->pspace)
7714 	    continue;
7715 
7716 	  if (loc->loc_type != bp_loc_hardware_breakpoint
7717 	      && loc->loc_type != bp_loc_software_breakpoint)
7718 	    continue;
7719 
7720 	  if (is_addr_in_objfile (loc_addr, objfile))
7721 	    {
7722 	      loc->shlib_disabled = 1;
7723 	      /* At this point, we don't know whether the object was
7724 		 unmapped from the inferior or not, so leave the
7725 		 inserted flag alone.  We'll handle failure to
7726 		 uninsert quietly, in case the object was indeed
7727 		 unmapped.  */
7728 
7729 	      mark_breakpoint_location_modified (loc);
7730 
7731 	      bp_modified = 1;
7732 	    }
7733 	}
7734 
7735       if (bp_modified)
7736 	gdb::observers::breakpoint_modified.notify (b);
7737     }
7738 }
7739 
7740 /* FORK & VFORK catchpoints.  */
7741 
7742 /* An instance of this type is used to represent a fork or vfork
7743    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7744    to CATCH_FORK_BREAKPOINT_OPS.  */
7745 
7746 struct fork_catchpoint : public breakpoint
7747 {
7748   /* Process id of a child process whose forking triggered this
7749      catchpoint.  This field is only valid immediately after this
7750      catchpoint has triggered.  */
7751   ptid_t forked_inferior_pid;
7752 };
7753 
7754 /* Implement the "insert" breakpoint_ops method for fork
7755    catchpoints.  */
7756 
7757 static int
7758 insert_catch_fork (struct bp_location *bl)
7759 {
7760   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7761 }
7762 
7763 /* Implement the "remove" breakpoint_ops method for fork
7764    catchpoints.  */
7765 
7766 static int
7767 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7768 {
7769   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7770 }
7771 
7772 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7773    catchpoints.  */
7774 
7775 static int
7776 breakpoint_hit_catch_fork (const struct bp_location *bl,
7777 			   const address_space *aspace, CORE_ADDR bp_addr,
7778 			   const struct target_waitstatus *ws)
7779 {
7780   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7781 
7782   if (ws->kind != TARGET_WAITKIND_FORKED)
7783     return 0;
7784 
7785   c->forked_inferior_pid = ws->value.related_pid;
7786   return 1;
7787 }
7788 
7789 /* Implement the "print_it" breakpoint_ops method for fork
7790    catchpoints.  */
7791 
7792 static enum print_stop_action
7793 print_it_catch_fork (bpstat bs)
7794 {
7795   struct ui_out *uiout = current_uiout;
7796   struct breakpoint *b = bs->breakpoint_at;
7797   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7798 
7799   annotate_catchpoint (b->number);
7800   maybe_print_thread_hit_breakpoint (uiout);
7801   if (b->disposition == disp_del)
7802     uiout->text ("Temporary catchpoint ");
7803   else
7804     uiout->text ("Catchpoint ");
7805   if (uiout->is_mi_like_p ())
7806     {
7807       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7808       uiout->field_string ("disp", bpdisp_text (b->disposition));
7809     }
7810   uiout->field_signed ("bkptno", b->number);
7811   uiout->text (" (forked process ");
7812   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7813   uiout->text ("), ");
7814   return PRINT_SRC_AND_LOC;
7815 }
7816 
7817 /* Implement the "print_one" breakpoint_ops method for fork
7818    catchpoints.  */
7819 
7820 static void
7821 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7822 {
7823   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7824   struct value_print_options opts;
7825   struct ui_out *uiout = current_uiout;
7826 
7827   get_user_print_options (&opts);
7828 
7829   /* Field 4, the address, is omitted (which makes the columns not
7830      line up too nicely with the headers, but the effect is relatively
7831      readable).  */
7832   if (opts.addressprint)
7833     uiout->field_skip ("addr");
7834   annotate_field (5);
7835   uiout->text ("fork");
7836   if (c->forked_inferior_pid != null_ptid)
7837     {
7838       uiout->text (", process ");
7839       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7840       uiout->spaces (1);
7841     }
7842 
7843   if (uiout->is_mi_like_p ())
7844     uiout->field_string ("catch-type", "fork");
7845 }
7846 
7847 /* Implement the "print_mention" breakpoint_ops method for fork
7848    catchpoints.  */
7849 
7850 static void
7851 print_mention_catch_fork (struct breakpoint *b)
7852 {
7853   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7854 }
7855 
7856 /* Implement the "print_recreate" breakpoint_ops method for fork
7857    catchpoints.  */
7858 
7859 static void
7860 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7861 {
7862   fprintf_unfiltered (fp, "catch fork");
7863   print_recreate_thread (b, fp);
7864 }
7865 
7866 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7867 
7868 static struct breakpoint_ops catch_fork_breakpoint_ops;
7869 
7870 /* Implement the "insert" breakpoint_ops method for vfork
7871    catchpoints.  */
7872 
7873 static int
7874 insert_catch_vfork (struct bp_location *bl)
7875 {
7876   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7877 }
7878 
7879 /* Implement the "remove" breakpoint_ops method for vfork
7880    catchpoints.  */
7881 
7882 static int
7883 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7884 {
7885   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7886 }
7887 
7888 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7889    catchpoints.  */
7890 
7891 static int
7892 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7893 			    const address_space *aspace, CORE_ADDR bp_addr,
7894 			    const struct target_waitstatus *ws)
7895 {
7896   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7897 
7898   if (ws->kind != TARGET_WAITKIND_VFORKED)
7899     return 0;
7900 
7901   c->forked_inferior_pid = ws->value.related_pid;
7902   return 1;
7903 }
7904 
7905 /* Implement the "print_it" breakpoint_ops method for vfork
7906    catchpoints.  */
7907 
7908 static enum print_stop_action
7909 print_it_catch_vfork (bpstat bs)
7910 {
7911   struct ui_out *uiout = current_uiout;
7912   struct breakpoint *b = bs->breakpoint_at;
7913   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7914 
7915   annotate_catchpoint (b->number);
7916   maybe_print_thread_hit_breakpoint (uiout);
7917   if (b->disposition == disp_del)
7918     uiout->text ("Temporary catchpoint ");
7919   else
7920     uiout->text ("Catchpoint ");
7921   if (uiout->is_mi_like_p ())
7922     {
7923       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7924       uiout->field_string ("disp", bpdisp_text (b->disposition));
7925     }
7926   uiout->field_signed ("bkptno", b->number);
7927   uiout->text (" (vforked process ");
7928   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7929   uiout->text ("), ");
7930   return PRINT_SRC_AND_LOC;
7931 }
7932 
7933 /* Implement the "print_one" breakpoint_ops method for vfork
7934    catchpoints.  */
7935 
7936 static void
7937 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7938 {
7939   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7940   struct value_print_options opts;
7941   struct ui_out *uiout = current_uiout;
7942 
7943   get_user_print_options (&opts);
7944   /* Field 4, the address, is omitted (which makes the columns not
7945      line up too nicely with the headers, but the effect is relatively
7946      readable).  */
7947   if (opts.addressprint)
7948     uiout->field_skip ("addr");
7949   annotate_field (5);
7950   uiout->text ("vfork");
7951   if (c->forked_inferior_pid != null_ptid)
7952     {
7953       uiout->text (", process ");
7954       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7955       uiout->spaces (1);
7956     }
7957 
7958   if (uiout->is_mi_like_p ())
7959     uiout->field_string ("catch-type", "vfork");
7960 }
7961 
7962 /* Implement the "print_mention" breakpoint_ops method for vfork
7963    catchpoints.  */
7964 
7965 static void
7966 print_mention_catch_vfork (struct breakpoint *b)
7967 {
7968   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7969 }
7970 
7971 /* Implement the "print_recreate" breakpoint_ops method for vfork
7972    catchpoints.  */
7973 
7974 static void
7975 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7976 {
7977   fprintf_unfiltered (fp, "catch vfork");
7978   print_recreate_thread (b, fp);
7979 }
7980 
7981 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7982 
7983 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7984 
7985 /* An instance of this type is used to represent an solib catchpoint.
7986    A breakpoint is really of this type iff its ops pointer points to
7987    CATCH_SOLIB_BREAKPOINT_OPS.  */
7988 
7989 struct solib_catchpoint : public breakpoint
7990 {
7991   ~solib_catchpoint () override;
7992 
7993   /* True for "catch load", false for "catch unload".  */
7994   bool is_load;
7995 
7996   /* Regular expression to match, if any.  COMPILED is only valid when
7997      REGEX is non-NULL.  */
7998   char *regex;
7999   std::unique_ptr<compiled_regex> compiled;
8000 };
8001 
8002 solib_catchpoint::~solib_catchpoint ()
8003 {
8004   xfree (this->regex);
8005 }
8006 
8007 static int
8008 insert_catch_solib (struct bp_location *ignore)
8009 {
8010   return 0;
8011 }
8012 
8013 static int
8014 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
8015 {
8016   return 0;
8017 }
8018 
8019 static int
8020 breakpoint_hit_catch_solib (const struct bp_location *bl,
8021 			    const address_space *aspace,
8022 			    CORE_ADDR bp_addr,
8023 			    const struct target_waitstatus *ws)
8024 {
8025   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8026 
8027   if (ws->kind == TARGET_WAITKIND_LOADED)
8028     return 1;
8029 
8030   for (breakpoint *other : all_breakpoints ())
8031     {
8032       if (other == bl->owner)
8033 	continue;
8034 
8035       if (other->type != bp_shlib_event)
8036 	continue;
8037 
8038       if (self->pspace != NULL && other->pspace != self->pspace)
8039 	continue;
8040 
8041       for (bp_location *other_bl : other->locations ())
8042 	{
8043 	  if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8044 	    return 1;
8045 	}
8046     }
8047 
8048   return 0;
8049 }
8050 
8051 static void
8052 check_status_catch_solib (struct bpstats *bs)
8053 {
8054   struct solib_catchpoint *self
8055     = (struct solib_catchpoint *) bs->breakpoint_at;
8056 
8057   if (self->is_load)
8058     {
8059       for (so_list *iter : current_program_space->added_solibs)
8060 	{
8061 	  if (!self->regex
8062 	      || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8063 	    return;
8064 	}
8065     }
8066   else
8067     {
8068       for (const std::string &iter : current_program_space->deleted_solibs)
8069 	{
8070 	  if (!self->regex
8071 	      || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8072 	    return;
8073 	}
8074     }
8075 
8076   bs->stop = 0;
8077   bs->print_it = print_it_noop;
8078 }
8079 
8080 static enum print_stop_action
8081 print_it_catch_solib (bpstat bs)
8082 {
8083   struct breakpoint *b = bs->breakpoint_at;
8084   struct ui_out *uiout = current_uiout;
8085 
8086   annotate_catchpoint (b->number);
8087   maybe_print_thread_hit_breakpoint (uiout);
8088   if (b->disposition == disp_del)
8089     uiout->text ("Temporary catchpoint ");
8090   else
8091     uiout->text ("Catchpoint ");
8092   uiout->field_signed ("bkptno", b->number);
8093   uiout->text ("\n");
8094   if (uiout->is_mi_like_p ())
8095     uiout->field_string ("disp", bpdisp_text (b->disposition));
8096   print_solib_event (1);
8097   return PRINT_SRC_AND_LOC;
8098 }
8099 
8100 static void
8101 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8102 {
8103   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8104   struct value_print_options opts;
8105   struct ui_out *uiout = current_uiout;
8106 
8107   get_user_print_options (&opts);
8108   /* Field 4, the address, is omitted (which makes the columns not
8109      line up too nicely with the headers, but the effect is relatively
8110      readable).  */
8111   if (opts.addressprint)
8112     {
8113       annotate_field (4);
8114       uiout->field_skip ("addr");
8115     }
8116 
8117   std::string msg;
8118   annotate_field (5);
8119   if (self->is_load)
8120     {
8121       if (self->regex)
8122 	msg = string_printf (_("load of library matching %s"), self->regex);
8123       else
8124 	msg = _("load of library");
8125     }
8126   else
8127     {
8128       if (self->regex)
8129 	msg = string_printf (_("unload of library matching %s"), self->regex);
8130       else
8131 	msg = _("unload of library");
8132     }
8133   uiout->field_string ("what", msg);
8134 
8135   if (uiout->is_mi_like_p ())
8136     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8137 }
8138 
8139 static void
8140 print_mention_catch_solib (struct breakpoint *b)
8141 {
8142   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8143 
8144   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8145 		   self->is_load ? "load" : "unload");
8146 }
8147 
8148 static void
8149 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8150 {
8151   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8152 
8153   fprintf_unfiltered (fp, "%s %s",
8154 		      b->disposition == disp_del ? "tcatch" : "catch",
8155 		      self->is_load ? "load" : "unload");
8156   if (self->regex)
8157     fprintf_unfiltered (fp, " %s", self->regex);
8158   fprintf_unfiltered (fp, "\n");
8159 }
8160 
8161 static struct breakpoint_ops catch_solib_breakpoint_ops;
8162 
8163 /* See breakpoint.h.  */
8164 
8165 void
8166 add_solib_catchpoint (const char *arg, bool is_load, bool is_temp, bool enabled)
8167 {
8168   struct gdbarch *gdbarch = get_current_arch ();
8169 
8170   if (!arg)
8171     arg = "";
8172   arg = skip_spaces (arg);
8173 
8174   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8175 
8176   if (*arg != '\0')
8177     {
8178       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8179 					     _("Invalid regexp")));
8180       c->regex = xstrdup (arg);
8181     }
8182 
8183   c->is_load = is_load;
8184   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8185 		   &catch_solib_breakpoint_ops);
8186 
8187   c->enable_state = enabled ? bp_enabled : bp_disabled;
8188 
8189   install_breakpoint (0, std::move (c), 1);
8190 }
8191 
8192 /* A helper function that does all the work for "catch load" and
8193    "catch unload".  */
8194 
8195 static void
8196 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8197 		      struct cmd_list_element *command)
8198 {
8199   const int enabled = 1;
8200   bool temp = command->context () == CATCH_TEMPORARY;
8201 
8202   add_solib_catchpoint (arg, is_load, temp, enabled);
8203 }
8204 
8205 static void
8206 catch_load_command_1 (const char *arg, int from_tty,
8207 		      struct cmd_list_element *command)
8208 {
8209   catch_load_or_unload (arg, from_tty, 1, command);
8210 }
8211 
8212 static void
8213 catch_unload_command_1 (const char *arg, int from_tty,
8214 			struct cmd_list_element *command)
8215 {
8216   catch_load_or_unload (arg, from_tty, 0, command);
8217 }
8218 
8219 /* See breakpoint.h.  */
8220 
8221 void
8222 init_catchpoint (struct breakpoint *b,
8223 		 struct gdbarch *gdbarch, bool temp,
8224 		 const char *cond_string,
8225 		 const struct breakpoint_ops *ops)
8226 {
8227   symtab_and_line sal;
8228   sal.pspace = current_program_space;
8229 
8230   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8231 
8232   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8233   b->disposition = temp ? disp_del : disp_donttouch;
8234 }
8235 
8236 void
8237 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8238 {
8239   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8240   set_breakpoint_number (internal, b);
8241   if (is_tracepoint (b))
8242     set_tracepoint_count (breakpoint_count);
8243   if (!internal)
8244     mention (b);
8245   gdb::observers::breakpoint_created.notify (b);
8246 
8247   if (update_gll)
8248     update_global_location_list (UGLL_MAY_INSERT);
8249 }
8250 
8251 static void
8252 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8253 				    bool temp, const char *cond_string,
8254 				    const struct breakpoint_ops *ops)
8255 {
8256   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8257 
8258   init_catchpoint (c.get (), gdbarch, temp, cond_string, ops);
8259 
8260   c->forked_inferior_pid = null_ptid;
8261 
8262   install_breakpoint (0, std::move (c), 1);
8263 }
8264 
8265 /* Exec catchpoints.  */
8266 
8267 /* An instance of this type is used to represent an exec catchpoint.
8268    A breakpoint is really of this type iff its ops pointer points to
8269    CATCH_EXEC_BREAKPOINT_OPS.  */
8270 
8271 struct exec_catchpoint : public breakpoint
8272 {
8273   ~exec_catchpoint () override;
8274 
8275   /* Filename of a program whose exec triggered this catchpoint.
8276      This field is only valid immediately after this catchpoint has
8277      triggered.  */
8278   char *exec_pathname;
8279 };
8280 
8281 /* Exec catchpoint destructor.  */
8282 
8283 exec_catchpoint::~exec_catchpoint ()
8284 {
8285   xfree (this->exec_pathname);
8286 }
8287 
8288 static int
8289 insert_catch_exec (struct bp_location *bl)
8290 {
8291   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8292 }
8293 
8294 static int
8295 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8296 {
8297   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8298 }
8299 
8300 static int
8301 breakpoint_hit_catch_exec (const struct bp_location *bl,
8302 			   const address_space *aspace, CORE_ADDR bp_addr,
8303 			   const struct target_waitstatus *ws)
8304 {
8305   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8306 
8307   if (ws->kind != TARGET_WAITKIND_EXECD)
8308     return 0;
8309 
8310   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8311   return 1;
8312 }
8313 
8314 static enum print_stop_action
8315 print_it_catch_exec (bpstat bs)
8316 {
8317   struct ui_out *uiout = current_uiout;
8318   struct breakpoint *b = bs->breakpoint_at;
8319   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8320 
8321   annotate_catchpoint (b->number);
8322   maybe_print_thread_hit_breakpoint (uiout);
8323   if (b->disposition == disp_del)
8324     uiout->text ("Temporary catchpoint ");
8325   else
8326     uiout->text ("Catchpoint ");
8327   if (uiout->is_mi_like_p ())
8328     {
8329       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8330       uiout->field_string ("disp", bpdisp_text (b->disposition));
8331     }
8332   uiout->field_signed ("bkptno", b->number);
8333   uiout->text (" (exec'd ");
8334   uiout->field_string ("new-exec", c->exec_pathname);
8335   uiout->text ("), ");
8336 
8337   return PRINT_SRC_AND_LOC;
8338 }
8339 
8340 static void
8341 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8342 {
8343   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8344   struct value_print_options opts;
8345   struct ui_out *uiout = current_uiout;
8346 
8347   get_user_print_options (&opts);
8348 
8349   /* Field 4, the address, is omitted (which makes the columns
8350      not line up too nicely with the headers, but the effect
8351      is relatively readable).  */
8352   if (opts.addressprint)
8353     uiout->field_skip ("addr");
8354   annotate_field (5);
8355   uiout->text ("exec");
8356   if (c->exec_pathname != NULL)
8357     {
8358       uiout->text (", program \"");
8359       uiout->field_string ("what", c->exec_pathname);
8360       uiout->text ("\" ");
8361     }
8362 
8363   if (uiout->is_mi_like_p ())
8364     uiout->field_string ("catch-type", "exec");
8365 }
8366 
8367 static void
8368 print_mention_catch_exec (struct breakpoint *b)
8369 {
8370   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8371 }
8372 
8373 /* Implement the "print_recreate" breakpoint_ops method for exec
8374    catchpoints.  */
8375 
8376 static void
8377 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8378 {
8379   fprintf_unfiltered (fp, "catch exec");
8380   print_recreate_thread (b, fp);
8381 }
8382 
8383 static struct breakpoint_ops catch_exec_breakpoint_ops;
8384 
8385 static int
8386 hw_breakpoint_used_count (void)
8387 {
8388   int i = 0;
8389 
8390   for (breakpoint *b : all_breakpoints ())
8391     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8392       for (bp_location *bl : b->locations ())
8393 	{
8394 	  /* Special types of hardware breakpoints may use more than
8395 	     one register.  */
8396 	  i += b->ops->resources_needed (bl);
8397 	}
8398 
8399   return i;
8400 }
8401 
8402 /* Returns the resources B would use if it were a hardware
8403    watchpoint.  */
8404 
8405 static int
8406 hw_watchpoint_use_count (struct breakpoint *b)
8407 {
8408   int i = 0;
8409 
8410   if (!breakpoint_enabled (b))
8411     return 0;
8412 
8413   for (bp_location *bl : b->locations ())
8414     {
8415       /* Special types of hardware watchpoints may use more than
8416 	 one register.  */
8417       i += b->ops->resources_needed (bl);
8418     }
8419 
8420   return i;
8421 }
8422 
8423 /* Returns the sum the used resources of all hardware watchpoints of
8424    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8425    the sum of the used resources of all hardware watchpoints of other
8426    types _not_ TYPE.  */
8427 
8428 static int
8429 hw_watchpoint_used_count_others (struct breakpoint *except,
8430 				 enum bptype type, int *other_type_used)
8431 {
8432   int i = 0;
8433 
8434   *other_type_used = 0;
8435   for (breakpoint *b : all_breakpoints ())
8436     {
8437       if (b == except)
8438 	continue;
8439       if (!breakpoint_enabled (b))
8440 	continue;
8441 
8442       if (b->type == type)
8443 	i += hw_watchpoint_use_count (b);
8444       else if (is_hardware_watchpoint (b))
8445 	*other_type_used = 1;
8446     }
8447 
8448   return i;
8449 }
8450 
8451 void
8452 disable_watchpoints_before_interactive_call_start (void)
8453 {
8454   for (breakpoint *b : all_breakpoints ())
8455     if (is_watchpoint (b) && breakpoint_enabled (b))
8456       {
8457 	b->enable_state = bp_call_disabled;
8458 	update_global_location_list (UGLL_DONT_INSERT);
8459       }
8460 }
8461 
8462 void
8463 enable_watchpoints_after_interactive_call_stop (void)
8464 {
8465   for (breakpoint *b : all_breakpoints ())
8466     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8467       {
8468 	b->enable_state = bp_enabled;
8469 	update_global_location_list (UGLL_MAY_INSERT);
8470       }
8471 }
8472 
8473 void
8474 disable_breakpoints_before_startup (void)
8475 {
8476   current_program_space->executing_startup = 1;
8477   update_global_location_list (UGLL_DONT_INSERT);
8478 }
8479 
8480 void
8481 enable_breakpoints_after_startup (void)
8482 {
8483   current_program_space->executing_startup = 0;
8484   breakpoint_re_set ();
8485 }
8486 
8487 /* Create a new single-step breakpoint for thread THREAD, with no
8488    locations.  */
8489 
8490 static struct breakpoint *
8491 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8492 {
8493   std::unique_ptr<breakpoint> b (new breakpoint ());
8494 
8495   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8496 					&momentary_breakpoint_ops);
8497 
8498   b->disposition = disp_donttouch;
8499   b->frame_id = null_frame_id;
8500 
8501   b->thread = thread;
8502   gdb_assert (b->thread != 0);
8503 
8504   return add_to_breakpoint_chain (std::move (b));
8505 }
8506 
8507 /* Set a momentary breakpoint of type TYPE at address specified by
8508    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8509    frame.  */
8510 
8511 breakpoint_up
8512 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8513 			  struct frame_id frame_id, enum bptype type)
8514 {
8515   struct breakpoint *b;
8516 
8517   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8518      tail-called one.  */
8519   gdb_assert (!frame_id_artificial_p (frame_id));
8520 
8521   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8522   b->enable_state = bp_enabled;
8523   b->disposition = disp_donttouch;
8524   b->frame_id = frame_id;
8525 
8526   b->thread = inferior_thread ()->global_num;
8527 
8528   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8529 
8530   return breakpoint_up (b);
8531 }
8532 
8533 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8534    The new breakpoint will have type TYPE, use OPS as its
8535    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8536 
8537 static struct breakpoint *
8538 momentary_breakpoint_from_master (struct breakpoint *orig,
8539 				  enum bptype type,
8540 				  const struct breakpoint_ops *ops,
8541 				  int loc_enabled)
8542 {
8543   struct breakpoint *copy;
8544 
8545   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8546   copy->loc = allocate_bp_location (copy);
8547   set_breakpoint_location_function (copy->loc);
8548 
8549   copy->loc->gdbarch = orig->loc->gdbarch;
8550   copy->loc->requested_address = orig->loc->requested_address;
8551   copy->loc->address = orig->loc->address;
8552   copy->loc->section = orig->loc->section;
8553   copy->loc->pspace = orig->loc->pspace;
8554   copy->loc->probe = orig->loc->probe;
8555   copy->loc->line_number = orig->loc->line_number;
8556   copy->loc->symtab = orig->loc->symtab;
8557   copy->loc->enabled = loc_enabled;
8558   copy->frame_id = orig->frame_id;
8559   copy->thread = orig->thread;
8560   copy->pspace = orig->pspace;
8561 
8562   copy->enable_state = bp_enabled;
8563   copy->disposition = disp_donttouch;
8564   copy->number = internal_breakpoint_number--;
8565 
8566   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8567   return copy;
8568 }
8569 
8570 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8571    ORIG is NULL.  */
8572 
8573 struct breakpoint *
8574 clone_momentary_breakpoint (struct breakpoint *orig)
8575 {
8576   /* If there's nothing to clone, then return nothing.  */
8577   if (orig == NULL)
8578     return NULL;
8579 
8580   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8581 }
8582 
8583 breakpoint_up
8584 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8585 				enum bptype type)
8586 {
8587   struct symtab_and_line sal;
8588 
8589   sal = find_pc_line (pc, 0);
8590   sal.pc = pc;
8591   sal.section = find_pc_overlay (pc);
8592   sal.explicit_pc = 1;
8593 
8594   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8595 }
8596 
8597 
8598 /* Tell the user we have just set a breakpoint B.  */
8599 
8600 static void
8601 mention (struct breakpoint *b)
8602 {
8603   b->ops->print_mention (b);
8604   current_uiout->text ("\n");
8605 }
8606 
8607 
8608 static bool bp_loc_is_permanent (struct bp_location *loc);
8609 
8610 /* Handle "set breakpoint auto-hw on".
8611 
8612    If the explicitly specified breakpoint type is not hardware
8613    breakpoint, check the memory map to see whether the breakpoint
8614    address is in read-only memory.
8615 
8616    - location type is not hardware breakpoint, memory is read-only.
8617    We change the type of the location to hardware breakpoint.
8618 
8619    - location type is hardware breakpoint, memory is read-write.  This
8620    means we've previously made the location hardware one, but then the
8621    memory map changed, so we undo.
8622 */
8623 
8624 static void
8625 handle_automatic_hardware_breakpoints (bp_location *bl)
8626 {
8627   if (automatic_hardware_breakpoints
8628       && bl->owner->type != bp_hardware_breakpoint
8629       && (bl->loc_type == bp_loc_software_breakpoint
8630 	  || bl->loc_type == bp_loc_hardware_breakpoint))
8631     {
8632       /* When breakpoints are removed, remove_breakpoints will use
8633 	 location types we've just set here, the only possible problem
8634 	 is that memory map has changed during running program, but
8635 	 it's not going to work anyway with current gdb.  */
8636       mem_region *mr = lookup_mem_region (bl->address);
8637 
8638       if (mr != nullptr)
8639 	{
8640 	  enum bp_loc_type new_type;
8641 
8642 	  if (mr->attrib.mode != MEM_RW)
8643 	    new_type = bp_loc_hardware_breakpoint;
8644 	  else
8645 	    new_type = bp_loc_software_breakpoint;
8646 
8647 	  if (new_type != bl->loc_type)
8648 	    {
8649 	      static bool said = false;
8650 
8651 	      bl->loc_type = new_type;
8652 	      if (!said)
8653 		{
8654 		  fprintf_filtered (gdb_stdout,
8655 				    _("Note: automatically using "
8656 				      "hardware breakpoints for "
8657 				      "read-only addresses.\n"));
8658 		  said = true;
8659 		}
8660 	    }
8661 	}
8662     }
8663 }
8664 
8665 static struct bp_location *
8666 add_location_to_breakpoint (struct breakpoint *b,
8667 			    const struct symtab_and_line *sal)
8668 {
8669   struct bp_location *loc, **tmp;
8670   CORE_ADDR adjusted_address;
8671   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8672 
8673   if (loc_gdbarch == NULL)
8674     loc_gdbarch = b->gdbarch;
8675 
8676   /* Adjust the breakpoint's address prior to allocating a location.
8677      Once we call allocate_bp_location(), that mostly uninitialized
8678      location will be placed on the location chain.  Adjustment of the
8679      breakpoint may cause target_read_memory() to be called and we do
8680      not want its scan of the location chain to find a breakpoint and
8681      location that's only been partially initialized.  */
8682   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8683 						sal->pc, b->type);
8684 
8685   /* Sort the locations by their ADDRESS.  */
8686   loc = allocate_bp_location (b);
8687   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8688        tmp = &((*tmp)->next))
8689     ;
8690   loc->next = *tmp;
8691   *tmp = loc;
8692 
8693   loc->requested_address = sal->pc;
8694   loc->address = adjusted_address;
8695   loc->pspace = sal->pspace;
8696   loc->probe.prob = sal->prob;
8697   loc->probe.objfile = sal->objfile;
8698   gdb_assert (loc->pspace != NULL);
8699   loc->section = sal->section;
8700   loc->gdbarch = loc_gdbarch;
8701   loc->line_number = sal->line;
8702   loc->symtab = sal->symtab;
8703   loc->symbol = sal->symbol;
8704   loc->msymbol = sal->msymbol;
8705   loc->objfile = sal->objfile;
8706 
8707   set_breakpoint_location_function (loc);
8708 
8709   /* While by definition, permanent breakpoints are already present in the
8710      code, we don't mark the location as inserted.  Normally one would expect
8711      that GDB could rely on that breakpoint instruction to stop the program,
8712      thus removing the need to insert its own breakpoint, except that executing
8713      the breakpoint instruction can kill the target instead of reporting a
8714      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8715      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8716      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8717      breakpoint be inserted normally results in QEMU knowing about the GDB
8718      breakpoint, and thus trap before the breakpoint instruction is executed.
8719      (If GDB later needs to continue execution past the permanent breakpoint,
8720      it manually increments the PC, thus avoiding executing the breakpoint
8721      instruction.)  */
8722   if (bp_loc_is_permanent (loc))
8723     loc->permanent = 1;
8724 
8725   return loc;
8726 }
8727 
8728 
8729 /* Return true if LOC is pointing to a permanent breakpoint,
8730    return false otherwise.  */
8731 
8732 static bool
8733 bp_loc_is_permanent (struct bp_location *loc)
8734 {
8735   gdb_assert (loc != NULL);
8736 
8737   /* If we have a non-breakpoint-backed catchpoint or a software
8738      watchpoint, just return 0.  We should not attempt to read from
8739      the addresses the locations of these breakpoint types point to.
8740      gdbarch_program_breakpoint_here_p, below, will attempt to read
8741      memory.  */
8742   if (!bl_address_is_meaningful (loc))
8743     return false;
8744 
8745   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8746   switch_to_program_space_and_thread (loc->pspace);
8747   return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8748 }
8749 
8750 /* Build a command list for the dprintf corresponding to the current
8751    settings of the dprintf style options.  */
8752 
8753 static void
8754 update_dprintf_command_list (struct breakpoint *b)
8755 {
8756   char *dprintf_args = b->extra_string;
8757   char *printf_line = NULL;
8758 
8759   if (!dprintf_args)
8760     return;
8761 
8762   dprintf_args = skip_spaces (dprintf_args);
8763 
8764   /* Allow a comma, as it may have terminated a location, but don't
8765      insist on it.  */
8766   if (*dprintf_args == ',')
8767     ++dprintf_args;
8768   dprintf_args = skip_spaces (dprintf_args);
8769 
8770   if (*dprintf_args != '"')
8771     error (_("Bad format string, missing '\"'."));
8772 
8773   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8774     printf_line = xstrprintf ("printf %s", dprintf_args);
8775   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8776     {
8777       if (!dprintf_function)
8778 	error (_("No function supplied for dprintf call"));
8779 
8780       if (dprintf_channel && strlen (dprintf_channel) > 0)
8781 	printf_line = xstrprintf ("call (void) %s (%s,%s)",
8782 				  dprintf_function,
8783 				  dprintf_channel,
8784 				  dprintf_args);
8785       else
8786 	printf_line = xstrprintf ("call (void) %s (%s)",
8787 				  dprintf_function,
8788 				  dprintf_args);
8789     }
8790   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8791     {
8792       if (target_can_run_breakpoint_commands ())
8793 	printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8794       else
8795 	{
8796 	  warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8797 	  printf_line = xstrprintf ("printf %s", dprintf_args);
8798 	}
8799     }
8800   else
8801     internal_error (__FILE__, __LINE__,
8802 		    _("Invalid dprintf style."));
8803 
8804   gdb_assert (printf_line != NULL);
8805 
8806   /* Manufacture a printf sequence.  */
8807   struct command_line *printf_cmd_line
8808     = new struct command_line (simple_control, printf_line);
8809   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8810 						    command_lines_deleter ()));
8811 }
8812 
8813 /* Update all dprintf commands, making their command lists reflect
8814    current style settings.  */
8815 
8816 static void
8817 update_dprintf_commands (const char *args, int from_tty,
8818 			 struct cmd_list_element *c)
8819 {
8820   for (breakpoint *b : all_breakpoints ())
8821     if (b->type == bp_dprintf)
8822 	update_dprintf_command_list (b);
8823 }
8824 
8825 /* Create a breakpoint with SAL as location.  Use LOCATION
8826    as a description of the location, and COND_STRING
8827    as condition expression.  If LOCATION is NULL then create an
8828    "address location" from the address in the SAL.  */
8829 
8830 static void
8831 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8832 		     gdb::array_view<const symtab_and_line> sals,
8833 		     event_location_up &&location,
8834 		     gdb::unique_xmalloc_ptr<char> filter,
8835 		     gdb::unique_xmalloc_ptr<char> cond_string,
8836 		     gdb::unique_xmalloc_ptr<char> extra_string,
8837 		     enum bptype type, enum bpdisp disposition,
8838 		     int thread, int task, int ignore_count,
8839 		     const struct breakpoint_ops *ops, int from_tty,
8840 		     int enabled, int internal, unsigned flags,
8841 		     int display_canonical)
8842 {
8843   int i;
8844 
8845   if (type == bp_hardware_breakpoint)
8846     {
8847       int target_resources_ok;
8848 
8849       i = hw_breakpoint_used_count ();
8850       target_resources_ok =
8851 	target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8852 					    i + 1, 0);
8853       if (target_resources_ok == 0)
8854 	error (_("No hardware breakpoint support in the target."));
8855       else if (target_resources_ok < 0)
8856 	error (_("Hardware breakpoints used exceeds limit."));
8857     }
8858 
8859   gdb_assert (!sals.empty ());
8860 
8861   for (const auto &sal : sals)
8862     {
8863       struct bp_location *loc;
8864 
8865       if (from_tty)
8866 	{
8867 	  struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8868 	  if (!loc_gdbarch)
8869 	    loc_gdbarch = gdbarch;
8870 
8871 	  describe_other_breakpoints (loc_gdbarch,
8872 				      sal.pspace, sal.pc, sal.section, thread);
8873 	}
8874 
8875       if (&sal == &sals[0])
8876 	{
8877 	  init_raw_breakpoint (b, gdbarch, sal, type, ops);
8878 	  b->thread = thread;
8879 	  b->task = task;
8880 
8881 	  b->cond_string = cond_string.release ();
8882 	  b->extra_string = extra_string.release ();
8883 	  b->ignore_count = ignore_count;
8884 	  b->enable_state = enabled ? bp_enabled : bp_disabled;
8885 	  b->disposition = disposition;
8886 
8887 	  if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8888 	    b->loc->inserted = 1;
8889 
8890 	  if (type == bp_static_tracepoint)
8891 	    {
8892 	      struct tracepoint *t = (struct tracepoint *) b;
8893 	      struct static_tracepoint_marker marker;
8894 
8895 	      if (strace_marker_p (b))
8896 		{
8897 		  /* We already know the marker exists, otherwise, we
8898 		     wouldn't see a sal for it.  */
8899 		  const char *p
8900 		    = &event_location_to_string (b->location.get ())[3];
8901 		  const char *endp;
8902 
8903 		  p = skip_spaces (p);
8904 
8905 		  endp = skip_to_space (p);
8906 
8907 		  t->static_trace_marker_id.assign (p, endp - p);
8908 
8909 		  printf_filtered (_("Probed static tracepoint "
8910 				     "marker \"%s\"\n"),
8911 				   t->static_trace_marker_id.c_str ());
8912 		}
8913 	      else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8914 		{
8915 		  t->static_trace_marker_id = std::move (marker.str_id);
8916 
8917 		  printf_filtered (_("Probed static tracepoint "
8918 				     "marker \"%s\"\n"),
8919 				   t->static_trace_marker_id.c_str ());
8920 		}
8921 	      else
8922 		warning (_("Couldn't determine the static "
8923 			   "tracepoint marker to probe"));
8924 	    }
8925 
8926 	  loc = b->loc;
8927 	}
8928       else
8929 	{
8930 	  loc = add_location_to_breakpoint (b, &sal);
8931 	  if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8932 	    loc->inserted = 1;
8933 	}
8934 
8935       /* Do not set breakpoint locations conditions yet.  As locations
8936 	 are inserted, they get sorted based on their addresses.  Let
8937 	 the list stabilize to have reliable location numbers.  */
8938 
8939       /* Dynamic printf requires and uses additional arguments on the
8940 	 command line, otherwise it's an error.  */
8941       if (type == bp_dprintf)
8942 	{
8943 	  if (b->extra_string)
8944 	    update_dprintf_command_list (b);
8945 	  else
8946 	    error (_("Format string required"));
8947 	}
8948       else if (b->extra_string)
8949 	error (_("Garbage '%s' at end of command"), b->extra_string);
8950     }
8951 
8952 
8953   /* The order of the locations is now stable.  Set the location
8954      condition using the location's number.  */
8955   int loc_num = 1;
8956   for (bp_location *loc : b->locations ())
8957     {
8958       if (b->cond_string != nullptr)
8959 	set_breakpoint_location_condition (b->cond_string, loc, b->number,
8960 					   loc_num);
8961 
8962       ++loc_num;
8963     }
8964 
8965   b->display_canonical = display_canonical;
8966   if (location != NULL)
8967     b->location = std::move (location);
8968   else
8969     b->location = new_address_location (b->loc->address, NULL, 0);
8970   b->filter = std::move (filter);
8971 }
8972 
8973 static void
8974 create_breakpoint_sal (struct gdbarch *gdbarch,
8975 		       gdb::array_view<const symtab_and_line> sals,
8976 		       event_location_up &&location,
8977 		       gdb::unique_xmalloc_ptr<char> filter,
8978 		       gdb::unique_xmalloc_ptr<char> cond_string,
8979 		       gdb::unique_xmalloc_ptr<char> extra_string,
8980 		       enum bptype type, enum bpdisp disposition,
8981 		       int thread, int task, int ignore_count,
8982 		       const struct breakpoint_ops *ops, int from_tty,
8983 		       int enabled, int internal, unsigned flags,
8984 		       int display_canonical)
8985 {
8986   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8987 
8988   init_breakpoint_sal (b.get (), gdbarch,
8989 		       sals, std::move (location),
8990 		       std::move (filter),
8991 		       std::move (cond_string),
8992 		       std::move (extra_string),
8993 		       type, disposition,
8994 		       thread, task, ignore_count,
8995 		       ops, from_tty,
8996 		       enabled, internal, flags,
8997 		       display_canonical);
8998 
8999   install_breakpoint (internal, std::move (b), 0);
9000 }
9001 
9002 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9003    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9004    value.  COND_STRING, if not NULL, specified the condition to be
9005    used for all breakpoints.  Essentially the only case where
9006    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9007    function.  In that case, it's still not possible to specify
9008    separate conditions for different overloaded functions, so
9009    we take just a single condition string.
9010 
9011    NOTE: If the function succeeds, the caller is expected to cleanup
9012    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9013    array contents).  If the function fails (error() is called), the
9014    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9015    COND and SALS arrays and each of those arrays contents.  */
9016 
9017 static void
9018 create_breakpoints_sal (struct gdbarch *gdbarch,
9019 			struct linespec_result *canonical,
9020 			gdb::unique_xmalloc_ptr<char> cond_string,
9021 			gdb::unique_xmalloc_ptr<char> extra_string,
9022 			enum bptype type, enum bpdisp disposition,
9023 			int thread, int task, int ignore_count,
9024 			const struct breakpoint_ops *ops, int from_tty,
9025 			int enabled, int internal, unsigned flags)
9026 {
9027   if (canonical->pre_expanded)
9028     gdb_assert (canonical->lsals.size () == 1);
9029 
9030   for (const auto &lsal : canonical->lsals)
9031     {
9032       /* Note that 'location' can be NULL in the case of a plain
9033 	 'break', without arguments.  */
9034       event_location_up location
9035 	= (canonical->location != NULL
9036 	   ? copy_event_location (canonical->location.get ()) : NULL);
9037       gdb::unique_xmalloc_ptr<char> filter_string
9038 	(lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9039 
9040       create_breakpoint_sal (gdbarch, lsal.sals,
9041 			     std::move (location),
9042 			     std::move (filter_string),
9043 			     std::move (cond_string),
9044 			     std::move (extra_string),
9045 			     type, disposition,
9046 			     thread, task, ignore_count, ops,
9047 			     from_tty, enabled, internal, flags,
9048 			     canonical->special_display);
9049     }
9050 }
9051 
9052 /* Parse LOCATION which is assumed to be a SAL specification possibly
9053    followed by conditionals.  On return, SALS contains an array of SAL
9054    addresses found.  LOCATION points to the end of the SAL (for
9055    linespec locations).
9056 
9057    The array and the line spec strings are allocated on the heap, it is
9058    the caller's responsibility to free them.  */
9059 
9060 static void
9061 parse_breakpoint_sals (struct event_location *location,
9062 		       struct linespec_result *canonical)
9063 {
9064   struct symtab_and_line cursal;
9065 
9066   if (event_location_type (location) == LINESPEC_LOCATION)
9067     {
9068       const char *spec = get_linespec_location (location)->spec_string;
9069 
9070       if (spec == NULL)
9071 	{
9072 	  /* The last displayed codepoint, if it's valid, is our default
9073 	     breakpoint address.  */
9074 	  if (last_displayed_sal_is_valid ())
9075 	    {
9076 	      /* Set sal's pspace, pc, symtab, and line to the values
9077 		 corresponding to the last call to print_frame_info.
9078 		 Be sure to reinitialize LINE with NOTCURRENT == 0
9079 		 as the breakpoint line number is inappropriate otherwise.
9080 		 find_pc_line would adjust PC, re-set it back.  */
9081 	      symtab_and_line sal = get_last_displayed_sal ();
9082 	      CORE_ADDR pc = sal.pc;
9083 
9084 	      sal = find_pc_line (pc, 0);
9085 
9086 	      /* "break" without arguments is equivalent to "break *PC"
9087 		 where PC is the last displayed codepoint's address.  So
9088 		 make sure to set sal.explicit_pc to prevent GDB from
9089 		 trying to expand the list of sals to include all other
9090 		 instances with the same symtab and line.  */
9091 	      sal.pc = pc;
9092 	      sal.explicit_pc = 1;
9093 
9094 	      struct linespec_sals lsal;
9095 	      lsal.sals = {sal};
9096 	      lsal.canonical = NULL;
9097 
9098 	      canonical->lsals.push_back (std::move (lsal));
9099 	      return;
9100 	    }
9101 	  else
9102 	    error (_("No default breakpoint address now."));
9103 	}
9104     }
9105 
9106   /* Force almost all breakpoints to be in terms of the
9107      current_source_symtab (which is decode_line_1's default).
9108      This should produce the results we want almost all of the
9109      time while leaving default_breakpoint_* alone.
9110 
9111      ObjC: However, don't match an Objective-C method name which
9112      may have a '+' or '-' succeeded by a '['.  */
9113   cursal = get_current_source_symtab_and_line ();
9114   if (last_displayed_sal_is_valid ())
9115     {
9116       const char *spec = NULL;
9117 
9118       if (event_location_type (location) == LINESPEC_LOCATION)
9119 	spec = get_linespec_location (location)->spec_string;
9120 
9121       if (!cursal.symtab
9122 	  || (spec != NULL
9123 	      && strchr ("+-", spec[0]) != NULL
9124 	      && spec[1] != '['))
9125 	{
9126 	  decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9127 			    get_last_displayed_symtab (),
9128 			    get_last_displayed_line (),
9129 			    canonical, NULL, NULL);
9130 	  return;
9131 	}
9132     }
9133 
9134   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9135 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
9136 }
9137 
9138 
9139 /* Convert each SAL into a real PC.  Verify that the PC can be
9140    inserted as a breakpoint.  If it can't throw an error.  */
9141 
9142 static void
9143 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9144 {
9145   for (auto &sal : sals)
9146     resolve_sal_pc (&sal);
9147 }
9148 
9149 /* Fast tracepoints may have restrictions on valid locations.  For
9150    instance, a fast tracepoint using a jump instead of a trap will
9151    likely have to overwrite more bytes than a trap would, and so can
9152    only be placed where the instruction is longer than the jump, or a
9153    multi-instruction sequence does not have a jump into the middle of
9154    it, etc.  */
9155 
9156 static void
9157 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9158 			    gdb::array_view<const symtab_and_line> sals)
9159 {
9160   for (const auto &sal : sals)
9161     {
9162       struct gdbarch *sarch;
9163 
9164       sarch = get_sal_arch (sal);
9165       /* We fall back to GDBARCH if there is no architecture
9166 	 associated with SAL.  */
9167       if (sarch == NULL)
9168 	sarch = gdbarch;
9169       std::string msg;
9170       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9171 	error (_("May not have a fast tracepoint at %s%s"),
9172 	       paddress (sarch, sal.pc), msg.c_str ());
9173     }
9174 }
9175 
9176 /* Given TOK, a string specification of condition and thread, as
9177    accepted by the 'break' command, extract the condition
9178    string and thread number and set *COND_STRING and *THREAD.
9179    PC identifies the context at which the condition should be parsed.
9180    If no condition is found, *COND_STRING is set to NULL.
9181    If no thread is found, *THREAD is set to -1.  */
9182 
9183 static void
9184 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9185 			   char **cond_string, int *thread, int *task,
9186 			   char **rest)
9187 {
9188   *cond_string = NULL;
9189   *thread = -1;
9190   *task = 0;
9191   *rest = NULL;
9192   bool force = false;
9193 
9194   while (tok && *tok)
9195     {
9196       const char *end_tok;
9197       int toklen;
9198       const char *cond_start = NULL;
9199       const char *cond_end = NULL;
9200 
9201       tok = skip_spaces (tok);
9202 
9203       if ((*tok == '"' || *tok == ',') && rest)
9204 	{
9205 	  *rest = savestring (tok, strlen (tok));
9206 	  return;
9207 	}
9208 
9209       end_tok = skip_to_space (tok);
9210 
9211       toklen = end_tok - tok;
9212 
9213       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9214 	{
9215 	  tok = cond_start = end_tok + 1;
9216 	  try
9217 	    {
9218 	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9219 	    }
9220 	  catch (const gdb_exception_error &)
9221 	    {
9222 	      if (!force)
9223 		throw;
9224 	      else
9225 		tok = tok + strlen (tok);
9226 	    }
9227 	  cond_end = tok;
9228 	  *cond_string = savestring (cond_start, cond_end - cond_start);
9229 	}
9230       else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
9231 	{
9232 	  tok = tok + toklen;
9233 	  force = true;
9234 	}
9235       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9236 	{
9237 	  const char *tmptok;
9238 	  struct thread_info *thr;
9239 
9240 	  tok = end_tok + 1;
9241 	  thr = parse_thread_id (tok, &tmptok);
9242 	  if (tok == tmptok)
9243 	    error (_("Junk after thread keyword."));
9244 	  *thread = thr->global_num;
9245 	  tok = tmptok;
9246 	}
9247       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9248 	{
9249 	  char *tmptok;
9250 
9251 	  tok = end_tok + 1;
9252 	  *task = strtol (tok, &tmptok, 0);
9253 	  if (tok == tmptok)
9254 	    error (_("Junk after task keyword."));
9255 	  if (!valid_task_id (*task))
9256 	    error (_("Unknown task %d."), *task);
9257 	  tok = tmptok;
9258 	}
9259       else if (rest)
9260 	{
9261 	  *rest = savestring (tok, strlen (tok));
9262 	  return;
9263 	}
9264       else
9265 	error (_("Junk at end of arguments."));
9266     }
9267 }
9268 
9269 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
9270    succeeds.  The parsed values are written to COND_STRING, THREAD,
9271    TASK, and REST.  See the comment of 'find_condition_and_thread'
9272    for the description of these parameters and INPUT.  */
9273 
9274 static void
9275 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
9276 				    const char *input, char **cond_string,
9277 				    int *thread, int *task, char **rest)
9278 {
9279   int num_failures = 0;
9280   for (auto &sal : sals)
9281     {
9282       char *cond = nullptr;
9283       int thread_id = 0;
9284       int task_id = 0;
9285       char *remaining = nullptr;
9286 
9287       /* Here we want to parse 'arg' to separate condition from thread
9288 	 number.  But because parsing happens in a context and the
9289 	 contexts of sals might be different, try each until there is
9290 	 success.  Finding one successful parse is sufficient for our
9291 	 goal.  When setting the breakpoint we'll re-parse the
9292 	 condition in the context of each sal.  */
9293       try
9294 	{
9295 	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
9296 				     &task_id, &remaining);
9297 	  *cond_string = cond;
9298 	  *thread = thread_id;
9299 	  *task = task_id;
9300 	  *rest = remaining;
9301 	  break;
9302 	}
9303       catch (const gdb_exception_error &e)
9304 	{
9305 	  num_failures++;
9306 	  /* If no sal remains, do not continue.  */
9307 	  if (num_failures == sals.size ())
9308 	    throw;
9309 	}
9310     }
9311 }
9312 
9313 /* Decode a static tracepoint marker spec.  */
9314 
9315 static std::vector<symtab_and_line>
9316 decode_static_tracepoint_spec (const char **arg_p)
9317 {
9318   const char *p = &(*arg_p)[3];
9319   const char *endp;
9320 
9321   p = skip_spaces (p);
9322 
9323   endp = skip_to_space (p);
9324 
9325   std::string marker_str (p, endp - p);
9326 
9327   std::vector<static_tracepoint_marker> markers
9328     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9329   if (markers.empty ())
9330     error (_("No known static tracepoint marker named %s"),
9331 	   marker_str.c_str ());
9332 
9333   std::vector<symtab_and_line> sals;
9334   sals.reserve (markers.size ());
9335 
9336   for (const static_tracepoint_marker &marker : markers)
9337     {
9338       symtab_and_line sal = find_pc_line (marker.address, 0);
9339       sal.pc = marker.address;
9340       sals.push_back (sal);
9341    }
9342 
9343   *arg_p = endp;
9344   return sals;
9345 }
9346 
9347 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
9348    according to IS_TRACEPOINT.  */
9349 
9350 static const struct breakpoint_ops *
9351 breakpoint_ops_for_event_location_type (enum event_location_type location_type,
9352 					bool is_tracepoint)
9353 {
9354   if (is_tracepoint)
9355     {
9356       if (location_type == PROBE_LOCATION)
9357 	return &tracepoint_probe_breakpoint_ops;
9358       else
9359 	return &tracepoint_breakpoint_ops;
9360     }
9361   else
9362     {
9363       if (location_type == PROBE_LOCATION)
9364 	return &bkpt_probe_breakpoint_ops;
9365       else
9366 	return &bkpt_breakpoint_ops;
9367     }
9368 }
9369 
9370 /* See breakpoint.h.  */
9371 
9372 const struct breakpoint_ops *
9373 breakpoint_ops_for_event_location (const struct event_location *location,
9374 				   bool is_tracepoint)
9375 {
9376   if (location != nullptr)
9377     return breakpoint_ops_for_event_location_type
9378       (event_location_type (location), is_tracepoint);
9379   return is_tracepoint ? &tracepoint_breakpoint_ops : &bkpt_breakpoint_ops;
9380 }
9381 
9382 /* See breakpoint.h.  */
9383 
9384 int
9385 create_breakpoint (struct gdbarch *gdbarch,
9386 		   struct event_location *location,
9387 		   const char *cond_string,
9388 		   int thread, const char *extra_string,
9389 		   bool force_condition, int parse_extra,
9390 		   int tempflag, enum bptype type_wanted,
9391 		   int ignore_count,
9392 		   enum auto_boolean pending_break_support,
9393 		   const struct breakpoint_ops *ops,
9394 		   int from_tty, int enabled, int internal,
9395 		   unsigned flags)
9396 {
9397   struct linespec_result canonical;
9398   int pending = 0;
9399   int task = 0;
9400   int prev_bkpt_count = breakpoint_count;
9401 
9402   gdb_assert (ops != NULL);
9403 
9404   /* If extra_string isn't useful, set it to NULL.  */
9405   if (extra_string != NULL && *extra_string == '\0')
9406     extra_string = NULL;
9407 
9408   try
9409     {
9410       ops->create_sals_from_location (location, &canonical, type_wanted);
9411     }
9412   catch (const gdb_exception_error &e)
9413     {
9414       /* If caller is interested in rc value from parse, set
9415 	 value.  */
9416       if (e.error == NOT_FOUND_ERROR)
9417 	{
9418 	  /* If pending breakpoint support is turned off, throw
9419 	     error.  */
9420 
9421 	  if (pending_break_support == AUTO_BOOLEAN_FALSE)
9422 	    throw;
9423 
9424 	  exception_print (gdb_stderr, e);
9425 
9426 	  /* If pending breakpoint support is auto query and the user
9427 	     selects no, then simply return the error code.  */
9428 	  if (pending_break_support == AUTO_BOOLEAN_AUTO
9429 	      && !nquery (_("Make %s pending on future shared library load? "),
9430 			  bptype_string (type_wanted)))
9431 	    return 0;
9432 
9433 	  /* At this point, either the user was queried about setting
9434 	     a pending breakpoint and selected yes, or pending
9435 	     breakpoint behavior is on and thus a pending breakpoint
9436 	     is defaulted on behalf of the user.  */
9437 	  pending = 1;
9438 	}
9439       else
9440 	throw;
9441     }
9442 
9443   if (!pending && canonical.lsals.empty ())
9444     return 0;
9445 
9446   /* Resolve all line numbers to PC's and verify that the addresses
9447      are ok for the target.  */
9448   if (!pending)
9449     {
9450       for (auto &lsal : canonical.lsals)
9451 	breakpoint_sals_to_pc (lsal.sals);
9452     }
9453 
9454   /* Fast tracepoints may have additional restrictions on location.  */
9455   if (!pending && type_wanted == bp_fast_tracepoint)
9456     {
9457       for (const auto &lsal : canonical.lsals)
9458 	check_fast_tracepoint_sals (gdbarch, lsal.sals);
9459     }
9460 
9461   /* Verify that condition can be parsed, before setting any
9462      breakpoints.  Allocate a separate condition expression for each
9463      breakpoint.  */
9464   if (!pending)
9465     {
9466       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9467       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9468 
9469       if (parse_extra)
9470 	{
9471 	  char *rest;
9472 	  char *cond;
9473 
9474 	  const linespec_sals &lsal = canonical.lsals[0];
9475 
9476 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
9477 					      &cond, &thread, &task, &rest);
9478 	  cond_string_copy.reset (cond);
9479 	  extra_string_copy.reset (rest);
9480 	}
9481       else
9482 	{
9483 	  if (type_wanted != bp_dprintf
9484 	      && extra_string != NULL && *extra_string != '\0')
9485 		error (_("Garbage '%s' at end of location"), extra_string);
9486 
9487 	  /* Check the validity of the condition.  We should error out
9488 	     if the condition is invalid at all of the locations and
9489 	     if it is not forced.  In the PARSE_EXTRA case above, this
9490 	     check is done when parsing the EXTRA_STRING.  */
9491 	  if (cond_string != nullptr && !force_condition)
9492 	    {
9493 	      int num_failures = 0;
9494 	      const linespec_sals &lsal = canonical.lsals[0];
9495 	      for (const auto &sal : lsal.sals)
9496 		{
9497 		  const char *cond = cond_string;
9498 		  try
9499 		    {
9500 		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
9501 		      /* One success is sufficient to keep going.  */
9502 		      break;
9503 		    }
9504 		  catch (const gdb_exception_error &)
9505 		    {
9506 		      num_failures++;
9507 		      /* If this is the last sal, error out.  */
9508 		      if (num_failures == lsal.sals.size ())
9509 			throw;
9510 		    }
9511 		}
9512 	    }
9513 
9514 	  /* Create a private copy of condition string.  */
9515 	  if (cond_string)
9516 	    cond_string_copy.reset (xstrdup (cond_string));
9517 	  /* Create a private copy of any extra string.  */
9518 	  if (extra_string)
9519 	    extra_string_copy.reset (xstrdup (extra_string));
9520 	}
9521 
9522       ops->create_breakpoints_sal (gdbarch, &canonical,
9523 				   std::move (cond_string_copy),
9524 				   std::move (extra_string_copy),
9525 				   type_wanted,
9526 				   tempflag ? disp_del : disp_donttouch,
9527 				   thread, task, ignore_count, ops,
9528 				   from_tty, enabled, internal, flags);
9529     }
9530   else
9531     {
9532       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9533 
9534       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9535       b->location = copy_event_location (location);
9536 
9537       if (parse_extra)
9538 	b->cond_string = NULL;
9539       else
9540 	{
9541 	  /* Create a private copy of condition string.  */
9542 	  b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9543 	  b->thread = thread;
9544 	}
9545 
9546       /* Create a private copy of any extra string.  */
9547       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9548       b->ignore_count = ignore_count;
9549       b->disposition = tempflag ? disp_del : disp_donttouch;
9550       b->condition_not_parsed = 1;
9551       b->enable_state = enabled ? bp_enabled : bp_disabled;
9552       if ((type_wanted != bp_breakpoint
9553 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
9554 	b->pspace = current_program_space;
9555 
9556       install_breakpoint (internal, std::move (b), 0);
9557     }
9558 
9559   if (canonical.lsals.size () > 1)
9560     {
9561       warning (_("Multiple breakpoints were set.\nUse the "
9562 		 "\"delete\" command to delete unwanted breakpoints."));
9563       prev_breakpoint_count = prev_bkpt_count;
9564     }
9565 
9566   update_global_location_list (UGLL_MAY_INSERT);
9567 
9568   return 1;
9569 }
9570 
9571 /* Set a breakpoint.
9572    ARG is a string describing breakpoint address,
9573    condition, and thread.
9574    FLAG specifies if a breakpoint is hardware on,
9575    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9576    and BP_TEMPFLAG.  */
9577 
9578 static void
9579 break_command_1 (const char *arg, int flag, int from_tty)
9580 {
9581   int tempflag = flag & BP_TEMPFLAG;
9582   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9583 			     ? bp_hardware_breakpoint
9584 			     : bp_breakpoint);
9585 
9586   event_location_up location = string_to_event_location (&arg, current_language);
9587   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
9588     (location.get (), false /* is_tracepoint */);
9589 
9590   create_breakpoint (get_current_arch (),
9591 		     location.get (),
9592 		     NULL, 0, arg, false, 1 /* parse arg */,
9593 		     tempflag, type_wanted,
9594 		     0 /* Ignore count */,
9595 		     pending_break_support,
9596 		     ops,
9597 		     from_tty,
9598 		     1 /* enabled */,
9599 		     0 /* internal */,
9600 		     0);
9601 }
9602 
9603 /* Helper function for break_command_1 and disassemble_command.  */
9604 
9605 void
9606 resolve_sal_pc (struct symtab_and_line *sal)
9607 {
9608   CORE_ADDR pc;
9609 
9610   if (sal->pc == 0 && sal->symtab != NULL)
9611     {
9612       if (!find_line_pc (sal->symtab, sal->line, &pc))
9613 	error (_("No line %d in file \"%s\"."),
9614 	       sal->line, symtab_to_filename_for_display (sal->symtab));
9615       sal->pc = pc;
9616 
9617       /* If this SAL corresponds to a breakpoint inserted using a line
9618 	 number, then skip the function prologue if necessary.  */
9619       if (sal->explicit_line)
9620 	skip_prologue_sal (sal);
9621     }
9622 
9623   if (sal->section == 0 && sal->symtab != NULL)
9624     {
9625       const struct blockvector *bv;
9626       const struct block *b;
9627       struct symbol *sym;
9628 
9629       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9630 				    SYMTAB_COMPUNIT (sal->symtab));
9631       if (bv != NULL)
9632 	{
9633 	  sym = block_linkage_function (b);
9634 	  if (sym != NULL)
9635 	    {
9636 	      fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9637 	      sal->section = sym->obj_section (SYMTAB_OBJFILE (sal->symtab));
9638 	    }
9639 	  else
9640 	    {
9641 	      /* It really is worthwhile to have the section, so we'll
9642 		 just have to look harder. This case can be executed
9643 		 if we have line numbers but no functions (as can
9644 		 happen in assembly source).  */
9645 
9646 	      scoped_restore_current_pspace_and_thread restore_pspace_thread;
9647 	      switch_to_program_space_and_thread (sal->pspace);
9648 
9649 	      bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9650 	      if (msym.minsym)
9651 		sal->section = msym.obj_section ();
9652 	    }
9653 	}
9654     }
9655 }
9656 
9657 void
9658 break_command (const char *arg, int from_tty)
9659 {
9660   break_command_1 (arg, 0, from_tty);
9661 }
9662 
9663 void
9664 tbreak_command (const char *arg, int from_tty)
9665 {
9666   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9667 }
9668 
9669 static void
9670 hbreak_command (const char *arg, int from_tty)
9671 {
9672   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9673 }
9674 
9675 static void
9676 thbreak_command (const char *arg, int from_tty)
9677 {
9678   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9679 }
9680 
9681 static void
9682 stop_command (const char *arg, int from_tty)
9683 {
9684   printf_filtered (_("Specify the type of breakpoint to set.\n\
9685 Usage: stop in <function | address>\n\
9686        stop at <line>\n"));
9687 }
9688 
9689 static void
9690 stopin_command (const char *arg, int from_tty)
9691 {
9692   int badInput = 0;
9693 
9694   if (arg == NULL)
9695     badInput = 1;
9696   else if (*arg != '*')
9697     {
9698       const char *argptr = arg;
9699       int hasColon = 0;
9700 
9701       /* Look for a ':'.  If this is a line number specification, then
9702 	 say it is bad, otherwise, it should be an address or
9703 	 function/method name.  */
9704       while (*argptr && !hasColon)
9705 	{
9706 	  hasColon = (*argptr == ':');
9707 	  argptr++;
9708 	}
9709 
9710       if (hasColon)
9711 	badInput = (*argptr != ':');	/* Not a class::method */
9712       else
9713 	badInput = isdigit (*arg);	/* a simple line number */
9714     }
9715 
9716   if (badInput)
9717     printf_filtered (_("Usage: stop in <function | address>\n"));
9718   else
9719     break_command_1 (arg, 0, from_tty);
9720 }
9721 
9722 static void
9723 stopat_command (const char *arg, int from_tty)
9724 {
9725   int badInput = 0;
9726 
9727   if (arg == NULL || *arg == '*')	/* no line number */
9728     badInput = 1;
9729   else
9730     {
9731       const char *argptr = arg;
9732       int hasColon = 0;
9733 
9734       /* Look for a ':'.  If there is a '::' then get out, otherwise
9735 	 it is probably a line number.  */
9736       while (*argptr && !hasColon)
9737 	{
9738 	  hasColon = (*argptr == ':');
9739 	  argptr++;
9740 	}
9741 
9742       if (hasColon)
9743 	badInput = (*argptr == ':');	/* we have class::method */
9744       else
9745 	badInput = !isdigit (*arg);	/* not a line number */
9746     }
9747 
9748   if (badInput)
9749     printf_filtered (_("Usage: stop at LINE\n"));
9750   else
9751     break_command_1 (arg, 0, from_tty);
9752 }
9753 
9754 /* The dynamic printf command is mostly like a regular breakpoint, but
9755    with a prewired command list consisting of a single output command,
9756    built from extra arguments supplied on the dprintf command
9757    line.  */
9758 
9759 static void
9760 dprintf_command (const char *arg, int from_tty)
9761 {
9762   event_location_up location = string_to_event_location (&arg, current_language);
9763 
9764   /* If non-NULL, ARG should have been advanced past the location;
9765      the next character must be ','.  */
9766   if (arg != NULL)
9767     {
9768       if (arg[0] != ',' || arg[1] == '\0')
9769 	error (_("Format string required"));
9770       else
9771 	{
9772 	  /* Skip the comma.  */
9773 	  ++arg;
9774 	}
9775     }
9776 
9777   create_breakpoint (get_current_arch (),
9778 		     location.get (),
9779 		     NULL, 0, arg, false, 1 /* parse arg */,
9780 		     0, bp_dprintf,
9781 		     0 /* Ignore count */,
9782 		     pending_break_support,
9783 		     &dprintf_breakpoint_ops,
9784 		     from_tty,
9785 		     1 /* enabled */,
9786 		     0 /* internal */,
9787 		     0);
9788 }
9789 
9790 static void
9791 agent_printf_command (const char *arg, int from_tty)
9792 {
9793   error (_("May only run agent-printf on the target"));
9794 }
9795 
9796 /* Implement the "breakpoint_hit" breakpoint_ops method for
9797    ranged breakpoints.  */
9798 
9799 static int
9800 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9801 				  const address_space *aspace,
9802 				  CORE_ADDR bp_addr,
9803 				  const struct target_waitstatus *ws)
9804 {
9805   if (ws->kind != TARGET_WAITKIND_STOPPED
9806       || ws->value.sig != GDB_SIGNAL_TRAP)
9807     return 0;
9808 
9809   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9810 					 bl->length, aspace, bp_addr);
9811 }
9812 
9813 /* Implement the "resources_needed" breakpoint_ops method for
9814    ranged breakpoints.  */
9815 
9816 static int
9817 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9818 {
9819   return target_ranged_break_num_registers ();
9820 }
9821 
9822 /* Implement the "print_it" breakpoint_ops method for
9823    ranged breakpoints.  */
9824 
9825 static enum print_stop_action
9826 print_it_ranged_breakpoint (bpstat bs)
9827 {
9828   struct breakpoint *b = bs->breakpoint_at;
9829   struct bp_location *bl = b->loc;
9830   struct ui_out *uiout = current_uiout;
9831 
9832   gdb_assert (b->type == bp_hardware_breakpoint);
9833 
9834   /* Ranged breakpoints have only one location.  */
9835   gdb_assert (bl && bl->next == NULL);
9836 
9837   annotate_breakpoint (b->number);
9838 
9839   maybe_print_thread_hit_breakpoint (uiout);
9840 
9841   if (b->disposition == disp_del)
9842     uiout->text ("Temporary ranged breakpoint ");
9843   else
9844     uiout->text ("Ranged breakpoint ");
9845   if (uiout->is_mi_like_p ())
9846     {
9847       uiout->field_string ("reason",
9848 		      async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9849       uiout->field_string ("disp", bpdisp_text (b->disposition));
9850     }
9851   uiout->field_signed ("bkptno", b->number);
9852   uiout->text (", ");
9853 
9854   return PRINT_SRC_AND_LOC;
9855 }
9856 
9857 /* Implement the "print_one" breakpoint_ops method for
9858    ranged breakpoints.  */
9859 
9860 static void
9861 print_one_ranged_breakpoint (struct breakpoint *b,
9862 			     struct bp_location **last_loc)
9863 {
9864   struct bp_location *bl = b->loc;
9865   struct value_print_options opts;
9866   struct ui_out *uiout = current_uiout;
9867 
9868   /* Ranged breakpoints have only one location.  */
9869   gdb_assert (bl && bl->next == NULL);
9870 
9871   get_user_print_options (&opts);
9872 
9873   if (opts.addressprint)
9874     /* We don't print the address range here, it will be printed later
9875        by print_one_detail_ranged_breakpoint.  */
9876     uiout->field_skip ("addr");
9877   annotate_field (5);
9878   print_breakpoint_location (b, bl);
9879   *last_loc = bl;
9880 }
9881 
9882 /* Implement the "print_one_detail" breakpoint_ops method for
9883    ranged breakpoints.  */
9884 
9885 static void
9886 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9887 				    struct ui_out *uiout)
9888 {
9889   CORE_ADDR address_start, address_end;
9890   struct bp_location *bl = b->loc;
9891   string_file stb;
9892 
9893   gdb_assert (bl);
9894 
9895   address_start = bl->address;
9896   address_end = address_start + bl->length - 1;
9897 
9898   uiout->text ("\taddress range: ");
9899   stb.printf ("[%s, %s]",
9900 	      print_core_address (bl->gdbarch, address_start),
9901 	      print_core_address (bl->gdbarch, address_end));
9902   uiout->field_stream ("addr", stb);
9903   uiout->text ("\n");
9904 }
9905 
9906 /* Implement the "print_mention" breakpoint_ops method for
9907    ranged breakpoints.  */
9908 
9909 static void
9910 print_mention_ranged_breakpoint (struct breakpoint *b)
9911 {
9912   struct bp_location *bl = b->loc;
9913   struct ui_out *uiout = current_uiout;
9914 
9915   gdb_assert (bl);
9916   gdb_assert (b->type == bp_hardware_breakpoint);
9917 
9918   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9919 		  b->number, paddress (bl->gdbarch, bl->address),
9920 		  paddress (bl->gdbarch, bl->address + bl->length - 1));
9921 }
9922 
9923 /* Implement the "print_recreate" breakpoint_ops method for
9924    ranged breakpoints.  */
9925 
9926 static void
9927 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9928 {
9929   fprintf_unfiltered (fp, "break-range %s, %s",
9930 		      event_location_to_string (b->location.get ()),
9931 		      event_location_to_string (b->location_range_end.get ()));
9932   print_recreate_thread (b, fp);
9933 }
9934 
9935 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9936 
9937 static struct breakpoint_ops ranged_breakpoint_ops;
9938 
9939 /* Find the address where the end of the breakpoint range should be
9940    placed, given the SAL of the end of the range.  This is so that if
9941    the user provides a line number, the end of the range is set to the
9942    last instruction of the given line.  */
9943 
9944 static CORE_ADDR
9945 find_breakpoint_range_end (struct symtab_and_line sal)
9946 {
9947   CORE_ADDR end;
9948 
9949   /* If the user provided a PC value, use it.  Otherwise,
9950      find the address of the end of the given location.  */
9951   if (sal.explicit_pc)
9952     end = sal.pc;
9953   else
9954     {
9955       int ret;
9956       CORE_ADDR start;
9957 
9958       ret = find_line_pc_range (sal, &start, &end);
9959       if (!ret)
9960 	error (_("Could not find location of the end of the range."));
9961 
9962       /* find_line_pc_range returns the start of the next line.  */
9963       end--;
9964     }
9965 
9966   return end;
9967 }
9968 
9969 /* Implement the "break-range" CLI command.  */
9970 
9971 static void
9972 break_range_command (const char *arg, int from_tty)
9973 {
9974   const char *arg_start;
9975   struct linespec_result canonical_start, canonical_end;
9976   int bp_count, can_use_bp, length;
9977   CORE_ADDR end;
9978   struct breakpoint *b;
9979 
9980   /* We don't support software ranged breakpoints.  */
9981   if (target_ranged_break_num_registers () < 0)
9982     error (_("This target does not support hardware ranged breakpoints."));
9983 
9984   bp_count = hw_breakpoint_used_count ();
9985   bp_count += target_ranged_break_num_registers ();
9986   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9987 						   bp_count, 0);
9988   if (can_use_bp < 0)
9989     error (_("Hardware breakpoints used exceeds limit."));
9990 
9991   arg = skip_spaces (arg);
9992   if (arg == NULL || arg[0] == '\0')
9993     error(_("No address range specified."));
9994 
9995   arg_start = arg;
9996   event_location_up start_location = string_to_event_location (&arg,
9997 							       current_language);
9998   parse_breakpoint_sals (start_location.get (), &canonical_start);
9999 
10000   if (arg[0] != ',')
10001     error (_("Too few arguments."));
10002   else if (canonical_start.lsals.empty ())
10003     error (_("Could not find location of the beginning of the range."));
10004 
10005   const linespec_sals &lsal_start = canonical_start.lsals[0];
10006 
10007   if (canonical_start.lsals.size () > 1
10008       || lsal_start.sals.size () != 1)
10009     error (_("Cannot create a ranged breakpoint with multiple locations."));
10010 
10011   const symtab_and_line &sal_start = lsal_start.sals[0];
10012   std::string addr_string_start (arg_start, arg - arg_start);
10013 
10014   arg++;	/* Skip the comma.  */
10015   arg = skip_spaces (arg);
10016 
10017   /* Parse the end location.  */
10018 
10019   arg_start = arg;
10020 
10021   /* We call decode_line_full directly here instead of using
10022      parse_breakpoint_sals because we need to specify the start location's
10023      symtab and line as the default symtab and line for the end of the
10024      range.  This makes it possible to have ranges like "foo.c:27, +14",
10025      where +14 means 14 lines from the start location.  */
10026   event_location_up end_location = string_to_event_location (&arg,
10027 							     current_language);
10028   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10029 		    sal_start.symtab, sal_start.line,
10030 		    &canonical_end, NULL, NULL);
10031 
10032   if (canonical_end.lsals.empty ())
10033     error (_("Could not find location of the end of the range."));
10034 
10035   const linespec_sals &lsal_end = canonical_end.lsals[0];
10036   if (canonical_end.lsals.size () > 1
10037       || lsal_end.sals.size () != 1)
10038     error (_("Cannot create a ranged breakpoint with multiple locations."));
10039 
10040   const symtab_and_line &sal_end = lsal_end.sals[0];
10041 
10042   end = find_breakpoint_range_end (sal_end);
10043   if (sal_start.pc > end)
10044     error (_("Invalid address range, end precedes start."));
10045 
10046   length = end - sal_start.pc + 1;
10047   if (length < 0)
10048     /* Length overflowed.  */
10049     error (_("Address range too large."));
10050   else if (length == 1)
10051     {
10052       /* This range is simple enough to be handled by
10053 	 the `hbreak' command.  */
10054       hbreak_command (&addr_string_start[0], 1);
10055 
10056       return;
10057     }
10058 
10059   /* Now set up the breakpoint.  */
10060   b = set_raw_breakpoint (get_current_arch (), sal_start,
10061 			  bp_hardware_breakpoint, &ranged_breakpoint_ops);
10062   set_breakpoint_count (breakpoint_count + 1);
10063   b->number = breakpoint_count;
10064   b->disposition = disp_donttouch;
10065   b->location = std::move (start_location);
10066   b->location_range_end = std::move (end_location);
10067   b->loc->length = length;
10068 
10069   mention (b);
10070   gdb::observers::breakpoint_created.notify (b);
10071   update_global_location_list (UGLL_MAY_INSERT);
10072 }
10073 
10074 /*  Return non-zero if EXP is verified as constant.  Returned zero
10075     means EXP is variable.  Also the constant detection may fail for
10076     some constant expressions and in such case still falsely return
10077     zero.  */
10078 
10079 static bool
10080 watchpoint_exp_is_const (const struct expression *exp)
10081 {
10082   return exp->op->constant_p ();
10083 }
10084 
10085 /* Watchpoint destructor.  */
10086 
10087 watchpoint::~watchpoint ()
10088 {
10089   xfree (this->exp_string);
10090   xfree (this->exp_string_reparse);
10091 }
10092 
10093 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10094 
10095 static void
10096 re_set_watchpoint (struct breakpoint *b)
10097 {
10098   struct watchpoint *w = (struct watchpoint *) b;
10099 
10100   /* Watchpoint can be either on expression using entirely global
10101      variables, or it can be on local variables.
10102 
10103      Watchpoints of the first kind are never auto-deleted, and even
10104      persist across program restarts.  Since they can use variables
10105      from shared libraries, we need to reparse expression as libraries
10106      are loaded and unloaded.
10107 
10108      Watchpoints on local variables can also change meaning as result
10109      of solib event.  For example, if a watchpoint uses both a local
10110      and a global variables in expression, it's a local watchpoint,
10111      but unloading of a shared library will make the expression
10112      invalid.  This is not a very common use case, but we still
10113      re-evaluate expression, to avoid surprises to the user.
10114 
10115      Note that for local watchpoints, we re-evaluate it only if
10116      watchpoints frame id is still valid.  If it's not, it means the
10117      watchpoint is out of scope and will be deleted soon.  In fact,
10118      I'm not sure we'll ever be called in this case.
10119 
10120      If a local watchpoint's frame id is still valid, then
10121      w->exp_valid_block is likewise valid, and we can safely use it.
10122 
10123      Don't do anything about disabled watchpoints, since they will be
10124      reevaluated again when enabled.  */
10125   update_watchpoint (w, 1 /* reparse */);
10126 }
10127 
10128 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10129 
10130 static int
10131 insert_watchpoint (struct bp_location *bl)
10132 {
10133   struct watchpoint *w = (struct watchpoint *) bl->owner;
10134   int length = w->exact ? 1 : bl->length;
10135 
10136   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10137 				   w->cond_exp.get ());
10138 }
10139 
10140 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10141 
10142 static int
10143 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10144 {
10145   struct watchpoint *w = (struct watchpoint *) bl->owner;
10146   int length = w->exact ? 1 : bl->length;
10147 
10148   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10149 				   w->cond_exp.get ());
10150 }
10151 
10152 static int
10153 breakpoint_hit_watchpoint (const struct bp_location *bl,
10154 			   const address_space *aspace, CORE_ADDR bp_addr,
10155 			   const struct target_waitstatus *ws)
10156 {
10157   struct breakpoint *b = bl->owner;
10158   struct watchpoint *w = (struct watchpoint *) b;
10159 
10160   /* Continuable hardware watchpoints are treated as non-existent if the
10161      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10162      some data address).  Otherwise gdb won't stop on a break instruction
10163      in the code (not from a breakpoint) when a hardware watchpoint has
10164      been defined.  Also skip watchpoints which we know did not trigger
10165      (did not match the data address).  */
10166   if (is_hardware_watchpoint (b)
10167       && w->watchpoint_triggered == watch_triggered_no)
10168     return 0;
10169 
10170   return 1;
10171 }
10172 
10173 static void
10174 check_status_watchpoint (bpstat bs)
10175 {
10176   gdb_assert (is_watchpoint (bs->breakpoint_at));
10177 
10178   bpstat_check_watchpoint (bs);
10179 }
10180 
10181 /* Implement the "resources_needed" breakpoint_ops method for
10182    hardware watchpoints.  */
10183 
10184 static int
10185 resources_needed_watchpoint (const struct bp_location *bl)
10186 {
10187   struct watchpoint *w = (struct watchpoint *) bl->owner;
10188   int length = w->exact? 1 : bl->length;
10189 
10190   return target_region_ok_for_hw_watchpoint (bl->address, length);
10191 }
10192 
10193 /* Implement the "works_in_software_mode" breakpoint_ops method for
10194    hardware watchpoints.  */
10195 
10196 static int
10197 works_in_software_mode_watchpoint (const struct breakpoint *b)
10198 {
10199   /* Read and access watchpoints only work with hardware support.  */
10200   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10201 }
10202 
10203 static enum print_stop_action
10204 print_it_watchpoint (bpstat bs)
10205 {
10206   struct breakpoint *b;
10207   enum print_stop_action result;
10208   struct watchpoint *w;
10209   struct ui_out *uiout = current_uiout;
10210 
10211   gdb_assert (bs->bp_location_at != NULL);
10212 
10213   b = bs->breakpoint_at;
10214   w = (struct watchpoint *) b;
10215 
10216   annotate_watchpoint (b->number);
10217   maybe_print_thread_hit_breakpoint (uiout);
10218 
10219   string_file stb;
10220 
10221   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10222   switch (b->type)
10223     {
10224     case bp_watchpoint:
10225     case bp_hardware_watchpoint:
10226       if (uiout->is_mi_like_p ())
10227 	uiout->field_string
10228 	  ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10229       mention (b);
10230       tuple_emitter.emplace (uiout, "value");
10231       uiout->text ("\nOld value = ");
10232       watchpoint_value_print (bs->old_val.get (), &stb);
10233       uiout->field_stream ("old", stb);
10234       uiout->text ("\nNew value = ");
10235       watchpoint_value_print (w->val.get (), &stb);
10236       uiout->field_stream ("new", stb);
10237       uiout->text ("\n");
10238       /* More than one watchpoint may have been triggered.  */
10239       result = PRINT_UNKNOWN;
10240       break;
10241 
10242     case bp_read_watchpoint:
10243       if (uiout->is_mi_like_p ())
10244 	uiout->field_string
10245 	  ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10246       mention (b);
10247       tuple_emitter.emplace (uiout, "value");
10248       uiout->text ("\nValue = ");
10249       watchpoint_value_print (w->val.get (), &stb);
10250       uiout->field_stream ("value", stb);
10251       uiout->text ("\n");
10252       result = PRINT_UNKNOWN;
10253       break;
10254 
10255     case bp_access_watchpoint:
10256       if (bs->old_val != NULL)
10257 	{
10258 	  if (uiout->is_mi_like_p ())
10259 	    uiout->field_string
10260 	      ("reason",
10261 	       async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10262 	  mention (b);
10263 	  tuple_emitter.emplace (uiout, "value");
10264 	  uiout->text ("\nOld value = ");
10265 	  watchpoint_value_print (bs->old_val.get (), &stb);
10266 	  uiout->field_stream ("old", stb);
10267 	  uiout->text ("\nNew value = ");
10268 	}
10269       else
10270 	{
10271 	  mention (b);
10272 	  if (uiout->is_mi_like_p ())
10273 	    uiout->field_string
10274 	      ("reason",
10275 	       async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10276 	  tuple_emitter.emplace (uiout, "value");
10277 	  uiout->text ("\nValue = ");
10278 	}
10279       watchpoint_value_print (w->val.get (), &stb);
10280       uiout->field_stream ("new", stb);
10281       uiout->text ("\n");
10282       result = PRINT_UNKNOWN;
10283       break;
10284     default:
10285       result = PRINT_UNKNOWN;
10286     }
10287 
10288   return result;
10289 }
10290 
10291 /* Implement the "print_mention" breakpoint_ops method for hardware
10292    watchpoints.  */
10293 
10294 static void
10295 print_mention_watchpoint (struct breakpoint *b)
10296 {
10297   struct watchpoint *w = (struct watchpoint *) b;
10298   struct ui_out *uiout = current_uiout;
10299   const char *tuple_name;
10300 
10301   switch (b->type)
10302     {
10303     case bp_watchpoint:
10304       uiout->text ("Watchpoint ");
10305       tuple_name = "wpt";
10306       break;
10307     case bp_hardware_watchpoint:
10308       uiout->text ("Hardware watchpoint ");
10309       tuple_name = "wpt";
10310       break;
10311     case bp_read_watchpoint:
10312       uiout->text ("Hardware read watchpoint ");
10313       tuple_name = "hw-rwpt";
10314       break;
10315     case bp_access_watchpoint:
10316       uiout->text ("Hardware access (read/write) watchpoint ");
10317       tuple_name = "hw-awpt";
10318       break;
10319     default:
10320       internal_error (__FILE__, __LINE__,
10321 		      _("Invalid hardware watchpoint type."));
10322     }
10323 
10324   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10325   uiout->field_signed ("number", b->number);
10326   uiout->text (": ");
10327   uiout->field_string ("exp", w->exp_string);
10328 }
10329 
10330 /* Implement the "print_recreate" breakpoint_ops method for
10331    watchpoints.  */
10332 
10333 static void
10334 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10335 {
10336   struct watchpoint *w = (struct watchpoint *) b;
10337 
10338   switch (b->type)
10339     {
10340     case bp_watchpoint:
10341     case bp_hardware_watchpoint:
10342       fprintf_unfiltered (fp, "watch");
10343       break;
10344     case bp_read_watchpoint:
10345       fprintf_unfiltered (fp, "rwatch");
10346       break;
10347     case bp_access_watchpoint:
10348       fprintf_unfiltered (fp, "awatch");
10349       break;
10350     default:
10351       internal_error (__FILE__, __LINE__,
10352 		      _("Invalid watchpoint type."));
10353     }
10354 
10355   fprintf_unfiltered (fp, " %s", w->exp_string);
10356   print_recreate_thread (b, fp);
10357 }
10358 
10359 /* Implement the "explains_signal" breakpoint_ops method for
10360    watchpoints.  */
10361 
10362 static int
10363 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10364 {
10365   /* A software watchpoint cannot cause a signal other than
10366      GDB_SIGNAL_TRAP.  */
10367   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10368     return 0;
10369 
10370   return 1;
10371 }
10372 
10373 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10374 
10375 static struct breakpoint_ops watchpoint_breakpoint_ops;
10376 
10377 /* Implement the "insert" breakpoint_ops method for
10378    masked hardware watchpoints.  */
10379 
10380 static int
10381 insert_masked_watchpoint (struct bp_location *bl)
10382 {
10383   struct watchpoint *w = (struct watchpoint *) bl->owner;
10384 
10385   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10386 					bl->watchpoint_type);
10387 }
10388 
10389 /* Implement the "remove" breakpoint_ops method for
10390    masked hardware watchpoints.  */
10391 
10392 static int
10393 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10394 {
10395   struct watchpoint *w = (struct watchpoint *) bl->owner;
10396 
10397   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10398 					bl->watchpoint_type);
10399 }
10400 
10401 /* Implement the "resources_needed" breakpoint_ops method for
10402    masked hardware watchpoints.  */
10403 
10404 static int
10405 resources_needed_masked_watchpoint (const struct bp_location *bl)
10406 {
10407   struct watchpoint *w = (struct watchpoint *) bl->owner;
10408 
10409   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10410 }
10411 
10412 /* Implement the "works_in_software_mode" breakpoint_ops method for
10413    masked hardware watchpoints.  */
10414 
10415 static int
10416 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10417 {
10418   return 0;
10419 }
10420 
10421 /* Implement the "print_it" breakpoint_ops method for
10422    masked hardware watchpoints.  */
10423 
10424 static enum print_stop_action
10425 print_it_masked_watchpoint (bpstat bs)
10426 {
10427   struct breakpoint *b = bs->breakpoint_at;
10428   struct ui_out *uiout = current_uiout;
10429 
10430   /* Masked watchpoints have only one location.  */
10431   gdb_assert (b->loc && b->loc->next == NULL);
10432 
10433   annotate_watchpoint (b->number);
10434   maybe_print_thread_hit_breakpoint (uiout);
10435 
10436   switch (b->type)
10437     {
10438     case bp_hardware_watchpoint:
10439       if (uiout->is_mi_like_p ())
10440 	uiout->field_string
10441 	  ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10442       break;
10443 
10444     case bp_read_watchpoint:
10445       if (uiout->is_mi_like_p ())
10446 	uiout->field_string
10447 	  ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10448       break;
10449 
10450     case bp_access_watchpoint:
10451       if (uiout->is_mi_like_p ())
10452 	uiout->field_string
10453 	  ("reason",
10454 	   async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10455       break;
10456     default:
10457       internal_error (__FILE__, __LINE__,
10458 		      _("Invalid hardware watchpoint type."));
10459     }
10460 
10461   mention (b);
10462   uiout->text (_("\n\
10463 Check the underlying instruction at PC for the memory\n\
10464 address and value which triggered this watchpoint.\n"));
10465   uiout->text ("\n");
10466 
10467   /* More than one watchpoint may have been triggered.  */
10468   return PRINT_UNKNOWN;
10469 }
10470 
10471 /* Implement the "print_one_detail" breakpoint_ops method for
10472    masked hardware watchpoints.  */
10473 
10474 static void
10475 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10476 				    struct ui_out *uiout)
10477 {
10478   struct watchpoint *w = (struct watchpoint *) b;
10479 
10480   /* Masked watchpoints have only one location.  */
10481   gdb_assert (b->loc && b->loc->next == NULL);
10482 
10483   uiout->text ("\tmask ");
10484   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10485   uiout->text ("\n");
10486 }
10487 
10488 /* Implement the "print_mention" breakpoint_ops method for
10489    masked hardware watchpoints.  */
10490 
10491 static void
10492 print_mention_masked_watchpoint (struct breakpoint *b)
10493 {
10494   struct watchpoint *w = (struct watchpoint *) b;
10495   struct ui_out *uiout = current_uiout;
10496   const char *tuple_name;
10497 
10498   switch (b->type)
10499     {
10500     case bp_hardware_watchpoint:
10501       uiout->text ("Masked hardware watchpoint ");
10502       tuple_name = "wpt";
10503       break;
10504     case bp_read_watchpoint:
10505       uiout->text ("Masked hardware read watchpoint ");
10506       tuple_name = "hw-rwpt";
10507       break;
10508     case bp_access_watchpoint:
10509       uiout->text ("Masked hardware access (read/write) watchpoint ");
10510       tuple_name = "hw-awpt";
10511       break;
10512     default:
10513       internal_error (__FILE__, __LINE__,
10514 		      _("Invalid hardware watchpoint type."));
10515     }
10516 
10517   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10518   uiout->field_signed ("number", b->number);
10519   uiout->text (": ");
10520   uiout->field_string ("exp", w->exp_string);
10521 }
10522 
10523 /* Implement the "print_recreate" breakpoint_ops method for
10524    masked hardware watchpoints.  */
10525 
10526 static void
10527 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10528 {
10529   struct watchpoint *w = (struct watchpoint *) b;
10530 
10531   switch (b->type)
10532     {
10533     case bp_hardware_watchpoint:
10534       fprintf_unfiltered (fp, "watch");
10535       break;
10536     case bp_read_watchpoint:
10537       fprintf_unfiltered (fp, "rwatch");
10538       break;
10539     case bp_access_watchpoint:
10540       fprintf_unfiltered (fp, "awatch");
10541       break;
10542     default:
10543       internal_error (__FILE__, __LINE__,
10544 		      _("Invalid hardware watchpoint type."));
10545     }
10546 
10547   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string,
10548 		      phex (w->hw_wp_mask, sizeof (CORE_ADDR)));
10549   print_recreate_thread (b, fp);
10550 }
10551 
10552 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10553 
10554 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10555 
10556 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10557 
10558 static bool
10559 is_masked_watchpoint (const struct breakpoint *b)
10560 {
10561   return b->ops == &masked_watchpoint_breakpoint_ops;
10562 }
10563 
10564 /* accessflag:  hw_write:  watch write,
10565 		hw_read:   watch read,
10566 		hw_access: watch access (read or write) */
10567 static void
10568 watch_command_1 (const char *arg, int accessflag, int from_tty,
10569 		 bool just_location, bool internal)
10570 {
10571   struct breakpoint *scope_breakpoint = NULL;
10572   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10573   struct value *result;
10574   int saved_bitpos = 0, saved_bitsize = 0;
10575   const char *exp_start = NULL;
10576   const char *exp_end = NULL;
10577   const char *tok, *end_tok;
10578   int toklen = -1;
10579   const char *cond_start = NULL;
10580   const char *cond_end = NULL;
10581   enum bptype bp_type;
10582   int thread = -1;
10583   /* Flag to indicate whether we are going to use masks for
10584      the hardware watchpoint.  */
10585   bool use_mask = false;
10586   CORE_ADDR mask = 0;
10587 
10588   /* Make sure that we actually have parameters to parse.  */
10589   if (arg != NULL && arg[0] != '\0')
10590     {
10591       const char *value_start;
10592 
10593       exp_end = arg + strlen (arg);
10594 
10595       /* Look for "parameter value" pairs at the end
10596 	 of the arguments string.  */
10597       for (tok = exp_end - 1; tok > arg; tok--)
10598 	{
10599 	  /* Skip whitespace at the end of the argument list.  */
10600 	  while (tok > arg && (*tok == ' ' || *tok == '\t'))
10601 	    tok--;
10602 
10603 	  /* Find the beginning of the last token.
10604 	     This is the value of the parameter.  */
10605 	  while (tok > arg && (*tok != ' ' && *tok != '\t'))
10606 	    tok--;
10607 	  value_start = tok + 1;
10608 
10609 	  /* Skip whitespace.  */
10610 	  while (tok > arg && (*tok == ' ' || *tok == '\t'))
10611 	    tok--;
10612 
10613 	  end_tok = tok;
10614 
10615 	  /* Find the beginning of the second to last token.
10616 	     This is the parameter itself.  */
10617 	  while (tok > arg && (*tok != ' ' && *tok != '\t'))
10618 	    tok--;
10619 	  tok++;
10620 	  toklen = end_tok - tok + 1;
10621 
10622 	  if (toklen == 6 && startswith (tok, "thread"))
10623 	    {
10624 	      struct thread_info *thr;
10625 	      /* At this point we've found a "thread" token, which means
10626 		 the user is trying to set a watchpoint that triggers
10627 		 only in a specific thread.  */
10628 	      const char *endp;
10629 
10630 	      if (thread != -1)
10631 		error(_("You can specify only one thread."));
10632 
10633 	      /* Extract the thread ID from the next token.  */
10634 	      thr = parse_thread_id (value_start, &endp);
10635 
10636 	      /* Check if the user provided a valid thread ID.  */
10637 	      if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10638 		invalid_thread_id_error (value_start);
10639 
10640 	      thread = thr->global_num;
10641 	    }
10642 	  else if (toklen == 4 && startswith (tok, "mask"))
10643 	    {
10644 	      /* We've found a "mask" token, which means the user wants to
10645 		 create a hardware watchpoint that is going to have the mask
10646 		 facility.  */
10647 	      struct value *mask_value, *mark;
10648 
10649 	      if (use_mask)
10650 		error(_("You can specify only one mask."));
10651 
10652 	      use_mask = just_location = true;
10653 
10654 	      mark = value_mark ();
10655 	      mask_value = parse_to_comma_and_eval (&value_start);
10656 	      mask = value_as_address (mask_value);
10657 	      value_free_to_mark (mark);
10658 	    }
10659 	  else
10660 	    /* We didn't recognize what we found.  We should stop here.  */
10661 	    break;
10662 
10663 	  /* Truncate the string and get rid of the "parameter value" pair before
10664 	     the arguments string is parsed by the parse_exp_1 function.  */
10665 	  exp_end = tok;
10666 	}
10667     }
10668   else
10669     exp_end = arg;
10670 
10671   /* Parse the rest of the arguments.  From here on out, everything
10672      is in terms of a newly allocated string instead of the original
10673      ARG.  */
10674   std::string expression (arg, exp_end - arg);
10675   exp_start = arg = expression.c_str ();
10676   innermost_block_tracker tracker;
10677   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10678   exp_end = arg;
10679   /* Remove trailing whitespace from the expression before saving it.
10680      This makes the eventual display of the expression string a bit
10681      prettier.  */
10682   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10683     --exp_end;
10684 
10685   /* Checking if the expression is not constant.  */
10686   if (watchpoint_exp_is_const (exp.get ()))
10687     {
10688       int len;
10689 
10690       len = exp_end - exp_start;
10691       while (len > 0 && isspace (exp_start[len - 1]))
10692 	len--;
10693       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10694     }
10695 
10696   exp_valid_block = tracker.block ();
10697   struct value *mark = value_mark ();
10698   struct value *val_as_value = nullptr;
10699   fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
10700 		      just_location);
10701 
10702   if (val_as_value != NULL && just_location)
10703     {
10704       saved_bitpos = value_bitpos (val_as_value);
10705       saved_bitsize = value_bitsize (val_as_value);
10706     }
10707 
10708   value_ref_ptr val;
10709   if (just_location)
10710     {
10711       int ret;
10712 
10713       exp_valid_block = NULL;
10714       val = release_value (value_addr (result));
10715       value_free_to_mark (mark);
10716 
10717       if (use_mask)
10718 	{
10719 	  ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10720 						   mask);
10721 	  if (ret == -1)
10722 	    error (_("This target does not support masked watchpoints."));
10723 	  else if (ret == -2)
10724 	    error (_("Invalid mask or memory region."));
10725 	}
10726     }
10727   else if (val_as_value != NULL)
10728     val = release_value (val_as_value);
10729 
10730   tok = skip_spaces (arg);
10731   end_tok = skip_to_space (tok);
10732 
10733   toklen = end_tok - tok;
10734   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10735     {
10736       tok = cond_start = end_tok + 1;
10737       innermost_block_tracker if_tracker;
10738       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10739 
10740       /* The watchpoint expression may not be local, but the condition
10741 	 may still be.  E.g.: `watch global if local > 0'.  */
10742       cond_exp_valid_block = if_tracker.block ();
10743 
10744       cond_end = tok;
10745     }
10746   if (*tok)
10747     error (_("Junk at end of command."));
10748 
10749   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10750 
10751   /* Save this because create_internal_breakpoint below invalidates
10752      'wp_frame'.  */
10753   frame_id watchpoint_frame = get_frame_id (wp_frame);
10754 
10755   /* If the expression is "local", then set up a "watchpoint scope"
10756      breakpoint at the point where we've left the scope of the watchpoint
10757      expression.  Create the scope breakpoint before the watchpoint, so
10758      that we will encounter it first in bpstat_stop_status.  */
10759   if (exp_valid_block != NULL && wp_frame != NULL)
10760     {
10761       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10762 
10763       if (frame_id_p (caller_frame_id))
10764 	{
10765 	  gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10766 	  CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10767 
10768 	  scope_breakpoint
10769 	    = create_internal_breakpoint (caller_arch, caller_pc,
10770 					  bp_watchpoint_scope,
10771 					  &momentary_breakpoint_ops);
10772 
10773 	  /* create_internal_breakpoint could invalidate WP_FRAME.  */
10774 	  wp_frame = NULL;
10775 
10776 	  scope_breakpoint->enable_state = bp_enabled;
10777 
10778 	  /* Automatically delete the breakpoint when it hits.  */
10779 	  scope_breakpoint->disposition = disp_del;
10780 
10781 	  /* Only break in the proper frame (help with recursion).  */
10782 	  scope_breakpoint->frame_id = caller_frame_id;
10783 
10784 	  /* Set the address at which we will stop.  */
10785 	  scope_breakpoint->loc->gdbarch = caller_arch;
10786 	  scope_breakpoint->loc->requested_address = caller_pc;
10787 	  scope_breakpoint->loc->address
10788 	    = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10789 					 scope_breakpoint->loc->requested_address,
10790 					 scope_breakpoint->type);
10791 	}
10792     }
10793 
10794   /* Now set up the breakpoint.  We create all watchpoints as hardware
10795      watchpoints here even if hardware watchpoints are turned off, a call
10796      to update_watchpoint later in this function will cause the type to
10797      drop back to bp_watchpoint (software watchpoint) if required.  */
10798 
10799   if (accessflag == hw_read)
10800     bp_type = bp_read_watchpoint;
10801   else if (accessflag == hw_access)
10802     bp_type = bp_access_watchpoint;
10803   else
10804     bp_type = bp_hardware_watchpoint;
10805 
10806   std::unique_ptr<watchpoint> w (new watchpoint ());
10807 
10808   if (use_mask)
10809     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10810 					  &masked_watchpoint_breakpoint_ops);
10811   else
10812     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10813 					  &watchpoint_breakpoint_ops);
10814   w->thread = thread;
10815   w->disposition = disp_donttouch;
10816   w->pspace = current_program_space;
10817   w->exp = std::move (exp);
10818   w->exp_valid_block = exp_valid_block;
10819   w->cond_exp_valid_block = cond_exp_valid_block;
10820   if (just_location)
10821     {
10822       struct type *t = value_type (val.get ());
10823       CORE_ADDR addr = value_as_address (val.get ());
10824 
10825       w->exp_string_reparse
10826 	= current_language->watch_location_expression (t, addr).release ();
10827 
10828       w->exp_string = xstrprintf ("-location %.*s",
10829 				  (int) (exp_end - exp_start), exp_start);
10830     }
10831   else
10832     w->exp_string = savestring (exp_start, exp_end - exp_start);
10833 
10834   if (use_mask)
10835     {
10836       w->hw_wp_mask = mask;
10837     }
10838   else
10839     {
10840       w->val = val;
10841       w->val_bitpos = saved_bitpos;
10842       w->val_bitsize = saved_bitsize;
10843       w->val_valid = true;
10844     }
10845 
10846   if (cond_start)
10847     w->cond_string = savestring (cond_start, cond_end - cond_start);
10848   else
10849     w->cond_string = 0;
10850 
10851   if (frame_id_p (watchpoint_frame))
10852     {
10853       w->watchpoint_frame = watchpoint_frame;
10854       w->watchpoint_thread = inferior_ptid;
10855     }
10856   else
10857     {
10858       w->watchpoint_frame = null_frame_id;
10859       w->watchpoint_thread = null_ptid;
10860     }
10861 
10862   if (scope_breakpoint != NULL)
10863     {
10864       /* The scope breakpoint is related to the watchpoint.  We will
10865 	 need to act on them together.  */
10866       w->related_breakpoint = scope_breakpoint;
10867       scope_breakpoint->related_breakpoint = w.get ();
10868     }
10869 
10870   if (!just_location)
10871     value_free_to_mark (mark);
10872 
10873   /* Finally update the new watchpoint.  This creates the locations
10874      that should be inserted.  */
10875   update_watchpoint (w.get (), 1);
10876 
10877   install_breakpoint (internal, std::move (w), 1);
10878 }
10879 
10880 /* Return count of debug registers needed to watch the given expression.
10881    If the watchpoint cannot be handled in hardware return zero.  */
10882 
10883 static int
10884 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10885 {
10886   int found_memory_cnt = 0;
10887 
10888   /* Did the user specifically forbid us to use hardware watchpoints? */
10889   if (!can_use_hw_watchpoints)
10890     return 0;
10891 
10892   gdb_assert (!vals.empty ());
10893   struct value *head = vals[0].get ();
10894 
10895   /* Make sure that the value of the expression depends only upon
10896      memory contents, and values computed from them within GDB.  If we
10897      find any register references or function calls, we can't use a
10898      hardware watchpoint.
10899 
10900      The idea here is that evaluating an expression generates a series
10901      of values, one holding the value of every subexpression.  (The
10902      expression a*b+c has five subexpressions: a, b, a*b, c, and
10903      a*b+c.)  GDB's values hold almost enough information to establish
10904      the criteria given above --- they identify memory lvalues,
10905      register lvalues, computed values, etcetera.  So we can evaluate
10906      the expression, and then scan the chain of values that leaves
10907      behind to decide whether we can detect any possible change to the
10908      expression's final value using only hardware watchpoints.
10909 
10910      However, I don't think that the values returned by inferior
10911      function calls are special in any way.  So this function may not
10912      notice that an expression involving an inferior function call
10913      can't be watched with hardware watchpoints.  FIXME.  */
10914   for (const value_ref_ptr &iter : vals)
10915     {
10916       struct value *v = iter.get ();
10917 
10918       if (VALUE_LVAL (v) == lval_memory)
10919 	{
10920 	  if (v != head && value_lazy (v))
10921 	    /* A lazy memory lvalue in the chain is one that GDB never
10922 	       needed to fetch; we either just used its address (e.g.,
10923 	       `a' in `a.b') or we never needed it at all (e.g., `a'
10924 	       in `a,b').  This doesn't apply to HEAD; if that is
10925 	       lazy then it was not readable, but watch it anyway.  */
10926 	    ;
10927 	  else
10928 	    {
10929 	      /* Ahh, memory we actually used!  Check if we can cover
10930 		 it with hardware watchpoints.  */
10931 	      struct type *vtype = check_typedef (value_type (v));
10932 
10933 	      /* We only watch structs and arrays if user asked for it
10934 		 explicitly, never if they just happen to appear in a
10935 		 middle of some value chain.  */
10936 	      if (v == head
10937 		  || (vtype->code () != TYPE_CODE_STRUCT
10938 		      && vtype->code () != TYPE_CODE_ARRAY))
10939 		{
10940 		  CORE_ADDR vaddr = value_address (v);
10941 		  int len;
10942 		  int num_regs;
10943 
10944 		  len = (target_exact_watchpoints
10945 			 && is_scalar_type_recursive (vtype))?
10946 		    1 : TYPE_LENGTH (value_type (v));
10947 
10948 		  num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10949 		  if (!num_regs)
10950 		    return 0;
10951 		  else
10952 		    found_memory_cnt += num_regs;
10953 		}
10954 	    }
10955 	}
10956       else if (VALUE_LVAL (v) != not_lval
10957 	       && deprecated_value_modifiable (v) == 0)
10958 	return 0;	/* These are values from the history (e.g., $1).  */
10959       else if (VALUE_LVAL (v) == lval_register)
10960 	return 0;	/* Cannot watch a register with a HW watchpoint.  */
10961     }
10962 
10963   /* The expression itself looks suitable for using a hardware
10964      watchpoint, but give the target machine a chance to reject it.  */
10965   return found_memory_cnt;
10966 }
10967 
10968 void
10969 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10970 {
10971   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10972 }
10973 
10974 /* Options for the watch, awatch, and rwatch commands.  */
10975 
10976 struct watch_options
10977 {
10978   /* For -location.  */
10979   bool location = false;
10980 };
10981 
10982 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10983 
10984    Historically GDB always accepted both '-location' and '-l' flags for
10985    these commands (both flags being synonyms).  When converting to the
10986    newer option scheme only '-location' is added here.  That's fine (for
10987    backward compatibility) as any non-ambiguous prefix of a flag will be
10988    accepted, so '-l', '-loc', are now all accepted.
10989 
10990    What this means is that, if in the future, we add any new flag here
10991    that starts with '-l' then this will break backward compatibility, so
10992    please, don't do that!  */
10993 
10994 static const gdb::option::option_def watch_option_defs[] = {
10995   gdb::option::flag_option_def<watch_options> {
10996     "location",
10997     [] (watch_options *opt) { return &opt->location; },
10998     N_("\
10999 This evaluates EXPRESSION and watches the memory to which is refers.\n\
11000 -l can be used as a short form of -location."),
11001   },
11002 };
11003 
11004 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
11005    commands.  */
11006 
11007 static gdb::option::option_def_group
11008 make_watch_options_def_group (watch_options *opts)
11009 {
11010   return {{watch_option_defs}, opts};
11011 }
11012 
11013 /* A helper function that looks for the "-location" argument and then
11014    calls watch_command_1.  */
11015 
11016 static void
11017 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11018 {
11019   watch_options opts;
11020   auto grp = make_watch_options_def_group (&opts);
11021   gdb::option::process_options
11022     (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
11023   if (arg != nullptr && *arg == '\0')
11024     arg = nullptr;
11025 
11026   watch_command_1 (arg, accessflag, from_tty, opts.location, false);
11027 }
11028 
11029 /* Command completion for 'watch', 'awatch', and 'rwatch' commands.   */
11030 static void
11031 watch_command_completer (struct cmd_list_element *ignore,
11032 			 completion_tracker &tracker,
11033 			 const char *text, const char * /*word*/)
11034 {
11035   const auto group = make_watch_options_def_group (nullptr);
11036   if (gdb::option::complete_options
11037       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
11038     return;
11039 
11040   const char *word = advance_to_expression_complete_word_point (tracker, text);
11041   expression_completer (ignore, tracker, text, word);
11042 }
11043 
11044 static void
11045 watch_command (const char *arg, int from_tty)
11046 {
11047   watch_maybe_just_location (arg, hw_write, from_tty);
11048 }
11049 
11050 void
11051 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
11052 {
11053   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11054 }
11055 
11056 static void
11057 rwatch_command (const char *arg, int from_tty)
11058 {
11059   watch_maybe_just_location (arg, hw_read, from_tty);
11060 }
11061 
11062 void
11063 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
11064 {
11065   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11066 }
11067 
11068 static void
11069 awatch_command (const char *arg, int from_tty)
11070 {
11071   watch_maybe_just_location (arg, hw_access, from_tty);
11072 }
11073 
11074 
11075 /* Data for the FSM that manages the until(location)/advance commands
11076    in infcmd.c.  Here because it uses the mechanisms of
11077    breakpoints.  */
11078 
11079 struct until_break_fsm : public thread_fsm
11080 {
11081   /* The thread that was current when the command was executed.  */
11082   int thread;
11083 
11084   /* The breakpoint set at the return address in the caller frame,
11085      plus breakpoints at all the destination locations.  */
11086   std::vector<breakpoint_up> breakpoints;
11087 
11088   until_break_fsm (struct interp *cmd_interp, int thread,
11089 		   std::vector<breakpoint_up> &&breakpoints)
11090     : thread_fsm (cmd_interp),
11091       thread (thread),
11092       breakpoints (std::move (breakpoints))
11093   {
11094   }
11095 
11096   void clean_up (struct thread_info *thread) override;
11097   bool should_stop (struct thread_info *thread) override;
11098   enum async_reply_reason do_async_reply_reason () override;
11099 };
11100 
11101 /* Implementation of the 'should_stop' FSM method for the
11102    until(location)/advance commands.  */
11103 
11104 bool
11105 until_break_fsm::should_stop (struct thread_info *tp)
11106 {
11107   for (const breakpoint_up &bp : breakpoints)
11108     if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11109 				bp.get ()) != NULL)
11110       {
11111 	set_finished ();
11112 	break;
11113       }
11114 
11115   return true;
11116 }
11117 
11118 /* Implementation of the 'clean_up' FSM method for the
11119    until(location)/advance commands.  */
11120 
11121 void
11122 until_break_fsm::clean_up (struct thread_info *)
11123 {
11124   /* Clean up our temporary breakpoints.  */
11125   breakpoints.clear ();
11126   delete_longjmp_breakpoint (thread);
11127 }
11128 
11129 /* Implementation of the 'async_reply_reason' FSM method for the
11130    until(location)/advance commands.  */
11131 
11132 enum async_reply_reason
11133 until_break_fsm::do_async_reply_reason ()
11134 {
11135   return EXEC_ASYNC_LOCATION_REACHED;
11136 }
11137 
11138 void
11139 until_break_command (const char *arg, int from_tty, int anywhere)
11140 {
11141   struct frame_info *frame;
11142   struct gdbarch *frame_gdbarch;
11143   struct frame_id stack_frame_id;
11144   struct frame_id caller_frame_id;
11145   int thread;
11146   struct thread_info *tp;
11147 
11148   clear_proceed_status (0);
11149 
11150   /* Set a breakpoint where the user wants it and at return from
11151      this function.  */
11152 
11153   event_location_up location = string_to_event_location (&arg, current_language);
11154 
11155   std::vector<symtab_and_line> sals
11156     = (last_displayed_sal_is_valid ()
11157        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11158 			get_last_displayed_symtab (),
11159 			get_last_displayed_line ())
11160        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11161 			NULL, NULL, 0));
11162 
11163   if (sals.empty ())
11164     error (_("Couldn't get information on specified line."));
11165 
11166   if (*arg)
11167     error (_("Junk at end of arguments."));
11168 
11169   tp = inferior_thread ();
11170   thread = tp->global_num;
11171 
11172   /* Note linespec handling above invalidates the frame chain.
11173      Installing a breakpoint also invalidates the frame chain (as it
11174      may need to switch threads), so do any frame handling before
11175      that.  */
11176 
11177   frame = get_selected_frame (NULL);
11178   frame_gdbarch = get_frame_arch (frame);
11179   stack_frame_id = get_stack_frame_id (frame);
11180   caller_frame_id = frame_unwind_caller_id (frame);
11181 
11182   /* Keep within the current frame, or in frames called by the current
11183      one.  */
11184 
11185   std::vector<breakpoint_up> breakpoints;
11186 
11187   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
11188 
11189   if (frame_id_p (caller_frame_id))
11190     {
11191       struct symtab_and_line sal2;
11192       struct gdbarch *caller_gdbarch;
11193 
11194       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11195       sal2.pc = frame_unwind_caller_pc (frame);
11196       caller_gdbarch = frame_unwind_caller_arch (frame);
11197 
11198       breakpoint_up caller_breakpoint
11199 	= set_momentary_breakpoint (caller_gdbarch, sal2,
11200 				    caller_frame_id, bp_until);
11201       breakpoints.emplace_back (std::move (caller_breakpoint));
11202 
11203       set_longjmp_breakpoint (tp, caller_frame_id);
11204       lj_deleter.emplace (thread);
11205     }
11206 
11207   /* set_momentary_breakpoint could invalidate FRAME.  */
11208   frame = NULL;
11209 
11210   /* If the user told us to continue until a specified location, we
11211      don't specify a frame at which we need to stop.  Otherwise,
11212      specify the selected frame, because we want to stop only at the
11213      very same frame.  */
11214   frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
11215 
11216   for (symtab_and_line &sal : sals)
11217     {
11218       resolve_sal_pc (&sal);
11219 
11220       breakpoint_up location_breakpoint
11221 	= set_momentary_breakpoint (frame_gdbarch, sal,
11222 				    stop_frame_id, bp_until);
11223       breakpoints.emplace_back (std::move (location_breakpoint));
11224     }
11225 
11226   tp->thread_fsm = new until_break_fsm (command_interp (), tp->global_num,
11227 					std::move (breakpoints));
11228 
11229   if (lj_deleter)
11230     lj_deleter->release ();
11231 
11232   proceed (-1, GDB_SIGNAL_DEFAULT);
11233 }
11234 
11235 /* This function attempts to parse an optional "if <cond>" clause
11236    from the arg string.  If one is not found, it returns NULL.
11237 
11238    Else, it returns a pointer to the condition string.  (It does not
11239    attempt to evaluate the string against a particular block.)  And,
11240    it updates arg to point to the first character following the parsed
11241    if clause in the arg string.  */
11242 
11243 const char *
11244 ep_parse_optional_if_clause (const char **arg)
11245 {
11246   const char *cond_string;
11247 
11248   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11249     return NULL;
11250 
11251   /* Skip the "if" keyword.  */
11252   (*arg) += 2;
11253 
11254   /* Skip any extra leading whitespace, and record the start of the
11255      condition string.  */
11256   *arg = skip_spaces (*arg);
11257   cond_string = *arg;
11258 
11259   /* Assume that the condition occupies the remainder of the arg
11260      string.  */
11261   (*arg) += strlen (cond_string);
11262 
11263   return cond_string;
11264 }
11265 
11266 /* Commands to deal with catching events, such as signals, exceptions,
11267    process start/exit, etc.  */
11268 
11269 typedef enum
11270 {
11271   catch_fork_temporary, catch_vfork_temporary,
11272   catch_fork_permanent, catch_vfork_permanent
11273 }
11274 catch_fork_kind;
11275 
11276 static void
11277 catch_fork_command_1 (const char *arg, int from_tty,
11278 		      struct cmd_list_element *command)
11279 {
11280   struct gdbarch *gdbarch = get_current_arch ();
11281   const char *cond_string = NULL;
11282   catch_fork_kind fork_kind;
11283 
11284   fork_kind = (catch_fork_kind) (uintptr_t) command->context ();
11285   bool temp = (fork_kind == catch_fork_temporary
11286 	       || fork_kind == catch_vfork_temporary);
11287 
11288   if (!arg)
11289     arg = "";
11290   arg = skip_spaces (arg);
11291 
11292   /* The allowed syntax is:
11293      catch [v]fork
11294      catch [v]fork if <cond>
11295 
11296      First, check if there's an if clause.  */
11297   cond_string = ep_parse_optional_if_clause (&arg);
11298 
11299   if ((*arg != '\0') && !isspace (*arg))
11300     error (_("Junk at end of arguments."));
11301 
11302   /* If this target supports it, create a fork or vfork catchpoint
11303      and enable reporting of such events.  */
11304   switch (fork_kind)
11305     {
11306     case catch_fork_temporary:
11307     case catch_fork_permanent:
11308       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11309 					  &catch_fork_breakpoint_ops);
11310       break;
11311     case catch_vfork_temporary:
11312     case catch_vfork_permanent:
11313       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11314 					  &catch_vfork_breakpoint_ops);
11315       break;
11316     default:
11317       error (_("unsupported or unknown fork kind; cannot catch it"));
11318       break;
11319     }
11320 }
11321 
11322 static void
11323 catch_exec_command_1 (const char *arg, int from_tty,
11324 		      struct cmd_list_element *command)
11325 {
11326   struct gdbarch *gdbarch = get_current_arch ();
11327   const char *cond_string = NULL;
11328   bool temp = command->context () == CATCH_TEMPORARY;
11329 
11330   if (!arg)
11331     arg = "";
11332   arg = skip_spaces (arg);
11333 
11334   /* The allowed syntax is:
11335      catch exec
11336      catch exec if <cond>
11337 
11338      First, check if there's an if clause.  */
11339   cond_string = ep_parse_optional_if_clause (&arg);
11340 
11341   if ((*arg != '\0') && !isspace (*arg))
11342     error (_("Junk at end of arguments."));
11343 
11344   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11345   init_catchpoint (c.get (), gdbarch, temp, cond_string,
11346 		   &catch_exec_breakpoint_ops);
11347   c->exec_pathname = NULL;
11348 
11349   install_breakpoint (0, std::move (c), 1);
11350 }
11351 
11352 void
11353 init_ada_exception_breakpoint (struct breakpoint *b,
11354 			       struct gdbarch *gdbarch,
11355 			       struct symtab_and_line sal,
11356 			       const char *addr_string,
11357 			       const struct breakpoint_ops *ops,
11358 			       int tempflag,
11359 			       int enabled,
11360 			       int from_tty)
11361 {
11362   if (from_tty)
11363     {
11364       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11365       if (!loc_gdbarch)
11366 	loc_gdbarch = gdbarch;
11367 
11368       describe_other_breakpoints (loc_gdbarch,
11369 				  sal.pspace, sal.pc, sal.section, -1);
11370       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11371 	 version for exception catchpoints, because two catchpoints
11372 	 used for different exception names will use the same address.
11373 	 In this case, a "breakpoint ... also set at..." warning is
11374 	 unproductive.  Besides, the warning phrasing is also a bit
11375 	 inappropriate, we should use the word catchpoint, and tell
11376 	 the user what type of catchpoint it is.  The above is good
11377 	 enough for now, though.  */
11378     }
11379 
11380   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
11381 
11382   b->enable_state = enabled ? bp_enabled : bp_disabled;
11383   b->disposition = tempflag ? disp_del : disp_donttouch;
11384   b->location = string_to_event_location (&addr_string,
11385 					  language_def (language_ada));
11386   b->language = language_ada;
11387 }
11388 
11389 
11390 
11391 /* Compare two breakpoints and return a strcmp-like result.  */
11392 
11393 static int
11394 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11395 {
11396   uintptr_t ua = (uintptr_t) a;
11397   uintptr_t ub = (uintptr_t) b;
11398 
11399   if (a->number < b->number)
11400     return -1;
11401   else if (a->number > b->number)
11402     return 1;
11403 
11404   /* Now sort by address, in case we see, e..g, two breakpoints with
11405      the number 0.  */
11406   if (ua < ub)
11407     return -1;
11408   return ua > ub ? 1 : 0;
11409 }
11410 
11411 /* Delete breakpoints by address or line.  */
11412 
11413 static void
11414 clear_command (const char *arg, int from_tty)
11415 {
11416   int default_match;
11417 
11418   std::vector<symtab_and_line> decoded_sals;
11419   symtab_and_line last_sal;
11420   gdb::array_view<symtab_and_line> sals;
11421   if (arg)
11422     {
11423       decoded_sals
11424 	= decode_line_with_current_source (arg,
11425 					   (DECODE_LINE_FUNFIRSTLINE
11426 					    | DECODE_LINE_LIST_MODE));
11427       default_match = 0;
11428       sals = decoded_sals;
11429     }
11430   else
11431     {
11432       /* Set sal's line, symtab, pc, and pspace to the values
11433 	 corresponding to the last call to print_frame_info.  If the
11434 	 codepoint is not valid, this will set all the fields to 0.  */
11435       last_sal = get_last_displayed_sal ();
11436       if (last_sal.symtab == 0)
11437 	error (_("No source file specified."));
11438 
11439       default_match = 1;
11440       sals = last_sal;
11441     }
11442 
11443   /* We don't call resolve_sal_pc here.  That's not as bad as it
11444      seems, because all existing breakpoints typically have both
11445      file/line and pc set.  So, if clear is given file/line, we can
11446      match this to existing breakpoint without obtaining pc at all.
11447 
11448      We only support clearing given the address explicitly
11449      present in breakpoint table.  Say, we've set breakpoint
11450      at file:line.  There were several PC values for that file:line,
11451      due to optimization, all in one block.
11452 
11453      We've picked one PC value.  If "clear" is issued with another
11454      PC corresponding to the same file:line, the breakpoint won't
11455      be cleared.  We probably can still clear the breakpoint, but
11456      since the other PC value is never presented to user, user
11457      can only find it by guessing, and it does not seem important
11458      to support that.  */
11459 
11460   /* For each line spec given, delete bps which correspond to it.  Do
11461      it in two passes, solely to preserve the current behavior that
11462      from_tty is forced true if we delete more than one
11463      breakpoint.  */
11464 
11465   std::vector<struct breakpoint *> found;
11466   for (const auto &sal : sals)
11467     {
11468       const char *sal_fullname;
11469 
11470       /* If exact pc given, clear bpts at that pc.
11471 	 If line given (pc == 0), clear all bpts on specified line.
11472 	 If defaulting, clear all bpts on default line
11473 	 or at default pc.
11474 
11475 	 defaulting    sal.pc != 0    tests to do
11476 
11477 	 0              1             pc
11478 	 1              1             pc _and_ line
11479 	 0              0             line
11480 	 1              0             <can't happen> */
11481 
11482       sal_fullname = (sal.symtab == NULL
11483 		      ? NULL : symtab_to_fullname (sal.symtab));
11484 
11485       /* Find all matching breakpoints and add them to 'found'.  */
11486       for (breakpoint *b : all_breakpoints ())
11487 	{
11488 	  int match = 0;
11489 	  /* Are we going to delete b?  */
11490 	  if (b->type != bp_none && !is_watchpoint (b))
11491 	    {
11492 	      for (bp_location *loc : b->locations ())
11493 		{
11494 		  /* If the user specified file:line, don't allow a PC
11495 		     match.  This matches historical gdb behavior.  */
11496 		  int pc_match = (!sal.explicit_line
11497 				  && sal.pc
11498 				  && (loc->pspace == sal.pspace)
11499 				  && (loc->address == sal.pc)
11500 				  && (!section_is_overlay (loc->section)
11501 				      || loc->section == sal.section));
11502 		  int line_match = 0;
11503 
11504 		  if ((default_match || sal.explicit_line)
11505 		      && loc->symtab != NULL
11506 		      && sal_fullname != NULL
11507 		      && sal.pspace == loc->pspace
11508 		      && loc->line_number == sal.line
11509 		      && filename_cmp (symtab_to_fullname (loc->symtab),
11510 				       sal_fullname) == 0)
11511 		    line_match = 1;
11512 
11513 		  if (pc_match || line_match)
11514 		    {
11515 		      match = 1;
11516 		      break;
11517 		    }
11518 		}
11519 	    }
11520 
11521 	  if (match)
11522 	    found.push_back (b);
11523 	}
11524     }
11525 
11526   /* Now go thru the 'found' chain and delete them.  */
11527   if (found.empty ())
11528     {
11529       if (arg)
11530 	error (_("No breakpoint at %s."), arg);
11531       else
11532 	error (_("No breakpoint at this line."));
11533     }
11534 
11535   /* Remove duplicates from the vec.  */
11536   std::sort (found.begin (), found.end (),
11537 	     [] (const breakpoint *bp_a, const breakpoint *bp_b)
11538 	     {
11539 	       return compare_breakpoints (bp_a, bp_b) < 0;
11540 	     });
11541   found.erase (std::unique (found.begin (), found.end (),
11542 			    [] (const breakpoint *bp_a, const breakpoint *bp_b)
11543 			    {
11544 			      return compare_breakpoints (bp_a, bp_b) == 0;
11545 			    }),
11546 	       found.end ());
11547 
11548   if (found.size () > 1)
11549     from_tty = 1;	/* Always report if deleted more than one.  */
11550   if (from_tty)
11551     {
11552       if (found.size () == 1)
11553 	printf_unfiltered (_("Deleted breakpoint "));
11554       else
11555 	printf_unfiltered (_("Deleted breakpoints "));
11556     }
11557 
11558   for (breakpoint *iter : found)
11559     {
11560       if (from_tty)
11561 	printf_unfiltered ("%d ", iter->number);
11562       delete_breakpoint (iter);
11563     }
11564   if (from_tty)
11565     putchar_unfiltered ('\n');
11566 }
11567 
11568 /* Delete breakpoint in BS if they are `delete' breakpoints and
11569    all breakpoints that are marked for deletion, whether hit or not.
11570    This is called after any breakpoint is hit, or after errors.  */
11571 
11572 void
11573 breakpoint_auto_delete (bpstat bs)
11574 {
11575   for (; bs; bs = bs->next)
11576     if (bs->breakpoint_at
11577 	&& bs->breakpoint_at->disposition == disp_del
11578 	&& bs->stop)
11579       delete_breakpoint (bs->breakpoint_at);
11580 
11581   for (breakpoint *b : all_breakpoints_safe ())
11582     if (b->disposition == disp_del_at_next_stop)
11583       delete_breakpoint (b);
11584 }
11585 
11586 /* A comparison function for bp_location AP and BP being interfaced to
11587    std::sort.  Sort elements primarily by their ADDRESS (no matter what
11588    bl_address_is_meaningful says), secondarily by ordering first
11589    permanent elements and terciarily just ensuring the array is sorted
11590    stable way despite std::sort being an unstable algorithm.  */
11591 
11592 static int
11593 bp_location_is_less_than (const bp_location *a, const bp_location *b)
11594 {
11595   if (a->address != b->address)
11596     return a->address < b->address;
11597 
11598   /* Sort locations at the same address by their pspace number, keeping
11599      locations of the same inferior (in a multi-inferior environment)
11600      grouped.  */
11601 
11602   if (a->pspace->num != b->pspace->num)
11603     return a->pspace->num < b->pspace->num;
11604 
11605   /* Sort permanent breakpoints first.  */
11606   if (a->permanent != b->permanent)
11607     return a->permanent > b->permanent;
11608 
11609   /* Sort by type in order to make duplicate determination easier.
11610      See update_global_location_list.  This is kept in sync with
11611      breakpoint_locations_match.  */
11612   if (a->loc_type < b->loc_type)
11613     return true;
11614 
11615   /* Likewise, for range-breakpoints, sort by length.  */
11616   if (a->loc_type == bp_loc_hardware_breakpoint
11617       && b->loc_type == bp_loc_hardware_breakpoint
11618       && a->length < b->length)
11619     return true;
11620 
11621   /* Make the internal GDB representation stable across GDB runs
11622      where A and B memory inside GDB can differ.  Breakpoint locations of
11623      the same type at the same address can be sorted in arbitrary order.  */
11624 
11625   if (a->owner->number != b->owner->number)
11626     return a->owner->number < b->owner->number;
11627 
11628   return a < b;
11629 }
11630 
11631 /* Set bp_locations_placed_address_before_address_max and
11632    bp_locations_shadow_len_after_address_max according to the current
11633    content of the bp_locations array.  */
11634 
11635 static void
11636 bp_locations_target_extensions_update (void)
11637 {
11638   bp_locations_placed_address_before_address_max = 0;
11639   bp_locations_shadow_len_after_address_max = 0;
11640 
11641   for (bp_location *bl : all_bp_locations ())
11642     {
11643       CORE_ADDR start, end, addr;
11644 
11645       if (!bp_location_has_shadow (bl))
11646 	continue;
11647 
11648       start = bl->target_info.placed_address;
11649       end = start + bl->target_info.shadow_len;
11650 
11651       gdb_assert (bl->address >= start);
11652       addr = bl->address - start;
11653       if (addr > bp_locations_placed_address_before_address_max)
11654 	bp_locations_placed_address_before_address_max = addr;
11655 
11656       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11657 
11658       gdb_assert (bl->address < end);
11659       addr = end - bl->address;
11660       if (addr > bp_locations_shadow_len_after_address_max)
11661 	bp_locations_shadow_len_after_address_max = addr;
11662     }
11663 }
11664 
11665 /* Download tracepoint locations if they haven't been.  */
11666 
11667 static void
11668 download_tracepoint_locations (void)
11669 {
11670   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11671 
11672   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11673 
11674   for (breakpoint *b : all_tracepoints ())
11675     {
11676       struct tracepoint *t;
11677       int bp_location_downloaded = 0;
11678 
11679       if ((b->type == bp_fast_tracepoint
11680 	   ? !may_insert_fast_tracepoints
11681 	   : !may_insert_tracepoints))
11682 	continue;
11683 
11684       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11685 	{
11686 	  if (target_can_download_tracepoint ())
11687 	    can_download_tracepoint = TRIBOOL_TRUE;
11688 	  else
11689 	    can_download_tracepoint = TRIBOOL_FALSE;
11690 	}
11691 
11692       if (can_download_tracepoint == TRIBOOL_FALSE)
11693 	break;
11694 
11695       for (bp_location *bl : b->locations ())
11696 	{
11697 	  /* In tracepoint, locations are _never_ duplicated, so
11698 	     should_be_inserted is equivalent to
11699 	     unduplicated_should_be_inserted.  */
11700 	  if (!should_be_inserted (bl) || bl->inserted)
11701 	    continue;
11702 
11703 	  switch_to_program_space_and_thread (bl->pspace);
11704 
11705 	  target_download_tracepoint (bl);
11706 
11707 	  bl->inserted = 1;
11708 	  bp_location_downloaded = 1;
11709 	}
11710       t = (struct tracepoint *) b;
11711       t->number_on_target = b->number;
11712       if (bp_location_downloaded)
11713 	gdb::observers::breakpoint_modified.notify (b);
11714     }
11715 }
11716 
11717 /* Swap the insertion/duplication state between two locations.  */
11718 
11719 static void
11720 swap_insertion (struct bp_location *left, struct bp_location *right)
11721 {
11722   const int left_inserted = left->inserted;
11723   const int left_duplicate = left->duplicate;
11724   const int left_needs_update = left->needs_update;
11725   const struct bp_target_info left_target_info = left->target_info;
11726 
11727   /* Locations of tracepoints can never be duplicated.  */
11728   if (is_tracepoint (left->owner))
11729     gdb_assert (!left->duplicate);
11730   if (is_tracepoint (right->owner))
11731     gdb_assert (!right->duplicate);
11732 
11733   left->inserted = right->inserted;
11734   left->duplicate = right->duplicate;
11735   left->needs_update = right->needs_update;
11736   left->target_info = right->target_info;
11737   right->inserted = left_inserted;
11738   right->duplicate = left_duplicate;
11739   right->needs_update = left_needs_update;
11740   right->target_info = left_target_info;
11741 }
11742 
11743 /* Force the re-insertion of the locations at ADDRESS.  This is called
11744    once a new/deleted/modified duplicate location is found and we are evaluating
11745    conditions on the target's side.  Such conditions need to be updated on
11746    the target.  */
11747 
11748 static void
11749 force_breakpoint_reinsertion (struct bp_location *bl)
11750 {
11751   CORE_ADDR address = 0;
11752   int pspace_num;
11753 
11754   address = bl->address;
11755   pspace_num = bl->pspace->num;
11756 
11757   /* This is only meaningful if the target is
11758      evaluating conditions and if the user has
11759      opted for condition evaluation on the target's
11760      side.  */
11761   if (gdb_evaluates_breakpoint_condition_p ()
11762       || !target_supports_evaluation_of_breakpoint_conditions ())
11763     return;
11764 
11765   /* Flag all breakpoint locations with this address and
11766      the same program space as the location
11767      as "its condition has changed".  We need to
11768      update the conditions on the target's side.  */
11769   for (bp_location *loc : all_bp_locations_at_addr (address))
11770     {
11771       if (!is_breakpoint (loc->owner)
11772 	  || pspace_num != loc->pspace->num)
11773 	continue;
11774 
11775       /* Flag the location appropriately.  We use a different state to
11776 	 let everyone know that we already updated the set of locations
11777 	 with addr bl->address and program space bl->pspace.  This is so
11778 	 we don't have to keep calling these functions just to mark locations
11779 	 that have already been marked.  */
11780       loc->condition_changed = condition_updated;
11781 
11782       /* Free the agent expression bytecode as well.  We will compute
11783 	 it later on.  */
11784       loc->cond_bytecode.reset ();
11785     }
11786 }
11787 
11788 /* Called whether new breakpoints are created, or existing breakpoints
11789    deleted, to update the global location list and recompute which
11790    locations are duplicate of which.
11791 
11792    The INSERT_MODE flag determines whether locations may not, may, or
11793    shall be inserted now.  See 'enum ugll_insert_mode' for more
11794    info.  */
11795 
11796 static void
11797 update_global_location_list (enum ugll_insert_mode insert_mode)
11798 {
11799   /* Last breakpoint location address that was marked for update.  */
11800   CORE_ADDR last_addr = 0;
11801   /* Last breakpoint location program space that was marked for update.  */
11802   int last_pspace_num = -1;
11803 
11804   /* Used in the duplicates detection below.  When iterating over all
11805      bp_locations, points to the first bp_location of a given address.
11806      Breakpoints and watchpoints of different types are never
11807      duplicates of each other.  Keep one pointer for each type of
11808      breakpoint/watchpoint, so we only need to loop over all locations
11809      once.  */
11810   struct bp_location *bp_loc_first;  /* breakpoint */
11811   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11812   struct bp_location *awp_loc_first; /* access watchpoint */
11813   struct bp_location *rwp_loc_first; /* read watchpoint */
11814 
11815   /* Saved former bp_locations array which we compare against the newly
11816      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11817   std::vector<bp_location *> old_locations = std::move (bp_locations);
11818   bp_locations.clear ();
11819 
11820   for (breakpoint *b : all_breakpoints ())
11821     for (bp_location *loc : b->locations ())
11822       bp_locations.push_back (loc);
11823 
11824   /* See if we need to "upgrade" a software breakpoint to a hardware
11825      breakpoint.  Do this before deciding whether locations are
11826      duplicates.  Also do this before sorting because sorting order
11827      depends on location type.  */
11828   for (bp_location *loc : bp_locations)
11829     if (!loc->inserted && should_be_inserted (loc))
11830 	handle_automatic_hardware_breakpoints (loc);
11831 
11832   std::sort (bp_locations.begin (), bp_locations.end (),
11833 	     bp_location_is_less_than);
11834 
11835   bp_locations_target_extensions_update ();
11836 
11837   /* Identify bp_location instances that are no longer present in the
11838      new list, and therefore should be freed.  Note that it's not
11839      necessary that those locations should be removed from inferior --
11840      if there's another location at the same address (previously
11841      marked as duplicate), we don't need to remove/insert the
11842      location.
11843 
11844      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11845      and former bp_location array state respectively.  */
11846 
11847   size_t loc_i = 0;
11848   for (bp_location *old_loc : old_locations)
11849     {
11850       /* Tells if 'old_loc' is found among the new locations.  If
11851 	 not, we have to free it.  */
11852       int found_object = 0;
11853       /* Tells if the location should remain inserted in the target.  */
11854       int keep_in_target = 0;
11855       int removed = 0;
11856 
11857       /* Skip LOCP entries which will definitely never be needed.
11858 	 Stop either at or being the one matching OLD_LOC.  */
11859       while (loc_i < bp_locations.size ()
11860 	     && bp_locations[loc_i]->address < old_loc->address)
11861 	loc_i++;
11862 
11863       for (size_t loc2_i = loc_i;
11864 	   (loc2_i < bp_locations.size ()
11865 	    && bp_locations[loc2_i]->address == old_loc->address);
11866 	   loc2_i++)
11867 	{
11868 	  /* Check if this is a new/duplicated location or a duplicated
11869 	     location that had its condition modified.  If so, we want to send
11870 	     its condition to the target if evaluation of conditions is taking
11871 	     place there.  */
11872 	  if (bp_locations[loc2_i]->condition_changed == condition_modified
11873 	      && (last_addr != old_loc->address
11874 		  || last_pspace_num != old_loc->pspace->num))
11875 	    {
11876 	      force_breakpoint_reinsertion (bp_locations[loc2_i]);
11877 	      last_pspace_num = old_loc->pspace->num;
11878 	    }
11879 
11880 	  if (bp_locations[loc2_i] == old_loc)
11881 	    found_object = 1;
11882 	}
11883 
11884       /* We have already handled this address, update it so that we don't
11885 	 have to go through updates again.  */
11886       last_addr = old_loc->address;
11887 
11888       /* Target-side condition evaluation: Handle deleted locations.  */
11889       if (!found_object)
11890 	force_breakpoint_reinsertion (old_loc);
11891 
11892       /* If this location is no longer present, and inserted, look if
11893 	 there's maybe a new location at the same address.  If so,
11894 	 mark that one inserted, and don't remove this one.  This is
11895 	 needed so that we don't have a time window where a breakpoint
11896 	 at certain location is not inserted.  */
11897 
11898       if (old_loc->inserted)
11899 	{
11900 	  /* If the location is inserted now, we might have to remove
11901 	     it.  */
11902 
11903 	  if (found_object && should_be_inserted (old_loc))
11904 	    {
11905 	      /* The location is still present in the location list,
11906 		 and still should be inserted.  Don't do anything.  */
11907 	      keep_in_target = 1;
11908 	    }
11909 	  else
11910 	    {
11911 	      /* This location still exists, but it won't be kept in the
11912 		 target since it may have been disabled.  We proceed to
11913 		 remove its target-side condition.  */
11914 
11915 	      /* The location is either no longer present, or got
11916 		 disabled.  See if there's another location at the
11917 		 same address, in which case we don't need to remove
11918 		 this one from the target.  */
11919 
11920 	      /* OLD_LOC comes from existing struct breakpoint.  */
11921 	      if (bl_address_is_meaningful (old_loc))
11922 		{
11923 		  for (size_t loc2_i = loc_i;
11924 		       (loc2_i < bp_locations.size ()
11925 			&& bp_locations[loc2_i]->address == old_loc->address);
11926 		       loc2_i++)
11927 		    {
11928 		      bp_location *loc2 = bp_locations[loc2_i];
11929 
11930 		      if (loc2 == old_loc)
11931 			continue;
11932 
11933 		      if (breakpoint_locations_match (loc2, old_loc))
11934 			{
11935 			  /* Read watchpoint locations are switched to
11936 			     access watchpoints, if the former are not
11937 			     supported, but the latter are.  */
11938 			  if (is_hardware_watchpoint (old_loc->owner))
11939 			    {
11940 			      gdb_assert (is_hardware_watchpoint (loc2->owner));
11941 			      loc2->watchpoint_type = old_loc->watchpoint_type;
11942 			    }
11943 
11944 			  /* loc2 is a duplicated location. We need to check
11945 			     if it should be inserted in case it will be
11946 			     unduplicated.  */
11947 			  if (unduplicated_should_be_inserted (loc2))
11948 			    {
11949 			      swap_insertion (old_loc, loc2);
11950 			      keep_in_target = 1;
11951 			      break;
11952 			    }
11953 			}
11954 		    }
11955 		}
11956 	    }
11957 
11958 	  if (!keep_in_target)
11959 	    {
11960 	      if (remove_breakpoint (old_loc))
11961 		{
11962 		  /* This is just about all we can do.  We could keep
11963 		     this location on the global list, and try to
11964 		     remove it next time, but there's no particular
11965 		     reason why we will succeed next time.
11966 
11967 		     Note that at this point, old_loc->owner is still
11968 		     valid, as delete_breakpoint frees the breakpoint
11969 		     only after calling us.  */
11970 		  printf_filtered (_("warning: Error removing "
11971 				     "breakpoint %d\n"),
11972 				   old_loc->owner->number);
11973 		}
11974 	      removed = 1;
11975 	    }
11976 	}
11977 
11978       if (!found_object)
11979 	{
11980 	  if (removed && target_is_non_stop_p ()
11981 	      && need_moribund_for_location_type (old_loc))
11982 	    {
11983 	      /* This location was removed from the target.  In
11984 		 non-stop mode, a race condition is possible where
11985 		 we've removed a breakpoint, but stop events for that
11986 		 breakpoint are already queued and will arrive later.
11987 		 We apply an heuristic to be able to distinguish such
11988 		 SIGTRAPs from other random SIGTRAPs: we keep this
11989 		 breakpoint location for a bit, and will retire it
11990 		 after we see some number of events.  The theory here
11991 		 is that reporting of events should, "on the average",
11992 		 be fair, so after a while we'll see events from all
11993 		 threads that have anything of interest, and no longer
11994 		 need to keep this breakpoint location around.  We
11995 		 don't hold locations forever so to reduce chances of
11996 		 mistaking a non-breakpoint SIGTRAP for a breakpoint
11997 		 SIGTRAP.
11998 
11999 		 The heuristic failing can be disastrous on
12000 		 decr_pc_after_break targets.
12001 
12002 		 On decr_pc_after_break targets, like e.g., x86-linux,
12003 		 if we fail to recognize a late breakpoint SIGTRAP,
12004 		 because events_till_retirement has reached 0 too
12005 		 soon, we'll fail to do the PC adjustment, and report
12006 		 a random SIGTRAP to the user.  When the user resumes
12007 		 the inferior, it will most likely immediately crash
12008 		 with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12009 		 corrupted, because of being resumed e.g., in the
12010 		 middle of a multi-byte instruction, or skipped a
12011 		 one-byte instruction.  This was actually seen happen
12012 		 on native x86-linux, and should be less rare on
12013 		 targets that do not support new thread events, like
12014 		 remote, due to the heuristic depending on
12015 		 thread_count.
12016 
12017 		 Mistaking a random SIGTRAP for a breakpoint trap
12018 		 causes similar symptoms (PC adjustment applied when
12019 		 it shouldn't), but then again, playing with SIGTRAPs
12020 		 behind the debugger's back is asking for trouble.
12021 
12022 		 Since hardware watchpoint traps are always
12023 		 distinguishable from other traps, so we don't need to
12024 		 apply keep hardware watchpoint moribund locations
12025 		 around.  We simply always ignore hardware watchpoint
12026 		 traps we can no longer explain.  */
12027 
12028 	      process_stratum_target *proc_target = nullptr;
12029 	      for (inferior *inf : all_inferiors ())
12030 		if (inf->pspace == old_loc->pspace)
12031 		  {
12032 		    proc_target = inf->process_target ();
12033 		    break;
12034 		  }
12035 	      if (proc_target != nullptr)
12036 		old_loc->events_till_retirement
12037 		  = 3 * (thread_count (proc_target) + 1);
12038 	      else
12039 		old_loc->events_till_retirement = 1;
12040 	      old_loc->owner = NULL;
12041 
12042 	      moribund_locations.push_back (old_loc);
12043 	    }
12044 	  else
12045 	    {
12046 	      old_loc->owner = NULL;
12047 	      decref_bp_location (&old_loc);
12048 	    }
12049 	}
12050     }
12051 
12052   /* Rescan breakpoints at the same address and section, marking the
12053      first one as "first" and any others as "duplicates".  This is so
12054      that the bpt instruction is only inserted once.  If we have a
12055      permanent breakpoint at the same place as BPT, make that one the
12056      official one, and the rest as duplicates.  Permanent breakpoints
12057      are sorted first for the same address.
12058 
12059      Do the same for hardware watchpoints, but also considering the
12060      watchpoint's type (regular/access/read) and length.  */
12061 
12062   bp_loc_first = NULL;
12063   wp_loc_first = NULL;
12064   awp_loc_first = NULL;
12065   rwp_loc_first = NULL;
12066 
12067   for (bp_location *loc : all_bp_locations ())
12068     {
12069       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12070 	 non-NULL.  */
12071       struct bp_location **loc_first_p;
12072       breakpoint *b = loc->owner;
12073 
12074       if (!unduplicated_should_be_inserted (loc)
12075 	  || !bl_address_is_meaningful (loc)
12076 	  /* Don't detect duplicate for tracepoint locations because they are
12077 	   never duplicated.  See the comments in field `duplicate' of
12078 	   `struct bp_location'.  */
12079 	  || is_tracepoint (b))
12080 	{
12081 	  /* Clear the condition modification flag.  */
12082 	  loc->condition_changed = condition_unchanged;
12083 	  continue;
12084 	}
12085 
12086       if (b->type == bp_hardware_watchpoint)
12087 	loc_first_p = &wp_loc_first;
12088       else if (b->type == bp_read_watchpoint)
12089 	loc_first_p = &rwp_loc_first;
12090       else if (b->type == bp_access_watchpoint)
12091 	loc_first_p = &awp_loc_first;
12092       else
12093 	loc_first_p = &bp_loc_first;
12094 
12095       if (*loc_first_p == NULL
12096 	  || (overlay_debugging && loc->section != (*loc_first_p)->section)
12097 	  || !breakpoint_locations_match (loc, *loc_first_p))
12098 	{
12099 	  *loc_first_p = loc;
12100 	  loc->duplicate = 0;
12101 
12102 	  if (is_breakpoint (loc->owner) && loc->condition_changed)
12103 	    {
12104 	      loc->needs_update = 1;
12105 	      /* Clear the condition modification flag.  */
12106 	      loc->condition_changed = condition_unchanged;
12107 	    }
12108 	  continue;
12109 	}
12110 
12111 
12112       /* This and the above ensure the invariant that the first location
12113 	 is not duplicated, and is the inserted one.
12114 	 All following are marked as duplicated, and are not inserted.  */
12115       if (loc->inserted)
12116 	swap_insertion (loc, *loc_first_p);
12117       loc->duplicate = 1;
12118 
12119       /* Clear the condition modification flag.  */
12120       loc->condition_changed = condition_unchanged;
12121     }
12122 
12123   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12124     {
12125       if (insert_mode != UGLL_DONT_INSERT)
12126 	insert_breakpoint_locations ();
12127       else
12128 	{
12129 	  /* Even though the caller told us to not insert new
12130 	     locations, we may still need to update conditions on the
12131 	     target's side of breakpoints that were already inserted
12132 	     if the target is evaluating breakpoint conditions.  We
12133 	     only update conditions for locations that are marked
12134 	     "needs_update".  */
12135 	  update_inserted_breakpoint_locations ();
12136 	}
12137     }
12138 
12139   if (insert_mode != UGLL_DONT_INSERT)
12140     download_tracepoint_locations ();
12141 }
12142 
12143 void
12144 breakpoint_retire_moribund (void)
12145 {
12146   for (int ix = 0; ix < moribund_locations.size (); ++ix)
12147     {
12148       struct bp_location *loc = moribund_locations[ix];
12149       if (--(loc->events_till_retirement) == 0)
12150 	{
12151 	  decref_bp_location (&loc);
12152 	  unordered_remove (moribund_locations, ix);
12153 	  --ix;
12154 	}
12155     }
12156 }
12157 
12158 static void
12159 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12160 {
12161 
12162   try
12163     {
12164       update_global_location_list (insert_mode);
12165     }
12166   catch (const gdb_exception_error &e)
12167     {
12168     }
12169 }
12170 
12171 /* Clear BKP from a BPS.  */
12172 
12173 static void
12174 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12175 {
12176   bpstat bs;
12177 
12178   for (bs = bps; bs; bs = bs->next)
12179     if (bs->breakpoint_at == bpt)
12180       {
12181 	bs->breakpoint_at = NULL;
12182 	bs->old_val = NULL;
12183 	/* bs->commands will be freed later.  */
12184       }
12185 }
12186 
12187 /* Callback for iterate_over_threads.  */
12188 static int
12189 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12190 {
12191   struct breakpoint *bpt = (struct breakpoint *) data;
12192 
12193   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12194   return 0;
12195 }
12196 
12197 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12198    callbacks.  */
12199 
12200 static void
12201 say_where (struct breakpoint *b)
12202 {
12203   struct value_print_options opts;
12204 
12205   get_user_print_options (&opts);
12206 
12207   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12208      single string.  */
12209   if (b->loc == NULL)
12210     {
12211       /* For pending locations, the output differs slightly based
12212 	 on b->extra_string.  If this is non-NULL, it contains either
12213 	 a condition or dprintf arguments.  */
12214       if (b->extra_string == NULL)
12215 	{
12216 	  printf_filtered (_(" (%s) pending."),
12217 			   event_location_to_string (b->location.get ()));
12218 	}
12219       else if (b->type == bp_dprintf)
12220 	{
12221 	  printf_filtered (_(" (%s,%s) pending."),
12222 			   event_location_to_string (b->location.get ()),
12223 			   b->extra_string);
12224 	}
12225       else
12226 	{
12227 	  printf_filtered (_(" (%s %s) pending."),
12228 			   event_location_to_string (b->location.get ()),
12229 			   b->extra_string);
12230 	}
12231     }
12232   else
12233     {
12234       if (opts.addressprint || b->loc->symtab == NULL)
12235 	printf_filtered (" at %ps",
12236 			 styled_string (address_style.style (),
12237 					paddress (b->loc->gdbarch,
12238 						  b->loc->address)));
12239       if (b->loc->symtab != NULL)
12240 	{
12241 	  /* If there is a single location, we can print the location
12242 	     more nicely.  */
12243 	  if (b->loc->next == NULL)
12244 	    {
12245 	      const char *filename
12246 		= symtab_to_filename_for_display (b->loc->symtab);
12247 	      printf_filtered (": file %ps, line %d.",
12248 			       styled_string (file_name_style.style (),
12249 					      filename),
12250 			       b->loc->line_number);
12251 	    }
12252 	  else
12253 	    /* This is not ideal, but each location may have a
12254 	       different file name, and this at least reflects the
12255 	       real situation somewhat.  */
12256 	    printf_filtered (": %s.",
12257 			     event_location_to_string (b->location.get ()));
12258 	}
12259 
12260       if (b->loc->next)
12261 	{
12262 	  struct bp_location *loc = b->loc;
12263 	  int n = 0;
12264 	  for (; loc; loc = loc->next)
12265 	    ++n;
12266 	  printf_filtered (" (%d locations)", n);
12267 	}
12268     }
12269 }
12270 
12271 bp_location::~bp_location ()
12272 {
12273   xfree (function_name);
12274 }
12275 
12276 /* Destructor for the breakpoint base class.  */
12277 
12278 breakpoint::~breakpoint ()
12279 {
12280   xfree (this->cond_string);
12281   xfree (this->extra_string);
12282 }
12283 
12284 /* See breakpoint.h.  */
12285 
12286 bp_locations_range breakpoint::locations ()
12287 {
12288   return bp_locations_range (this->loc);
12289 }
12290 
12291 static struct bp_location *
12292 base_breakpoint_allocate_location (struct breakpoint *self)
12293 {
12294   return new bp_location (self);
12295 }
12296 
12297 static void
12298 base_breakpoint_re_set (struct breakpoint *b)
12299 {
12300   /* Nothing to re-set. */
12301 }
12302 
12303 #define internal_error_pure_virtual_called() \
12304   gdb_assert_not_reached ("pure virtual function called")
12305 
12306 static int
12307 base_breakpoint_insert_location (struct bp_location *bl)
12308 {
12309   internal_error_pure_virtual_called ();
12310 }
12311 
12312 static int
12313 base_breakpoint_remove_location (struct bp_location *bl,
12314 				 enum remove_bp_reason reason)
12315 {
12316   internal_error_pure_virtual_called ();
12317 }
12318 
12319 static int
12320 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12321 				const address_space *aspace,
12322 				CORE_ADDR bp_addr,
12323 				const struct target_waitstatus *ws)
12324 {
12325   internal_error_pure_virtual_called ();
12326 }
12327 
12328 static void
12329 base_breakpoint_check_status (bpstat bs)
12330 {
12331   /* Always stop.   */
12332 }
12333 
12334 /* A "works_in_software_mode" breakpoint_ops method that just internal
12335    errors.  */
12336 
12337 static int
12338 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12339 {
12340   internal_error_pure_virtual_called ();
12341 }
12342 
12343 /* A "resources_needed" breakpoint_ops method that just internal
12344    errors.  */
12345 
12346 static int
12347 base_breakpoint_resources_needed (const struct bp_location *bl)
12348 {
12349   internal_error_pure_virtual_called ();
12350 }
12351 
12352 static enum print_stop_action
12353 base_breakpoint_print_it (bpstat bs)
12354 {
12355   internal_error_pure_virtual_called ();
12356 }
12357 
12358 static void
12359 base_breakpoint_print_one_detail (const struct breakpoint *self,
12360 				  struct ui_out *uiout)
12361 {
12362   /* nothing */
12363 }
12364 
12365 static void
12366 base_breakpoint_print_mention (struct breakpoint *b)
12367 {
12368   internal_error_pure_virtual_called ();
12369 }
12370 
12371 static void
12372 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12373 {
12374   internal_error_pure_virtual_called ();
12375 }
12376 
12377 static void
12378 base_breakpoint_create_sals_from_location
12379   (struct event_location *location,
12380    struct linespec_result *canonical,
12381    enum bptype type_wanted)
12382 {
12383   internal_error_pure_virtual_called ();
12384 }
12385 
12386 static void
12387 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12388 					struct linespec_result *c,
12389 					gdb::unique_xmalloc_ptr<char> cond_string,
12390 					gdb::unique_xmalloc_ptr<char> extra_string,
12391 					enum bptype type_wanted,
12392 					enum bpdisp disposition,
12393 					int thread,
12394 					int task, int ignore_count,
12395 					const struct breakpoint_ops *o,
12396 					int from_tty, int enabled,
12397 					int internal, unsigned flags)
12398 {
12399   internal_error_pure_virtual_called ();
12400 }
12401 
12402 static std::vector<symtab_and_line>
12403 base_breakpoint_decode_location (struct breakpoint *b,
12404 				 struct event_location *location,
12405 				 struct program_space *search_pspace)
12406 {
12407   internal_error_pure_virtual_called ();
12408 }
12409 
12410 /* The default 'explains_signal' method.  */
12411 
12412 static int
12413 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12414 {
12415   return 1;
12416 }
12417 
12418 /* The default "after_condition_true" method.  */
12419 
12420 static void
12421 base_breakpoint_after_condition_true (struct bpstats *bs)
12422 {
12423   /* Nothing to do.   */
12424 }
12425 
12426 struct breakpoint_ops base_breakpoint_ops =
12427 {
12428   base_breakpoint_allocate_location,
12429   base_breakpoint_re_set,
12430   base_breakpoint_insert_location,
12431   base_breakpoint_remove_location,
12432   base_breakpoint_breakpoint_hit,
12433   base_breakpoint_check_status,
12434   base_breakpoint_resources_needed,
12435   base_breakpoint_works_in_software_mode,
12436   base_breakpoint_print_it,
12437   NULL,
12438   base_breakpoint_print_one_detail,
12439   base_breakpoint_print_mention,
12440   base_breakpoint_print_recreate,
12441   base_breakpoint_create_sals_from_location,
12442   base_breakpoint_create_breakpoints_sal,
12443   base_breakpoint_decode_location,
12444   base_breakpoint_explains_signal,
12445   base_breakpoint_after_condition_true,
12446 };
12447 
12448 /* Default breakpoint_ops methods.  */
12449 
12450 static void
12451 bkpt_re_set (struct breakpoint *b)
12452 {
12453   /* FIXME: is this still reachable?  */
12454   if (breakpoint_event_location_empty_p (b))
12455     {
12456       /* Anything without a location can't be re-set.  */
12457       delete_breakpoint (b);
12458       return;
12459     }
12460 
12461   breakpoint_re_set_default (b);
12462 }
12463 
12464 static int
12465 bkpt_insert_location (struct bp_location *bl)
12466 {
12467   CORE_ADDR addr = bl->target_info.reqstd_address;
12468 
12469   bl->target_info.kind = breakpoint_kind (bl, &addr);
12470   bl->target_info.placed_address = addr;
12471 
12472   if (bl->loc_type == bp_loc_hardware_breakpoint)
12473     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12474   else
12475     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12476 }
12477 
12478 static int
12479 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12480 {
12481   if (bl->loc_type == bp_loc_hardware_breakpoint)
12482     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12483   else
12484     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12485 }
12486 
12487 static int
12488 bkpt_breakpoint_hit (const struct bp_location *bl,
12489 		     const address_space *aspace, CORE_ADDR bp_addr,
12490 		     const struct target_waitstatus *ws)
12491 {
12492   if (ws->kind != TARGET_WAITKIND_STOPPED
12493       || ws->value.sig != GDB_SIGNAL_TRAP)
12494     return 0;
12495 
12496   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12497 				 aspace, bp_addr))
12498     return 0;
12499 
12500   if (overlay_debugging		/* unmapped overlay section */
12501       && section_is_overlay (bl->section)
12502       && !section_is_mapped (bl->section))
12503     return 0;
12504 
12505   return 1;
12506 }
12507 
12508 static int
12509 dprintf_breakpoint_hit (const struct bp_location *bl,
12510 			const address_space *aspace, CORE_ADDR bp_addr,
12511 			const struct target_waitstatus *ws)
12512 {
12513   if (dprintf_style == dprintf_style_agent
12514       && target_can_run_breakpoint_commands ())
12515     {
12516       /* An agent-style dprintf never causes a stop.  If we see a trap
12517 	 for this address it must be for a breakpoint that happens to
12518 	 be set at the same address.  */
12519       return 0;
12520     }
12521 
12522   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12523 }
12524 
12525 static int
12526 bkpt_resources_needed (const struct bp_location *bl)
12527 {
12528   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12529 
12530   return 1;
12531 }
12532 
12533 static enum print_stop_action
12534 bkpt_print_it (bpstat bs)
12535 {
12536   struct breakpoint *b;
12537   const struct bp_location *bl;
12538   int bp_temp;
12539   struct ui_out *uiout = current_uiout;
12540 
12541   gdb_assert (bs->bp_location_at != NULL);
12542 
12543   bl = bs->bp_location_at.get ();
12544   b = bs->breakpoint_at;
12545 
12546   bp_temp = b->disposition == disp_del;
12547   if (bl->address != bl->requested_address)
12548     breakpoint_adjustment_warning (bl->requested_address,
12549 				   bl->address,
12550 				   b->number, 1);
12551   annotate_breakpoint (b->number);
12552   maybe_print_thread_hit_breakpoint (uiout);
12553 
12554   if (uiout->is_mi_like_p ())
12555     {
12556       uiout->field_string ("reason",
12557 			   async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12558       uiout->field_string ("disp", bpdisp_text (b->disposition));
12559     }
12560   if (bp_temp)
12561     uiout->message ("Temporary breakpoint %pF, ",
12562 		    signed_field ("bkptno", b->number));
12563   else
12564     uiout->message ("Breakpoint %pF, ",
12565 		    signed_field ("bkptno", b->number));
12566 
12567   return PRINT_SRC_AND_LOC;
12568 }
12569 
12570 static void
12571 bkpt_print_mention (struct breakpoint *b)
12572 {
12573   if (current_uiout->is_mi_like_p ())
12574     return;
12575 
12576   switch (b->type)
12577     {
12578     case bp_breakpoint:
12579     case bp_gnu_ifunc_resolver:
12580       if (b->disposition == disp_del)
12581 	printf_filtered (_("Temporary breakpoint"));
12582       else
12583 	printf_filtered (_("Breakpoint"));
12584       printf_filtered (_(" %d"), b->number);
12585       if (b->type == bp_gnu_ifunc_resolver)
12586 	printf_filtered (_(" at gnu-indirect-function resolver"));
12587       break;
12588     case bp_hardware_breakpoint:
12589       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12590       break;
12591     case bp_dprintf:
12592       printf_filtered (_("Dprintf %d"), b->number);
12593       break;
12594     }
12595 
12596   say_where (b);
12597 }
12598 
12599 static void
12600 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12601 {
12602   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12603     fprintf_unfiltered (fp, "tbreak");
12604   else if (tp->type == bp_breakpoint)
12605     fprintf_unfiltered (fp, "break");
12606   else if (tp->type == bp_hardware_breakpoint
12607 	   && tp->disposition == disp_del)
12608     fprintf_unfiltered (fp, "thbreak");
12609   else if (tp->type == bp_hardware_breakpoint)
12610     fprintf_unfiltered (fp, "hbreak");
12611   else
12612     internal_error (__FILE__, __LINE__,
12613 		    _("unhandled breakpoint type %d"), (int) tp->type);
12614 
12615   fprintf_unfiltered (fp, " %s",
12616 		      event_location_to_string (tp->location.get ()));
12617 
12618   /* Print out extra_string if this breakpoint is pending.  It might
12619      contain, for example, conditions that were set by the user.  */
12620   if (tp->loc == NULL && tp->extra_string != NULL)
12621     fprintf_unfiltered (fp, " %s", tp->extra_string);
12622 
12623   print_recreate_thread (tp, fp);
12624 }
12625 
12626 static void
12627 bkpt_create_sals_from_location (struct event_location *location,
12628 				struct linespec_result *canonical,
12629 				enum bptype type_wanted)
12630 {
12631   create_sals_from_location_default (location, canonical, type_wanted);
12632 }
12633 
12634 static void
12635 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12636 			     struct linespec_result *canonical,
12637 			     gdb::unique_xmalloc_ptr<char> cond_string,
12638 			     gdb::unique_xmalloc_ptr<char> extra_string,
12639 			     enum bptype type_wanted,
12640 			     enum bpdisp disposition,
12641 			     int thread,
12642 			     int task, int ignore_count,
12643 			     const struct breakpoint_ops *ops,
12644 			     int from_tty, int enabled,
12645 			     int internal, unsigned flags)
12646 {
12647   create_breakpoints_sal_default (gdbarch, canonical,
12648 				  std::move (cond_string),
12649 				  std::move (extra_string),
12650 				  type_wanted,
12651 				  disposition, thread, task,
12652 				  ignore_count, ops, from_tty,
12653 				  enabled, internal, flags);
12654 }
12655 
12656 static std::vector<symtab_and_line>
12657 bkpt_decode_location (struct breakpoint *b,
12658 		      struct event_location *location,
12659 		      struct program_space *search_pspace)
12660 {
12661   return decode_location_default (b, location, search_pspace);
12662 }
12663 
12664 /* Virtual table for internal breakpoints.  */
12665 
12666 static void
12667 internal_bkpt_re_set (struct breakpoint *b)
12668 {
12669   switch (b->type)
12670     {
12671       /* Delete overlay event and longjmp master breakpoints; they
12672 	 will be reset later by breakpoint_re_set.  */
12673     case bp_overlay_event:
12674     case bp_longjmp_master:
12675     case bp_std_terminate_master:
12676     case bp_exception_master:
12677       delete_breakpoint (b);
12678       break;
12679 
12680       /* This breakpoint is special, it's set up when the inferior
12681 	 starts and we really don't want to touch it.  */
12682     case bp_shlib_event:
12683 
12684       /* Like bp_shlib_event, this breakpoint type is special.  Once
12685 	 it is set up, we do not want to touch it.  */
12686     case bp_thread_event:
12687       break;
12688     }
12689 }
12690 
12691 static void
12692 internal_bkpt_check_status (bpstat bs)
12693 {
12694   if (bs->breakpoint_at->type == bp_shlib_event)
12695     {
12696       /* If requested, stop when the dynamic linker notifies GDB of
12697 	 events.  This allows the user to get control and place
12698 	 breakpoints in initializer routines for dynamically loaded
12699 	 objects (among other things).  */
12700       bs->stop = stop_on_solib_events;
12701       bs->print = stop_on_solib_events;
12702     }
12703   else
12704     bs->stop = 0;
12705 }
12706 
12707 static enum print_stop_action
12708 internal_bkpt_print_it (bpstat bs)
12709 {
12710   struct breakpoint *b;
12711 
12712   b = bs->breakpoint_at;
12713 
12714   switch (b->type)
12715     {
12716     case bp_shlib_event:
12717       /* Did we stop because the user set the stop_on_solib_events
12718 	 variable?  (If so, we report this as a generic, "Stopped due
12719 	 to shlib event" message.) */
12720       print_solib_event (0);
12721       break;
12722 
12723     case bp_thread_event:
12724       /* Not sure how we will get here.
12725 	 GDB should not stop for these breakpoints.  */
12726       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12727       break;
12728 
12729     case bp_overlay_event:
12730       /* By analogy with the thread event, GDB should not stop for these.  */
12731       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12732       break;
12733 
12734     case bp_longjmp_master:
12735       /* These should never be enabled.  */
12736       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12737       break;
12738 
12739     case bp_std_terminate_master:
12740       /* These should never be enabled.  */
12741       printf_filtered (_("std::terminate Master Breakpoint: "
12742 			 "gdb should not stop!\n"));
12743       break;
12744 
12745     case bp_exception_master:
12746       /* These should never be enabled.  */
12747       printf_filtered (_("Exception Master Breakpoint: "
12748 			 "gdb should not stop!\n"));
12749       break;
12750     }
12751 
12752   return PRINT_NOTHING;
12753 }
12754 
12755 static void
12756 internal_bkpt_print_mention (struct breakpoint *b)
12757 {
12758   /* Nothing to mention.  These breakpoints are internal.  */
12759 }
12760 
12761 /* Virtual table for momentary breakpoints  */
12762 
12763 static void
12764 momentary_bkpt_re_set (struct breakpoint *b)
12765 {
12766   /* Keep temporary breakpoints, which can be encountered when we step
12767      over a dlopen call and solib_add is resetting the breakpoints.
12768      Otherwise these should have been blown away via the cleanup chain
12769      or by breakpoint_init_inferior when we rerun the executable.  */
12770 }
12771 
12772 static void
12773 momentary_bkpt_check_status (bpstat bs)
12774 {
12775   /* Nothing.  The point of these breakpoints is causing a stop.  */
12776 }
12777 
12778 static enum print_stop_action
12779 momentary_bkpt_print_it (bpstat bs)
12780 {
12781   return PRINT_UNKNOWN;
12782 }
12783 
12784 static void
12785 momentary_bkpt_print_mention (struct breakpoint *b)
12786 {
12787   /* Nothing to mention.  These breakpoints are internal.  */
12788 }
12789 
12790 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12791 
12792    It gets cleared already on the removal of the first one of such placed
12793    breakpoints.  This is OK as they get all removed altogether.  */
12794 
12795 longjmp_breakpoint::~longjmp_breakpoint ()
12796 {
12797   thread_info *tp = find_thread_global_id (this->thread);
12798 
12799   if (tp != NULL)
12800     tp->initiating_frame = null_frame_id;
12801 }
12802 
12803 /* Specific methods for probe breakpoints.  */
12804 
12805 static int
12806 bkpt_probe_insert_location (struct bp_location *bl)
12807 {
12808   int v = bkpt_insert_location (bl);
12809 
12810   if (v == 0)
12811     {
12812       /* The insertion was successful, now let's set the probe's semaphore
12813 	 if needed.  */
12814       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12815     }
12816 
12817   return v;
12818 }
12819 
12820 static int
12821 bkpt_probe_remove_location (struct bp_location *bl,
12822 			    enum remove_bp_reason reason)
12823 {
12824   /* Let's clear the semaphore before removing the location.  */
12825   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12826 
12827   return bkpt_remove_location (bl, reason);
12828 }
12829 
12830 static void
12831 bkpt_probe_create_sals_from_location (struct event_location *location,
12832 				      struct linespec_result *canonical,
12833 				      enum bptype type_wanted)
12834 {
12835   struct linespec_sals lsal;
12836 
12837   lsal.sals = parse_probes (location, NULL, canonical);
12838   lsal.canonical
12839     = xstrdup (event_location_to_string (canonical->location.get ()));
12840   canonical->lsals.push_back (std::move (lsal));
12841 }
12842 
12843 static std::vector<symtab_and_line>
12844 bkpt_probe_decode_location (struct breakpoint *b,
12845 			    struct event_location *location,
12846 			    struct program_space *search_pspace)
12847 {
12848   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12849   if (sals.empty ())
12850     error (_("probe not found"));
12851   return sals;
12852 }
12853 
12854 /* The breakpoint_ops structure to be used in tracepoints.  */
12855 
12856 static void
12857 tracepoint_re_set (struct breakpoint *b)
12858 {
12859   breakpoint_re_set_default (b);
12860 }
12861 
12862 static int
12863 tracepoint_breakpoint_hit (const struct bp_location *bl,
12864 			   const address_space *aspace, CORE_ADDR bp_addr,
12865 			   const struct target_waitstatus *ws)
12866 {
12867   /* By definition, the inferior does not report stops at
12868      tracepoints.  */
12869   return 0;
12870 }
12871 
12872 static void
12873 tracepoint_print_one_detail (const struct breakpoint *self,
12874 			     struct ui_out *uiout)
12875 {
12876   struct tracepoint *tp = (struct tracepoint *) self;
12877   if (!tp->static_trace_marker_id.empty ())
12878     {
12879       gdb_assert (self->type == bp_static_tracepoint);
12880 
12881       uiout->message ("\tmarker id is %pF\n",
12882 		      string_field ("static-tracepoint-marker-string-id",
12883 				    tp->static_trace_marker_id.c_str ()));
12884     }
12885 }
12886 
12887 static void
12888 tracepoint_print_mention (struct breakpoint *b)
12889 {
12890   if (current_uiout->is_mi_like_p ())
12891     return;
12892 
12893   switch (b->type)
12894     {
12895     case bp_tracepoint:
12896       printf_filtered (_("Tracepoint"));
12897       printf_filtered (_(" %d"), b->number);
12898       break;
12899     case bp_fast_tracepoint:
12900       printf_filtered (_("Fast tracepoint"));
12901       printf_filtered (_(" %d"), b->number);
12902       break;
12903     case bp_static_tracepoint:
12904       printf_filtered (_("Static tracepoint"));
12905       printf_filtered (_(" %d"), b->number);
12906       break;
12907     default:
12908       internal_error (__FILE__, __LINE__,
12909 		      _("unhandled tracepoint type %d"), (int) b->type);
12910     }
12911 
12912   say_where (b);
12913 }
12914 
12915 static void
12916 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12917 {
12918   struct tracepoint *tp = (struct tracepoint *) self;
12919 
12920   if (self->type == bp_fast_tracepoint)
12921     fprintf_unfiltered (fp, "ftrace");
12922   else if (self->type == bp_static_tracepoint)
12923     fprintf_unfiltered (fp, "strace");
12924   else if (self->type == bp_tracepoint)
12925     fprintf_unfiltered (fp, "trace");
12926   else
12927     internal_error (__FILE__, __LINE__,
12928 		    _("unhandled tracepoint type %d"), (int) self->type);
12929 
12930   fprintf_unfiltered (fp, " %s",
12931 		      event_location_to_string (self->location.get ()));
12932   print_recreate_thread (self, fp);
12933 
12934   if (tp->pass_count)
12935     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12936 }
12937 
12938 static void
12939 tracepoint_create_sals_from_location (struct event_location *location,
12940 				      struct linespec_result *canonical,
12941 				      enum bptype type_wanted)
12942 {
12943   create_sals_from_location_default (location, canonical, type_wanted);
12944 }
12945 
12946 static void
12947 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12948 				   struct linespec_result *canonical,
12949 				   gdb::unique_xmalloc_ptr<char> cond_string,
12950 				   gdb::unique_xmalloc_ptr<char> extra_string,
12951 				   enum bptype type_wanted,
12952 				   enum bpdisp disposition,
12953 				   int thread,
12954 				   int task, int ignore_count,
12955 				   const struct breakpoint_ops *ops,
12956 				   int from_tty, int enabled,
12957 				   int internal, unsigned flags)
12958 {
12959   create_breakpoints_sal_default (gdbarch, canonical,
12960 				  std::move (cond_string),
12961 				  std::move (extra_string),
12962 				  type_wanted,
12963 				  disposition, thread, task,
12964 				  ignore_count, ops, from_tty,
12965 				  enabled, internal, flags);
12966 }
12967 
12968 static std::vector<symtab_and_line>
12969 tracepoint_decode_location (struct breakpoint *b,
12970 			    struct event_location *location,
12971 			    struct program_space *search_pspace)
12972 {
12973   return decode_location_default (b, location, search_pspace);
12974 }
12975 
12976 struct breakpoint_ops tracepoint_breakpoint_ops;
12977 
12978 /* Virtual table for tracepoints on static probes.  */
12979 
12980 static void
12981 tracepoint_probe_create_sals_from_location
12982   (struct event_location *location,
12983    struct linespec_result *canonical,
12984    enum bptype type_wanted)
12985 {
12986   /* We use the same method for breakpoint on probes.  */
12987   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
12988 }
12989 
12990 static std::vector<symtab_and_line>
12991 tracepoint_probe_decode_location (struct breakpoint *b,
12992 				  struct event_location *location,
12993 				  struct program_space *search_pspace)
12994 {
12995   /* We use the same method for breakpoint on probes.  */
12996   return bkpt_probe_decode_location (b, location, search_pspace);
12997 }
12998 
12999 /* Dprintf breakpoint_ops methods.  */
13000 
13001 static void
13002 dprintf_re_set (struct breakpoint *b)
13003 {
13004   breakpoint_re_set_default (b);
13005 
13006   /* extra_string should never be non-NULL for dprintf.  */
13007   gdb_assert (b->extra_string != NULL);
13008 
13009   /* 1 - connect to target 1, that can run breakpoint commands.
13010      2 - create a dprintf, which resolves fine.
13011      3 - disconnect from target 1
13012      4 - connect to target 2, that can NOT run breakpoint commands.
13013 
13014      After steps #3/#4, you'll want the dprintf command list to
13015      be updated, because target 1 and 2 may well return different
13016      answers for target_can_run_breakpoint_commands().
13017      Given absence of finer grained resetting, we get to do
13018      it all the time.  */
13019   if (b->extra_string != NULL)
13020     update_dprintf_command_list (b);
13021 }
13022 
13023 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13024 
13025 static void
13026 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13027 {
13028   fprintf_unfiltered (fp, "dprintf %s,%s",
13029 		      event_location_to_string (tp->location.get ()),
13030 		      tp->extra_string);
13031   print_recreate_thread (tp, fp);
13032 }
13033 
13034 /* Implement the "after_condition_true" breakpoint_ops method for
13035    dprintf.
13036 
13037    dprintf's are implemented with regular commands in their command
13038    list, but we run the commands here instead of before presenting the
13039    stop to the user, as dprintf's don't actually cause a stop.  This
13040    also makes it so that the commands of multiple dprintfs at the same
13041    address are all handled.  */
13042 
13043 static void
13044 dprintf_after_condition_true (struct bpstats *bs)
13045 {
13046   struct bpstats tmp_bs;
13047   struct bpstats *tmp_bs_p = &tmp_bs;
13048 
13049   /* dprintf's never cause a stop.  This wasn't set in the
13050      check_status hook instead because that would make the dprintf's
13051      condition not be evaluated.  */
13052   bs->stop = 0;
13053 
13054   /* Run the command list here.  Take ownership of it instead of
13055      copying.  We never want these commands to run later in
13056      bpstat_do_actions, if a breakpoint that causes a stop happens to
13057      be set at same address as this dprintf, or even if running the
13058      commands here throws.  */
13059   tmp_bs.commands = bs->commands;
13060   bs->commands = NULL;
13061 
13062   bpstat_do_actions_1 (&tmp_bs_p);
13063 
13064   /* 'tmp_bs.commands' will usually be NULL by now, but
13065      bpstat_do_actions_1 may return early without processing the whole
13066      list.  */
13067 }
13068 
13069 /* The breakpoint_ops structure to be used on static tracepoints with
13070    markers (`-m').  */
13071 
13072 static void
13073 strace_marker_create_sals_from_location (struct event_location *location,
13074 					 struct linespec_result *canonical,
13075 					 enum bptype type_wanted)
13076 {
13077   struct linespec_sals lsal;
13078   const char *arg_start, *arg;
13079 
13080   arg = arg_start = get_linespec_location (location)->spec_string;
13081   lsal.sals = decode_static_tracepoint_spec (&arg);
13082 
13083   std::string str (arg_start, arg - arg_start);
13084   const char *ptr = str.c_str ();
13085   canonical->location
13086     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13087 
13088   lsal.canonical
13089     = xstrdup (event_location_to_string (canonical->location.get ()));
13090   canonical->lsals.push_back (std::move (lsal));
13091 }
13092 
13093 static void
13094 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13095 				      struct linespec_result *canonical,
13096 				      gdb::unique_xmalloc_ptr<char> cond_string,
13097 				      gdb::unique_xmalloc_ptr<char> extra_string,
13098 				      enum bptype type_wanted,
13099 				      enum bpdisp disposition,
13100 				      int thread,
13101 				      int task, int ignore_count,
13102 				      const struct breakpoint_ops *ops,
13103 				      int from_tty, int enabled,
13104 				      int internal, unsigned flags)
13105 {
13106   const linespec_sals &lsal = canonical->lsals[0];
13107 
13108   /* If the user is creating a static tracepoint by marker id
13109      (strace -m MARKER_ID), then store the sals index, so that
13110      breakpoint_re_set can try to match up which of the newly
13111      found markers corresponds to this one, and, don't try to
13112      expand multiple locations for each sal, given than SALS
13113      already should contain all sals for MARKER_ID.  */
13114 
13115   for (size_t i = 0; i < lsal.sals.size (); i++)
13116     {
13117       event_location_up location
13118 	= copy_event_location (canonical->location.get ());
13119 
13120       std::unique_ptr<tracepoint> tp (new tracepoint ());
13121       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13122 			   std::move (location), NULL,
13123 			   std::move (cond_string),
13124 			   std::move (extra_string),
13125 			   type_wanted, disposition,
13126 			   thread, task, ignore_count, ops,
13127 			   from_tty, enabled, internal, flags,
13128 			   canonical->special_display);
13129       /* Given that its possible to have multiple markers with
13130 	 the same string id, if the user is creating a static
13131 	 tracepoint by marker id ("strace -m MARKER_ID"), then
13132 	 store the sals index, so that breakpoint_re_set can
13133 	 try to match up which of the newly found markers
13134 	 corresponds to this one  */
13135       tp->static_trace_marker_id_idx = i;
13136 
13137       install_breakpoint (internal, std::move (tp), 0);
13138     }
13139 }
13140 
13141 static std::vector<symtab_and_line>
13142 strace_marker_decode_location (struct breakpoint *b,
13143 			       struct event_location *location,
13144 			       struct program_space *search_pspace)
13145 {
13146   struct tracepoint *tp = (struct tracepoint *) b;
13147   const char *s = get_linespec_location (location)->spec_string;
13148 
13149   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13150   if (sals.size () > tp->static_trace_marker_id_idx)
13151     {
13152       sals[0] = sals[tp->static_trace_marker_id_idx];
13153       sals.resize (1);
13154       return sals;
13155     }
13156   else
13157     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13158 }
13159 
13160 static struct breakpoint_ops strace_marker_breakpoint_ops;
13161 
13162 static int
13163 strace_marker_p (struct breakpoint *b)
13164 {
13165   return b->ops == &strace_marker_breakpoint_ops;
13166 }
13167 
13168 /* Delete a breakpoint and clean up all traces of it in the data
13169    structures.  */
13170 
13171 void
13172 delete_breakpoint (struct breakpoint *bpt)
13173 {
13174   gdb_assert (bpt != NULL);
13175 
13176   /* Has this bp already been deleted?  This can happen because
13177      multiple lists can hold pointers to bp's.  bpstat lists are
13178      especial culprits.
13179 
13180      One example of this happening is a watchpoint's scope bp.  When
13181      the scope bp triggers, we notice that the watchpoint is out of
13182      scope, and delete it.  We also delete its scope bp.  But the
13183      scope bp is marked "auto-deleting", and is already on a bpstat.
13184      That bpstat is then checked for auto-deleting bp's, which are
13185      deleted.
13186 
13187      A real solution to this problem might involve reference counts in
13188      bp's, and/or giving them pointers back to their referencing
13189      bpstat's, and teaching delete_breakpoint to only free a bp's
13190      storage when no more references were extent.  A cheaper bandaid
13191      was chosen.  */
13192   if (bpt->type == bp_none)
13193     return;
13194 
13195   /* At least avoid this stale reference until the reference counting
13196      of breakpoints gets resolved.  */
13197   if (bpt->related_breakpoint != bpt)
13198     {
13199       struct breakpoint *related;
13200       struct watchpoint *w;
13201 
13202       if (bpt->type == bp_watchpoint_scope)
13203 	w = (struct watchpoint *) bpt->related_breakpoint;
13204       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13205 	w = (struct watchpoint *) bpt;
13206       else
13207 	w = NULL;
13208       if (w != NULL)
13209 	watchpoint_del_at_next_stop (w);
13210 
13211       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13212       for (related = bpt; related->related_breakpoint != bpt;
13213 	   related = related->related_breakpoint);
13214       related->related_breakpoint = bpt->related_breakpoint;
13215       bpt->related_breakpoint = bpt;
13216     }
13217 
13218   /* watch_command_1 creates a watchpoint but only sets its number if
13219      update_watchpoint succeeds in creating its bp_locations.  If there's
13220      a problem in that process, we'll be asked to delete the half-created
13221      watchpoint.  In that case, don't announce the deletion.  */
13222   if (bpt->number)
13223     gdb::observers::breakpoint_deleted.notify (bpt);
13224 
13225   if (breakpoint_chain == bpt)
13226     breakpoint_chain = bpt->next;
13227 
13228   for (breakpoint *b : all_breakpoints ())
13229     if (b->next == bpt)
13230       {
13231 	b->next = bpt->next;
13232 	break;
13233       }
13234 
13235   /* Be sure no bpstat's are pointing at the breakpoint after it's
13236      been freed.  */
13237   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13238      in all threads for now.  Note that we cannot just remove bpstats
13239      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13240      commands are associated with the bpstat; if we remove it here,
13241      then the later call to bpstat_do_actions (&stop_bpstat); in
13242      event-top.c won't do anything, and temporary breakpoints with
13243      commands won't work.  */
13244 
13245   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13246 
13247   /* Now that breakpoint is removed from breakpoint list, update the
13248      global location list.  This will remove locations that used to
13249      belong to this breakpoint.  Do this before freeing the breakpoint
13250      itself, since remove_breakpoint looks at location's owner.  It
13251      might be better design to have location completely
13252      self-contained, but it's not the case now.  */
13253   update_global_location_list (UGLL_DONT_INSERT);
13254 
13255   /* On the chance that someone will soon try again to delete this
13256      same bp, we mark it as deleted before freeing its storage.  */
13257   bpt->type = bp_none;
13258   delete bpt;
13259 }
13260 
13261 /* Iterator function to call a user-provided callback function once
13262    for each of B and its related breakpoints.  */
13263 
13264 static void
13265 iterate_over_related_breakpoints (struct breakpoint *b,
13266 				  gdb::function_view<void (breakpoint *)> function)
13267 {
13268   struct breakpoint *related;
13269 
13270   related = b;
13271   do
13272     {
13273       struct breakpoint *next;
13274 
13275       /* FUNCTION may delete RELATED.  */
13276       next = related->related_breakpoint;
13277 
13278       if (next == related)
13279 	{
13280 	  /* RELATED is the last ring entry.  */
13281 	  function (related);
13282 
13283 	  /* FUNCTION may have deleted it, so we'd never reach back to
13284 	     B.  There's nothing left to do anyway, so just break
13285 	     out.  */
13286 	  break;
13287 	}
13288       else
13289 	function (related);
13290 
13291       related = next;
13292     }
13293   while (related != b);
13294 }
13295 
13296 static void
13297 delete_command (const char *arg, int from_tty)
13298 {
13299   dont_repeat ();
13300 
13301   if (arg == 0)
13302     {
13303       int breaks_to_delete = 0;
13304 
13305       /* Delete all breakpoints if no argument.  Do not delete
13306 	 internal breakpoints, these have to be deleted with an
13307 	 explicit breakpoint number argument.  */
13308       for (breakpoint *b : all_breakpoints ())
13309 	if (user_breakpoint_p (b))
13310 	  {
13311 	    breaks_to_delete = 1;
13312 	    break;
13313 	  }
13314 
13315       /* Ask user only if there are some breakpoints to delete.  */
13316       if (!from_tty
13317 	  || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13318 	for (breakpoint *b : all_breakpoints_safe ())
13319 	  if (user_breakpoint_p (b))
13320 	    delete_breakpoint (b);
13321     }
13322   else
13323     map_breakpoint_numbers
13324       (arg, [&] (breakpoint *br)
13325        {
13326 	 iterate_over_related_breakpoints (br, delete_breakpoint);
13327        });
13328 }
13329 
13330 /* Return true if all locations of B bound to PSPACE are pending.  If
13331    PSPACE is NULL, all locations of all program spaces are
13332    considered.  */
13333 
13334 static int
13335 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13336 {
13337   for (bp_location *loc : b->locations ())
13338     if ((pspace == NULL
13339 	 || loc->pspace == pspace)
13340 	&& !loc->shlib_disabled
13341 	&& !loc->pspace->executing_startup)
13342       return 0;
13343   return 1;
13344 }
13345 
13346 /* Subroutine of update_breakpoint_locations to simplify it.
13347    Return non-zero if multiple fns in list LOC have the same name.
13348    Null names are ignored.  */
13349 
13350 static int
13351 ambiguous_names_p (struct bp_location *loc)
13352 {
13353   struct bp_location *l;
13354   htab_up htab (htab_create_alloc (13, htab_hash_string, htab_eq_string, NULL,
13355 				   xcalloc, xfree));
13356 
13357   for (l = loc; l != NULL; l = l->next)
13358     {
13359       const char **slot;
13360       const char *name = l->function_name;
13361 
13362       /* Allow for some names to be NULL, ignore them.  */
13363       if (name == NULL)
13364 	continue;
13365 
13366       slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
13367 					     INSERT);
13368       /* NOTE: We can assume slot != NULL here because xcalloc never
13369 	 returns NULL.  */
13370       if (*slot != NULL)
13371 	return 1;
13372       *slot = name;
13373     }
13374 
13375   return 0;
13376 }
13377 
13378 /* When symbols change, it probably means the sources changed as well,
13379    and it might mean the static tracepoint markers are no longer at
13380    the same address or line numbers they used to be at last we
13381    checked.  Losing your static tracepoints whenever you rebuild is
13382    undesirable.  This function tries to resync/rematch gdb static
13383    tracepoints with the markers on the target, for static tracepoints
13384    that have not been set by marker id.  Static tracepoint that have
13385    been set by marker id are reset by marker id in breakpoint_re_set.
13386    The heuristic is:
13387 
13388    1) For a tracepoint set at a specific address, look for a marker at
13389    the old PC.  If one is found there, assume to be the same marker.
13390    If the name / string id of the marker found is different from the
13391    previous known name, assume that means the user renamed the marker
13392    in the sources, and output a warning.
13393 
13394    2) For a tracepoint set at a given line number, look for a marker
13395    at the new address of the old line number.  If one is found there,
13396    assume to be the same marker.  If the name / string id of the
13397    marker found is different from the previous known name, assume that
13398    means the user renamed the marker in the sources, and output a
13399    warning.
13400 
13401    3) If a marker is no longer found at the same address or line, it
13402    may mean the marker no longer exists.  But it may also just mean
13403    the code changed a bit.  Maybe the user added a few lines of code
13404    that made the marker move up or down (in line number terms).  Ask
13405    the target for info about the marker with the string id as we knew
13406    it.  If found, update line number and address in the matching
13407    static tracepoint.  This will get confused if there's more than one
13408    marker with the same ID (possible in UST, although unadvised
13409    precisely because it confuses tools).  */
13410 
13411 static struct symtab_and_line
13412 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13413 {
13414   struct tracepoint *tp = (struct tracepoint *) b;
13415   struct static_tracepoint_marker marker;
13416   CORE_ADDR pc;
13417 
13418   pc = sal.pc;
13419   if (sal.line)
13420     find_line_pc (sal.symtab, sal.line, &pc);
13421 
13422   if (target_static_tracepoint_marker_at (pc, &marker))
13423     {
13424       if (tp->static_trace_marker_id != marker.str_id)
13425 	warning (_("static tracepoint %d changed probed marker from %s to %s"),
13426 		 b->number, tp->static_trace_marker_id.c_str (),
13427 		 marker.str_id.c_str ());
13428 
13429       tp->static_trace_marker_id = std::move (marker.str_id);
13430 
13431       return sal;
13432     }
13433 
13434   /* Old marker wasn't found on target at lineno.  Try looking it up
13435      by string ID.  */
13436   if (!sal.explicit_pc
13437       && sal.line != 0
13438       && sal.symtab != NULL
13439       && !tp->static_trace_marker_id.empty ())
13440     {
13441       std::vector<static_tracepoint_marker> markers
13442 	= target_static_tracepoint_markers_by_strid
13443 	    (tp->static_trace_marker_id.c_str ());
13444 
13445       if (!markers.empty ())
13446 	{
13447 	  struct symbol *sym;
13448 	  struct static_tracepoint_marker *tpmarker;
13449 	  struct ui_out *uiout = current_uiout;
13450 	  struct explicit_location explicit_loc;
13451 
13452 	  tpmarker = &markers[0];
13453 
13454 	  tp->static_trace_marker_id = std::move (tpmarker->str_id);
13455 
13456 	  warning (_("marker for static tracepoint %d (%s) not "
13457 		     "found at previous line number"),
13458 		   b->number, tp->static_trace_marker_id.c_str ());
13459 
13460 	  symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13461 	  sym = find_pc_sect_function (tpmarker->address, NULL);
13462 	  uiout->text ("Now in ");
13463 	  if (sym)
13464 	    {
13465 	      uiout->field_string ("func", sym->print_name (),
13466 				   function_name_style.style ());
13467 	      uiout->text (" at ");
13468 	    }
13469 	  uiout->field_string ("file",
13470 			       symtab_to_filename_for_display (sal2.symtab),
13471 			       file_name_style.style ());
13472 	  uiout->text (":");
13473 
13474 	  if (uiout->is_mi_like_p ())
13475 	    {
13476 	      const char *fullname = symtab_to_fullname (sal2.symtab);
13477 
13478 	      uiout->field_string ("fullname", fullname);
13479 	    }
13480 
13481 	  uiout->field_signed ("line", sal2.line);
13482 	  uiout->text ("\n");
13483 
13484 	  b->loc->line_number = sal2.line;
13485 	  b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13486 
13487 	  b->location.reset (NULL);
13488 	  initialize_explicit_location (&explicit_loc);
13489 	  explicit_loc.source_filename
13490 	    = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13491 	  explicit_loc.line_offset.offset = b->loc->line_number;
13492 	  explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13493 	  b->location = new_explicit_location (&explicit_loc);
13494 
13495 	  /* Might be nice to check if function changed, and warn if
13496 	     so.  */
13497 	}
13498     }
13499   return sal;
13500 }
13501 
13502 /* Returns 1 iff locations A and B are sufficiently same that
13503    we don't need to report breakpoint as changed.  */
13504 
13505 static int
13506 locations_are_equal (struct bp_location *a, struct bp_location *b)
13507 {
13508   while (a && b)
13509     {
13510       if (a->address != b->address)
13511 	return 0;
13512 
13513       if (a->shlib_disabled != b->shlib_disabled)
13514 	return 0;
13515 
13516       if (a->enabled != b->enabled)
13517 	return 0;
13518 
13519       if (a->disabled_by_cond != b->disabled_by_cond)
13520 	return 0;
13521 
13522       a = a->next;
13523       b = b->next;
13524     }
13525 
13526   if ((a == NULL) != (b == NULL))
13527     return 0;
13528 
13529   return 1;
13530 }
13531 
13532 /* Split all locations of B that are bound to PSPACE out of B's
13533    location list to a separate list and return that list's head.  If
13534    PSPACE is NULL, hoist out all locations of B.  */
13535 
13536 static struct bp_location *
13537 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13538 {
13539   struct bp_location head;
13540   struct bp_location *i = b->loc;
13541   struct bp_location **i_link = &b->loc;
13542   struct bp_location *hoisted = &head;
13543 
13544   if (pspace == NULL)
13545     {
13546       i = b->loc;
13547       b->loc = NULL;
13548       return i;
13549     }
13550 
13551   head.next = NULL;
13552 
13553   while (i != NULL)
13554     {
13555       if (i->pspace == pspace)
13556 	{
13557 	  *i_link = i->next;
13558 	  i->next = NULL;
13559 	  hoisted->next = i;
13560 	  hoisted = i;
13561 	}
13562       else
13563 	i_link = &i->next;
13564       i = *i_link;
13565     }
13566 
13567   return head.next;
13568 }
13569 
13570 /* Create new breakpoint locations for B (a hardware or software
13571    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13572    zero, then B is a ranged breakpoint.  Only recreates locations for
13573    FILTER_PSPACE.  Locations of other program spaces are left
13574    untouched.  */
13575 
13576 void
13577 update_breakpoint_locations (struct breakpoint *b,
13578 			     struct program_space *filter_pspace,
13579 			     gdb::array_view<const symtab_and_line> sals,
13580 			     gdb::array_view<const symtab_and_line> sals_end)
13581 {
13582   struct bp_location *existing_locations;
13583 
13584   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13585     {
13586       /* Ranged breakpoints have only one start location and one end
13587 	 location.  */
13588       b->enable_state = bp_disabled;
13589       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13590 			   "multiple locations found\n"),
13591 			 b->number);
13592       return;
13593     }
13594 
13595   /* If there's no new locations, and all existing locations are
13596      pending, don't do anything.  This optimizes the common case where
13597      all locations are in the same shared library, that was unloaded.
13598      We'd like to retain the location, so that when the library is
13599      loaded again, we don't loose the enabled/disabled status of the
13600      individual locations.  */
13601   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13602     return;
13603 
13604   existing_locations = hoist_existing_locations (b, filter_pspace);
13605 
13606   for (const auto &sal : sals)
13607     {
13608       struct bp_location *new_loc;
13609 
13610       switch_to_program_space_and_thread (sal.pspace);
13611 
13612       new_loc = add_location_to_breakpoint (b, &sal);
13613 
13614       /* Reparse conditions, they might contain references to the
13615 	 old symtab.  */
13616       if (b->cond_string != NULL)
13617 	{
13618 	  const char *s;
13619 
13620 	  s = b->cond_string;
13621 	  try
13622 	    {
13623 	      new_loc->cond = parse_exp_1 (&s, sal.pc,
13624 					   block_for_pc (sal.pc),
13625 					   0);
13626 	    }
13627 	  catch (const gdb_exception_error &e)
13628 	    {
13629 	      new_loc->disabled_by_cond = true;
13630 	    }
13631 	}
13632 
13633       if (!sals_end.empty ())
13634 	{
13635 	  CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13636 
13637 	  new_loc->length = end - sals[0].pc + 1;
13638 	}
13639     }
13640 
13641   /* If possible, carry over 'disable' status from existing
13642      breakpoints.  */
13643   {
13644     struct bp_location *e = existing_locations;
13645     /* If there are multiple breakpoints with the same function name,
13646        e.g. for inline functions, comparing function names won't work.
13647        Instead compare pc addresses; this is just a heuristic as things
13648        may have moved, but in practice it gives the correct answer
13649        often enough until a better solution is found.  */
13650     int have_ambiguous_names = ambiguous_names_p (b->loc);
13651 
13652     for (; e; e = e->next)
13653       {
13654 	if ((!e->enabled || e->disabled_by_cond) && e->function_name)
13655 	  {
13656 	    if (have_ambiguous_names)
13657 	      {
13658 		for (bp_location *l : b->locations ())
13659 		  {
13660 		    /* Ignore software vs hardware location type at
13661 		       this point, because with "set breakpoint
13662 		       auto-hw", after a re-set, locations that were
13663 		       hardware can end up as software, or vice versa.
13664 		       As mentioned above, this is an heuristic and in
13665 		       practice should give the correct answer often
13666 		       enough.  */
13667 		    if (breakpoint_locations_match (e, l, true))
13668 		      {
13669 			l->enabled = e->enabled;
13670 			l->disabled_by_cond = e->disabled_by_cond;
13671 			break;
13672 		      }
13673 		  }
13674 	      }
13675 	    else
13676 	      {
13677 		for (bp_location *l : b->locations ())
13678 		  if (l->function_name
13679 		      && strcmp (e->function_name, l->function_name) == 0)
13680 		    {
13681 		      l->enabled = e->enabled;
13682 		      l->disabled_by_cond = e->disabled_by_cond;
13683 		      break;
13684 		    }
13685 	      }
13686 	  }
13687       }
13688   }
13689 
13690   if (!locations_are_equal (existing_locations, b->loc))
13691     gdb::observers::breakpoint_modified.notify (b);
13692 }
13693 
13694 /* Find the SaL locations corresponding to the given LOCATION.
13695    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13696 
13697 static std::vector<symtab_and_line>
13698 location_to_sals (struct breakpoint *b, struct event_location *location,
13699 		  struct program_space *search_pspace, int *found)
13700 {
13701   struct gdb_exception exception;
13702 
13703   gdb_assert (b->ops != NULL);
13704 
13705   std::vector<symtab_and_line> sals;
13706 
13707   try
13708     {
13709       sals = b->ops->decode_location (b, location, search_pspace);
13710     }
13711   catch (gdb_exception_error &e)
13712     {
13713       int not_found_and_ok = 0;
13714 
13715       /* For pending breakpoints, it's expected that parsing will
13716 	 fail until the right shared library is loaded.  User has
13717 	 already told to create pending breakpoints and don't need
13718 	 extra messages.  If breakpoint is in bp_shlib_disabled
13719 	 state, then user already saw the message about that
13720 	 breakpoint being disabled, and don't want to see more
13721 	 errors.  */
13722       if (e.error == NOT_FOUND_ERROR
13723 	  && (b->condition_not_parsed
13724 	      || (b->loc != NULL
13725 		  && search_pspace != NULL
13726 		  && b->loc->pspace != search_pspace)
13727 	      || (b->loc && b->loc->shlib_disabled)
13728 	      || (b->loc && b->loc->pspace->executing_startup)
13729 	      || b->enable_state == bp_disabled))
13730 	not_found_and_ok = 1;
13731 
13732       if (!not_found_and_ok)
13733 	{
13734 	  /* We surely don't want to warn about the same breakpoint
13735 	     10 times.  One solution, implemented here, is disable
13736 	     the breakpoint on error.  Another solution would be to
13737 	     have separate 'warning emitted' flag.  Since this
13738 	     happens only when a binary has changed, I don't know
13739 	     which approach is better.  */
13740 	  b->enable_state = bp_disabled;
13741 	  throw;
13742 	}
13743 
13744       exception = std::move (e);
13745     }
13746 
13747   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13748     {
13749       for (auto &sal : sals)
13750 	resolve_sal_pc (&sal);
13751       if (b->condition_not_parsed && b->extra_string != NULL)
13752 	{
13753 	  char *cond_string, *extra_string;
13754 	  int thread, task;
13755 
13756 	  find_condition_and_thread_for_sals (sals, b->extra_string,
13757 					      &cond_string, &thread,
13758 					      &task, &extra_string);
13759 	  gdb_assert (b->cond_string == NULL);
13760 	  if (cond_string)
13761 	    b->cond_string = cond_string;
13762 	  b->thread = thread;
13763 	  b->task = task;
13764 	  if (extra_string)
13765 	    {
13766 	      xfree (b->extra_string);
13767 	      b->extra_string = extra_string;
13768 	    }
13769 	  b->condition_not_parsed = 0;
13770 	}
13771 
13772       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13773 	sals[0] = update_static_tracepoint (b, sals[0]);
13774 
13775       *found = 1;
13776     }
13777   else
13778     *found = 0;
13779 
13780   return sals;
13781 }
13782 
13783 /* The default re_set method, for typical hardware or software
13784    breakpoints.  Reevaluate the breakpoint and recreate its
13785    locations.  */
13786 
13787 static void
13788 breakpoint_re_set_default (struct breakpoint *b)
13789 {
13790   struct program_space *filter_pspace = current_program_space;
13791   std::vector<symtab_and_line> expanded, expanded_end;
13792 
13793   int found;
13794   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13795 							filter_pspace, &found);
13796   if (found)
13797     expanded = std::move (sals);
13798 
13799   if (b->location_range_end != NULL)
13800     {
13801       std::vector<symtab_and_line> sals_end
13802 	= location_to_sals (b, b->location_range_end.get (),
13803 			    filter_pspace, &found);
13804       if (found)
13805 	expanded_end = std::move (sals_end);
13806     }
13807 
13808   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13809 }
13810 
13811 /* Default method for creating SALs from an address string.  It basically
13812    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13813 
13814 static void
13815 create_sals_from_location_default (struct event_location *location,
13816 				   struct linespec_result *canonical,
13817 				   enum bptype type_wanted)
13818 {
13819   parse_breakpoint_sals (location, canonical);
13820 }
13821 
13822 /* Call create_breakpoints_sal for the given arguments.  This is the default
13823    function for the `create_breakpoints_sal' method of
13824    breakpoint_ops.  */
13825 
13826 static void
13827 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13828 				struct linespec_result *canonical,
13829 				gdb::unique_xmalloc_ptr<char> cond_string,
13830 				gdb::unique_xmalloc_ptr<char> extra_string,
13831 				enum bptype type_wanted,
13832 				enum bpdisp disposition,
13833 				int thread,
13834 				int task, int ignore_count,
13835 				const struct breakpoint_ops *ops,
13836 				int from_tty, int enabled,
13837 				int internal, unsigned flags)
13838 {
13839   create_breakpoints_sal (gdbarch, canonical,
13840 			  std::move (cond_string),
13841 			  std::move (extra_string),
13842 			  type_wanted, disposition,
13843 			  thread, task, ignore_count, ops, from_tty,
13844 			  enabled, internal, flags);
13845 }
13846 
13847 /* Decode the line represented by S by calling decode_line_full.  This is the
13848    default function for the `decode_location' method of breakpoint_ops.  */
13849 
13850 static std::vector<symtab_and_line>
13851 decode_location_default (struct breakpoint *b,
13852 			 struct event_location *location,
13853 			 struct program_space *search_pspace)
13854 {
13855   struct linespec_result canonical;
13856 
13857   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13858 		    NULL, 0, &canonical, multiple_symbols_all,
13859 		    b->filter.get ());
13860 
13861   /* We should get 0 or 1 resulting SALs.  */
13862   gdb_assert (canonical.lsals.size () < 2);
13863 
13864   if (!canonical.lsals.empty ())
13865     {
13866       const linespec_sals &lsal = canonical.lsals[0];
13867       return std::move (lsal.sals);
13868     }
13869   return {};
13870 }
13871 
13872 /* Reset a breakpoint.  */
13873 
13874 static void
13875 breakpoint_re_set_one (breakpoint *b)
13876 {
13877   input_radix = b->input_radix;
13878   set_language (b->language);
13879 
13880   b->ops->re_set (b);
13881 }
13882 
13883 /* Re-set breakpoint locations for the current program space.
13884    Locations bound to other program spaces are left untouched.  */
13885 
13886 void
13887 breakpoint_re_set (void)
13888 {
13889   {
13890     scoped_restore_current_language save_language;
13891     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13892     scoped_restore_current_pspace_and_thread restore_pspace_thread;
13893 
13894     /* breakpoint_re_set_one sets the current_language to the language
13895        of the breakpoint it is resetting (see prepare_re_set_context)
13896        before re-evaluating the breakpoint's location.  This change can
13897        unfortunately get undone by accident if the language_mode is set
13898        to auto, and we either switch frames, or more likely in this context,
13899        we select the current frame.
13900 
13901        We prevent this by temporarily turning the language_mode to
13902        language_mode_manual.  We restore it once all breakpoints
13903        have been reset.  */
13904     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13905     language_mode = language_mode_manual;
13906 
13907     /* Note: we must not try to insert locations until after all
13908        breakpoints have been re-set.  Otherwise, e.g., when re-setting
13909        breakpoint 1, we'd insert the locations of breakpoint 2, which
13910        hadn't been re-set yet, and thus may have stale locations.  */
13911 
13912     for (breakpoint *b : all_breakpoints_safe ())
13913       {
13914 	try
13915 	  {
13916 	    breakpoint_re_set_one (b);
13917 	  }
13918 	catch (const gdb_exception &ex)
13919 	  {
13920 	    exception_fprintf (gdb_stderr, ex,
13921 			       "Error in re-setting breakpoint %d: ",
13922 			       b->number);
13923 	  }
13924       }
13925 
13926     jit_breakpoint_re_set ();
13927   }
13928 
13929   create_overlay_event_breakpoint ();
13930   create_longjmp_master_breakpoint ();
13931   create_std_terminate_master_breakpoint ();
13932   create_exception_master_breakpoint ();
13933 
13934   /* Now we can insert.  */
13935   update_global_location_list (UGLL_MAY_INSERT);
13936 }
13937 
13938 /* Reset the thread number of this breakpoint:
13939 
13940    - If the breakpoint is for all threads, leave it as-is.
13941    - Else, reset it to the current thread for inferior_ptid.  */
13942 void
13943 breakpoint_re_set_thread (struct breakpoint *b)
13944 {
13945   if (b->thread != -1)
13946     {
13947       b->thread = inferior_thread ()->global_num;
13948 
13949       /* We're being called after following a fork.  The new fork is
13950 	 selected as current, and unless this was a vfork will have a
13951 	 different program space from the original thread.  Reset that
13952 	 as well.  */
13953       b->loc->pspace = current_program_space;
13954     }
13955 }
13956 
13957 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13958    If from_tty is nonzero, it prints a message to that effect,
13959    which ends with a period (no newline).  */
13960 
13961 void
13962 set_ignore_count (int bptnum, int count, int from_tty)
13963 {
13964   if (count < 0)
13965     count = 0;
13966 
13967   for (breakpoint *b : all_breakpoints ())
13968     if (b->number == bptnum)
13969       {
13970 	if (is_tracepoint (b))
13971 	  {
13972 	    if (from_tty && count != 0)
13973 	      printf_filtered (_("Ignore count ignored for tracepoint %d."),
13974 			       bptnum);
13975 	    return;
13976 	  }
13977 
13978 	b->ignore_count = count;
13979 	if (from_tty)
13980 	  {
13981 	    if (count == 0)
13982 	      printf_filtered (_("Will stop next time "
13983 				 "breakpoint %d is reached."),
13984 			       bptnum);
13985 	    else if (count == 1)
13986 	      printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13987 			       bptnum);
13988 	    else
13989 	      printf_filtered (_("Will ignore next %d "
13990 				 "crossings of breakpoint %d."),
13991 			       count, bptnum);
13992 	  }
13993 	gdb::observers::breakpoint_modified.notify (b);
13994 	return;
13995       }
13996 
13997   error (_("No breakpoint number %d."), bptnum);
13998 }
13999 
14000 /* Command to set ignore-count of breakpoint N to COUNT.  */
14001 
14002 static void
14003 ignore_command (const char *args, int from_tty)
14004 {
14005   const char *p = args;
14006   int num;
14007 
14008   if (p == 0)
14009     error_no_arg (_("a breakpoint number"));
14010 
14011   num = get_number (&p);
14012   if (num == 0)
14013     error (_("bad breakpoint number: '%s'"), args);
14014   if (*p == 0)
14015     error (_("Second argument (specified ignore-count) is missing."));
14016 
14017   set_ignore_count (num,
14018 		    longest_to_int (value_as_long (parse_and_eval (p))),
14019 		    from_tty);
14020   if (from_tty)
14021     printf_filtered ("\n");
14022 }
14023 
14024 
14025 /* Call FUNCTION on each of the breakpoints with numbers in the range
14026    defined by BP_NUM_RANGE (an inclusive range).  */
14027 
14028 static void
14029 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14030 			     gdb::function_view<void (breakpoint *)> function)
14031 {
14032   if (bp_num_range.first == 0)
14033     {
14034       warning (_("bad breakpoint number at or near '%d'"),
14035 	       bp_num_range.first);
14036     }
14037   else
14038     {
14039       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14040 	{
14041 	  bool match = false;
14042 
14043 	  for (breakpoint *b : all_breakpoints_safe ())
14044 	    if (b->number == i)
14045 	      {
14046 		match = true;
14047 		function (b);
14048 		break;
14049 	      }
14050 	  if (!match)
14051 	    printf_unfiltered (_("No breakpoint number %d.\n"), i);
14052 	}
14053     }
14054 }
14055 
14056 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14057    ARGS.  */
14058 
14059 static void
14060 map_breakpoint_numbers (const char *args,
14061 			gdb::function_view<void (breakpoint *)> function)
14062 {
14063   if (args == NULL || *args == '\0')
14064     error_no_arg (_("one or more breakpoint numbers"));
14065 
14066   number_or_range_parser parser (args);
14067 
14068   while (!parser.finished ())
14069     {
14070       int num = parser.get_number ();
14071       map_breakpoint_number_range (std::make_pair (num, num), function);
14072     }
14073 }
14074 
14075 /* Return the breakpoint location structure corresponding to the
14076    BP_NUM and LOC_NUM values.  */
14077 
14078 static struct bp_location *
14079 find_location_by_number (int bp_num, int loc_num)
14080 {
14081   breakpoint *b = get_breakpoint (bp_num);
14082 
14083   if (!b || b->number != bp_num)
14084     error (_("Bad breakpoint number '%d'"), bp_num);
14085 
14086   if (loc_num == 0)
14087     error (_("Bad breakpoint location number '%d'"), loc_num);
14088 
14089   int n = 0;
14090   for (bp_location *loc : b->locations ())
14091     if (++n == loc_num)
14092       return loc;
14093 
14094   error (_("Bad breakpoint location number '%d'"), loc_num);
14095 }
14096 
14097 /* Modes of operation for extract_bp_num.  */
14098 enum class extract_bp_kind
14099 {
14100   /* Extracting a breakpoint number.  */
14101   bp,
14102 
14103   /* Extracting a location number.  */
14104   loc,
14105 };
14106 
14107 /* Extract a breakpoint or location number (as determined by KIND)
14108    from the string starting at START.  TRAILER is a character which
14109    can be found after the number.  If you don't want a trailer, use
14110    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14111    string.  This always returns a positive integer.  */
14112 
14113 static int
14114 extract_bp_num (extract_bp_kind kind, const char *start,
14115 		int trailer, const char **end_out = NULL)
14116 {
14117   const char *end = start;
14118   int num = get_number_trailer (&end, trailer);
14119   if (num < 0)
14120     error (kind == extract_bp_kind::bp
14121 	   ? _("Negative breakpoint number '%.*s'")
14122 	   : _("Negative breakpoint location number '%.*s'"),
14123 	   int (end - start), start);
14124   if (num == 0)
14125     error (kind == extract_bp_kind::bp
14126 	   ? _("Bad breakpoint number '%.*s'")
14127 	   : _("Bad breakpoint location number '%.*s'"),
14128 	   int (end - start), start);
14129 
14130   if (end_out != NULL)
14131     *end_out = end;
14132   return num;
14133 }
14134 
14135 /* Extract a breakpoint or location range (as determined by KIND) in
14136    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14137    representing the (inclusive) range.  The returned pair's elements
14138    are always positive integers.  */
14139 
14140 static std::pair<int, int>
14141 extract_bp_or_bp_range (extract_bp_kind kind,
14142 			const std::string &arg,
14143 			std::string::size_type arg_offset)
14144 {
14145   std::pair<int, int> range;
14146   const char *bp_loc = &arg[arg_offset];
14147   std::string::size_type dash = arg.find ('-', arg_offset);
14148   if (dash != std::string::npos)
14149     {
14150       /* bp_loc is a range (x-z).  */
14151       if (arg.length () == dash + 1)
14152 	error (kind == extract_bp_kind::bp
14153 	       ? _("Bad breakpoint number at or near: '%s'")
14154 	       : _("Bad breakpoint location number at or near: '%s'"),
14155 	       bp_loc);
14156 
14157       const char *end;
14158       const char *start_first = bp_loc;
14159       const char *start_second = &arg[dash + 1];
14160       range.first = extract_bp_num (kind, start_first, '-');
14161       range.second = extract_bp_num (kind, start_second, '\0', &end);
14162 
14163       if (range.first > range.second)
14164 	error (kind == extract_bp_kind::bp
14165 	       ? _("Inverted breakpoint range at '%.*s'")
14166 	       : _("Inverted breakpoint location range at '%.*s'"),
14167 	       int (end - start_first), start_first);
14168     }
14169   else
14170     {
14171       /* bp_loc is a single value.  */
14172       range.first = extract_bp_num (kind, bp_loc, '\0');
14173       range.second = range.first;
14174     }
14175   return range;
14176 }
14177 
14178 /* Extract the breakpoint/location range specified by ARG.  Returns
14179    the breakpoint range in BP_NUM_RANGE, and the location range in
14180    BP_LOC_RANGE.
14181 
14182    ARG may be in any of the following forms:
14183 
14184    x     where 'x' is a breakpoint number.
14185    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14186    x.y   where 'x' is a breakpoint number and 'y' a location number.
14187    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14188 	 location number range.
14189 */
14190 
14191 static void
14192 extract_bp_number_and_location (const std::string &arg,
14193 				std::pair<int, int> &bp_num_range,
14194 				std::pair<int, int> &bp_loc_range)
14195 {
14196   std::string::size_type dot = arg.find ('.');
14197 
14198   if (dot != std::string::npos)
14199     {
14200       /* Handle 'x.y' and 'x.y-z' cases.  */
14201 
14202       if (arg.length () == dot + 1 || dot == 0)
14203 	error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14204 
14205       bp_num_range.first
14206 	= extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14207       bp_num_range.second = bp_num_range.first;
14208 
14209       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14210 					     arg, dot + 1);
14211     }
14212   else
14213     {
14214       /* Handle x and x-y cases.  */
14215 
14216       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14217       bp_loc_range.first = 0;
14218       bp_loc_range.second = 0;
14219     }
14220 }
14221 
14222 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14223    specifies whether to enable or disable.  */
14224 
14225 static void
14226 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14227 {
14228   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14229   if (loc != NULL)
14230     {
14231       if (loc->disabled_by_cond && enable)
14232 	error (_("Breakpoint %d's condition is invalid at location %d, "
14233 		 "cannot enable."), bp_num, loc_num);
14234 
14235       if (loc->enabled != enable)
14236 	{
14237 	  loc->enabled = enable;
14238 	  mark_breakpoint_location_modified (loc);
14239 	}
14240       if (target_supports_enable_disable_tracepoint ()
14241 	  && current_trace_status ()->running && loc->owner
14242 	  && is_tracepoint (loc->owner))
14243 	target_disable_tracepoint (loc);
14244     }
14245   update_global_location_list (UGLL_DONT_INSERT);
14246 
14247   gdb::observers::breakpoint_modified.notify (loc->owner);
14248 }
14249 
14250 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14251    number of the breakpoint, and BP_LOC_RANGE specifies the
14252    (inclusive) range of location numbers of that breakpoint to
14253    enable/disable.  ENABLE specifies whether to enable or disable the
14254    location.  */
14255 
14256 static void
14257 enable_disable_breakpoint_location_range (int bp_num,
14258 					  std::pair<int, int> &bp_loc_range,
14259 					  bool enable)
14260 {
14261   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14262     enable_disable_bp_num_loc (bp_num, i, enable);
14263 }
14264 
14265 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14266    If from_tty is nonzero, it prints a message to that effect,
14267    which ends with a period (no newline).  */
14268 
14269 void
14270 disable_breakpoint (struct breakpoint *bpt)
14271 {
14272   /* Never disable a watchpoint scope breakpoint; we want to
14273      hit them when we leave scope so we can delete both the
14274      watchpoint and its scope breakpoint at that time.  */
14275   if (bpt->type == bp_watchpoint_scope)
14276     return;
14277 
14278   bpt->enable_state = bp_disabled;
14279 
14280   /* Mark breakpoint locations modified.  */
14281   mark_breakpoint_modified (bpt);
14282 
14283   if (target_supports_enable_disable_tracepoint ()
14284       && current_trace_status ()->running && is_tracepoint (bpt))
14285     {
14286       for (bp_location *location : bpt->locations ())
14287 	target_disable_tracepoint (location);
14288     }
14289 
14290   update_global_location_list (UGLL_DONT_INSERT);
14291 
14292   gdb::observers::breakpoint_modified.notify (bpt);
14293 }
14294 
14295 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14296    specified in ARGS.  ARGS may be in any of the formats handled by
14297    extract_bp_number_and_location.  ENABLE specifies whether to enable
14298    or disable the breakpoints/locations.  */
14299 
14300 static void
14301 enable_disable_command (const char *args, int from_tty, bool enable)
14302 {
14303   if (args == 0)
14304     {
14305       for (breakpoint *bpt : all_breakpoints ())
14306 	if (user_breakpoint_p (bpt))
14307 	  {
14308 	    if (enable)
14309 	      enable_breakpoint (bpt);
14310 	    else
14311 	      disable_breakpoint (bpt);
14312 	  }
14313     }
14314   else
14315     {
14316       std::string num = extract_arg (&args);
14317 
14318       while (!num.empty ())
14319 	{
14320 	  std::pair<int, int> bp_num_range, bp_loc_range;
14321 
14322 	  extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14323 
14324 	  if (bp_loc_range.first == bp_loc_range.second
14325 	      && bp_loc_range.first == 0)
14326 	    {
14327 	      /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14328 	      map_breakpoint_number_range (bp_num_range,
14329 					   enable
14330 					   ? enable_breakpoint
14331 					   : disable_breakpoint);
14332 	    }
14333 	  else
14334 	    {
14335 	      /* Handle breakpoint ids with formats 'x.y' or
14336 		 'x.y-z'.  */
14337 	      enable_disable_breakpoint_location_range
14338 		(bp_num_range.first, bp_loc_range, enable);
14339 	    }
14340 	  num = extract_arg (&args);
14341 	}
14342     }
14343 }
14344 
14345 /* The disable command disables the specified breakpoints/locations
14346    (or all defined breakpoints) so they're no longer effective in
14347    stopping the inferior.  ARGS may be in any of the forms defined in
14348    extract_bp_number_and_location.  */
14349 
14350 static void
14351 disable_command (const char *args, int from_tty)
14352 {
14353   enable_disable_command (args, from_tty, false);
14354 }
14355 
14356 static void
14357 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14358 			int count)
14359 {
14360   int target_resources_ok;
14361 
14362   if (bpt->type == bp_hardware_breakpoint)
14363     {
14364       int i;
14365       i = hw_breakpoint_used_count ();
14366       target_resources_ok =
14367 	target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
14368 					    i + 1, 0);
14369       if (target_resources_ok == 0)
14370 	error (_("No hardware breakpoint support in the target."));
14371       else if (target_resources_ok < 0)
14372 	error (_("Hardware breakpoints used exceeds limit."));
14373     }
14374 
14375   if (is_watchpoint (bpt))
14376     {
14377       /* Initialize it just to avoid a GCC false warning.  */
14378       enum enable_state orig_enable_state = bp_disabled;
14379 
14380       try
14381 	{
14382 	  struct watchpoint *w = (struct watchpoint *) bpt;
14383 
14384 	  orig_enable_state = bpt->enable_state;
14385 	  bpt->enable_state = bp_enabled;
14386 	  update_watchpoint (w, 1 /* reparse */);
14387 	}
14388       catch (const gdb_exception &e)
14389 	{
14390 	  bpt->enable_state = orig_enable_state;
14391 	  exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14392 			     bpt->number);
14393 	  return;
14394 	}
14395     }
14396 
14397   bpt->enable_state = bp_enabled;
14398 
14399   /* Mark breakpoint locations modified.  */
14400   mark_breakpoint_modified (bpt);
14401 
14402   if (target_supports_enable_disable_tracepoint ()
14403       && current_trace_status ()->running && is_tracepoint (bpt))
14404     {
14405       for (bp_location *location : bpt->locations ())
14406 	target_enable_tracepoint (location);
14407     }
14408 
14409   bpt->disposition = disposition;
14410   bpt->enable_count = count;
14411   update_global_location_list (UGLL_MAY_INSERT);
14412 
14413   gdb::observers::breakpoint_modified.notify (bpt);
14414 }
14415 
14416 
14417 void
14418 enable_breakpoint (struct breakpoint *bpt)
14419 {
14420   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14421 }
14422 
14423 /* The enable command enables the specified breakpoints/locations (or
14424    all defined breakpoints) so they once again become (or continue to
14425    be) effective in stopping the inferior.  ARGS may be in any of the
14426    forms defined in extract_bp_number_and_location.  */
14427 
14428 static void
14429 enable_command (const char *args, int from_tty)
14430 {
14431   enable_disable_command (args, from_tty, true);
14432 }
14433 
14434 static void
14435 enable_once_command (const char *args, int from_tty)
14436 {
14437   map_breakpoint_numbers
14438     (args, [&] (breakpoint *b)
14439      {
14440        iterate_over_related_breakpoints
14441 	 (b, [&] (breakpoint *bpt)
14442 	  {
14443 	    enable_breakpoint_disp (bpt, disp_disable, 1);
14444 	  });
14445      });
14446 }
14447 
14448 static void
14449 enable_count_command (const char *args, int from_tty)
14450 {
14451   int count;
14452 
14453   if (args == NULL)
14454     error_no_arg (_("hit count"));
14455 
14456   count = get_number (&args);
14457 
14458   map_breakpoint_numbers
14459     (args, [&] (breakpoint *b)
14460      {
14461        iterate_over_related_breakpoints
14462 	 (b, [&] (breakpoint *bpt)
14463 	  {
14464 	    enable_breakpoint_disp (bpt, disp_disable, count);
14465 	  });
14466      });
14467 }
14468 
14469 static void
14470 enable_delete_command (const char *args, int from_tty)
14471 {
14472   map_breakpoint_numbers
14473     (args, [&] (breakpoint *b)
14474      {
14475        iterate_over_related_breakpoints
14476 	 (b, [&] (breakpoint *bpt)
14477 	  {
14478 	    enable_breakpoint_disp (bpt, disp_del, 1);
14479 	  });
14480      });
14481 }
14482 
14483 /* Invalidate last known value of any hardware watchpoint if
14484    the memory which that value represents has been written to by
14485    GDB itself.  */
14486 
14487 static void
14488 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14489 				      CORE_ADDR addr, ssize_t len,
14490 				      const bfd_byte *data)
14491 {
14492   for (breakpoint *bp : all_breakpoints ())
14493     if (bp->enable_state == bp_enabled
14494 	&& bp->type == bp_hardware_watchpoint)
14495       {
14496 	struct watchpoint *wp = (struct watchpoint *) bp;
14497 
14498 	if (wp->val_valid && wp->val != nullptr)
14499 	  {
14500 	    for (bp_location *loc : bp->locations ())
14501 	      if (loc->loc_type == bp_loc_hardware_watchpoint
14502 		  && loc->address + loc->length > addr
14503 		  && addr + len > loc->address)
14504 		{
14505 		  wp->val = NULL;
14506 		  wp->val_valid = false;
14507 		}
14508 	  }
14509       }
14510 }
14511 
14512 /* Create and insert a breakpoint for software single step.  */
14513 
14514 void
14515 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14516 			       const address_space *aspace,
14517 			       CORE_ADDR next_pc)
14518 {
14519   struct thread_info *tp = inferior_thread ();
14520   struct symtab_and_line sal;
14521   CORE_ADDR pc = next_pc;
14522 
14523   if (tp->control.single_step_breakpoints == NULL)
14524     {
14525       tp->control.single_step_breakpoints
14526 	= new_single_step_breakpoint (tp->global_num, gdbarch);
14527     }
14528 
14529   sal = find_pc_line (pc, 0);
14530   sal.pc = pc;
14531   sal.section = find_pc_overlay (pc);
14532   sal.explicit_pc = 1;
14533   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14534 
14535   update_global_location_list (UGLL_INSERT);
14536 }
14537 
14538 /* Insert single step breakpoints according to the current state.  */
14539 
14540 int
14541 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14542 {
14543   struct regcache *regcache = get_current_regcache ();
14544   std::vector<CORE_ADDR> next_pcs;
14545 
14546   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14547 
14548   if (!next_pcs.empty ())
14549     {
14550       struct frame_info *frame = get_current_frame ();
14551       const address_space *aspace = get_frame_address_space (frame);
14552 
14553       for (CORE_ADDR pc : next_pcs)
14554 	insert_single_step_breakpoint (gdbarch, aspace, pc);
14555 
14556       return 1;
14557     }
14558   else
14559     return 0;
14560 }
14561 
14562 /* See breakpoint.h.  */
14563 
14564 int
14565 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14566 				       const address_space *aspace,
14567 				       CORE_ADDR pc)
14568 {
14569   for (bp_location *loc : bp->locations ())
14570     if (loc->inserted
14571 	&& breakpoint_location_address_match (loc, aspace, pc))
14572       return 1;
14573 
14574   return 0;
14575 }
14576 
14577 /* Check whether a software single-step breakpoint is inserted at
14578    PC.  */
14579 
14580 int
14581 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14582 					CORE_ADDR pc)
14583 {
14584   for (breakpoint *bpt : all_breakpoints ())
14585     {
14586       if (bpt->type == bp_single_step
14587 	  && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14588 	return 1;
14589     }
14590   return 0;
14591 }
14592 
14593 /* Tracepoint-specific operations.  */
14594 
14595 /* Set tracepoint count to NUM.  */
14596 static void
14597 set_tracepoint_count (int num)
14598 {
14599   tracepoint_count = num;
14600   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14601 }
14602 
14603 static void
14604 trace_command (const char *arg, int from_tty)
14605 {
14606   event_location_up location = string_to_event_location (&arg,
14607 							 current_language);
14608   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
14609     (location.get (), true /* is_tracepoint */);
14610 
14611   create_breakpoint (get_current_arch (),
14612 		     location.get (),
14613 		     NULL, 0, arg, false, 1 /* parse arg */,
14614 		     0 /* tempflag */,
14615 		     bp_tracepoint /* type_wanted */,
14616 		     0 /* Ignore count */,
14617 		     pending_break_support,
14618 		     ops,
14619 		     from_tty,
14620 		     1 /* enabled */,
14621 		     0 /* internal */, 0);
14622 }
14623 
14624 static void
14625 ftrace_command (const char *arg, int from_tty)
14626 {
14627   event_location_up location = string_to_event_location (&arg,
14628 							 current_language);
14629   create_breakpoint (get_current_arch (),
14630 		     location.get (),
14631 		     NULL, 0, arg, false, 1 /* parse arg */,
14632 		     0 /* tempflag */,
14633 		     bp_fast_tracepoint /* type_wanted */,
14634 		     0 /* Ignore count */,
14635 		     pending_break_support,
14636 		     &tracepoint_breakpoint_ops,
14637 		     from_tty,
14638 		     1 /* enabled */,
14639 		     0 /* internal */, 0);
14640 }
14641 
14642 /* strace command implementation.  Creates a static tracepoint.  */
14643 
14644 static void
14645 strace_command (const char *arg, int from_tty)
14646 {
14647   struct breakpoint_ops *ops;
14648   event_location_up location;
14649 
14650   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14651      or with a normal static tracepoint.  */
14652   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14653     {
14654       ops = &strace_marker_breakpoint_ops;
14655       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14656     }
14657   else
14658     {
14659       ops = &tracepoint_breakpoint_ops;
14660       location = string_to_event_location (&arg, current_language);
14661     }
14662 
14663   create_breakpoint (get_current_arch (),
14664 		     location.get (),
14665 		     NULL, 0, arg, false, 1 /* parse arg */,
14666 		     0 /* tempflag */,
14667 		     bp_static_tracepoint /* type_wanted */,
14668 		     0 /* Ignore count */,
14669 		     pending_break_support,
14670 		     ops,
14671 		     from_tty,
14672 		     1 /* enabled */,
14673 		     0 /* internal */, 0);
14674 }
14675 
14676 /* Set up a fake reader function that gets command lines from a linked
14677    list that was acquired during tracepoint uploading.  */
14678 
14679 static struct uploaded_tp *this_utp;
14680 static int next_cmd;
14681 
14682 static char *
14683 read_uploaded_action (void)
14684 {
14685   char *rslt = nullptr;
14686 
14687   if (next_cmd < this_utp->cmd_strings.size ())
14688     {
14689       rslt = this_utp->cmd_strings[next_cmd].get ();
14690       next_cmd++;
14691     }
14692 
14693   return rslt;
14694 }
14695 
14696 /* Given information about a tracepoint as recorded on a target (which
14697    can be either a live system or a trace file), attempt to create an
14698    equivalent GDB tracepoint.  This is not a reliable process, since
14699    the target does not necessarily have all the information used when
14700    the tracepoint was originally defined.  */
14701 
14702 struct tracepoint *
14703 create_tracepoint_from_upload (struct uploaded_tp *utp)
14704 {
14705   const char *addr_str;
14706   char small_buf[100];
14707   struct tracepoint *tp;
14708 
14709   if (utp->at_string)
14710     addr_str = utp->at_string.get ();
14711   else
14712     {
14713       /* In the absence of a source location, fall back to raw
14714 	 address.  Since there is no way to confirm that the address
14715 	 means the same thing as when the trace was started, warn the
14716 	 user.  */
14717       warning (_("Uploaded tracepoint %d has no "
14718 		 "source location, using raw address"),
14719 	       utp->number);
14720       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14721       addr_str = small_buf;
14722     }
14723 
14724   /* There's not much we can do with a sequence of bytecodes.  */
14725   if (utp->cond && !utp->cond_string)
14726     warning (_("Uploaded tracepoint %d condition "
14727 	       "has no source form, ignoring it"),
14728 	     utp->number);
14729 
14730   event_location_up location = string_to_event_location (&addr_str,
14731 							 current_language);
14732   if (!create_breakpoint (get_current_arch (),
14733 			  location.get (),
14734 			  utp->cond_string.get (), -1, addr_str,
14735 			  false /* force_condition */,
14736 			  0 /* parse cond/thread */,
14737 			  0 /* tempflag */,
14738 			  utp->type /* type_wanted */,
14739 			  0 /* Ignore count */,
14740 			  pending_break_support,
14741 			  &tracepoint_breakpoint_ops,
14742 			  0 /* from_tty */,
14743 			  utp->enabled /* enabled */,
14744 			  0 /* internal */,
14745 			  CREATE_BREAKPOINT_FLAGS_INSERTED))
14746     return NULL;
14747 
14748   /* Get the tracepoint we just created.  */
14749   tp = get_tracepoint (tracepoint_count);
14750   gdb_assert (tp != NULL);
14751 
14752   if (utp->pass > 0)
14753     {
14754       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14755 		 tp->number);
14756 
14757       trace_pass_command (small_buf, 0);
14758     }
14759 
14760   /* If we have uploaded versions of the original commands, set up a
14761      special-purpose "reader" function and call the usual command line
14762      reader, then pass the result to the breakpoint command-setting
14763      function.  */
14764   if (!utp->cmd_strings.empty ())
14765     {
14766       counted_command_line cmd_list;
14767 
14768       this_utp = utp;
14769       next_cmd = 0;
14770 
14771       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14772 
14773       breakpoint_set_commands (tp, std::move (cmd_list));
14774     }
14775   else if (!utp->actions.empty ()
14776 	   || !utp->step_actions.empty ())
14777     warning (_("Uploaded tracepoint %d actions "
14778 	       "have no source form, ignoring them"),
14779 	     utp->number);
14780 
14781   /* Copy any status information that might be available.  */
14782   tp->hit_count = utp->hit_count;
14783   tp->traceframe_usage = utp->traceframe_usage;
14784 
14785   return tp;
14786 }
14787 
14788 /* Print information on tracepoint number TPNUM_EXP, or all if
14789    omitted.  */
14790 
14791 static void
14792 info_tracepoints_command (const char *args, int from_tty)
14793 {
14794   struct ui_out *uiout = current_uiout;
14795   int num_printed;
14796 
14797   num_printed = breakpoint_1 (args, false, is_tracepoint);
14798 
14799   if (num_printed == 0)
14800     {
14801       if (args == NULL || *args == '\0')
14802 	uiout->message ("No tracepoints.\n");
14803       else
14804 	uiout->message ("No tracepoint matching '%s'.\n", args);
14805     }
14806 
14807   default_collect_info ();
14808 }
14809 
14810 /* The 'enable trace' command enables tracepoints.
14811    Not supported by all targets.  */
14812 static void
14813 enable_trace_command (const char *args, int from_tty)
14814 {
14815   enable_command (args, from_tty);
14816 }
14817 
14818 /* The 'disable trace' command disables tracepoints.
14819    Not supported by all targets.  */
14820 static void
14821 disable_trace_command (const char *args, int from_tty)
14822 {
14823   disable_command (args, from_tty);
14824 }
14825 
14826 /* Remove a tracepoint (or all if no argument).  */
14827 static void
14828 delete_trace_command (const char *arg, int from_tty)
14829 {
14830   dont_repeat ();
14831 
14832   if (arg == 0)
14833     {
14834       int breaks_to_delete = 0;
14835 
14836       /* Delete all breakpoints if no argument.
14837 	 Do not delete internal or call-dummy breakpoints, these
14838 	 have to be deleted with an explicit breakpoint number
14839 	 argument.  */
14840       for (breakpoint *tp : all_tracepoints ())
14841 	if (is_tracepoint (tp) && user_breakpoint_p (tp))
14842 	  {
14843 	    breaks_to_delete = 1;
14844 	    break;
14845 	  }
14846 
14847       /* Ask user only if there are some breakpoints to delete.  */
14848       if (!from_tty
14849 	  || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14850 	{
14851 	  for (breakpoint *b : all_breakpoints_safe ())
14852 	    if (is_tracepoint (b) && user_breakpoint_p (b))
14853 	      delete_breakpoint (b);
14854 	}
14855     }
14856   else
14857     map_breakpoint_numbers
14858       (arg, [&] (breakpoint *br)
14859        {
14860 	 iterate_over_related_breakpoints (br, delete_breakpoint);
14861        });
14862 }
14863 
14864 /* Helper function for trace_pass_command.  */
14865 
14866 static void
14867 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14868 {
14869   tp->pass_count = count;
14870   gdb::observers::breakpoint_modified.notify (tp);
14871   if (from_tty)
14872     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14873 		     tp->number, count);
14874 }
14875 
14876 /* Set passcount for tracepoint.
14877 
14878    First command argument is passcount, second is tracepoint number.
14879    If tracepoint number omitted, apply to most recently defined.
14880    Also accepts special argument "all".  */
14881 
14882 static void
14883 trace_pass_command (const char *args, int from_tty)
14884 {
14885   struct tracepoint *t1;
14886   ULONGEST count;
14887 
14888   if (args == 0 || *args == 0)
14889     error (_("passcount command requires an "
14890 	     "argument (count + optional TP num)"));
14891 
14892   count = strtoulst (args, &args, 10);	/* Count comes first, then TP num.  */
14893 
14894   args = skip_spaces (args);
14895   if (*args && strncasecmp (args, "all", 3) == 0)
14896     {
14897       args += 3;			/* Skip special argument "all".  */
14898       if (*args)
14899 	error (_("Junk at end of arguments."));
14900 
14901       for (breakpoint *b : all_tracepoints ())
14902 	{
14903 	  t1 = (struct tracepoint *) b;
14904 	  trace_pass_set_count (t1, count, from_tty);
14905 	}
14906     }
14907   else if (*args == '\0')
14908     {
14909       t1 = get_tracepoint_by_number (&args, NULL);
14910       if (t1)
14911 	trace_pass_set_count (t1, count, from_tty);
14912     }
14913   else
14914     {
14915       number_or_range_parser parser (args);
14916       while (!parser.finished ())
14917 	{
14918 	  t1 = get_tracepoint_by_number (&args, &parser);
14919 	  if (t1)
14920 	    trace_pass_set_count (t1, count, from_tty);
14921 	}
14922     }
14923 }
14924 
14925 struct tracepoint *
14926 get_tracepoint (int num)
14927 {
14928   for (breakpoint *t : all_tracepoints ())
14929     if (t->number == num)
14930       return (struct tracepoint *) t;
14931 
14932   return NULL;
14933 }
14934 
14935 /* Find the tracepoint with the given target-side number (which may be
14936    different from the tracepoint number after disconnecting and
14937    reconnecting).  */
14938 
14939 struct tracepoint *
14940 get_tracepoint_by_number_on_target (int num)
14941 {
14942   for (breakpoint *b : all_tracepoints ())
14943     {
14944       struct tracepoint *t = (struct tracepoint *) b;
14945 
14946       if (t->number_on_target == num)
14947 	return t;
14948     }
14949 
14950   return NULL;
14951 }
14952 
14953 /* Utility: parse a tracepoint number and look it up in the list.
14954    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14955    If the argument is missing, the most recent tracepoint
14956    (tracepoint_count) is returned.  */
14957 
14958 struct tracepoint *
14959 get_tracepoint_by_number (const char **arg,
14960 			  number_or_range_parser *parser)
14961 {
14962   int tpnum;
14963   const char *instring = arg == NULL ? NULL : *arg;
14964 
14965   if (parser != NULL)
14966     {
14967       gdb_assert (!parser->finished ());
14968       tpnum = parser->get_number ();
14969     }
14970   else if (arg == NULL || *arg == NULL || ! **arg)
14971     tpnum = tracepoint_count;
14972   else
14973     tpnum = get_number (arg);
14974 
14975   if (tpnum <= 0)
14976     {
14977       if (instring && *instring)
14978 	printf_filtered (_("bad tracepoint number at or near '%s'\n"),
14979 			 instring);
14980       else
14981 	printf_filtered (_("No previous tracepoint\n"));
14982       return NULL;
14983     }
14984 
14985   for (breakpoint *t : all_tracepoints ())
14986     if (t->number == tpnum)
14987       return (struct tracepoint *) t;
14988 
14989   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14990   return NULL;
14991 }
14992 
14993 void
14994 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14995 {
14996   if (b->thread != -1)
14997     fprintf_unfiltered (fp, " thread %d", b->thread);
14998 
14999   if (b->task != 0)
15000     fprintf_unfiltered (fp, " task %d", b->task);
15001 
15002   fprintf_unfiltered (fp, "\n");
15003 }
15004 
15005 /* Save information on user settable breakpoints (watchpoints, etc) to
15006    a new script file named FILENAME.  If FILTER is non-NULL, call it
15007    on each breakpoint and only include the ones for which it returns
15008    true.  */
15009 
15010 static void
15011 save_breakpoints (const char *filename, int from_tty,
15012 		  bool (*filter) (const struct breakpoint *))
15013 {
15014   int any = 0;
15015   int extra_trace_bits = 0;
15016 
15017   if (filename == 0 || *filename == 0)
15018     error (_("Argument required (file name in which to save)"));
15019 
15020   /* See if we have anything to save.  */
15021   for (breakpoint *tp : all_breakpoints ())
15022     {
15023       /* Skip internal and momentary breakpoints.  */
15024       if (!user_breakpoint_p (tp))
15025 	continue;
15026 
15027       /* If we have a filter, only save the breakpoints it accepts.  */
15028       if (filter && !filter (tp))
15029 	continue;
15030 
15031       any = 1;
15032 
15033       if (is_tracepoint (tp))
15034 	{
15035 	  extra_trace_bits = 1;
15036 
15037 	  /* We can stop searching.  */
15038 	  break;
15039 	}
15040     }
15041 
15042   if (!any)
15043     {
15044       warning (_("Nothing to save."));
15045       return;
15046     }
15047 
15048   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15049 
15050   stdio_file fp;
15051 
15052   if (!fp.open (expanded_filename.get (), "w"))
15053     error (_("Unable to open file '%s' for saving (%s)"),
15054 	   expanded_filename.get (), safe_strerror (errno));
15055 
15056   if (extra_trace_bits)
15057     save_trace_state_variables (&fp);
15058 
15059   for (breakpoint *tp : all_breakpoints ())
15060     {
15061       /* Skip internal and momentary breakpoints.  */
15062       if (!user_breakpoint_p (tp))
15063 	continue;
15064 
15065       /* If we have a filter, only save the breakpoints it accepts.  */
15066       if (filter && !filter (tp))
15067 	continue;
15068 
15069       tp->ops->print_recreate (tp, &fp);
15070 
15071       /* Note, we can't rely on tp->number for anything, as we can't
15072 	 assume the recreated breakpoint numbers will match.  Use $bpnum
15073 	 instead.  */
15074 
15075       if (tp->cond_string)
15076 	fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15077 
15078       if (tp->ignore_count)
15079 	fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15080 
15081       if (tp->type != bp_dprintf && tp->commands)
15082 	{
15083 	  fp.puts ("  commands\n");
15084 
15085 	  current_uiout->redirect (&fp);
15086 	  try
15087 	    {
15088 	      print_command_lines (current_uiout, tp->commands.get (), 2);
15089 	    }
15090 	  catch (const gdb_exception &ex)
15091 	    {
15092 	    current_uiout->redirect (NULL);
15093 	      throw;
15094 	    }
15095 
15096 	  current_uiout->redirect (NULL);
15097 	  fp.puts ("  end\n");
15098 	}
15099 
15100       if (tp->enable_state == bp_disabled)
15101 	fp.puts ("disable $bpnum\n");
15102 
15103       /* If this is a multi-location breakpoint, check if the locations
15104 	 should be individually disabled.  Watchpoint locations are
15105 	 special, and not user visible.  */
15106       if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15107 	{
15108 	  int n = 1;
15109 
15110 	  for (bp_location *loc : tp->locations ())
15111 	    {
15112 	      if (!loc->enabled)
15113 		fp.printf ("disable $bpnum.%d\n", n);
15114 
15115 	      n++;
15116 	    }
15117 	}
15118     }
15119 
15120   if (extra_trace_bits && *default_collect)
15121     fp.printf ("set default-collect %s\n", default_collect);
15122 
15123   if (from_tty)
15124     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15125 }
15126 
15127 /* The `save breakpoints' command.  */
15128 
15129 static void
15130 save_breakpoints_command (const char *args, int from_tty)
15131 {
15132   save_breakpoints (args, from_tty, NULL);
15133 }
15134 
15135 /* The `save tracepoints' command.  */
15136 
15137 static void
15138 save_tracepoints_command (const char *args, int from_tty)
15139 {
15140   save_breakpoints (args, from_tty, is_tracepoint);
15141 }
15142 
15143 
15144 /* This help string is used to consolidate all the help string for specifying
15145    locations used by several commands.  */
15146 
15147 #define LOCATION_HELP_STRING \
15148 "Linespecs are colon-separated lists of location parameters, such as\n\
15149 source filename, function name, label name, and line number.\n\
15150 Example: To specify the start of a label named \"the_top\" in the\n\
15151 function \"fact\" in the file \"factorial.c\", use\n\
15152 \"factorial.c:fact:the_top\".\n\
15153 \n\
15154 Address locations begin with \"*\" and specify an exact address in the\n\
15155 program.  Example: To specify the fourth byte past the start function\n\
15156 \"main\", use \"*main + 4\".\n\
15157 \n\
15158 Explicit locations are similar to linespecs but use an option/argument\n\
15159 syntax to specify location parameters.\n\
15160 Example: To specify the start of the label named \"the_top\" in the\n\
15161 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15162 -function fact -label the_top\".\n\
15163 \n\
15164 By default, a specified function is matched against the program's\n\
15165 functions in all scopes.  For C++, this means in all namespaces and\n\
15166 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15167 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15168 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15169 specified name as a complete fully-qualified name instead."
15170 
15171 /* This help string is used for the break, hbreak, tbreak and thbreak
15172    commands.  It is defined as a macro to prevent duplication.
15173    COMMAND should be a string constant containing the name of the
15174    command.  */
15175 
15176 #define BREAK_ARGS_HELP(command) \
15177 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
15178 \t[-force-condition] [if CONDITION]\n\
15179 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15180 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15181 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15182 `-probe-dtrace' (for a DTrace probe).\n\
15183 LOCATION may be a linespec, address, or explicit location as described\n\
15184 below.\n\
15185 \n\
15186 With no LOCATION, uses current execution address of the selected\n\
15187 stack frame.  This is useful for breaking on return to a stack frame.\n\
15188 \n\
15189 THREADNUM is the number from \"info threads\".\n\
15190 CONDITION is a boolean expression.\n\
15191 \n\
15192 With the \"-force-condition\" flag, the condition is defined even when\n\
15193 it is invalid for all current locations.\n\
15194 \n" LOCATION_HELP_STRING "\n\n\
15195 Multiple breakpoints at one place are permitted, and useful if their\n\
15196 conditions are different.\n\
15197 \n\
15198 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15199 
15200 /* List of subcommands for "catch".  */
15201 static struct cmd_list_element *catch_cmdlist;
15202 
15203 /* List of subcommands for "tcatch".  */
15204 static struct cmd_list_element *tcatch_cmdlist;
15205 
15206 void
15207 add_catch_command (const char *name, const char *docstring,
15208 		   cmd_const_sfunc_ftype *sfunc,
15209 		   completer_ftype *completer,
15210 		   void *user_data_catch,
15211 		   void *user_data_tcatch)
15212 {
15213   struct cmd_list_element *command;
15214 
15215   command = add_cmd (name, class_breakpoint, docstring,
15216 		     &catch_cmdlist);
15217   set_cmd_sfunc (command, sfunc);
15218   command->set_context (user_data_catch);
15219   set_cmd_completer (command, completer);
15220 
15221   command = add_cmd (name, class_breakpoint, docstring,
15222 		     &tcatch_cmdlist);
15223   set_cmd_sfunc (command, sfunc);
15224   command->set_context (user_data_tcatch);
15225   set_cmd_completer (command, completer);
15226 }
15227 
15228 /* Zero if any of the breakpoint's locations could be a location where
15229    functions have been inlined, nonzero otherwise.  */
15230 
15231 static int
15232 is_non_inline_function (struct breakpoint *b)
15233 {
15234   /* The shared library event breakpoint is set on the address of a
15235      non-inline function.  */
15236   if (b->type == bp_shlib_event)
15237     return 1;
15238 
15239   return 0;
15240 }
15241 
15242 /* Nonzero if the specified PC cannot be a location where functions
15243    have been inlined.  */
15244 
15245 int
15246 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15247 			   const struct target_waitstatus *ws)
15248 {
15249   for (breakpoint *b : all_breakpoints ())
15250     {
15251       if (!is_non_inline_function (b))
15252 	continue;
15253 
15254       for (bp_location *bl : b->locations ())
15255 	{
15256 	  if (!bl->shlib_disabled
15257 	      && bpstat_check_location (bl, aspace, pc, ws))
15258 	    return 1;
15259 	}
15260     }
15261 
15262   return 0;
15263 }
15264 
15265 /* Remove any references to OBJFILE which is going to be freed.  */
15266 
15267 void
15268 breakpoint_free_objfile (struct objfile *objfile)
15269 {
15270   for (bp_location *loc : all_bp_locations ())
15271     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15272       loc->symtab = NULL;
15273 }
15274 
15275 void
15276 initialize_breakpoint_ops (void)
15277 {
15278   static int initialized = 0;
15279 
15280   struct breakpoint_ops *ops;
15281 
15282   if (initialized)
15283     return;
15284   initialized = 1;
15285 
15286   /* The breakpoint_ops structure to be inherit by all kinds of
15287      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15288      internal and momentary breakpoints, etc.).  */
15289   ops = &bkpt_base_breakpoint_ops;
15290   *ops = base_breakpoint_ops;
15291   ops->re_set = bkpt_re_set;
15292   ops->insert_location = bkpt_insert_location;
15293   ops->remove_location = bkpt_remove_location;
15294   ops->breakpoint_hit = bkpt_breakpoint_hit;
15295   ops->create_sals_from_location = bkpt_create_sals_from_location;
15296   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15297   ops->decode_location = bkpt_decode_location;
15298 
15299   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15300   ops = &bkpt_breakpoint_ops;
15301   *ops = bkpt_base_breakpoint_ops;
15302   ops->re_set = bkpt_re_set;
15303   ops->resources_needed = bkpt_resources_needed;
15304   ops->print_it = bkpt_print_it;
15305   ops->print_mention = bkpt_print_mention;
15306   ops->print_recreate = bkpt_print_recreate;
15307 
15308   /* Ranged breakpoints.  */
15309   ops = &ranged_breakpoint_ops;
15310   *ops = bkpt_breakpoint_ops;
15311   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15312   ops->resources_needed = resources_needed_ranged_breakpoint;
15313   ops->print_it = print_it_ranged_breakpoint;
15314   ops->print_one = print_one_ranged_breakpoint;
15315   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15316   ops->print_mention = print_mention_ranged_breakpoint;
15317   ops->print_recreate = print_recreate_ranged_breakpoint;
15318 
15319   /* Internal breakpoints.  */
15320   ops = &internal_breakpoint_ops;
15321   *ops = bkpt_base_breakpoint_ops;
15322   ops->re_set = internal_bkpt_re_set;
15323   ops->check_status = internal_bkpt_check_status;
15324   ops->print_it = internal_bkpt_print_it;
15325   ops->print_mention = internal_bkpt_print_mention;
15326 
15327   /* Momentary breakpoints.  */
15328   ops = &momentary_breakpoint_ops;
15329   *ops = bkpt_base_breakpoint_ops;
15330   ops->re_set = momentary_bkpt_re_set;
15331   ops->check_status = momentary_bkpt_check_status;
15332   ops->print_it = momentary_bkpt_print_it;
15333   ops->print_mention = momentary_bkpt_print_mention;
15334 
15335   /* Probe breakpoints.  */
15336   ops = &bkpt_probe_breakpoint_ops;
15337   *ops = bkpt_breakpoint_ops;
15338   ops->insert_location = bkpt_probe_insert_location;
15339   ops->remove_location = bkpt_probe_remove_location;
15340   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15341   ops->decode_location = bkpt_probe_decode_location;
15342 
15343   /* Watchpoints.  */
15344   ops = &watchpoint_breakpoint_ops;
15345   *ops = base_breakpoint_ops;
15346   ops->re_set = re_set_watchpoint;
15347   ops->insert_location = insert_watchpoint;
15348   ops->remove_location = remove_watchpoint;
15349   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15350   ops->check_status = check_status_watchpoint;
15351   ops->resources_needed = resources_needed_watchpoint;
15352   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15353   ops->print_it = print_it_watchpoint;
15354   ops->print_mention = print_mention_watchpoint;
15355   ops->print_recreate = print_recreate_watchpoint;
15356   ops->explains_signal = explains_signal_watchpoint;
15357 
15358   /* Masked watchpoints.  */
15359   ops = &masked_watchpoint_breakpoint_ops;
15360   *ops = watchpoint_breakpoint_ops;
15361   ops->insert_location = insert_masked_watchpoint;
15362   ops->remove_location = remove_masked_watchpoint;
15363   ops->resources_needed = resources_needed_masked_watchpoint;
15364   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15365   ops->print_it = print_it_masked_watchpoint;
15366   ops->print_one_detail = print_one_detail_masked_watchpoint;
15367   ops->print_mention = print_mention_masked_watchpoint;
15368   ops->print_recreate = print_recreate_masked_watchpoint;
15369 
15370   /* Tracepoints.  */
15371   ops = &tracepoint_breakpoint_ops;
15372   *ops = base_breakpoint_ops;
15373   ops->re_set = tracepoint_re_set;
15374   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15375   ops->print_one_detail = tracepoint_print_one_detail;
15376   ops->print_mention = tracepoint_print_mention;
15377   ops->print_recreate = tracepoint_print_recreate;
15378   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15379   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15380   ops->decode_location = tracepoint_decode_location;
15381 
15382   /* Probe tracepoints.  */
15383   ops = &tracepoint_probe_breakpoint_ops;
15384   *ops = tracepoint_breakpoint_ops;
15385   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15386   ops->decode_location = tracepoint_probe_decode_location;
15387 
15388   /* Static tracepoints with marker (`-m').  */
15389   ops = &strace_marker_breakpoint_ops;
15390   *ops = tracepoint_breakpoint_ops;
15391   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15392   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15393   ops->decode_location = strace_marker_decode_location;
15394 
15395   /* Fork catchpoints.  */
15396   ops = &catch_fork_breakpoint_ops;
15397   *ops = base_breakpoint_ops;
15398   ops->insert_location = insert_catch_fork;
15399   ops->remove_location = remove_catch_fork;
15400   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15401   ops->print_it = print_it_catch_fork;
15402   ops->print_one = print_one_catch_fork;
15403   ops->print_mention = print_mention_catch_fork;
15404   ops->print_recreate = print_recreate_catch_fork;
15405 
15406   /* Vfork catchpoints.  */
15407   ops = &catch_vfork_breakpoint_ops;
15408   *ops = base_breakpoint_ops;
15409   ops->insert_location = insert_catch_vfork;
15410   ops->remove_location = remove_catch_vfork;
15411   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15412   ops->print_it = print_it_catch_vfork;
15413   ops->print_one = print_one_catch_vfork;
15414   ops->print_mention = print_mention_catch_vfork;
15415   ops->print_recreate = print_recreate_catch_vfork;
15416 
15417   /* Exec catchpoints.  */
15418   ops = &catch_exec_breakpoint_ops;
15419   *ops = base_breakpoint_ops;
15420   ops->insert_location = insert_catch_exec;
15421   ops->remove_location = remove_catch_exec;
15422   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15423   ops->print_it = print_it_catch_exec;
15424   ops->print_one = print_one_catch_exec;
15425   ops->print_mention = print_mention_catch_exec;
15426   ops->print_recreate = print_recreate_catch_exec;
15427 
15428   /* Solib-related catchpoints.  */
15429   ops = &catch_solib_breakpoint_ops;
15430   *ops = base_breakpoint_ops;
15431   ops->insert_location = insert_catch_solib;
15432   ops->remove_location = remove_catch_solib;
15433   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15434   ops->check_status = check_status_catch_solib;
15435   ops->print_it = print_it_catch_solib;
15436   ops->print_one = print_one_catch_solib;
15437   ops->print_mention = print_mention_catch_solib;
15438   ops->print_recreate = print_recreate_catch_solib;
15439 
15440   ops = &dprintf_breakpoint_ops;
15441   *ops = bkpt_base_breakpoint_ops;
15442   ops->re_set = dprintf_re_set;
15443   ops->resources_needed = bkpt_resources_needed;
15444   ops->print_it = bkpt_print_it;
15445   ops->print_mention = bkpt_print_mention;
15446   ops->print_recreate = dprintf_print_recreate;
15447   ops->after_condition_true = dprintf_after_condition_true;
15448   ops->breakpoint_hit = dprintf_breakpoint_hit;
15449 }
15450 
15451 /* Chain containing all defined "enable breakpoint" subcommands.  */
15452 
15453 static struct cmd_list_element *enablebreaklist = NULL;
15454 
15455 /* See breakpoint.h.  */
15456 
15457 cmd_list_element *commands_cmd_element = nullptr;
15458 
15459 void _initialize_breakpoint ();
15460 void
15461 _initialize_breakpoint ()
15462 {
15463   struct cmd_list_element *c;
15464 
15465   initialize_breakpoint_ops ();
15466 
15467   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
15468 					 "breakpoint");
15469   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
15470 				       "breakpoint");
15471   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
15472 					 "breakpoint");
15473 
15474   breakpoint_chain = 0;
15475   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15476      before a breakpoint is set.  */
15477   breakpoint_count = 0;
15478 
15479   tracepoint_count = 0;
15480 
15481   add_com ("ignore", class_breakpoint, ignore_command, _("\
15482 Set ignore-count of breakpoint number N to COUNT.\n\
15483 Usage is `ignore N COUNT'."));
15484 
15485   commands_cmd_element = add_com ("commands", class_breakpoint,
15486 				  commands_command, _("\
15487 Set commands to be executed when the given breakpoints are hit.\n\
15488 Give a space-separated breakpoint list as argument after \"commands\".\n\
15489 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15490 (e.g. `5-7').\n\
15491 With no argument, the targeted breakpoint is the last one set.\n\
15492 The commands themselves follow starting on the next line.\n\
15493 Type a line containing \"end\" to indicate the end of them.\n\
15494 Give \"silent\" as the first line to make the breakpoint silent;\n\
15495 then no output is printed when it is hit, except what the commands print."));
15496 
15497   const auto cc_opts = make_condition_command_options_def_group (nullptr);
15498   static std::string condition_command_help
15499     = gdb::option::build_help (_("\
15500 Specify breakpoint number N to break only if COND is true.\n\
15501 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
15502 is an expression to be evaluated whenever breakpoint N is reached.\n\
15503 \n\
15504 Options:\n\
15505 %OPTIONS%"), cc_opts);
15506 
15507   c = add_com ("condition", class_breakpoint, condition_command,
15508 	       condition_command_help.c_str ());
15509   set_cmd_completer_handle_brkchars (c, condition_completer);
15510 
15511   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15512 Set a temporary breakpoint.\n\
15513 Like \"break\" except the breakpoint is only temporary,\n\
15514 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15515 by using \"enable delete\" on the breakpoint number.\n\
15516 \n"
15517 BREAK_ARGS_HELP ("tbreak")));
15518   set_cmd_completer (c, location_completer);
15519 
15520   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15521 Set a hardware assisted breakpoint.\n\
15522 Like \"break\" except the breakpoint requires hardware support,\n\
15523 some target hardware may not have this support.\n\
15524 \n"
15525 BREAK_ARGS_HELP ("hbreak")));
15526   set_cmd_completer (c, location_completer);
15527 
15528   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15529 Set a temporary hardware assisted breakpoint.\n\
15530 Like \"hbreak\" except the breakpoint is only temporary,\n\
15531 so it will be deleted when hit.\n\
15532 \n"
15533 BREAK_ARGS_HELP ("thbreak")));
15534   set_cmd_completer (c, location_completer);
15535 
15536   cmd_list_element *enable_cmd
15537     = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15538 Enable all or some breakpoints.\n\
15539 Usage: enable [BREAKPOINTNUM]...\n\
15540 Give breakpoint numbers (separated by spaces) as arguments.\n\
15541 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15542 This is used to cancel the effect of the \"disable\" command.\n\
15543 With a subcommand you can enable temporarily."),
15544 		      &enablelist, 1, &cmdlist);
15545 
15546   add_com_alias ("en", enable_cmd, class_breakpoint, 1);
15547 
15548   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15549 Enable all or some breakpoints.\n\
15550 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
15551 Give breakpoint numbers (separated by spaces) as arguments.\n\
15552 This is used to cancel the effect of the \"disable\" command.\n\
15553 May be abbreviated to simply \"enable\"."),
15554 		   &enablebreaklist, 1, &enablelist);
15555 
15556   add_cmd ("once", no_class, enable_once_command, _("\
15557 Enable some breakpoints for one hit.\n\
15558 Usage: enable breakpoints once BREAKPOINTNUM...\n\
15559 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15560 	   &enablebreaklist);
15561 
15562   add_cmd ("delete", no_class, enable_delete_command, _("\
15563 Enable some breakpoints and delete when hit.\n\
15564 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
15565 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15566 	   &enablebreaklist);
15567 
15568   add_cmd ("count", no_class, enable_count_command, _("\
15569 Enable some breakpoints for COUNT hits.\n\
15570 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
15571 If a breakpoint is hit while enabled in this fashion,\n\
15572 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15573 	   &enablebreaklist);
15574 
15575   add_cmd ("delete", no_class, enable_delete_command, _("\
15576 Enable some breakpoints and delete when hit.\n\
15577 Usage: enable delete BREAKPOINTNUM...\n\
15578 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15579 	   &enablelist);
15580 
15581   add_cmd ("once", no_class, enable_once_command, _("\
15582 Enable some breakpoints for one hit.\n\
15583 Usage: enable once BREAKPOINTNUM...\n\
15584 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15585 	   &enablelist);
15586 
15587   add_cmd ("count", no_class, enable_count_command, _("\
15588 Enable some breakpoints for COUNT hits.\n\
15589 Usage: enable count COUNT BREAKPOINTNUM...\n\
15590 If a breakpoint is hit while enabled in this fashion,\n\
15591 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15592 	   &enablelist);
15593 
15594   cmd_list_element *disable_cmd
15595     = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15596 Disable all or some breakpoints.\n\
15597 Usage: disable [BREAKPOINTNUM]...\n\
15598 Arguments are breakpoint numbers with spaces in between.\n\
15599 To disable all breakpoints, give no argument.\n\
15600 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15601 		      &disablelist, 1, &cmdlist);
15602   add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
15603   add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
15604 
15605   add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
15606 Disable all or some breakpoints.\n\
15607 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
15608 Arguments are breakpoint numbers with spaces in between.\n\
15609 To disable all breakpoints, give no argument.\n\
15610 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15611 This command may be abbreviated \"disable\"."),
15612 	   &disablelist);
15613 
15614   cmd_list_element *delete_cmd
15615     = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15616 Delete all or some breakpoints.\n\
15617 Usage: delete [BREAKPOINTNUM]...\n\
15618 Arguments are breakpoint numbers with spaces in between.\n\
15619 To delete all breakpoints, give no argument.\n\
15620 \n\
15621 Also a prefix command for deletion of other GDB objects."),
15622 		      &deletelist, 1, &cmdlist);
15623   add_com_alias ("d", delete_cmd, class_breakpoint, 1);
15624   add_com_alias ("del", delete_cmd, class_breakpoint, 1);
15625 
15626   add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
15627 Delete all or some breakpoints or auto-display expressions.\n\
15628 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
15629 Arguments are breakpoint numbers with spaces in between.\n\
15630 To delete all breakpoints, give no argument.\n\
15631 This command may be abbreviated \"delete\"."),
15632 	   &deletelist);
15633 
15634   cmd_list_element *clear_cmd
15635    = add_com ("clear", class_breakpoint, clear_command, _("\
15636 Clear breakpoint at specified location.\n\
15637 Argument may be a linespec, explicit, or address location as described below.\n\
15638 \n\
15639 With no argument, clears all breakpoints in the line that the selected frame\n\
15640 is executing in.\n"
15641 "\n" LOCATION_HELP_STRING "\n\n\
15642 See also the \"delete\" command which clears breakpoints by number."));
15643   add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
15644 
15645   cmd_list_element *break_cmd
15646     = add_com ("break", class_breakpoint, break_command, _("\
15647 Set breakpoint at specified location.\n"
15648 BREAK_ARGS_HELP ("break")));
15649   set_cmd_completer (break_cmd, location_completer);
15650 
15651   add_com_alias ("b", break_cmd, class_run, 1);
15652   add_com_alias ("br", break_cmd, class_run, 1);
15653   add_com_alias ("bre", break_cmd, class_run, 1);
15654   add_com_alias ("brea", break_cmd, class_run, 1);
15655 
15656   if (dbx_commands)
15657     {
15658       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15659 Break in function/address or break at a line in the current file."),
15660 			     &stoplist, 1, &cmdlist);
15661       add_cmd ("in", class_breakpoint, stopin_command,
15662 	       _("Break in function or address."), &stoplist);
15663       add_cmd ("at", class_breakpoint, stopat_command,
15664 	       _("Break at a line in the current file."), &stoplist);
15665       add_com ("status", class_info, info_breakpoints_command, _("\
15666 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15667 The \"Type\" column indicates one of:\n\
15668 \tbreakpoint     - normal breakpoint\n\
15669 \twatchpoint     - watchpoint\n\
15670 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15671 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15672 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15673 address and file/line number respectively.\n\
15674 \n\
15675 Convenience variable \"$_\" and default examine address for \"x\"\n\
15676 are set to the address of the last breakpoint listed unless the command\n\
15677 is prefixed with \"server \".\n\n\
15678 Convenience variable \"$bpnum\" contains the number of the last\n\
15679 breakpoint set."));
15680     }
15681 
15682   cmd_list_element *info_breakpoints_cmd
15683     = add_info ("breakpoints", info_breakpoints_command, _("\
15684 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15685 The \"Type\" column indicates one of:\n\
15686 \tbreakpoint     - normal breakpoint\n\
15687 \twatchpoint     - watchpoint\n\
15688 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15689 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15690 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15691 address and file/line number respectively.\n\
15692 \n\
15693 Convenience variable \"$_\" and default examine address for \"x\"\n\
15694 are set to the address of the last breakpoint listed unless the command\n\
15695 is prefixed with \"server \".\n\n\
15696 Convenience variable \"$bpnum\" contains the number of the last\n\
15697 breakpoint set."));
15698 
15699   add_info_alias ("b", info_breakpoints_cmd, 1);
15700 
15701   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15702 Status of all breakpoints, or breakpoint number NUMBER.\n\
15703 The \"Type\" column indicates one of:\n\
15704 \tbreakpoint     - normal breakpoint\n\
15705 \twatchpoint     - watchpoint\n\
15706 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15707 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15708 \tuntil          - internal breakpoint used by the \"until\" command\n\
15709 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15710 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15711 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15712 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15713 address and file/line number respectively.\n\
15714 \n\
15715 Convenience variable \"$_\" and default examine address for \"x\"\n\
15716 are set to the address of the last breakpoint listed unless the command\n\
15717 is prefixed with \"server \".\n\n\
15718 Convenience variable \"$bpnum\" contains the number of the last\n\
15719 breakpoint set."),
15720 	   &maintenanceinfolist);
15721 
15722   add_basic_prefix_cmd ("catch", class_breakpoint, _("\
15723 Set catchpoints to catch events."),
15724 			&catch_cmdlist,
15725 			0/*allow-unknown*/, &cmdlist);
15726 
15727   add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
15728 Set temporary catchpoints to catch events."),
15729 			&tcatch_cmdlist,
15730 			0/*allow-unknown*/, &cmdlist);
15731 
15732   add_catch_command ("fork", _("Catch calls to fork."),
15733 		     catch_fork_command_1,
15734 		     NULL,
15735 		     (void *) (uintptr_t) catch_fork_permanent,
15736 		     (void *) (uintptr_t) catch_fork_temporary);
15737   add_catch_command ("vfork", _("Catch calls to vfork."),
15738 		     catch_fork_command_1,
15739 		     NULL,
15740 		     (void *) (uintptr_t) catch_vfork_permanent,
15741 		     (void *) (uintptr_t) catch_vfork_temporary);
15742   add_catch_command ("exec", _("Catch calls to exec."),
15743 		     catch_exec_command_1,
15744 		     NULL,
15745 		     CATCH_PERMANENT,
15746 		     CATCH_TEMPORARY);
15747   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15748 Usage: catch load [REGEX]\n\
15749 If REGEX is given, only stop for libraries matching the regular expression."),
15750 		     catch_load_command_1,
15751 		     NULL,
15752 		     CATCH_PERMANENT,
15753 		     CATCH_TEMPORARY);
15754   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15755 Usage: catch unload [REGEX]\n\
15756 If REGEX is given, only stop for libraries matching the regular expression."),
15757 		     catch_unload_command_1,
15758 		     NULL,
15759 		     CATCH_PERMANENT,
15760 		     CATCH_TEMPORARY);
15761 
15762   const auto opts = make_watch_options_def_group (nullptr);
15763 
15764   static const std::string watch_help = gdb::option::build_help (_("\
15765 Set a watchpoint for EXPRESSION.\n\
15766 Usage: watch [-location] EXPRESSION\n\
15767 \n\
15768 Options:\n\
15769 %OPTIONS%\n\
15770 \n\
15771 A watchpoint stops execution of your program whenever the value of\n\
15772 an expression changes."), opts);
15773   c = add_com ("watch", class_breakpoint, watch_command,
15774 	       watch_help.c_str ());
15775   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15776 
15777   static const std::string rwatch_help = gdb::option::build_help (_("\
15778 Set a read watchpoint for EXPRESSION.\n\
15779 Usage: rwatch [-location] EXPRESSION\n\
15780 \n\
15781 Options:\n\
15782 %OPTIONS%\n\
15783 \n\
15784 A read watchpoint stops execution of your program whenever the value of\n\
15785 an expression is read."), opts);
15786   c = add_com ("rwatch", class_breakpoint, rwatch_command,
15787 	       rwatch_help.c_str ());
15788   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15789 
15790   static const std::string awatch_help = gdb::option::build_help (_("\
15791 Set an access watchpoint for EXPRESSION.\n\
15792 Usage: awatch [-location] EXPRESSION\n\
15793 \n\
15794 Options:\n\
15795 %OPTIONS%\n\
15796 \n\
15797 An access watchpoint stops execution of your program whenever the value\n\
15798 of an expression is either read or written."), opts);
15799   c = add_com ("awatch", class_breakpoint, awatch_command,
15800 	       awatch_help.c_str ());
15801   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15802 
15803   add_info ("watchpoints", info_watchpoints_command, _("\
15804 Status of specified watchpoints (all watchpoints if no argument)."));
15805 
15806   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15807      respond to changes - contrary to the description.  */
15808   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15809 			    &can_use_hw_watchpoints, _("\
15810 Set debugger's willingness to use watchpoint hardware."), _("\
15811 Show debugger's willingness to use watchpoint hardware."), _("\
15812 If zero, gdb will not use hardware for new watchpoints, even if\n\
15813 such is available.  (However, any hardware watchpoints that were\n\
15814 created before setting this to nonzero, will continue to use watchpoint\n\
15815 hardware.)"),
15816 			    NULL,
15817 			    show_can_use_hw_watchpoints,
15818 			    &setlist, &showlist);
15819 
15820   can_use_hw_watchpoints = 1;
15821 
15822   /* Tracepoint manipulation commands.  */
15823 
15824   cmd_list_element *trace_cmd
15825     = add_com ("trace", class_breakpoint, trace_command, _("\
15826 Set a tracepoint at specified location.\n\
15827 \n"
15828 BREAK_ARGS_HELP ("trace") "\n\
15829 Do \"help tracepoints\" for info on other tracepoint commands."));
15830   set_cmd_completer (trace_cmd, location_completer);
15831 
15832   add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
15833   add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
15834   add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
15835   add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
15836 
15837   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15838 Set a fast tracepoint at specified location.\n\
15839 \n"
15840 BREAK_ARGS_HELP ("ftrace") "\n\
15841 Do \"help tracepoints\" for info on other tracepoint commands."));
15842   set_cmd_completer (c, location_completer);
15843 
15844   c = add_com ("strace", class_breakpoint, strace_command, _("\
15845 Set a static tracepoint at location or marker.\n\
15846 \n\
15847 strace [LOCATION] [if CONDITION]\n\
15848 LOCATION may be a linespec, explicit, or address location (described below) \n\
15849 or -m MARKER_ID.\n\n\
15850 If a marker id is specified, probe the marker with that name.  With\n\
15851 no LOCATION, uses current execution address of the selected stack frame.\n\
15852 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15853 This collects arbitrary user data passed in the probe point call to the\n\
15854 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15855 by printing the $_sdata variable like any other convenience variable.\n\
15856 \n\
15857 CONDITION is a boolean expression.\n\
15858 \n" LOCATION_HELP_STRING "\n\n\
15859 Multiple tracepoints at one place are permitted, and useful if their\n\
15860 conditions are different.\n\
15861 \n\
15862 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15863 Do \"help tracepoints\" for info on other tracepoint commands."));
15864   set_cmd_completer (c, location_completer);
15865 
15866   cmd_list_element *info_tracepoints_cmd
15867     = add_info ("tracepoints", info_tracepoints_command, _("\
15868 Status of specified tracepoints (all tracepoints if no argument).\n\
15869 Convenience variable \"$tpnum\" contains the number of the\n\
15870 last tracepoint set."));
15871 
15872   add_info_alias ("tp", info_tracepoints_cmd, 1);
15873 
15874   cmd_list_element *delete_tracepoints_cmd
15875     = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15876 Delete specified tracepoints.\n\
15877 Arguments are tracepoint numbers, separated by spaces.\n\
15878 No argument means delete all tracepoints."),
15879 	   &deletelist);
15880   add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
15881 
15882   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15883 Disable specified tracepoints.\n\
15884 Arguments are tracepoint numbers, separated by spaces.\n\
15885 No argument means disable all tracepoints."),
15886 	   &disablelist);
15887   deprecate_cmd (c, "disable");
15888 
15889   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15890 Enable specified tracepoints.\n\
15891 Arguments are tracepoint numbers, separated by spaces.\n\
15892 No argument means enable all tracepoints."),
15893 	   &enablelist);
15894   deprecate_cmd (c, "enable");
15895 
15896   add_com ("passcount", class_trace, trace_pass_command, _("\
15897 Set the passcount for a tracepoint.\n\
15898 The trace will end when the tracepoint has been passed 'count' times.\n\
15899 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15900 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15901 
15902   add_basic_prefix_cmd ("save", class_breakpoint,
15903 			_("Save breakpoint definitions as a script."),
15904 			&save_cmdlist,
15905 			0/*allow-unknown*/, &cmdlist);
15906 
15907   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15908 Save current breakpoint definitions as a script.\n\
15909 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15910 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15911 session to restore them."),
15912 	       &save_cmdlist);
15913   set_cmd_completer (c, filename_completer);
15914 
15915   cmd_list_element *save_tracepoints_cmd
15916     = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15917 Save current tracepoint definitions as a script.\n\
15918 Use the 'source' command in another debug session to restore them."),
15919 	       &save_cmdlist);
15920   set_cmd_completer (save_tracepoints_cmd, filename_completer);
15921 
15922   c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
15923   deprecate_cmd (c, "save tracepoints");
15924 
15925   add_basic_prefix_cmd ("breakpoint", class_maintenance, _("\
15926 Breakpoint specific settings.\n\
15927 Configure various breakpoint-specific variables such as\n\
15928 pending breakpoint behavior."),
15929 			&breakpoint_set_cmdlist,
15930 			0/*allow-unknown*/, &setlist);
15931   add_show_prefix_cmd ("breakpoint", class_maintenance, _("\
15932 Breakpoint specific settings.\n\
15933 Configure various breakpoint-specific variables such as\n\
15934 pending breakpoint behavior."),
15935 		       &breakpoint_show_cmdlist,
15936 		       0/*allow-unknown*/, &showlist);
15937 
15938   add_setshow_auto_boolean_cmd ("pending", no_class,
15939 				&pending_break_support, _("\
15940 Set debugger's behavior regarding pending breakpoints."), _("\
15941 Show debugger's behavior regarding pending breakpoints."), _("\
15942 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15943 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15944 an error.  If auto, an unrecognized breakpoint location results in a\n\
15945 user-query to see if a pending breakpoint should be created."),
15946 				NULL,
15947 				show_pending_break_support,
15948 				&breakpoint_set_cmdlist,
15949 				&breakpoint_show_cmdlist);
15950 
15951   pending_break_support = AUTO_BOOLEAN_AUTO;
15952 
15953   add_setshow_boolean_cmd ("auto-hw", no_class,
15954 			   &automatic_hardware_breakpoints, _("\
15955 Set automatic usage of hardware breakpoints."), _("\
15956 Show automatic usage of hardware breakpoints."), _("\
15957 If set, the debugger will automatically use hardware breakpoints for\n\
15958 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15959 a warning will be emitted for such breakpoints."),
15960 			   NULL,
15961 			   show_automatic_hardware_breakpoints,
15962 			   &breakpoint_set_cmdlist,
15963 			   &breakpoint_show_cmdlist);
15964 
15965   add_setshow_boolean_cmd ("always-inserted", class_support,
15966 			   &always_inserted_mode, _("\
15967 Set mode for inserting breakpoints."), _("\
15968 Show mode for inserting breakpoints."), _("\
15969 When this mode is on, breakpoints are inserted immediately as soon as\n\
15970 they're created, kept inserted even when execution stops, and removed\n\
15971 only when the user deletes them.  When this mode is off (the default),\n\
15972 breakpoints are inserted only when execution continues, and removed\n\
15973 when execution stops."),
15974 				NULL,
15975 				&show_always_inserted_mode,
15976 				&breakpoint_set_cmdlist,
15977 				&breakpoint_show_cmdlist);
15978 
15979   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15980 			condition_evaluation_enums,
15981 			&condition_evaluation_mode_1, _("\
15982 Set mode of breakpoint condition evaluation."), _("\
15983 Show mode of breakpoint condition evaluation."), _("\
15984 When this is set to \"host\", breakpoint conditions will be\n\
15985 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15986 breakpoint conditions will be downloaded to the target (if the target\n\
15987 supports such feature) and conditions will be evaluated on the target's side.\n\
15988 If this is set to \"auto\" (default), this will be automatically set to\n\
15989 \"target\" if it supports condition evaluation, otherwise it will\n\
15990 be set to \"host\"."),
15991 			   &set_condition_evaluation_mode,
15992 			   &show_condition_evaluation_mode,
15993 			   &breakpoint_set_cmdlist,
15994 			   &breakpoint_show_cmdlist);
15995 
15996   add_com ("break-range", class_breakpoint, break_range_command, _("\
15997 Set a breakpoint for an address range.\n\
15998 break-range START-LOCATION, END-LOCATION\n\
15999 where START-LOCATION and END-LOCATION can be one of the following:\n\
16000   LINENUM, for that line in the current file,\n\
16001   FILE:LINENUM, for that line in that file,\n\
16002   +OFFSET, for that number of lines after the current line\n\
16003 	   or the start of the range\n\
16004   FUNCTION, for the first line in that function,\n\
16005   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16006   *ADDRESS, for the instruction at that address.\n\
16007 \n\
16008 The breakpoint will stop execution of the inferior whenever it executes\n\
16009 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16010 range (including START-LOCATION and END-LOCATION)."));
16011 
16012   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16013 Set a dynamic printf at specified location.\n\
16014 dprintf location,format string,arg1,arg2,...\n\
16015 location may be a linespec, explicit, or address location.\n"
16016 "\n" LOCATION_HELP_STRING));
16017   set_cmd_completer (c, location_completer);
16018 
16019   add_setshow_enum_cmd ("dprintf-style", class_support,
16020 			dprintf_style_enums, &dprintf_style, _("\
16021 Set the style of usage for dynamic printf."), _("\
16022 Show the style of usage for dynamic printf."), _("\
16023 This setting chooses how GDB will do a dynamic printf.\n\
16024 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16025 console, as with the \"printf\" command.\n\
16026 If the value is \"call\", the print is done by calling a function in your\n\
16027 program; by default printf(), but you can choose a different function or\n\
16028 output stream by setting dprintf-function and dprintf-channel."),
16029 			update_dprintf_commands, NULL,
16030 			&setlist, &showlist);
16031 
16032   dprintf_function = xstrdup ("printf");
16033   add_setshow_string_cmd ("dprintf-function", class_support,
16034 			  &dprintf_function, _("\
16035 Set the function to use for dynamic printf."), _("\
16036 Show the function to use for dynamic printf."), NULL,
16037 			  update_dprintf_commands, NULL,
16038 			  &setlist, &showlist);
16039 
16040   dprintf_channel = xstrdup ("");
16041   add_setshow_string_cmd ("dprintf-channel", class_support,
16042 			  &dprintf_channel, _("\
16043 Set the channel to use for dynamic printf."), _("\
16044 Show the channel to use for dynamic printf."), NULL,
16045 			  update_dprintf_commands, NULL,
16046 			  &setlist, &showlist);
16047 
16048   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16049 			   &disconnected_dprintf, _("\
16050 Set whether dprintf continues after GDB disconnects."), _("\
16051 Show whether dprintf continues after GDB disconnects."), _("\
16052 Use this to let dprintf commands continue to hit and produce output\n\
16053 even if GDB disconnects or detaches from the target."),
16054 			   NULL,
16055 			   NULL,
16056 			   &setlist, &showlist);
16057 
16058   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16059 Target agent only formatted printing, like the C \"printf\" function.\n\
16060 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
16061 This supports most C printf format specifications, like %s, %d, etc.\n\
16062 This is useful for formatted output in user-defined commands."));
16063 
16064   automatic_hardware_breakpoints = true;
16065 
16066   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
16067 					   "breakpoint");
16068   gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
16069 				      "breakpoint");
16070 }
16071