xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/breakpoint.c (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1 /* Everything about breakpoints, for GDB.
2 
3    Copyright (C) 1986-2023 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observable.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdbsupport/gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "stack.h"
63 #include "ax-gdb.h"
64 #include "dummy-frame.h"
65 #include "interps.h"
66 #include "gdbsupport/format.h"
67 #include "thread-fsm.h"
68 #include "tid-parse.h"
69 #include "cli/cli-style.h"
70 #include "cli/cli-decode.h"
71 
72 /* readline include files */
73 #include "readline/tilde.h"
74 
75 /* readline defines this.  */
76 #undef savestring
77 
78 #include "mi/mi-common.h"
79 #include "extension.h"
80 #include <algorithm>
81 #include "progspace-and-thread.h"
82 #include "gdbsupport/array-view.h"
83 #include "gdbsupport/gdb_optional.h"
84 
85 /* Prototypes for local functions.  */
86 
87 static void map_breakpoint_numbers (const char *,
88 				    gdb::function_view<void (breakpoint *)>);
89 
90 static void
91   create_sals_from_location_spec_default (location_spec *locspec,
92 					  linespec_result *canonical);
93 
94 static void create_breakpoints_sal (struct gdbarch *,
95 				    struct linespec_result *,
96 				    gdb::unique_xmalloc_ptr<char>,
97 				    gdb::unique_xmalloc_ptr<char>,
98 				    enum bptype,
99 				    enum bpdisp, int, int,
100 				    int,
101 				    int, int, int, unsigned);
102 
103 static int can_use_hardware_watchpoint
104     (const std::vector<value_ref_ptr> &vals);
105 
106 static void mention (const breakpoint *);
107 
108 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
109 
110 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
111 
112 static struct breakpoint *
113   momentary_breakpoint_from_master (struct breakpoint *orig,
114 				    enum bptype type,
115 				    int loc_enabled, int thread);
116 
117 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, bool);
118 
119 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
120 					    CORE_ADDR bpaddr,
121 					    enum bptype bptype,
122 					    struct program_space *pspace);
123 
124 static bool watchpoint_locations_match (const struct bp_location *loc1,
125 					const struct bp_location *loc2);
126 
127 static bool breakpoint_locations_match (const struct bp_location *loc1,
128 					const struct bp_location *loc2,
129 					bool sw_hw_bps_match = false);
130 
131 static bool breakpoint_location_address_match (struct bp_location *bl,
132 					       const struct address_space *aspace,
133 					       CORE_ADDR addr);
134 
135 static bool breakpoint_location_address_range_overlap (struct bp_location *,
136 						       const address_space *,
137 						       CORE_ADDR, int);
138 
139 static int remove_breakpoint (struct bp_location *);
140 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
141 
142 static enum print_stop_action print_bp_stop_message (bpstat *bs);
143 
144 static int hw_breakpoint_used_count (void);
145 
146 static int hw_watchpoint_use_count (struct breakpoint *);
147 
148 static int hw_watchpoint_used_count_others (struct breakpoint *except,
149 					    enum bptype type,
150 					    int *other_type_used);
151 
152 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
153 				    int count);
154 
155 static void decref_bp_location (struct bp_location **loc);
156 
157 static std::vector<symtab_and_line> bkpt_probe_decode_location_spec
158      (struct breakpoint *b,
159       location_spec *locspec,
160       struct program_space *search_pspace);
161 
162 static bool bl_address_is_meaningful (bp_location *loc);
163 
164 static int find_loc_num_by_location (const bp_location *loc);
165 
166 /* update_global_location_list's modes of operation wrt to whether to
167    insert locations now.  */
168 enum ugll_insert_mode
169 {
170   /* Don't insert any breakpoint locations into the inferior, only
171      remove already-inserted locations that no longer should be
172      inserted.  Functions that delete a breakpoint or breakpoints
173      should specify this mode, so that deleting a breakpoint doesn't
174      have the side effect of inserting the locations of other
175      breakpoints that are marked not-inserted, but should_be_inserted
176      returns true on them.
177 
178      This behavior is useful is situations close to tear-down -- e.g.,
179      after an exec, while the target still has execution, but
180      breakpoint shadows of the previous executable image should *NOT*
181      be restored to the new image; or before detaching, where the
182      target still has execution and wants to delete breakpoints from
183      GDB's lists, and all breakpoints had already been removed from
184      the inferior.  */
185   UGLL_DONT_INSERT,
186 
187   /* May insert breakpoints iff breakpoints_should_be_inserted_now
188      claims breakpoints should be inserted now.  */
189   UGLL_MAY_INSERT,
190 
191   /* Insert locations now, irrespective of
192      breakpoints_should_be_inserted_now.  E.g., say all threads are
193      stopped right now, and the user did "continue".  We need to
194      insert breakpoints _before_ resuming the target, but
195      UGLL_MAY_INSERT wouldn't insert them, because
196      breakpoints_should_be_inserted_now returns false at that point,
197      as no thread is running yet.  */
198   UGLL_INSERT
199 };
200 
201 static void update_global_location_list (enum ugll_insert_mode);
202 
203 static void update_global_location_list_nothrow (enum ugll_insert_mode);
204 
205 static void insert_breakpoint_locations (void);
206 
207 static void trace_pass_command (const char *, int);
208 
209 static void set_tracepoint_count (int num);
210 
211 static bool is_masked_watchpoint (const struct breakpoint *b);
212 
213 /* Return true if B refers to a static tracepoint set by marker ("-m"),
214    zero otherwise.  */
215 
216 static bool strace_marker_p (struct breakpoint *b);
217 
218 static void bkpt_probe_create_sals_from_location_spec
219      (location_spec *locspec,
220       struct linespec_result *canonical);
221 static void tracepoint_probe_create_sals_from_location_spec
222      (location_spec *locspec,
223       struct linespec_result *canonical);
224 
225 const struct breakpoint_ops code_breakpoint_ops =
226 {
227   create_sals_from_location_spec_default,
228   create_breakpoints_sal,
229 };
230 
231 /* Breakpoints set on probes.  */
232 static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
233 {
234   bkpt_probe_create_sals_from_location_spec,
235   create_breakpoints_sal,
236 };
237 
238 /* Tracepoints set on probes.  */
239 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
240 {
241   tracepoint_probe_create_sals_from_location_spec,
242   create_breakpoints_sal,
243 };
244 
245 /* Implementation of abstract dtors.  These must exist to satisfy the
246    linker.  */
247 
248 breakpoint::~breakpoint ()
249 {
250 }
251 
252 code_breakpoint::~code_breakpoint ()
253 {
254 }
255 
256 catchpoint::~catchpoint ()
257 {
258 }
259 
260 /* The structure to be used in regular breakpoints.  */
261 struct ordinary_breakpoint : public code_breakpoint
262 {
263   using code_breakpoint::code_breakpoint;
264 
265   int resources_needed (const struct bp_location *) override;
266   enum print_stop_action print_it (const bpstat *bs) const override;
267   void print_mention () const override;
268   void print_recreate (struct ui_file *fp) const override;
269 };
270 
271 /* Internal breakpoints.  These typically have a lifetime the same as
272    the program, and they end up installed on the breakpoint chain with
273    a negative breakpoint number.  They're visible in "maint info
274    breakpoints", but not "info breakpoints".  */
275 struct internal_breakpoint : public code_breakpoint
276 {
277   internal_breakpoint (struct gdbarch *gdbarch,
278 		       enum bptype type, CORE_ADDR address)
279     : code_breakpoint (gdbarch, type)
280   {
281     symtab_and_line sal;
282     sal.pc = address;
283     sal.section = find_pc_overlay (sal.pc);
284     sal.pspace = current_program_space;
285     add_location (sal);
286 
287     pspace = current_program_space;
288     disposition = disp_donttouch;
289   }
290 
291   void re_set () override;
292   void check_status (struct bpstat *bs) override;
293   enum print_stop_action print_it (const bpstat *bs) const override;
294   void print_mention () const override;
295 };
296 
297 /* Momentary breakpoints.  These typically have a lifetime of some run
298    control command only, are always thread-specific, and have 0 for
299    breakpoint number.  I.e., there can be many momentary breakpoints
300    on the breakpoint chain and they all same the same number (zero).
301    They're visible in "maint info breakpoints", but not "info
302    breakpoints".  */
303 struct momentary_breakpoint : public code_breakpoint
304 {
305   momentary_breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
306 			program_space *pspace_,
307 			const struct frame_id &frame_id_,
308 			int thread_)
309     : code_breakpoint (gdbarch_, bptype)
310   {
311     /* If FRAME_ID is valid, it should be a real frame, not an inlined
312        or tail-called one.  */
313     gdb_assert (!frame_id_artificial_p (frame_id));
314 
315     /* Momentary breakpoints are always thread-specific.  */
316     gdb_assert (thread_ > 0);
317 
318     pspace = pspace_;
319     enable_state = bp_enabled;
320     disposition = disp_donttouch;
321     frame_id = frame_id_;
322     thread = thread_;
323   }
324 
325   void re_set () override;
326   void check_status (struct bpstat *bs) override;
327   enum print_stop_action print_it (const bpstat *bs) const override;
328   void print_mention () const override;
329 };
330 
331 /* DPrintf breakpoints.  */
332 struct dprintf_breakpoint : public ordinary_breakpoint
333 {
334   using ordinary_breakpoint::ordinary_breakpoint;
335 
336   void re_set () override;
337   int breakpoint_hit (const struct bp_location *bl,
338 		      const address_space *aspace,
339 		      CORE_ADDR bp_addr,
340 		      const target_waitstatus &ws) override;
341   void print_recreate (struct ui_file *fp) const override;
342   void after_condition_true (struct bpstat *bs) override;
343 };
344 
345 /* Ranged breakpoints.  */
346 struct ranged_breakpoint : public ordinary_breakpoint
347 {
348   explicit ranged_breakpoint (struct gdbarch *gdbarch,
349 			      const symtab_and_line &sal_start,
350 			      int length,
351 			      location_spec_up start_locspec,
352 			      location_spec_up end_locspec)
353     : ordinary_breakpoint (gdbarch, bp_hardware_breakpoint)
354   {
355     bp_location *bl = add_location (sal_start);
356     bl->length = length;
357 
358     disposition = disp_donttouch;
359 
360     locspec = std::move (start_locspec);
361     locspec_range_end = std::move (end_locspec);
362   }
363 
364   int breakpoint_hit (const struct bp_location *bl,
365 		      const address_space *aspace,
366 		      CORE_ADDR bp_addr,
367 		      const target_waitstatus &ws) override;
368   int resources_needed (const struct bp_location *) override;
369   enum print_stop_action print_it (const bpstat *bs) const override;
370   bool print_one (bp_location **) const override;
371   void print_one_detail (struct ui_out *) const override;
372   void print_mention () const override;
373   void print_recreate (struct ui_file *fp) const override;
374 };
375 
376 /* Static tracepoints with marker (`-m').  */
377 struct static_marker_tracepoint : public tracepoint
378 {
379   using tracepoint::tracepoint;
380 
381   std::vector<symtab_and_line> decode_location_spec
382        (struct location_spec *locspec,
383 	struct program_space *search_pspace) override;
384 };
385 
386 /* The style in which to perform a dynamic printf.  This is a user
387    option because different output options have different tradeoffs;
388    if GDB does the printing, there is better error handling if there
389    is a problem with any of the arguments, but using an inferior
390    function lets you have special-purpose printers and sending of
391    output to the same place as compiled-in print functions.  */
392 
393 static const char dprintf_style_gdb[] = "gdb";
394 static const char dprintf_style_call[] = "call";
395 static const char dprintf_style_agent[] = "agent";
396 static const char *const dprintf_style_enums[] = {
397   dprintf_style_gdb,
398   dprintf_style_call,
399   dprintf_style_agent,
400   NULL
401 };
402 static const char *dprintf_style = dprintf_style_gdb;
403 
404 /* The function to use for dynamic printf if the preferred style is to
405    call into the inferior.  The value is simply a string that is
406    copied into the command, so it can be anything that GDB can
407    evaluate to a callable address, not necessarily a function name.  */
408 
409 static std::string dprintf_function = "printf";
410 
411 /* The channel to use for dynamic printf if the preferred style is to
412    call into the inferior; if a nonempty string, it will be passed to
413    the call as the first argument, with the format string as the
414    second.  As with the dprintf function, this can be anything that
415    GDB knows how to evaluate, so in addition to common choices like
416    "stderr", this could be an app-specific expression like
417    "mystreams[curlogger]".  */
418 
419 static std::string dprintf_channel;
420 
421 /* True if dprintf commands should continue to operate even if GDB
422    has disconnected.  */
423 static bool disconnected_dprintf = true;
424 
425 struct command_line *
426 breakpoint_commands (struct breakpoint *b)
427 {
428   return b->commands ? b->commands.get () : NULL;
429 }
430 
431 /* Flag indicating that a command has proceeded the inferior past the
432    current breakpoint.  */
433 
434 static bool breakpoint_proceeded;
435 
436 const char *
437 bpdisp_text (enum bpdisp disp)
438 {
439   /* NOTE: the following values are a part of MI protocol and
440      represent values of 'disp' field returned when inferior stops at
441      a breakpoint.  */
442   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
443 
444   return bpdisps[(int) disp];
445 }
446 
447 /* Prototypes for exported functions.  */
448 /* If FALSE, gdb will not use hardware support for watchpoints, even
449    if such is available.  */
450 static int can_use_hw_watchpoints;
451 
452 static void
453 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
454 			     struct cmd_list_element *c,
455 			     const char *value)
456 {
457   gdb_printf (file,
458 	      _("Debugger's willingness to use "
459 		"watchpoint hardware is %s.\n"),
460 	      value);
461 }
462 
463 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
464    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
465    for unrecognized breakpoint locations.
466    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
467 static enum auto_boolean pending_break_support;
468 static void
469 show_pending_break_support (struct ui_file *file, int from_tty,
470 			    struct cmd_list_element *c,
471 			    const char *value)
472 {
473   gdb_printf (file,
474 	      _("Debugger's behavior regarding "
475 		"pending breakpoints is %s.\n"),
476 	      value);
477 }
478 
479 /* If true, gdb will automatically use hardware breakpoints for breakpoints
480    set with "break" but falling in read-only memory.
481    If false, gdb will warn about such breakpoints, but won't automatically
482    use hardware breakpoints.  */
483 static bool automatic_hardware_breakpoints;
484 static void
485 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
486 				     struct cmd_list_element *c,
487 				     const char *value)
488 {
489   gdb_printf (file,
490 	      _("Automatic usage of hardware breakpoints is %s.\n"),
491 	      value);
492 }
493 
494 /* If on, GDB keeps breakpoints inserted even if the inferior is
495    stopped, and immediately inserts any new breakpoints as soon as
496    they're created.  If off (default), GDB keeps breakpoints off of
497    the target as long as possible.  That is, it delays inserting
498    breakpoints until the next resume, and removes them again when the
499    target fully stops.  This is a bit safer in case GDB crashes while
500    processing user input.  */
501 static bool always_inserted_mode = false;
502 
503 static void
504 show_always_inserted_mode (struct ui_file *file, int from_tty,
505 		     struct cmd_list_element *c, const char *value)
506 {
507   gdb_printf (file, _("Always inserted breakpoint mode is %s.\n"),
508 	      value);
509 }
510 
511 /* See breakpoint.h.  */
512 
513 int
514 breakpoints_should_be_inserted_now (void)
515 {
516   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
517     {
518       /* If breakpoints are global, they should be inserted even if no
519 	 thread under gdb's control is running, or even if there are
520 	 no threads under GDB's control yet.  */
521       return 1;
522     }
523   else
524     {
525       if (always_inserted_mode)
526 	{
527 	  /* The user wants breakpoints inserted even if all threads
528 	     are stopped.  */
529 	  return 1;
530 	}
531 
532       for (inferior *inf : all_inferiors ())
533 	if (inf->has_execution ()
534 	    && threads_are_executing (inf->process_target ()))
535 	  return 1;
536 
537       /* Don't remove breakpoints yet if, even though all threads are
538 	 stopped, we still have events to process.  */
539       for (thread_info *tp : all_non_exited_threads ())
540 	if (tp->resumed () && tp->has_pending_waitstatus ())
541 	  return 1;
542     }
543   return 0;
544 }
545 
546 static const char condition_evaluation_both[] = "host or target";
547 
548 /* Modes for breakpoint condition evaluation.  */
549 static const char condition_evaluation_auto[] = "auto";
550 static const char condition_evaluation_host[] = "host";
551 static const char condition_evaluation_target[] = "target";
552 static const char *const condition_evaluation_enums[] = {
553   condition_evaluation_auto,
554   condition_evaluation_host,
555   condition_evaluation_target,
556   NULL
557 };
558 
559 /* Global that holds the current mode for breakpoint condition evaluation.  */
560 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
561 
562 /* Global that we use to display information to the user (gets its value from
563    condition_evaluation_mode_1.  */
564 static const char *condition_evaluation_mode = condition_evaluation_auto;
565 
566 /* Translate a condition evaluation mode MODE into either "host"
567    or "target".  This is used mostly to translate from "auto" to the
568    real setting that is being used.  It returns the translated
569    evaluation mode.  */
570 
571 static const char *
572 translate_condition_evaluation_mode (const char *mode)
573 {
574   if (mode == condition_evaluation_auto)
575     {
576       if (target_supports_evaluation_of_breakpoint_conditions ())
577 	return condition_evaluation_target;
578       else
579 	return condition_evaluation_host;
580     }
581   else
582     return mode;
583 }
584 
585 /* Discovers what condition_evaluation_auto translates to.  */
586 
587 static const char *
588 breakpoint_condition_evaluation_mode (void)
589 {
590   return translate_condition_evaluation_mode (condition_evaluation_mode);
591 }
592 
593 /* Return true if GDB should evaluate breakpoint conditions or false
594    otherwise.  */
595 
596 static bool
597 gdb_evaluates_breakpoint_condition_p (void)
598 {
599   const char *mode = breakpoint_condition_evaluation_mode ();
600 
601   return (mode == condition_evaluation_host);
602 }
603 
604 /* Are we executing breakpoint commands?  */
605 static int executing_breakpoint_commands;
606 
607 /* Are overlay event breakpoints enabled? */
608 static int overlay_events_enabled;
609 
610 /* See description in breakpoint.h. */
611 bool target_exact_watchpoints = false;
612 
613 /* Walk the following statement or block through all breakpoints.
614    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
615    current breakpoint.  */
616 
617 #define ALL_BREAKPOINTS_SAFE(B,TMP)	\
618 	for (B = breakpoint_chain;	\
619 	     B ? (TMP=B->next, 1): 0;	\
620 	     B = TMP)
621 
622 /* Chains of all breakpoints defined.  */
623 
624 static struct breakpoint *breakpoint_chain;
625 
626 /* See breakpoint.h.  */
627 
628 breakpoint_range
629 all_breakpoints ()
630 {
631   return breakpoint_range (breakpoint_chain);
632 }
633 
634 /* See breakpoint.h.  */
635 
636 breakpoint_safe_range
637 all_breakpoints_safe ()
638 {
639   return breakpoint_safe_range (all_breakpoints ());
640 }
641 
642 /* See breakpoint.h.  */
643 
644 tracepoint_range
645 all_tracepoints ()
646 {
647   return tracepoint_range (breakpoint_chain);
648 }
649 
650 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS.  */
651 
652 static std::vector<bp_location *> bp_locations;
653 
654 /* See breakpoint.h.  */
655 
656 const std::vector<bp_location *> &
657 all_bp_locations ()
658 {
659   return bp_locations;
660 }
661 
662 /* Range to iterate over breakpoint locations at a given address.  */
663 
664 struct bp_locations_at_addr_range
665 {
666   using iterator = std::vector<bp_location *>::iterator;
667 
668   bp_locations_at_addr_range (CORE_ADDR addr)
669   {
670     struct compare
671     {
672       bool operator() (const bp_location *loc, CORE_ADDR addr_) const
673       { return loc->address < addr_; }
674 
675       bool operator() (CORE_ADDR addr_, const bp_location *loc) const
676       { return addr_ < loc->address; }
677     };
678 
679     auto it_pair = std::equal_range (bp_locations.begin (), bp_locations.end (),
680 				     addr, compare ());
681 
682     m_begin = it_pair.first;
683     m_end = it_pair.second;
684   }
685 
686   iterator begin () const
687   { return m_begin; }
688 
689   iterator end () const
690   { return m_end; }
691 
692 private:
693   iterator m_begin;
694   iterator m_end;
695 };
696 
697 /* Return a range to iterate over all breakpoint locations exactly at address
698    ADDR.
699 
700    If it's needed to iterate multiple times on the same range, it's possible
701    to save the range in a local variable and use it multiple times:
702 
703      auto range = all_bp_locations_at_addr (addr);
704 
705      for (bp_location *loc : range)
706        // use loc
707 
708      for (bp_location *loc : range)
709        // use loc
710 
711    This saves a bit of time, as it avoids re-doing the binary searches to find
712    the range's boundaries.  Just remember not to change the bp_locations vector
713    in the mean time, as it could make the range's iterators stale.  */
714 
715 static bp_locations_at_addr_range
716 all_bp_locations_at_addr (CORE_ADDR addr)
717 {
718   return bp_locations_at_addr_range (addr);
719 }
720 
721 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
722    ADDRESS for the current elements of BP_LOCATIONS which get a valid
723    result from bp_location_has_shadow.  You can use it for roughly
724    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
725    an address you need to read.  */
726 
727 static CORE_ADDR bp_locations_placed_address_before_address_max;
728 
729 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
730    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
731    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
732    You can use it for roughly limiting the subrange of BP_LOCATIONS to
733    scan for shadow bytes for an address you need to read.  */
734 
735 static CORE_ADDR bp_locations_shadow_len_after_address_max;
736 
737 /* The locations that no longer correspond to any breakpoint, unlinked
738    from the bp_locations array, but for which a hit may still be
739    reported by a target.  */
740 static std::vector<bp_location *> moribund_locations;
741 
742 /* Number of last breakpoint made.  */
743 
744 static int breakpoint_count;
745 
746 /* The value of `breakpoint_count' before the last command that
747    created breakpoints.  If the last (break-like) command created more
748    than one breakpoint, then the difference between BREAKPOINT_COUNT
749    and PREV_BREAKPOINT_COUNT is more than one.  */
750 static int prev_breakpoint_count;
751 
752 /* Number of last tracepoint made.  */
753 
754 static int tracepoint_count;
755 
756 static struct cmd_list_element *breakpoint_set_cmdlist;
757 static struct cmd_list_element *breakpoint_show_cmdlist;
758 struct cmd_list_element *save_cmdlist;
759 
760 /* Return whether a breakpoint is an active enabled breakpoint.  */
761 static bool
762 breakpoint_enabled (struct breakpoint *b)
763 {
764   return (b->enable_state == bp_enabled);
765 }
766 
767 /* Set breakpoint count to NUM.  */
768 
769 static void
770 set_breakpoint_count (int num)
771 {
772   prev_breakpoint_count = breakpoint_count;
773   breakpoint_count = num;
774   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
775 }
776 
777 /* Used by `start_rbreak_breakpoints' below, to record the current
778    breakpoint count before "rbreak" creates any breakpoint.  */
779 static int rbreak_start_breakpoint_count;
780 
781 /* Called at the start an "rbreak" command to record the first
782    breakpoint made.  */
783 
784 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
785 {
786   rbreak_start_breakpoint_count = breakpoint_count;
787 }
788 
789 /* Called at the end of an "rbreak" command to record the last
790    breakpoint made.  */
791 
792 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
793 {
794   prev_breakpoint_count = rbreak_start_breakpoint_count;
795 }
796 
797 /* Used in run_command to zero the hit count when a new run starts.  */
798 
799 void
800 clear_breakpoint_hit_counts (void)
801 {
802   for (breakpoint *b : all_breakpoints ())
803     b->hit_count = 0;
804 }
805 
806 
807 /* Return the breakpoint with the specified number, or NULL
808    if the number does not refer to an existing breakpoint.  */
809 
810 struct breakpoint *
811 get_breakpoint (int num)
812 {
813   for (breakpoint *b : all_breakpoints ())
814     if (b->number == num)
815       return b;
816 
817   return nullptr;
818 }
819 
820 /* Return TRUE if NUM refer to an existing breakpoint that has
821    multiple code locations.  */
822 
823 static bool
824 has_multiple_locations (int num)
825 {
826   for (breakpoint *b : all_breakpoints ())
827     if (b->number == num)
828       return b->loc != nullptr && b->loc->next != nullptr;
829 
830   return false;
831 }
832 
833 
834 
835 /* Mark locations as "conditions have changed" in case the target supports
836    evaluating conditions on its side.  */
837 
838 static void
839 mark_breakpoint_modified (struct breakpoint *b)
840 {
841   /* This is only meaningful if the target is
842      evaluating conditions and if the user has
843      opted for condition evaluation on the target's
844      side.  */
845   if (gdb_evaluates_breakpoint_condition_p ()
846       || !target_supports_evaluation_of_breakpoint_conditions ())
847     return;
848 
849   if (!is_breakpoint (b))
850     return;
851 
852   for (bp_location *loc : b->locations ())
853     loc->condition_changed = condition_modified;
854 }
855 
856 /* Mark location as "conditions have changed" in case the target supports
857    evaluating conditions on its side.  */
858 
859 static void
860 mark_breakpoint_location_modified (struct bp_location *loc)
861 {
862   /* This is only meaningful if the target is
863      evaluating conditions and if the user has
864      opted for condition evaluation on the target's
865      side.  */
866   if (gdb_evaluates_breakpoint_condition_p ()
867       || !target_supports_evaluation_of_breakpoint_conditions ())
868 
869     return;
870 
871   if (!is_breakpoint (loc->owner))
872     return;
873 
874   loc->condition_changed = condition_modified;
875 }
876 
877 /* Sets the condition-evaluation mode using the static global
878    condition_evaluation_mode.  */
879 
880 static void
881 set_condition_evaluation_mode (const char *args, int from_tty,
882 			       struct cmd_list_element *c)
883 {
884   const char *old_mode, *new_mode;
885 
886   if ((condition_evaluation_mode_1 == condition_evaluation_target)
887       && !target_supports_evaluation_of_breakpoint_conditions ())
888     {
889       condition_evaluation_mode_1 = condition_evaluation_mode;
890       warning (_("Target does not support breakpoint condition evaluation.\n"
891 		 "Using host evaluation mode instead."));
892       return;
893     }
894 
895   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
896   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
897 
898   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
899      settings was "auto".  */
900   condition_evaluation_mode = condition_evaluation_mode_1;
901 
902   /* Only update the mode if the user picked a different one.  */
903   if (new_mode != old_mode)
904     {
905       /* If the user switched to a different evaluation mode, we
906 	 need to synch the changes with the target as follows:
907 
908 	 "host" -> "target": Send all (valid) conditions to the target.
909 	 "target" -> "host": Remove all the conditions from the target.
910       */
911 
912       if (new_mode == condition_evaluation_target)
913 	{
914 	  /* Mark everything modified and synch conditions with the
915 	     target.  */
916 	  for (bp_location *loc : all_bp_locations ())
917 	    mark_breakpoint_location_modified (loc);
918 	}
919       else
920 	{
921 	  /* Manually mark non-duplicate locations to synch conditions
922 	     with the target.  We do this to remove all the conditions the
923 	     target knows about.  */
924 	  for (bp_location *loc : all_bp_locations ())
925 	    if (is_breakpoint (loc->owner) && loc->inserted)
926 	      loc->needs_update = 1;
927 	}
928 
929       /* Do the update.  */
930       update_global_location_list (UGLL_MAY_INSERT);
931     }
932 
933   return;
934 }
935 
936 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
937    what "auto" is translating to.  */
938 
939 static void
940 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
941 				struct cmd_list_element *c, const char *value)
942 {
943   if (condition_evaluation_mode == condition_evaluation_auto)
944     gdb_printf (file,
945 		_("Breakpoint condition evaluation "
946 		  "mode is %s (currently %s).\n"),
947 		value,
948 		breakpoint_condition_evaluation_mode ());
949   else
950     gdb_printf (file, _("Breakpoint condition evaluation mode is %s.\n"),
951 		value);
952 }
953 
954 /* Parse COND_STRING in the context of LOC and set as the condition
955    expression of LOC.  BP_NUM is the number of LOC's owner, LOC_NUM is
956    the number of LOC within its owner.  In case of parsing error, mark
957    LOC as DISABLED_BY_COND.  In case of success, unset DISABLED_BY_COND.  */
958 
959 static void
960 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
961 				   int bp_num, int loc_num)
962 {
963   bool has_junk = false;
964   try
965     {
966       expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
967 					   block_for_pc (loc->address), 0);
968       if (*cond_string != 0)
969 	has_junk = true;
970       else
971 	{
972 	  loc->cond = std::move (new_exp);
973 	  if (loc->disabled_by_cond && loc->enabled)
974 	    gdb_printf (_("Breakpoint %d's condition is now valid at "
975 			  "location %d, enabling.\n"),
976 			bp_num, loc_num);
977 
978 	  loc->disabled_by_cond = false;
979 	}
980     }
981   catch (const gdb_exception_error &e)
982     {
983       if (loc->enabled)
984 	{
985 	  /* Warn if a user-enabled location is now becoming disabled-by-cond.
986 	     BP_NUM is 0 if the breakpoint is being defined for the first
987 	     time using the "break ... if ..." command, and non-zero if
988 	     already defined.  */
989 	  if (bp_num != 0)
990 	    warning (_("failed to validate condition at location %d.%d, "
991 		       "disabling:\n  %s"), bp_num, loc_num, e.what ());
992 	  else
993 	    warning (_("failed to validate condition at location %d, "
994 		       "disabling:\n  %s"), loc_num, e.what ());
995 	}
996 
997       loc->disabled_by_cond = true;
998     }
999 
1000   if (has_junk)
1001     error (_("Garbage '%s' follows condition"), cond_string);
1002 }
1003 
1004 void
1005 set_breakpoint_condition (struct breakpoint *b, const char *exp,
1006 			  int from_tty, bool force)
1007 {
1008   if (*exp == 0)
1009     {
1010       b->cond_string.reset ();
1011 
1012       if (is_watchpoint (b))
1013 	gdb::checked_static_cast<watchpoint *> (b)->cond_exp.reset ();
1014       else
1015 	{
1016 	  int loc_num = 1;
1017 	  for (bp_location *loc : b->locations ())
1018 	    {
1019 	      loc->cond.reset ();
1020 	      if (loc->disabled_by_cond && loc->enabled)
1021 		gdb_printf (_("Breakpoint %d's condition is now valid at "
1022 			      "location %d, enabling.\n"),
1023 			    b->number, loc_num);
1024 	      loc->disabled_by_cond = false;
1025 	      loc_num++;
1026 
1027 	      /* No need to free the condition agent expression
1028 		 bytecode (if we have one).  We will handle this
1029 		 when we go through update_global_location_list.  */
1030 	    }
1031 	}
1032 
1033       if (from_tty)
1034 	gdb_printf (_("Breakpoint %d now unconditional.\n"), b->number);
1035     }
1036   else
1037     {
1038       if (is_watchpoint (b))
1039 	{
1040 	  innermost_block_tracker tracker;
1041 	  const char *arg = exp;
1042 	  expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
1043 	  if (*arg != 0)
1044 	    error (_("Junk at end of expression"));
1045 	  watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
1046 	  w->cond_exp = std::move (new_exp);
1047 	  w->cond_exp_valid_block = tracker.block ();
1048 	}
1049       else
1050 	{
1051 	  /* Parse and set condition expressions.  We make two passes.
1052 	     In the first, we parse the condition string to see if it
1053 	     is valid in at least one location.  If so, the condition
1054 	     would be accepted.  So we go ahead and set the locations'
1055 	     conditions.  In case no valid case is found, we throw
1056 	     the error and the condition string will be rejected.
1057 	     This two-pass approach is taken to avoid setting the
1058 	     state of locations in case of a reject.  */
1059 	  for (bp_location *loc : b->locations ())
1060 	    {
1061 	      try
1062 		{
1063 		  const char *arg = exp;
1064 		  parse_exp_1 (&arg, loc->address,
1065 			       block_for_pc (loc->address), 0);
1066 		  if (*arg != 0)
1067 		    error (_("Junk at end of expression"));
1068 		  break;
1069 		}
1070 	      catch (const gdb_exception_error &e)
1071 		{
1072 		  /* Condition string is invalid.  If this happens to
1073 		     be the last loc, abandon (if not forced) or continue
1074 		     (if forced).  */
1075 		  if (loc->next == nullptr && !force)
1076 		    throw;
1077 		}
1078 	    }
1079 
1080 	  /* If we reach here, the condition is valid at some locations.  */
1081 	  int loc_num = 1;
1082 	  for (bp_location *loc : b->locations ())
1083 	    {
1084 	      set_breakpoint_location_condition (exp, loc, b->number, loc_num);
1085 	      loc_num++;
1086 	    }
1087 	}
1088 
1089       /* We know that the new condition parsed successfully.  The
1090 	 condition string of the breakpoint can be safely updated.  */
1091       b->cond_string = make_unique_xstrdup (exp);
1092       b->condition_not_parsed = 0;
1093     }
1094   mark_breakpoint_modified (b);
1095 
1096   gdb::observers::breakpoint_modified.notify (b);
1097 }
1098 
1099 /* See breakpoint.h.  */
1100 
1101 void
1102 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
1103 			  bool force)
1104 {
1105   for (breakpoint *b : all_breakpoints ())
1106     if (b->number == bpnum)
1107       {
1108 	/* Check if this breakpoint has a "stop" method implemented in an
1109 	   extension language.  This method and conditions entered into GDB
1110 	   from the CLI are mutually exclusive.  */
1111 	const struct extension_language_defn *extlang
1112 	  = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1113 
1114 	if (extlang != NULL)
1115 	  {
1116 	    error (_("Only one stop condition allowed.  There is currently"
1117 		     " a %s stop condition defined for this breakpoint."),
1118 		   ext_lang_capitalized_name (extlang));
1119 	  }
1120 	set_breakpoint_condition (b, exp, from_tty, force);
1121 
1122 	if (is_breakpoint (b))
1123 	  update_global_location_list (UGLL_MAY_INSERT);
1124 
1125 	return;
1126       }
1127 
1128   error (_("No breakpoint number %d."), bpnum);
1129 }
1130 
1131 /* The options for the "condition" command.  */
1132 
1133 struct condition_command_opts
1134 {
1135   /* For "-force".  */
1136   bool force_condition = false;
1137 };
1138 
1139 static const gdb::option::option_def condition_command_option_defs[] = {
1140 
1141   gdb::option::flag_option_def<condition_command_opts> {
1142     "force",
1143     [] (condition_command_opts *opts) { return &opts->force_condition; },
1144     N_("Set the condition even if it is invalid for all current locations."),
1145   },
1146 
1147 };
1148 
1149 /* Create an option_def_group for the "condition" options, with
1150    CC_OPTS as context.  */
1151 
1152 static inline gdb::option::option_def_group
1153 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1154 {
1155   return {{condition_command_option_defs}, cc_opts};
1156 }
1157 
1158 /* Completion for the "condition" command.  */
1159 
1160 static void
1161 condition_completer (struct cmd_list_element *cmd,
1162 		     completion_tracker &tracker,
1163 		     const char *text, const char * /*word*/)
1164 {
1165   bool has_no_arguments = (*text == '\0');
1166   condition_command_opts cc_opts;
1167   const auto group = make_condition_command_options_def_group (&cc_opts);
1168   if (gdb::option::complete_options
1169       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1170     return;
1171 
1172   text = skip_spaces (text);
1173   const char *space = skip_to_space (text);
1174   if (*space == '\0')
1175     {
1176       int len;
1177 
1178       if (text[0] == '$')
1179 	{
1180 	  tracker.advance_custom_word_point_by (1);
1181 	  /* We don't support completion of history indices.  */
1182 	  if (!isdigit (text[1]))
1183 	    complete_internalvar (tracker, &text[1]);
1184 	  return;
1185 	}
1186 
1187       /* Suggest the "-force" flag if no arguments are given.  If
1188 	 arguments were passed, they either already include the flag,
1189 	 or we are beyond the point of suggesting it because it's
1190 	 positionally the first argument.  */
1191       if (has_no_arguments)
1192 	gdb::option::complete_on_all_options (tracker, group);
1193 
1194       /* We're completing the breakpoint number.  */
1195       len = strlen (text);
1196 
1197       for (breakpoint *b : all_breakpoints ())
1198 	{
1199 	  char number[50];
1200 
1201 	  xsnprintf (number, sizeof (number), "%d", b->number);
1202 
1203 	  if (strncmp (number, text, len) == 0)
1204 	    tracker.add_completion (make_unique_xstrdup (number));
1205 	}
1206 
1207       return;
1208     }
1209 
1210   /* We're completing the expression part.  Skip the breakpoint num.  */
1211   const char *exp_start = skip_spaces (space);
1212   tracker.advance_custom_word_point_by (exp_start - text);
1213   text = exp_start;
1214   const char *word = advance_to_expression_complete_word_point (tracker, text);
1215   expression_completer (cmd, tracker, text, word);
1216 }
1217 
1218 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1219 
1220 static void
1221 condition_command (const char *arg, int from_tty)
1222 {
1223   const char *p;
1224   int bnum;
1225 
1226   if (arg == 0)
1227     error_no_arg (_("breakpoint number"));
1228 
1229   p = arg;
1230 
1231   /* Check if the "-force" flag was passed.  */
1232   condition_command_opts cc_opts;
1233   const auto group = make_condition_command_options_def_group (&cc_opts);
1234   gdb::option::process_options
1235     (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1236 
1237   bnum = get_number (&p);
1238   if (bnum == 0)
1239     error (_("Bad breakpoint argument: '%s'"), arg);
1240 
1241   set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1242 }
1243 
1244 /* Check that COMMAND do not contain commands that are suitable
1245    only for tracepoints and not suitable for ordinary breakpoints.
1246    Throw if any such commands is found.  */
1247 
1248 static void
1249 check_no_tracepoint_commands (struct command_line *commands)
1250 {
1251   struct command_line *c;
1252 
1253   for (c = commands; c; c = c->next)
1254     {
1255       if (c->control_type == while_stepping_control)
1256 	error (_("The 'while-stepping' command can "
1257 		 "only be used for tracepoints"));
1258 
1259       check_no_tracepoint_commands (c->body_list_0.get ());
1260       check_no_tracepoint_commands (c->body_list_1.get ());
1261 
1262       /* Not that command parsing removes leading whitespace and comment
1263 	 lines and also empty lines.  So, we only need to check for
1264 	 command directly.  */
1265       if (strstr (c->line, "collect ") == c->line)
1266 	error (_("The 'collect' command can only be used for tracepoints"));
1267 
1268       if (strstr (c->line, "teval ") == c->line)
1269 	error (_("The 'teval' command can only be used for tracepoints"));
1270     }
1271 }
1272 
1273 struct longjmp_breakpoint : public momentary_breakpoint
1274 {
1275   using momentary_breakpoint::momentary_breakpoint;
1276 
1277   ~longjmp_breakpoint () override;
1278 };
1279 
1280 /* Encapsulate tests for different types of tracepoints.  */
1281 
1282 static bool
1283 is_tracepoint_type (bptype type)
1284 {
1285   return (type == bp_tracepoint
1286 	  || type == bp_fast_tracepoint
1287 	  || type == bp_static_tracepoint
1288 	  || type == bp_static_marker_tracepoint);
1289 }
1290 
1291 /* See breakpoint.h.  */
1292 
1293 bool
1294 is_tracepoint (const struct breakpoint *b)
1295 {
1296   return is_tracepoint_type (b->type);
1297 }
1298 
1299 /* Factory function to create an appropriate instance of breakpoint given
1300    TYPE.  */
1301 
1302 template<typename... Arg>
1303 static std::unique_ptr<code_breakpoint>
1304 new_breakpoint_from_type (struct gdbarch *gdbarch, bptype type,
1305 			  Arg&&... args)
1306 {
1307   code_breakpoint *b;
1308 
1309   switch (type)
1310     {
1311     case bp_breakpoint:
1312     case bp_hardware_breakpoint:
1313       b = new ordinary_breakpoint (gdbarch, type,
1314 				   std::forward<Arg> (args)...);
1315       break;
1316 
1317     case bp_fast_tracepoint:
1318     case bp_static_tracepoint:
1319     case bp_tracepoint:
1320       b = new tracepoint (gdbarch, type,
1321 			  std::forward<Arg> (args)...);
1322       break;
1323 
1324     case bp_static_marker_tracepoint:
1325       b = new static_marker_tracepoint (gdbarch, type,
1326 					std::forward<Arg> (args)...);
1327       break;
1328 
1329     case bp_dprintf:
1330       b = new dprintf_breakpoint (gdbarch, type,
1331 				  std::forward<Arg> (args)...);
1332       break;
1333 
1334     default:
1335       gdb_assert_not_reached ("invalid type");
1336     }
1337 
1338   return std::unique_ptr<code_breakpoint> (b);
1339 }
1340 
1341 /* A helper function that validates that COMMANDS are valid for a
1342    breakpoint.  This function will throw an exception if a problem is
1343    found.  */
1344 
1345 static void
1346 validate_commands_for_breakpoint (struct breakpoint *b,
1347 				  struct command_line *commands)
1348 {
1349   if (is_tracepoint (b))
1350     {
1351       struct tracepoint *t = (struct tracepoint *) b;
1352       struct command_line *c;
1353       struct command_line *while_stepping = 0;
1354 
1355       /* Reset the while-stepping step count.  The previous commands
1356 	 might have included a while-stepping action, while the new
1357 	 ones might not.  */
1358       t->step_count = 0;
1359 
1360       /* We need to verify that each top-level element of commands is
1361 	 valid for tracepoints, that there's at most one
1362 	 while-stepping element, and that the while-stepping's body
1363 	 has valid tracing commands excluding nested while-stepping.
1364 	 We also need to validate the tracepoint action line in the
1365 	 context of the tracepoint --- validate_actionline actually
1366 	 has side effects, like setting the tracepoint's
1367 	 while-stepping STEP_COUNT, in addition to checking if the
1368 	 collect/teval actions parse and make sense in the
1369 	 tracepoint's context.  */
1370       for (c = commands; c; c = c->next)
1371 	{
1372 	  if (c->control_type == while_stepping_control)
1373 	    {
1374 	      if (b->type == bp_fast_tracepoint)
1375 		error (_("The 'while-stepping' command "
1376 			 "cannot be used for fast tracepoint"));
1377 	      else if (b->type == bp_static_tracepoint
1378 		       || b->type == bp_static_marker_tracepoint)
1379 		error (_("The 'while-stepping' command "
1380 			 "cannot be used for static tracepoint"));
1381 
1382 	      if (while_stepping)
1383 		error (_("The 'while-stepping' command "
1384 			 "can be used only once"));
1385 	      else
1386 		while_stepping = c;
1387 	    }
1388 
1389 	  validate_actionline (c->line, b);
1390 	}
1391       if (while_stepping)
1392 	{
1393 	  struct command_line *c2;
1394 
1395 	  gdb_assert (while_stepping->body_list_1 == nullptr);
1396 	  c2 = while_stepping->body_list_0.get ();
1397 	  for (; c2; c2 = c2->next)
1398 	    {
1399 	      if (c2->control_type == while_stepping_control)
1400 		error (_("The 'while-stepping' command cannot be nested"));
1401 	    }
1402 	}
1403     }
1404   else
1405     {
1406       check_no_tracepoint_commands (commands);
1407     }
1408 }
1409 
1410 /* Return a vector of all the static tracepoints set at ADDR.  The
1411    caller is responsible for releasing the vector.  */
1412 
1413 std::vector<breakpoint *>
1414 static_tracepoints_here (CORE_ADDR addr)
1415 {
1416   std::vector<breakpoint *> found;
1417 
1418   for (breakpoint *b : all_breakpoints ())
1419     if (b->type == bp_static_tracepoint
1420 	|| b->type == bp_static_marker_tracepoint)
1421       {
1422 	for (bp_location *loc : b->locations ())
1423 	  if (loc->address == addr)
1424 	    found.push_back (b);
1425       }
1426 
1427   return found;
1428 }
1429 
1430 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1431    validate that only allowed commands are included.  */
1432 
1433 void
1434 breakpoint_set_commands (struct breakpoint *b,
1435 			 counted_command_line &&commands)
1436 {
1437   validate_commands_for_breakpoint (b, commands.get ());
1438 
1439   b->commands = std::move (commands);
1440   gdb::observers::breakpoint_modified.notify (b);
1441 }
1442 
1443 /* Set the internal `silent' flag on the breakpoint.  Note that this
1444    is not the same as the "silent" that may appear in the breakpoint's
1445    commands.  */
1446 
1447 void
1448 breakpoint_set_silent (struct breakpoint *b, int silent)
1449 {
1450   int old_silent = b->silent;
1451 
1452   b->silent = silent;
1453   if (old_silent != silent)
1454     gdb::observers::breakpoint_modified.notify (b);
1455 }
1456 
1457 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1458    breakpoint work for any thread.  */
1459 
1460 void
1461 breakpoint_set_thread (struct breakpoint *b, int thread)
1462 {
1463   int old_thread = b->thread;
1464 
1465   b->thread = thread;
1466   if (old_thread != thread)
1467     gdb::observers::breakpoint_modified.notify (b);
1468 }
1469 
1470 /* Set the task for this breakpoint.  If TASK is 0, make the
1471    breakpoint work for any task.  */
1472 
1473 void
1474 breakpoint_set_task (struct breakpoint *b, int task)
1475 {
1476   int old_task = b->task;
1477 
1478   b->task = task;
1479   if (old_task != task)
1480     gdb::observers::breakpoint_modified.notify (b);
1481 }
1482 
1483 static void
1484 commands_command_1 (const char *arg, int from_tty,
1485 		    struct command_line *control)
1486 {
1487   counted_command_line cmd;
1488   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1489      NULL after the call to read_command_lines if the user provides an empty
1490      list of command by just typing "end".  */
1491   bool cmd_read = false;
1492 
1493   std::string new_arg;
1494 
1495   if (arg == NULL || !*arg)
1496     {
1497       /* Argument not explicitly given.  Synthesize it.  */
1498       if (breakpoint_count - prev_breakpoint_count > 1)
1499 	new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1500 				 breakpoint_count);
1501       else if (breakpoint_count > 0)
1502 	new_arg = string_printf ("%d", breakpoint_count);
1503     }
1504   else
1505     {
1506       /* Create a copy of ARG.  This is needed because the "commands"
1507 	 command may be coming from a script.  In that case, the read
1508 	 line buffer is going to be overwritten in the lambda of
1509 	 'map_breakpoint_numbers' below when reading the next line
1510 	 before we are are done parsing the breakpoint numbers.  */
1511       new_arg = arg;
1512     }
1513   arg = new_arg.c_str ();
1514 
1515   map_breakpoint_numbers
1516     (arg, [&] (breakpoint *b)
1517      {
1518        if (!cmd_read)
1519 	 {
1520 	   gdb_assert (cmd == NULL);
1521 	   if (control != NULL)
1522 	     cmd = control->body_list_0;
1523 	   else
1524 	     {
1525 	       std::string str
1526 		 = string_printf (_("Type commands for breakpoint(s) "
1527 				    "%s, one per line."),
1528 				  arg);
1529 
1530 	       auto do_validate = [=] (const char *line)
1531 				  {
1532 				    validate_actionline (line, b);
1533 				  };
1534 	       gdb::function_view<void (const char *)> validator;
1535 	       if (is_tracepoint (b))
1536 		 validator = do_validate;
1537 
1538 	       cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1539 	     }
1540 	   cmd_read = true;
1541 	 }
1542 
1543        /* If a breakpoint was on the list more than once, we don't need to
1544 	  do anything.  */
1545        if (b->commands != cmd)
1546 	 {
1547 	   validate_commands_for_breakpoint (b, cmd.get ());
1548 	   b->commands = cmd;
1549 	   gdb::observers::breakpoint_modified.notify (b);
1550 	 }
1551      });
1552 }
1553 
1554 static void
1555 commands_command (const char *arg, int from_tty)
1556 {
1557   commands_command_1 (arg, from_tty, NULL);
1558 }
1559 
1560 /* Like commands_command, but instead of reading the commands from
1561    input stream, takes them from an already parsed command structure.
1562 
1563    This is used by cli-script.c to DTRT with breakpoint commands
1564    that are part of if and while bodies.  */
1565 enum command_control_type
1566 commands_from_control_command (const char *arg, struct command_line *cmd)
1567 {
1568   commands_command_1 (arg, 0, cmd);
1569   return simple_control;
1570 }
1571 
1572 /* Return true if BL->TARGET_INFO contains valid information.  */
1573 
1574 static bool
1575 bp_location_has_shadow (struct bp_location *bl)
1576 {
1577   if (bl->loc_type != bp_loc_software_breakpoint)
1578     return false;
1579   if (!bl->inserted)
1580     return false;
1581   if (bl->target_info.shadow_len == 0)
1582     /* BL isn't valid, or doesn't shadow memory.  */
1583     return false;
1584   return true;
1585 }
1586 
1587 /* Update BUF, which is LEN bytes read from the target address
1588    MEMADDR, by replacing a memory breakpoint with its shadowed
1589    contents.
1590 
1591    If READBUF is not NULL, this buffer must not overlap with the of
1592    the breakpoint location's shadow_contents buffer.  Otherwise, a
1593    failed assertion internal error will be raised.  */
1594 
1595 static void
1596 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1597 			    const gdb_byte *writebuf_org,
1598 			    ULONGEST memaddr, LONGEST len,
1599 			    struct bp_target_info *target_info,
1600 			    struct gdbarch *gdbarch)
1601 {
1602   /* Now do full processing of the found relevant range of elements.  */
1603   CORE_ADDR bp_addr = 0;
1604   int bp_size = 0;
1605   int bptoffset = 0;
1606 
1607   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1608 				 current_program_space->aspace, 0))
1609     {
1610       /* The breakpoint is inserted in a different address space.  */
1611       return;
1612     }
1613 
1614   /* Addresses and length of the part of the breakpoint that
1615      we need to copy.  */
1616   bp_addr = target_info->placed_address;
1617   bp_size = target_info->shadow_len;
1618 
1619   if (bp_addr + bp_size <= memaddr)
1620     {
1621       /* The breakpoint is entirely before the chunk of memory we are
1622 	 reading.  */
1623       return;
1624     }
1625 
1626   if (bp_addr >= memaddr + len)
1627     {
1628       /* The breakpoint is entirely after the chunk of memory we are
1629 	 reading.  */
1630       return;
1631     }
1632 
1633   /* Offset within shadow_contents.  */
1634   if (bp_addr < memaddr)
1635     {
1636       /* Only copy the second part of the breakpoint.  */
1637       bp_size -= memaddr - bp_addr;
1638       bptoffset = memaddr - bp_addr;
1639       bp_addr = memaddr;
1640     }
1641 
1642   if (bp_addr + bp_size > memaddr + len)
1643     {
1644       /* Only copy the first part of the breakpoint.  */
1645       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1646     }
1647 
1648   if (readbuf != NULL)
1649     {
1650       /* Verify that the readbuf buffer does not overlap with the
1651 	 shadow_contents buffer.  */
1652       gdb_assert (target_info->shadow_contents >= readbuf + len
1653 		  || readbuf >= (target_info->shadow_contents
1654 				 + target_info->shadow_len));
1655 
1656       /* Update the read buffer with this inserted breakpoint's
1657 	 shadow.  */
1658       memcpy (readbuf + bp_addr - memaddr,
1659 	      target_info->shadow_contents + bptoffset, bp_size);
1660     }
1661   else
1662     {
1663       const unsigned char *bp;
1664       CORE_ADDR addr = target_info->reqstd_address;
1665       int placed_size;
1666 
1667       /* Update the shadow with what we want to write to memory.  */
1668       memcpy (target_info->shadow_contents + bptoffset,
1669 	      writebuf_org + bp_addr - memaddr, bp_size);
1670 
1671       /* Determine appropriate breakpoint contents and size for this
1672 	 address.  */
1673       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1674 
1675       /* Update the final write buffer with this inserted
1676 	 breakpoint's INSN.  */
1677       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1678     }
1679 }
1680 
1681 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1682    by replacing any memory breakpoints with their shadowed contents.
1683 
1684    If READBUF is not NULL, this buffer must not overlap with any of
1685    the breakpoint location's shadow_contents buffers.  Otherwise,
1686    a failed assertion internal error will be raised.
1687 
1688    The range of shadowed area by each bp_location is:
1689      bl->address - bp_locations_placed_address_before_address_max
1690      up to bl->address + bp_locations_shadow_len_after_address_max
1691    The range we were requested to resolve shadows for is:
1692      memaddr ... memaddr + len
1693    Thus the safe cutoff boundaries for performance optimization are
1694      memaddr + len <= (bl->address
1695 		       - bp_locations_placed_address_before_address_max)
1696    and:
1697      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1698 
1699 void
1700 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1701 			const gdb_byte *writebuf_org,
1702 			ULONGEST memaddr, LONGEST len)
1703 {
1704   /* Left boundary, right boundary and median element of our binary
1705      search.  */
1706   unsigned bc_l, bc_r, bc;
1707 
1708   /* Find BC_L which is a leftmost element which may affect BUF
1709      content.  It is safe to report lower value but a failure to
1710      report higher one.  */
1711 
1712   bc_l = 0;
1713   bc_r = bp_locations.size ();
1714   while (bc_l + 1 < bc_r)
1715     {
1716       struct bp_location *bl;
1717 
1718       bc = (bc_l + bc_r) / 2;
1719       bl = bp_locations[bc];
1720 
1721       /* Check first BL->ADDRESS will not overflow due to the added
1722 	 constant.  Then advance the left boundary only if we are sure
1723 	 the BC element can in no way affect the BUF content (MEMADDR
1724 	 to MEMADDR + LEN range).
1725 
1726 	 Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1727 	 offset so that we cannot miss a breakpoint with its shadow
1728 	 range tail still reaching MEMADDR.  */
1729 
1730       if ((bl->address + bp_locations_shadow_len_after_address_max
1731 	   >= bl->address)
1732 	  && (bl->address + bp_locations_shadow_len_after_address_max
1733 	      <= memaddr))
1734 	bc_l = bc;
1735       else
1736 	bc_r = bc;
1737     }
1738 
1739   /* Due to the binary search above, we need to make sure we pick the
1740      first location that's at BC_L's address.  E.g., if there are
1741      multiple locations at the same address, BC_L may end up pointing
1742      at a duplicate location, and miss the "master"/"inserted"
1743      location.  Say, given locations L1, L2 and L3 at addresses A and
1744      B:
1745 
1746       L1@A, L2@A, L3@B, ...
1747 
1748      BC_L could end up pointing at location L2, while the "master"
1749      location could be L1.  Since the `loc->inserted' flag is only set
1750      on "master" locations, we'd forget to restore the shadow of L1
1751      and L2.  */
1752   while (bc_l > 0
1753 	 && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1754     bc_l--;
1755 
1756   /* Now do full processing of the found relevant range of elements.  */
1757 
1758   for (bc = bc_l; bc < bp_locations.size (); bc++)
1759     {
1760       struct bp_location *bl = bp_locations[bc];
1761 
1762       /* bp_location array has BL->OWNER always non-NULL.  */
1763       if (bl->owner->type == bp_none)
1764 	warning (_("reading through apparently deleted breakpoint #%d?"),
1765 		 bl->owner->number);
1766 
1767       /* Performance optimization: any further element can no longer affect BUF
1768 	 content.  */
1769 
1770       if (bl->address >= bp_locations_placed_address_before_address_max
1771 	  && (memaddr + len
1772 	      <= (bl->address
1773 		  - bp_locations_placed_address_before_address_max)))
1774 	break;
1775 
1776       if (!bp_location_has_shadow (bl))
1777 	continue;
1778 
1779       one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1780 				  memaddr, len, &bl->target_info, bl->gdbarch);
1781     }
1782 }
1783 
1784 /* See breakpoint.h.  */
1785 
1786 bool
1787 is_breakpoint (const struct breakpoint *bpt)
1788 {
1789   return (bpt->type == bp_breakpoint
1790 	  || bpt->type == bp_hardware_breakpoint
1791 	  || bpt->type == bp_dprintf);
1792 }
1793 
1794 /* Return true if BPT is of any hardware watchpoint kind.  */
1795 
1796 static bool
1797 is_hardware_watchpoint (const struct breakpoint *bpt)
1798 {
1799   return (bpt->type == bp_hardware_watchpoint
1800 	  || bpt->type == bp_read_watchpoint
1801 	  || bpt->type == bp_access_watchpoint);
1802 }
1803 
1804 /* See breakpoint.h.  */
1805 
1806 bool
1807 is_watchpoint (const struct breakpoint *bpt)
1808 {
1809   return (is_hardware_watchpoint (bpt)
1810 	  || bpt->type == bp_watchpoint);
1811 }
1812 
1813 /* Returns true if the current thread and its running state are safe
1814    to evaluate or update watchpoint B.  Watchpoints on local
1815    expressions need to be evaluated in the context of the thread that
1816    was current when the watchpoint was created, and, that thread needs
1817    to be stopped to be able to select the correct frame context.
1818    Watchpoints on global expressions can be evaluated on any thread,
1819    and in any state.  It is presently left to the target allowing
1820    memory accesses when threads are running.  */
1821 
1822 static bool
1823 watchpoint_in_thread_scope (struct watchpoint *b)
1824 {
1825   return (b->pspace == current_program_space
1826 	  && (b->watchpoint_thread == null_ptid
1827 	      || (inferior_ptid == b->watchpoint_thread
1828 		  && !inferior_thread ()->executing ())));
1829 }
1830 
1831 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1832    associated bp_watchpoint_scope breakpoint.  */
1833 
1834 static void
1835 watchpoint_del_at_next_stop (struct watchpoint *w)
1836 {
1837   if (w->related_breakpoint != w)
1838     {
1839       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1840       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1841       w->related_breakpoint->disposition = disp_del_at_next_stop;
1842       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1843       w->related_breakpoint = w;
1844     }
1845   w->disposition = disp_del_at_next_stop;
1846 }
1847 
1848 /* Extract a bitfield value from value VAL using the bit parameters contained in
1849    watchpoint W.  */
1850 
1851 static struct value *
1852 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1853 {
1854   struct value *bit_val;
1855 
1856   if (val == NULL)
1857     return NULL;
1858 
1859   bit_val = allocate_value (value_type (val));
1860 
1861   unpack_value_bitfield (bit_val,
1862 			 w->val_bitpos,
1863 			 w->val_bitsize,
1864 			 value_contents_for_printing (val).data (),
1865 			 value_offset (val),
1866 			 val);
1867 
1868   return bit_val;
1869 }
1870 
1871 /* Allocate a dummy location and add it to B.  This is required
1872    because bpstat_stop_status requires a location to be able to report
1873    stops.  */
1874 
1875 static void
1876 add_dummy_location (struct breakpoint *b,
1877 		    struct program_space *pspace)
1878 {
1879   gdb_assert (b->loc == NULL);
1880 
1881   b->loc = new bp_location (b, bp_loc_other);
1882   b->loc->pspace = pspace;
1883 }
1884 
1885 /* Assuming that B is a watchpoint:
1886    - Reparse watchpoint expression, if REPARSE is true
1887    - Evaluate expression and store the result in B->val
1888    - Evaluate the condition if there is one, and store the result
1889      in b->loc->cond.
1890    - Update the list of values that must be watched in B->loc.
1891 
1892    If the watchpoint disposition is disp_del_at_next_stop, then do
1893    nothing.  If this is local watchpoint that is out of scope, delete
1894    it.
1895 
1896    Even with `set breakpoint always-inserted on' the watchpoints are
1897    removed + inserted on each stop here.  Normal breakpoints must
1898    never be removed because they might be missed by a running thread
1899    when debugging in non-stop mode.  On the other hand, hardware
1900    watchpoints (is_hardware_watchpoint; processed here) are specific
1901    to each LWP since they are stored in each LWP's hardware debug
1902    registers.  Therefore, such LWP must be stopped first in order to
1903    be able to modify its hardware watchpoints.
1904 
1905    Hardware watchpoints must be reset exactly once after being
1906    presented to the user.  It cannot be done sooner, because it would
1907    reset the data used to present the watchpoint hit to the user.  And
1908    it must not be done later because it could display the same single
1909    watchpoint hit during multiple GDB stops.  Note that the latter is
1910    relevant only to the hardware watchpoint types bp_read_watchpoint
1911    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1912    not user-visible - its hit is suppressed if the memory content has
1913    not changed.
1914 
1915    The following constraints influence the location where we can reset
1916    hardware watchpoints:
1917 
1918    * target_stopped_by_watchpoint and target_stopped_data_address are
1919      called several times when GDB stops.
1920 
1921    [linux]
1922    * Multiple hardware watchpoints can be hit at the same time,
1923      causing GDB to stop.  GDB only presents one hardware watchpoint
1924      hit at a time as the reason for stopping, and all the other hits
1925      are presented later, one after the other, each time the user
1926      requests the execution to be resumed.  Execution is not resumed
1927      for the threads still having pending hit event stored in
1928      LWP_INFO->STATUS.  While the watchpoint is already removed from
1929      the inferior on the first stop the thread hit event is kept being
1930      reported from its cached value by linux_nat_stopped_data_address
1931      until the real thread resume happens after the watchpoint gets
1932      presented and thus its LWP_INFO->STATUS gets reset.
1933 
1934    Therefore the hardware watchpoint hit can get safely reset on the
1935    watchpoint removal from inferior.  */
1936 
1937 static void
1938 update_watchpoint (struct watchpoint *b, bool reparse)
1939 {
1940   bool within_current_scope;
1941 
1942   /* If this is a local watchpoint, we only want to check if the
1943      watchpoint frame is in scope if the current thread is the thread
1944      that was used to create the watchpoint.  */
1945   if (!watchpoint_in_thread_scope (b))
1946     return;
1947 
1948   if (b->disposition == disp_del_at_next_stop)
1949     return;
1950 
1951   gdb::optional<scoped_restore_selected_frame> restore_frame;
1952 
1953   /* Determine if the watchpoint is within scope.  */
1954   if (b->exp_valid_block == NULL)
1955     within_current_scope = true;
1956   else
1957     {
1958       frame_info_ptr fi = get_current_frame ();
1959       struct gdbarch *frame_arch = get_frame_arch (fi);
1960       CORE_ADDR frame_pc = get_frame_pc (fi);
1961 
1962       /* If we're at a point where the stack has been destroyed
1963 	 (e.g. in a function epilogue), unwinding may not work
1964 	 properly. Do not attempt to recreate locations at this
1965 	 point.  See similar comments in watchpoint_check.  */
1966       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1967 	return;
1968 
1969       /* Save the current frame's ID so we can restore it after
1970 	 evaluating the watchpoint expression on its own frame.  */
1971       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1972 	 took a frame parameter, so that we didn't have to change the
1973 	 selected frame.  */
1974       restore_frame.emplace ();
1975 
1976       fi = frame_find_by_id (b->watchpoint_frame);
1977       within_current_scope = (fi != NULL);
1978       if (within_current_scope)
1979 	select_frame (fi);
1980     }
1981 
1982   /* We don't free locations.  They are stored in the bp_location array
1983      and update_global_location_list will eventually delete them and
1984      remove breakpoints if needed.  */
1985   b->loc = NULL;
1986 
1987   if (within_current_scope && reparse)
1988     {
1989       const char *s;
1990 
1991       b->exp.reset ();
1992       s = (b->exp_string_reparse
1993 	   ? b->exp_string_reparse.get ()
1994 	   : b->exp_string.get ());
1995       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1996       /* If the meaning of expression itself changed, the old value is
1997 	 no longer relevant.  We don't want to report a watchpoint hit
1998 	 to the user when the old value and the new value may actually
1999 	 be completely different objects.  */
2000       b->val = NULL;
2001       b->val_valid = false;
2002 
2003       /* Note that unlike with breakpoints, the watchpoint's condition
2004 	 expression is stored in the breakpoint object, not in the
2005 	 locations (re)created below.  */
2006       if (b->cond_string != NULL)
2007 	{
2008 	  b->cond_exp.reset ();
2009 
2010 	  s = b->cond_string.get ();
2011 	  b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
2012 	}
2013     }
2014 
2015   /* If we failed to parse the expression, for example because
2016      it refers to a global variable in a not-yet-loaded shared library,
2017      don't try to insert watchpoint.  We don't automatically delete
2018      such watchpoint, though, since failure to parse expression
2019      is different from out-of-scope watchpoint.  */
2020   if (!target_has_execution ())
2021     {
2022       /* Without execution, memory can't change.  No use to try and
2023 	 set watchpoint locations.  The watchpoint will be reset when
2024 	 the target gains execution, through breakpoint_re_set.  */
2025       if (!can_use_hw_watchpoints)
2026 	{
2027 	  if (b->works_in_software_mode ())
2028 	    b->type = bp_watchpoint;
2029 	  else
2030 	    error (_("Can't set read/access watchpoint when "
2031 		     "hardware watchpoints are disabled."));
2032 	}
2033     }
2034   else if (within_current_scope && b->exp)
2035     {
2036       std::vector<value_ref_ptr> val_chain;
2037       struct value *v, *result;
2038       struct program_space *frame_pspace;
2039 
2040       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
2041 			  &val_chain, false);
2042 
2043       /* Avoid setting b->val if it's already set.  The meaning of
2044 	 b->val is 'the last value' user saw, and we should update
2045 	 it only if we reported that last value to user.  As it
2046 	 happens, the code that reports it updates b->val directly.
2047 	 We don't keep track of the memory value for masked
2048 	 watchpoints.  */
2049       if (!b->val_valid && !is_masked_watchpoint (b))
2050 	{
2051 	  if (b->val_bitsize != 0)
2052 	    v = extract_bitfield_from_watchpoint_value (b, v);
2053 	  b->val = release_value (v);
2054 	  b->val_valid = true;
2055 	}
2056 
2057       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
2058 
2059       /* Look at each value on the value chain.  */
2060       gdb_assert (!val_chain.empty ());
2061       for (const value_ref_ptr &iter : val_chain)
2062 	{
2063 	  v = iter.get ();
2064 
2065 	  /* If it's a memory location, and GDB actually needed
2066 	     its contents to evaluate the expression, then we
2067 	     must watch it.  If the first value returned is
2068 	     still lazy, that means an error occurred reading it;
2069 	     watch it anyway in case it becomes readable.  */
2070 	  if (VALUE_LVAL (v) == lval_memory
2071 	      && (v == val_chain[0] || ! value_lazy (v)))
2072 	    {
2073 	      struct type *vtype = check_typedef (value_type (v));
2074 
2075 	      /* We only watch structs and arrays if user asked
2076 		 for it explicitly, never if they just happen to
2077 		 appear in the middle of some value chain.  */
2078 	      if (v == result
2079 		  || (vtype->code () != TYPE_CODE_STRUCT
2080 		      && vtype->code () != TYPE_CODE_ARRAY))
2081 		{
2082 		  CORE_ADDR addr;
2083 		  enum target_hw_bp_type type;
2084 		  struct bp_location *loc, **tmp;
2085 		  int bitpos = 0, bitsize = 0;
2086 
2087 		  if (value_bitsize (v) != 0)
2088 		    {
2089 		      /* Extract the bit parameters out from the bitfield
2090 			 sub-expression.  */
2091 		      bitpos = value_bitpos (v);
2092 		      bitsize = value_bitsize (v);
2093 		    }
2094 		  else if (v == result && b->val_bitsize != 0)
2095 		    {
2096 		     /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2097 			lvalue whose bit parameters are saved in the fields
2098 			VAL_BITPOS and VAL_BITSIZE.  */
2099 		      bitpos = b->val_bitpos;
2100 		      bitsize = b->val_bitsize;
2101 		    }
2102 
2103 		  addr = value_address (v);
2104 		  if (bitsize != 0)
2105 		    {
2106 		      /* Skip the bytes that don't contain the bitfield.  */
2107 		      addr += bitpos / 8;
2108 		    }
2109 
2110 		  type = hw_write;
2111 		  if (b->type == bp_read_watchpoint)
2112 		    type = hw_read;
2113 		  else if (b->type == bp_access_watchpoint)
2114 		    type = hw_access;
2115 
2116 		  loc = b->allocate_location ();
2117 		  for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
2118 		    ;
2119 		  *tmp = loc;
2120 		  loc->gdbarch = value_type (v)->arch ();
2121 
2122 		  loc->pspace = frame_pspace;
2123 		  loc->address
2124 		    = gdbarch_remove_non_address_bits (loc->gdbarch, addr);
2125 
2126 		  if (bitsize != 0)
2127 		    {
2128 		      /* Just cover the bytes that make up the bitfield.  */
2129 		      loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2130 		    }
2131 		  else
2132 		    loc->length = value_type (v)->length ();
2133 
2134 		  loc->watchpoint_type = type;
2135 		}
2136 	    }
2137 	}
2138 
2139       /* Change the type of breakpoint between hardware assisted or
2140 	 an ordinary watchpoint depending on the hardware support and
2141 	 free hardware slots.  Recheck the number of free hardware slots
2142 	 as the value chain may have changed.  */
2143 	{
2144 	  int reg_cnt;
2145 	  enum bp_loc_type loc_type;
2146 
2147 	  reg_cnt = can_use_hardware_watchpoint (val_chain);
2148 
2149 	  if (reg_cnt)
2150 	    {
2151 	      int i, target_resources_ok, other_type_used;
2152 	      enum bptype type;
2153 
2154 	      /* Use an exact watchpoint when there's only one memory region to be
2155 		 watched, and only one debug register is needed to watch it.  */
2156 	      b->exact = target_exact_watchpoints && reg_cnt == 1;
2157 
2158 	      /* We need to determine how many resources are already
2159 		 used for all other hardware watchpoints plus this one
2160 		 to see if we still have enough resources to also fit
2161 		 this watchpoint in as well.  */
2162 
2163 	      /* If this is a software watchpoint, we try to turn it
2164 		 to a hardware one -- count resources as if B was of
2165 		 hardware watchpoint type.  */
2166 	      type = b->type;
2167 	      if (type == bp_watchpoint)
2168 		type = bp_hardware_watchpoint;
2169 
2170 	      /* This watchpoint may or may not have been placed on
2171 		 the list yet at this point (it won't be in the list
2172 		 if we're trying to create it for the first time,
2173 		 through watch_command), so always account for it
2174 		 manually.  */
2175 
2176 	      /* Count resources used by all watchpoints except B.  */
2177 	      i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2178 
2179 	      /* Add in the resources needed for B.  */
2180 	      i += hw_watchpoint_use_count (b);
2181 
2182 	      target_resources_ok
2183 		= target_can_use_hardware_watchpoint (type, i, other_type_used);
2184 	      if (target_resources_ok <= 0)
2185 		{
2186 		  bool sw_mode = b->works_in_software_mode ();
2187 
2188 		  if (target_resources_ok == 0 && !sw_mode)
2189 		    error (_("Target does not support this type of "
2190 			     "hardware watchpoint."));
2191 		  else if (target_resources_ok < 0 && !sw_mode)
2192 		    error (_("There are not enough available hardware "
2193 			     "resources for this watchpoint."));
2194 
2195 		  /* Downgrade to software watchpoint.  */
2196 		  b->type = bp_watchpoint;
2197 		}
2198 	      else
2199 		{
2200 		  /* If this was a software watchpoint, we've just
2201 		     found we have enough resources to turn it to a
2202 		     hardware watchpoint.  Otherwise, this is a
2203 		     nop.  */
2204 		  b->type = type;
2205 		}
2206 	    }
2207 	  else if (!b->works_in_software_mode ())
2208 	    {
2209 	      if (!can_use_hw_watchpoints)
2210 		error (_("Can't set read/access watchpoint when "
2211 			 "hardware watchpoints are disabled."));
2212 	      else
2213 		error (_("Expression cannot be implemented with "
2214 			 "read/access watchpoint."));
2215 	    }
2216 	  else
2217 	    b->type = bp_watchpoint;
2218 
2219 	  loc_type = (b->type == bp_watchpoint? bp_loc_software_watchpoint
2220 		      : bp_loc_hardware_watchpoint);
2221 	  for (bp_location *bl : b->locations ())
2222 	    bl->loc_type = loc_type;
2223 	}
2224 
2225       /* If a software watchpoint is not watching any memory, then the
2226 	 above left it without any location set up.  But,
2227 	 bpstat_stop_status requires a location to be able to report
2228 	 stops, so make sure there's at least a dummy one.  */
2229       if (b->type == bp_watchpoint && b->loc == NULL)
2230 	add_dummy_location (b, frame_pspace);
2231     }
2232   else if (!within_current_scope)
2233     {
2234       gdb_printf (_("\
2235 Watchpoint %d deleted because the program has left the block\n\
2236 in which its expression is valid.\n"),
2237 		  b->number);
2238       watchpoint_del_at_next_stop (b);
2239     }
2240 }
2241 
2242 /* Returns true iff breakpoint location should be
2243    inserted in the inferior.  We don't differentiate the type of BL's owner
2244    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2245    breakpoint_ops is not defined, because in insert_bp_location,
2246    tracepoint's insert_location will not be called.  */
2247 
2248 static bool
2249 should_be_inserted (struct bp_location *bl)
2250 {
2251   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2252     return false;
2253 
2254   if (bl->owner->disposition == disp_del_at_next_stop)
2255     return false;
2256 
2257   if (!bl->enabled || bl->disabled_by_cond
2258       || bl->shlib_disabled || bl->duplicate)
2259     return false;
2260 
2261   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2262     return false;
2263 
2264   /* This is set for example, when we're attached to the parent of a
2265      vfork, and have detached from the child.  The child is running
2266      free, and we expect it to do an exec or exit, at which point the
2267      OS makes the parent schedulable again (and the target reports
2268      that the vfork is done).  Until the child is done with the shared
2269      memory region, do not insert breakpoints in the parent, otherwise
2270      the child could still trip on the parent's breakpoints.  Since
2271      the parent is blocked anyway, it won't miss any breakpoint.  */
2272   if (bl->pspace->breakpoints_not_allowed)
2273     return false;
2274 
2275   /* Don't insert a breakpoint if we're trying to step past its
2276      location, except if the breakpoint is a single-step breakpoint,
2277      and the breakpoint's thread is the thread which is stepping past
2278      a breakpoint.  */
2279   if ((bl->loc_type == bp_loc_software_breakpoint
2280        || bl->loc_type == bp_loc_hardware_breakpoint)
2281       && stepping_past_instruction_at (bl->pspace->aspace,
2282 				       bl->address)
2283       /* The single-step breakpoint may be inserted at the location
2284 	 we're trying to step if the instruction branches to itself.
2285 	 However, the instruction won't be executed at all and it may
2286 	 break the semantics of the instruction, for example, the
2287 	 instruction is a conditional branch or updates some flags.
2288 	 We can't fix it unless GDB is able to emulate the instruction
2289 	 or switch to displaced stepping.  */
2290       && !(bl->owner->type == bp_single_step
2291 	   && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2292     {
2293       infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2294 			   paddress (bl->gdbarch, bl->address));
2295       return false;
2296     }
2297 
2298   /* Don't insert watchpoints if we're trying to step past the
2299      instruction that triggered one.  */
2300   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2301       && stepping_past_nonsteppable_watchpoint ())
2302     {
2303       infrun_debug_printf ("stepping past non-steppable watchpoint. "
2304 			   "skipping watchpoint at %s:%d",
2305 			   paddress (bl->gdbarch, bl->address), bl->length);
2306       return false;
2307     }
2308 
2309   return true;
2310 }
2311 
2312 /* Same as should_be_inserted but does the check assuming
2313    that the location is not duplicated.  */
2314 
2315 static bool
2316 unduplicated_should_be_inserted (struct bp_location *bl)
2317 {
2318   scoped_restore restore_bl_duplicate
2319     = make_scoped_restore (&bl->duplicate, 0);
2320 
2321   return should_be_inserted (bl);
2322 }
2323 
2324 /* Parses a conditional described by an expression COND into an
2325    agent expression bytecode suitable for evaluation
2326    by the bytecode interpreter.  Return NULL if there was
2327    any error during parsing.  */
2328 
2329 static agent_expr_up
2330 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2331 {
2332   if (cond == NULL)
2333     return NULL;
2334 
2335   agent_expr_up aexpr;
2336 
2337   /* We don't want to stop processing, so catch any errors
2338      that may show up.  */
2339   try
2340     {
2341       aexpr = gen_eval_for_expr (scope, cond);
2342     }
2343 
2344   catch (const gdb_exception_error &ex)
2345     {
2346       /* If we got here, it means the condition could not be parsed to a valid
2347 	 bytecode expression and thus can't be evaluated on the target's side.
2348 	 It's no use iterating through the conditions.  */
2349     }
2350 
2351   /* We have a valid agent expression.  */
2352   return aexpr;
2353 }
2354 
2355 /* Based on location BL, create a list of breakpoint conditions to be
2356    passed on to the target.  If we have duplicated locations with different
2357    conditions, we will add such conditions to the list.  The idea is that the
2358    target will evaluate the list of conditions and will only notify GDB when
2359    one of them is true.  */
2360 
2361 static void
2362 build_target_condition_list (struct bp_location *bl)
2363 {
2364   bool null_condition_or_parse_error = false;
2365   int modified = bl->needs_update;
2366 
2367   /* Release conditions left over from a previous insert.  */
2368   bl->target_info.conditions.clear ();
2369 
2370   /* This is only meaningful if the target is
2371      evaluating conditions and if the user has
2372      opted for condition evaluation on the target's
2373      side.  */
2374   if (gdb_evaluates_breakpoint_condition_p ()
2375       || !target_supports_evaluation_of_breakpoint_conditions ())
2376     return;
2377 
2378   auto loc_range = all_bp_locations_at_addr (bl->address);
2379 
2380   /* Do a first pass to check for locations with no assigned
2381      conditions or conditions that fail to parse to a valid agent
2382      expression bytecode.  If any of these happen, then it's no use to
2383      send conditions to the target since this location will always
2384      trigger and generate a response back to GDB.  Note we consider
2385      all locations at the same address irrespective of type, i.e.,
2386      even if the locations aren't considered duplicates (e.g.,
2387      software breakpoint and hardware breakpoint at the same
2388      address).  */
2389   for (bp_location *loc : loc_range)
2390     {
2391       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2392 	{
2393 	  if (modified)
2394 	    {
2395 	      /* Re-parse the conditions since something changed.  In that
2396 		 case we already freed the condition bytecodes (see
2397 		 force_breakpoint_reinsertion).  We just
2398 		 need to parse the condition to bytecodes again.  */
2399 	      loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2400 							loc->cond.get ());
2401 	    }
2402 
2403 	  /* If we have a NULL bytecode expression, it means something
2404 	     went wrong or we have a null condition expression.  */
2405 	  if (!loc->cond_bytecode)
2406 	    {
2407 	      null_condition_or_parse_error = true;
2408 	      break;
2409 	    }
2410 	}
2411     }
2412 
2413   /* If any of these happened, it means we will have to evaluate the conditions
2414      for the location's address on gdb's side.  It is no use keeping bytecodes
2415      for all the other duplicate locations, thus we free all of them here.
2416 
2417      This is so we have a finer control over which locations' conditions are
2418      being evaluated by GDB or the remote stub.  */
2419   if (null_condition_or_parse_error)
2420     {
2421       for (bp_location *loc : loc_range)
2422 	{
2423 	  if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2424 	    {
2425 	      /* Only go as far as the first NULL bytecode is
2426 		 located.  */
2427 	      if (!loc->cond_bytecode)
2428 		return;
2429 
2430 	      loc->cond_bytecode.reset ();
2431 	    }
2432 	}
2433     }
2434 
2435   /* No NULL conditions or failed bytecode generation.  Build a
2436      condition list for this location's address.  If we have software
2437      and hardware locations at the same address, they aren't
2438      considered duplicates, but we still marge all the conditions
2439      anyway, as it's simpler, and doesn't really make a practical
2440      difference.  */
2441   for (bp_location *loc : loc_range)
2442     if (loc->cond
2443 	&& is_breakpoint (loc->owner)
2444 	&& loc->pspace->num == bl->pspace->num
2445 	&& loc->owner->enable_state == bp_enabled
2446 	&& loc->enabled
2447 	&& !loc->disabled_by_cond)
2448       {
2449 	/* Add the condition to the vector.  This will be used later
2450 	   to send the conditions to the target.  */
2451 	bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2452       }
2453 
2454   return;
2455 }
2456 
2457 /* Parses a command described by string CMD into an agent expression
2458    bytecode suitable for evaluation by the bytecode interpreter.
2459    Return NULL if there was any error during parsing.  */
2460 
2461 static agent_expr_up
2462 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2463 {
2464   const char *cmdrest;
2465   const char *format_start, *format_end;
2466   struct gdbarch *gdbarch = get_current_arch ();
2467 
2468   if (cmd == NULL)
2469     return NULL;
2470 
2471   cmdrest = cmd;
2472 
2473   if (*cmdrest == ',')
2474     ++cmdrest;
2475   cmdrest = skip_spaces (cmdrest);
2476 
2477   if (*cmdrest++ != '"')
2478     error (_("No format string following the location"));
2479 
2480   format_start = cmdrest;
2481 
2482   format_pieces fpieces (&cmdrest);
2483 
2484   format_end = cmdrest;
2485 
2486   if (*cmdrest++ != '"')
2487     error (_("Bad format string, non-terminated '\"'."));
2488 
2489   cmdrest = skip_spaces (cmdrest);
2490 
2491   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2492     error (_("Invalid argument syntax"));
2493 
2494   if (*cmdrest == ',')
2495     cmdrest++;
2496   cmdrest = skip_spaces (cmdrest);
2497 
2498   /* For each argument, make an expression.  */
2499 
2500   std::vector<struct expression *> argvec;
2501   while (*cmdrest != '\0')
2502     {
2503       const char *cmd1;
2504 
2505       cmd1 = cmdrest;
2506       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2507       argvec.push_back (expr.release ());
2508       cmdrest = cmd1;
2509       if (*cmdrest == ',')
2510 	++cmdrest;
2511     }
2512 
2513   agent_expr_up aexpr;
2514 
2515   /* We don't want to stop processing, so catch any errors
2516      that may show up.  */
2517   try
2518     {
2519       aexpr = gen_printf (scope, gdbarch, 0, 0,
2520 			  format_start, format_end - format_start,
2521 			  argvec.size (), argvec.data ());
2522     }
2523   catch (const gdb_exception_error &ex)
2524     {
2525       /* If we got here, it means the command could not be parsed to a valid
2526 	 bytecode expression and thus can't be evaluated on the target's side.
2527 	 It's no use iterating through the other commands.  */
2528     }
2529 
2530   /* We have a valid agent expression, return it.  */
2531   return aexpr;
2532 }
2533 
2534 /* Based on location BL, create a list of breakpoint commands to be
2535    passed on to the target.  If we have duplicated locations with
2536    different commands, we will add any such to the list.  */
2537 
2538 static void
2539 build_target_command_list (struct bp_location *bl)
2540 {
2541   bool null_command_or_parse_error = false;
2542   int modified = bl->needs_update;
2543 
2544   /* Clear commands left over from a previous insert.  */
2545   bl->target_info.tcommands.clear ();
2546 
2547   if (!target_can_run_breakpoint_commands ())
2548     return;
2549 
2550   /* For now, limit to agent-style dprintf breakpoints.  */
2551   if (dprintf_style != dprintf_style_agent)
2552     return;
2553 
2554   auto loc_range = all_bp_locations_at_addr (bl->address);
2555 
2556   /* For now, if we have any location at the same address that isn't a
2557      dprintf, don't install the target-side commands, as that would
2558      make the breakpoint not be reported to the core, and we'd lose
2559      control.  */
2560   for (bp_location *loc : loc_range)
2561     if (is_breakpoint (loc->owner)
2562 	&& loc->pspace->num == bl->pspace->num
2563 	&& loc->owner->type != bp_dprintf)
2564       return;
2565 
2566   /* Do a first pass to check for locations with no assigned
2567      conditions or conditions that fail to parse to a valid agent expression
2568      bytecode.  If any of these happen, then it's no use to send conditions
2569      to the target since this location will always trigger and generate a
2570      response back to GDB.  */
2571   for (bp_location *loc : loc_range)
2572     {
2573       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2574 	{
2575 	  if (modified)
2576 	    {
2577 	      /* Re-parse the commands since something changed.  In that
2578 		 case we already freed the command bytecodes (see
2579 		 force_breakpoint_reinsertion).  We just
2580 		 need to parse the command to bytecodes again.  */
2581 	      loc->cmd_bytecode
2582 		= parse_cmd_to_aexpr (bl->address,
2583 				      loc->owner->extra_string.get ());
2584 	    }
2585 
2586 	  /* If we have a NULL bytecode expression, it means something
2587 	     went wrong or we have a null command expression.  */
2588 	  if (!loc->cmd_bytecode)
2589 	    {
2590 	      null_command_or_parse_error = true;
2591 	      break;
2592 	    }
2593 	}
2594     }
2595 
2596   /* If anything failed, then we're not doing target-side commands,
2597      and so clean up.  */
2598   if (null_command_or_parse_error)
2599     {
2600       for (bp_location *loc : loc_range)
2601 	if (is_breakpoint (loc->owner)
2602 	    && loc->pspace->num == bl->pspace->num)
2603 	  {
2604 	    /* Only go as far as the first NULL bytecode is
2605 	       located.  */
2606 	    if (loc->cmd_bytecode == NULL)
2607 	      return;
2608 
2609 	    loc->cmd_bytecode.reset ();
2610 	  }
2611     }
2612 
2613   /* No NULL commands or failed bytecode generation.  Build a command
2614      list for all duplicate locations at this location's address.
2615      Note that here we must care for whether the breakpoint location
2616      types are considered duplicates, otherwise, say, if we have a
2617      software and hardware location at the same address, the target
2618      could end up running the commands twice.  For the moment, we only
2619      support targets-side commands with dprintf, but it doesn't hurt
2620      to be pedantically correct in case that changes.  */
2621   for (bp_location *loc : loc_range)
2622     if (breakpoint_locations_match (bl, loc)
2623 	&& loc->owner->extra_string
2624 	&& is_breakpoint (loc->owner)
2625 	&& loc->pspace->num == bl->pspace->num
2626 	&& loc->owner->enable_state == bp_enabled
2627 	&& loc->enabled
2628 	&& !loc->disabled_by_cond)
2629       {
2630 	/* Add the command to the vector.  This will be used later
2631 	   to send the commands to the target.  */
2632 	bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2633       }
2634 
2635   bl->target_info.persist = 0;
2636   /* Maybe flag this location as persistent.  */
2637   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2638     bl->target_info.persist = 1;
2639 }
2640 
2641 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2642    of breakpoint according to ADDR except single-step breakpoint.
2643    Get the kind of single-step breakpoint according to the current
2644    registers state.  */
2645 
2646 static int
2647 breakpoint_kind (const struct bp_location *bl, CORE_ADDR *addr)
2648 {
2649   if (bl->owner->type == bp_single_step)
2650     {
2651       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2652       struct regcache *regcache;
2653 
2654       regcache = get_thread_regcache (thr);
2655 
2656       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2657 							 regcache, addr);
2658     }
2659   else
2660     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2661 }
2662 
2663 /* Rethrow the currently handled exception, if it's a TARGET_CLOSE_ERROR.
2664    E is either the currently handled exception, or a copy, or a sliced copy,
2665    so we can't rethrow that one, but we can use it to inspect the properties
2666    of the currently handled exception.  */
2667 
2668 static void
2669 rethrow_on_target_close_error (const gdb_exception &e)
2670 {
2671   if (e.reason == 0)
2672     return;
2673   /* Can't set the breakpoint.  */
2674 
2675   if (e.error != TARGET_CLOSE_ERROR)
2676     return;
2677 
2678   /* If the target has closed then it will have deleted any breakpoints
2679      inserted within the target inferior, as a result any further attempts
2680      to interact with the breakpoint objects is not possible.  Just rethrow
2681      the error.  Don't use e to rethrow, to prevent object slicing of the
2682      exception.  */
2683   throw;
2684 }
2685 
2686 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2687    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2688    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2689    Returns 0 for success, 1 if the bp_location type is not supported or
2690    -1 for failure.
2691 
2692    NOTE drow/2003-09-09: This routine could be broken down to an
2693    object-style method for each breakpoint or catchpoint type.  */
2694 static int
2695 insert_bp_location (struct bp_location *bl,
2696 		    struct ui_file *tmp_error_stream,
2697 		    int *disabled_breaks,
2698 		    int *hw_breakpoint_error,
2699 		    int *hw_bp_error_explained_already)
2700 {
2701   gdb_exception bp_excpt;
2702 
2703   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2704     return 0;
2705 
2706   /* Note we don't initialize bl->target_info, as that wipes out
2707      the breakpoint location's shadow_contents if the breakpoint
2708      is still inserted at that location.  This in turn breaks
2709      target_read_memory which depends on these buffers when
2710      a memory read is requested at the breakpoint location:
2711      Once the target_info has been wiped, we fail to see that
2712      we have a breakpoint inserted at that address and thus
2713      read the breakpoint instead of returning the data saved in
2714      the breakpoint location's shadow contents.  */
2715   bl->target_info.reqstd_address = bl->address;
2716   bl->target_info.placed_address_space = bl->pspace->aspace;
2717   bl->target_info.length = bl->length;
2718 
2719   /* When working with target-side conditions, we must pass all the conditions
2720      for the same breakpoint address down to the target since GDB will not
2721      insert those locations.  With a list of breakpoint conditions, the target
2722      can decide when to stop and notify GDB.  */
2723 
2724   if (is_breakpoint (bl->owner))
2725     {
2726       build_target_condition_list (bl);
2727       build_target_command_list (bl);
2728       /* Reset the modification marker.  */
2729       bl->needs_update = 0;
2730     }
2731 
2732   /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2733      set at a read-only address, then a breakpoint location will have
2734      been changed to hardware breakpoint before we get here.  If it is
2735      "off" however, error out before actually trying to insert the
2736      breakpoint, with a nicer error message.  */
2737   if (bl->loc_type == bp_loc_software_breakpoint
2738       && !automatic_hardware_breakpoints)
2739     {
2740       mem_region *mr = lookup_mem_region (bl->address);
2741 
2742       if (mr != nullptr && mr->attrib.mode != MEM_RW)
2743 	{
2744 	  gdb_printf (tmp_error_stream,
2745 		      _("Cannot insert breakpoint %d.\n"
2746 			"Cannot set software breakpoint "
2747 			"at read-only address %s\n"),
2748 		      bl->owner->number,
2749 		      paddress (bl->gdbarch, bl->address));
2750 	  return 1;
2751 	}
2752     }
2753 
2754   if (bl->loc_type == bp_loc_software_breakpoint
2755       || bl->loc_type == bp_loc_hardware_breakpoint)
2756     {
2757       /* First check to see if we have to handle an overlay.  */
2758       if (overlay_debugging == ovly_off
2759 	  || bl->section == NULL
2760 	  || !(section_is_overlay (bl->section)))
2761 	{
2762 	  /* No overlay handling: just set the breakpoint.  */
2763 	  try
2764 	    {
2765 	      int val;
2766 
2767 	      val = bl->owner->insert_location (bl);
2768 	      if (val)
2769 		bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2770 	    }
2771 	  catch (gdb_exception &e)
2772 	    {
2773 	      rethrow_on_target_close_error (e);
2774 	      bp_excpt = std::move (e);
2775 	    }
2776 	}
2777       else
2778 	{
2779 	  /* This breakpoint is in an overlay section.
2780 	     Shall we set a breakpoint at the LMA?  */
2781 	  if (!overlay_events_enabled)
2782 	    {
2783 	      /* Yes -- overlay event support is not active,
2784 		 so we must try to set a breakpoint at the LMA.
2785 		 This will not work for a hardware breakpoint.  */
2786 	      if (bl->loc_type == bp_loc_hardware_breakpoint)
2787 		warning (_("hardware breakpoint %d not supported in overlay!"),
2788 			 bl->owner->number);
2789 	      else
2790 		{
2791 		  CORE_ADDR addr = overlay_unmapped_address (bl->address,
2792 							     bl->section);
2793 		  /* Set a software (trap) breakpoint at the LMA.  */
2794 		  bl->overlay_target_info = bl->target_info;
2795 		  bl->overlay_target_info.reqstd_address = addr;
2796 
2797 		  /* No overlay handling: just set the breakpoint.  */
2798 		  try
2799 		    {
2800 		      int val;
2801 
2802 		      bl->overlay_target_info.kind
2803 			= breakpoint_kind (bl, &addr);
2804 		      bl->overlay_target_info.placed_address = addr;
2805 		      val = target_insert_breakpoint (bl->gdbarch,
2806 						      &bl->overlay_target_info);
2807 		      if (val)
2808 			bp_excpt
2809 			  = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2810 		    }
2811 		  catch (gdb_exception &e)
2812 		    {
2813 		      rethrow_on_target_close_error (e);
2814 		      bp_excpt = std::move (e);
2815 		    }
2816 
2817 		  if (bp_excpt.reason != 0)
2818 		    gdb_printf (tmp_error_stream,
2819 				"Overlay breakpoint %d "
2820 				"failed: in ROM?\n",
2821 				bl->owner->number);
2822 		}
2823 	    }
2824 	  /* Shall we set a breakpoint at the VMA? */
2825 	  if (section_is_mapped (bl->section))
2826 	    {
2827 	      /* Yes.  This overlay section is mapped into memory.  */
2828 	      try
2829 		{
2830 		  int val;
2831 
2832 		  val = bl->owner->insert_location (bl);
2833 		  if (val)
2834 		    bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2835 		}
2836 	      catch (gdb_exception &e)
2837 		{
2838 		  rethrow_on_target_close_error (e);
2839 		  bp_excpt = std::move (e);
2840 		}
2841 	    }
2842 	  else
2843 	    {
2844 	      /* No.  This breakpoint will not be inserted.
2845 		 No error, but do not mark the bp as 'inserted'.  */
2846 	      return 0;
2847 	    }
2848 	}
2849 
2850       if (bp_excpt.reason != 0)
2851 	{
2852 	  /* Can't set the breakpoint.  */
2853 	  gdb_assert (bl->owner != nullptr);
2854 
2855 	  /* In some cases, we might not be able to insert a
2856 	     breakpoint in a shared library that has already been
2857 	     removed, but we have not yet processed the shlib unload
2858 	     event.  Unfortunately, some targets that implement
2859 	     breakpoint insertion themselves can't tell why the
2860 	     breakpoint insertion failed (e.g., the remote target
2861 	     doesn't define error codes), so we must treat generic
2862 	     errors as memory errors.  */
2863 	  if (bp_excpt.reason == RETURN_ERROR
2864 	      && (bp_excpt.error == GENERIC_ERROR
2865 		  || bp_excpt.error == MEMORY_ERROR)
2866 	      && bl->loc_type == bp_loc_software_breakpoint
2867 	      && (solib_name_from_address (bl->pspace, bl->address)
2868 		  || shared_objfile_contains_address_p (bl->pspace,
2869 							bl->address)))
2870 	    {
2871 	      /* See also: disable_breakpoints_in_shlibs.  */
2872 	      bl->shlib_disabled = 1;
2873 	      gdb::observers::breakpoint_modified.notify (bl->owner);
2874 	      if (!*disabled_breaks)
2875 		{
2876 		  gdb_printf (tmp_error_stream,
2877 			      "Cannot insert breakpoint %d.\n",
2878 			      bl->owner->number);
2879 		  gdb_printf (tmp_error_stream,
2880 			      "Temporarily disabling shared "
2881 			      "library breakpoints:\n");
2882 		}
2883 	      *disabled_breaks = 1;
2884 	      gdb_printf (tmp_error_stream,
2885 			  "breakpoint #%d\n", bl->owner->number);
2886 	      return 0;
2887 	    }
2888 	  else
2889 	    {
2890 	      if (bl->loc_type == bp_loc_hardware_breakpoint)
2891 		{
2892 		  *hw_breakpoint_error = 1;
2893 		  *hw_bp_error_explained_already = bp_excpt.message != NULL;
2894 		  gdb_printf (tmp_error_stream,
2895 			      "Cannot insert hardware breakpoint %d%s",
2896 			      bl->owner->number,
2897 			      bp_excpt.message ? ":" : ".\n");
2898 		  if (bp_excpt.message != NULL)
2899 		    gdb_printf (tmp_error_stream, "%s.\n",
2900 				bp_excpt.what ());
2901 		}
2902 	      else
2903 		{
2904 		  if (bp_excpt.message == NULL)
2905 		    {
2906 		      std::string message
2907 			= memory_error_message (TARGET_XFER_E_IO,
2908 						bl->gdbarch, bl->address);
2909 
2910 		      gdb_printf (tmp_error_stream,
2911 				  "Cannot insert breakpoint %d.\n"
2912 				  "%s\n",
2913 				  bl->owner->number, message.c_str ());
2914 		    }
2915 		  else
2916 		    {
2917 		      gdb_printf (tmp_error_stream,
2918 				  "Cannot insert breakpoint %d: %s\n",
2919 				  bl->owner->number,
2920 				  bp_excpt.what ());
2921 		    }
2922 		}
2923 	      return 1;
2924 
2925 	    }
2926 	}
2927       else
2928 	bl->inserted = 1;
2929 
2930       return 0;
2931     }
2932 
2933   else if (bl->loc_type == bp_loc_hardware_watchpoint
2934 	   /* NOTE drow/2003-09-08: This state only exists for removing
2935 	      watchpoints.  It's not clear that it's necessary...  */
2936 	   && bl->owner->disposition != disp_del_at_next_stop)
2937     {
2938       int val;
2939 
2940       val = bl->owner->insert_location (bl);
2941 
2942       /* If trying to set a read-watchpoint, and it turns out it's not
2943 	 supported, try emulating one with an access watchpoint.  */
2944       if (val == 1 && bl->watchpoint_type == hw_read)
2945 	{
2946 	  /* But don't try to insert it, if there's already another
2947 	     hw_access location that would be considered a duplicate
2948 	     of this one.  */
2949 	  for (bp_location *loc : all_bp_locations ())
2950 	    if (loc != bl
2951 		&& loc->watchpoint_type == hw_access
2952 		&& watchpoint_locations_match (bl, loc))
2953 	      {
2954 		bl->duplicate = 1;
2955 		bl->inserted = 1;
2956 		bl->target_info = loc->target_info;
2957 		bl->watchpoint_type = hw_access;
2958 		val = 0;
2959 		break;
2960 	      }
2961 
2962 	  if (val == 1)
2963 	    {
2964 	      bl->watchpoint_type = hw_access;
2965 	      val = bl->owner->insert_location (bl);
2966 
2967 	      if (val)
2968 		/* Back to the original value.  */
2969 		bl->watchpoint_type = hw_read;
2970 	    }
2971 	}
2972 
2973       bl->inserted = (val == 0);
2974     }
2975 
2976   else if (bl->owner->type == bp_catchpoint)
2977     {
2978       int val;
2979 
2980       val = bl->owner->insert_location (bl);
2981       if (val)
2982 	{
2983 	  bl->owner->enable_state = bp_disabled;
2984 
2985 	  if (val == 1)
2986 	    warning (_("\
2987 Error inserting catchpoint %d: Your system does not support this type\n\
2988 of catchpoint."), bl->owner->number);
2989 	  else
2990 	    warning (_("Error inserting catchpoint %d."), bl->owner->number);
2991 	}
2992 
2993       bl->inserted = (val == 0);
2994 
2995       /* We've already printed an error message if there was a problem
2996 	 inserting this catchpoint, and we've disabled the catchpoint,
2997 	 so just return success.  */
2998       return 0;
2999     }
3000 
3001   return 0;
3002 }
3003 
3004 /* This function is called when program space PSPACE is about to be
3005    deleted.  It takes care of updating breakpoints to not reference
3006    PSPACE anymore.  */
3007 
3008 void
3009 breakpoint_program_space_exit (struct program_space *pspace)
3010 {
3011   /* Remove any breakpoint that was set through this program space.  */
3012   for (breakpoint *b : all_breakpoints_safe ())
3013     if (b->pspace == pspace)
3014       delete_breakpoint (b);
3015 
3016   /* Breakpoints set through other program spaces could have locations
3017      bound to PSPACE as well.  Remove those.  */
3018   for (bp_location *loc : all_bp_locations ())
3019     {
3020       struct bp_location *tmp;
3021 
3022       if (loc->pspace == pspace)
3023 	{
3024 	  /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
3025 	  if (loc->owner->loc == loc)
3026 	    loc->owner->loc = loc->next;
3027 	  else
3028 	    for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
3029 	      if (tmp->next == loc)
3030 		{
3031 		  tmp->next = loc->next;
3032 		  break;
3033 		}
3034 	}
3035     }
3036 
3037   /* Now update the global location list to permanently delete the
3038      removed locations above.  */
3039   update_global_location_list (UGLL_DONT_INSERT);
3040 }
3041 
3042 /* Make sure all breakpoints are inserted in inferior.
3043    Throws exception on any error.
3044    A breakpoint that is already inserted won't be inserted
3045    again, so calling this function twice is safe.  */
3046 void
3047 insert_breakpoints (void)
3048 {
3049   for (breakpoint *bpt : all_breakpoints ())
3050     if (is_hardware_watchpoint (bpt))
3051       {
3052 	struct watchpoint *w = (struct watchpoint *) bpt;
3053 
3054 	update_watchpoint (w, false /* don't reparse.  */);
3055       }
3056 
3057   /* Updating watchpoints creates new locations, so update the global
3058      location list.  Explicitly tell ugll to insert locations and
3059      ignore breakpoints_always_inserted_mode.  Also,
3060      update_global_location_list tries to "upgrade" software
3061      breakpoints to hardware breakpoints to handle "set breakpoint
3062      auto-hw", so we need to call it even if we don't have new
3063      locations.  */
3064   update_global_location_list (UGLL_INSERT);
3065 }
3066 
3067 /* This is used when we need to synch breakpoint conditions between GDB and the
3068    target.  It is the case with deleting and disabling of breakpoints when using
3069    always-inserted mode.  */
3070 
3071 static void
3072 update_inserted_breakpoint_locations (void)
3073 {
3074   int error_flag = 0;
3075   int val = 0;
3076   int disabled_breaks = 0;
3077   int hw_breakpoint_error = 0;
3078   int hw_bp_details_reported = 0;
3079 
3080   string_file tmp_error_stream;
3081 
3082   /* Explicitly mark the warning -- this will only be printed if
3083      there was an error.  */
3084   tmp_error_stream.puts ("Warning:\n");
3085 
3086   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3087 
3088   for (bp_location *bl : all_bp_locations ())
3089     {
3090       /* We only want to update software breakpoints and hardware
3091 	 breakpoints.  */
3092       if (!is_breakpoint (bl->owner))
3093 	continue;
3094 
3095       /* We only want to update locations that are already inserted
3096 	 and need updating.  This is to avoid unwanted insertion during
3097 	 deletion of breakpoints.  */
3098       if (!bl->inserted || !bl->needs_update)
3099 	continue;
3100 
3101       switch_to_program_space_and_thread (bl->pspace);
3102 
3103       /* For targets that support global breakpoints, there's no need
3104 	 to select an inferior to insert breakpoint to.  In fact, even
3105 	 if we aren't attached to any process yet, we should still
3106 	 insert breakpoints.  */
3107       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3108 	  && (inferior_ptid == null_ptid || !target_has_execution ()))
3109 	continue;
3110 
3111       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3112 				    &hw_breakpoint_error, &hw_bp_details_reported);
3113       if (val)
3114 	error_flag = val;
3115     }
3116 
3117   if (error_flag)
3118     {
3119       target_terminal::ours_for_output ();
3120       error_stream (tmp_error_stream);
3121     }
3122 }
3123 
3124 /* Used when starting or continuing the program.  */
3125 
3126 static void
3127 insert_breakpoint_locations (void)
3128 {
3129   int error_flag = 0;
3130   int val = 0;
3131   int disabled_breaks = 0;
3132   int hw_breakpoint_error = 0;
3133   int hw_bp_error_explained_already = 0;
3134 
3135   string_file tmp_error_stream;
3136 
3137   /* Explicitly mark the warning -- this will only be printed if
3138      there was an error.  */
3139   tmp_error_stream.puts ("Warning:\n");
3140 
3141   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3142 
3143   for (bp_location *bl : all_bp_locations ())
3144     {
3145       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3146 	continue;
3147 
3148       /* There is no point inserting thread-specific breakpoints if
3149 	 the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3150 	 has BL->OWNER always non-NULL.  */
3151       if (bl->owner->thread != -1
3152 	  && !valid_global_thread_id (bl->owner->thread))
3153 	continue;
3154 
3155       switch_to_program_space_and_thread (bl->pspace);
3156 
3157       /* For targets that support global breakpoints, there's no need
3158 	 to select an inferior to insert breakpoint to.  In fact, even
3159 	 if we aren't attached to any process yet, we should still
3160 	 insert breakpoints.  */
3161       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3162 	  && (inferior_ptid == null_ptid || !target_has_execution ()))
3163 	continue;
3164 
3165       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3166 				    &hw_breakpoint_error, &hw_bp_error_explained_already);
3167       if (val)
3168 	error_flag = val;
3169     }
3170 
3171   /* If we failed to insert all locations of a watchpoint, remove
3172      them, as half-inserted watchpoint is of limited use.  */
3173   for (breakpoint *bpt : all_breakpoints ())
3174     {
3175       bool some_failed = false;
3176 
3177       if (!is_hardware_watchpoint (bpt))
3178 	continue;
3179 
3180       if (!breakpoint_enabled (bpt))
3181 	continue;
3182 
3183       if (bpt->disposition == disp_del_at_next_stop)
3184 	continue;
3185 
3186       for (bp_location *loc : bpt->locations ())
3187 	if (!loc->inserted && should_be_inserted (loc))
3188 	  {
3189 	    some_failed = true;
3190 	    break;
3191 	  }
3192 
3193       if (some_failed)
3194 	{
3195 	  for (bp_location *loc : bpt->locations ())
3196 	    if (loc->inserted)
3197 	      remove_breakpoint (loc);
3198 
3199 	  hw_breakpoint_error = 1;
3200 	  tmp_error_stream.printf ("Could not insert "
3201 				   "hardware watchpoint %d.\n",
3202 				   bpt->number);
3203 	  error_flag = -1;
3204 	}
3205     }
3206 
3207   if (error_flag)
3208     {
3209       /* If a hardware breakpoint or watchpoint was inserted, add a
3210 	 message about possibly exhausted resources.  */
3211       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3212 	{
3213 	  tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3214 You may have requested too many hardware breakpoints/watchpoints.\n");
3215 	}
3216       target_terminal::ours_for_output ();
3217       error_stream (tmp_error_stream);
3218     }
3219 }
3220 
3221 /* Used when the program stops.
3222    Returns zero if successful, or non-zero if there was a problem
3223    removing a breakpoint location.  */
3224 
3225 int
3226 remove_breakpoints (void)
3227 {
3228   int val = 0;
3229 
3230   for (bp_location *bl : all_bp_locations ())
3231     if (bl->inserted && !is_tracepoint (bl->owner))
3232       val |= remove_breakpoint (bl);
3233 
3234   return val;
3235 }
3236 
3237 /* When a thread exits, remove breakpoints that are related to
3238    that thread.  */
3239 
3240 static void
3241 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3242 {
3243   for (breakpoint *b : all_breakpoints_safe ())
3244     {
3245       if (b->thread == tp->global_num && user_breakpoint_p (b))
3246 	{
3247 	  b->disposition = disp_del_at_next_stop;
3248 
3249 	  gdb_printf (_("\
3250 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3251 		      b->number, print_thread_id (tp));
3252 
3253 	  /* Hide it from the user.  */
3254 	  b->number = 0;
3255        }
3256     }
3257 }
3258 
3259 /* See breakpoint.h.  */
3260 
3261 void
3262 remove_breakpoints_inf (inferior *inf)
3263 {
3264   int val;
3265 
3266   for (bp_location *bl : all_bp_locations ())
3267     {
3268       if (bl->pspace != inf->pspace)
3269 	continue;
3270 
3271       if (bl->inserted && !bl->target_info.persist)
3272 	{
3273 	  val = remove_breakpoint (bl);
3274 	  if (val != 0)
3275 	    return;
3276 	}
3277     }
3278 }
3279 
3280 static int internal_breakpoint_number = -1;
3281 
3282 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3283    If INTERNAL is non-zero, the breakpoint number will be populated
3284    from internal_breakpoint_number and that variable decremented.
3285    Otherwise the breakpoint number will be populated from
3286    breakpoint_count and that value incremented.  Internal breakpoints
3287    do not set the internal var bpnum.  */
3288 static void
3289 set_breakpoint_number (int internal, struct breakpoint *b)
3290 {
3291   if (internal)
3292     b->number = internal_breakpoint_number--;
3293   else
3294     {
3295       set_breakpoint_count (breakpoint_count + 1);
3296       b->number = breakpoint_count;
3297     }
3298 }
3299 
3300 /* Create a TYPE breakpoint on ADDRESS from an object file with GDBARCH.  */
3301 
3302 static struct breakpoint *
3303 create_internal_breakpoint (struct gdbarch *gdbarch,
3304 			    CORE_ADDR address, enum bptype type)
3305 {
3306   std::unique_ptr<internal_breakpoint> b
3307     (new internal_breakpoint (gdbarch, type, address));
3308 
3309   b->number = internal_breakpoint_number--;
3310 
3311   return add_to_breakpoint_chain (std::move (b));
3312 }
3313 
3314 /* Create a TYPE breakpoint on minimal symbol MSYM from an object file with
3315    GDBARCH.  */
3316 
3317 static struct breakpoint *
3318 create_internal_breakpoint (struct gdbarch *gdbarch,
3319 			    struct bound_minimal_symbol &msym, enum bptype type)
3320 {
3321   CORE_ADDR address;
3322 
3323   address = msym.value_address ();
3324 
3325   address = gdbarch_convert_from_func_ptr_addr
3326     (gdbarch, address, current_inferior ()->top_target ());
3327 
3328   /* Note that we're not using gdbarch_addr_bits_remove here, because that's
3329      related to addresses in $pc.  We're getting the address from the
3330      minimal symbol table.  */
3331 
3332   /* Is gdbarch_deprecated_function_start_offset needed here?  Or is that dealt
3333      with elsewhere?  Needs testing on vax.  */
3334 
3335   if (gdbarch_skip_entrypoint_p (gdbarch))
3336     address = gdbarch_skip_entrypoint (gdbarch, address);
3337 
3338   return create_internal_breakpoint (gdbarch, address, type);
3339 }
3340 
3341 static const char *const longjmp_names[] =
3342   {
3343     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3344   };
3345 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3346 
3347 /* Per-objfile data private to breakpoint.c.  */
3348 struct breakpoint_objfile_data
3349 {
3350   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3351   struct bound_minimal_symbol overlay_msym;
3352 
3353   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3354   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3355 
3356   /* True if we have looked for longjmp probes.  */
3357   int longjmp_searched = 0;
3358 
3359   /* SystemTap probe points for longjmp (if any).  These are non-owning
3360      references.  */
3361   std::vector<probe *> longjmp_probes;
3362 
3363   /* Minimal symbol for "std::terminate()" (if any).  */
3364   struct bound_minimal_symbol terminate_msym;
3365 
3366   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3367   struct bound_minimal_symbol exception_msym;
3368 
3369   /* True if we have looked for exception probes.  */
3370   int exception_searched = 0;
3371 
3372   /* SystemTap probe points for unwinding (if any).  These are non-owning
3373      references.  */
3374   std::vector<probe *> exception_probes;
3375 };
3376 
3377 static const registry<objfile>::key<breakpoint_objfile_data>
3378   breakpoint_objfile_key;
3379 
3380 /* Minimal symbol not found sentinel.  */
3381 static struct minimal_symbol msym_not_found;
3382 
3383 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3384 
3385 static bool
3386 msym_not_found_p (const struct minimal_symbol *msym)
3387 {
3388   return msym == &msym_not_found;
3389 }
3390 
3391 /* Return per-objfile data needed by breakpoint.c.
3392    Allocate the data if necessary.  */
3393 
3394 static struct breakpoint_objfile_data *
3395 get_breakpoint_objfile_data (struct objfile *objfile)
3396 {
3397   struct breakpoint_objfile_data *bp_objfile_data;
3398 
3399   bp_objfile_data = breakpoint_objfile_key.get (objfile);
3400   if (bp_objfile_data == NULL)
3401     bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3402   return bp_objfile_data;
3403 }
3404 
3405 static void
3406 create_overlay_event_breakpoint (void)
3407 {
3408   const char *const func_name = "_ovly_debug_event";
3409 
3410   for (objfile *objfile : current_program_space->objfiles ())
3411     {
3412       struct breakpoint *b;
3413       struct breakpoint_objfile_data *bp_objfile_data;
3414       CORE_ADDR addr;
3415 
3416       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3417 
3418       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3419 	continue;
3420 
3421       if (bp_objfile_data->overlay_msym.minsym == NULL)
3422 	{
3423 	  struct bound_minimal_symbol m;
3424 
3425 	  m = lookup_minimal_symbol_text (func_name, objfile);
3426 	  if (m.minsym == NULL)
3427 	    {
3428 	      /* Avoid future lookups in this objfile.  */
3429 	      bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3430 	      continue;
3431 	    }
3432 	  bp_objfile_data->overlay_msym = m;
3433 	}
3434 
3435       addr = bp_objfile_data->overlay_msym.value_address ();
3436       b = create_internal_breakpoint (objfile->arch (), addr,
3437 				      bp_overlay_event);
3438       b->locspec = new_explicit_location_spec_function (func_name);
3439 
3440       if (overlay_debugging == ovly_auto)
3441 	{
3442 	  b->enable_state = bp_enabled;
3443 	  overlay_events_enabled = 1;
3444 	}
3445       else
3446        {
3447 	 b->enable_state = bp_disabled;
3448 	 overlay_events_enabled = 0;
3449        }
3450     }
3451 }
3452 
3453 /* Install a master longjmp breakpoint for OBJFILE using a probe.  Return
3454    true if a breakpoint was installed.  */
3455 
3456 static bool
3457 create_longjmp_master_breakpoint_probe (objfile *objfile)
3458 {
3459   struct gdbarch *gdbarch = objfile->arch ();
3460   struct breakpoint_objfile_data *bp_objfile_data
3461     = get_breakpoint_objfile_data (objfile);
3462 
3463   if (!bp_objfile_data->longjmp_searched)
3464     {
3465       std::vector<probe *> ret
3466 	= find_probes_in_objfile (objfile, "libc", "longjmp");
3467 
3468       if (!ret.empty ())
3469 	{
3470 	  /* We are only interested in checking one element.  */
3471 	  probe *p = ret[0];
3472 
3473 	  if (!p->can_evaluate_arguments ())
3474 	    {
3475 	      /* We cannot use the probe interface here,
3476 		 because it does not know how to evaluate
3477 		 arguments.  */
3478 	      ret.clear ();
3479 	    }
3480 	}
3481       bp_objfile_data->longjmp_probes = ret;
3482       bp_objfile_data->longjmp_searched = 1;
3483     }
3484 
3485   if (bp_objfile_data->longjmp_probes.empty ())
3486     return false;
3487 
3488   for (probe *p : bp_objfile_data->longjmp_probes)
3489     {
3490       struct breakpoint *b;
3491 
3492       b = create_internal_breakpoint (gdbarch,
3493 				      p->get_relocated_address (objfile),
3494 				      bp_longjmp_master);
3495       b->locspec = new_probe_location_spec ("-probe-stap libc:longjmp");
3496       b->enable_state = bp_disabled;
3497     }
3498 
3499   return true;
3500 }
3501 
3502 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3503    Return true if at least one breakpoint was installed.  */
3504 
3505 static bool
3506 create_longjmp_master_breakpoint_names (objfile *objfile)
3507 {
3508   struct gdbarch *gdbarch = objfile->arch ();
3509   if (!gdbarch_get_longjmp_target_p (gdbarch))
3510     return false;
3511 
3512   struct breakpoint_objfile_data *bp_objfile_data
3513     = get_breakpoint_objfile_data (objfile);
3514   unsigned int installed_bp = 0;
3515 
3516   for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3517     {
3518       struct breakpoint *b;
3519       const char *func_name;
3520       CORE_ADDR addr;
3521 
3522       if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3523 	continue;
3524 
3525       func_name = longjmp_names[i];
3526       if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3527 	{
3528 	  struct bound_minimal_symbol m;
3529 
3530 	  m = lookup_minimal_symbol_text (func_name, objfile);
3531 	  if (m.minsym == NULL)
3532 	    {
3533 	      /* Prevent future lookups in this objfile.  */
3534 	      bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3535 	      continue;
3536 	    }
3537 	  bp_objfile_data->longjmp_msym[i] = m;
3538 	}
3539 
3540       addr = bp_objfile_data->longjmp_msym[i].value_address ();
3541       b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master);
3542       b->locspec = new_explicit_location_spec_function (func_name);
3543       b->enable_state = bp_disabled;
3544       installed_bp++;
3545     }
3546 
3547   return installed_bp > 0;
3548 }
3549 
3550 /* Create a master longjmp breakpoint.  */
3551 
3552 static void
3553 create_longjmp_master_breakpoint (void)
3554 {
3555   scoped_restore_current_program_space restore_pspace;
3556 
3557   for (struct program_space *pspace : program_spaces)
3558     {
3559       set_current_program_space (pspace);
3560 
3561       for (objfile *obj : current_program_space->objfiles ())
3562 	{
3563 	  /* Skip separate debug object, it's handled in the loop below.  */
3564 	  if (obj->separate_debug_objfile_backlink != nullptr)
3565 	    continue;
3566 
3567 	  /* Try a probe kind breakpoint on main objfile.  */
3568 	  if (create_longjmp_master_breakpoint_probe (obj))
3569 	    continue;
3570 
3571 	  /* Try longjmp_names kind breakpoints on main and separate_debug
3572 	     objfiles.  */
3573 	  for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3574 	    if (create_longjmp_master_breakpoint_names (debug_objfile))
3575 	      break;
3576 	}
3577     }
3578 }
3579 
3580 /* Create a master std::terminate breakpoint.  */
3581 static void
3582 create_std_terminate_master_breakpoint (void)
3583 {
3584   const char *const func_name = "std::terminate()";
3585 
3586   scoped_restore_current_program_space restore_pspace;
3587 
3588   for (struct program_space *pspace : program_spaces)
3589     {
3590       set_current_program_space (pspace);
3591 
3592       for (objfile *objfile : current_program_space->objfiles ())
3593 	{
3594 	  struct breakpoint *b;
3595 	  struct breakpoint_objfile_data *bp_objfile_data;
3596 
3597 	  bp_objfile_data = get_breakpoint_objfile_data (objfile);
3598 
3599 	  if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3600 	    continue;
3601 
3602 	  if (bp_objfile_data->terminate_msym.minsym == NULL)
3603 	    {
3604 	      struct bound_minimal_symbol m;
3605 
3606 	      m = lookup_minimal_symbol (func_name, NULL, objfile);
3607 	      if (m.minsym == NULL || (m.minsym->type () != mst_text
3608 				       && m.minsym->type () != mst_file_text))
3609 		{
3610 		  /* Prevent future lookups in this objfile.  */
3611 		  bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3612 		  continue;
3613 		}
3614 	      bp_objfile_data->terminate_msym = m;
3615 	    }
3616 
3617 	  b = create_internal_breakpoint (objfile->arch (),
3618 					  bp_objfile_data->terminate_msym,
3619 					  bp_std_terminate_master);
3620 	  b->locspec = new_explicit_location_spec_function (func_name);
3621 	  b->enable_state = bp_disabled;
3622 	}
3623     }
3624 }
3625 
3626 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3627    probe.  Return true if a breakpoint was installed.  */
3628 
3629 static bool
3630 create_exception_master_breakpoint_probe (objfile *objfile)
3631 {
3632   struct breakpoint *b;
3633   struct gdbarch *gdbarch;
3634   struct breakpoint_objfile_data *bp_objfile_data;
3635 
3636   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3637 
3638   /* We prefer the SystemTap probe point if it exists.  */
3639   if (!bp_objfile_data->exception_searched)
3640     {
3641       std::vector<probe *> ret
3642 	= find_probes_in_objfile (objfile, "libgcc", "unwind");
3643 
3644       if (!ret.empty ())
3645 	{
3646 	  /* We are only interested in checking one element.  */
3647 	  probe *p = ret[0];
3648 
3649 	  if (!p->can_evaluate_arguments ())
3650 	    {
3651 	      /* We cannot use the probe interface here, because it does
3652 		 not know how to evaluate arguments.  */
3653 	      ret.clear ();
3654 	    }
3655 	}
3656       bp_objfile_data->exception_probes = ret;
3657       bp_objfile_data->exception_searched = 1;
3658     }
3659 
3660   if (bp_objfile_data->exception_probes.empty ())
3661     return false;
3662 
3663   gdbarch = objfile->arch ();
3664 
3665   for (probe *p : bp_objfile_data->exception_probes)
3666     {
3667       b = create_internal_breakpoint (gdbarch,
3668 				      p->get_relocated_address (objfile),
3669 				      bp_exception_master);
3670       b->locspec = new_probe_location_spec ("-probe-stap libgcc:unwind");
3671       b->enable_state = bp_disabled;
3672     }
3673 
3674   return true;
3675 }
3676 
3677 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3678    _Unwind_DebugHook.  Return true if a breakpoint was installed.  */
3679 
3680 static bool
3681 create_exception_master_breakpoint_hook (objfile *objfile)
3682 {
3683   const char *const func_name = "_Unwind_DebugHook";
3684   struct breakpoint *b;
3685   struct gdbarch *gdbarch;
3686   struct breakpoint_objfile_data *bp_objfile_data;
3687 
3688   bp_objfile_data = get_breakpoint_objfile_data (objfile);
3689 
3690   if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3691     return false;
3692 
3693   gdbarch = objfile->arch ();
3694 
3695   if (bp_objfile_data->exception_msym.minsym == NULL)
3696     {
3697       struct bound_minimal_symbol debug_hook;
3698 
3699       debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3700       if (debug_hook.minsym == NULL)
3701 	{
3702 	  bp_objfile_data->exception_msym.minsym = &msym_not_found;
3703 	  return false;
3704 	}
3705 
3706       bp_objfile_data->exception_msym = debug_hook;
3707     }
3708 
3709   b = create_internal_breakpoint (gdbarch, bp_objfile_data->exception_msym,
3710 				  bp_exception_master);
3711   b->locspec = new_explicit_location_spec_function (func_name);
3712   b->enable_state = bp_disabled;
3713 
3714   return true;
3715 }
3716 
3717 /* Install a master breakpoint on the unwinder's debug hook.  */
3718 
3719 static void
3720 create_exception_master_breakpoint (void)
3721 {
3722   for (objfile *obj : current_program_space->objfiles ())
3723     {
3724       /* Skip separate debug object.  */
3725       if (obj->separate_debug_objfile_backlink)
3726 	continue;
3727 
3728       /* Try a probe kind breakpoint.  */
3729       if (create_exception_master_breakpoint_probe (obj))
3730 	continue;
3731 
3732       /* Iterate over main and separate debug objects and try an
3733 	 _Unwind_DebugHook kind breakpoint.  */
3734       for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3735 	if (create_exception_master_breakpoint_hook (debug_objfile))
3736 	  break;
3737     }
3738 }
3739 
3740 /* Does B have a location spec?  */
3741 
3742 static bool
3743 breakpoint_location_spec_empty_p (const struct breakpoint *b)
3744 {
3745   return (b->locspec != nullptr && b->locspec->empty_p ());
3746 }
3747 
3748 void
3749 update_breakpoints_after_exec (void)
3750 {
3751   /* We're about to delete breakpoints from GDB's lists.  If the
3752      INSERTED flag is true, GDB will try to lift the breakpoints by
3753      writing the breakpoints' "shadow contents" back into memory.  The
3754      "shadow contents" are NOT valid after an exec, so GDB should not
3755      do that.  Instead, the target is responsible from marking
3756      breakpoints out as soon as it detects an exec.  We don't do that
3757      here instead, because there may be other attempts to delete
3758      breakpoints after detecting an exec and before reaching here.  */
3759   for (bp_location *bploc : all_bp_locations ())
3760     if (bploc->pspace == current_program_space)
3761       gdb_assert (!bploc->inserted);
3762 
3763   for (breakpoint *b : all_breakpoints_safe ())
3764     {
3765       if (b->pspace != current_program_space)
3766 	continue;
3767 
3768       /* Solib breakpoints must be explicitly reset after an exec().  */
3769       if (b->type == bp_shlib_event)
3770 	{
3771 	  delete_breakpoint (b);
3772 	  continue;
3773 	}
3774 
3775       /* JIT breakpoints must be explicitly reset after an exec().  */
3776       if (b->type == bp_jit_event)
3777 	{
3778 	  delete_breakpoint (b);
3779 	  continue;
3780 	}
3781 
3782       /* Thread event breakpoints must be set anew after an exec(),
3783 	 as must overlay event and longjmp master breakpoints.  */
3784       if (b->type == bp_thread_event || b->type == bp_overlay_event
3785 	  || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3786 	  || b->type == bp_exception_master)
3787 	{
3788 	  delete_breakpoint (b);
3789 	  continue;
3790 	}
3791 
3792       /* Step-resume breakpoints are meaningless after an exec().  */
3793       if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3794 	{
3795 	  delete_breakpoint (b);
3796 	  continue;
3797 	}
3798 
3799       /* Just like single-step breakpoints.  */
3800       if (b->type == bp_single_step)
3801 	{
3802 	  delete_breakpoint (b);
3803 	  continue;
3804 	}
3805 
3806       /* Longjmp and longjmp-resume breakpoints are also meaningless
3807 	 after an exec.  */
3808       if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3809 	  || b->type == bp_longjmp_call_dummy
3810 	  || b->type == bp_exception || b->type == bp_exception_resume)
3811 	{
3812 	  delete_breakpoint (b);
3813 	  continue;
3814 	}
3815 
3816       if (b->type == bp_catchpoint)
3817 	{
3818 	  /* For now, none of the bp_catchpoint breakpoints need to
3819 	     do anything at this point.  In the future, if some of
3820 	     the catchpoints need to something, we will need to add
3821 	     a new method, and call this method from here.  */
3822 	  continue;
3823 	}
3824 
3825       /* bp_finish is a special case.  The only way we ought to be able
3826 	 to see one of these when an exec() has happened, is if the user
3827 	 caught a vfork, and then said "finish".  Ordinarily a finish just
3828 	 carries them to the call-site of the current callee, by setting
3829 	 a temporary bp there and resuming.  But in this case, the finish
3830 	 will carry them entirely through the vfork & exec.
3831 
3832 	 We don't want to allow a bp_finish to remain inserted now.  But
3833 	 we can't safely delete it, 'cause finish_command has a handle to
3834 	 the bp on a bpstat, and will later want to delete it.  There's a
3835 	 chance (and I've seen it happen) that if we delete the bp_finish
3836 	 here, that its storage will get reused by the time finish_command
3837 	 gets 'round to deleting the "use to be a bp_finish" breakpoint.
3838 	 We really must allow finish_command to delete a bp_finish.
3839 
3840 	 In the absence of a general solution for the "how do we know
3841 	 it's safe to delete something others may have handles to?"
3842 	 problem, what we'll do here is just uninsert the bp_finish, and
3843 	 let finish_command delete it.
3844 
3845 	 (We know the bp_finish is "doomed" in the sense that it's
3846 	 momentary, and will be deleted as soon as finish_command sees
3847 	 the inferior stopped.  So it doesn't matter that the bp's
3848 	 address is probably bogus in the new a.out, unlike e.g., the
3849 	 solib breakpoints.)  */
3850 
3851       if (b->type == bp_finish)
3852 	{
3853 	  continue;
3854 	}
3855 
3856       /* Without a symbolic address, we have little hope of the
3857 	 pre-exec() address meaning the same thing in the post-exec()
3858 	 a.out.  */
3859       if (breakpoint_location_spec_empty_p (b))
3860 	{
3861 	  delete_breakpoint (b);
3862 	  continue;
3863 	}
3864     }
3865 }
3866 
3867 int
3868 detach_breakpoints (ptid_t ptid)
3869 {
3870   int val = 0;
3871   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3872   struct inferior *inf = current_inferior ();
3873 
3874   if (ptid.pid () == inferior_ptid.pid ())
3875     error (_("Cannot detach breakpoints of inferior_ptid"));
3876 
3877   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3878   inferior_ptid = ptid;
3879   for (bp_location *bl : all_bp_locations ())
3880     {
3881       if (bl->pspace != inf->pspace)
3882 	continue;
3883 
3884       /* This function must physically remove breakpoints locations
3885 	 from the specified ptid, without modifying the breakpoint
3886 	 package's state.  Locations of type bp_loc_other and
3887 	 bp_loc_software_watchpoint are only maintained at GDB side,
3888 	 so there is no need to remove them.  Moreover, removing these
3889 	 would modify the breakpoint package's state.  */
3890       if (bl->loc_type == bp_loc_other
3891 	  || bl->loc_type == bp_loc_software_watchpoint)
3892 	continue;
3893 
3894       if (bl->inserted)
3895 	val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3896     }
3897 
3898   return val;
3899 }
3900 
3901 /* Remove the breakpoint location BL from the current address space.
3902    Note that this is used to detach breakpoints from a child fork.
3903    When we get here, the child isn't in the inferior list, and neither
3904    do we have objects to represent its address space --- we should
3905    *not* look at bl->pspace->aspace here.  */
3906 
3907 static int
3908 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3909 {
3910   int val;
3911 
3912   /* BL is never in moribund_locations by our callers.  */
3913   gdb_assert (bl->owner != NULL);
3914 
3915   /* The type of none suggests that owner is actually deleted.
3916      This should not ever happen.  */
3917   gdb_assert (bl->owner->type != bp_none);
3918 
3919   if (bl->loc_type == bp_loc_software_breakpoint
3920       || bl->loc_type == bp_loc_hardware_breakpoint)
3921     {
3922       /* "Normal" instruction breakpoint: either the standard
3923 	 trap-instruction bp (bp_breakpoint), or a
3924 	 bp_hardware_breakpoint.  */
3925 
3926       /* First check to see if we have to handle an overlay.  */
3927       if (overlay_debugging == ovly_off
3928 	  || bl->section == NULL
3929 	  || !(section_is_overlay (bl->section)))
3930 	{
3931 	  /* No overlay handling: just remove the breakpoint.  */
3932 
3933 	  /* If we're trying to uninsert a memory breakpoint that we
3934 	     know is set in a dynamic object that is marked
3935 	     shlib_disabled, then either the dynamic object was
3936 	     removed with "remove-symbol-file" or with
3937 	     "nosharedlibrary".  In the former case, we don't know
3938 	     whether another dynamic object might have loaded over the
3939 	     breakpoint's address -- the user might well let us know
3940 	     about it next with add-symbol-file (the whole point of
3941 	     add-symbol-file is letting the user manually maintain a
3942 	     list of dynamically loaded objects).  If we have the
3943 	     breakpoint's shadow memory, that is, this is a software
3944 	     breakpoint managed by GDB, check whether the breakpoint
3945 	     is still inserted in memory, to avoid overwriting wrong
3946 	     code with stale saved shadow contents.  Note that HW
3947 	     breakpoints don't have shadow memory, as they're
3948 	     implemented using a mechanism that is not dependent on
3949 	     being able to modify the target's memory, and as such
3950 	     they should always be removed.  */
3951 	  if (bl->shlib_disabled
3952 	      && bl->target_info.shadow_len != 0
3953 	      && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3954 	    val = 0;
3955 	  else
3956 	    val = bl->owner->remove_location (bl, reason);
3957 	}
3958       else
3959 	{
3960 	  /* This breakpoint is in an overlay section.
3961 	     Did we set a breakpoint at the LMA?  */
3962 	  if (!overlay_events_enabled)
3963 	      {
3964 		/* Yes -- overlay event support is not active, so we
3965 		   should have set a breakpoint at the LMA.  Remove it.
3966 		*/
3967 		/* Ignore any failures: if the LMA is in ROM, we will
3968 		   have already warned when we failed to insert it.  */
3969 		if (bl->loc_type == bp_loc_hardware_breakpoint)
3970 		  target_remove_hw_breakpoint (bl->gdbarch,
3971 					       &bl->overlay_target_info);
3972 		else
3973 		  target_remove_breakpoint (bl->gdbarch,
3974 					    &bl->overlay_target_info,
3975 					    reason);
3976 	      }
3977 	  /* Did we set a breakpoint at the VMA?
3978 	     If so, we will have marked the breakpoint 'inserted'.  */
3979 	  if (bl->inserted)
3980 	    {
3981 	      /* Yes -- remove it.  Previously we did not bother to
3982 		 remove the breakpoint if the section had been
3983 		 unmapped, but let's not rely on that being safe.  We
3984 		 don't know what the overlay manager might do.  */
3985 
3986 	      /* However, we should remove *software* breakpoints only
3987 		 if the section is still mapped, or else we overwrite
3988 		 wrong code with the saved shadow contents.  */
3989 	      if (bl->loc_type == bp_loc_hardware_breakpoint
3990 		  || section_is_mapped (bl->section))
3991 		val = bl->owner->remove_location (bl, reason);
3992 	      else
3993 		val = 0;
3994 	    }
3995 	  else
3996 	    {
3997 	      /* No -- not inserted, so no need to remove.  No error.  */
3998 	      val = 0;
3999 	    }
4000 	}
4001 
4002       /* In some cases, we might not be able to remove a breakpoint in
4003 	 a shared library that has already been removed, but we have
4004 	 not yet processed the shlib unload event.  Similarly for an
4005 	 unloaded add-symbol-file object - the user might not yet have
4006 	 had the chance to remove-symbol-file it.  shlib_disabled will
4007 	 be set if the library/object has already been removed, but
4008 	 the breakpoint hasn't been uninserted yet, e.g., after
4009 	 "nosharedlibrary" or "remove-symbol-file" with breakpoints
4010 	 always-inserted mode.  */
4011       if (val
4012 	  && (bl->loc_type == bp_loc_software_breakpoint
4013 	      && (bl->shlib_disabled
4014 		  || solib_name_from_address (bl->pspace, bl->address)
4015 		  || shared_objfile_contains_address_p (bl->pspace,
4016 							bl->address))))
4017 	val = 0;
4018 
4019       if (val)
4020 	return val;
4021       bl->inserted = (reason == DETACH_BREAKPOINT);
4022     }
4023   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4024     {
4025       bl->inserted = (reason == DETACH_BREAKPOINT);
4026       bl->owner->remove_location (bl, reason);
4027 
4028       /* Failure to remove any of the hardware watchpoints comes here.  */
4029       if (reason == REMOVE_BREAKPOINT && bl->inserted)
4030 	warning (_("Could not remove hardware watchpoint %d."),
4031 		 bl->owner->number);
4032     }
4033   else if (bl->owner->type == bp_catchpoint
4034 	   && breakpoint_enabled (bl->owner)
4035 	   && !bl->duplicate)
4036     {
4037       val = bl->owner->remove_location (bl, reason);
4038       if (val)
4039 	return val;
4040 
4041       bl->inserted = (reason == DETACH_BREAKPOINT);
4042     }
4043 
4044   return 0;
4045 }
4046 
4047 static int
4048 remove_breakpoint (struct bp_location *bl)
4049 {
4050   /* BL is never in moribund_locations by our callers.  */
4051   gdb_assert (bl->owner != NULL);
4052 
4053   /* The type of none suggests that owner is actually deleted.
4054      This should not ever happen.  */
4055   gdb_assert (bl->owner->type != bp_none);
4056 
4057   scoped_restore_current_pspace_and_thread restore_pspace_thread;
4058 
4059   switch_to_program_space_and_thread (bl->pspace);
4060 
4061   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4062 }
4063 
4064 /* Clear the "inserted" flag in all breakpoints.  */
4065 
4066 void
4067 mark_breakpoints_out (void)
4068 {
4069   for (bp_location *bl : all_bp_locations ())
4070     if (bl->pspace == current_program_space)
4071       bl->inserted = 0;
4072 }
4073 
4074 /* Clear the "inserted" flag in all breakpoints and delete any
4075    breakpoints which should go away between runs of the program.
4076 
4077    Plus other such housekeeping that has to be done for breakpoints
4078    between runs.
4079 
4080    Note: this function gets called at the end of a run (by
4081    generic_mourn_inferior) and when a run begins (by
4082    init_wait_for_inferior).  */
4083 
4084 
4085 
4086 void
4087 breakpoint_init_inferior (enum inf_context context)
4088 {
4089   struct program_space *pspace = current_program_space;
4090 
4091   /* If breakpoint locations are shared across processes, then there's
4092      nothing to do.  */
4093   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4094     return;
4095 
4096   mark_breakpoints_out ();
4097 
4098   for (breakpoint *b : all_breakpoints_safe ())
4099     {
4100       if (b->loc && b->loc->pspace != pspace)
4101 	continue;
4102 
4103       switch (b->type)
4104 	{
4105 	case bp_call_dummy:
4106 	case bp_longjmp_call_dummy:
4107 
4108 	  /* If the call dummy breakpoint is at the entry point it will
4109 	     cause problems when the inferior is rerun, so we better get
4110 	     rid of it.  */
4111 
4112 	case bp_watchpoint_scope:
4113 
4114 	  /* Also get rid of scope breakpoints.  */
4115 
4116 	case bp_shlib_event:
4117 
4118 	  /* Also remove solib event breakpoints.  Their addresses may
4119 	     have changed since the last time we ran the program.
4120 	     Actually we may now be debugging against different target;
4121 	     and so the solib backend that installed this breakpoint may
4122 	     not be used in by the target.  E.g.,
4123 
4124 	     (gdb) file prog-linux
4125 	     (gdb) run               # native linux target
4126 	     ...
4127 	     (gdb) kill
4128 	     (gdb) file prog-win.exe
4129 	     (gdb) tar rem :9999     # remote Windows gdbserver.
4130 	  */
4131 
4132 	case bp_step_resume:
4133 
4134 	  /* Also remove step-resume breakpoints.  */
4135 
4136 	case bp_single_step:
4137 
4138 	  /* Also remove single-step breakpoints.  */
4139 
4140 	  delete_breakpoint (b);
4141 	  break;
4142 
4143 	case bp_watchpoint:
4144 	case bp_hardware_watchpoint:
4145 	case bp_read_watchpoint:
4146 	case bp_access_watchpoint:
4147 	  {
4148 	    struct watchpoint *w = (struct watchpoint *) b;
4149 
4150 	    /* Likewise for watchpoints on local expressions.  */
4151 	    if (w->exp_valid_block != NULL)
4152 	      delete_breakpoint (b);
4153 	    else
4154 	      {
4155 		/* Get rid of existing locations, which are no longer
4156 		   valid.  New ones will be created in
4157 		   update_watchpoint, when the inferior is restarted.
4158 		   The next update_global_location_list call will
4159 		   garbage collect them.  */
4160 		b->loc = NULL;
4161 
4162 		if (context == inf_starting)
4163 		  {
4164 		    /* Reset val field to force reread of starting value in
4165 		       insert_breakpoints.  */
4166 		    w->val.reset (nullptr);
4167 		    w->val_valid = false;
4168 		  }
4169 	      }
4170 	  }
4171 	  break;
4172 	default:
4173 	  break;
4174 	}
4175     }
4176 
4177   /* Get rid of the moribund locations.  */
4178   for (bp_location *bl : moribund_locations)
4179     decref_bp_location (&bl);
4180   moribund_locations.clear ();
4181 }
4182 
4183 /* These functions concern about actual breakpoints inserted in the
4184    target --- to e.g. check if we need to do decr_pc adjustment or if
4185    we need to hop over the bkpt --- so we check for address space
4186    match, not program space.  */
4187 
4188 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4189    exists at PC.  It returns ordinary_breakpoint_here if it's an
4190    ordinary breakpoint, or permanent_breakpoint_here if it's a
4191    permanent breakpoint.
4192    - When continuing from a location with an ordinary breakpoint, we
4193      actually single step once before calling insert_breakpoints.
4194    - When continuing from a location with a permanent breakpoint, we
4195      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4196      the target, to advance the PC past the breakpoint.  */
4197 
4198 enum breakpoint_here
4199 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4200 {
4201   bool any_breakpoint_here = false;
4202 
4203   for (bp_location *bl : all_bp_locations ())
4204     {
4205       if (bl->loc_type != bp_loc_software_breakpoint
4206 	  && bl->loc_type != bp_loc_hardware_breakpoint)
4207 	continue;
4208 
4209       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4210       if ((breakpoint_enabled (bl->owner)
4211 	   || bl->permanent)
4212 	  && breakpoint_location_address_match (bl, aspace, pc))
4213 	{
4214 	  if (overlay_debugging
4215 	      && section_is_overlay (bl->section)
4216 	      && !section_is_mapped (bl->section))
4217 	    continue;		/* unmapped overlay -- can't be a match */
4218 	  else if (bl->permanent)
4219 	    return permanent_breakpoint_here;
4220 	  else
4221 	    any_breakpoint_here = true;
4222 	}
4223     }
4224 
4225   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4226 }
4227 
4228 /* See breakpoint.h.  */
4229 
4230 int
4231 breakpoint_in_range_p (const address_space *aspace,
4232 		       CORE_ADDR addr, ULONGEST len)
4233 {
4234   for (bp_location *bl : all_bp_locations ())
4235     {
4236       if (bl->loc_type != bp_loc_software_breakpoint
4237 	  && bl->loc_type != bp_loc_hardware_breakpoint)
4238 	continue;
4239 
4240       if ((breakpoint_enabled (bl->owner)
4241 	   || bl->permanent)
4242 	  && breakpoint_location_address_range_overlap (bl, aspace,
4243 							addr, len))
4244 	{
4245 	  if (overlay_debugging
4246 	      && section_is_overlay (bl->section)
4247 	      && !section_is_mapped (bl->section))
4248 	    {
4249 	      /* Unmapped overlay -- can't be a match.  */
4250 	      continue;
4251 	    }
4252 
4253 	  return 1;
4254 	}
4255     }
4256 
4257   return 0;
4258 }
4259 
4260 /* Return true if there's a moribund breakpoint at PC.  */
4261 
4262 int
4263 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4264 {
4265   for (bp_location *loc : moribund_locations)
4266     if (breakpoint_location_address_match (loc, aspace, pc))
4267       return 1;
4268 
4269   return 0;
4270 }
4271 
4272 /* Returns true iff BL is inserted at PC, in address space ASPACE.  */
4273 
4274 static bool
4275 bp_location_inserted_here_p (const struct bp_location *bl,
4276 			     const address_space *aspace, CORE_ADDR pc)
4277 {
4278   if (bl->inserted
4279       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4280 				   aspace, pc))
4281     {
4282       /* An unmapped overlay can't be a match.  */
4283       return !(overlay_debugging
4284 	       && section_is_overlay (bl->section)
4285 	       && !section_is_mapped (bl->section));
4286     }
4287   return false;
4288 }
4289 
4290 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4291 
4292 int
4293 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4294 {
4295   for (bp_location *bl : all_bp_locations_at_addr (pc))
4296     {
4297       if (bl->loc_type != bp_loc_software_breakpoint
4298 	  && bl->loc_type != bp_loc_hardware_breakpoint)
4299 	continue;
4300 
4301       if (bp_location_inserted_here_p (bl, aspace, pc))
4302 	return 1;
4303     }
4304   return 0;
4305 }
4306 
4307 /* This function returns non-zero iff there is a software breakpoint
4308    inserted at PC.  */
4309 
4310 int
4311 software_breakpoint_inserted_here_p (const address_space *aspace,
4312 				     CORE_ADDR pc)
4313 {
4314   for (bp_location *bl : all_bp_locations_at_addr (pc))
4315     {
4316       if (bl->loc_type != bp_loc_software_breakpoint)
4317 	continue;
4318 
4319       if (bp_location_inserted_here_p (bl, aspace, pc))
4320 	return 1;
4321     }
4322 
4323   return 0;
4324 }
4325 
4326 /* See breakpoint.h.  */
4327 
4328 int
4329 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4330 				     CORE_ADDR pc)
4331 {
4332   for (bp_location *bl : all_bp_locations_at_addr (pc))
4333     {
4334       if (bl->loc_type != bp_loc_hardware_breakpoint)
4335 	continue;
4336 
4337       if (bp_location_inserted_here_p (bl, aspace, pc))
4338 	return 1;
4339     }
4340 
4341   return 0;
4342 }
4343 
4344 int
4345 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4346 				       CORE_ADDR addr, ULONGEST len)
4347 {
4348   for (breakpoint *bpt : all_breakpoints ())
4349     {
4350       if (bpt->type != bp_hardware_watchpoint
4351 	  && bpt->type != bp_access_watchpoint)
4352 	continue;
4353 
4354       if (!breakpoint_enabled (bpt))
4355 	continue;
4356 
4357       for (bp_location *loc : bpt->locations ())
4358 	if (loc->pspace->aspace == aspace && loc->inserted)
4359 	  {
4360 	    CORE_ADDR l, h;
4361 
4362 	    /* Check for intersection.  */
4363 	    l = std::max<CORE_ADDR> (loc->address, addr);
4364 	    h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4365 	    if (l < h)
4366 	      return 1;
4367 	  }
4368     }
4369   return 0;
4370 }
4371 
4372 /* See breakpoint.h.  */
4373 
4374 bool
4375 is_catchpoint (struct breakpoint *b)
4376 {
4377   return (b->type == bp_catchpoint);
4378 }
4379 
4380 /* Clear a bpstat so that it says we are not at any breakpoint.
4381    Also free any storage that is part of a bpstat.  */
4382 
4383 void
4384 bpstat_clear (bpstat **bsp)
4385 {
4386   bpstat *p;
4387   bpstat *q;
4388 
4389   if (bsp == 0)
4390     return;
4391   p = *bsp;
4392   while (p != NULL)
4393     {
4394       q = p->next;
4395       delete p;
4396       p = q;
4397     }
4398   *bsp = NULL;
4399 }
4400 
4401 bpstat::bpstat (const bpstat &other)
4402   : next (NULL),
4403     bp_location_at (other.bp_location_at),
4404     breakpoint_at (other.breakpoint_at),
4405     commands (other.commands),
4406     print (other.print),
4407     stop (other.stop),
4408     print_it (other.print_it)
4409 {
4410   if (other.old_val != NULL)
4411     old_val = release_value (value_copy (other.old_val.get ()));
4412 }
4413 
4414 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4415    is part of the bpstat is copied as well.  */
4416 
4417 bpstat *
4418 bpstat_copy (bpstat *bs)
4419 {
4420   bpstat *p = nullptr;
4421   bpstat *tmp;
4422   bpstat *retval = nullptr;
4423 
4424   if (bs == NULL)
4425     return bs;
4426 
4427   for (; bs != NULL; bs = bs->next)
4428     {
4429       tmp = new bpstat (*bs);
4430 
4431       if (p == NULL)
4432 	/* This is the first thing in the chain.  */
4433 	retval = tmp;
4434       else
4435 	p->next = tmp;
4436       p = tmp;
4437     }
4438   p->next = NULL;
4439   return retval;
4440 }
4441 
4442 /* Find the bpstat associated with this breakpoint.  */
4443 
4444 bpstat *
4445 bpstat_find_breakpoint (bpstat *bsp, struct breakpoint *breakpoint)
4446 {
4447   if (bsp == NULL)
4448     return NULL;
4449 
4450   for (; bsp != NULL; bsp = bsp->next)
4451     {
4452       if (bsp->breakpoint_at == breakpoint)
4453 	return bsp;
4454     }
4455   return NULL;
4456 }
4457 
4458 /* See breakpoint.h.  */
4459 
4460 bool
4461 bpstat_explains_signal (bpstat *bsp, enum gdb_signal sig)
4462 {
4463   for (; bsp != NULL; bsp = bsp->next)
4464     {
4465       if (bsp->breakpoint_at == NULL)
4466 	{
4467 	  /* A moribund location can never explain a signal other than
4468 	     GDB_SIGNAL_TRAP.  */
4469 	  if (sig == GDB_SIGNAL_TRAP)
4470 	    return true;
4471 	}
4472       else
4473 	{
4474 	  if (bsp->breakpoint_at->explains_signal (sig))
4475 	    return true;
4476 	}
4477     }
4478 
4479   return false;
4480 }
4481 
4482 /* See breakpoint.h.  */
4483 
4484 int
4485 bpstat_num (bpstat **bsp, int *num)
4486 {
4487   struct breakpoint *b;
4488 
4489   if ((*bsp) == NULL)
4490     return 0;			/* No more breakpoint values */
4491 
4492   /* We assume we'll never have several bpstats that correspond to a
4493      single breakpoint -- otherwise, this function might return the
4494      same number more than once and this will look ugly.  */
4495   b = (*bsp)->breakpoint_at;
4496   *bsp = (*bsp)->next;
4497   if (b == NULL)
4498     return -1;			/* breakpoint that's been deleted since */
4499 
4500   *num = b->number;		/* We have its number */
4501   return 1;
4502 }
4503 
4504 /* See breakpoint.h  */
4505 
4506 int
4507 bpstat_locno (const bpstat *bs)
4508 {
4509   const struct breakpoint *b = bs->breakpoint_at;
4510   const struct bp_location *bl = bs->bp_location_at.get ();
4511 
4512   int locno = 0;
4513 
4514   if (b != nullptr && b->loc != nullptr && b->loc->next != nullptr)
4515     {
4516       const bp_location *bl_i;
4517 
4518       for (bl_i = b->loc;
4519 	   bl_i != bl && bl_i->next != nullptr;
4520 	   bl_i = bl_i->next)
4521 	locno++;
4522 
4523       if (bl_i == bl)
4524 	locno++;
4525       else
4526 	{
4527 	  warning (_("location number not found for breakpoint %d address %s."),
4528 		   b->number, paddress (bl->gdbarch, bl->address));
4529 	  locno = 0;
4530 	}
4531     }
4532 
4533   return locno;
4534 }
4535 
4536 /* See breakpoint.h.  */
4537 
4538 void
4539 print_num_locno (const bpstat *bs, struct ui_out *uiout)
4540 {
4541   struct breakpoint *b = bs->breakpoint_at;
4542 
4543   if (b == nullptr)
4544     uiout->text (_("deleted breakpoint"));
4545   else
4546     {
4547       uiout->field_signed ("bkptno", b->number);
4548 
4549       int locno = bpstat_locno (bs);
4550       if (locno != 0)
4551 	uiout->message (".%pF", signed_field ("locno", locno));
4552     }
4553 }
4554 
4555 /* See breakpoint.h.  */
4556 
4557 void
4558 bpstat_clear_actions (void)
4559 {
4560   bpstat *bs;
4561 
4562   if (inferior_ptid == null_ptid)
4563     return;
4564 
4565   thread_info *tp = inferior_thread ();
4566   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4567     {
4568       bs->commands = NULL;
4569       bs->old_val.reset (nullptr);
4570     }
4571 }
4572 
4573 /* Called when a command is about to proceed the inferior.  */
4574 
4575 static void
4576 breakpoint_about_to_proceed (void)
4577 {
4578   if (inferior_ptid != null_ptid)
4579     {
4580       struct thread_info *tp = inferior_thread ();
4581 
4582       /* Allow inferior function calls in breakpoint commands to not
4583 	 interrupt the command list.  When the call finishes
4584 	 successfully, the inferior will be standing at the same
4585 	 breakpoint as if nothing happened.  */
4586       if (tp->control.in_infcall)
4587 	return;
4588     }
4589 
4590   breakpoint_proceeded = 1;
4591 }
4592 
4593 /* Return true iff CMD as the first line of a command sequence is `silent'
4594    or its equivalent.  */
4595 
4596 static bool
4597 command_line_is_silent (struct command_line *cmd)
4598 {
4599   return cmd && (strcmp ("silent", cmd->line) == 0);
4600 }
4601 
4602 /* Sets the $_hit_bpnum and $_hit_locno to bpnum and locno.
4603    A locno 0 is changed to 1 to e.g. let the user do
4604      (gdb) disable $_hit_bpnum.$_hit_locno
4605    for a single location breakpoint.  */
4606 
4607 static void
4608 set_hit_convenience_vars (int bpnum, int locno)
4609 {
4610   set_internalvar_integer (lookup_internalvar ("_hit_bpnum"), bpnum);
4611   set_internalvar_integer (lookup_internalvar ("_hit_locno"),
4612 			   (locno > 0 ? locno : 1));
4613 }
4614 
4615 /* Execute all the commands associated with all the breakpoints at
4616    this location.  Any of these commands could cause the process to
4617    proceed beyond this point, etc.  We look out for such changes by
4618    checking the global "breakpoint_proceeded" after each command.
4619 
4620    Returns true if a breakpoint command resumed the inferior.  In that
4621    case, it is the caller's responsibility to recall it again with the
4622    bpstat of the current thread.  */
4623 
4624 static bool
4625 bpstat_do_actions_1 (bpstat **bsp)
4626 {
4627   bpstat *bs;
4628   bool again = false;
4629 
4630   /* Avoid endless recursion if a `source' command is contained
4631      in bs->commands.  */
4632   if (executing_breakpoint_commands)
4633     return false;
4634 
4635   scoped_restore save_executing
4636     = make_scoped_restore (&executing_breakpoint_commands, 1);
4637 
4638   scoped_restore preventer = prevent_dont_repeat ();
4639 
4640   /* This pointer will iterate over the list of bpstat's.  */
4641   bs = *bsp;
4642 
4643   /* The $_hit_* convenience variables are set before running the
4644      commands of BS.  In case we have several bs, after the loop,
4645      we set again the variables to the first printed bpnum and locno.
4646      For multiple breakpoints, this ensures the variables are set to the
4647      breakpoint printed for the user. */
4648   int printed_hit_bpnum = -1;
4649   int printed_hit_locno = -1;
4650 
4651   breakpoint_proceeded = 0;
4652   for (; bs != NULL; bs = bs->next)
4653     {
4654       struct command_line *cmd = NULL;
4655 
4656       /* Set the _hit_* convenience variables before running BS's commands.  */
4657       {
4658 	const struct breakpoint *b = bs->breakpoint_at;
4659 	if (b != nullptr)
4660 	  {
4661 	    int locno = bpstat_locno (bs);
4662 
4663 	    set_hit_convenience_vars (b->number, locno);
4664 	    if (printed_hit_locno == -1 && bs->print)
4665 	      {
4666 		printed_hit_bpnum = b->number;
4667 		printed_hit_locno = locno;
4668 	      }
4669 	  }
4670       }
4671 
4672       /* Take ownership of the BSP's command tree, if it has one.
4673 
4674 	 The command tree could legitimately contain commands like
4675 	 'step' and 'next', which call clear_proceed_status, which
4676 	 frees the bpstat BS and its command tree.  To make sure this doesn't
4677 	 free the tree we're executing out from under us, we need to
4678 	 take ownership of the tree ourselves.  Since a given bpstat's
4679 	 commands are only executed once, we don't need to copy it; we
4680 	 can clear the pointer in the bpstat, and make sure we free
4681 	 the tree when we're done.  */
4682       counted_command_line ccmd = bs->commands;
4683       bs->commands = NULL;
4684       if (ccmd != NULL)
4685 	cmd = ccmd.get ();
4686       if (command_line_is_silent (cmd))
4687 	{
4688 	  /* The action has been already done by bpstat_stop_status.  */
4689 	  cmd = cmd->next;
4690 	}
4691 
4692       while (cmd != NULL)
4693 	{
4694 	  execute_control_command (cmd);
4695 	  /* After execute_control_command, if breakpoint_proceeded is true,
4696 	     BS has been freed and cannot be accessed anymore.  */
4697 
4698 	  if (breakpoint_proceeded)
4699 	    break;
4700 	  else
4701 	    cmd = cmd->next;
4702 	}
4703 
4704       if (breakpoint_proceeded)
4705 	{
4706 	  if (current_ui->async)
4707 	    /* If we are in async mode, then the target might be still
4708 	       running, not stopped at any breakpoint, so nothing for
4709 	       us to do here -- just return to the event loop.  */
4710 	    ;
4711 	  else
4712 	    /* In sync mode, when execute_control_command returns
4713 	       we're already standing on the next breakpoint.
4714 	       Breakpoint commands for that stop were not run, since
4715 	       execute_command does not run breakpoint commands --
4716 	       only command_line_handler does, but that one is not
4717 	       involved in execution of breakpoint commands.  So, we
4718 	       can now execute breakpoint commands.  It should be
4719 	       noted that making execute_command do bpstat actions is
4720 	       not an option -- in this case we'll have recursive
4721 	       invocation of bpstat for each breakpoint with a
4722 	       command, and can easily blow up GDB stack.  Instead, we
4723 	       return true, which will trigger the caller to recall us
4724 	       with the new stop_bpstat.  */
4725 	    again = true;
4726 	  break;
4727 	}
4728     }
4729 
4730   /* Now that we have executed the commands of all bs, set the _hit_*
4731      convenience variables to the printed values.  */
4732   if (printed_hit_locno != -1)
4733     set_hit_convenience_vars (printed_hit_bpnum, printed_hit_locno);
4734 
4735   return again;
4736 }
4737 
4738 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4739    one, is alive and has execution.  Return NULL otherwise.  */
4740 
4741 static thread_info *
4742 get_bpstat_thread ()
4743 {
4744   if (inferior_ptid == null_ptid || !target_has_execution ())
4745     return NULL;
4746 
4747   thread_info *tp = inferior_thread ();
4748   if (tp->state == THREAD_EXITED || tp->executing ())
4749     return NULL;
4750   return tp;
4751 }
4752 
4753 void
4754 bpstat_do_actions (void)
4755 {
4756   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4757   thread_info *tp;
4758 
4759   /* Do any commands attached to breakpoint we are stopped at.  */
4760   while ((tp = get_bpstat_thread ()) != NULL)
4761     {
4762       /* Since in sync mode, bpstat_do_actions may resume the
4763 	 inferior, and only return when it is stopped at the next
4764 	 breakpoint, we keep doing breakpoint actions until it returns
4765 	 false to indicate the inferior was not resumed.  */
4766       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4767 	break;
4768     }
4769 
4770   cleanup_if_error.release ();
4771 }
4772 
4773 /* Print out the (old or new) value associated with a watchpoint.  */
4774 
4775 static void
4776 watchpoint_value_print (struct value *val, struct ui_file *stream)
4777 {
4778   if (val == NULL)
4779     fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4780   else
4781     {
4782       struct value_print_options opts;
4783       get_user_print_options (&opts);
4784       value_print (val, stream, &opts);
4785     }
4786 }
4787 
4788 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4789    debugging multiple threads.  */
4790 
4791 void
4792 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4793 {
4794   if (uiout->is_mi_like_p ())
4795     return;
4796 
4797   uiout->text ("\n");
4798 
4799   if (show_thread_that_caused_stop ())
4800     {
4801       struct thread_info *thr = inferior_thread ();
4802 
4803       uiout->text ("Thread ");
4804       uiout->field_string ("thread-id", print_thread_id (thr));
4805 
4806       const char *name = thread_name (thr);
4807       if (name != NULL)
4808 	{
4809 	  uiout->text (" \"");
4810 	  uiout->field_string ("name", name);
4811 	  uiout->text ("\"");
4812 	}
4813 
4814       uiout->text (" hit ");
4815     }
4816 }
4817 
4818 /* Generic routine for printing messages indicating why we
4819    stopped.  The behavior of this function depends on the value
4820    'print_it' in the bpstat structure.  Under some circumstances we
4821    may decide not to print anything here and delegate the task to
4822    normal_stop().  */
4823 
4824 static enum print_stop_action
4825 print_bp_stop_message (bpstat *bs)
4826 {
4827   switch (bs->print_it)
4828     {
4829     case print_it_noop:
4830       /* Nothing should be printed for this bpstat entry.  */
4831       return PRINT_UNKNOWN;
4832       break;
4833 
4834     case print_it_done:
4835       /* We still want to print the frame, but we already printed the
4836 	 relevant messages.  */
4837       return PRINT_SRC_AND_LOC;
4838       break;
4839 
4840     case print_it_normal:
4841       {
4842 	struct breakpoint *b = bs->breakpoint_at;
4843 
4844 	/* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4845 	   which has since been deleted.  */
4846 	if (b == NULL)
4847 	  return PRINT_UNKNOWN;
4848 
4849 	/* Normal case.  Call the breakpoint's print_it method.  */
4850 	return b->print_it (bs);
4851       }
4852       break;
4853 
4854     default:
4855       internal_error (_("print_bp_stop_message: unrecognized enum value"));
4856       break;
4857     }
4858 }
4859 
4860 /* See breakpoint.h.  */
4861 
4862 void
4863 print_solib_event (bool is_catchpoint)
4864 {
4865   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4866   bool any_added = !current_program_space->added_solibs.empty ();
4867 
4868   if (!is_catchpoint)
4869     {
4870       if (any_added || any_deleted)
4871 	current_uiout->text (_("Stopped due to shared library event:\n"));
4872       else
4873 	current_uiout->text (_("Stopped due to shared library event (no "
4874 			       "libraries added or removed)\n"));
4875     }
4876 
4877   if (current_uiout->is_mi_like_p ())
4878     current_uiout->field_string ("reason",
4879 				 async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4880 
4881   if (any_deleted)
4882     {
4883       current_uiout->text (_("  Inferior unloaded "));
4884       ui_out_emit_list list_emitter (current_uiout, "removed");
4885       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4886 	{
4887 	  const std::string &name = current_program_space->deleted_solibs[ix];
4888 
4889 	  if (ix > 0)
4890 	    current_uiout->text ("    ");
4891 	  current_uiout->field_string ("library", name);
4892 	  current_uiout->text ("\n");
4893 	}
4894     }
4895 
4896   if (any_added)
4897     {
4898       current_uiout->text (_("  Inferior loaded "));
4899       ui_out_emit_list list_emitter (current_uiout, "added");
4900       bool first = true;
4901       for (so_list *iter : current_program_space->added_solibs)
4902 	{
4903 	  if (!first)
4904 	    current_uiout->text ("    ");
4905 	  first = false;
4906 	  current_uiout->field_string ("library", iter->so_name);
4907 	  current_uiout->text ("\n");
4908 	}
4909     }
4910 }
4911 
4912 /* Print a message indicating what happened.  This is called from
4913    normal_stop().  The input to this routine is the head of the bpstat
4914    list - a list of the eventpoints that caused this stop.  KIND is
4915    the target_waitkind for the stopping event.  This
4916    routine calls the generic print routine for printing a message
4917    about reasons for stopping.  This will print (for example) the
4918    "Breakpoint n," part of the output.  The return value of this
4919    routine is one of:
4920 
4921    PRINT_UNKNOWN: Means we printed nothing.
4922    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4923    code to print the location.  An example is
4924    "Breakpoint 1, " which should be followed by
4925    the location.
4926    PRINT_SRC_ONLY: Means we printed something, but there is no need
4927    to also print the location part of the message.
4928    An example is the catch/throw messages, which
4929    don't require a location appended to the end.
4930    PRINT_NOTHING: We have done some printing and we don't need any
4931    further info to be printed.  */
4932 
4933 enum print_stop_action
4934 bpstat_print (bpstat *bs, target_waitkind kind)
4935 {
4936   enum print_stop_action val;
4937 
4938   /* Maybe another breakpoint in the chain caused us to stop.
4939      (Currently all watchpoints go on the bpstat whether hit or not.
4940      That probably could (should) be changed, provided care is taken
4941      with respect to bpstat_explains_signal).  */
4942   for (; bs; bs = bs->next)
4943     {
4944       val = print_bp_stop_message (bs);
4945       if (val == PRINT_SRC_ONLY
4946 	  || val == PRINT_SRC_AND_LOC
4947 	  || val == PRINT_NOTHING)
4948 	return val;
4949     }
4950 
4951   /* If we had hit a shared library event breakpoint,
4952      print_bp_stop_message would print out this message.  If we hit an
4953      OS-level shared library event, do the same thing.  */
4954   if (kind == TARGET_WAITKIND_LOADED)
4955     {
4956       print_solib_event (false);
4957       return PRINT_NOTHING;
4958     }
4959 
4960   /* We reached the end of the chain, or we got a null BS to start
4961      with and nothing was printed.  */
4962   return PRINT_UNKNOWN;
4963 }
4964 
4965 /* Evaluate the boolean expression EXP and return the result.  */
4966 
4967 static bool
4968 breakpoint_cond_eval (expression *exp)
4969 {
4970   scoped_value_mark mark;
4971   return value_true (evaluate_expression (exp));
4972 }
4973 
4974 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4975 
4976 bpstat::bpstat (struct bp_location *bl, bpstat ***bs_link_pointer)
4977   : next (NULL),
4978     bp_location_at (bp_location_ref_ptr::new_reference (bl)),
4979     breakpoint_at (bl->owner),
4980     commands (NULL),
4981     print (0),
4982     stop (0),
4983     print_it (print_it_normal)
4984 {
4985   **bs_link_pointer = this;
4986   *bs_link_pointer = &next;
4987 }
4988 
4989 bpstat::bpstat ()
4990   : next (NULL),
4991     breakpoint_at (NULL),
4992     commands (NULL),
4993     print (0),
4994     stop (0),
4995     print_it (print_it_normal)
4996 {
4997 }
4998 
4999 /* The target has stopped with waitstatus WS.  Check if any hardware
5000    watchpoints have triggered, according to the target.  */
5001 
5002 int
5003 watchpoints_triggered (const target_waitstatus &ws)
5004 {
5005   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
5006   CORE_ADDR addr;
5007 
5008   if (!stopped_by_watchpoint)
5009     {
5010       /* We were not stopped by a watchpoint.  Mark all watchpoints
5011 	 as not triggered.  */
5012       for (breakpoint *b : all_breakpoints ())
5013 	if (is_hardware_watchpoint (b))
5014 	  {
5015 	    struct watchpoint *w = (struct watchpoint *) b;
5016 
5017 	    w->watchpoint_triggered = watch_triggered_no;
5018 	  }
5019 
5020       return 0;
5021     }
5022 
5023   if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
5024     {
5025       /* We were stopped by a watchpoint, but we don't know where.
5026 	 Mark all watchpoints as unknown.  */
5027       for (breakpoint *b : all_breakpoints ())
5028 	if (is_hardware_watchpoint (b))
5029 	  {
5030 	    struct watchpoint *w = (struct watchpoint *) b;
5031 
5032 	    w->watchpoint_triggered = watch_triggered_unknown;
5033 	  }
5034 
5035       return 1;
5036     }
5037 
5038   /* The target could report the data address.  Mark watchpoints
5039      affected by this data address as triggered, and all others as not
5040      triggered.  */
5041 
5042   for (breakpoint *b : all_breakpoints ())
5043     if (is_hardware_watchpoint (b))
5044       {
5045 	struct watchpoint *w = (struct watchpoint *) b;
5046 
5047 	w->watchpoint_triggered = watch_triggered_no;
5048 	for (bp_location *loc : b->locations ())
5049 	  {
5050 	    if (is_masked_watchpoint (b))
5051 	      {
5052 		CORE_ADDR newaddr = addr & w->hw_wp_mask;
5053 		CORE_ADDR start = loc->address & w->hw_wp_mask;
5054 
5055 		if (newaddr == start)
5056 		  {
5057 		    w->watchpoint_triggered = watch_triggered_yes;
5058 		    break;
5059 		  }
5060 	      }
5061 	    /* Exact match not required.  Within range is sufficient.  */
5062 	    else if (target_watchpoint_addr_within_range
5063 		       (current_inferior ()->top_target (), addr, loc->address,
5064 			loc->length))
5065 	      {
5066 		w->watchpoint_triggered = watch_triggered_yes;
5067 		break;
5068 	      }
5069 	  }
5070       }
5071 
5072   return 1;
5073 }
5074 
5075 /* Possible return values for watchpoint_check.  */
5076 enum wp_check_result
5077   {
5078     /* The watchpoint has been deleted.  */
5079     WP_DELETED = 1,
5080 
5081     /* The value has changed.  */
5082     WP_VALUE_CHANGED = 2,
5083 
5084     /* The value has not changed.  */
5085     WP_VALUE_NOT_CHANGED = 3,
5086 
5087     /* Ignore this watchpoint, no matter if the value changed or not.  */
5088     WP_IGNORE = 4,
5089   };
5090 
5091 #define BP_TEMPFLAG 1
5092 #define BP_HARDWAREFLAG 2
5093 
5094 /* Evaluate watchpoint condition expression and check if its value
5095    changed.  */
5096 
5097 static wp_check_result
5098 watchpoint_check (bpstat *bs)
5099 {
5100   struct watchpoint *b;
5101   frame_info_ptr fr;
5102   bool within_current_scope;
5103 
5104   /* BS is built from an existing struct breakpoint.  */
5105   gdb_assert (bs->breakpoint_at != NULL);
5106   b = (struct watchpoint *) bs->breakpoint_at;
5107 
5108   /* If this is a local watchpoint, we only want to check if the
5109      watchpoint frame is in scope if the current thread is the thread
5110      that was used to create the watchpoint.  */
5111   if (!watchpoint_in_thread_scope (b))
5112     return WP_IGNORE;
5113 
5114   if (b->exp_valid_block == NULL)
5115     within_current_scope = true;
5116   else
5117     {
5118       frame_info_ptr frame = get_current_frame ();
5119       struct gdbarch *frame_arch = get_frame_arch (frame);
5120       CORE_ADDR frame_pc = get_frame_pc (frame);
5121 
5122       /* stack_frame_destroyed_p() returns a non-zero value if we're
5123 	 still in the function but the stack frame has already been
5124 	 invalidated.  Since we can't rely on the values of local
5125 	 variables after the stack has been destroyed, we are treating
5126 	 the watchpoint in that state as `not changed' without further
5127 	 checking.  Don't mark watchpoints as changed if the current
5128 	 frame is in an epilogue - even if they are in some other
5129 	 frame, our view of the stack is likely to be wrong and
5130 	 frame_find_by_id could error out.  */
5131       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5132 	return WP_IGNORE;
5133 
5134       fr = frame_find_by_id (b->watchpoint_frame);
5135       within_current_scope = (fr != NULL);
5136 
5137       /* If we've gotten confused in the unwinder, we might have
5138 	 returned a frame that can't describe this variable.  */
5139       if (within_current_scope)
5140 	{
5141 	  struct symbol *function;
5142 
5143 	  function = get_frame_function (fr);
5144 	  if (function == NULL
5145 	      || !contained_in (b->exp_valid_block, function->value_block ()))
5146 	    within_current_scope = false;
5147 	}
5148 
5149       if (within_current_scope)
5150 	/* If we end up stopping, the current frame will get selected
5151 	   in normal_stop.  So this call to select_frame won't affect
5152 	   the user.  */
5153 	select_frame (fr);
5154     }
5155 
5156   if (within_current_scope)
5157     {
5158       /* We use value_{,free_to_}mark because it could be a *long*
5159 	 time before we return to the command level and call
5160 	 free_all_values.  We can't call free_all_values because we
5161 	 might be in the middle of evaluating a function call.  */
5162 
5163       struct value *mark;
5164       struct value *new_val;
5165 
5166       if (is_masked_watchpoint (b))
5167 	/* Since we don't know the exact trigger address (from
5168 	   stopped_data_address), just tell the user we've triggered
5169 	   a mask watchpoint.  */
5170 	return WP_VALUE_CHANGED;
5171 
5172       mark = value_mark ();
5173       fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
5174 			  NULL, NULL, false);
5175 
5176       if (b->val_bitsize != 0)
5177 	new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5178 
5179       /* We use value_equal_contents instead of value_equal because
5180 	 the latter coerces an array to a pointer, thus comparing just
5181 	 the address of the array instead of its contents.  This is
5182 	 not what we want.  */
5183       if ((b->val != NULL) != (new_val != NULL)
5184 	  || (b->val != NULL && !value_equal_contents (b->val.get (),
5185 						       new_val)))
5186 	{
5187 	  bs->old_val = b->val;
5188 	  b->val = release_value (new_val);
5189 	  b->val_valid = true;
5190 	  if (new_val != NULL)
5191 	    value_free_to_mark (mark);
5192 	  return WP_VALUE_CHANGED;
5193 	}
5194       else
5195 	{
5196 	  /* Nothing changed.  */
5197 	  value_free_to_mark (mark);
5198 	  return WP_VALUE_NOT_CHANGED;
5199 	}
5200     }
5201   else
5202     {
5203       /* This seems like the only logical thing to do because
5204 	 if we temporarily ignored the watchpoint, then when
5205 	 we reenter the block in which it is valid it contains
5206 	 garbage (in the case of a function, it may have two
5207 	 garbage values, one before and one after the prologue).
5208 	 So we can't even detect the first assignment to it and
5209 	 watch after that (since the garbage may or may not equal
5210 	 the first value assigned).  */
5211       /* We print all the stop information in
5212 	 breakpointprint_it, but in this case, by the time we
5213 	 call breakpoint->print_it this bp will be deleted
5214 	 already.  So we have no choice but print the information
5215 	 here.  */
5216 
5217       SWITCH_THRU_ALL_UIS ()
5218 	{
5219 	  struct ui_out *uiout = current_uiout;
5220 
5221 	  if (uiout->is_mi_like_p ())
5222 	    uiout->field_string
5223 	      ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5224 	  uiout->message ("\nWatchpoint %pF deleted because the program has "
5225 			  "left the block in\n"
5226 			  "which its expression is valid.\n",
5227 			  signed_field ("wpnum", b->number));
5228 	}
5229 
5230       /* Make sure the watchpoint's commands aren't executed.  */
5231       b->commands = NULL;
5232       watchpoint_del_at_next_stop (b);
5233 
5234       return WP_DELETED;
5235     }
5236 }
5237 
5238 /* Return true if it looks like target has stopped due to hitting
5239    breakpoint location BL.  This function does not check if we should
5240    stop, only if BL explains the stop.  */
5241 
5242 static bool
5243 bpstat_check_location (const struct bp_location *bl,
5244 		       const address_space *aspace, CORE_ADDR bp_addr,
5245 		       const target_waitstatus &ws)
5246 {
5247   struct breakpoint *b = bl->owner;
5248 
5249   /* BL is from an existing breakpoint.  */
5250   gdb_assert (b != NULL);
5251 
5252   return b->breakpoint_hit (bl, aspace, bp_addr, ws);
5253 }
5254 
5255 /* Determine if the watched values have actually changed, and we
5256    should stop.  If not, set BS->stop to 0.  */
5257 
5258 static void
5259 bpstat_check_watchpoint (bpstat *bs)
5260 {
5261   const struct bp_location *bl;
5262   struct watchpoint *b;
5263 
5264   /* BS is built for existing struct breakpoint.  */
5265   bl = bs->bp_location_at.get ();
5266   gdb_assert (bl != NULL);
5267   b = (struct watchpoint *) bs->breakpoint_at;
5268   gdb_assert (b != NULL);
5269 
5270     {
5271       bool must_check_value = false;
5272 
5273       if (b->type == bp_watchpoint)
5274 	/* For a software watchpoint, we must always check the
5275 	   watched value.  */
5276 	must_check_value = true;
5277       else if (b->watchpoint_triggered == watch_triggered_yes)
5278 	/* We have a hardware watchpoint (read, write, or access)
5279 	   and the target earlier reported an address watched by
5280 	   this watchpoint.  */
5281 	must_check_value = true;
5282       else if (b->watchpoint_triggered == watch_triggered_unknown
5283 	       && b->type == bp_hardware_watchpoint)
5284 	/* We were stopped by a hardware watchpoint, but the target could
5285 	   not report the data address.  We must check the watchpoint's
5286 	   value.  Access and read watchpoints are out of luck; without
5287 	   a data address, we can't figure it out.  */
5288 	must_check_value = true;
5289 
5290       if (must_check_value)
5291 	{
5292 	  wp_check_result e;
5293 
5294 	  try
5295 	    {
5296 	      e = watchpoint_check (bs);
5297 	    }
5298 	  catch (const gdb_exception &ex)
5299 	    {
5300 	      exception_fprintf (gdb_stderr, ex,
5301 				 "Error evaluating expression "
5302 				 "for watchpoint %d\n",
5303 				 b->number);
5304 
5305 	      SWITCH_THRU_ALL_UIS ()
5306 		{
5307 		  gdb_printf (_("Watchpoint %d deleted.\n"),
5308 			      b->number);
5309 		}
5310 	      watchpoint_del_at_next_stop (b);
5311 	      e = WP_DELETED;
5312 	    }
5313 
5314 	  switch (e)
5315 	    {
5316 	    case WP_DELETED:
5317 	      /* We've already printed what needs to be printed.  */
5318 	      bs->print_it = print_it_done;
5319 	      /* Stop.  */
5320 	      break;
5321 	    case WP_IGNORE:
5322 	      bs->print_it = print_it_noop;
5323 	      bs->stop = 0;
5324 	      break;
5325 	    case WP_VALUE_CHANGED:
5326 	      if (b->type == bp_read_watchpoint)
5327 		{
5328 		  /* There are two cases to consider here:
5329 
5330 		     1. We're watching the triggered memory for reads.
5331 		     In that case, trust the target, and always report
5332 		     the watchpoint hit to the user.  Even though
5333 		     reads don't cause value changes, the value may
5334 		     have changed since the last time it was read, and
5335 		     since we're not trapping writes, we will not see
5336 		     those, and as such we should ignore our notion of
5337 		     old value.
5338 
5339 		     2. We're watching the triggered memory for both
5340 		     reads and writes.  There are two ways this may
5341 		     happen:
5342 
5343 		     2.1. This is a target that can't break on data
5344 		     reads only, but can break on accesses (reads or
5345 		     writes), such as e.g., x86.  We detect this case
5346 		     at the time we try to insert read watchpoints.
5347 
5348 		     2.2. Otherwise, the target supports read
5349 		     watchpoints, but, the user set an access or write
5350 		     watchpoint watching the same memory as this read
5351 		     watchpoint.
5352 
5353 		     If we're watching memory writes as well as reads,
5354 		     ignore watchpoint hits when we find that the
5355 		     value hasn't changed, as reads don't cause
5356 		     changes.  This still gives false positives when
5357 		     the program writes the same value to memory as
5358 		     what there was already in memory (we will confuse
5359 		     it for a read), but it's much better than
5360 		     nothing.  */
5361 
5362 		  int other_write_watchpoint = 0;
5363 
5364 		  if (bl->watchpoint_type == hw_read)
5365 		    {
5366 		      for (breakpoint *other_b : all_breakpoints ())
5367 			if (other_b->type == bp_hardware_watchpoint
5368 			    || other_b->type == bp_access_watchpoint)
5369 			  {
5370 			    struct watchpoint *other_w =
5371 			      (struct watchpoint *) other_b;
5372 
5373 			    if (other_w->watchpoint_triggered
5374 				== watch_triggered_yes)
5375 			      {
5376 				other_write_watchpoint = 1;
5377 				break;
5378 			      }
5379 			  }
5380 		    }
5381 
5382 		  if (other_write_watchpoint
5383 		      || bl->watchpoint_type == hw_access)
5384 		    {
5385 		      /* We're watching the same memory for writes,
5386 			 and the value changed since the last time we
5387 			 updated it, so this trap must be for a write.
5388 			 Ignore it.  */
5389 		      bs->print_it = print_it_noop;
5390 		      bs->stop = 0;
5391 		    }
5392 		}
5393 	      break;
5394 	    case WP_VALUE_NOT_CHANGED:
5395 	      if (b->type == bp_hardware_watchpoint
5396 		  || b->type == bp_watchpoint)
5397 		{
5398 		  /* Don't stop: write watchpoints shouldn't fire if
5399 		     the value hasn't changed.  */
5400 		  bs->print_it = print_it_noop;
5401 		  bs->stop = 0;
5402 		}
5403 	      /* Stop.  */
5404 	      break;
5405 	    default:
5406 	      /* Can't happen.  */
5407 	      break;
5408 	    }
5409 	}
5410       else	/* !must_check_value */
5411 	{
5412 	  /* This is a case where some watchpoint(s) triggered, but
5413 	     not at the address of this watchpoint, or else no
5414 	     watchpoint triggered after all.  So don't print
5415 	     anything for this watchpoint.  */
5416 	  bs->print_it = print_it_noop;
5417 	  bs->stop = 0;
5418 	}
5419     }
5420 }
5421 
5422 /* For breakpoints that are currently marked as telling gdb to stop,
5423    check conditions (condition proper, frame, thread and ignore count)
5424    of breakpoint referred to by BS.  If we should not stop for this
5425    breakpoint, set BS->stop to 0.  */
5426 
5427 static void
5428 bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
5429 {
5430   INFRUN_SCOPED_DEBUG_ENTER_EXIT;
5431 
5432   const struct bp_location *bl;
5433   struct breakpoint *b;
5434   /* Assume stop.  */
5435   bool condition_result = true;
5436   struct expression *cond;
5437 
5438   gdb_assert (bs->stop);
5439 
5440   /* BS is built for existing struct breakpoint.  */
5441   bl = bs->bp_location_at.get ();
5442   gdb_assert (bl != NULL);
5443   b = bs->breakpoint_at;
5444   gdb_assert (b != NULL);
5445 
5446   infrun_debug_printf ("thread = %s, breakpoint %d.%d",
5447 		       thread->ptid.to_string ().c_str (),
5448 		       b->number, find_loc_num_by_location (bl));
5449 
5450   /* Even if the target evaluated the condition on its end and notified GDB, we
5451      need to do so again since GDB does not know if we stopped due to a
5452      breakpoint or a single step breakpoint.  */
5453 
5454   if (frame_id_p (b->frame_id)
5455       && b->frame_id != get_stack_frame_id (get_current_frame ()))
5456     {
5457       infrun_debug_printf ("incorrect frame %s not %s, not stopping",
5458 			   get_stack_frame_id (get_current_frame ()).to_string ().c_str (),
5459 			   b->frame_id.to_string ().c_str ());
5460       bs->stop = 0;
5461       return;
5462     }
5463 
5464   /* If this is a thread/task-specific breakpoint, don't waste cpu
5465      evaluating the condition if this isn't the specified
5466      thread/task.  */
5467   if ((b->thread != -1 && b->thread != thread->global_num)
5468       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5469     {
5470       infrun_debug_printf ("incorrect thread or task, not stopping");
5471       bs->stop = 0;
5472       return;
5473     }
5474 
5475   /* Evaluate extension language breakpoints that have a "stop" method
5476      implemented.  */
5477   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5478 
5479   if (is_watchpoint (b))
5480     {
5481       struct watchpoint *w = (struct watchpoint *) b;
5482 
5483       cond = w->cond_exp.get ();
5484     }
5485   else
5486     cond = bl->cond.get ();
5487 
5488   if (cond != nullptr && b->disposition != disp_del_at_next_stop)
5489     {
5490       bool within_current_scope = true;
5491       struct watchpoint * w;
5492 
5493       /* We use scoped_value_mark because it could be a long time
5494 	 before we return to the command level and call
5495 	 free_all_values.  We can't call free_all_values because we
5496 	 might be in the middle of evaluating a function call.  */
5497       scoped_value_mark mark;
5498 
5499       if (is_watchpoint (b))
5500 	w = (struct watchpoint *) b;
5501       else
5502 	w = NULL;
5503 
5504       /* Need to select the frame, with all that implies so that
5505 	 the conditions will have the right context.  Because we
5506 	 use the frame, we will not see an inlined function's
5507 	 variables when we arrive at a breakpoint at the start
5508 	 of the inlined function; the current frame will be the
5509 	 call site.  */
5510       if (w == NULL || w->cond_exp_valid_block == NULL)
5511 	select_frame (get_current_frame ());
5512       else
5513 	{
5514 	  frame_info_ptr frame;
5515 
5516 	  /* For local watchpoint expressions, which particular
5517 	     instance of a local is being watched matters, so we
5518 	     keep track of the frame to evaluate the expression
5519 	     in.  To evaluate the condition however, it doesn't
5520 	     really matter which instantiation of the function
5521 	     where the condition makes sense triggers the
5522 	     watchpoint.  This allows an expression like "watch
5523 	     global if q > 10" set in `func', catch writes to
5524 	     global on all threads that call `func', or catch
5525 	     writes on all recursive calls of `func' by a single
5526 	     thread.  We simply always evaluate the condition in
5527 	     the innermost frame that's executing where it makes
5528 	     sense to evaluate the condition.  It seems
5529 	     intuitive.  */
5530 	  frame = block_innermost_frame (w->cond_exp_valid_block);
5531 	  if (frame != NULL)
5532 	    select_frame (frame);
5533 	  else
5534 	    within_current_scope = false;
5535 	}
5536       if (within_current_scope)
5537 	{
5538 	  try
5539 	    {
5540 	      condition_result = breakpoint_cond_eval (cond);
5541 	    }
5542 	  catch (const gdb_exception &ex)
5543 	    {
5544 	      exception_fprintf (gdb_stderr, ex,
5545 				 "Error in testing breakpoint condition:\n");
5546 	    }
5547 	}
5548       else
5549 	{
5550 	  warning (_("Watchpoint condition cannot be tested "
5551 		     "in the current scope"));
5552 	  /* If we failed to set the right context for this
5553 	     watchpoint, unconditionally report it.  */
5554 	}
5555       /* FIXME-someday, should give breakpoint #.  */
5556     }
5557 
5558   if (cond != nullptr && !condition_result)
5559     {
5560       infrun_debug_printf ("condition_result = false, not stopping");
5561       bs->stop = 0;
5562       return;
5563     }
5564   else if (b->ignore_count > 0)
5565     {
5566       infrun_debug_printf ("ignore count %d, not stopping",
5567 			   b->ignore_count);
5568       b->ignore_count--;
5569       bs->stop = 0;
5570       /* Increase the hit count even though we don't stop.  */
5571       ++(b->hit_count);
5572       gdb::observers::breakpoint_modified.notify (b);
5573       return;
5574     }
5575 
5576   if (bs->stop)
5577     infrun_debug_printf ("stopping at this breakpoint");
5578   else
5579     infrun_debug_printf ("not stopping at this breakpoint");
5580 }
5581 
5582 /* Returns true if we need to track moribund locations of LOC's type
5583    on the current target.  */
5584 
5585 static bool
5586 need_moribund_for_location_type (const struct bp_location *loc)
5587 {
5588   return ((loc->loc_type == bp_loc_software_breakpoint
5589 	   && !target_supports_stopped_by_sw_breakpoint ())
5590 	  || (loc->loc_type == bp_loc_hardware_breakpoint
5591 	      && !target_supports_stopped_by_hw_breakpoint ()));
5592 }
5593 
5594 /* See breakpoint.h.  */
5595 
5596 bpstat *
5597 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5598 		    const target_waitstatus &ws)
5599 {
5600   bpstat *bs_head = nullptr, **bs_link = &bs_head;
5601 
5602   for (breakpoint *b : all_breakpoints ())
5603     {
5604       if (!breakpoint_enabled (b))
5605 	continue;
5606 
5607       for (bp_location *bl : b->locations ())
5608 	{
5609 	  /* For hardware watchpoints, we look only at the first
5610 	     location.  The watchpoint_check function will work on the
5611 	     entire expression, not the individual locations.  For
5612 	     read watchpoints, the watchpoints_triggered function has
5613 	     checked all locations already.  */
5614 	  if (b->type == bp_hardware_watchpoint && bl != b->loc)
5615 	    break;
5616 
5617 	  if (!bl->enabled || bl->disabled_by_cond || bl->shlib_disabled)
5618 	    continue;
5619 
5620 	  if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5621 	    continue;
5622 
5623 	  /* Come here if it's a watchpoint, or if the break address
5624 	     matches.  */
5625 
5626 	  bpstat *bs = new bpstat (bl, &bs_link);	/* Alloc a bpstat to
5627 							   explain stop.  */
5628 
5629 	  /* Assume we stop.  Should we find a watchpoint that is not
5630 	     actually triggered, or if the condition of the breakpoint
5631 	     evaluates as false, we'll reset 'stop' to 0.  */
5632 	  bs->stop = 1;
5633 	  bs->print = 1;
5634 
5635 	  /* If this is a scope breakpoint, mark the associated
5636 	     watchpoint as triggered so that we will handle the
5637 	     out-of-scope event.  We'll get to the watchpoint next
5638 	     iteration.  */
5639 	  if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5640 	    {
5641 	      struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5642 
5643 	      w->watchpoint_triggered = watch_triggered_yes;
5644 	    }
5645 	}
5646     }
5647 
5648   /* Check if a moribund breakpoint explains the stop.  */
5649   if (!target_supports_stopped_by_sw_breakpoint ()
5650       || !target_supports_stopped_by_hw_breakpoint ())
5651     {
5652       for (bp_location *loc : moribund_locations)
5653 	{
5654 	  if (breakpoint_location_address_match (loc, aspace, bp_addr)
5655 	      && need_moribund_for_location_type (loc))
5656 	    {
5657 	      bpstat *bs = new bpstat (loc, &bs_link);
5658 	      /* For hits of moribund locations, we should just proceed.  */
5659 	      bs->stop = 0;
5660 	      bs->print = 0;
5661 	      bs->print_it = print_it_noop;
5662 	    }
5663 	}
5664     }
5665 
5666   return bs_head;
5667 }
5668 
5669 /* See breakpoint.h.  */
5670 
5671 bpstat *
5672 bpstat_stop_status (const address_space *aspace,
5673 		    CORE_ADDR bp_addr, thread_info *thread,
5674 		    const target_waitstatus &ws,
5675 		    bpstat *stop_chain)
5676 {
5677   struct breakpoint *b = NULL;
5678   /* First item of allocated bpstat's.  */
5679   bpstat *bs_head = stop_chain;
5680   bpstat *bs;
5681   int need_remove_insert;
5682   int removed_any;
5683 
5684   /* First, build the bpstat chain with locations that explain a
5685      target stop, while being careful to not set the target running,
5686      as that may invalidate locations (in particular watchpoint
5687      locations are recreated).  Resuming will happen here with
5688      breakpoint conditions or watchpoint expressions that include
5689      inferior function calls.  */
5690   if (bs_head == NULL)
5691     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5692 
5693   /* A bit of special processing for shlib breakpoints.  We need to
5694      process solib loading here, so that the lists of loaded and
5695      unloaded libraries are correct before we handle "catch load" and
5696      "catch unload".  */
5697   for (bs = bs_head; bs != NULL; bs = bs->next)
5698     {
5699       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5700 	{
5701 	  handle_solib_event ();
5702 	  break;
5703 	}
5704     }
5705 
5706   /* Now go through the locations that caused the target to stop, and
5707      check whether we're interested in reporting this stop to higher
5708      layers, or whether we should resume the target transparently.  */
5709 
5710   removed_any = 0;
5711 
5712   for (bs = bs_head; bs != NULL; bs = bs->next)
5713     {
5714       if (!bs->stop)
5715 	continue;
5716 
5717       b = bs->breakpoint_at;
5718       b->check_status (bs);
5719       if (bs->stop)
5720 	{
5721 	  bpstat_check_breakpoint_conditions (bs, thread);
5722 
5723 	  if (bs->stop)
5724 	    {
5725 	      ++(b->hit_count);
5726 
5727 	      /* We will stop here.  */
5728 	      if (b->disposition == disp_disable)
5729 		{
5730 		  --(b->enable_count);
5731 		  if (b->enable_count <= 0)
5732 		    b->enable_state = bp_disabled;
5733 		  removed_any = 1;
5734 		}
5735 	      gdb::observers::breakpoint_modified.notify (b);
5736 	      if (b->silent)
5737 		bs->print = 0;
5738 	      bs->commands = b->commands;
5739 	      if (command_line_is_silent (bs->commands
5740 					  ? bs->commands.get () : NULL))
5741 		bs->print = 0;
5742 
5743 	      b->after_condition_true (bs);
5744 	    }
5745 
5746 	}
5747 
5748       /* Print nothing for this entry if we don't stop or don't
5749 	 print.  */
5750       if (!bs->stop || !bs->print)
5751 	bs->print_it = print_it_noop;
5752     }
5753 
5754   /* If we aren't stopping, the value of some hardware watchpoint may
5755      not have changed, but the intermediate memory locations we are
5756      watching may have.  Don't bother if we're stopping; this will get
5757      done later.  */
5758   need_remove_insert = 0;
5759   if (! bpstat_causes_stop (bs_head))
5760     for (bs = bs_head; bs != NULL; bs = bs->next)
5761       if (!bs->stop
5762 	  && bs->breakpoint_at
5763 	  && is_hardware_watchpoint (bs->breakpoint_at))
5764 	{
5765 	  struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5766 
5767 	  update_watchpoint (w, false /* don't reparse.  */);
5768 	  need_remove_insert = 1;
5769 	}
5770 
5771   if (need_remove_insert)
5772     update_global_location_list (UGLL_MAY_INSERT);
5773   else if (removed_any)
5774     update_global_location_list (UGLL_DONT_INSERT);
5775 
5776   return bs_head;
5777 }
5778 
5779 /* See breakpoint.h.  */
5780 
5781 bpstat *
5782 bpstat_stop_status_nowatch (const address_space *aspace, CORE_ADDR bp_addr,
5783 			    thread_info *thread, const target_waitstatus &ws)
5784 {
5785   gdb_assert (!target_stopped_by_watchpoint ());
5786 
5787   /* Clear all watchpoints' 'watchpoint_triggered' value from a
5788      previous stop to avoid confusing bpstat_stop_status.  */
5789   watchpoints_triggered (ws);
5790 
5791   return bpstat_stop_status (aspace, bp_addr, thread, ws);
5792 }
5793 
5794 static void
5795 handle_jit_event (CORE_ADDR address)
5796 {
5797   struct gdbarch *gdbarch;
5798 
5799   infrun_debug_printf ("handling bp_jit_event");
5800 
5801   /* Switch terminal for any messages produced by
5802      breakpoint_re_set.  */
5803   target_terminal::ours_for_output ();
5804 
5805   gdbarch = get_frame_arch (get_current_frame ());
5806   /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5807      thus it is expected that its objectfile can be found through
5808      minimal symbol lookup.  If it doesn't work (and assert fails), it
5809      most likely means that `jit_breakpoint_re_set` was changes and this
5810      function needs to be updated too.  */
5811   bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5812   gdb_assert (jit_bp_sym.objfile != nullptr);
5813   objfile *objfile = jit_bp_sym.objfile;
5814   if (objfile->separate_debug_objfile_backlink)
5815     objfile = objfile->separate_debug_objfile_backlink;
5816   jit_event_handler (gdbarch, objfile);
5817 
5818   target_terminal::inferior ();
5819 }
5820 
5821 /* Prepare WHAT final decision for infrun.  */
5822 
5823 /* Decide what infrun needs to do with this bpstat.  */
5824 
5825 struct bpstat_what
5826 bpstat_what (bpstat *bs_head)
5827 {
5828   struct bpstat_what retval;
5829   bpstat *bs;
5830 
5831   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5832   retval.call_dummy = STOP_NONE;
5833   retval.is_longjmp = false;
5834 
5835   for (bs = bs_head; bs != NULL; bs = bs->next)
5836     {
5837       /* Extract this BS's action.  After processing each BS, we check
5838 	 if its action overrides all we've seem so far.  */
5839       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5840       enum bptype bptype;
5841 
5842       if (bs->breakpoint_at == NULL)
5843 	{
5844 	  /* I suspect this can happen if it was a momentary
5845 	     breakpoint which has since been deleted.  */
5846 	  bptype = bp_none;
5847 	}
5848       else
5849 	bptype = bs->breakpoint_at->type;
5850 
5851       switch (bptype)
5852 	{
5853 	case bp_none:
5854 	  break;
5855 	case bp_breakpoint:
5856 	case bp_hardware_breakpoint:
5857 	case bp_single_step:
5858 	case bp_until:
5859 	case bp_finish:
5860 	case bp_shlib_event:
5861 	  if (bs->stop)
5862 	    {
5863 	      if (bs->print)
5864 		this_action = BPSTAT_WHAT_STOP_NOISY;
5865 	      else
5866 		this_action = BPSTAT_WHAT_STOP_SILENT;
5867 	    }
5868 	  else
5869 	    this_action = BPSTAT_WHAT_SINGLE;
5870 	  break;
5871 	case bp_watchpoint:
5872 	case bp_hardware_watchpoint:
5873 	case bp_read_watchpoint:
5874 	case bp_access_watchpoint:
5875 	  if (bs->stop)
5876 	    {
5877 	      if (bs->print)
5878 		this_action = BPSTAT_WHAT_STOP_NOISY;
5879 	      else
5880 		this_action = BPSTAT_WHAT_STOP_SILENT;
5881 	    }
5882 	  else
5883 	    {
5884 	      /* There was a watchpoint, but we're not stopping.
5885 		 This requires no further action.  */
5886 	    }
5887 	  break;
5888 	case bp_longjmp:
5889 	case bp_longjmp_call_dummy:
5890 	case bp_exception:
5891 	  if (bs->stop)
5892 	    {
5893 	      this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5894 	      retval.is_longjmp = bptype != bp_exception;
5895 	    }
5896 	  else
5897 	    this_action = BPSTAT_WHAT_SINGLE;
5898 	  break;
5899 	case bp_longjmp_resume:
5900 	case bp_exception_resume:
5901 	  if (bs->stop)
5902 	    {
5903 	      this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5904 	      retval.is_longjmp = bptype == bp_longjmp_resume;
5905 	    }
5906 	  else
5907 	    this_action = BPSTAT_WHAT_SINGLE;
5908 	  break;
5909 	case bp_step_resume:
5910 	  if (bs->stop)
5911 	    this_action = BPSTAT_WHAT_STEP_RESUME;
5912 	  else
5913 	    {
5914 	      /* It is for the wrong frame.  */
5915 	      this_action = BPSTAT_WHAT_SINGLE;
5916 	    }
5917 	  break;
5918 	case bp_hp_step_resume:
5919 	  if (bs->stop)
5920 	    this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5921 	  else
5922 	    {
5923 	      /* It is for the wrong frame.  */
5924 	      this_action = BPSTAT_WHAT_SINGLE;
5925 	    }
5926 	  break;
5927 	case bp_watchpoint_scope:
5928 	case bp_thread_event:
5929 	case bp_overlay_event:
5930 	case bp_longjmp_master:
5931 	case bp_std_terminate_master:
5932 	case bp_exception_master:
5933 	  this_action = BPSTAT_WHAT_SINGLE;
5934 	  break;
5935 	case bp_catchpoint:
5936 	  if (bs->stop)
5937 	    {
5938 	      if (bs->print)
5939 		this_action = BPSTAT_WHAT_STOP_NOISY;
5940 	      else
5941 		this_action = BPSTAT_WHAT_STOP_SILENT;
5942 	    }
5943 	  else
5944 	    {
5945 	      /* Some catchpoints are implemented with breakpoints.
5946 		 For those, we need to step over the breakpoint.  */
5947 	      if (bs->bp_location_at->loc_type == bp_loc_software_breakpoint
5948 		  || bs->bp_location_at->loc_type == bp_loc_hardware_breakpoint)
5949 		this_action = BPSTAT_WHAT_SINGLE;
5950 	    }
5951 	  break;
5952 	case bp_jit_event:
5953 	  this_action = BPSTAT_WHAT_SINGLE;
5954 	  break;
5955 	case bp_call_dummy:
5956 	  /* Make sure the action is stop (silent or noisy),
5957 	     so infrun.c pops the dummy frame.  */
5958 	  retval.call_dummy = STOP_STACK_DUMMY;
5959 	  this_action = BPSTAT_WHAT_STOP_SILENT;
5960 	  break;
5961 	case bp_std_terminate:
5962 	  /* Make sure the action is stop (silent or noisy),
5963 	     so infrun.c pops the dummy frame.  */
5964 	  retval.call_dummy = STOP_STD_TERMINATE;
5965 	  this_action = BPSTAT_WHAT_STOP_SILENT;
5966 	  break;
5967 	case bp_tracepoint:
5968 	case bp_fast_tracepoint:
5969 	case bp_static_tracepoint:
5970 	case bp_static_marker_tracepoint:
5971 	  /* Tracepoint hits should not be reported back to GDB, and
5972 	     if one got through somehow, it should have been filtered
5973 	     out already.  */
5974 	  internal_error (_("bpstat_what: tracepoint encountered"));
5975 	  break;
5976 	case bp_gnu_ifunc_resolver:
5977 	  /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5978 	  this_action = BPSTAT_WHAT_SINGLE;
5979 	  break;
5980 	case bp_gnu_ifunc_resolver_return:
5981 	  /* The breakpoint will be removed, execution will restart from the
5982 	     PC of the former breakpoint.  */
5983 	  this_action = BPSTAT_WHAT_KEEP_CHECKING;
5984 	  break;
5985 
5986 	case bp_dprintf:
5987 	  if (bs->stop)
5988 	    this_action = BPSTAT_WHAT_STOP_SILENT;
5989 	  else
5990 	    this_action = BPSTAT_WHAT_SINGLE;
5991 	  break;
5992 
5993 	default:
5994 	  internal_error (_("bpstat_what: unhandled bptype %d"), (int) bptype);
5995 	}
5996 
5997       retval.main_action = std::max (retval.main_action, this_action);
5998     }
5999 
6000   return retval;
6001 }
6002 
6003 void
6004 bpstat_run_callbacks (bpstat *bs_head)
6005 {
6006   bpstat *bs;
6007 
6008   for (bs = bs_head; bs != NULL; bs = bs->next)
6009     {
6010       struct breakpoint *b = bs->breakpoint_at;
6011 
6012       if (b == NULL)
6013 	continue;
6014       switch (b->type)
6015 	{
6016 	case bp_jit_event:
6017 	  handle_jit_event (bs->bp_location_at->address);
6018 	  break;
6019 	case bp_gnu_ifunc_resolver:
6020 	  gnu_ifunc_resolver_stop ((code_breakpoint *) b);
6021 	  break;
6022 	case bp_gnu_ifunc_resolver_return:
6023 	  gnu_ifunc_resolver_return_stop ((code_breakpoint *) b);
6024 	  break;
6025 	}
6026     }
6027 }
6028 
6029 /* See breakpoint.h.  */
6030 
6031 bool
6032 bpstat_should_step ()
6033 {
6034   for (breakpoint *b : all_breakpoints ())
6035     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
6036       return true;
6037 
6038   return false;
6039 }
6040 
6041 /* See breakpoint.h.  */
6042 
6043 bool
6044 bpstat_causes_stop (bpstat *bs)
6045 {
6046   for (; bs != NULL; bs = bs->next)
6047     if (bs->stop)
6048       return true;
6049 
6050   return false;
6051 }
6052 
6053 
6054 
6055 /* Compute a number of spaces suitable to indent the next line
6056    so it starts at the position corresponding to the table column
6057    named COL_NAME in the currently active table of UIOUT.  */
6058 
6059 static int
6060 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6061 {
6062   int i, total_width, width, align;
6063   const char *text;
6064 
6065   total_width = 0;
6066   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
6067     {
6068       if (strcmp (text, col_name) == 0)
6069 	return total_width;
6070 
6071       total_width += width + 1;
6072     }
6073 
6074   return 0;
6075 }
6076 
6077 /* Determine if the locations of this breakpoint will have their conditions
6078    evaluated by the target, host or a mix of both.  Returns the following:
6079 
6080     "host": Host evals condition.
6081     "host or target": Host or Target evals condition.
6082     "target": Target evals condition.
6083 */
6084 
6085 static const char *
6086 bp_condition_evaluator (const breakpoint *b)
6087 {
6088   char host_evals = 0;
6089   char target_evals = 0;
6090 
6091   if (!b)
6092     return NULL;
6093 
6094   if (!is_breakpoint (b))
6095     return NULL;
6096 
6097   if (gdb_evaluates_breakpoint_condition_p ()
6098       || !target_supports_evaluation_of_breakpoint_conditions ())
6099     return condition_evaluation_host;
6100 
6101   for (bp_location *bl : b->locations ())
6102     {
6103       if (bl->cond_bytecode)
6104 	target_evals++;
6105       else
6106 	host_evals++;
6107     }
6108 
6109   if (host_evals && target_evals)
6110     return condition_evaluation_both;
6111   else if (target_evals)
6112     return condition_evaluation_target;
6113   else
6114     return condition_evaluation_host;
6115 }
6116 
6117 /* Determine the breakpoint location's condition evaluator.  This is
6118    similar to bp_condition_evaluator, but for locations.  */
6119 
6120 static const char *
6121 bp_location_condition_evaluator (const struct bp_location *bl)
6122 {
6123   if (bl && !is_breakpoint (bl->owner))
6124     return NULL;
6125 
6126   if (gdb_evaluates_breakpoint_condition_p ()
6127       || !target_supports_evaluation_of_breakpoint_conditions ())
6128     return condition_evaluation_host;
6129 
6130   if (bl && bl->cond_bytecode)
6131     return condition_evaluation_target;
6132   else
6133     return condition_evaluation_host;
6134 }
6135 
6136 /* Print the LOC location out of the list of B->LOC locations.  */
6137 
6138 static void
6139 print_breakpoint_location (const breakpoint *b,
6140 			   struct bp_location *loc)
6141 {
6142   struct ui_out *uiout = current_uiout;
6143 
6144   scoped_restore_current_program_space restore_pspace;
6145 
6146   if (loc != NULL && loc->shlib_disabled)
6147     loc = NULL;
6148 
6149   if (loc != NULL)
6150     set_current_program_space (loc->pspace);
6151 
6152   if (b->display_canonical)
6153     uiout->field_string ("what", b->locspec->to_string ());
6154   else if (loc && loc->symtab)
6155     {
6156       const struct symbol *sym = loc->symbol;
6157 
6158       if (sym)
6159 	{
6160 	  uiout->text ("in ");
6161 	  uiout->field_string ("func", sym->print_name (),
6162 			       function_name_style.style ());
6163 	  uiout->text (" ");
6164 	  uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6165 	  uiout->text ("at ");
6166 	}
6167       uiout->field_string ("file",
6168 			   symtab_to_filename_for_display (loc->symtab),
6169 			   file_name_style.style ());
6170       uiout->text (":");
6171 
6172       if (uiout->is_mi_like_p ())
6173 	uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6174 
6175       uiout->field_signed ("line", loc->line_number);
6176     }
6177   else if (loc)
6178     {
6179       string_file stb;
6180 
6181       print_address_symbolic (loc->gdbarch, loc->address, &stb,
6182 			      demangle, "");
6183       uiout->field_stream ("at", stb);
6184     }
6185   else
6186     {
6187       uiout->field_string ("pending", b->locspec->to_string ());
6188       /* If extra_string is available, it could be holding a condition
6189 	 or dprintf arguments.  In either case, make sure it is printed,
6190 	 too, but only for non-MI streams.  */
6191       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6192 	{
6193 	  if (b->type == bp_dprintf)
6194 	    uiout->text (",");
6195 	  else
6196 	    uiout->text (" ");
6197 	  uiout->text (b->extra_string.get ());
6198 	}
6199     }
6200 
6201   if (loc && is_breakpoint (b)
6202       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6203       && bp_condition_evaluator (b) == condition_evaluation_both)
6204     {
6205       uiout->text (" (");
6206       uiout->field_string ("evaluated-by",
6207 			   bp_location_condition_evaluator (loc));
6208       uiout->text (")");
6209     }
6210 }
6211 
6212 static const char *
6213 bptype_string (enum bptype type)
6214 {
6215   struct ep_type_description
6216     {
6217       enum bptype type;
6218       const char *description;
6219     };
6220   static struct ep_type_description bptypes[] =
6221   {
6222     {bp_none, "?deleted?"},
6223     {bp_breakpoint, "breakpoint"},
6224     {bp_hardware_breakpoint, "hw breakpoint"},
6225     {bp_single_step, "sw single-step"},
6226     {bp_until, "until"},
6227     {bp_finish, "finish"},
6228     {bp_watchpoint, "watchpoint"},
6229     {bp_hardware_watchpoint, "hw watchpoint"},
6230     {bp_read_watchpoint, "read watchpoint"},
6231     {bp_access_watchpoint, "acc watchpoint"},
6232     {bp_longjmp, "longjmp"},
6233     {bp_longjmp_resume, "longjmp resume"},
6234     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6235     {bp_exception, "exception"},
6236     {bp_exception_resume, "exception resume"},
6237     {bp_step_resume, "step resume"},
6238     {bp_hp_step_resume, "high-priority step resume"},
6239     {bp_watchpoint_scope, "watchpoint scope"},
6240     {bp_call_dummy, "call dummy"},
6241     {bp_std_terminate, "std::terminate"},
6242     {bp_shlib_event, "shlib events"},
6243     {bp_thread_event, "thread events"},
6244     {bp_overlay_event, "overlay events"},
6245     {bp_longjmp_master, "longjmp master"},
6246     {bp_std_terminate_master, "std::terminate master"},
6247     {bp_exception_master, "exception master"},
6248     {bp_catchpoint, "catchpoint"},
6249     {bp_tracepoint, "tracepoint"},
6250     {bp_fast_tracepoint, "fast tracepoint"},
6251     {bp_static_tracepoint, "static tracepoint"},
6252     {bp_static_marker_tracepoint, "static marker tracepoint"},
6253     {bp_dprintf, "dprintf"},
6254     {bp_jit_event, "jit events"},
6255     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6256     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6257   };
6258 
6259   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6260       || ((int) type != bptypes[(int) type].type))
6261     internal_error (_("bptypes table does not describe type #%d."),
6262 		    (int) type);
6263 
6264   return bptypes[(int) type].description;
6265 }
6266 
6267 /* For MI, output a field named 'thread-groups' with a list as the value.
6268    For CLI, prefix the list with the string 'inf'. */
6269 
6270 static void
6271 output_thread_groups (struct ui_out *uiout,
6272 		      const char *field_name,
6273 		      const std::vector<int> &inf_nums,
6274 		      int mi_only)
6275 {
6276   int is_mi = uiout->is_mi_like_p ();
6277 
6278   /* For backward compatibility, don't display inferiors in CLI unless
6279      there are several.  Always display them for MI. */
6280   if (!is_mi && mi_only)
6281     return;
6282 
6283   ui_out_emit_list list_emitter (uiout, field_name);
6284 
6285   for (size_t i = 0; i < inf_nums.size (); i++)
6286     {
6287       if (is_mi)
6288 	{
6289 	  char mi_group[10];
6290 
6291 	  xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6292 	  uiout->field_string (NULL, mi_group);
6293 	}
6294       else
6295 	{
6296 	  if (i == 0)
6297 	    uiout->text (" inf ");
6298 	  else
6299 	    uiout->text (", ");
6300 
6301 	  uiout->text (plongest (inf_nums[i]));
6302 	}
6303     }
6304 }
6305 
6306 /* See breakpoint.h. */
6307 
6308 bool fix_breakpoint_script_output_globally = false;
6309 
6310 /* Print B to gdb_stdout.  If RAW_LOC, print raw breakpoint locations
6311    instead of going via breakpoint_ops::print_one.  This makes "maint
6312    info breakpoints" show the software breakpoint locations of
6313    catchpoints, which are considered internal implementation
6314    detail.  Returns true if RAW_LOC is false and if the breakpoint's
6315    print_one method did something; false otherwise.  */
6316 
6317 static bool
6318 print_one_breakpoint_location (struct breakpoint *b,
6319 			       struct bp_location *loc,
6320 			       int loc_number,
6321 			       struct bp_location **last_loc,
6322 			       int allflag, bool raw_loc)
6323 {
6324   struct command_line *l;
6325   static char bpenables[] = "nynny";
6326 
6327   struct ui_out *uiout = current_uiout;
6328   bool header_of_multiple = false;
6329   bool part_of_multiple = (loc != NULL);
6330   struct value_print_options opts;
6331 
6332   get_user_print_options (&opts);
6333 
6334   gdb_assert (!loc || loc_number != 0);
6335   /* See comment in print_one_breakpoint concerning treatment of
6336      breakpoints with single disabled location.  */
6337   if (loc == NULL
6338       && (b->loc != NULL
6339 	  && (b->loc->next != NULL
6340 	      || !b->loc->enabled || b->loc->disabled_by_cond)))
6341     header_of_multiple = true;
6342   if (loc == NULL)
6343     loc = b->loc;
6344 
6345   annotate_record ();
6346 
6347   /* 1 */
6348   annotate_field (0);
6349   if (part_of_multiple)
6350     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6351   else
6352     uiout->field_signed ("number", b->number);
6353 
6354   /* 2 */
6355   annotate_field (1);
6356   if (part_of_multiple)
6357     uiout->field_skip ("type");
6358   else
6359     uiout->field_string ("type", bptype_string (b->type));
6360 
6361   /* 3 */
6362   annotate_field (2);
6363   if (part_of_multiple)
6364     uiout->field_skip ("disp");
6365   else
6366     uiout->field_string ("disp", bpdisp_text (b->disposition));
6367 
6368   /* 4 */
6369   annotate_field (3);
6370   if (part_of_multiple)
6371     {
6372       /* For locations that are disabled because of an invalid
6373 	 condition, display "N*" on the CLI, where "*" refers to a
6374 	 footnote below the table.  For MI, simply display a "N"
6375 	 without a footnote.  On the CLI, for enabled locations whose
6376 	 breakpoint is disabled, display "y-".  */
6377       auto get_enable_state = [uiout, loc] () -> const char *
6378         {
6379 	  if (uiout->is_mi_like_p ())
6380 	    {
6381 	      if (loc->disabled_by_cond)
6382 		return "N";
6383 	      else if (!loc->enabled)
6384 		return "n";
6385 	      else
6386 		return "y";
6387 	    }
6388 	  else
6389 	    {
6390 	      if (loc->disabled_by_cond)
6391 		return "N*";
6392 	      else if (!loc->enabled)
6393 		return "n";
6394 	      else if (!breakpoint_enabled (loc->owner))
6395 		return "y-";
6396 	      else
6397 		return "y";
6398 	    }
6399 	};
6400       uiout->field_string ("enabled", get_enable_state ());
6401     }
6402   else
6403     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6404 
6405   /* 5 and 6 */
6406   bool result = false;
6407   if (!raw_loc && b->print_one (last_loc))
6408     result = true;
6409   else
6410     {
6411       if (is_watchpoint (b))
6412 	{
6413 	  struct watchpoint *w = (struct watchpoint *) b;
6414 
6415 	  /* Field 4, the address, is omitted (which makes the columns
6416 	     not line up too nicely with the headers, but the effect
6417 	     is relatively readable).  */
6418 	  if (opts.addressprint)
6419 	    uiout->field_skip ("addr");
6420 	  annotate_field (5);
6421 	  uiout->field_string ("what", w->exp_string.get ());
6422 	}
6423       else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6424 	       || is_ada_exception_catchpoint (b))
6425 	{
6426 	  if (opts.addressprint)
6427 	    {
6428 	      annotate_field (4);
6429 	      if (header_of_multiple)
6430 		uiout->field_string ("addr", "<MULTIPLE>",
6431 				     metadata_style.style ());
6432 	      else if (b->loc == NULL || loc->shlib_disabled)
6433 		uiout->field_string ("addr", "<PENDING>",
6434 				     metadata_style.style ());
6435 	      else
6436 		uiout->field_core_addr ("addr",
6437 					loc->gdbarch, loc->address);
6438 	    }
6439 	  annotate_field (5);
6440 	  if (!header_of_multiple)
6441 	    print_breakpoint_location (b, loc);
6442 	  if (b->loc)
6443 	    *last_loc = b->loc;
6444 	}
6445     }
6446 
6447   if (loc != NULL && !header_of_multiple)
6448     {
6449       std::vector<int> inf_nums;
6450       int mi_only = 1;
6451 
6452       for (inferior *inf : all_inferiors ())
6453 	{
6454 	  if (inf->pspace == loc->pspace)
6455 	    inf_nums.push_back (inf->num);
6456 	}
6457 
6458 	/* For backward compatibility, don't display inferiors in CLI unless
6459 	   there are several.  Always display for MI. */
6460 	if (allflag
6461 	    || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6462 		&& (program_spaces.size () > 1
6463 		    || number_of_inferiors () > 1)
6464 		/* LOC is for existing B, it cannot be in
6465 		   moribund_locations and thus having NULL OWNER.  */
6466 		&& loc->owner->type != bp_catchpoint))
6467 	mi_only = 0;
6468       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6469     }
6470 
6471   if (!part_of_multiple)
6472     {
6473       if (b->thread != -1)
6474 	{
6475 	  /* FIXME: This seems to be redundant and lost here; see the
6476 	     "stop only in" line a little further down.  */
6477 	  uiout->text (" thread ");
6478 	  uiout->field_signed ("thread", b->thread);
6479 	}
6480       else if (b->task != 0)
6481 	{
6482 	  uiout->text (" task ");
6483 	  uiout->field_signed ("task", b->task);
6484 	}
6485     }
6486 
6487   uiout->text ("\n");
6488 
6489   if (!part_of_multiple)
6490     b->print_one_detail (uiout);
6491 
6492   if (part_of_multiple && frame_id_p (b->frame_id))
6493     {
6494       annotate_field (6);
6495       uiout->text ("\tstop only in stack frame at ");
6496       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6497 	 the frame ID.  */
6498       uiout->field_core_addr ("frame",
6499 			      b->gdbarch, b->frame_id.stack_addr);
6500       uiout->text ("\n");
6501     }
6502 
6503   if (!part_of_multiple && b->cond_string)
6504     {
6505       annotate_field (7);
6506       if (is_tracepoint (b))
6507 	uiout->text ("\ttrace only if ");
6508       else
6509 	uiout->text ("\tstop only if ");
6510       uiout->field_string ("cond", b->cond_string.get ());
6511 
6512       /* Print whether the target is doing the breakpoint's condition
6513 	 evaluation.  If GDB is doing the evaluation, don't print anything.  */
6514       if (is_breakpoint (b)
6515 	  && breakpoint_condition_evaluation_mode ()
6516 	  == condition_evaluation_target)
6517 	{
6518 	  uiout->message (" (%pF evals)",
6519 			  string_field ("evaluated-by",
6520 					bp_condition_evaluator (b)));
6521 	}
6522       uiout->text ("\n");
6523     }
6524 
6525   if (!part_of_multiple && b->thread != -1)
6526     {
6527       /* FIXME should make an annotation for this.  */
6528       uiout->text ("\tstop only in thread ");
6529       if (uiout->is_mi_like_p ())
6530 	uiout->field_signed ("thread", b->thread);
6531       else
6532 	{
6533 	  struct thread_info *thr = find_thread_global_id (b->thread);
6534 
6535 	  uiout->field_string ("thread", print_thread_id (thr));
6536 	}
6537       uiout->text ("\n");
6538     }
6539 
6540   if (!part_of_multiple)
6541     {
6542       if (b->hit_count)
6543 	{
6544 	  /* FIXME should make an annotation for this.  */
6545 	  if (is_catchpoint (b))
6546 	    uiout->text ("\tcatchpoint");
6547 	  else if (is_tracepoint (b))
6548 	    uiout->text ("\ttracepoint");
6549 	  else
6550 	    uiout->text ("\tbreakpoint");
6551 	  uiout->text (" already hit ");
6552 	  uiout->field_signed ("times", b->hit_count);
6553 	  if (b->hit_count == 1)
6554 	    uiout->text (" time\n");
6555 	  else
6556 	    uiout->text (" times\n");
6557 	}
6558       else
6559 	{
6560 	  /* Output the count also if it is zero, but only if this is mi.  */
6561 	  if (uiout->is_mi_like_p ())
6562 	    uiout->field_signed ("times", b->hit_count);
6563 	}
6564     }
6565 
6566   if (!part_of_multiple && b->ignore_count)
6567     {
6568       annotate_field (8);
6569       uiout->message ("\tignore next %pF hits\n",
6570 		      signed_field ("ignore", b->ignore_count));
6571     }
6572 
6573   /* Note that an enable count of 1 corresponds to "enable once"
6574      behavior, which is reported by the combination of enablement and
6575      disposition, so we don't need to mention it here.  */
6576   if (!part_of_multiple && b->enable_count > 1)
6577     {
6578       annotate_field (8);
6579       uiout->text ("\tdisable after ");
6580       /* Tweak the wording to clarify that ignore and enable counts
6581 	 are distinct, and have additive effect.  */
6582       if (b->ignore_count)
6583 	uiout->text ("additional ");
6584       else
6585 	uiout->text ("next ");
6586       uiout->field_signed ("enable", b->enable_count);
6587       uiout->text (" hits\n");
6588     }
6589 
6590   if (!part_of_multiple && is_tracepoint (b))
6591     {
6592       struct tracepoint *tp = (struct tracepoint *) b;
6593 
6594       if (tp->traceframe_usage)
6595 	{
6596 	  uiout->text ("\ttrace buffer usage ");
6597 	  uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6598 	  uiout->text (" bytes\n");
6599 	}
6600     }
6601 
6602   l = b->commands ? b->commands.get () : NULL;
6603   if (!part_of_multiple && l)
6604     {
6605       annotate_field (9);
6606 
6607       bool use_fixed_output =
6608 	(uiout->test_flags (fix_breakpoint_script_output)
6609          || fix_breakpoint_script_output_globally);
6610 
6611       gdb::optional<ui_out_emit_tuple> tuple_emitter;
6612       gdb::optional<ui_out_emit_list> list_emitter;
6613 
6614       if (use_fixed_output)
6615 	list_emitter.emplace (uiout, "script");
6616       else
6617 	tuple_emitter.emplace (uiout, "script");
6618 
6619       print_command_lines (uiout, l, 4);
6620     }
6621 
6622   if (is_tracepoint (b))
6623     {
6624       struct tracepoint *t = (struct tracepoint *) b;
6625 
6626       if (!part_of_multiple && t->pass_count)
6627 	{
6628 	  annotate_field (10);
6629 	  uiout->text ("\tpass count ");
6630 	  uiout->field_signed ("pass", t->pass_count);
6631 	  uiout->text (" \n");
6632 	}
6633 
6634       /* Don't display it when tracepoint or tracepoint location is
6635 	 pending.   */
6636       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6637 	{
6638 	  annotate_field (11);
6639 
6640 	  if (uiout->is_mi_like_p ())
6641 	    uiout->field_string ("installed",
6642 				 loc->inserted ? "y" : "n");
6643 	  else
6644 	    {
6645 	      if (loc->inserted)
6646 		uiout->text ("\t");
6647 	      else
6648 		uiout->text ("\tnot ");
6649 	      uiout->text ("installed on target\n");
6650 	    }
6651 	}
6652     }
6653 
6654   if (uiout->is_mi_like_p () && !part_of_multiple)
6655     {
6656       if (is_watchpoint (b))
6657 	{
6658 	  struct watchpoint *w = (struct watchpoint *) b;
6659 
6660 	  uiout->field_string ("original-location", w->exp_string.get ());
6661 	}
6662       else if (b->locspec != nullptr)
6663 	{
6664 	  const char *str = b->locspec->to_string ();
6665 	  if (str != nullptr)
6666 	    uiout->field_string ("original-location", str);
6667 	}
6668     }
6669 
6670   return result;
6671 }
6672 
6673 /* See breakpoint.h. */
6674 
6675 bool fix_multi_location_breakpoint_output_globally = false;
6676 
6677 static void
6678 print_one_breakpoint (struct breakpoint *b,
6679 		      struct bp_location **last_loc,
6680 		      int allflag)
6681 {
6682   struct ui_out *uiout = current_uiout;
6683   bool use_fixed_output
6684     = (uiout->test_flags (fix_multi_location_breakpoint_output)
6685        || fix_multi_location_breakpoint_output_globally);
6686 
6687   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6688   bool printed = print_one_breakpoint_location (b, NULL, 0, last_loc,
6689 						allflag, false);
6690 
6691   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6692      are outside.  */
6693   if (!use_fixed_output)
6694     bkpt_tuple_emitter.reset ();
6695 
6696   /* If this breakpoint has custom print function,
6697      it's already printed.  Otherwise, print individual
6698      locations, if any.  */
6699   if (!printed || allflag)
6700     {
6701       /* If breakpoint has a single location that is disabled, we
6702 	 print it as if it had several locations, since otherwise it's
6703 	 hard to represent "breakpoint enabled, location disabled"
6704 	 situation.
6705 
6706 	 Note that while hardware watchpoints have several locations
6707 	 internally, that's not a property exposed to users.
6708 
6709 	 Likewise, while catchpoints may be implemented with
6710 	 breakpoints (e.g., catch throw), that's not a property
6711 	 exposed to users.  We do however display the internal
6712 	 breakpoint locations with "maint info breakpoints".  */
6713       if (!is_hardware_watchpoint (b)
6714 	  && (!is_catchpoint (b) || is_exception_catchpoint (b)
6715 	      || is_ada_exception_catchpoint (b))
6716 	  && (allflag
6717 	      || (b->loc && (b->loc->next
6718 			     || !b->loc->enabled
6719 			     || b->loc->disabled_by_cond))))
6720 	{
6721 	  gdb::optional<ui_out_emit_list> locations_list;
6722 
6723 	  /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6724 	     MI record.  For later versions, place breakpoint locations in a
6725 	     list.  */
6726 	  if (uiout->is_mi_like_p () && use_fixed_output)
6727 	    locations_list.emplace (uiout, "locations");
6728 
6729 	  int n = 1;
6730 	  for (bp_location *loc : b->locations ())
6731 	    {
6732 	      ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6733 	      print_one_breakpoint_location (b, loc, n, last_loc,
6734 					     allflag, allflag);
6735 	      n++;
6736 	    }
6737 	}
6738     }
6739 }
6740 
6741 static int
6742 breakpoint_address_bits (struct breakpoint *b)
6743 {
6744   int print_address_bits = 0;
6745 
6746   for (bp_location *loc : b->locations ())
6747     {
6748       if (!bl_address_is_meaningful (loc))
6749 	continue;
6750 
6751       int addr_bit = gdbarch_addr_bit (loc->gdbarch);
6752       if (addr_bit > print_address_bits)
6753 	print_address_bits = addr_bit;
6754     }
6755 
6756   return print_address_bits;
6757 }
6758 
6759 /* See breakpoint.h.  */
6760 
6761 void
6762 print_breakpoint (breakpoint *b)
6763 {
6764   struct bp_location *dummy_loc = NULL;
6765   print_one_breakpoint (b, &dummy_loc, 0);
6766 }
6767 
6768 /* Return true if this breakpoint was set by the user, false if it is
6769    internal or momentary.  */
6770 
6771 int
6772 user_breakpoint_p (struct breakpoint *b)
6773 {
6774   return b->number > 0;
6775 }
6776 
6777 /* See breakpoint.h.  */
6778 
6779 int
6780 pending_breakpoint_p (struct breakpoint *b)
6781 {
6782   return b->loc == NULL;
6783 }
6784 
6785 /* Print information on breakpoints (including watchpoints and tracepoints).
6786 
6787    If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6788    understood by number_or_range_parser.  Only breakpoints included in this
6789    list are then printed.
6790 
6791    If SHOW_INTERNAL is true, print internal breakpoints.
6792 
6793    If FILTER is non-NULL, call it on each breakpoint and only include the
6794    ones for which it returns true.
6795 
6796    Return the total number of breakpoints listed.  */
6797 
6798 static int
6799 breakpoint_1 (const char *bp_num_list, bool show_internal,
6800 	      bool (*filter) (const struct breakpoint *))
6801 {
6802   struct bp_location *last_loc = NULL;
6803   int nr_printable_breakpoints;
6804   struct value_print_options opts;
6805   int print_address_bits = 0;
6806   int print_type_col_width = 14;
6807   struct ui_out *uiout = current_uiout;
6808   bool has_disabled_by_cond_location = false;
6809 
6810   get_user_print_options (&opts);
6811 
6812   /* Compute the number of rows in the table, as well as the size
6813      required for address fields.  */
6814   nr_printable_breakpoints = 0;
6815   for (breakpoint *b : all_breakpoints ())
6816     {
6817       /* If we have a filter, only list the breakpoints it accepts.  */
6818       if (filter && !filter (b))
6819 	continue;
6820 
6821       /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6822 	 accept.  Skip the others.  */
6823       if (bp_num_list != NULL && *bp_num_list != '\0')
6824 	{
6825 	  if (show_internal && parse_and_eval_long (bp_num_list) != b->number)
6826 	    continue;
6827 	  if (!show_internal && !number_is_in_list (bp_num_list, b->number))
6828 	    continue;
6829 	}
6830 
6831       if (show_internal || user_breakpoint_p (b))
6832 	{
6833 	  int addr_bit, type_len;
6834 
6835 	  addr_bit = breakpoint_address_bits (b);
6836 	  if (addr_bit > print_address_bits)
6837 	    print_address_bits = addr_bit;
6838 
6839 	  type_len = strlen (bptype_string (b->type));
6840 	  if (type_len > print_type_col_width)
6841 	    print_type_col_width = type_len;
6842 
6843 	  nr_printable_breakpoints++;
6844 	}
6845     }
6846 
6847   {
6848     ui_out_emit_table table_emitter (uiout,
6849 				     opts.addressprint ? 6 : 5,
6850 				     nr_printable_breakpoints,
6851 				     "BreakpointTable");
6852 
6853     if (nr_printable_breakpoints > 0)
6854       annotate_breakpoints_headers ();
6855     if (nr_printable_breakpoints > 0)
6856       annotate_field (0);
6857     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6858     if (nr_printable_breakpoints > 0)
6859       annotate_field (1);
6860     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6861     if (nr_printable_breakpoints > 0)
6862       annotate_field (2);
6863     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6864     if (nr_printable_breakpoints > 0)
6865       annotate_field (3);
6866     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6867     if (opts.addressprint)
6868       {
6869 	if (nr_printable_breakpoints > 0)
6870 	  annotate_field (4);
6871 	if (print_address_bits <= 32)
6872 	  uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6873 	else
6874 	  uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6875       }
6876     if (nr_printable_breakpoints > 0)
6877       annotate_field (5);
6878     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6879     uiout->table_body ();
6880     if (nr_printable_breakpoints > 0)
6881       annotate_breakpoints_table ();
6882 
6883     for (breakpoint *b : all_breakpoints ())
6884       {
6885 	QUIT;
6886 	/* If we have a filter, only list the breakpoints it accepts.  */
6887 	if (filter && !filter (b))
6888 	  continue;
6889 
6890 	/* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6891 	   accept.  Skip the others.  */
6892 
6893 	if (bp_num_list != NULL && *bp_num_list != '\0')
6894 	  {
6895 	    if (show_internal)	/* maintenance info breakpoint */
6896 	      {
6897 		if (parse_and_eval_long (bp_num_list) != b->number)
6898 		  continue;
6899 	      }
6900 	    else		/* all others */
6901 	      {
6902 		if (!number_is_in_list (bp_num_list, b->number))
6903 		  continue;
6904 	      }
6905 	  }
6906 	/* We only print out user settable breakpoints unless the
6907 	   show_internal is set.  */
6908 	if (show_internal || user_breakpoint_p (b))
6909 	  {
6910 	    print_one_breakpoint (b, &last_loc, show_internal);
6911 	    for (bp_location *loc : b->locations ())
6912 	      if (loc->disabled_by_cond)
6913 		has_disabled_by_cond_location = true;
6914 	  }
6915       }
6916   }
6917 
6918   if (nr_printable_breakpoints == 0)
6919     {
6920       /* If there's a filter, let the caller decide how to report
6921 	 empty list.  */
6922       if (!filter)
6923 	{
6924 	  if (bp_num_list == NULL || *bp_num_list == '\0')
6925 	    uiout->message ("No breakpoints or watchpoints.\n");
6926 	  else
6927 	    uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6928 			    bp_num_list);
6929 	}
6930     }
6931   else
6932     {
6933       if (last_loc && !server_command)
6934 	set_next_address (last_loc->gdbarch, last_loc->address);
6935 
6936       if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
6937 	uiout->message (_("(*): Breakpoint condition is invalid at this "
6938 			  "location.\n"));
6939     }
6940 
6941   /* FIXME?  Should this be moved up so that it is only called when
6942      there have been breakpoints? */
6943   annotate_breakpoints_table_end ();
6944 
6945   return nr_printable_breakpoints;
6946 }
6947 
6948 /* Display the value of default-collect in a way that is generally
6949    compatible with the breakpoint list.  */
6950 
6951 static void
6952 default_collect_info (void)
6953 {
6954   struct ui_out *uiout = current_uiout;
6955 
6956   /* If it has no value (which is frequently the case), say nothing; a
6957      message like "No default-collect." gets in user's face when it's
6958      not wanted.  */
6959   if (default_collect.empty ())
6960     return;
6961 
6962   /* The following phrase lines up nicely with per-tracepoint collect
6963      actions.  */
6964   uiout->text ("default collect ");
6965   uiout->field_string ("default-collect", default_collect);
6966   uiout->text (" \n");
6967 }
6968 
6969 static void
6970 info_breakpoints_command (const char *args, int from_tty)
6971 {
6972   breakpoint_1 (args, false, NULL);
6973 
6974   default_collect_info ();
6975 }
6976 
6977 static void
6978 info_watchpoints_command (const char *args, int from_tty)
6979 {
6980   int num_printed = breakpoint_1 (args, false, is_watchpoint);
6981   struct ui_out *uiout = current_uiout;
6982 
6983   if (num_printed == 0)
6984     {
6985       if (args == NULL || *args == '\0')
6986 	uiout->message ("No watchpoints.\n");
6987       else
6988 	uiout->message ("No watchpoint matching '%s'.\n", args);
6989     }
6990 }
6991 
6992 static void
6993 maintenance_info_breakpoints (const char *args, int from_tty)
6994 {
6995   breakpoint_1 (args, true, NULL);
6996 
6997   default_collect_info ();
6998 }
6999 
7000 static bool
7001 breakpoint_has_pc (struct breakpoint *b,
7002 		   struct program_space *pspace,
7003 		   CORE_ADDR pc, struct obj_section *section)
7004 {
7005   for (bp_location *bl : b->locations ())
7006     {
7007       if (bl->pspace == pspace
7008 	  && bl->address == pc
7009 	  && (!overlay_debugging || bl->section == section))
7010 	return true;
7011     }
7012   return false;
7013 }
7014 
7015 /* See breakpoint.h.  */
7016 
7017 void
7018 describe_other_breakpoints (struct gdbarch *gdbarch,
7019 			    struct program_space *pspace, CORE_ADDR pc,
7020 			    struct obj_section *section, int thread)
7021 {
7022   int others = 0;
7023 
7024   for (breakpoint *b : all_breakpoints ())
7025     others += (user_breakpoint_p (b)
7026 	       && breakpoint_has_pc (b, pspace, pc, section));
7027 
7028   if (others > 0)
7029     {
7030       if (others == 1)
7031 	gdb_printf (_("Note: breakpoint "));
7032       else /* if (others == ???) */
7033 	gdb_printf (_("Note: breakpoints "));
7034       for (breakpoint *b : all_breakpoints ())
7035 	if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
7036 	  {
7037 	    others--;
7038 	    gdb_printf ("%d", b->number);
7039 	    if (b->thread == -1 && thread != -1)
7040 	      gdb_printf (" (all threads)");
7041 	    else if (b->thread != -1)
7042 	      gdb_printf (" (thread %d)", b->thread);
7043 	    gdb_printf ("%s%s ",
7044 			((b->enable_state == bp_disabled
7045 			  || b->enable_state == bp_call_disabled)
7046 			 ? " (disabled)"
7047 			 : ""),
7048 			(others > 1) ? ","
7049 			: ((others == 1) ? " and" : ""));
7050 	  }
7051       current_uiout->message (_("also set at pc %ps.\n"),
7052 			      styled_string (address_style.style (),
7053 					     paddress (gdbarch, pc)));
7054     }
7055 }
7056 
7057 
7058 /* Return true iff it is meaningful to use the address member of LOC.
7059    For some breakpoint types, the locations' address members are
7060    irrelevant and it makes no sense to attempt to compare them to
7061    other addresses (or use them for any other purpose either).
7062 
7063    More specifically, software watchpoints and catchpoints that are
7064    not backed by breakpoints always have a zero valued location
7065    address and we don't want to mark breakpoints of any of these types
7066    to be a duplicate of an actual breakpoint location at address
7067    zero.  */
7068 
7069 static bool
7070 bl_address_is_meaningful (bp_location *loc)
7071 {
7072   return loc->loc_type != bp_loc_other;
7073 }
7074 
7075 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7076    true if LOC1 and LOC2 represent the same watchpoint location.  */
7077 
7078 static bool
7079 watchpoint_locations_match (const struct bp_location *loc1,
7080 			    const struct bp_location *loc2)
7081 {
7082   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
7083   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7084 
7085   /* Both of them must exist.  */
7086   gdb_assert (w1 != NULL);
7087   gdb_assert (w2 != NULL);
7088 
7089   /* If the target can evaluate the condition expression in hardware,
7090      then we we need to insert both watchpoints even if they are at
7091      the same place.  Otherwise the watchpoint will only trigger when
7092      the condition of whichever watchpoint was inserted evaluates to
7093      true, not giving a chance for GDB to check the condition of the
7094      other watchpoint.  */
7095   if ((w1->cond_exp
7096        && target_can_accel_watchpoint_condition (loc1->address,
7097 						 loc1->length,
7098 						 loc1->watchpoint_type,
7099 						 w1->cond_exp.get ()))
7100       || (w2->cond_exp
7101 	  && target_can_accel_watchpoint_condition (loc2->address,
7102 						    loc2->length,
7103 						    loc2->watchpoint_type,
7104 						    w2->cond_exp.get ())))
7105     return false;
7106 
7107   /* Note that this checks the owner's type, not the location's.  In
7108      case the target does not support read watchpoints, but does
7109      support access watchpoints, we'll have bp_read_watchpoint
7110      watchpoints with hw_access locations.  Those should be considered
7111      duplicates of hw_read locations.  The hw_read locations will
7112      become hw_access locations later.  */
7113   return (loc1->owner->type == loc2->owner->type
7114 	  && loc1->pspace->aspace == loc2->pspace->aspace
7115 	  && loc1->address == loc2->address
7116 	  && loc1->length == loc2->length);
7117 }
7118 
7119 /* See breakpoint.h.  */
7120 
7121 int
7122 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
7123 			  const address_space *aspace2, CORE_ADDR addr2)
7124 {
7125   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7126 	   || aspace1 == aspace2)
7127 	  && addr1 == addr2);
7128 }
7129 
7130 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7131    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7132    matches ASPACE2.  On targets that have global breakpoints, the address
7133    space doesn't really matter.  */
7134 
7135 static bool
7136 breakpoint_address_match_range (const address_space *aspace1,
7137 				CORE_ADDR addr1,
7138 				int len1, const address_space *aspace2,
7139 				CORE_ADDR addr2)
7140 {
7141   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7142 	   || aspace1 == aspace2)
7143 	  && addr2 >= addr1 && addr2 < addr1 + len1);
7144 }
7145 
7146 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7147    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7148    matches the breakpoint's address space.  On targets that have global
7149    breakpoints, the address space doesn't really matter.  */
7150 
7151 static bool
7152 breakpoint_location_address_match (struct bp_location *bl,
7153 				   const address_space *aspace,
7154 				   CORE_ADDR addr)
7155 {
7156   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7157 				    aspace, addr)
7158 	  || (bl->length
7159 	      && breakpoint_address_match_range (bl->pspace->aspace,
7160 						 bl->address, bl->length,
7161 						 aspace, addr)));
7162 }
7163 
7164 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7165    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
7166    match happens only if ASPACE matches the breakpoint's address
7167    space.  On targets that have global breakpoints, the address space
7168    doesn't really matter.  */
7169 
7170 static bool
7171 breakpoint_location_address_range_overlap (struct bp_location *bl,
7172 					   const address_space *aspace,
7173 					   CORE_ADDR addr, int len)
7174 {
7175   if (gdbarch_has_global_breakpoints (target_gdbarch ())
7176       || bl->pspace->aspace == aspace)
7177     {
7178       int bl_len = bl->length != 0 ? bl->length : 1;
7179 
7180       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7181 	return 1;
7182     }
7183   return 0;
7184 }
7185 
7186 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7187    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7188    true, otherwise returns false.  */
7189 
7190 static bool
7191 tracepoint_locations_match (const struct bp_location *loc1,
7192 			    const struct bp_location *loc2)
7193 {
7194   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7195     /* Since tracepoint locations are never duplicated with others', tracepoint
7196        locations at the same address of different tracepoints are regarded as
7197        different locations.  */
7198     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7199   else
7200     return false;
7201 }
7202 
7203 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7204    (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
7205    the same location.  If SW_HW_BPS_MATCH is true, then software
7206    breakpoint locations and hardware breakpoint locations match,
7207    otherwise they don't.  */
7208 
7209 static bool
7210 breakpoint_locations_match (const struct bp_location *loc1,
7211 			    const struct bp_location *loc2,
7212 			    bool sw_hw_bps_match)
7213 {
7214   int hw_point1, hw_point2;
7215 
7216   /* Both of them must not be in moribund_locations.  */
7217   gdb_assert (loc1->owner != NULL);
7218   gdb_assert (loc2->owner != NULL);
7219 
7220   hw_point1 = is_hardware_watchpoint (loc1->owner);
7221   hw_point2 = is_hardware_watchpoint (loc2->owner);
7222 
7223   if (hw_point1 != hw_point2)
7224     return false;
7225   else if (hw_point1)
7226     return watchpoint_locations_match (loc1, loc2);
7227   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7228     return tracepoint_locations_match (loc1, loc2);
7229   else
7230     /* We compare bp_location.length in order to cover ranged
7231        breakpoints.  Keep this in sync with
7232        bp_location_is_less_than.  */
7233     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7234 				     loc2->pspace->aspace, loc2->address)
7235 	    && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
7236 	    && loc1->length == loc2->length);
7237 }
7238 
7239 static void
7240 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7241 			       int bnum, bool have_bnum)
7242 {
7243   /* The longest string possibly returned by hex_string_custom
7244      is 50 chars.  These must be at least that big for safety.  */
7245   char astr1[64];
7246   char astr2[64];
7247 
7248   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7249   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7250   if (have_bnum)
7251     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7252 	     bnum, astr1, astr2);
7253   else
7254     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7255 }
7256 
7257 /* Adjust a breakpoint's address to account for architectural
7258    constraints on breakpoint placement.  Return the adjusted address.
7259    Note: Very few targets require this kind of adjustment.  For most
7260    targets, this function is simply the identity function.  */
7261 
7262 static CORE_ADDR
7263 adjust_breakpoint_address (struct gdbarch *gdbarch,
7264 			   CORE_ADDR bpaddr, enum bptype bptype,
7265 			   struct program_space *pspace)
7266 {
7267   gdb_assert (pspace != nullptr);
7268 
7269   if (bptype == bp_watchpoint
7270       || bptype == bp_hardware_watchpoint
7271       || bptype == bp_read_watchpoint
7272       || bptype == bp_access_watchpoint
7273       || bptype == bp_catchpoint)
7274     {
7275       /* Watchpoints and the various bp_catch_* eventpoints should not
7276 	 have their addresses modified.  */
7277       return bpaddr;
7278     }
7279   else if (bptype == bp_single_step)
7280     {
7281       /* Single-step breakpoints should not have their addresses
7282 	 modified.  If there's any architectural constrain that
7283 	 applies to this address, then it should have already been
7284 	 taken into account when the breakpoint was created in the
7285 	 first place.  If we didn't do this, stepping through e.g.,
7286 	 Thumb-2 IT blocks would break.  */
7287       return bpaddr;
7288     }
7289   else
7290     {
7291       CORE_ADDR adjusted_bpaddr = bpaddr;
7292 
7293       /* Some targets have architectural constraints on the placement
7294 	 of breakpoint instructions.  Obtain the adjusted address.  */
7295       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7296 	{
7297 	  /* Targets that implement this adjustment function will likely
7298 	     inspect either the symbol table, target memory at BPADDR, or
7299 	     even state registers, so ensure a suitable thread (and its
7300 	     associated program space) are currently selected.  */
7301 	  scoped_restore_current_pspace_and_thread restore_pspace_thread;
7302 	  switch_to_program_space_and_thread (pspace);
7303 	  adjusted_bpaddr
7304 	    = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7305 	}
7306 
7307       adjusted_bpaddr
7308 	= gdbarch_remove_non_address_bits (gdbarch, adjusted_bpaddr);
7309 
7310       /* An adjusted breakpoint address can significantly alter
7311 	 a user's expectations.  Print a warning if an adjustment
7312 	 is required.  */
7313       if (adjusted_bpaddr != bpaddr)
7314 	breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, false);
7315 
7316       return adjusted_bpaddr;
7317     }
7318 }
7319 
7320 static bp_loc_type
7321 bp_location_from_bp_type (bptype type)
7322 {
7323   switch (type)
7324     {
7325     case bp_breakpoint:
7326     case bp_single_step:
7327     case bp_until:
7328     case bp_finish:
7329     case bp_longjmp:
7330     case bp_longjmp_resume:
7331     case bp_longjmp_call_dummy:
7332     case bp_exception:
7333     case bp_exception_resume:
7334     case bp_step_resume:
7335     case bp_hp_step_resume:
7336     case bp_watchpoint_scope:
7337     case bp_call_dummy:
7338     case bp_std_terminate:
7339     case bp_shlib_event:
7340     case bp_thread_event:
7341     case bp_overlay_event:
7342     case bp_jit_event:
7343     case bp_longjmp_master:
7344     case bp_std_terminate_master:
7345     case bp_exception_master:
7346     case bp_gnu_ifunc_resolver:
7347     case bp_gnu_ifunc_resolver_return:
7348     case bp_dprintf:
7349       return bp_loc_software_breakpoint;
7350     case bp_hardware_breakpoint:
7351       return bp_loc_hardware_breakpoint;
7352     case bp_hardware_watchpoint:
7353     case bp_read_watchpoint:
7354     case bp_access_watchpoint:
7355       return bp_loc_hardware_watchpoint;
7356     case bp_watchpoint:
7357       return bp_loc_software_watchpoint;
7358     case bp_catchpoint:
7359     case bp_tracepoint:
7360     case bp_fast_tracepoint:
7361     case bp_static_tracepoint:
7362     case bp_static_marker_tracepoint:
7363       return bp_loc_other;
7364     default:
7365       internal_error (_("unknown breakpoint type"));
7366     }
7367 }
7368 
7369 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7370 {
7371   this->owner = owner;
7372   this->cond_bytecode = NULL;
7373   this->shlib_disabled = 0;
7374   this->enabled = 1;
7375   this->disabled_by_cond = false;
7376 
7377   this->loc_type = type;
7378 
7379   if (this->loc_type == bp_loc_software_breakpoint
7380       || this->loc_type == bp_loc_hardware_breakpoint)
7381     mark_breakpoint_location_modified (this);
7382 
7383   incref ();
7384 }
7385 
7386 bp_location::bp_location (breakpoint *owner)
7387   : bp_location::bp_location (owner,
7388 			      bp_location_from_bp_type (owner->type))
7389 {
7390 }
7391 
7392 /* Decrement reference count.  If the reference count reaches 0,
7393    destroy the bp_location.  Sets *BLP to NULL.  */
7394 
7395 static void
7396 decref_bp_location (struct bp_location **blp)
7397 {
7398   bp_location_ref_policy::decref (*blp);
7399   *blp = NULL;
7400 }
7401 
7402 /* Add breakpoint B at the end of the global breakpoint chain.  */
7403 
7404 static breakpoint *
7405 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7406 {
7407   struct breakpoint *b1;
7408   struct breakpoint *result = b.get ();
7409 
7410   /* Add this breakpoint to the end of the chain so that a list of
7411      breakpoints will come out in order of increasing numbers.  */
7412 
7413   b1 = breakpoint_chain;
7414   if (b1 == 0)
7415     breakpoint_chain = b.release ();
7416   else
7417     {
7418       while (b1->next)
7419 	b1 = b1->next;
7420       b1->next = b.release ();
7421     }
7422 
7423   return result;
7424 }
7425 
7426 /* Initialize loc->function_name.  */
7427 
7428 static void
7429 set_breakpoint_location_function (struct bp_location *loc)
7430 {
7431   gdb_assert (loc->owner != NULL);
7432 
7433   if (loc->owner->type == bp_breakpoint
7434       || loc->owner->type == bp_hardware_breakpoint
7435       || is_tracepoint (loc->owner))
7436     {
7437       const char *function_name;
7438 
7439       if (loc->msymbol != NULL
7440 	  && (loc->msymbol->type () == mst_text_gnu_ifunc
7441 	      || loc->msymbol->type () == mst_data_gnu_ifunc))
7442 	{
7443 	  struct breakpoint *b = loc->owner;
7444 
7445 	  function_name = loc->msymbol->linkage_name ();
7446 
7447 	  if (b->type == bp_breakpoint && b->loc == loc
7448 	      && loc->next == NULL && b->related_breakpoint == b)
7449 	    {
7450 	      /* Create only the whole new breakpoint of this type but do not
7451 		 mess more complicated breakpoints with multiple locations.  */
7452 	      b->type = bp_gnu_ifunc_resolver;
7453 	      /* Remember the resolver's address for use by the return
7454 		 breakpoint.  */
7455 	      loc->related_address = loc->address;
7456 	    }
7457 	}
7458       else
7459 	find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7460 
7461       if (function_name)
7462 	loc->function_name = make_unique_xstrdup (function_name);
7463     }
7464 }
7465 
7466 /* Attempt to determine architecture of location identified by SAL.  */
7467 struct gdbarch *
7468 get_sal_arch (struct symtab_and_line sal)
7469 {
7470   if (sal.section)
7471     return sal.section->objfile->arch ();
7472   if (sal.symtab)
7473     return sal.symtab->compunit ()->objfile ()->arch ();
7474 
7475   return NULL;
7476 }
7477 
7478 /* Call this routine when stepping and nexting to enable a breakpoint
7479    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7480    initiated the operation.  */
7481 
7482 void
7483 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7484 {
7485   int thread = tp->global_num;
7486 
7487   /* To avoid having to rescan all objfile symbols at every step,
7488      we maintain a list of continually-inserted but always disabled
7489      longjmp "master" breakpoints.  Here, we simply create momentary
7490      clones of those and enable them for the requested thread.  */
7491   for (breakpoint *b : all_breakpoints_safe ())
7492     if (b->pspace == current_program_space
7493 	&& (b->type == bp_longjmp_master
7494 	    || b->type == bp_exception_master))
7495       {
7496 	enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7497 	/* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7498 	   after their removal.  */
7499 	momentary_breakpoint_from_master (b, type, 1, thread);
7500       }
7501 
7502   tp->initiating_frame = frame;
7503 }
7504 
7505 /* Delete all longjmp breakpoints from THREAD.  */
7506 void
7507 delete_longjmp_breakpoint (int thread)
7508 {
7509   for (breakpoint *b : all_breakpoints_safe ())
7510     if (b->type == bp_longjmp || b->type == bp_exception)
7511       {
7512 	if (b->thread == thread)
7513 	  delete_breakpoint (b);
7514       }
7515 }
7516 
7517 void
7518 delete_longjmp_breakpoint_at_next_stop (int thread)
7519 {
7520   for (breakpoint *b : all_breakpoints_safe ())
7521     if (b->type == bp_longjmp || b->type == bp_exception)
7522       {
7523 	if (b->thread == thread)
7524 	  b->disposition = disp_del_at_next_stop;
7525       }
7526 }
7527 
7528 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7529    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7530    pointer to any of them.  Return NULL if this system cannot place longjmp
7531    breakpoints.  */
7532 
7533 struct breakpoint *
7534 set_longjmp_breakpoint_for_call_dummy (void)
7535 {
7536   breakpoint *retval = nullptr;
7537 
7538   for (breakpoint *b : all_breakpoints ())
7539     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7540       {
7541 	int thread = inferior_thread ()->global_num;
7542 	breakpoint *new_b
7543 	  = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7544 					      1, thread);
7545 
7546 	/* Link NEW_B into the chain of RETVAL breakpoints.  */
7547 
7548 	gdb_assert (new_b->related_breakpoint == new_b);
7549 	if (retval == NULL)
7550 	  retval = new_b;
7551 	new_b->related_breakpoint = retval;
7552 	while (retval->related_breakpoint != new_b->related_breakpoint)
7553 	  retval = retval->related_breakpoint;
7554 	retval->related_breakpoint = new_b;
7555       }
7556 
7557   return retval;
7558 }
7559 
7560 /* Verify all existing dummy frames and their associated breakpoints for
7561    TP.  Remove those which can no longer be found in the current frame
7562    stack.
7563 
7564    If the unwind fails then there is not sufficient information to discard
7565    dummy frames.  In this case, elide the clean up and the dummy frames will
7566    be cleaned up next time this function is called from a location where
7567    unwinding is possible.  */
7568 
7569 void
7570 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7571 {
7572   struct breakpoint *b, *b_tmp;
7573 
7574   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7575     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7576       {
7577 	struct breakpoint *dummy_b = b->related_breakpoint;
7578 
7579 	/* Find the bp_call_dummy breakpoint in the list of breakpoints
7580 	   chained off b->related_breakpoint.  */
7581 	while (dummy_b != b && dummy_b->type != bp_call_dummy)
7582 	  dummy_b = dummy_b->related_breakpoint;
7583 
7584 	/* If there was no bp_call_dummy breakpoint then there's nothing
7585 	   more to do.  Or, if the dummy frame associated with the
7586 	   bp_call_dummy is still on the stack then we need to leave this
7587 	   bp_call_dummy in place.  */
7588 	if (dummy_b->type != bp_call_dummy
7589 	    || frame_find_by_id (dummy_b->frame_id) != NULL)
7590 	  continue;
7591 
7592 	/* We didn't find the dummy frame on the stack, this could be
7593 	   because we have longjmp'd to a stack frame that is previous to
7594 	   the dummy frame, or it could be because the stack unwind is
7595 	   broken at some point between the longjmp frame and the dummy
7596 	   frame.
7597 
7598 	   Next we figure out why the stack unwind stopped.  If it looks
7599 	   like the unwind is complete then we assume the dummy frame has
7600 	   been jumped over, however, if the unwind stopped for an
7601 	   unexpected reason then we assume the stack unwind is currently
7602 	   broken, and that we will (eventually) return to the dummy
7603 	   frame.
7604 
7605 	   It might be tempting to consider using frame_id_inner here, but
7606 	   that is not safe.   There is no guarantee that the stack frames
7607 	   we are looking at here are even on the same stack as the
7608 	   original dummy frame, hence frame_id_inner can't be used.  See
7609 	   the comments on frame_id_inner for more details.  */
7610 	bool unwind_finished_unexpectedly = false;
7611 	for (frame_info_ptr fi = get_current_frame (); fi != nullptr; )
7612 	  {
7613 	    frame_info_ptr prev = get_prev_frame (fi);
7614 	    if (prev == nullptr)
7615 	      {
7616 		/* FI is the last stack frame.  Why did this frame not
7617 		   unwind further?  */
7618 		auto stop_reason = get_frame_unwind_stop_reason (fi);
7619 		if (stop_reason != UNWIND_NO_REASON
7620 		    && stop_reason != UNWIND_OUTERMOST)
7621 		  unwind_finished_unexpectedly = true;
7622 	      }
7623 	    fi = prev;
7624 	  }
7625 	if (unwind_finished_unexpectedly)
7626 	  continue;
7627 
7628 	dummy_frame_discard (dummy_b->frame_id, tp);
7629 
7630 	while (b->related_breakpoint != b)
7631 	  {
7632 	    if (b_tmp == b->related_breakpoint)
7633 	      b_tmp = b->related_breakpoint->next;
7634 	    delete_breakpoint (b->related_breakpoint);
7635 	  }
7636 	delete_breakpoint (b);
7637       }
7638 }
7639 
7640 void
7641 enable_overlay_breakpoints (void)
7642 {
7643   for (breakpoint *b : all_breakpoints ())
7644     if (b->type == bp_overlay_event)
7645       {
7646 	b->enable_state = bp_enabled;
7647 	update_global_location_list (UGLL_MAY_INSERT);
7648 	overlay_events_enabled = 1;
7649       }
7650 }
7651 
7652 void
7653 disable_overlay_breakpoints (void)
7654 {
7655   for (breakpoint *b : all_breakpoints ())
7656     if (b->type == bp_overlay_event)
7657       {
7658 	b->enable_state = bp_disabled;
7659 	update_global_location_list (UGLL_DONT_INSERT);
7660 	overlay_events_enabled = 0;
7661       }
7662 }
7663 
7664 /* Set an active std::terminate breakpoint for each std::terminate
7665    master breakpoint.  */
7666 void
7667 set_std_terminate_breakpoint (void)
7668 {
7669   for (breakpoint *b : all_breakpoints_safe ())
7670     if (b->pspace == current_program_space
7671 	&& b->type == bp_std_terminate_master)
7672       {
7673 	momentary_breakpoint_from_master (b, bp_std_terminate, 1,
7674 					  inferior_thread ()->global_num);
7675       }
7676 }
7677 
7678 /* Delete all the std::terminate breakpoints.  */
7679 void
7680 delete_std_terminate_breakpoint (void)
7681 {
7682   for (breakpoint *b : all_breakpoints_safe ())
7683     if (b->type == bp_std_terminate)
7684       delete_breakpoint (b);
7685 }
7686 
7687 struct breakpoint *
7688 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7689 {
7690   struct breakpoint *b;
7691 
7692   b = create_internal_breakpoint (gdbarch, address, bp_thread_event);
7693 
7694   b->enable_state = bp_enabled;
7695   /* locspec has to be used or breakpoint_re_set will delete me.  */
7696   b->locspec = new_address_location_spec (b->loc->address, NULL, 0);
7697 
7698   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7699 
7700   return b;
7701 }
7702 
7703 struct lang_and_radix
7704   {
7705     enum language lang;
7706     int radix;
7707   };
7708 
7709 /* Create a breakpoint for JIT code registration and unregistration.  */
7710 
7711 struct breakpoint *
7712 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7713 {
7714   return create_internal_breakpoint (gdbarch, address, bp_jit_event);
7715 }
7716 
7717 /* Remove JIT code registration and unregistration breakpoint(s).  */
7718 
7719 void
7720 remove_jit_event_breakpoints (void)
7721 {
7722   for (breakpoint *b : all_breakpoints_safe ())
7723     if (b->type == bp_jit_event
7724 	&& b->loc->pspace == current_program_space)
7725       delete_breakpoint (b);
7726 }
7727 
7728 void
7729 remove_solib_event_breakpoints (void)
7730 {
7731   for (breakpoint *b : all_breakpoints_safe ())
7732     if (b->type == bp_shlib_event
7733 	&& b->loc->pspace == current_program_space)
7734       delete_breakpoint (b);
7735 }
7736 
7737 /* See breakpoint.h.  */
7738 
7739 void
7740 remove_solib_event_breakpoints_at_next_stop (void)
7741 {
7742   for (breakpoint *b : all_breakpoints_safe ())
7743     if (b->type == bp_shlib_event
7744 	&& b->loc->pspace == current_program_space)
7745       b->disposition = disp_del_at_next_stop;
7746 }
7747 
7748 /* Helper for create_solib_event_breakpoint /
7749    create_and_insert_solib_event_breakpoint.  Allows specifying which
7750    INSERT_MODE to pass through to update_global_location_list.  */
7751 
7752 static struct breakpoint *
7753 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7754 				 enum ugll_insert_mode insert_mode)
7755 {
7756   struct breakpoint *b;
7757 
7758   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event);
7759   update_global_location_list_nothrow (insert_mode);
7760   return b;
7761 }
7762 
7763 struct breakpoint *
7764 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7765 {
7766   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7767 }
7768 
7769 /* See breakpoint.h.  */
7770 
7771 struct breakpoint *
7772 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7773 {
7774   struct breakpoint *b;
7775 
7776   /* Explicitly tell update_global_location_list to insert
7777      locations.  */
7778   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7779   if (!b->loc->inserted)
7780     {
7781       delete_breakpoint (b);
7782       return NULL;
7783     }
7784   return b;
7785 }
7786 
7787 /* Disable any breakpoints that are on code in shared libraries.  Only
7788    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7789 
7790 void
7791 disable_breakpoints_in_shlibs (void)
7792 {
7793   for (bp_location *loc : all_bp_locations ())
7794     {
7795       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7796       struct breakpoint *b = loc->owner;
7797 
7798       /* We apply the check to all breakpoints, including disabled for
7799 	 those with loc->duplicate set.  This is so that when breakpoint
7800 	 becomes enabled, or the duplicate is removed, gdb will try to
7801 	 insert all breakpoints.  If we don't set shlib_disabled here,
7802 	 we'll try to insert those breakpoints and fail.  */
7803       if (((b->type == bp_breakpoint)
7804 	   || (b->type == bp_jit_event)
7805 	   || (b->type == bp_hardware_breakpoint)
7806 	   || (is_tracepoint (b)))
7807 	  && loc->pspace == current_program_space
7808 	  && !loc->shlib_disabled
7809 	  && solib_name_from_address (loc->pspace, loc->address)
7810 	  )
7811 	{
7812 	  loc->shlib_disabled = 1;
7813 	}
7814     }
7815 }
7816 
7817 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7818    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7819    disabled ones can just stay disabled.  */
7820 
7821 static void
7822 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7823 {
7824   bool disabled_shlib_breaks = false;
7825 
7826   for (bp_location *loc : all_bp_locations ())
7827     {
7828       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7829       struct breakpoint *b = loc->owner;
7830 
7831       if (solib->pspace == loc->pspace
7832 	  && !loc->shlib_disabled
7833 	  && (((b->type == bp_breakpoint
7834 		|| b->type == bp_jit_event
7835 		|| b->type == bp_hardware_breakpoint)
7836 	       && (loc->loc_type == bp_loc_hardware_breakpoint
7837 		   || loc->loc_type == bp_loc_software_breakpoint))
7838 	      || is_tracepoint (b))
7839 	  && solib_contains_address_p (solib, loc->address))
7840 	{
7841 	  loc->shlib_disabled = 1;
7842 	  /* At this point, we cannot rely on remove_breakpoint
7843 	     succeeding so we must mark the breakpoint as not inserted
7844 	     to prevent future errors occurring in remove_breakpoints.  */
7845 	  loc->inserted = 0;
7846 
7847 	  /* This may cause duplicate notifications for the same breakpoint.  */
7848 	  gdb::observers::breakpoint_modified.notify (b);
7849 
7850 	  if (!disabled_shlib_breaks)
7851 	    {
7852 	      target_terminal::ours_for_output ();
7853 	      warning (_("Temporarily disabling breakpoints "
7854 			 "for unloaded shared library \"%s\""),
7855 		       solib->so_name);
7856 	    }
7857 	  disabled_shlib_breaks = true;
7858 	}
7859     }
7860 }
7861 
7862 /* Disable any breakpoints and tracepoints in OBJFILE upon
7863    notification of free_objfile.  Only apply to enabled breakpoints,
7864    disabled ones can just stay disabled.  */
7865 
7866 static void
7867 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7868 {
7869   if (objfile == NULL)
7870     return;
7871 
7872   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7873      managed by the user with add-symbol-file/remove-symbol-file.
7874      Similarly to how breakpoints in shared libraries are handled in
7875      response to "nosharedlibrary", mark breakpoints in such modules
7876      shlib_disabled so they end up uninserted on the next global
7877      location list update.  Shared libraries not loaded by the user
7878      aren't handled here -- they're already handled in
7879      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7880      solib_unloaded observer.  We skip objfiles that are not
7881      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7882      main objfile).  */
7883   if ((objfile->flags & OBJF_SHARED) == 0
7884       || (objfile->flags & OBJF_USERLOADED) == 0)
7885     return;
7886 
7887   for (breakpoint *b : all_breakpoints ())
7888     {
7889       bool bp_modified = false;
7890 
7891       if (!is_breakpoint (b) && !is_tracepoint (b))
7892 	continue;
7893 
7894       for (bp_location *loc : b->locations ())
7895 	{
7896 	  CORE_ADDR loc_addr = loc->address;
7897 
7898 	  if (loc->loc_type != bp_loc_hardware_breakpoint
7899 	      && loc->loc_type != bp_loc_software_breakpoint)
7900 	    continue;
7901 
7902 	  if (loc->shlib_disabled != 0)
7903 	    continue;
7904 
7905 	  if (objfile->pspace != loc->pspace)
7906 	    continue;
7907 
7908 	  if (loc->loc_type != bp_loc_hardware_breakpoint
7909 	      && loc->loc_type != bp_loc_software_breakpoint)
7910 	    continue;
7911 
7912 	  if (is_addr_in_objfile (loc_addr, objfile))
7913 	    {
7914 	      loc->shlib_disabled = 1;
7915 	      /* At this point, we don't know whether the object was
7916 		 unmapped from the inferior or not, so leave the
7917 		 inserted flag alone.  We'll handle failure to
7918 		 uninsert quietly, in case the object was indeed
7919 		 unmapped.  */
7920 
7921 	      mark_breakpoint_location_modified (loc);
7922 
7923 	      bp_modified = true;
7924 	    }
7925 	}
7926 
7927       if (bp_modified)
7928 	gdb::observers::breakpoint_modified.notify (b);
7929     }
7930 }
7931 
7932 /* See breakpoint.h.  */
7933 
7934 breakpoint::breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
7935 			bool temp, const char *cond_string_)
7936   : type (bptype),
7937     disposition (temp ? disp_del : disp_donttouch),
7938     gdbarch (gdbarch_),
7939     language (current_language->la_language),
7940     input_radix (::input_radix),
7941     cond_string (cond_string_ != nullptr
7942 		 ? make_unique_xstrdup (cond_string_)
7943 		 : nullptr),
7944     related_breakpoint (this)
7945 {
7946 }
7947 
7948 /* See breakpoint.h.  */
7949 
7950 catchpoint::catchpoint (struct gdbarch *gdbarch, bool temp,
7951 			const char *cond_string)
7952   : breakpoint (gdbarch, bp_catchpoint, temp, cond_string)
7953 {
7954   add_dummy_location (this, current_program_space);
7955 
7956   pspace = current_program_space;
7957 }
7958 
7959 void
7960 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
7961 {
7962   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
7963   set_breakpoint_number (internal, b);
7964   if (is_tracepoint (b))
7965     set_tracepoint_count (breakpoint_count);
7966   if (!internal)
7967     mention (b);
7968   gdb::observers::breakpoint_created.notify (b);
7969 
7970   if (update_gll)
7971     update_global_location_list (UGLL_MAY_INSERT);
7972 }
7973 
7974 static int
7975 hw_breakpoint_used_count (void)
7976 {
7977   int i = 0;
7978 
7979   for (breakpoint *b : all_breakpoints ())
7980     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
7981       for (bp_location *bl : b->locations ())
7982 	{
7983 	  /* Special types of hardware breakpoints may use more than
7984 	     one register.  */
7985 	  i += b->resources_needed (bl);
7986 	}
7987 
7988   return i;
7989 }
7990 
7991 /* Returns the resources B would use if it were a hardware
7992    watchpoint.  */
7993 
7994 static int
7995 hw_watchpoint_use_count (struct breakpoint *b)
7996 {
7997   int i = 0;
7998 
7999   if (!breakpoint_enabled (b))
8000     return 0;
8001 
8002   for (bp_location *bl : b->locations ())
8003     {
8004       /* Special types of hardware watchpoints may use more than
8005 	 one register.  */
8006       i += b->resources_needed (bl);
8007     }
8008 
8009   return i;
8010 }
8011 
8012 /* Returns the sum the used resources of all hardware watchpoints of
8013    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8014    the sum of the used resources of all hardware watchpoints of other
8015    types _not_ TYPE.  */
8016 
8017 static int
8018 hw_watchpoint_used_count_others (struct breakpoint *except,
8019 				 enum bptype type, int *other_type_used)
8020 {
8021   int i = 0;
8022 
8023   *other_type_used = 0;
8024   for (breakpoint *b : all_breakpoints ())
8025     {
8026       if (b == except)
8027 	continue;
8028       if (!breakpoint_enabled (b))
8029 	continue;
8030 
8031       if (b->type == type)
8032 	i += hw_watchpoint_use_count (b);
8033       else if (is_hardware_watchpoint (b))
8034 	*other_type_used = 1;
8035     }
8036 
8037   return i;
8038 }
8039 
8040 void
8041 disable_watchpoints_before_interactive_call_start (void)
8042 {
8043   for (breakpoint *b : all_breakpoints ())
8044     if (is_watchpoint (b) && breakpoint_enabled (b))
8045       {
8046 	b->enable_state = bp_call_disabled;
8047 	update_global_location_list (UGLL_DONT_INSERT);
8048       }
8049 }
8050 
8051 void
8052 enable_watchpoints_after_interactive_call_stop (void)
8053 {
8054   for (breakpoint *b : all_breakpoints ())
8055     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8056       {
8057 	b->enable_state = bp_enabled;
8058 	update_global_location_list (UGLL_MAY_INSERT);
8059       }
8060 }
8061 
8062 void
8063 disable_breakpoints_before_startup (void)
8064 {
8065   current_program_space->executing_startup = 1;
8066   update_global_location_list (UGLL_DONT_INSERT);
8067 }
8068 
8069 void
8070 enable_breakpoints_after_startup (void)
8071 {
8072   current_program_space->executing_startup = 0;
8073   breakpoint_re_set ();
8074 }
8075 
8076 /* Allocate a new momentary breakpoint.  */
8077 
8078 template<typename... Arg>
8079 static momentary_breakpoint *
8080 new_momentary_breakpoint (struct gdbarch *gdbarch, enum bptype type,
8081 			  Arg&&... args)
8082 {
8083   if (type == bp_longjmp || type == bp_exception)
8084     return new longjmp_breakpoint (gdbarch, type,
8085 				   std::forward<Arg> (args)...);
8086   else
8087     return new momentary_breakpoint (gdbarch, type,
8088 				     std::forward<Arg> (args)...);
8089 }
8090 
8091 /* Set a momentary breakpoint of type TYPE at address specified by
8092    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8093    frame.  */
8094 
8095 breakpoint_up
8096 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8097 			  struct frame_id frame_id, enum bptype type)
8098 {
8099   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8100      tail-called one.  */
8101   gdb_assert (!frame_id_artificial_p (frame_id));
8102 
8103   std::unique_ptr<momentary_breakpoint> b
8104     (new_momentary_breakpoint (gdbarch, type, sal.pspace, frame_id,
8105 			       inferior_thread ()->global_num));
8106 
8107   b->add_location (sal);
8108 
8109   breakpoint_up bp (add_to_breakpoint_chain (std::move (b)));
8110 
8111   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8112 
8113   return bp;
8114 }
8115 
8116 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8117    The new breakpoint will have type TYPE, use OPS as its
8118    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8119 
8120 static struct breakpoint *
8121 momentary_breakpoint_from_master (struct breakpoint *orig,
8122 				  enum bptype type,
8123 				  int loc_enabled,
8124 				  int thread)
8125 {
8126   std::unique_ptr<breakpoint> copy
8127     (new_momentary_breakpoint (orig->gdbarch, type, orig->pspace,
8128 			       orig->frame_id, thread));
8129   copy->loc = copy->allocate_location ();
8130   set_breakpoint_location_function (copy->loc);
8131 
8132   copy->loc->gdbarch = orig->loc->gdbarch;
8133   copy->loc->requested_address = orig->loc->requested_address;
8134   copy->loc->address = orig->loc->address;
8135   copy->loc->section = orig->loc->section;
8136   copy->loc->pspace = orig->loc->pspace;
8137   copy->loc->probe = orig->loc->probe;
8138   copy->loc->line_number = orig->loc->line_number;
8139   copy->loc->symtab = orig->loc->symtab;
8140   copy->loc->enabled = loc_enabled;
8141 
8142   breakpoint *b = add_to_breakpoint_chain (std::move (copy));
8143   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8144   return b;
8145 }
8146 
8147 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8148    ORIG is NULL.  */
8149 
8150 struct breakpoint *
8151 clone_momentary_breakpoint (struct breakpoint *orig)
8152 {
8153   /* If there's nothing to clone, then return nothing.  */
8154   if (orig == NULL)
8155     return NULL;
8156 
8157   return momentary_breakpoint_from_master (orig, orig->type, 0,
8158 					   orig->thread);
8159 }
8160 
8161 breakpoint_up
8162 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8163 				enum bptype type)
8164 {
8165   struct symtab_and_line sal;
8166 
8167   sal = find_pc_line (pc, 0);
8168   sal.pc = pc;
8169   sal.section = find_pc_overlay (pc);
8170   sal.explicit_pc = 1;
8171 
8172   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8173 }
8174 
8175 
8176 /* Tell the user we have just set a breakpoint B.  */
8177 
8178 static void
8179 mention (const breakpoint *b)
8180 {
8181   b->print_mention ();
8182   current_uiout->text ("\n");
8183 }
8184 
8185 
8186 static bool bp_loc_is_permanent (struct bp_location *loc);
8187 
8188 /* Handle "set breakpoint auto-hw on".
8189 
8190    If the explicitly specified breakpoint type is not hardware
8191    breakpoint, check the memory map to see whether the breakpoint
8192    address is in read-only memory.
8193 
8194    - location type is not hardware breakpoint, memory is read-only.
8195    We change the type of the location to hardware breakpoint.
8196 
8197    - location type is hardware breakpoint, memory is read-write.  This
8198    means we've previously made the location hardware one, but then the
8199    memory map changed, so we undo.
8200 */
8201 
8202 static void
8203 handle_automatic_hardware_breakpoints (bp_location *bl)
8204 {
8205   if (automatic_hardware_breakpoints
8206       && bl->owner->type != bp_hardware_breakpoint
8207       && (bl->loc_type == bp_loc_software_breakpoint
8208 	  || bl->loc_type == bp_loc_hardware_breakpoint))
8209     {
8210       /* When breakpoints are removed, remove_breakpoints will use
8211 	 location types we've just set here, the only possible problem
8212 	 is that memory map has changed during running program, but
8213 	 it's not going to work anyway with current gdb.  */
8214       mem_region *mr = lookup_mem_region (bl->address);
8215 
8216       if (mr != nullptr)
8217 	{
8218 	  enum bp_loc_type new_type;
8219 
8220 	  if (mr->attrib.mode != MEM_RW)
8221 	    new_type = bp_loc_hardware_breakpoint;
8222 	  else
8223 	    new_type = bp_loc_software_breakpoint;
8224 
8225 	  if (new_type != bl->loc_type)
8226 	    {
8227 	      static bool said = false;
8228 
8229 	      bl->loc_type = new_type;
8230 	      if (!said)
8231 		{
8232 		  gdb_printf (_("Note: automatically using "
8233 				"hardware breakpoints for "
8234 				"read-only addresses.\n"));
8235 		  said = true;
8236 		}
8237 	    }
8238 	}
8239     }
8240 }
8241 
8242 bp_location *
8243 code_breakpoint::add_location (const symtab_and_line &sal)
8244 {
8245   struct bp_location *new_loc, **tmp;
8246   CORE_ADDR adjusted_address;
8247   struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8248 
8249   if (loc_gdbarch == NULL)
8250     loc_gdbarch = gdbarch;
8251 
8252   /* Adjust the breakpoint's address prior to allocating a location.
8253      Once we call allocate_location(), that mostly uninitialized
8254      location will be placed on the location chain.  Adjustment of the
8255      breakpoint may cause target_read_memory() to be called and we do
8256      not want its scan of the location chain to find a breakpoint and
8257      location that's only been partially initialized.  */
8258   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8259 						sal.pc, type,
8260 						sal.pspace);
8261 
8262   /* Sort the locations by their ADDRESS.  */
8263   new_loc = allocate_location ();
8264   for (tmp = &(loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8265        tmp = &((*tmp)->next))
8266     ;
8267   new_loc->next = *tmp;
8268   *tmp = new_loc;
8269 
8270   new_loc->requested_address = sal.pc;
8271   new_loc->address = adjusted_address;
8272   new_loc->pspace = sal.pspace;
8273   new_loc->probe.prob = sal.prob;
8274   new_loc->probe.objfile = sal.objfile;
8275   gdb_assert (new_loc->pspace != NULL);
8276   new_loc->section = sal.section;
8277   new_loc->gdbarch = loc_gdbarch;
8278   new_loc->line_number = sal.line;
8279   new_loc->symtab = sal.symtab;
8280   new_loc->symbol = sal.symbol;
8281   new_loc->msymbol = sal.msymbol;
8282   new_loc->objfile = sal.objfile;
8283 
8284   set_breakpoint_location_function (new_loc);
8285 
8286   /* While by definition, permanent breakpoints are already present in the
8287      code, we don't mark the location as inserted.  Normally one would expect
8288      that GDB could rely on that breakpoint instruction to stop the program,
8289      thus removing the need to insert its own breakpoint, except that executing
8290      the breakpoint instruction can kill the target instead of reporting a
8291      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8292      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8293      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8294      breakpoint be inserted normally results in QEMU knowing about the GDB
8295      breakpoint, and thus trap before the breakpoint instruction is executed.
8296      (If GDB later needs to continue execution past the permanent breakpoint,
8297      it manually increments the PC, thus avoiding executing the breakpoint
8298      instruction.)  */
8299   if (bp_loc_is_permanent (new_loc))
8300     new_loc->permanent = 1;
8301 
8302   return new_loc;
8303 }
8304 
8305 
8306 /* Return true if LOC is pointing to a permanent breakpoint,
8307    return false otherwise.  */
8308 
8309 static bool
8310 bp_loc_is_permanent (struct bp_location *loc)
8311 {
8312   gdb_assert (loc != NULL);
8313 
8314   /* If we have a non-breakpoint-backed catchpoint or a software
8315      watchpoint, just return 0.  We should not attempt to read from
8316      the addresses the locations of these breakpoint types point to.
8317      gdbarch_program_breakpoint_here_p, below, will attempt to read
8318      memory.  */
8319   if (!bl_address_is_meaningful (loc))
8320     return false;
8321 
8322   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8323   switch_to_program_space_and_thread (loc->pspace);
8324   return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8325 }
8326 
8327 /* Build a command list for the dprintf corresponding to the current
8328    settings of the dprintf style options.  */
8329 
8330 static void
8331 update_dprintf_command_list (struct breakpoint *b)
8332 {
8333   const char *dprintf_args = b->extra_string.get ();
8334   gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
8335 
8336   if (!dprintf_args)
8337     return;
8338 
8339   dprintf_args = skip_spaces (dprintf_args);
8340 
8341   /* Allow a comma, as it may have terminated a location, but don't
8342      insist on it.  */
8343   if (*dprintf_args == ',')
8344     ++dprintf_args;
8345   dprintf_args = skip_spaces (dprintf_args);
8346 
8347   if (*dprintf_args != '"')
8348     error (_("Bad format string, missing '\"'."));
8349 
8350   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8351     printf_line = xstrprintf ("printf %s", dprintf_args);
8352   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8353     {
8354       if (dprintf_function.empty ())
8355 	error (_("No function supplied for dprintf call"));
8356 
8357       if (!dprintf_channel.empty ())
8358 	printf_line = xstrprintf ("call (void) %s (%s,%s)",
8359 				  dprintf_function.c_str (),
8360 				  dprintf_channel.c_str (),
8361 				  dprintf_args);
8362       else
8363 	printf_line = xstrprintf ("call (void) %s (%s)",
8364 				  dprintf_function.c_str (),
8365 				  dprintf_args);
8366     }
8367   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8368     {
8369       if (target_can_run_breakpoint_commands ())
8370 	printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8371       else
8372 	{
8373 	  warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8374 	  printf_line = xstrprintf ("printf %s", dprintf_args);
8375 	}
8376     }
8377   else
8378     internal_error (_("Invalid dprintf style."));
8379 
8380   gdb_assert (printf_line != NULL);
8381 
8382   /* Manufacture a printf sequence.  */
8383   struct command_line *printf_cmd_line
8384     = new struct command_line (simple_control, printf_line.release ());
8385   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8386 						    command_lines_deleter ()));
8387 }
8388 
8389 /* Update all dprintf commands, making their command lists reflect
8390    current style settings.  */
8391 
8392 static void
8393 update_dprintf_commands (const char *args, int from_tty,
8394 			 struct cmd_list_element *c)
8395 {
8396   for (breakpoint *b : all_breakpoints ())
8397     if (b->type == bp_dprintf)
8398 	update_dprintf_command_list (b);
8399 }
8400 
8401 code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
8402 				  enum bptype type_,
8403 				  gdb::array_view<const symtab_and_line> sals,
8404 				  location_spec_up &&locspec_,
8405 				  gdb::unique_xmalloc_ptr<char> filter_,
8406 				  gdb::unique_xmalloc_ptr<char> cond_string_,
8407 				  gdb::unique_xmalloc_ptr<char> extra_string_,
8408 				  enum bpdisp disposition_,
8409 				  int thread_, int task_, int ignore_count_,
8410 				  int from_tty,
8411 				  int enabled_, unsigned flags,
8412 				  int display_canonical_)
8413   : breakpoint (gdbarch_, type_)
8414 {
8415   int i;
8416 
8417   if (type == bp_hardware_breakpoint)
8418     {
8419       int target_resources_ok;
8420 
8421       i = hw_breakpoint_used_count ();
8422       target_resources_ok =
8423 	target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8424 					    i + 1, 0);
8425       if (target_resources_ok == 0)
8426 	error (_("No hardware breakpoint support in the target."));
8427       else if (target_resources_ok < 0)
8428 	error (_("Hardware breakpoints used exceeds limit."));
8429     }
8430 
8431   gdb_assert (!sals.empty ());
8432 
8433   thread = thread_;
8434   task = task_;
8435 
8436   cond_string = std::move (cond_string_);
8437   extra_string = std::move (extra_string_);
8438   ignore_count = ignore_count_;
8439   enable_state = enabled_ ? bp_enabled : bp_disabled;
8440   disposition = disposition_;
8441 
8442   if (type == bp_static_tracepoint
8443       || type == bp_static_marker_tracepoint)
8444     {
8445       auto *t = gdb::checked_static_cast<struct tracepoint *> (this);
8446       struct static_tracepoint_marker marker;
8447 
8448       if (strace_marker_p (this))
8449 	{
8450 	  /* We already know the marker exists, otherwise, we wouldn't
8451 	     see a sal for it.  */
8452 	  const char *p = &locspec_->to_string ()[3];
8453 	  const char *endp;
8454 
8455 	  p = skip_spaces (p);
8456 
8457 	  endp = skip_to_space (p);
8458 
8459 	  t->static_trace_marker_id.assign (p, endp - p);
8460 
8461 	  gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8462 		      t->static_trace_marker_id.c_str ());
8463 	}
8464       else if (target_static_tracepoint_marker_at (sals[0].pc, &marker))
8465 	{
8466 	  t->static_trace_marker_id = std::move (marker.str_id);
8467 
8468 	  gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8469 		      t->static_trace_marker_id.c_str ());
8470 	}
8471       else
8472 	warning (_("Couldn't determine the static tracepoint marker to probe"));
8473     }
8474 
8475   for (const auto &sal : sals)
8476     {
8477       if (from_tty)
8478 	{
8479 	  struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8480 	  if (loc_gdbarch == nullptr)
8481 	    loc_gdbarch = gdbarch;
8482 
8483 	  describe_other_breakpoints (loc_gdbarch,
8484 				      sal.pspace, sal.pc, sal.section, thread);
8485 	}
8486 
8487       bp_location *new_loc = add_location (sal);
8488       if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8489 	new_loc->inserted = 1;
8490 
8491       /* Do not set breakpoint locations conditions yet.  As locations
8492 	 are inserted, they get sorted based on their addresses.  Let
8493 	 the list stabilize to have reliable location numbers.  */
8494 
8495       /* Dynamic printf requires and uses additional arguments on the
8496 	 command line, otherwise it's an error.  */
8497       if (type == bp_dprintf)
8498 	{
8499 	  if (extra_string != nullptr)
8500 	    update_dprintf_command_list (this);
8501 	  else
8502 	    error (_("Format string required"));
8503 	}
8504       else if (extra_string != nullptr)
8505 	error (_("Garbage '%s' at end of command"), extra_string.get ());
8506     }
8507 
8508   /* The order of the locations is now stable.  Set the location
8509      condition using the location's number.  */
8510   int loc_num = 1;
8511   for (bp_location *bl : locations ())
8512     {
8513       if (cond_string != nullptr)
8514 	set_breakpoint_location_condition (cond_string.get (), bl,
8515 					   number, loc_num);
8516 
8517       ++loc_num;
8518     }
8519 
8520   display_canonical = display_canonical_;
8521   if (locspec_ != nullptr)
8522     locspec = std::move (locspec_);
8523   else
8524     locspec = new_address_location_spec (this->loc->address, NULL, 0);
8525   filter = std::move (filter_);
8526 }
8527 
8528 static void
8529 create_breakpoint_sal (struct gdbarch *gdbarch,
8530 		       gdb::array_view<const symtab_and_line> sals,
8531 		       location_spec_up &&locspec,
8532 		       gdb::unique_xmalloc_ptr<char> filter,
8533 		       gdb::unique_xmalloc_ptr<char> cond_string,
8534 		       gdb::unique_xmalloc_ptr<char> extra_string,
8535 		       enum bptype type, enum bpdisp disposition,
8536 		       int thread, int task, int ignore_count,
8537 		       int from_tty,
8538 		       int enabled, int internal, unsigned flags,
8539 		       int display_canonical)
8540 {
8541   std::unique_ptr<code_breakpoint> b
8542     = new_breakpoint_from_type (gdbarch,
8543 				type,
8544 				sals,
8545 				std::move (locspec),
8546 				std::move (filter),
8547 				std::move (cond_string),
8548 				std::move (extra_string),
8549 				disposition,
8550 				thread, task, ignore_count,
8551 				from_tty,
8552 				enabled, flags,
8553 				display_canonical);
8554 
8555   install_breakpoint (internal, std::move (b), 0);
8556 }
8557 
8558 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8559    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8560    value.  COND_STRING, if not NULL, specified the condition to be
8561    used for all breakpoints.  Essentially the only case where
8562    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8563    function.  In that case, it's still not possible to specify
8564    separate conditions for different overloaded functions, so
8565    we take just a single condition string.
8566 
8567    NOTE: If the function succeeds, the caller is expected to cleanup
8568    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8569    array contents).  If the function fails (error() is called), the
8570    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8571    COND and SALS arrays and each of those arrays contents.  */
8572 
8573 static void
8574 create_breakpoints_sal (struct gdbarch *gdbarch,
8575 			struct linespec_result *canonical,
8576 			gdb::unique_xmalloc_ptr<char> cond_string,
8577 			gdb::unique_xmalloc_ptr<char> extra_string,
8578 			enum bptype type, enum bpdisp disposition,
8579 			int thread, int task, int ignore_count,
8580 			int from_tty,
8581 			int enabled, int internal, unsigned flags)
8582 {
8583   if (canonical->pre_expanded)
8584     gdb_assert (canonical->lsals.size () == 1);
8585 
8586   for (const auto &lsal : canonical->lsals)
8587     {
8588       /* Note that 'location' can be NULL in the case of a plain
8589 	 'break', without arguments.  */
8590       location_spec_up locspec
8591 	= (canonical->locspec != nullptr
8592 	   ? canonical->locspec->clone ()
8593 	   : nullptr);
8594       gdb::unique_xmalloc_ptr<char> filter_string
8595 	(lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8596 
8597       create_breakpoint_sal (gdbarch, lsal.sals,
8598 			     std::move (locspec),
8599 			     std::move (filter_string),
8600 			     std::move (cond_string),
8601 			     std::move (extra_string),
8602 			     type, disposition,
8603 			     thread, task, ignore_count,
8604 			     from_tty, enabled, internal, flags,
8605 			     canonical->special_display);
8606     }
8607 }
8608 
8609 /* Parse LOCSPEC which is assumed to be a SAL specification possibly
8610    followed by conditionals.  On return, SALS contains an array of SAL
8611    addresses found.  LOCSPEC points to the end of the SAL (for
8612    linespec locspecs).
8613 
8614    The array and the line spec strings are allocated on the heap, it is
8615    the caller's responsibility to free them.  */
8616 
8617 static void
8618 parse_breakpoint_sals (location_spec *locspec,
8619 		       struct linespec_result *canonical)
8620 {
8621   struct symtab_and_line cursal;
8622 
8623   if (locspec->type () == LINESPEC_LOCATION_SPEC)
8624     {
8625       const char *spec = as_linespec_location_spec (locspec)->spec_string;
8626 
8627       if (spec == NULL)
8628 	{
8629 	  /* The last displayed codepoint, if it's valid, is our default
8630 	     breakpoint address.  */
8631 	  if (last_displayed_sal_is_valid ())
8632 	    {
8633 	      /* Set sal's pspace, pc, symtab, and line to the values
8634 		 corresponding to the last call to print_frame_info.
8635 		 Be sure to reinitialize LINE with NOTCURRENT == 0
8636 		 as the breakpoint line number is inappropriate otherwise.
8637 		 find_pc_line would adjust PC, re-set it back.  */
8638 	      symtab_and_line sal = get_last_displayed_sal ();
8639 	      CORE_ADDR pc = sal.pc;
8640 
8641 	      sal = find_pc_line (pc, 0);
8642 
8643 	      /* "break" without arguments is equivalent to "break *PC"
8644 		 where PC is the last displayed codepoint's address.  So
8645 		 make sure to set sal.explicit_pc to prevent GDB from
8646 		 trying to expand the list of sals to include all other
8647 		 instances with the same symtab and line.  */
8648 	      sal.pc = pc;
8649 	      sal.explicit_pc = 1;
8650 
8651 	      struct linespec_sals lsal;
8652 	      lsal.sals = {sal};
8653 	      lsal.canonical = NULL;
8654 
8655 	      canonical->lsals.push_back (std::move (lsal));
8656 	      return;
8657 	    }
8658 	  else
8659 	    error (_("No default breakpoint address now."));
8660 	}
8661     }
8662 
8663   /* Force almost all breakpoints to be in terms of the
8664      current_source_symtab (which is decode_line_1's default).
8665      This should produce the results we want almost all of the
8666      time while leaving default_breakpoint_* alone.
8667 
8668      ObjC: However, don't match an Objective-C method name which
8669      may have a '+' or '-' succeeded by a '['.  */
8670   cursal = get_current_source_symtab_and_line ();
8671   if (last_displayed_sal_is_valid ())
8672     {
8673       const char *spec = NULL;
8674 
8675       if (locspec->type () == LINESPEC_LOCATION_SPEC)
8676 	spec = as_linespec_location_spec (locspec)->spec_string;
8677 
8678       if (!cursal.symtab
8679 	  || (spec != NULL
8680 	      && strchr ("+-", spec[0]) != NULL
8681 	      && spec[1] != '['))
8682 	{
8683 	  decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8684 			    get_last_displayed_symtab (),
8685 			    get_last_displayed_line (),
8686 			    canonical, NULL, NULL);
8687 	  return;
8688 	}
8689     }
8690 
8691   decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8692 		    cursal.symtab, cursal.line, canonical, NULL, NULL);
8693 }
8694 
8695 
8696 /* Convert each SAL into a real PC.  Verify that the PC can be
8697    inserted as a breakpoint.  If it can't throw an error.  */
8698 
8699 static void
8700 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
8701 {
8702   for (auto &sal : sals)
8703     resolve_sal_pc (&sal);
8704 }
8705 
8706 /* Fast tracepoints may have restrictions on valid locations.  For
8707    instance, a fast tracepoint using a jump instead of a trap will
8708    likely have to overwrite more bytes than a trap would, and so can
8709    only be placed where the instruction is longer than the jump, or a
8710    multi-instruction sequence does not have a jump into the middle of
8711    it, etc.  */
8712 
8713 static void
8714 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8715 			    gdb::array_view<const symtab_and_line> sals)
8716 {
8717   for (const auto &sal : sals)
8718     {
8719       struct gdbarch *sarch;
8720 
8721       sarch = get_sal_arch (sal);
8722       /* We fall back to GDBARCH if there is no architecture
8723 	 associated with SAL.  */
8724       if (sarch == NULL)
8725 	sarch = gdbarch;
8726       std::string msg;
8727       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
8728 	error (_("May not have a fast tracepoint at %s%s"),
8729 	       paddress (sarch, sal.pc), msg.c_str ());
8730     }
8731 }
8732 
8733 /* Given TOK, a string specification of condition and thread, as
8734    accepted by the 'break' command, extract the condition
8735    string and thread number and set *COND_STRING and *THREAD.
8736    PC identifies the context at which the condition should be parsed.
8737    If no condition is found, *COND_STRING is set to NULL.
8738    If no thread is found, *THREAD is set to -1.  */
8739 
8740 static void
8741 find_condition_and_thread (const char *tok, CORE_ADDR pc,
8742 			   gdb::unique_xmalloc_ptr<char> *cond_string,
8743 			   int *thread, int *task,
8744 			   gdb::unique_xmalloc_ptr<char> *rest)
8745 {
8746   cond_string->reset ();
8747   *thread = -1;
8748   *task = 0;
8749   rest->reset ();
8750   bool force = false;
8751 
8752   while (tok && *tok)
8753     {
8754       const char *end_tok;
8755       int toklen;
8756       const char *cond_start = NULL;
8757       const char *cond_end = NULL;
8758 
8759       tok = skip_spaces (tok);
8760 
8761       if ((*tok == '"' || *tok == ',') && rest)
8762 	{
8763 	  rest->reset (savestring (tok, strlen (tok)));
8764 	  return;
8765 	}
8766 
8767       end_tok = skip_to_space (tok);
8768 
8769       toklen = end_tok - tok;
8770 
8771       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8772 	{
8773 	  tok = cond_start = end_tok + 1;
8774 	  try
8775 	    {
8776 	      parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
8777 	    }
8778 	  catch (const gdb_exception_error &)
8779 	    {
8780 	      if (!force)
8781 		throw;
8782 	      else
8783 		tok = tok + strlen (tok);
8784 	    }
8785 	  cond_end = tok;
8786 	  cond_string->reset (savestring (cond_start, cond_end - cond_start));
8787 	}
8788       else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
8789 	{
8790 	  tok = tok + toklen;
8791 	  force = true;
8792 	}
8793       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8794 	{
8795 	  const char *tmptok;
8796 	  struct thread_info *thr;
8797 
8798 	  tok = end_tok + 1;
8799 	  thr = parse_thread_id (tok, &tmptok);
8800 	  if (tok == tmptok)
8801 	    error (_("Junk after thread keyword."));
8802 	  *thread = thr->global_num;
8803 	  tok = tmptok;
8804 	}
8805       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8806 	{
8807 	  char *tmptok;
8808 
8809 	  tok = end_tok + 1;
8810 	  *task = strtol (tok, &tmptok, 0);
8811 	  if (tok == tmptok)
8812 	    error (_("Junk after task keyword."));
8813 	  if (!valid_task_id (*task))
8814 	    error (_("Unknown task %d."), *task);
8815 	  tok = tmptok;
8816 	}
8817       else if (rest)
8818 	{
8819 	  rest->reset (savestring (tok, strlen (tok)));
8820 	  return;
8821 	}
8822       else
8823 	error (_("Junk at end of arguments."));
8824     }
8825 }
8826 
8827 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
8828    succeeds.  The parsed values are written to COND_STRING, THREAD,
8829    TASK, and REST.  See the comment of 'find_condition_and_thread'
8830    for the description of these parameters and INPUT.  */
8831 
8832 static void
8833 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
8834 				    const char *input,
8835 				    gdb::unique_xmalloc_ptr<char> *cond_string,
8836 				    int *thread, int *task,
8837 				    gdb::unique_xmalloc_ptr<char> *rest)
8838 {
8839   int num_failures = 0;
8840   for (auto &sal : sals)
8841     {
8842       gdb::unique_xmalloc_ptr<char> cond;
8843       int thread_id = 0;
8844       int task_id = 0;
8845       gdb::unique_xmalloc_ptr<char> remaining;
8846 
8847       /* Here we want to parse 'arg' to separate condition from thread
8848 	 number.  But because parsing happens in a context and the
8849 	 contexts of sals might be different, try each until there is
8850 	 success.  Finding one successful parse is sufficient for our
8851 	 goal.  When setting the breakpoint we'll re-parse the
8852 	 condition in the context of each sal.  */
8853       try
8854 	{
8855 	  find_condition_and_thread (input, sal.pc, &cond, &thread_id,
8856 				     &task_id, &remaining);
8857 	  *cond_string = std::move (cond);
8858 	  *thread = thread_id;
8859 	  *task = task_id;
8860 	  *rest = std::move (remaining);
8861 	  break;
8862 	}
8863       catch (const gdb_exception_error &e)
8864 	{
8865 	  num_failures++;
8866 	  /* If no sal remains, do not continue.  */
8867 	  if (num_failures == sals.size ())
8868 	    throw;
8869 	}
8870     }
8871 }
8872 
8873 /* Decode a static tracepoint marker spec.  */
8874 
8875 static std::vector<symtab_and_line>
8876 decode_static_tracepoint_spec (const char **arg_p)
8877 {
8878   const char *p = &(*arg_p)[3];
8879   const char *endp;
8880 
8881   p = skip_spaces (p);
8882 
8883   endp = skip_to_space (p);
8884 
8885   std::string marker_str (p, endp - p);
8886 
8887   std::vector<static_tracepoint_marker> markers
8888     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
8889   if (markers.empty ())
8890     error (_("No known static tracepoint marker named %s"),
8891 	   marker_str.c_str ());
8892 
8893   std::vector<symtab_and_line> sals;
8894   sals.reserve (markers.size ());
8895 
8896   for (const static_tracepoint_marker &marker : markers)
8897     {
8898       symtab_and_line sal = find_pc_line (marker.address, 0);
8899       sal.pc = marker.address;
8900       sals.push_back (sal);
8901    }
8902 
8903   *arg_p = endp;
8904   return sals;
8905 }
8906 
8907 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
8908    according to IS_TRACEPOINT.  */
8909 
8910 static const struct breakpoint_ops *
8911 breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
8912 				       bool is_tracepoint)
8913 {
8914   if (is_tracepoint)
8915     {
8916       if (locspec_type == PROBE_LOCATION_SPEC)
8917 	return &tracepoint_probe_breakpoint_ops;
8918       else
8919 	return &code_breakpoint_ops;
8920     }
8921   else
8922     {
8923       if (locspec_type == PROBE_LOCATION_SPEC)
8924 	return &bkpt_probe_breakpoint_ops;
8925       else
8926 	return &code_breakpoint_ops;
8927     }
8928 }
8929 
8930 /* See breakpoint.h.  */
8931 
8932 const struct breakpoint_ops *
8933 breakpoint_ops_for_location_spec (const location_spec *locspec,
8934 				  bool is_tracepoint)
8935 {
8936   if (locspec != nullptr)
8937     return (breakpoint_ops_for_location_spec_type
8938 	    (locspec->type (), is_tracepoint));
8939   return &code_breakpoint_ops;
8940 }
8941 
8942 /* See breakpoint.h.  */
8943 
8944 int
8945 create_breakpoint (struct gdbarch *gdbarch,
8946 		   location_spec *locspec,
8947 		   const char *cond_string,
8948 		   int thread, const char *extra_string,
8949 		   bool force_condition, int parse_extra,
8950 		   int tempflag, enum bptype type_wanted,
8951 		   int ignore_count,
8952 		   enum auto_boolean pending_break_support,
8953 		   const struct breakpoint_ops *ops,
8954 		   int from_tty, int enabled, int internal,
8955 		   unsigned flags)
8956 {
8957   struct linespec_result canonical;
8958   bool pending = false;
8959   int task = 0;
8960   int prev_bkpt_count = breakpoint_count;
8961 
8962   gdb_assert (ops != NULL);
8963 
8964   /* If extra_string isn't useful, set it to NULL.  */
8965   if (extra_string != NULL && *extra_string == '\0')
8966     extra_string = NULL;
8967 
8968   try
8969     {
8970       ops->create_sals_from_location_spec (locspec, &canonical);
8971     }
8972   catch (const gdb_exception_error &e)
8973     {
8974       /* If caller is interested in rc value from parse, set
8975 	 value.  */
8976       if (e.error == NOT_FOUND_ERROR)
8977 	{
8978 	  /* If pending breakpoint support is turned off, throw
8979 	     error.  */
8980 
8981 	  if (pending_break_support == AUTO_BOOLEAN_FALSE)
8982 	    throw;
8983 
8984 	  exception_print (gdb_stderr, e);
8985 
8986 	  /* If pending breakpoint support is auto query and the user
8987 	     selects no, then simply return the error code.  */
8988 	  if (pending_break_support == AUTO_BOOLEAN_AUTO
8989 	      && !nquery (_("Make %s pending on future shared library load? "),
8990 			  bptype_string (type_wanted)))
8991 	    return 0;
8992 
8993 	  /* At this point, either the user was queried about setting
8994 	     a pending breakpoint and selected yes, or pending
8995 	     breakpoint behavior is on and thus a pending breakpoint
8996 	     is defaulted on behalf of the user.  */
8997 	  pending = true;
8998 	}
8999       else
9000 	throw;
9001     }
9002 
9003   if (!pending && canonical.lsals.empty ())
9004     return 0;
9005 
9006   /* Resolve all line numbers to PC's and verify that the addresses
9007      are ok for the target.  */
9008   if (!pending)
9009     {
9010       for (auto &lsal : canonical.lsals)
9011 	breakpoint_sals_to_pc (lsal.sals);
9012     }
9013 
9014   /* Fast tracepoints may have additional restrictions on location.  */
9015   if (!pending && type_wanted == bp_fast_tracepoint)
9016     {
9017       for (const auto &lsal : canonical.lsals)
9018 	check_fast_tracepoint_sals (gdbarch, lsal.sals);
9019     }
9020 
9021   /* Verify that condition can be parsed, before setting any
9022      breakpoints.  Allocate a separate condition expression for each
9023      breakpoint.  */
9024   if (!pending)
9025     {
9026       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9027       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9028 
9029       if (parse_extra)
9030 	{
9031 	  gdb::unique_xmalloc_ptr<char> rest;
9032 	  gdb::unique_xmalloc_ptr<char> cond;
9033 
9034 	  const linespec_sals &lsal = canonical.lsals[0];
9035 
9036 	  find_condition_and_thread_for_sals (lsal.sals, extra_string,
9037 					      &cond, &thread, &task, &rest);
9038 	  cond_string_copy = std::move (cond);
9039 	  extra_string_copy = std::move (rest);
9040 	}
9041       else
9042 	{
9043 	  if (type_wanted != bp_dprintf
9044 	      && extra_string != NULL && *extra_string != '\0')
9045 		error (_("Garbage '%s' at end of location"), extra_string);
9046 
9047 	  /* Check the validity of the condition.  We should error out
9048 	     if the condition is invalid at all of the locations and
9049 	     if it is not forced.  In the PARSE_EXTRA case above, this
9050 	     check is done when parsing the EXTRA_STRING.  */
9051 	  if (cond_string != nullptr && !force_condition)
9052 	    {
9053 	      int num_failures = 0;
9054 	      const linespec_sals &lsal = canonical.lsals[0];
9055 	      for (const auto &sal : lsal.sals)
9056 		{
9057 		  const char *cond = cond_string;
9058 		  try
9059 		    {
9060 		      parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
9061 		      /* One success is sufficient to keep going.  */
9062 		      break;
9063 		    }
9064 		  catch (const gdb_exception_error &)
9065 		    {
9066 		      num_failures++;
9067 		      /* If this is the last sal, error out.  */
9068 		      if (num_failures == lsal.sals.size ())
9069 			throw;
9070 		    }
9071 		}
9072 	    }
9073 
9074 	  /* Create a private copy of condition string.  */
9075 	  if (cond_string)
9076 	    cond_string_copy.reset (xstrdup (cond_string));
9077 	  /* Create a private copy of any extra string.  */
9078 	  if (extra_string)
9079 	    extra_string_copy.reset (xstrdup (extra_string));
9080 	}
9081 
9082       ops->create_breakpoints_sal (gdbarch, &canonical,
9083 				   std::move (cond_string_copy),
9084 				   std::move (extra_string_copy),
9085 				   type_wanted,
9086 				   tempflag ? disp_del : disp_donttouch,
9087 				   thread, task, ignore_count,
9088 				   from_tty, enabled, internal, flags);
9089     }
9090   else
9091     {
9092       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (gdbarch,
9093 								 type_wanted);
9094       b->locspec = locspec->clone ();
9095 
9096       if (parse_extra)
9097 	b->cond_string = NULL;
9098       else
9099 	{
9100 	  /* Create a private copy of condition string.  */
9101 	  b->cond_string.reset (cond_string != NULL
9102 				? xstrdup (cond_string)
9103 				: NULL);
9104 	  b->thread = thread;
9105 	}
9106 
9107       /* Create a private copy of any extra string.  */
9108       b->extra_string.reset (extra_string != NULL
9109 			     ? xstrdup (extra_string)
9110 			     : NULL);
9111       b->ignore_count = ignore_count;
9112       b->disposition = tempflag ? disp_del : disp_donttouch;
9113       b->condition_not_parsed = 1;
9114       b->enable_state = enabled ? bp_enabled : bp_disabled;
9115       if ((type_wanted != bp_breakpoint
9116 	   && type_wanted != bp_hardware_breakpoint) || thread != -1)
9117 	b->pspace = current_program_space;
9118 
9119       install_breakpoint (internal, std::move (b), 0);
9120     }
9121 
9122   if (canonical.lsals.size () > 1)
9123     {
9124       warning (_("Multiple breakpoints were set.\nUse the "
9125 		 "\"delete\" command to delete unwanted breakpoints."));
9126       prev_breakpoint_count = prev_bkpt_count;
9127     }
9128 
9129   update_global_location_list (UGLL_MAY_INSERT);
9130 
9131   return 1;
9132 }
9133 
9134 /* Set a breakpoint.
9135    ARG is a string describing breakpoint address,
9136    condition, and thread.
9137    FLAG specifies if a breakpoint is hardware on,
9138    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9139    and BP_TEMPFLAG.  */
9140 
9141 static void
9142 break_command_1 (const char *arg, int flag, int from_tty)
9143 {
9144   int tempflag = flag & BP_TEMPFLAG;
9145   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9146 			     ? bp_hardware_breakpoint
9147 			     : bp_breakpoint);
9148 
9149   location_spec_up locspec = string_to_location_spec (&arg, current_language);
9150   const struct breakpoint_ops *ops
9151     = breakpoint_ops_for_location_spec (locspec.get (),
9152 					false /* is_tracepoint */);
9153 
9154   create_breakpoint (get_current_arch (),
9155 		     locspec.get (),
9156 		     NULL, 0, arg, false, 1 /* parse arg */,
9157 		     tempflag, type_wanted,
9158 		     0 /* Ignore count */,
9159 		     pending_break_support,
9160 		     ops,
9161 		     from_tty,
9162 		     1 /* enabled */,
9163 		     0 /* internal */,
9164 		     0);
9165 }
9166 
9167 /* Helper function for break_command_1 and disassemble_command.  */
9168 
9169 void
9170 resolve_sal_pc (struct symtab_and_line *sal)
9171 {
9172   CORE_ADDR pc;
9173 
9174   if (sal->pc == 0 && sal->symtab != NULL)
9175     {
9176       if (!find_line_pc (sal->symtab, sal->line, &pc))
9177 	error (_("No line %d in file \"%s\"."),
9178 	       sal->line, symtab_to_filename_for_display (sal->symtab));
9179       sal->pc = pc;
9180 
9181       /* If this SAL corresponds to a breakpoint inserted using a line
9182 	 number, then skip the function prologue if necessary.  */
9183       if (sal->explicit_line)
9184 	skip_prologue_sal (sal);
9185     }
9186 
9187   if (sal->section == 0 && sal->symtab != NULL)
9188     {
9189       const struct blockvector *bv;
9190       const struct block *b;
9191       struct symbol *sym;
9192 
9193       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9194 				    sal->symtab->compunit ());
9195       if (bv != NULL)
9196 	{
9197 	  sym = block_linkage_function (b);
9198 	  if (sym != NULL)
9199 	    {
9200 	      fixup_symbol_section (sym, sal->symtab->compunit ()->objfile ());
9201 	      sal->section
9202 		= sym->obj_section (sal->symtab->compunit ()->objfile ());
9203 	    }
9204 	  else
9205 	    {
9206 	      /* It really is worthwhile to have the section, so we'll
9207 		 just have to look harder. This case can be executed
9208 		 if we have line numbers but no functions (as can
9209 		 happen in assembly source).  */
9210 
9211 	      scoped_restore_current_pspace_and_thread restore_pspace_thread;
9212 	      switch_to_program_space_and_thread (sal->pspace);
9213 
9214 	      bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9215 	      if (msym.minsym)
9216 		sal->section = msym.obj_section ();
9217 	    }
9218 	}
9219     }
9220 }
9221 
9222 void
9223 break_command (const char *arg, int from_tty)
9224 {
9225   break_command_1 (arg, 0, from_tty);
9226 }
9227 
9228 void
9229 tbreak_command (const char *arg, int from_tty)
9230 {
9231   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9232 }
9233 
9234 static void
9235 hbreak_command (const char *arg, int from_tty)
9236 {
9237   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9238 }
9239 
9240 static void
9241 thbreak_command (const char *arg, int from_tty)
9242 {
9243   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9244 }
9245 
9246 /* The dynamic printf command is mostly like a regular breakpoint, but
9247    with a prewired command list consisting of a single output command,
9248    built from extra arguments supplied on the dprintf command
9249    line.  */
9250 
9251 static void
9252 dprintf_command (const char *arg, int from_tty)
9253 {
9254   location_spec_up locspec = string_to_location_spec (&arg, current_language);
9255 
9256   /* If non-NULL, ARG should have been advanced past the location;
9257      the next character must be ','.  */
9258   if (arg != NULL)
9259     {
9260       if (arg[0] != ',' || arg[1] == '\0')
9261 	error (_("Format string required"));
9262       else
9263 	{
9264 	  /* Skip the comma.  */
9265 	  ++arg;
9266 	}
9267     }
9268 
9269   create_breakpoint (get_current_arch (),
9270 		     locspec.get (),
9271 		     NULL, 0, arg, false, 1 /* parse arg */,
9272 		     0, bp_dprintf,
9273 		     0 /* Ignore count */,
9274 		     pending_break_support,
9275 		     &code_breakpoint_ops,
9276 		     from_tty,
9277 		     1 /* enabled */,
9278 		     0 /* internal */,
9279 		     0);
9280 }
9281 
9282 static void
9283 agent_printf_command (const char *arg, int from_tty)
9284 {
9285   error (_("May only run agent-printf on the target"));
9286 }
9287 
9288 /* Implement the "breakpoint_hit" method for ranged breakpoints.  */
9289 
9290 int
9291 ranged_breakpoint::breakpoint_hit (const struct bp_location *bl,
9292 				   const address_space *aspace,
9293 				   CORE_ADDR bp_addr,
9294 				   const target_waitstatus &ws)
9295 {
9296   if (ws.kind () != TARGET_WAITKIND_STOPPED
9297       || ws.sig () != GDB_SIGNAL_TRAP)
9298     return 0;
9299 
9300   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9301 					 bl->length, aspace, bp_addr);
9302 }
9303 
9304 /* Implement the "resources_needed" method for ranged breakpoints.  */
9305 
9306 int
9307 ranged_breakpoint::resources_needed (const struct bp_location *bl)
9308 {
9309   return target_ranged_break_num_registers ();
9310 }
9311 
9312 /* Implement the "print_it" method for ranged breakpoints.  */
9313 
9314 enum print_stop_action
9315 ranged_breakpoint::print_it (const bpstat *bs) const
9316 {
9317   struct bp_location *bl = loc;
9318   struct ui_out *uiout = current_uiout;
9319 
9320   gdb_assert (type == bp_hardware_breakpoint);
9321 
9322   /* Ranged breakpoints have only one location.  */
9323   gdb_assert (bl && bl->next == NULL);
9324 
9325   annotate_breakpoint (number);
9326 
9327   maybe_print_thread_hit_breakpoint (uiout);
9328 
9329   if (disposition == disp_del)
9330     uiout->text ("Temporary ranged breakpoint ");
9331   else
9332     uiout->text ("Ranged breakpoint ");
9333   if (uiout->is_mi_like_p ())
9334     {
9335       uiout->field_string ("reason",
9336 		      async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9337       uiout->field_string ("disp", bpdisp_text (disposition));
9338     }
9339   print_num_locno (bs, uiout);
9340   uiout->text (", ");
9341 
9342   return PRINT_SRC_AND_LOC;
9343 }
9344 
9345 /* Implement the "print_one" method for ranged breakpoints.  */
9346 
9347 bool
9348 ranged_breakpoint::print_one (bp_location **last_loc) const
9349 {
9350   struct bp_location *bl = loc;
9351   struct value_print_options opts;
9352   struct ui_out *uiout = current_uiout;
9353 
9354   /* Ranged breakpoints have only one location.  */
9355   gdb_assert (bl && bl->next == NULL);
9356 
9357   get_user_print_options (&opts);
9358 
9359   if (opts.addressprint)
9360     /* We don't print the address range here, it will be printed later
9361        by ranged_breakpoint::print_one_detail.  */
9362     uiout->field_skip ("addr");
9363   annotate_field (5);
9364   print_breakpoint_location (this, bl);
9365   *last_loc = bl;
9366 
9367   return true;
9368 }
9369 
9370 /* Implement the "print_one_detail" method for ranged breakpoints.  */
9371 
9372 void
9373 ranged_breakpoint::print_one_detail (struct ui_out *uiout) const
9374 {
9375   CORE_ADDR address_start, address_end;
9376   struct bp_location *bl = loc;
9377   string_file stb;
9378 
9379   gdb_assert (bl);
9380 
9381   address_start = bl->address;
9382   address_end = address_start + bl->length - 1;
9383 
9384   uiout->text ("\taddress range: ");
9385   stb.printf ("[%s, %s]",
9386 	      print_core_address (bl->gdbarch, address_start),
9387 	      print_core_address (bl->gdbarch, address_end));
9388   uiout->field_stream ("addr", stb);
9389   uiout->text ("\n");
9390 }
9391 
9392 /* Implement the "print_mention" method for ranged breakpoints.  */
9393 
9394 void
9395 ranged_breakpoint::print_mention () const
9396 {
9397   struct bp_location *bl = loc;
9398   struct ui_out *uiout = current_uiout;
9399 
9400   gdb_assert (bl);
9401   gdb_assert (type == bp_hardware_breakpoint);
9402 
9403   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9404 		  number, paddress (bl->gdbarch, bl->address),
9405 		  paddress (bl->gdbarch, bl->address + bl->length - 1));
9406 }
9407 
9408 /* Implement the "print_recreate" method for ranged breakpoints.  */
9409 
9410 void
9411 ranged_breakpoint::print_recreate (struct ui_file *fp) const
9412 {
9413   gdb_printf (fp, "break-range %s, %s",
9414 	      locspec->to_string (),
9415 	      locspec_range_end->to_string ());
9416   print_recreate_thread (fp);
9417 }
9418 
9419 /* Find the address where the end of the breakpoint range should be
9420    placed, given the SAL of the end of the range.  This is so that if
9421    the user provides a line number, the end of the range is set to the
9422    last instruction of the given line.  */
9423 
9424 static CORE_ADDR
9425 find_breakpoint_range_end (struct symtab_and_line sal)
9426 {
9427   CORE_ADDR end;
9428 
9429   /* If the user provided a PC value, use it.  Otherwise,
9430      find the address of the end of the given location.  */
9431   if (sal.explicit_pc)
9432     end = sal.pc;
9433   else
9434     {
9435       int ret;
9436       CORE_ADDR start;
9437 
9438       ret = find_line_pc_range (sal, &start, &end);
9439       if (!ret)
9440 	error (_("Could not find location of the end of the range."));
9441 
9442       /* find_line_pc_range returns the start of the next line.  */
9443       end--;
9444     }
9445 
9446   return end;
9447 }
9448 
9449 /* Implement the "break-range" CLI command.  */
9450 
9451 static void
9452 break_range_command (const char *arg, int from_tty)
9453 {
9454   const char *arg_start;
9455   struct linespec_result canonical_start, canonical_end;
9456   int bp_count, can_use_bp, length;
9457   CORE_ADDR end;
9458 
9459   /* We don't support software ranged breakpoints.  */
9460   if (target_ranged_break_num_registers () < 0)
9461     error (_("This target does not support hardware ranged breakpoints."));
9462 
9463   bp_count = hw_breakpoint_used_count ();
9464   bp_count += target_ranged_break_num_registers ();
9465   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9466 						   bp_count, 0);
9467   if (can_use_bp < 0)
9468     error (_("Hardware breakpoints used exceeds limit."));
9469 
9470   arg = skip_spaces (arg);
9471   if (arg == NULL || arg[0] == '\0')
9472     error(_("No address range specified."));
9473 
9474   arg_start = arg;
9475   location_spec_up start_locspec
9476     = string_to_location_spec (&arg, current_language);
9477   parse_breakpoint_sals (start_locspec.get (), &canonical_start);
9478 
9479   if (arg[0] != ',')
9480     error (_("Too few arguments."));
9481   else if (canonical_start.lsals.empty ())
9482     error (_("Could not find location of the beginning of the range."));
9483 
9484   const linespec_sals &lsal_start = canonical_start.lsals[0];
9485 
9486   if (canonical_start.lsals.size () > 1
9487       || lsal_start.sals.size () != 1)
9488     error (_("Cannot create a ranged breakpoint with multiple locations."));
9489 
9490   const symtab_and_line &sal_start = lsal_start.sals[0];
9491   std::string addr_string_start (arg_start, arg - arg_start);
9492 
9493   arg++;	/* Skip the comma.  */
9494   arg = skip_spaces (arg);
9495 
9496   /* Parse the end location specification.  */
9497 
9498   arg_start = arg;
9499 
9500   /* We call decode_line_full directly here instead of using
9501      parse_breakpoint_sals because we need to specify the start
9502      location spec's symtab and line as the default symtab and line
9503      for the end of the range.  This makes it possible to have ranges
9504      like "foo.c:27, +14", where +14 means 14 lines from the start
9505      location spec.  */
9506   location_spec_up end_locspec
9507     = string_to_location_spec (&arg, current_language);
9508   decode_line_full (end_locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9509 		    sal_start.symtab, sal_start.line,
9510 		    &canonical_end, NULL, NULL);
9511 
9512   if (canonical_end.lsals.empty ())
9513     error (_("Could not find location of the end of the range."));
9514 
9515   const linespec_sals &lsal_end = canonical_end.lsals[0];
9516   if (canonical_end.lsals.size () > 1
9517       || lsal_end.sals.size () != 1)
9518     error (_("Cannot create a ranged breakpoint with multiple locations."));
9519 
9520   const symtab_and_line &sal_end = lsal_end.sals[0];
9521 
9522   end = find_breakpoint_range_end (sal_end);
9523   if (sal_start.pc > end)
9524     error (_("Invalid address range, end precedes start."));
9525 
9526   length = end - sal_start.pc + 1;
9527   if (length < 0)
9528     /* Length overflowed.  */
9529     error (_("Address range too large."));
9530   else if (length == 1)
9531     {
9532       /* This range is simple enough to be handled by
9533 	 the `hbreak' command.  */
9534       hbreak_command (&addr_string_start[0], 1);
9535 
9536       return;
9537     }
9538 
9539   /* Now set up the breakpoint and install it.  */
9540 
9541   std::unique_ptr<breakpoint> br
9542     (new ranged_breakpoint (get_current_arch (),
9543 			    sal_start, length,
9544 			    std::move (start_locspec),
9545 			    std::move (end_locspec)));
9546 
9547   install_breakpoint (false, std::move (br), true);
9548 }
9549 
9550 /*  Return non-zero if EXP is verified as constant.  Returned zero
9551     means EXP is variable.  Also the constant detection may fail for
9552     some constant expressions and in such case still falsely return
9553     zero.  */
9554 
9555 static bool
9556 watchpoint_exp_is_const (const struct expression *exp)
9557 {
9558   return exp->op->constant_p ();
9559 }
9560 
9561 /* Implement the "re_set" method for watchpoints.  */
9562 
9563 void
9564 watchpoint::re_set ()
9565 {
9566   /* Watchpoint can be either on expression using entirely global
9567      variables, or it can be on local variables.
9568 
9569      Watchpoints of the first kind are never auto-deleted, and even
9570      persist across program restarts.  Since they can use variables
9571      from shared libraries, we need to reparse expression as libraries
9572      are loaded and unloaded.
9573 
9574      Watchpoints on local variables can also change meaning as result
9575      of solib event.  For example, if a watchpoint uses both a local
9576      and a global variables in expression, it's a local watchpoint,
9577      but unloading of a shared library will make the expression
9578      invalid.  This is not a very common use case, but we still
9579      re-evaluate expression, to avoid surprises to the user.
9580 
9581      Note that for local watchpoints, we re-evaluate it only if
9582      watchpoints frame id is still valid.  If it's not, it means the
9583      watchpoint is out of scope and will be deleted soon.  In fact,
9584      I'm not sure we'll ever be called in this case.
9585 
9586      If a local watchpoint's frame id is still valid, then
9587      exp_valid_block is likewise valid, and we can safely use it.
9588 
9589      Don't do anything about disabled watchpoints, since they will be
9590      reevaluated again when enabled.  */
9591   update_watchpoint (this, true /* reparse */);
9592 }
9593 
9594 /* Implement the "insert" method for hardware watchpoints.  */
9595 
9596 int
9597 watchpoint::insert_location (struct bp_location *bl)
9598 {
9599   int length = exact ? 1 : bl->length;
9600 
9601   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9602 				   cond_exp.get ());
9603 }
9604 
9605 /* Implement the "remove" method for hardware watchpoints.  */
9606 
9607 int
9608 watchpoint::remove_location (struct bp_location *bl,
9609 			     enum remove_bp_reason reason)
9610 {
9611   int length = exact ? 1 : bl->length;
9612 
9613   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9614 				   cond_exp.get ());
9615 }
9616 
9617 int
9618 watchpoint::breakpoint_hit (const struct bp_location *bl,
9619 			    const address_space *aspace, CORE_ADDR bp_addr,
9620 			    const target_waitstatus &ws)
9621 {
9622   struct breakpoint *b = bl->owner;
9623 
9624   /* Continuable hardware watchpoints are treated as non-existent if the
9625      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9626      some data address).  Otherwise gdb won't stop on a break instruction
9627      in the code (not from a breakpoint) when a hardware watchpoint has
9628      been defined.  Also skip watchpoints which we know did not trigger
9629      (did not match the data address).  */
9630   if (is_hardware_watchpoint (b)
9631       && watchpoint_triggered == watch_triggered_no)
9632     return 0;
9633 
9634   return 1;
9635 }
9636 
9637 void
9638 watchpoint::check_status (bpstat *bs)
9639 {
9640   gdb_assert (is_watchpoint (bs->breakpoint_at));
9641 
9642   bpstat_check_watchpoint (bs);
9643 }
9644 
9645 /* Implement the "resources_needed" method for hardware
9646    watchpoints.  */
9647 
9648 int
9649 watchpoint::resources_needed (const struct bp_location *bl)
9650 {
9651   int length = exact? 1 : bl->length;
9652 
9653   return target_region_ok_for_hw_watchpoint (bl->address, length);
9654 }
9655 
9656 /* Implement the "works_in_software_mode" method for hardware
9657    watchpoints.  */
9658 
9659 bool
9660 watchpoint::works_in_software_mode () const
9661 {
9662   /* Read and access watchpoints only work with hardware support.  */
9663   return type == bp_watchpoint || type == bp_hardware_watchpoint;
9664 }
9665 
9666 enum print_stop_action
9667 watchpoint::print_it (const bpstat *bs) const
9668 {
9669   struct breakpoint *b;
9670   enum print_stop_action result;
9671   struct ui_out *uiout = current_uiout;
9672 
9673   gdb_assert (bs->bp_location_at != NULL);
9674 
9675   b = bs->breakpoint_at;
9676 
9677   annotate_watchpoint (b->number);
9678   maybe_print_thread_hit_breakpoint (uiout);
9679 
9680   string_file stb;
9681 
9682   gdb::optional<ui_out_emit_tuple> tuple_emitter;
9683   switch (b->type)
9684     {
9685     case bp_watchpoint:
9686     case bp_hardware_watchpoint:
9687       if (uiout->is_mi_like_p ())
9688 	uiout->field_string
9689 	  ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9690       mention (b);
9691       tuple_emitter.emplace (uiout, "value");
9692       uiout->text ("\nOld value = ");
9693       watchpoint_value_print (bs->old_val.get (), &stb);
9694       uiout->field_stream ("old", stb);
9695       uiout->text ("\nNew value = ");
9696       watchpoint_value_print (val.get (), &stb);
9697       uiout->field_stream ("new", stb);
9698       uiout->text ("\n");
9699       /* More than one watchpoint may have been triggered.  */
9700       result = PRINT_UNKNOWN;
9701       break;
9702 
9703     case bp_read_watchpoint:
9704       if (uiout->is_mi_like_p ())
9705 	uiout->field_string
9706 	  ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9707       mention (b);
9708       tuple_emitter.emplace (uiout, "value");
9709       uiout->text ("\nValue = ");
9710       watchpoint_value_print (val.get (), &stb);
9711       uiout->field_stream ("value", stb);
9712       uiout->text ("\n");
9713       result = PRINT_UNKNOWN;
9714       break;
9715 
9716     case bp_access_watchpoint:
9717       if (bs->old_val != NULL)
9718 	{
9719 	  if (uiout->is_mi_like_p ())
9720 	    uiout->field_string
9721 	      ("reason",
9722 	       async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9723 	  mention (b);
9724 	  tuple_emitter.emplace (uiout, "value");
9725 	  uiout->text ("\nOld value = ");
9726 	  watchpoint_value_print (bs->old_val.get (), &stb);
9727 	  uiout->field_stream ("old", stb);
9728 	  uiout->text ("\nNew value = ");
9729 	}
9730       else
9731 	{
9732 	  mention (b);
9733 	  if (uiout->is_mi_like_p ())
9734 	    uiout->field_string
9735 	      ("reason",
9736 	       async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9737 	  tuple_emitter.emplace (uiout, "value");
9738 	  uiout->text ("\nValue = ");
9739 	}
9740       watchpoint_value_print (val.get (), &stb);
9741       uiout->field_stream ("new", stb);
9742       uiout->text ("\n");
9743       result = PRINT_UNKNOWN;
9744       break;
9745     default:
9746       result = PRINT_UNKNOWN;
9747     }
9748 
9749   return result;
9750 }
9751 
9752 /* Implement the "print_mention" method for hardware watchpoints.  */
9753 
9754 void
9755 watchpoint::print_mention () const
9756 {
9757   struct ui_out *uiout = current_uiout;
9758   const char *tuple_name;
9759 
9760   switch (type)
9761     {
9762     case bp_watchpoint:
9763       uiout->text ("Watchpoint ");
9764       tuple_name = "wpt";
9765       break;
9766     case bp_hardware_watchpoint:
9767       uiout->text ("Hardware watchpoint ");
9768       tuple_name = "wpt";
9769       break;
9770     case bp_read_watchpoint:
9771       uiout->text ("Hardware read watchpoint ");
9772       tuple_name = "hw-rwpt";
9773       break;
9774     case bp_access_watchpoint:
9775       uiout->text ("Hardware access (read/write) watchpoint ");
9776       tuple_name = "hw-awpt";
9777       break;
9778     default:
9779       internal_error (_("Invalid hardware watchpoint type."));
9780     }
9781 
9782   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
9783   uiout->field_signed ("number", number);
9784   uiout->text (": ");
9785   uiout->field_string ("exp", exp_string.get ());
9786 }
9787 
9788 /* Implement the "print_recreate" method for watchpoints.  */
9789 
9790 void
9791 watchpoint::print_recreate (struct ui_file *fp) const
9792 {
9793   switch (type)
9794     {
9795     case bp_watchpoint:
9796     case bp_hardware_watchpoint:
9797       gdb_printf (fp, "watch");
9798       break;
9799     case bp_read_watchpoint:
9800       gdb_printf (fp, "rwatch");
9801       break;
9802     case bp_access_watchpoint:
9803       gdb_printf (fp, "awatch");
9804       break;
9805     default:
9806       internal_error (_("Invalid watchpoint type."));
9807     }
9808 
9809   gdb_printf (fp, " %s", exp_string.get ());
9810   print_recreate_thread (fp);
9811 }
9812 
9813 /* Implement the "explains_signal" method for watchpoints.  */
9814 
9815 bool
9816 watchpoint::explains_signal (enum gdb_signal sig)
9817 {
9818   /* A software watchpoint cannot cause a signal other than
9819      GDB_SIGNAL_TRAP.  */
9820   if (type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
9821     return false;
9822 
9823   return true;
9824 }
9825 
9826 struct masked_watchpoint : public watchpoint
9827 {
9828   using watchpoint::watchpoint;
9829 
9830   int insert_location (struct bp_location *) override;
9831   int remove_location (struct bp_location *,
9832 		       enum remove_bp_reason reason) override;
9833   int resources_needed (const struct bp_location *) override;
9834   bool works_in_software_mode () const override;
9835   enum print_stop_action print_it (const bpstat *bs) const override;
9836   void print_one_detail (struct ui_out *) const override;
9837   void print_mention () const override;
9838   void print_recreate (struct ui_file *fp) const override;
9839 };
9840 
9841 /* Implement the "insert" method for masked hardware watchpoints.  */
9842 
9843 int
9844 masked_watchpoint::insert_location (struct bp_location *bl)
9845 {
9846   return target_insert_mask_watchpoint (bl->address, hw_wp_mask,
9847 					bl->watchpoint_type);
9848 }
9849 
9850 /* Implement the "remove" method for masked hardware watchpoints.  */
9851 
9852 int
9853 masked_watchpoint::remove_location (struct bp_location *bl,
9854 				    enum remove_bp_reason reason)
9855 {
9856   return target_remove_mask_watchpoint (bl->address, hw_wp_mask,
9857 					bl->watchpoint_type);
9858 }
9859 
9860 /* Implement the "resources_needed" method for masked hardware
9861    watchpoints.  */
9862 
9863 int
9864 masked_watchpoint::resources_needed (const struct bp_location *bl)
9865 {
9866   return target_masked_watch_num_registers (bl->address, hw_wp_mask);
9867 }
9868 
9869 /* Implement the "works_in_software_mode" method for masked hardware
9870    watchpoints.  */
9871 
9872 bool
9873 masked_watchpoint::works_in_software_mode () const
9874 {
9875   return false;
9876 }
9877 
9878 /* Implement the "print_it" method for masked hardware
9879    watchpoints.  */
9880 
9881 enum print_stop_action
9882 masked_watchpoint::print_it (const bpstat *bs) const
9883 {
9884   struct breakpoint *b = bs->breakpoint_at;
9885   struct ui_out *uiout = current_uiout;
9886 
9887   /* Masked watchpoints have only one location.  */
9888   gdb_assert (b->loc && b->loc->next == NULL);
9889 
9890   annotate_watchpoint (b->number);
9891   maybe_print_thread_hit_breakpoint (uiout);
9892 
9893   switch (b->type)
9894     {
9895     case bp_hardware_watchpoint:
9896       if (uiout->is_mi_like_p ())
9897 	uiout->field_string
9898 	  ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9899       break;
9900 
9901     case bp_read_watchpoint:
9902       if (uiout->is_mi_like_p ())
9903 	uiout->field_string
9904 	  ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9905       break;
9906 
9907     case bp_access_watchpoint:
9908       if (uiout->is_mi_like_p ())
9909 	uiout->field_string
9910 	  ("reason",
9911 	   async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9912       break;
9913     default:
9914       internal_error (_("Invalid hardware watchpoint type."));
9915     }
9916 
9917   mention (b);
9918   uiout->text (_("\n\
9919 Check the underlying instruction at PC for the memory\n\
9920 address and value which triggered this watchpoint.\n"));
9921   uiout->text ("\n");
9922 
9923   /* More than one watchpoint may have been triggered.  */
9924   return PRINT_UNKNOWN;
9925 }
9926 
9927 /* Implement the "print_one_detail" method for masked hardware
9928    watchpoints.  */
9929 
9930 void
9931 masked_watchpoint::print_one_detail (struct ui_out *uiout) const
9932 {
9933   /* Masked watchpoints have only one location.  */
9934   gdb_assert (loc && loc->next == NULL);
9935 
9936   uiout->text ("\tmask ");
9937   uiout->field_core_addr ("mask", loc->gdbarch, hw_wp_mask);
9938   uiout->text ("\n");
9939 }
9940 
9941 /* Implement the "print_mention" method for masked hardware
9942    watchpoints.  */
9943 
9944 void
9945 masked_watchpoint::print_mention () const
9946 {
9947   struct ui_out *uiout = current_uiout;
9948   const char *tuple_name;
9949 
9950   switch (type)
9951     {
9952     case bp_hardware_watchpoint:
9953       uiout->text ("Masked hardware watchpoint ");
9954       tuple_name = "wpt";
9955       break;
9956     case bp_read_watchpoint:
9957       uiout->text ("Masked hardware read watchpoint ");
9958       tuple_name = "hw-rwpt";
9959       break;
9960     case bp_access_watchpoint:
9961       uiout->text ("Masked hardware access (read/write) watchpoint ");
9962       tuple_name = "hw-awpt";
9963       break;
9964     default:
9965       internal_error (_("Invalid hardware watchpoint type."));
9966     }
9967 
9968   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
9969   uiout->field_signed ("number", number);
9970   uiout->text (": ");
9971   uiout->field_string ("exp", exp_string.get ());
9972 }
9973 
9974 /* Implement the "print_recreate" method for masked hardware
9975    watchpoints.  */
9976 
9977 void
9978 masked_watchpoint::print_recreate (struct ui_file *fp) const
9979 {
9980   switch (type)
9981     {
9982     case bp_hardware_watchpoint:
9983       gdb_printf (fp, "watch");
9984       break;
9985     case bp_read_watchpoint:
9986       gdb_printf (fp, "rwatch");
9987       break;
9988     case bp_access_watchpoint:
9989       gdb_printf (fp, "awatch");
9990       break;
9991     default:
9992       internal_error (_("Invalid hardware watchpoint type."));
9993     }
9994 
9995   gdb_printf (fp, " %s mask 0x%s", exp_string.get (),
9996 	      phex (hw_wp_mask, sizeof (CORE_ADDR)));
9997   print_recreate_thread (fp);
9998 }
9999 
10000 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10001 
10002 static bool
10003 is_masked_watchpoint (const struct breakpoint *b)
10004 {
10005   return dynamic_cast<const masked_watchpoint *> (b) != nullptr;
10006 }
10007 
10008 /* accessflag:  hw_write:  watch write,
10009 		hw_read:   watch read,
10010 		hw_access: watch access (read or write) */
10011 static void
10012 watch_command_1 (const char *arg, int accessflag, int from_tty,
10013 		 bool just_location, bool internal)
10014 {
10015   struct breakpoint *scope_breakpoint = NULL;
10016   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10017   struct value *result;
10018   int saved_bitpos = 0, saved_bitsize = 0;
10019   const char *exp_start = NULL;
10020   const char *exp_end = NULL;
10021   const char *tok, *end_tok;
10022   int toklen = -1;
10023   const char *cond_start = NULL;
10024   const char *cond_end = NULL;
10025   enum bptype bp_type;
10026   int thread = -1;
10027   /* Flag to indicate whether we are going to use masks for
10028      the hardware watchpoint.  */
10029   bool use_mask = false;
10030   CORE_ADDR mask = 0;
10031   int task = 0;
10032 
10033   /* Make sure that we actually have parameters to parse.  */
10034   if (arg != NULL && arg[0] != '\0')
10035     {
10036       const char *value_start;
10037 
10038       exp_end = arg + strlen (arg);
10039 
10040       /* Look for "parameter value" pairs at the end
10041 	 of the arguments string.  */
10042       for (tok = exp_end - 1; tok > arg; tok--)
10043 	{
10044 	  /* Skip whitespace at the end of the argument list.  */
10045 	  while (tok > arg && (*tok == ' ' || *tok == '\t'))
10046 	    tok--;
10047 
10048 	  /* Find the beginning of the last token.
10049 	     This is the value of the parameter.  */
10050 	  while (tok > arg && (*tok != ' ' && *tok != '\t'))
10051 	    tok--;
10052 	  value_start = tok + 1;
10053 
10054 	  /* Skip whitespace.  */
10055 	  while (tok > arg && (*tok == ' ' || *tok == '\t'))
10056 	    tok--;
10057 
10058 	  end_tok = tok;
10059 
10060 	  /* Find the beginning of the second to last token.
10061 	     This is the parameter itself.  */
10062 	  while (tok > arg && (*tok != ' ' && *tok != '\t'))
10063 	    tok--;
10064 	  tok++;
10065 	  toklen = end_tok - tok + 1;
10066 
10067 	  if (toklen == 6 && startswith (tok, "thread"))
10068 	    {
10069 	      struct thread_info *thr;
10070 	      /* At this point we've found a "thread" token, which means
10071 		 the user is trying to set a watchpoint that triggers
10072 		 only in a specific thread.  */
10073 	      const char *endp;
10074 
10075 	      if (thread != -1)
10076 		error(_("You can specify only one thread."));
10077 
10078 	      /* Extract the thread ID from the next token.  */
10079 	      thr = parse_thread_id (value_start, &endp);
10080 
10081 	      /* Check if the user provided a valid thread ID.  */
10082 	      if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10083 		invalid_thread_id_error (value_start);
10084 
10085 	      thread = thr->global_num;
10086 	    }
10087 	  else if (toklen == 4 && startswith (tok, "task"))
10088 	    {
10089 	      char *tmp;
10090 
10091 	      task = strtol (value_start, &tmp, 0);
10092 	      if (tmp == value_start)
10093 		error (_("Junk after task keyword."));
10094 	      if (!valid_task_id (task))
10095 		error (_("Unknown task %d."), task);
10096 	    }
10097 	  else if (toklen == 4 && startswith (tok, "mask"))
10098 	    {
10099 	      /* We've found a "mask" token, which means the user wants to
10100 		 create a hardware watchpoint that is going to have the mask
10101 		 facility.  */
10102 	      struct value *mask_value;
10103 
10104 	      if (use_mask)
10105 		error(_("You can specify only one mask."));
10106 
10107 	      use_mask = just_location = true;
10108 
10109 	      scoped_value_mark mark;
10110 	      mask_value = parse_to_comma_and_eval (&value_start);
10111 	      mask = value_as_address (mask_value);
10112 	    }
10113 	  else
10114 	    /* We didn't recognize what we found.  We should stop here.  */
10115 	    break;
10116 
10117 	  /* Truncate the string and get rid of the "parameter value" pair before
10118 	     the arguments string is parsed by the parse_exp_1 function.  */
10119 	  exp_end = tok;
10120 	}
10121     }
10122   else
10123     exp_end = arg;
10124 
10125   /* Parse the rest of the arguments.  From here on out, everything
10126      is in terms of a newly allocated string instead of the original
10127      ARG.  */
10128   std::string expression (arg, exp_end - arg);
10129   exp_start = arg = expression.c_str ();
10130   innermost_block_tracker tracker;
10131   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10132   exp_end = arg;
10133   /* Remove trailing whitespace from the expression before saving it.
10134      This makes the eventual display of the expression string a bit
10135      prettier.  */
10136   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10137     --exp_end;
10138 
10139   /* Checking if the expression is not constant.  */
10140   if (watchpoint_exp_is_const (exp.get ()))
10141     {
10142       int len;
10143 
10144       len = exp_end - exp_start;
10145       while (len > 0 && isspace (exp_start[len - 1]))
10146 	len--;
10147       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10148     }
10149 
10150   exp_valid_block = tracker.block ();
10151   struct value *mark = value_mark ();
10152   struct value *val_as_value = nullptr;
10153   fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
10154 		      just_location);
10155 
10156   if (val_as_value != NULL && just_location)
10157     {
10158       saved_bitpos = value_bitpos (val_as_value);
10159       saved_bitsize = value_bitsize (val_as_value);
10160     }
10161 
10162   value_ref_ptr val;
10163   if (just_location)
10164     {
10165       int ret;
10166 
10167       exp_valid_block = NULL;
10168       val = release_value (value_addr (result));
10169       value_free_to_mark (mark);
10170 
10171       if (use_mask)
10172 	{
10173 	  ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10174 						   mask);
10175 	  if (ret == -1)
10176 	    error (_("This target does not support masked watchpoints."));
10177 	  else if (ret == -2)
10178 	    error (_("Invalid mask or memory region."));
10179 	}
10180     }
10181   else if (val_as_value != NULL)
10182     val = release_value (val_as_value);
10183 
10184   tok = skip_spaces (arg);
10185   end_tok = skip_to_space (tok);
10186 
10187   toklen = end_tok - tok;
10188   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10189     {
10190       tok = cond_start = end_tok + 1;
10191       innermost_block_tracker if_tracker;
10192       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10193 
10194       /* The watchpoint expression may not be local, but the condition
10195 	 may still be.  E.g.: `watch global if local > 0'.  */
10196       cond_exp_valid_block = if_tracker.block ();
10197 
10198       cond_end = tok;
10199     }
10200   if (*tok)
10201     error (_("Junk at end of command."));
10202 
10203   frame_info_ptr wp_frame = block_innermost_frame (exp_valid_block);
10204 
10205   /* Save this because create_internal_breakpoint below invalidates
10206      'wp_frame'.  */
10207   frame_id watchpoint_frame = get_frame_id (wp_frame);
10208 
10209   /* If the expression is "local", then set up a "watchpoint scope"
10210      breakpoint at the point where we've left the scope of the watchpoint
10211      expression.  Create the scope breakpoint before the watchpoint, so
10212      that we will encounter it first in bpstat_stop_status.  */
10213   if (exp_valid_block != NULL && wp_frame != NULL)
10214     {
10215       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10216 
10217       if (frame_id_p (caller_frame_id))
10218 	{
10219 	  gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10220 	  CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10221 
10222 	  scope_breakpoint
10223 	    = create_internal_breakpoint (caller_arch, caller_pc,
10224 					  bp_watchpoint_scope);
10225 
10226 	  /* create_internal_breakpoint could invalidate WP_FRAME.  */
10227 	  wp_frame = NULL;
10228 
10229 	  scope_breakpoint->enable_state = bp_enabled;
10230 
10231 	  /* Automatically delete the breakpoint when it hits.  */
10232 	  scope_breakpoint->disposition = disp_del;
10233 
10234 	  /* Only break in the proper frame (help with recursion).  */
10235 	  scope_breakpoint->frame_id = caller_frame_id;
10236 
10237 	  /* Set the address at which we will stop.  */
10238 	  scope_breakpoint->loc->gdbarch = caller_arch;
10239 	  scope_breakpoint->loc->requested_address = caller_pc;
10240 	  scope_breakpoint->loc->address
10241 	    = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10242 					 scope_breakpoint->loc->requested_address,
10243 					 scope_breakpoint->type,
10244 					 current_program_space);
10245 	}
10246     }
10247 
10248   /* Now set up the breakpoint.  We create all watchpoints as hardware
10249      watchpoints here even if hardware watchpoints are turned off, a call
10250      to update_watchpoint later in this function will cause the type to
10251      drop back to bp_watchpoint (software watchpoint) if required.  */
10252 
10253   if (accessflag == hw_read)
10254     bp_type = bp_read_watchpoint;
10255   else if (accessflag == hw_access)
10256     bp_type = bp_access_watchpoint;
10257   else
10258     bp_type = bp_hardware_watchpoint;
10259 
10260   std::unique_ptr<watchpoint> w;
10261   if (use_mask)
10262     w.reset (new masked_watchpoint (nullptr, bp_type));
10263   else
10264     w.reset (new watchpoint (nullptr, bp_type));
10265 
10266   w->thread = thread;
10267   w->task = task;
10268   w->disposition = disp_donttouch;
10269   w->pspace = current_program_space;
10270   w->exp = std::move (exp);
10271   w->exp_valid_block = exp_valid_block;
10272   w->cond_exp_valid_block = cond_exp_valid_block;
10273   if (just_location)
10274     {
10275       struct type *t = value_type (val.get ());
10276       CORE_ADDR addr = value_as_address (val.get ());
10277 
10278       w->exp_string_reparse
10279 	= current_language->watch_location_expression (t, addr);
10280 
10281       w->exp_string = xstrprintf ("-location %.*s",
10282 				  (int) (exp_end - exp_start), exp_start);
10283     }
10284   else
10285     w->exp_string.reset (savestring (exp_start, exp_end - exp_start));
10286 
10287   if (use_mask)
10288     {
10289       w->hw_wp_mask = mask;
10290     }
10291   else
10292     {
10293       w->val = val;
10294       w->val_bitpos = saved_bitpos;
10295       w->val_bitsize = saved_bitsize;
10296       w->val_valid = true;
10297     }
10298 
10299   if (cond_start)
10300     w->cond_string.reset (savestring (cond_start, cond_end - cond_start));
10301   else
10302     w->cond_string = 0;
10303 
10304   if (frame_id_p (watchpoint_frame))
10305     {
10306       w->watchpoint_frame = watchpoint_frame;
10307       w->watchpoint_thread = inferior_ptid;
10308     }
10309   else
10310     {
10311       w->watchpoint_frame = null_frame_id;
10312       w->watchpoint_thread = null_ptid;
10313     }
10314 
10315   if (scope_breakpoint != NULL)
10316     {
10317       /* The scope breakpoint is related to the watchpoint.  We will
10318 	 need to act on them together.  */
10319       w->related_breakpoint = scope_breakpoint;
10320       scope_breakpoint->related_breakpoint = w.get ();
10321     }
10322 
10323   if (!just_location)
10324     value_free_to_mark (mark);
10325 
10326   /* Finally update the new watchpoint.  This creates the locations
10327      that should be inserted.  */
10328   update_watchpoint (w.get (), true /* reparse */);
10329 
10330   install_breakpoint (internal, std::move (w), 1);
10331 }
10332 
10333 /* Return count of debug registers needed to watch the given expression.
10334    If the watchpoint cannot be handled in hardware return zero.  */
10335 
10336 static int
10337 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10338 {
10339   int found_memory_cnt = 0;
10340 
10341   /* Did the user specifically forbid us to use hardware watchpoints? */
10342   if (!can_use_hw_watchpoints)
10343     return 0;
10344 
10345   gdb_assert (!vals.empty ());
10346   struct value *head = vals[0].get ();
10347 
10348   /* Make sure that the value of the expression depends only upon
10349      memory contents, and values computed from them within GDB.  If we
10350      find any register references or function calls, we can't use a
10351      hardware watchpoint.
10352 
10353      The idea here is that evaluating an expression generates a series
10354      of values, one holding the value of every subexpression.  (The
10355      expression a*b+c has five subexpressions: a, b, a*b, c, and
10356      a*b+c.)  GDB's values hold almost enough information to establish
10357      the criteria given above --- they identify memory lvalues,
10358      register lvalues, computed values, etcetera.  So we can evaluate
10359      the expression, and then scan the chain of values that leaves
10360      behind to decide whether we can detect any possible change to the
10361      expression's final value using only hardware watchpoints.
10362 
10363      However, I don't think that the values returned by inferior
10364      function calls are special in any way.  So this function may not
10365      notice that an expression involving an inferior function call
10366      can't be watched with hardware watchpoints.  FIXME.  */
10367   for (const value_ref_ptr &iter : vals)
10368     {
10369       struct value *v = iter.get ();
10370 
10371       if (VALUE_LVAL (v) == lval_memory)
10372 	{
10373 	  if (v != head && value_lazy (v))
10374 	    /* A lazy memory lvalue in the chain is one that GDB never
10375 	       needed to fetch; we either just used its address (e.g.,
10376 	       `a' in `a.b') or we never needed it at all (e.g., `a'
10377 	       in `a,b').  This doesn't apply to HEAD; if that is
10378 	       lazy then it was not readable, but watch it anyway.  */
10379 	    ;
10380 	  else
10381 	    {
10382 	      /* Ahh, memory we actually used!  Check if we can cover
10383 		 it with hardware watchpoints.  */
10384 	      struct type *vtype = check_typedef (value_type (v));
10385 
10386 	      /* We only watch structs and arrays if user asked for it
10387 		 explicitly, never if they just happen to appear in a
10388 		 middle of some value chain.  */
10389 	      if (v == head
10390 		  || (vtype->code () != TYPE_CODE_STRUCT
10391 		      && vtype->code () != TYPE_CODE_ARRAY))
10392 		{
10393 		  CORE_ADDR vaddr = value_address (v);
10394 		  int len;
10395 		  int num_regs;
10396 
10397 		  len = (target_exact_watchpoints
10398 			 && is_scalar_type_recursive (vtype))?
10399 		    1 : value_type (v)->length ();
10400 
10401 		  num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10402 		  if (!num_regs)
10403 		    return 0;
10404 		  else
10405 		    found_memory_cnt += num_regs;
10406 		}
10407 	    }
10408 	}
10409       else if (VALUE_LVAL (v) != not_lval
10410 	       && deprecated_value_modifiable (v) == 0)
10411 	return 0;	/* These are values from the history (e.g., $1).  */
10412       else if (VALUE_LVAL (v) == lval_register)
10413 	return 0;	/* Cannot watch a register with a HW watchpoint.  */
10414     }
10415 
10416   /* The expression itself looks suitable for using a hardware
10417      watchpoint, but give the target machine a chance to reject it.  */
10418   return found_memory_cnt;
10419 }
10420 
10421 void
10422 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10423 {
10424   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10425 }
10426 
10427 /* Options for the watch, awatch, and rwatch commands.  */
10428 
10429 struct watch_options
10430 {
10431   /* For -location.  */
10432   bool location = false;
10433 };
10434 
10435 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10436 
10437    Historically GDB always accepted both '-location' and '-l' flags for
10438    these commands (both flags being synonyms).  When converting to the
10439    newer option scheme only '-location' is added here.  That's fine (for
10440    backward compatibility) as any non-ambiguous prefix of a flag will be
10441    accepted, so '-l', '-loc', are now all accepted.
10442 
10443    What this means is that, if in the future, we add any new flag here
10444    that starts with '-l' then this will break backward compatibility, so
10445    please, don't do that!  */
10446 
10447 static const gdb::option::option_def watch_option_defs[] = {
10448   gdb::option::flag_option_def<watch_options> {
10449     "location",
10450     [] (watch_options *opt) { return &opt->location; },
10451     N_("\
10452 This evaluates EXPRESSION and watches the memory to which is refers.\n\
10453 -l can be used as a short form of -location."),
10454   },
10455 };
10456 
10457 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
10458    commands.  */
10459 
10460 static gdb::option::option_def_group
10461 make_watch_options_def_group (watch_options *opts)
10462 {
10463   return {{watch_option_defs}, opts};
10464 }
10465 
10466 /* A helper function that looks for the "-location" argument and then
10467    calls watch_command_1.  */
10468 
10469 static void
10470 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10471 {
10472   watch_options opts;
10473   auto grp = make_watch_options_def_group (&opts);
10474   gdb::option::process_options
10475     (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
10476   if (arg != nullptr && *arg == '\0')
10477     arg = nullptr;
10478 
10479   watch_command_1 (arg, accessflag, from_tty, opts.location, false);
10480 }
10481 
10482 /* Command completion for 'watch', 'awatch', and 'rwatch' commands.   */
10483 static void
10484 watch_command_completer (struct cmd_list_element *ignore,
10485 			 completion_tracker &tracker,
10486 			 const char *text, const char * /*word*/)
10487 {
10488   const auto group = make_watch_options_def_group (nullptr);
10489   if (gdb::option::complete_options
10490       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
10491     return;
10492 
10493   const char *word = advance_to_expression_complete_word_point (tracker, text);
10494   expression_completer (ignore, tracker, text, word);
10495 }
10496 
10497 static void
10498 watch_command (const char *arg, int from_tty)
10499 {
10500   watch_maybe_just_location (arg, hw_write, from_tty);
10501 }
10502 
10503 void
10504 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
10505 {
10506   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10507 }
10508 
10509 static void
10510 rwatch_command (const char *arg, int from_tty)
10511 {
10512   watch_maybe_just_location (arg, hw_read, from_tty);
10513 }
10514 
10515 void
10516 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
10517 {
10518   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10519 }
10520 
10521 static void
10522 awatch_command (const char *arg, int from_tty)
10523 {
10524   watch_maybe_just_location (arg, hw_access, from_tty);
10525 }
10526 
10527 
10528 /* Data for the FSM that manages the until(location)/advance commands
10529    in infcmd.c.  Here because it uses the mechanisms of
10530    breakpoints.  */
10531 
10532 struct until_break_fsm : public thread_fsm
10533 {
10534   /* The thread that was current when the command was executed.  */
10535   int thread;
10536 
10537   /* The breakpoint set at the return address in the caller frame,
10538      plus breakpoints at all the destination locations.  */
10539   std::vector<breakpoint_up> breakpoints;
10540 
10541   until_break_fsm (struct interp *cmd_interp, int thread,
10542 		   std::vector<breakpoint_up> &&breakpoints)
10543     : thread_fsm (cmd_interp),
10544       thread (thread),
10545       breakpoints (std::move (breakpoints))
10546   {
10547   }
10548 
10549   void clean_up (struct thread_info *thread) override;
10550   bool should_stop (struct thread_info *thread) override;
10551   enum async_reply_reason do_async_reply_reason () override;
10552 };
10553 
10554 /* Implementation of the 'should_stop' FSM method for the
10555    until(location)/advance commands.  */
10556 
10557 bool
10558 until_break_fsm::should_stop (struct thread_info *tp)
10559 {
10560   for (const breakpoint_up &bp : breakpoints)
10561     if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10562 				bp.get ()) != NULL)
10563       {
10564 	set_finished ();
10565 	break;
10566       }
10567 
10568   return true;
10569 }
10570 
10571 /* Implementation of the 'clean_up' FSM method for the
10572    until(location)/advance commands.  */
10573 
10574 void
10575 until_break_fsm::clean_up (struct thread_info *)
10576 {
10577   /* Clean up our temporary breakpoints.  */
10578   breakpoints.clear ();
10579   delete_longjmp_breakpoint (thread);
10580 }
10581 
10582 /* Implementation of the 'async_reply_reason' FSM method for the
10583    until(location)/advance commands.  */
10584 
10585 enum async_reply_reason
10586 until_break_fsm::do_async_reply_reason ()
10587 {
10588   return EXEC_ASYNC_LOCATION_REACHED;
10589 }
10590 
10591 void
10592 until_break_command (const char *arg, int from_tty, int anywhere)
10593 {
10594   frame_info_ptr frame;
10595   struct gdbarch *frame_gdbarch;
10596   struct frame_id stack_frame_id;
10597   struct frame_id caller_frame_id;
10598   int thread;
10599   struct thread_info *tp;
10600 
10601   clear_proceed_status (0);
10602 
10603   /* Set a breakpoint where the user wants it and at return from
10604      this function.  */
10605 
10606   location_spec_up locspec = string_to_location_spec (&arg, current_language);
10607 
10608   std::vector<symtab_and_line> sals
10609     = (last_displayed_sal_is_valid ()
10610        ? decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10611 			get_last_displayed_symtab (),
10612 			get_last_displayed_line ())
10613        : decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE,
10614 			NULL, NULL, 0));
10615 
10616   if (sals.empty ())
10617     error (_("Couldn't get information on specified line."));
10618 
10619   if (*arg)
10620     error (_("Junk at end of arguments."));
10621 
10622   tp = inferior_thread ();
10623   thread = tp->global_num;
10624 
10625   /* Note linespec handling above invalidates the frame chain.
10626      Installing a breakpoint also invalidates the frame chain (as it
10627      may need to switch threads), so do any frame handling before
10628      that.  */
10629 
10630   frame = get_selected_frame (NULL);
10631   frame_gdbarch = get_frame_arch (frame);
10632   stack_frame_id = get_stack_frame_id (frame);
10633   caller_frame_id = frame_unwind_caller_id (frame);
10634 
10635   /* Keep within the current frame, or in frames called by the current
10636      one.  */
10637 
10638   std::vector<breakpoint_up> breakpoints;
10639 
10640   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
10641 
10642   if (frame_id_p (caller_frame_id))
10643     {
10644       struct symtab_and_line sal2;
10645       struct gdbarch *caller_gdbarch;
10646 
10647       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10648       sal2.pc = frame_unwind_caller_pc (frame);
10649       caller_gdbarch = frame_unwind_caller_arch (frame);
10650 
10651       breakpoint_up caller_breakpoint
10652 	= set_momentary_breakpoint (caller_gdbarch, sal2,
10653 				    caller_frame_id, bp_until);
10654       breakpoints.emplace_back (std::move (caller_breakpoint));
10655 
10656       set_longjmp_breakpoint (tp, stack_frame_id);
10657       lj_deleter.emplace (thread);
10658     }
10659 
10660   /* set_momentary_breakpoint could invalidate FRAME.  */
10661   frame = NULL;
10662 
10663   /* If the user told us to continue until a specified location, we
10664      don't specify a frame at which we need to stop.  Otherwise,
10665      specify the selected frame, because we want to stop only at the
10666      very same frame.  */
10667   frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
10668 
10669   for (symtab_and_line &sal : sals)
10670     {
10671       resolve_sal_pc (&sal);
10672 
10673       breakpoint_up location_breakpoint
10674 	= set_momentary_breakpoint (frame_gdbarch, sal,
10675 				    stop_frame_id, bp_until);
10676       breakpoints.emplace_back (std::move (location_breakpoint));
10677     }
10678 
10679   tp->set_thread_fsm
10680     (std::unique_ptr<thread_fsm>
10681      (new until_break_fsm (command_interp (), tp->global_num,
10682 			   std::move (breakpoints))));
10683 
10684   if (lj_deleter)
10685     lj_deleter->release ();
10686 
10687   proceed (-1, GDB_SIGNAL_DEFAULT);
10688 }
10689 
10690 
10691 
10692 /* Compare two breakpoints and return a strcmp-like result.  */
10693 
10694 static int
10695 compare_breakpoints (const breakpoint *a, const breakpoint *b)
10696 {
10697   uintptr_t ua = (uintptr_t) a;
10698   uintptr_t ub = (uintptr_t) b;
10699 
10700   if (a->number < b->number)
10701     return -1;
10702   else if (a->number > b->number)
10703     return 1;
10704 
10705   /* Now sort by address, in case we see, e..g, two breakpoints with
10706      the number 0.  */
10707   if (ua < ub)
10708     return -1;
10709   return ua > ub ? 1 : 0;
10710 }
10711 
10712 /* Delete breakpoints by address or line.  */
10713 
10714 static void
10715 clear_command (const char *arg, int from_tty)
10716 {
10717   int default_match;
10718 
10719   std::vector<symtab_and_line> decoded_sals;
10720   symtab_and_line last_sal;
10721   gdb::array_view<symtab_and_line> sals;
10722   if (arg)
10723     {
10724       decoded_sals
10725 	= decode_line_with_current_source (arg,
10726 					   (DECODE_LINE_FUNFIRSTLINE
10727 					    | DECODE_LINE_LIST_MODE));
10728       default_match = 0;
10729       sals = decoded_sals;
10730     }
10731   else
10732     {
10733       /* Set sal's line, symtab, pc, and pspace to the values
10734 	 corresponding to the last call to print_frame_info.  If the
10735 	 codepoint is not valid, this will set all the fields to 0.  */
10736       last_sal = get_last_displayed_sal ();
10737       if (last_sal.symtab == 0)
10738 	error (_("No source file specified."));
10739 
10740       default_match = 1;
10741       sals = last_sal;
10742     }
10743 
10744   /* We don't call resolve_sal_pc here.  That's not as bad as it
10745      seems, because all existing breakpoints typically have both
10746      file/line and pc set.  So, if clear is given file/line, we can
10747      match this to existing breakpoint without obtaining pc at all.
10748 
10749      We only support clearing given the address explicitly
10750      present in breakpoint table.  Say, we've set breakpoint
10751      at file:line.  There were several PC values for that file:line,
10752      due to optimization, all in one block.
10753 
10754      We've picked one PC value.  If "clear" is issued with another
10755      PC corresponding to the same file:line, the breakpoint won't
10756      be cleared.  We probably can still clear the breakpoint, but
10757      since the other PC value is never presented to user, user
10758      can only find it by guessing, and it does not seem important
10759      to support that.  */
10760 
10761   /* For each line spec given, delete bps which correspond to it.  Do
10762      it in two passes, solely to preserve the current behavior that
10763      from_tty is forced true if we delete more than one
10764      breakpoint.  */
10765 
10766   std::vector<struct breakpoint *> found;
10767   for (const auto &sal : sals)
10768     {
10769       const char *sal_fullname;
10770 
10771       /* If exact pc given, clear bpts at that pc.
10772 	 If line given (pc == 0), clear all bpts on specified line.
10773 	 If defaulting, clear all bpts on default line
10774 	 or at default pc.
10775 
10776 	 defaulting    sal.pc != 0    tests to do
10777 
10778 	 0              1             pc
10779 	 1              1             pc _and_ line
10780 	 0              0             line
10781 	 1              0             <can't happen> */
10782 
10783       sal_fullname = (sal.symtab == NULL
10784 		      ? NULL : symtab_to_fullname (sal.symtab));
10785 
10786       /* Find all matching breakpoints and add them to 'found'.  */
10787       for (breakpoint *b : all_breakpoints ())
10788 	{
10789 	  int match = 0;
10790 	  /* Are we going to delete b?  */
10791 	  if (b->type != bp_none && !is_watchpoint (b)
10792 	      && user_breakpoint_p (b))
10793 	    {
10794 	      for (bp_location *loc : b->locations ())
10795 		{
10796 		  /* If the user specified file:line, don't allow a PC
10797 		     match.  This matches historical gdb behavior.  */
10798 		  int pc_match = (!sal.explicit_line
10799 				  && sal.pc
10800 				  && (loc->pspace == sal.pspace)
10801 				  && (loc->address == sal.pc)
10802 				  && (!section_is_overlay (loc->section)
10803 				      || loc->section == sal.section));
10804 		  int line_match = 0;
10805 
10806 		  if ((default_match || sal.explicit_line)
10807 		      && loc->symtab != NULL
10808 		      && sal_fullname != NULL
10809 		      && sal.pspace == loc->pspace
10810 		      && loc->line_number == sal.line
10811 		      && filename_cmp (symtab_to_fullname (loc->symtab),
10812 				       sal_fullname) == 0)
10813 		    line_match = 1;
10814 
10815 		  if (pc_match || line_match)
10816 		    {
10817 		      match = 1;
10818 		      break;
10819 		    }
10820 		}
10821 	    }
10822 
10823 	  if (match)
10824 	    found.push_back (b);
10825 	}
10826     }
10827 
10828   /* Now go thru the 'found' chain and delete them.  */
10829   if (found.empty ())
10830     {
10831       if (arg)
10832 	error (_("No breakpoint at %s."), arg);
10833       else
10834 	error (_("No breakpoint at this line."));
10835     }
10836 
10837   /* Remove duplicates from the vec.  */
10838   std::sort (found.begin (), found.end (),
10839 	     [] (const breakpoint *bp_a, const breakpoint *bp_b)
10840 	     {
10841 	       return compare_breakpoints (bp_a, bp_b) < 0;
10842 	     });
10843   found.erase (std::unique (found.begin (), found.end (),
10844 			    [] (const breakpoint *bp_a, const breakpoint *bp_b)
10845 			    {
10846 			      return compare_breakpoints (bp_a, bp_b) == 0;
10847 			    }),
10848 	       found.end ());
10849 
10850   if (found.size () > 1)
10851     from_tty = 1;	/* Always report if deleted more than one.  */
10852   if (from_tty)
10853     {
10854       if (found.size () == 1)
10855 	gdb_printf (_("Deleted breakpoint "));
10856       else
10857 	gdb_printf (_("Deleted breakpoints "));
10858     }
10859 
10860   for (breakpoint *iter : found)
10861     {
10862       if (from_tty)
10863 	gdb_printf ("%d ", iter->number);
10864       delete_breakpoint (iter);
10865     }
10866   if (from_tty)
10867     gdb_putc ('\n');
10868 }
10869 
10870 /* Delete breakpoint in BS if they are `delete' breakpoints and
10871    all breakpoints that are marked for deletion, whether hit or not.
10872    This is called after any breakpoint is hit, or after errors.  */
10873 
10874 void
10875 breakpoint_auto_delete (bpstat *bs)
10876 {
10877   for (; bs; bs = bs->next)
10878     if (bs->breakpoint_at
10879 	&& bs->breakpoint_at->disposition == disp_del
10880 	&& bs->stop)
10881       delete_breakpoint (bs->breakpoint_at);
10882 
10883   for (breakpoint *b : all_breakpoints_safe ())
10884     if (b->disposition == disp_del_at_next_stop)
10885       delete_breakpoint (b);
10886 }
10887 
10888 /* A comparison function for bp_location AP and BP being interfaced to
10889    std::sort.  Sort elements primarily by their ADDRESS (no matter what
10890    bl_address_is_meaningful says), secondarily by ordering first
10891    permanent elements and terciarily just ensuring the array is sorted
10892    stable way despite std::sort being an unstable algorithm.  */
10893 
10894 static int
10895 bp_location_is_less_than (const bp_location *a, const bp_location *b)
10896 {
10897   if (a->address != b->address)
10898     return a->address < b->address;
10899 
10900   /* Sort locations at the same address by their pspace number, keeping
10901      locations of the same inferior (in a multi-inferior environment)
10902      grouped.  */
10903 
10904   if (a->pspace->num != b->pspace->num)
10905     return a->pspace->num < b->pspace->num;
10906 
10907   /* Sort permanent breakpoints first.  */
10908   if (a->permanent != b->permanent)
10909     return a->permanent > b->permanent;
10910 
10911   /* Sort by type in order to make duplicate determination easier.
10912      See update_global_location_list.  This is kept in sync with
10913      breakpoint_locations_match.  */
10914   if (a->loc_type < b->loc_type)
10915     return true;
10916 
10917   /* Likewise, for range-breakpoints, sort by length.  */
10918   if (a->loc_type == bp_loc_hardware_breakpoint
10919       && b->loc_type == bp_loc_hardware_breakpoint
10920       && a->length < b->length)
10921     return true;
10922 
10923   /* Make the internal GDB representation stable across GDB runs
10924      where A and B memory inside GDB can differ.  Breakpoint locations of
10925      the same type at the same address can be sorted in arbitrary order.  */
10926 
10927   if (a->owner->number != b->owner->number)
10928     return a->owner->number < b->owner->number;
10929 
10930   return a < b;
10931 }
10932 
10933 /* Set bp_locations_placed_address_before_address_max and
10934    bp_locations_shadow_len_after_address_max according to the current
10935    content of the bp_locations array.  */
10936 
10937 static void
10938 bp_locations_target_extensions_update (void)
10939 {
10940   bp_locations_placed_address_before_address_max = 0;
10941   bp_locations_shadow_len_after_address_max = 0;
10942 
10943   for (bp_location *bl : all_bp_locations ())
10944     {
10945       CORE_ADDR start, end, addr;
10946 
10947       if (!bp_location_has_shadow (bl))
10948 	continue;
10949 
10950       start = bl->target_info.placed_address;
10951       end = start + bl->target_info.shadow_len;
10952 
10953       gdb_assert (bl->address >= start);
10954       addr = bl->address - start;
10955       if (addr > bp_locations_placed_address_before_address_max)
10956 	bp_locations_placed_address_before_address_max = addr;
10957 
10958       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
10959 
10960       gdb_assert (bl->address < end);
10961       addr = end - bl->address;
10962       if (addr > bp_locations_shadow_len_after_address_max)
10963 	bp_locations_shadow_len_after_address_max = addr;
10964     }
10965 }
10966 
10967 /* Download tracepoint locations if they haven't been.  */
10968 
10969 static void
10970 download_tracepoint_locations (void)
10971 {
10972   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
10973 
10974   scoped_restore_current_pspace_and_thread restore_pspace_thread;
10975 
10976   for (breakpoint *b : all_tracepoints ())
10977     {
10978       struct tracepoint *t;
10979       bool bp_location_downloaded = false;
10980 
10981       if ((b->type == bp_fast_tracepoint
10982 	   ? !may_insert_fast_tracepoints
10983 	   : !may_insert_tracepoints))
10984 	continue;
10985 
10986       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
10987 	{
10988 	  if (target_can_download_tracepoint ())
10989 	    can_download_tracepoint = TRIBOOL_TRUE;
10990 	  else
10991 	    can_download_tracepoint = TRIBOOL_FALSE;
10992 	}
10993 
10994       if (can_download_tracepoint == TRIBOOL_FALSE)
10995 	break;
10996 
10997       for (bp_location *bl : b->locations ())
10998 	{
10999 	  /* In tracepoint, locations are _never_ duplicated, so
11000 	     should_be_inserted is equivalent to
11001 	     unduplicated_should_be_inserted.  */
11002 	  if (!should_be_inserted (bl) || bl->inserted)
11003 	    continue;
11004 
11005 	  switch_to_program_space_and_thread (bl->pspace);
11006 
11007 	  target_download_tracepoint (bl);
11008 
11009 	  bl->inserted = 1;
11010 	  bp_location_downloaded = true;
11011 	}
11012       t = (struct tracepoint *) b;
11013       t->number_on_target = b->number;
11014       if (bp_location_downloaded)
11015 	gdb::observers::breakpoint_modified.notify (b);
11016     }
11017 }
11018 
11019 /* Swap the insertion/duplication state between two locations.  */
11020 
11021 static void
11022 swap_insertion (struct bp_location *left, struct bp_location *right)
11023 {
11024   const int left_inserted = left->inserted;
11025   const int left_duplicate = left->duplicate;
11026   const int left_needs_update = left->needs_update;
11027   const struct bp_target_info left_target_info = left->target_info;
11028 
11029   /* Locations of tracepoints can never be duplicated.  */
11030   if (is_tracepoint (left->owner))
11031     gdb_assert (!left->duplicate);
11032   if (is_tracepoint (right->owner))
11033     gdb_assert (!right->duplicate);
11034 
11035   left->inserted = right->inserted;
11036   left->duplicate = right->duplicate;
11037   left->needs_update = right->needs_update;
11038   left->target_info = right->target_info;
11039   right->inserted = left_inserted;
11040   right->duplicate = left_duplicate;
11041   right->needs_update = left_needs_update;
11042   right->target_info = left_target_info;
11043 }
11044 
11045 /* Force the re-insertion of the locations at ADDRESS.  This is called
11046    once a new/deleted/modified duplicate location is found and we are evaluating
11047    conditions on the target's side.  Such conditions need to be updated on
11048    the target.  */
11049 
11050 static void
11051 force_breakpoint_reinsertion (struct bp_location *bl)
11052 {
11053   CORE_ADDR address = 0;
11054   int pspace_num;
11055 
11056   address = bl->address;
11057   pspace_num = bl->pspace->num;
11058 
11059   /* This is only meaningful if the target is
11060      evaluating conditions and if the user has
11061      opted for condition evaluation on the target's
11062      side.  */
11063   if (gdb_evaluates_breakpoint_condition_p ()
11064       || !target_supports_evaluation_of_breakpoint_conditions ())
11065     return;
11066 
11067   /* Flag all breakpoint locations with this address and
11068      the same program space as the location
11069      as "its condition has changed".  We need to
11070      update the conditions on the target's side.  */
11071   for (bp_location *loc : all_bp_locations_at_addr (address))
11072     {
11073       if (!is_breakpoint (loc->owner)
11074 	  || pspace_num != loc->pspace->num)
11075 	continue;
11076 
11077       /* Flag the location appropriately.  We use a different state to
11078 	 let everyone know that we already updated the set of locations
11079 	 with addr bl->address and program space bl->pspace.  This is so
11080 	 we don't have to keep calling these functions just to mark locations
11081 	 that have already been marked.  */
11082       loc->condition_changed = condition_updated;
11083 
11084       /* Free the agent expression bytecode as well.  We will compute
11085 	 it later on.  */
11086       loc->cond_bytecode.reset ();
11087     }
11088 }
11089 
11090 /* Called whether new breakpoints are created, or existing breakpoints
11091    deleted, to update the global location list and recompute which
11092    locations are duplicate of which.
11093 
11094    The INSERT_MODE flag determines whether locations may not, may, or
11095    shall be inserted now.  See 'enum ugll_insert_mode' for more
11096    info.  */
11097 
11098 static void
11099 update_global_location_list (enum ugll_insert_mode insert_mode)
11100 {
11101   /* Last breakpoint location address that was marked for update.  */
11102   CORE_ADDR last_addr = 0;
11103   /* Last breakpoint location program space that was marked for update.  */
11104   int last_pspace_num = -1;
11105 
11106   /* Used in the duplicates detection below.  When iterating over all
11107      bp_locations, points to the first bp_location of a given address.
11108      Breakpoints and watchpoints of different types are never
11109      duplicates of each other.  Keep one pointer for each type of
11110      breakpoint/watchpoint, so we only need to loop over all locations
11111      once.  */
11112   struct bp_location *bp_loc_first;  /* breakpoint */
11113   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11114   struct bp_location *awp_loc_first; /* access watchpoint */
11115   struct bp_location *rwp_loc_first; /* read watchpoint */
11116 
11117   /* Saved former bp_locations array which we compare against the newly
11118      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11119   std::vector<bp_location *> old_locations = std::move (bp_locations);
11120   bp_locations.clear ();
11121 
11122   for (breakpoint *b : all_breakpoints ())
11123     for (bp_location *loc : b->locations ())
11124       bp_locations.push_back (loc);
11125 
11126   /* See if we need to "upgrade" a software breakpoint to a hardware
11127      breakpoint.  Do this before deciding whether locations are
11128      duplicates.  Also do this before sorting because sorting order
11129      depends on location type.  */
11130   for (bp_location *loc : bp_locations)
11131     if (!loc->inserted && should_be_inserted (loc))
11132 	handle_automatic_hardware_breakpoints (loc);
11133 
11134   std::sort (bp_locations.begin (), bp_locations.end (),
11135 	     bp_location_is_less_than);
11136 
11137   bp_locations_target_extensions_update ();
11138 
11139   /* Identify bp_location instances that are no longer present in the
11140      new list, and therefore should be freed.  Note that it's not
11141      necessary that those locations should be removed from inferior --
11142      if there's another location at the same address (previously
11143      marked as duplicate), we don't need to remove/insert the
11144      location.
11145 
11146      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11147      and former bp_location array state respectively.  */
11148 
11149   size_t loc_i = 0;
11150   for (bp_location *old_loc : old_locations)
11151     {
11152       /* Tells if 'old_loc' is found among the new locations.  If
11153 	 not, we have to free it.  */
11154       bool found_object = false;
11155       /* Tells if the location should remain inserted in the target.  */
11156       bool keep_in_target = false;
11157       bool removed = false;
11158 
11159       /* Skip LOCP entries which will definitely never be needed.
11160 	 Stop either at or being the one matching OLD_LOC.  */
11161       while (loc_i < bp_locations.size ()
11162 	     && bp_locations[loc_i]->address < old_loc->address)
11163 	loc_i++;
11164 
11165       for (size_t loc2_i = loc_i;
11166 	   (loc2_i < bp_locations.size ()
11167 	    && bp_locations[loc2_i]->address == old_loc->address);
11168 	   loc2_i++)
11169 	{
11170 	  /* Check if this is a new/duplicated location or a duplicated
11171 	     location that had its condition modified.  If so, we want to send
11172 	     its condition to the target if evaluation of conditions is taking
11173 	     place there.  */
11174 	  if (bp_locations[loc2_i]->condition_changed == condition_modified
11175 	      && (last_addr != old_loc->address
11176 		  || last_pspace_num != old_loc->pspace->num))
11177 	    {
11178 	      force_breakpoint_reinsertion (bp_locations[loc2_i]);
11179 	      last_pspace_num = old_loc->pspace->num;
11180 	    }
11181 
11182 	  if (bp_locations[loc2_i] == old_loc)
11183 	    found_object = true;
11184 	}
11185 
11186       /* We have already handled this address, update it so that we don't
11187 	 have to go through updates again.  */
11188       last_addr = old_loc->address;
11189 
11190       /* Target-side condition evaluation: Handle deleted locations.  */
11191       if (!found_object)
11192 	force_breakpoint_reinsertion (old_loc);
11193 
11194       /* If this location is no longer present, and inserted, look if
11195 	 there's maybe a new location at the same address.  If so,
11196 	 mark that one inserted, and don't remove this one.  This is
11197 	 needed so that we don't have a time window where a breakpoint
11198 	 at certain location is not inserted.  */
11199 
11200       if (old_loc->inserted)
11201 	{
11202 	  /* If the location is inserted now, we might have to remove
11203 	     it.  */
11204 
11205 	  if (found_object && should_be_inserted (old_loc))
11206 	    {
11207 	      /* The location is still present in the location list,
11208 		 and still should be inserted.  Don't do anything.  */
11209 	      keep_in_target = true;
11210 	    }
11211 	  else
11212 	    {
11213 	      /* This location still exists, but it won't be kept in the
11214 		 target since it may have been disabled.  We proceed to
11215 		 remove its target-side condition.  */
11216 
11217 	      /* The location is either no longer present, or got
11218 		 disabled.  See if there's another location at the
11219 		 same address, in which case we don't need to remove
11220 		 this one from the target.  */
11221 
11222 	      /* OLD_LOC comes from existing struct breakpoint.  */
11223 	      if (bl_address_is_meaningful (old_loc))
11224 		{
11225 		  for (size_t loc2_i = loc_i;
11226 		       (loc2_i < bp_locations.size ()
11227 			&& bp_locations[loc2_i]->address == old_loc->address);
11228 		       loc2_i++)
11229 		    {
11230 		      bp_location *loc2 = bp_locations[loc2_i];
11231 
11232 		      if (loc2 == old_loc)
11233 			continue;
11234 
11235 		      if (breakpoint_locations_match (loc2, old_loc))
11236 			{
11237 			  /* Read watchpoint locations are switched to
11238 			     access watchpoints, if the former are not
11239 			     supported, but the latter are.  */
11240 			  if (is_hardware_watchpoint (old_loc->owner))
11241 			    {
11242 			      gdb_assert (is_hardware_watchpoint (loc2->owner));
11243 			      loc2->watchpoint_type = old_loc->watchpoint_type;
11244 			    }
11245 
11246 			  /* loc2 is a duplicated location. We need to check
11247 			     if it should be inserted in case it will be
11248 			     unduplicated.  */
11249 			  if (unduplicated_should_be_inserted (loc2))
11250 			    {
11251 			      swap_insertion (old_loc, loc2);
11252 			      keep_in_target = true;
11253 			      break;
11254 			    }
11255 			}
11256 		    }
11257 		}
11258 	    }
11259 
11260 	  if (!keep_in_target)
11261 	    {
11262 	      if (remove_breakpoint (old_loc))
11263 		{
11264 		  /* This is just about all we can do.  We could keep
11265 		     this location on the global list, and try to
11266 		     remove it next time, but there's no particular
11267 		     reason why we will succeed next time.
11268 
11269 		     Note that at this point, old_loc->owner is still
11270 		     valid, as delete_breakpoint frees the breakpoint
11271 		     only after calling us.  */
11272 		  gdb_printf (_("warning: Error removing "
11273 				"breakpoint %d\n"),
11274 			      old_loc->owner->number);
11275 		}
11276 	      removed = true;
11277 	    }
11278 	}
11279 
11280       if (!found_object)
11281 	{
11282 	  if (removed && target_is_non_stop_p ()
11283 	      && need_moribund_for_location_type (old_loc))
11284 	    {
11285 	      /* This location was removed from the target.  In
11286 		 non-stop mode, a race condition is possible where
11287 		 we've removed a breakpoint, but stop events for that
11288 		 breakpoint are already queued and will arrive later.
11289 		 We apply an heuristic to be able to distinguish such
11290 		 SIGTRAPs from other random SIGTRAPs: we keep this
11291 		 breakpoint location for a bit, and will retire it
11292 		 after we see some number of events.  The theory here
11293 		 is that reporting of events should, "on the average",
11294 		 be fair, so after a while we'll see events from all
11295 		 threads that have anything of interest, and no longer
11296 		 need to keep this breakpoint location around.  We
11297 		 don't hold locations forever so to reduce chances of
11298 		 mistaking a non-breakpoint SIGTRAP for a breakpoint
11299 		 SIGTRAP.
11300 
11301 		 The heuristic failing can be disastrous on
11302 		 decr_pc_after_break targets.
11303 
11304 		 On decr_pc_after_break targets, like e.g., x86-linux,
11305 		 if we fail to recognize a late breakpoint SIGTRAP,
11306 		 because events_till_retirement has reached 0 too
11307 		 soon, we'll fail to do the PC adjustment, and report
11308 		 a random SIGTRAP to the user.  When the user resumes
11309 		 the inferior, it will most likely immediately crash
11310 		 with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11311 		 corrupted, because of being resumed e.g., in the
11312 		 middle of a multi-byte instruction, or skipped a
11313 		 one-byte instruction.  This was actually seen happen
11314 		 on native x86-linux, and should be less rare on
11315 		 targets that do not support new thread events, like
11316 		 remote, due to the heuristic depending on
11317 		 thread_count.
11318 
11319 		 Mistaking a random SIGTRAP for a breakpoint trap
11320 		 causes similar symptoms (PC adjustment applied when
11321 		 it shouldn't), but then again, playing with SIGTRAPs
11322 		 behind the debugger's back is asking for trouble.
11323 
11324 		 Since hardware watchpoint traps are always
11325 		 distinguishable from other traps, so we don't need to
11326 		 apply keep hardware watchpoint moribund locations
11327 		 around.  We simply always ignore hardware watchpoint
11328 		 traps we can no longer explain.  */
11329 
11330 	      process_stratum_target *proc_target = nullptr;
11331 	      for (inferior *inf : all_inferiors ())
11332 		if (inf->pspace == old_loc->pspace)
11333 		  {
11334 		    proc_target = inf->process_target ();
11335 		    break;
11336 		  }
11337 	      if (proc_target != nullptr)
11338 		old_loc->events_till_retirement
11339 		  = 3 * (thread_count (proc_target) + 1);
11340 	      else
11341 		old_loc->events_till_retirement = 1;
11342 	      old_loc->owner = NULL;
11343 
11344 	      moribund_locations.push_back (old_loc);
11345 	    }
11346 	  else
11347 	    {
11348 	      old_loc->owner = NULL;
11349 	      decref_bp_location (&old_loc);
11350 	    }
11351 	}
11352     }
11353 
11354   /* Rescan breakpoints at the same address and section, marking the
11355      first one as "first" and any others as "duplicates".  This is so
11356      that the bpt instruction is only inserted once.  If we have a
11357      permanent breakpoint at the same place as BPT, make that one the
11358      official one, and the rest as duplicates.  Permanent breakpoints
11359      are sorted first for the same address.
11360 
11361      Do the same for hardware watchpoints, but also considering the
11362      watchpoint's type (regular/access/read) and length.  */
11363 
11364   bp_loc_first = NULL;
11365   wp_loc_first = NULL;
11366   awp_loc_first = NULL;
11367   rwp_loc_first = NULL;
11368 
11369   for (bp_location *loc : all_bp_locations ())
11370     {
11371       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11372 	 non-NULL.  */
11373       struct bp_location **loc_first_p;
11374       breakpoint *b = loc->owner;
11375 
11376       if (!unduplicated_should_be_inserted (loc)
11377 	  || !bl_address_is_meaningful (loc)
11378 	  /* Don't detect duplicate for tracepoint locations because they are
11379 	   never duplicated.  See the comments in field `duplicate' of
11380 	   `struct bp_location'.  */
11381 	  || is_tracepoint (b))
11382 	{
11383 	  /* Clear the condition modification flag.  */
11384 	  loc->condition_changed = condition_unchanged;
11385 	  continue;
11386 	}
11387 
11388       if (b->type == bp_hardware_watchpoint)
11389 	loc_first_p = &wp_loc_first;
11390       else if (b->type == bp_read_watchpoint)
11391 	loc_first_p = &rwp_loc_first;
11392       else if (b->type == bp_access_watchpoint)
11393 	loc_first_p = &awp_loc_first;
11394       else
11395 	loc_first_p = &bp_loc_first;
11396 
11397       if (*loc_first_p == NULL
11398 	  || (overlay_debugging && loc->section != (*loc_first_p)->section)
11399 	  || !breakpoint_locations_match (loc, *loc_first_p))
11400 	{
11401 	  *loc_first_p = loc;
11402 	  loc->duplicate = 0;
11403 
11404 	  if (is_breakpoint (loc->owner) && loc->condition_changed)
11405 	    {
11406 	      loc->needs_update = 1;
11407 	      /* Clear the condition modification flag.  */
11408 	      loc->condition_changed = condition_unchanged;
11409 	    }
11410 	  continue;
11411 	}
11412 
11413 
11414       /* This and the above ensure the invariant that the first location
11415 	 is not duplicated, and is the inserted one.
11416 	 All following are marked as duplicated, and are not inserted.  */
11417       if (loc->inserted)
11418 	swap_insertion (loc, *loc_first_p);
11419       loc->duplicate = 1;
11420 
11421       /* Clear the condition modification flag.  */
11422       loc->condition_changed = condition_unchanged;
11423     }
11424 
11425   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
11426     {
11427       if (insert_mode != UGLL_DONT_INSERT)
11428 	insert_breakpoint_locations ();
11429       else
11430 	{
11431 	  /* Even though the caller told us to not insert new
11432 	     locations, we may still need to update conditions on the
11433 	     target's side of breakpoints that were already inserted
11434 	     if the target is evaluating breakpoint conditions.  We
11435 	     only update conditions for locations that are marked
11436 	     "needs_update".  */
11437 	  update_inserted_breakpoint_locations ();
11438 	}
11439     }
11440 
11441   if (insert_mode != UGLL_DONT_INSERT)
11442     download_tracepoint_locations ();
11443 }
11444 
11445 void
11446 breakpoint_retire_moribund (void)
11447 {
11448   for (int ix = 0; ix < moribund_locations.size (); ++ix)
11449     {
11450       struct bp_location *loc = moribund_locations[ix];
11451       if (--(loc->events_till_retirement) == 0)
11452 	{
11453 	  decref_bp_location (&loc);
11454 	  unordered_remove (moribund_locations, ix);
11455 	  --ix;
11456 	}
11457     }
11458 }
11459 
11460 static void
11461 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
11462 {
11463 
11464   try
11465     {
11466       update_global_location_list (insert_mode);
11467     }
11468   catch (const gdb_exception_error &e)
11469     {
11470     }
11471 }
11472 
11473 /* Clear BKP from a BPS.  */
11474 
11475 static void
11476 bpstat_remove_bp_location (bpstat *bps, struct breakpoint *bpt)
11477 {
11478   bpstat *bs;
11479 
11480   for (bs = bps; bs; bs = bs->next)
11481     if (bs->breakpoint_at == bpt)
11482       {
11483 	bs->breakpoint_at = NULL;
11484 	bs->old_val = NULL;
11485 	/* bs->commands will be freed later.  */
11486       }
11487 }
11488 
11489 /* Callback for iterate_over_threads.  */
11490 static int
11491 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11492 {
11493   struct breakpoint *bpt = (struct breakpoint *) data;
11494 
11495   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11496   return 0;
11497 }
11498 
11499 /* Helper for breakpoint and tracepoint breakpoint->mention
11500    callbacks.  */
11501 
11502 static void
11503 say_where (const breakpoint *b)
11504 {
11505   struct value_print_options opts;
11506 
11507   get_user_print_options (&opts);
11508 
11509   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11510      single string.  */
11511   if (b->loc == NULL)
11512     {
11513       /* For pending locations, the output differs slightly based
11514 	 on b->extra_string.  If this is non-NULL, it contains either
11515 	 a condition or dprintf arguments.  */
11516       if (b->extra_string == NULL)
11517 	{
11518 	  gdb_printf (_(" (%s) pending."), b->locspec->to_string ());
11519 	}
11520       else if (b->type == bp_dprintf)
11521 	{
11522 	  gdb_printf (_(" (%s,%s) pending."),
11523 		      b->locspec->to_string (),
11524 		      b->extra_string.get ());
11525 	}
11526       else
11527 	{
11528 	  gdb_printf (_(" (%s %s) pending."),
11529 		      b->locspec->to_string (),
11530 		      b->extra_string.get ());
11531 	}
11532     }
11533   else
11534     {
11535       if (opts.addressprint || b->loc->symtab == NULL)
11536 	gdb_printf (" at %ps",
11537 		    styled_string (address_style.style (),
11538 				   paddress (b->loc->gdbarch,
11539 					     b->loc->address)));
11540       if (b->loc->symtab != NULL)
11541 	{
11542 	  /* If there is a single location, we can print the location
11543 	     more nicely.  */
11544 	  if (b->loc->next == NULL)
11545 	    {
11546 	      const char *filename
11547 		= symtab_to_filename_for_display (b->loc->symtab);
11548 	      gdb_printf (": file %ps, line %d.",
11549 			  styled_string (file_name_style.style (),
11550 					 filename),
11551 			  b->loc->line_number);
11552 	    }
11553 	  else
11554 	    /* This is not ideal, but each location may have a
11555 	       different file name, and this at least reflects the
11556 	       real situation somewhat.  */
11557 	    gdb_printf (": %s.", b->locspec->to_string ());
11558 	}
11559 
11560       if (b->loc->next)
11561 	{
11562 	  struct bp_location *loc = b->loc;
11563 	  int n = 0;
11564 	  for (; loc; loc = loc->next)
11565 	    ++n;
11566 	  gdb_printf (" (%d locations)", n);
11567 	}
11568     }
11569 }
11570 
11571 /* See breakpoint.h.  */
11572 
11573 bp_location_range breakpoint::locations () const
11574 {
11575   return bp_location_range (this->loc);
11576 }
11577 
11578 struct bp_location *
11579 breakpoint::allocate_location ()
11580 {
11581   return new bp_location (this);
11582 }
11583 
11584 #define internal_error_pure_virtual_called() \
11585   gdb_assert_not_reached ("pure virtual function called")
11586 
11587 int
11588 breakpoint::insert_location (struct bp_location *bl)
11589 {
11590   internal_error_pure_virtual_called ();
11591 }
11592 
11593 int
11594 breakpoint::remove_location (struct bp_location *bl,
11595 			     enum remove_bp_reason reason)
11596 {
11597   internal_error_pure_virtual_called ();
11598 }
11599 
11600 int
11601 breakpoint::breakpoint_hit (const struct bp_location *bl,
11602 			    const address_space *aspace,
11603 			    CORE_ADDR bp_addr,
11604 			    const target_waitstatus &ws)
11605 {
11606   internal_error_pure_virtual_called ();
11607 }
11608 
11609 int
11610 breakpoint::resources_needed (const struct bp_location *bl)
11611 {
11612   internal_error_pure_virtual_called ();
11613 }
11614 
11615 enum print_stop_action
11616 breakpoint::print_it (const bpstat *bs) const
11617 {
11618   internal_error_pure_virtual_called ();
11619 }
11620 
11621 void
11622 breakpoint::print_mention () const
11623 {
11624   internal_error_pure_virtual_called ();
11625 }
11626 
11627 void
11628 breakpoint::print_recreate (struct ui_file *fp) const
11629 {
11630   internal_error_pure_virtual_called ();
11631 }
11632 
11633 /* Default breakpoint_ops methods.  */
11634 
11635 void
11636 code_breakpoint::re_set ()
11637 {
11638   /* FIXME: is this still reachable?  */
11639   if (breakpoint_location_spec_empty_p (this))
11640     {
11641       /* Anything without a location can't be re-set.  */
11642       delete_breakpoint (this);
11643       return;
11644     }
11645 
11646   re_set_default ();
11647 }
11648 
11649 int
11650 code_breakpoint::insert_location (struct bp_location *bl)
11651 {
11652   CORE_ADDR addr = bl->target_info.reqstd_address;
11653 
11654   bl->target_info.kind = breakpoint_kind (bl, &addr);
11655   bl->target_info.placed_address = addr;
11656 
11657   int result;
11658   if (bl->loc_type == bp_loc_hardware_breakpoint)
11659     result = target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
11660   else
11661     result = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
11662 
11663   if (result == 0 && bl->probe.prob != nullptr)
11664     {
11665       /* The insertion was successful, now let's set the probe's semaphore
11666 	 if needed.  */
11667       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
11668     }
11669 
11670   return result;
11671 }
11672 
11673 int
11674 code_breakpoint::remove_location (struct bp_location *bl,
11675 				  enum remove_bp_reason reason)
11676 {
11677   if (bl->probe.prob != nullptr)
11678     {
11679       /* Let's clear the semaphore before removing the location.  */
11680       bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
11681     }
11682 
11683   if (bl->loc_type == bp_loc_hardware_breakpoint)
11684     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
11685   else
11686     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
11687 }
11688 
11689 int
11690 code_breakpoint::breakpoint_hit (const struct bp_location *bl,
11691 				 const address_space *aspace,
11692 				 CORE_ADDR bp_addr,
11693 				 const target_waitstatus &ws)
11694 {
11695   if (ws.kind () != TARGET_WAITKIND_STOPPED
11696       || ws.sig () != GDB_SIGNAL_TRAP)
11697     return 0;
11698 
11699   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
11700 				 aspace, bp_addr))
11701     return 0;
11702 
11703   if (overlay_debugging		/* unmapped overlay section */
11704       && section_is_overlay (bl->section)
11705       && !section_is_mapped (bl->section))
11706     return 0;
11707 
11708   return 1;
11709 }
11710 
11711 int
11712 dprintf_breakpoint::breakpoint_hit (const struct bp_location *bl,
11713 				    const address_space *aspace,
11714 				    CORE_ADDR bp_addr,
11715 				    const target_waitstatus &ws)
11716 {
11717   if (dprintf_style == dprintf_style_agent
11718       && target_can_run_breakpoint_commands ())
11719     {
11720       /* An agent-style dprintf never causes a stop.  If we see a trap
11721 	 for this address it must be for a breakpoint that happens to
11722 	 be set at the same address.  */
11723       return 0;
11724     }
11725 
11726   return this->ordinary_breakpoint::breakpoint_hit (bl, aspace, bp_addr, ws);
11727 }
11728 
11729 int
11730 ordinary_breakpoint::resources_needed (const struct bp_location *bl)
11731 {
11732   gdb_assert (type == bp_hardware_breakpoint);
11733 
11734   return 1;
11735 }
11736 
11737 enum print_stop_action
11738 ordinary_breakpoint::print_it (const bpstat *bs) const
11739 {
11740   const struct bp_location *bl;
11741   int bp_temp;
11742   struct ui_out *uiout = current_uiout;
11743 
11744   bl = bs->bp_location_at.get ();
11745 
11746   bp_temp = disposition == disp_del;
11747   if (bl->address != bl->requested_address)
11748     breakpoint_adjustment_warning (bl->requested_address,
11749 				   bl->address,
11750 				   number, true);
11751   annotate_breakpoint (number);
11752   maybe_print_thread_hit_breakpoint (uiout);
11753 
11754   if (uiout->is_mi_like_p ())
11755     {
11756       uiout->field_string ("reason",
11757 			   async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11758       uiout->field_string ("disp", bpdisp_text (disposition));
11759     }
11760 
11761   if (bp_temp)
11762     uiout->text ("Temporary breakpoint ");
11763   else
11764     uiout->text ("Breakpoint ");
11765   print_num_locno (bs, uiout);
11766   uiout->text (", ");
11767 
11768   return PRINT_SRC_AND_LOC;
11769 }
11770 
11771 void
11772 ordinary_breakpoint::print_mention () const
11773 {
11774   if (current_uiout->is_mi_like_p ())
11775     return;
11776 
11777   switch (type)
11778     {
11779     case bp_breakpoint:
11780     case bp_gnu_ifunc_resolver:
11781       if (disposition == disp_del)
11782 	gdb_printf (_("Temporary breakpoint"));
11783       else
11784 	gdb_printf (_("Breakpoint"));
11785       gdb_printf (_(" %d"), number);
11786       if (type == bp_gnu_ifunc_resolver)
11787 	gdb_printf (_(" at gnu-indirect-function resolver"));
11788       break;
11789     case bp_hardware_breakpoint:
11790       gdb_printf (_("Hardware assisted breakpoint %d"), number);
11791       break;
11792     case bp_dprintf:
11793       gdb_printf (_("Dprintf %d"), number);
11794       break;
11795     }
11796 
11797   say_where (this);
11798 }
11799 
11800 void
11801 ordinary_breakpoint::print_recreate (struct ui_file *fp) const
11802 {
11803   if (type == bp_breakpoint && disposition == disp_del)
11804     gdb_printf (fp, "tbreak");
11805   else if (type == bp_breakpoint)
11806     gdb_printf (fp, "break");
11807   else if (type == bp_hardware_breakpoint
11808 	   && disposition == disp_del)
11809     gdb_printf (fp, "thbreak");
11810   else if (type == bp_hardware_breakpoint)
11811     gdb_printf (fp, "hbreak");
11812   else
11813     internal_error (_("unhandled breakpoint type %d"), (int) type);
11814 
11815   gdb_printf (fp, " %s", locspec->to_string ());
11816 
11817   /* Print out extra_string if this breakpoint is pending.  It might
11818      contain, for example, conditions that were set by the user.  */
11819   if (loc == NULL && extra_string != NULL)
11820     gdb_printf (fp, " %s", extra_string.get ());
11821 
11822   print_recreate_thread (fp);
11823 }
11824 
11825 std::vector<symtab_and_line>
11826 code_breakpoint::decode_location_spec (location_spec *locspec,
11827 				       program_space *search_pspace)
11828 {
11829   if (locspec->type () == PROBE_LOCATION_SPEC)
11830     return bkpt_probe_decode_location_spec (this, locspec, search_pspace);
11831 
11832   struct linespec_result canonical;
11833 
11834   decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
11835 		    NULL, 0, &canonical, multiple_symbols_all,
11836 		    filter.get ());
11837 
11838   /* We should get 0 or 1 resulting SALs.  */
11839   gdb_assert (canonical.lsals.size () < 2);
11840 
11841   if (!canonical.lsals.empty ())
11842     {
11843       const linespec_sals &lsal = canonical.lsals[0];
11844       return std::move (lsal.sals);
11845     }
11846   return {};
11847 }
11848 
11849 /* Virtual table for internal breakpoints.  */
11850 
11851 void
11852 internal_breakpoint::re_set ()
11853 {
11854   switch (type)
11855     {
11856       /* Delete overlay event and longjmp master breakpoints; they
11857 	 will be reset later by breakpoint_re_set.  */
11858     case bp_overlay_event:
11859     case bp_longjmp_master:
11860     case bp_std_terminate_master:
11861     case bp_exception_master:
11862       delete_breakpoint (this);
11863       break;
11864 
11865       /* This breakpoint is special, it's set up when the inferior
11866 	 starts and we really don't want to touch it.  */
11867     case bp_shlib_event:
11868 
11869       /* Like bp_shlib_event, this breakpoint type is special.  Once
11870 	 it is set up, we do not want to touch it.  */
11871     case bp_thread_event:
11872       break;
11873     }
11874 }
11875 
11876 void
11877 internal_breakpoint::check_status (bpstat *bs)
11878 {
11879   if (type == bp_shlib_event)
11880     {
11881       /* If requested, stop when the dynamic linker notifies GDB of
11882 	 events.  This allows the user to get control and place
11883 	 breakpoints in initializer routines for dynamically loaded
11884 	 objects (among other things).  */
11885       bs->stop = stop_on_solib_events;
11886       bs->print = stop_on_solib_events;
11887     }
11888   else
11889     bs->stop = 0;
11890 }
11891 
11892 enum print_stop_action
11893 internal_breakpoint::print_it (const bpstat *bs) const
11894 {
11895   switch (type)
11896     {
11897     case bp_shlib_event:
11898       /* Did we stop because the user set the stop_on_solib_events
11899 	 variable?  (If so, we report this as a generic, "Stopped due
11900 	 to shlib event" message.) */
11901       print_solib_event (false);
11902       break;
11903 
11904     case bp_thread_event:
11905       /* Not sure how we will get here.
11906 	 GDB should not stop for these breakpoints.  */
11907       gdb_printf (_("Thread Event Breakpoint: gdb should not stop!\n"));
11908       break;
11909 
11910     case bp_overlay_event:
11911       /* By analogy with the thread event, GDB should not stop for these.  */
11912       gdb_printf (_("Overlay Event Breakpoint: gdb should not stop!\n"));
11913       break;
11914 
11915     case bp_longjmp_master:
11916       /* These should never be enabled.  */
11917       gdb_printf (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
11918       break;
11919 
11920     case bp_std_terminate_master:
11921       /* These should never be enabled.  */
11922       gdb_printf (_("std::terminate Master Breakpoint: "
11923 		    "gdb should not stop!\n"));
11924       break;
11925 
11926     case bp_exception_master:
11927       /* These should never be enabled.  */
11928       gdb_printf (_("Exception Master Breakpoint: "
11929 		    "gdb should not stop!\n"));
11930       break;
11931     }
11932 
11933   return PRINT_NOTHING;
11934 }
11935 
11936 void
11937 internal_breakpoint::print_mention () const
11938 {
11939   /* Nothing to mention.  These breakpoints are internal.  */
11940 }
11941 
11942 /* Virtual table for momentary breakpoints  */
11943 
11944 void
11945 momentary_breakpoint::re_set ()
11946 {
11947   /* Keep temporary breakpoints, which can be encountered when we step
11948      over a dlopen call and solib_add is resetting the breakpoints.
11949      Otherwise these should have been blown away via the cleanup chain
11950      or by breakpoint_init_inferior when we rerun the executable.  */
11951 }
11952 
11953 void
11954 momentary_breakpoint::check_status (bpstat *bs)
11955 {
11956   /* Nothing.  The point of these breakpoints is causing a stop.  */
11957 }
11958 
11959 enum print_stop_action
11960 momentary_breakpoint::print_it (const bpstat *bs) const
11961 {
11962   return PRINT_UNKNOWN;
11963 }
11964 
11965 void
11966 momentary_breakpoint::print_mention () const
11967 {
11968   /* Nothing to mention.  These breakpoints are internal.  */
11969 }
11970 
11971 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
11972 
11973    It gets cleared already on the removal of the first one of such placed
11974    breakpoints.  This is OK as they get all removed altogether.  */
11975 
11976 longjmp_breakpoint::~longjmp_breakpoint ()
11977 {
11978   thread_info *tp = find_thread_global_id (this->thread);
11979 
11980   if (tp != NULL)
11981     tp->initiating_frame = null_frame_id;
11982 }
11983 
11984 static void
11985 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
11986 					   struct linespec_result *canonical)
11987 
11988 {
11989   struct linespec_sals lsal;
11990 
11991   lsal.sals = parse_probes (locspec, NULL, canonical);
11992   lsal.canonical = xstrdup (canonical->locspec->to_string ());
11993   canonical->lsals.push_back (std::move (lsal));
11994 }
11995 
11996 static std::vector<symtab_and_line>
11997 bkpt_probe_decode_location_spec (struct breakpoint *b,
11998 				 location_spec *locspec,
11999 				 program_space *search_pspace)
12000 {
12001   std::vector<symtab_and_line> sals
12002     = parse_probes (locspec, search_pspace, NULL);
12003   if (sals.empty ())
12004     error (_("probe not found"));
12005   return sals;
12006 }
12007 
12008 int
12009 tracepoint::breakpoint_hit (const struct bp_location *bl,
12010 			    const address_space *aspace, CORE_ADDR bp_addr,
12011 			    const target_waitstatus &ws)
12012 {
12013   /* By definition, the inferior does not report stops at
12014      tracepoints.  */
12015   return 0;
12016 }
12017 
12018 void
12019 tracepoint::print_one_detail (struct ui_out *uiout) const
12020 {
12021   if (!static_trace_marker_id.empty ())
12022     {
12023       gdb_assert (type == bp_static_tracepoint
12024 		  || type == bp_static_marker_tracepoint);
12025 
12026       uiout->message ("\tmarker id is %pF\n",
12027 		      string_field ("static-tracepoint-marker-string-id",
12028 				    static_trace_marker_id.c_str ()));
12029     }
12030 }
12031 
12032 void
12033 tracepoint::print_mention () const
12034 {
12035   if (current_uiout->is_mi_like_p ())
12036     return;
12037 
12038   switch (type)
12039     {
12040     case bp_tracepoint:
12041       gdb_printf (_("Tracepoint"));
12042       gdb_printf (_(" %d"), number);
12043       break;
12044     case bp_fast_tracepoint:
12045       gdb_printf (_("Fast tracepoint"));
12046       gdb_printf (_(" %d"), number);
12047       break;
12048     case bp_static_tracepoint:
12049     case bp_static_marker_tracepoint:
12050       gdb_printf (_("Static tracepoint"));
12051       gdb_printf (_(" %d"), number);
12052       break;
12053     default:
12054       internal_error (_("unhandled tracepoint type %d"), (int) type);
12055     }
12056 
12057   say_where (this);
12058 }
12059 
12060 void
12061 tracepoint::print_recreate (struct ui_file *fp) const
12062 {
12063   if (type == bp_fast_tracepoint)
12064     gdb_printf (fp, "ftrace");
12065   else if (type == bp_static_tracepoint
12066 	   || type == bp_static_marker_tracepoint)
12067     gdb_printf (fp, "strace");
12068   else if (type == bp_tracepoint)
12069     gdb_printf (fp, "trace");
12070   else
12071     internal_error (_("unhandled tracepoint type %d"), (int) type);
12072 
12073   gdb_printf (fp, " %s", locspec->to_string ());
12074   print_recreate_thread (fp);
12075 
12076   if (pass_count)
12077     gdb_printf (fp, "  passcount %d\n", pass_count);
12078 }
12079 
12080 /* Virtual table for tracepoints on static probes.  */
12081 
12082 static void
12083 tracepoint_probe_create_sals_from_location_spec
12084   (location_spec *locspec,
12085    struct linespec_result *canonical)
12086 {
12087   /* We use the same method for breakpoint on probes.  */
12088   bkpt_probe_create_sals_from_location_spec (locspec, canonical);
12089 }
12090 
12091 void
12092 dprintf_breakpoint::re_set ()
12093 {
12094   re_set_default ();
12095 
12096   /* extra_string should never be non-NULL for dprintf.  */
12097   gdb_assert (extra_string != NULL);
12098 
12099   /* 1 - connect to target 1, that can run breakpoint commands.
12100      2 - create a dprintf, which resolves fine.
12101      3 - disconnect from target 1
12102      4 - connect to target 2, that can NOT run breakpoint commands.
12103 
12104      After steps #3/#4, you'll want the dprintf command list to
12105      be updated, because target 1 and 2 may well return different
12106      answers for target_can_run_breakpoint_commands().
12107      Given absence of finer grained resetting, we get to do
12108      it all the time.  */
12109   if (extra_string != NULL)
12110     update_dprintf_command_list (this);
12111 }
12112 
12113 /* Implement the "print_recreate" method for dprintf.  */
12114 
12115 void
12116 dprintf_breakpoint::print_recreate (struct ui_file *fp) const
12117 {
12118   gdb_printf (fp, "dprintf %s,%s", locspec->to_string (), extra_string.get ());
12119   print_recreate_thread (fp);
12120 }
12121 
12122 /* Implement the "after_condition_true" method for dprintf.
12123 
12124    dprintf's are implemented with regular commands in their command
12125    list, but we run the commands here instead of before presenting the
12126    stop to the user, as dprintf's don't actually cause a stop.  This
12127    also makes it so that the commands of multiple dprintfs at the same
12128    address are all handled.  */
12129 
12130 void
12131 dprintf_breakpoint::after_condition_true (struct bpstat *bs)
12132 {
12133   /* dprintf's never cause a stop.  This wasn't set in the
12134      check_status hook instead because that would make the dprintf's
12135      condition not be evaluated.  */
12136   bs->stop = 0;
12137 
12138   /* Run the command list here.  Take ownership of it instead of
12139      copying.  We never want these commands to run later in
12140      bpstat_do_actions, if a breakpoint that causes a stop happens to
12141      be set at same address as this dprintf, or even if running the
12142      commands here throws.  */
12143   counted_command_line cmds = std::move (bs->commands);
12144   gdb_assert (cmds != nullptr);
12145   execute_control_commands (cmds.get (), 0);
12146 }
12147 
12148 /* The breakpoint_ops structure to be used on static tracepoints with
12149    markers (`-m').  */
12150 
12151 static void
12152 strace_marker_create_sals_from_location_spec (location_spec *locspec,
12153 					      struct linespec_result *canonical)
12154 {
12155   struct linespec_sals lsal;
12156   const char *arg_start, *arg;
12157 
12158   arg = arg_start = as_linespec_location_spec (locspec)->spec_string;
12159   lsal.sals = decode_static_tracepoint_spec (&arg);
12160 
12161   std::string str (arg_start, arg - arg_start);
12162   const char *ptr = str.c_str ();
12163   canonical->locspec
12164     = new_linespec_location_spec (&ptr, symbol_name_match_type::FULL);
12165 
12166   lsal.canonical = xstrdup (canonical->locspec->to_string ());
12167   canonical->lsals.push_back (std::move (lsal));
12168 }
12169 
12170 static void
12171 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12172 				      struct linespec_result *canonical,
12173 				      gdb::unique_xmalloc_ptr<char> cond_string,
12174 				      gdb::unique_xmalloc_ptr<char> extra_string,
12175 				      enum bptype type_wanted,
12176 				      enum bpdisp disposition,
12177 				      int thread,
12178 				      int task, int ignore_count,
12179 				      int from_tty, int enabled,
12180 				      int internal, unsigned flags)
12181 {
12182   const linespec_sals &lsal = canonical->lsals[0];
12183 
12184   /* If the user is creating a static tracepoint by marker id
12185      (strace -m MARKER_ID), then store the sals index, so that
12186      breakpoint_re_set can try to match up which of the newly
12187      found markers corresponds to this one, and, don't try to
12188      expand multiple locations for each sal, given than SALS
12189      already should contain all sals for MARKER_ID.  */
12190 
12191   for (size_t i = 0; i < lsal.sals.size (); i++)
12192     {
12193       location_spec_up locspec = canonical->locspec->clone ();
12194 
12195       std::unique_ptr<tracepoint> tp
12196 	(new tracepoint (gdbarch,
12197 			 type_wanted,
12198 			 lsal.sals[i],
12199 			 std::move (locspec),
12200 			 NULL,
12201 			 std::move (cond_string),
12202 			 std::move (extra_string),
12203 			 disposition,
12204 			 thread, task, ignore_count,
12205 			 from_tty, enabled, flags,
12206 			 canonical->special_display));
12207 
12208       /* Given that its possible to have multiple markers with
12209 	 the same string id, if the user is creating a static
12210 	 tracepoint by marker id ("strace -m MARKER_ID"), then
12211 	 store the sals index, so that breakpoint_re_set can
12212 	 try to match up which of the newly found markers
12213 	 corresponds to this one  */
12214       tp->static_trace_marker_id_idx = i;
12215 
12216       install_breakpoint (internal, std::move (tp), 0);
12217     }
12218 }
12219 
12220 std::vector<symtab_and_line>
12221 static_marker_tracepoint::decode_location_spec (location_spec *locspec,
12222 						program_space *search_pspace)
12223 {
12224   const char *s = as_linespec_location_spec (locspec)->spec_string;
12225 
12226   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
12227   if (sals.size () > static_trace_marker_id_idx)
12228     {
12229       sals[0] = sals[static_trace_marker_id_idx];
12230       sals.resize (1);
12231       return sals;
12232     }
12233   else
12234     error (_("marker %s not found"), static_trace_marker_id.c_str ());
12235 }
12236 
12237 /* Static tracepoints with marker (`-m').  */
12238 static struct breakpoint_ops strace_marker_breakpoint_ops =
12239 {
12240   strace_marker_create_sals_from_location_spec,
12241   strace_marker_create_breakpoints_sal,
12242 };
12243 
12244 static bool
12245 strace_marker_p (struct breakpoint *b)
12246 {
12247   return b->type == bp_static_marker_tracepoint;
12248 }
12249 
12250 /* Delete a breakpoint and clean up all traces of it in the data
12251    structures.  */
12252 
12253 void
12254 delete_breakpoint (struct breakpoint *bpt)
12255 {
12256   gdb_assert (bpt != NULL);
12257 
12258   /* Has this bp already been deleted?  This can happen because
12259      multiple lists can hold pointers to bp's.  bpstat lists are
12260      especial culprits.
12261 
12262      One example of this happening is a watchpoint's scope bp.  When
12263      the scope bp triggers, we notice that the watchpoint is out of
12264      scope, and delete it.  We also delete its scope bp.  But the
12265      scope bp is marked "auto-deleting", and is already on a bpstat.
12266      That bpstat is then checked for auto-deleting bp's, which are
12267      deleted.
12268 
12269      A real solution to this problem might involve reference counts in
12270      bp's, and/or giving them pointers back to their referencing
12271      bpstat's, and teaching delete_breakpoint to only free a bp's
12272      storage when no more references were extent.  A cheaper bandaid
12273      was chosen.  */
12274   if (bpt->type == bp_none)
12275     return;
12276 
12277   /* At least avoid this stale reference until the reference counting
12278      of breakpoints gets resolved.  */
12279   if (bpt->related_breakpoint != bpt)
12280     {
12281       struct breakpoint *related;
12282       struct watchpoint *w;
12283 
12284       if (bpt->type == bp_watchpoint_scope)
12285 	w = (struct watchpoint *) bpt->related_breakpoint;
12286       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12287 	w = (struct watchpoint *) bpt;
12288       else
12289 	w = NULL;
12290       if (w != NULL)
12291 	watchpoint_del_at_next_stop (w);
12292 
12293       /* Unlink bpt from the bpt->related_breakpoint ring.  */
12294       for (related = bpt; related->related_breakpoint != bpt;
12295 	   related = related->related_breakpoint);
12296       related->related_breakpoint = bpt->related_breakpoint;
12297       bpt->related_breakpoint = bpt;
12298     }
12299 
12300   /* watch_command_1 creates a watchpoint but only sets its number if
12301      update_watchpoint succeeds in creating its bp_locations.  If there's
12302      a problem in that process, we'll be asked to delete the half-created
12303      watchpoint.  In that case, don't announce the deletion.  */
12304   if (bpt->number)
12305     gdb::observers::breakpoint_deleted.notify (bpt);
12306 
12307   if (breakpoint_chain == bpt)
12308     breakpoint_chain = bpt->next;
12309 
12310   for (breakpoint *b : all_breakpoints ())
12311     if (b->next == bpt)
12312       {
12313 	b->next = bpt->next;
12314 	break;
12315       }
12316 
12317   /* Be sure no bpstat's are pointing at the breakpoint after it's
12318      been freed.  */
12319   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
12320      in all threads for now.  Note that we cannot just remove bpstats
12321      pointing at bpt from the stop_bpstat list entirely, as breakpoint
12322      commands are associated with the bpstat; if we remove it here,
12323      then the later call to bpstat_do_actions (&stop_bpstat); in
12324      event-top.c won't do anything, and temporary breakpoints with
12325      commands won't work.  */
12326 
12327   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12328 
12329   /* Now that breakpoint is removed from breakpoint list, update the
12330      global location list.  This will remove locations that used to
12331      belong to this breakpoint.  Do this before freeing the breakpoint
12332      itself, since remove_breakpoint looks at location's owner.  It
12333      might be better design to have location completely
12334      self-contained, but it's not the case now.  */
12335   update_global_location_list (UGLL_DONT_INSERT);
12336 
12337   /* On the chance that someone will soon try again to delete this
12338      same bp, we mark it as deleted before freeing its storage.  */
12339   bpt->type = bp_none;
12340   delete bpt;
12341 }
12342 
12343 /* Iterator function to call a user-provided callback function once
12344    for each of B and its related breakpoints.  */
12345 
12346 static void
12347 iterate_over_related_breakpoints (struct breakpoint *b,
12348 				  gdb::function_view<void (breakpoint *)> function)
12349 {
12350   struct breakpoint *related;
12351 
12352   related = b;
12353   do
12354     {
12355       struct breakpoint *next;
12356 
12357       /* FUNCTION may delete RELATED.  */
12358       next = related->related_breakpoint;
12359 
12360       if (next == related)
12361 	{
12362 	  /* RELATED is the last ring entry.  */
12363 	  function (related);
12364 
12365 	  /* FUNCTION may have deleted it, so we'd never reach back to
12366 	     B.  There's nothing left to do anyway, so just break
12367 	     out.  */
12368 	  break;
12369 	}
12370       else
12371 	function (related);
12372 
12373       related = next;
12374     }
12375   while (related != b);
12376 }
12377 
12378 static void
12379 delete_command (const char *arg, int from_tty)
12380 {
12381   dont_repeat ();
12382 
12383   if (arg == 0)
12384     {
12385       int breaks_to_delete = 0;
12386 
12387       /* Delete all breakpoints if no argument.  Do not delete
12388 	 internal breakpoints, these have to be deleted with an
12389 	 explicit breakpoint number argument.  */
12390       for (breakpoint *b : all_breakpoints ())
12391 	if (user_breakpoint_p (b))
12392 	  {
12393 	    breaks_to_delete = 1;
12394 	    break;
12395 	  }
12396 
12397       /* Ask user only if there are some breakpoints to delete.  */
12398       if (!from_tty
12399 	  || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12400 	for (breakpoint *b : all_breakpoints_safe ())
12401 	  if (user_breakpoint_p (b))
12402 	    delete_breakpoint (b);
12403     }
12404   else
12405     map_breakpoint_numbers
12406       (arg, [&] (breakpoint *br)
12407        {
12408 	 iterate_over_related_breakpoints (br, delete_breakpoint);
12409        });
12410 }
12411 
12412 /* Return true if all locations of B bound to PSPACE are pending.  If
12413    PSPACE is NULL, all locations of all program spaces are
12414    considered.  */
12415 
12416 static bool
12417 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
12418 {
12419   for (bp_location *loc : b->locations ())
12420     if ((pspace == NULL
12421 	 || loc->pspace == pspace)
12422 	&& !loc->shlib_disabled
12423 	&& !loc->pspace->executing_startup)
12424       return false;
12425   return true;
12426 }
12427 
12428 /* Subroutine of update_breakpoint_locations to simplify it.
12429    Return true if multiple fns in list LOC have the same name.
12430    Null names are ignored.  */
12431 
12432 static bool
12433 ambiguous_names_p (struct bp_location *loc)
12434 {
12435   struct bp_location *l;
12436   htab_up htab (htab_create_alloc (13, htab_hash_string, htab_eq_string, NULL,
12437 				   xcalloc, xfree));
12438 
12439   for (l = loc; l != NULL; l = l->next)
12440     {
12441       const char **slot;
12442       const char *name = l->function_name.get ();
12443 
12444       /* Allow for some names to be NULL, ignore them.  */
12445       if (name == NULL)
12446 	continue;
12447 
12448       slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
12449 					     INSERT);
12450       /* NOTE: We can assume slot != NULL here because xcalloc never
12451 	 returns NULL.  */
12452       if (*slot != NULL)
12453 	return true;
12454       *slot = name;
12455     }
12456 
12457   return false;
12458 }
12459 
12460 /* When symbols change, it probably means the sources changed as well,
12461    and it might mean the static tracepoint markers are no longer at
12462    the same address or line numbers they used to be at last we
12463    checked.  Losing your static tracepoints whenever you rebuild is
12464    undesirable.  This function tries to resync/rematch gdb static
12465    tracepoints with the markers on the target, for static tracepoints
12466    that have not been set by marker id.  Static tracepoint that have
12467    been set by marker id are reset by marker id in breakpoint_re_set.
12468    The heuristic is:
12469 
12470    1) For a tracepoint set at a specific address, look for a marker at
12471    the old PC.  If one is found there, assume to be the same marker.
12472    If the name / string id of the marker found is different from the
12473    previous known name, assume that means the user renamed the marker
12474    in the sources, and output a warning.
12475 
12476    2) For a tracepoint set at a given line number, look for a marker
12477    at the new address of the old line number.  If one is found there,
12478    assume to be the same marker.  If the name / string id of the
12479    marker found is different from the previous known name, assume that
12480    means the user renamed the marker in the sources, and output a
12481    warning.
12482 
12483    3) If a marker is no longer found at the same address or line, it
12484    may mean the marker no longer exists.  But it may also just mean
12485    the code changed a bit.  Maybe the user added a few lines of code
12486    that made the marker move up or down (in line number terms).  Ask
12487    the target for info about the marker with the string id as we knew
12488    it.  If found, update line number and address in the matching
12489    static tracepoint.  This will get confused if there's more than one
12490    marker with the same ID (possible in UST, although unadvised
12491    precisely because it confuses tools).  */
12492 
12493 static struct symtab_and_line
12494 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12495 {
12496   struct tracepoint *tp = (struct tracepoint *) b;
12497   struct static_tracepoint_marker marker;
12498   CORE_ADDR pc;
12499 
12500   pc = sal.pc;
12501   if (sal.line)
12502     find_line_pc (sal.symtab, sal.line, &pc);
12503 
12504   if (target_static_tracepoint_marker_at (pc, &marker))
12505     {
12506       if (tp->static_trace_marker_id != marker.str_id)
12507 	warning (_("static tracepoint %d changed probed marker from %s to %s"),
12508 		 b->number, tp->static_trace_marker_id.c_str (),
12509 		 marker.str_id.c_str ());
12510 
12511       tp->static_trace_marker_id = std::move (marker.str_id);
12512 
12513       return sal;
12514     }
12515 
12516   /* Old marker wasn't found on target at lineno.  Try looking it up
12517      by string ID.  */
12518   if (!sal.explicit_pc
12519       && sal.line != 0
12520       && sal.symtab != NULL
12521       && !tp->static_trace_marker_id.empty ())
12522     {
12523       std::vector<static_tracepoint_marker> markers
12524 	= target_static_tracepoint_markers_by_strid
12525 	    (tp->static_trace_marker_id.c_str ());
12526 
12527       if (!markers.empty ())
12528 	{
12529 	  struct symbol *sym;
12530 	  struct static_tracepoint_marker *tpmarker;
12531 	  struct ui_out *uiout = current_uiout;
12532 
12533 	  tpmarker = &markers[0];
12534 
12535 	  tp->static_trace_marker_id = std::move (tpmarker->str_id);
12536 
12537 	  warning (_("marker for static tracepoint %d (%s) not "
12538 		     "found at previous line number"),
12539 		   b->number, tp->static_trace_marker_id.c_str ());
12540 
12541 	  symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
12542 	  sym = find_pc_sect_function (tpmarker->address, NULL);
12543 	  uiout->text ("Now in ");
12544 	  if (sym)
12545 	    {
12546 	      uiout->field_string ("func", sym->print_name (),
12547 				   function_name_style.style ());
12548 	      uiout->text (" at ");
12549 	    }
12550 	  uiout->field_string ("file",
12551 			       symtab_to_filename_for_display (sal2.symtab),
12552 			       file_name_style.style ());
12553 	  uiout->text (":");
12554 
12555 	  if (uiout->is_mi_like_p ())
12556 	    {
12557 	      const char *fullname = symtab_to_fullname (sal2.symtab);
12558 
12559 	      uiout->field_string ("fullname", fullname);
12560 	    }
12561 
12562 	  uiout->field_signed ("line", sal2.line);
12563 	  uiout->text ("\n");
12564 
12565 	  b->loc->line_number = sal2.line;
12566 	  b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
12567 
12568 	  std::unique_ptr<explicit_location_spec> els
12569 	    (new explicit_location_spec ());
12570 	  els->source_filename
12571 	    = xstrdup (symtab_to_filename_for_display (sal2.symtab));
12572 	  els->line_offset.offset = b->loc->line_number;
12573 	  els->line_offset.sign = LINE_OFFSET_NONE;
12574 
12575 	  b->locspec = std::move (els);
12576 
12577 	  /* Might be nice to check if function changed, and warn if
12578 	     so.  */
12579 	}
12580     }
12581   return sal;
12582 }
12583 
12584 /* Returns true iff locations A and B are sufficiently same that
12585    we don't need to report breakpoint as changed.  */
12586 
12587 static bool
12588 locations_are_equal (struct bp_location *a, struct bp_location *b)
12589 {
12590   while (a && b)
12591     {
12592       if (a->address != b->address)
12593 	return false;
12594 
12595       if (a->shlib_disabled != b->shlib_disabled)
12596 	return false;
12597 
12598       if (a->enabled != b->enabled)
12599 	return false;
12600 
12601       if (a->disabled_by_cond != b->disabled_by_cond)
12602 	return false;
12603 
12604       a = a->next;
12605       b = b->next;
12606     }
12607 
12608   if ((a == NULL) != (b == NULL))
12609     return false;
12610 
12611   return true;
12612 }
12613 
12614 /* Split all locations of B that are bound to PSPACE out of B's
12615    location list to a separate list and return that list's head.  If
12616    PSPACE is NULL, hoist out all locations of B.  */
12617 
12618 static struct bp_location *
12619 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
12620 {
12621   struct bp_location head;
12622   struct bp_location *i = b->loc;
12623   struct bp_location **i_link = &b->loc;
12624   struct bp_location *hoisted = &head;
12625 
12626   if (pspace == NULL)
12627     {
12628       i = b->loc;
12629       b->loc = NULL;
12630       return i;
12631     }
12632 
12633   head.next = NULL;
12634 
12635   while (i != NULL)
12636     {
12637       if (i->pspace == pspace)
12638 	{
12639 	  *i_link = i->next;
12640 	  i->next = NULL;
12641 	  hoisted->next = i;
12642 	  hoisted = i;
12643 	}
12644       else
12645 	i_link = &i->next;
12646       i = *i_link;
12647     }
12648 
12649   return head.next;
12650 }
12651 
12652 /* Create new breakpoint locations for B (a hardware or software
12653    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
12654    zero, then B is a ranged breakpoint.  Only recreates locations for
12655    FILTER_PSPACE.  Locations of other program spaces are left
12656    untouched.  */
12657 
12658 void
12659 update_breakpoint_locations (code_breakpoint *b,
12660 			     struct program_space *filter_pspace,
12661 			     gdb::array_view<const symtab_and_line> sals,
12662 			     gdb::array_view<const symtab_and_line> sals_end)
12663 {
12664   struct bp_location *existing_locations;
12665 
12666   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
12667     {
12668       /* Ranged breakpoints have only one start location and one end
12669 	 location.  */
12670       b->enable_state = bp_disabled;
12671       gdb_printf (gdb_stderr,
12672 		  _("Could not reset ranged breakpoint %d: "
12673 		    "multiple locations found\n"),
12674 		  b->number);
12675       return;
12676     }
12677 
12678   /* If there's no new locations, and all existing locations are
12679      pending, don't do anything.  This optimizes the common case where
12680      all locations are in the same shared library, that was unloaded.
12681      We'd like to retain the location, so that when the library is
12682      loaded again, we don't loose the enabled/disabled status of the
12683      individual locations.  */
12684   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
12685     return;
12686 
12687   existing_locations = hoist_existing_locations (b, filter_pspace);
12688 
12689   for (const auto &sal : sals)
12690     {
12691       struct bp_location *new_loc;
12692 
12693       switch_to_program_space_and_thread (sal.pspace);
12694 
12695       new_loc = b->add_location (sal);
12696 
12697       /* Reparse conditions, they might contain references to the
12698 	 old symtab.  */
12699       if (b->cond_string != NULL)
12700 	{
12701 	  const char *s;
12702 
12703 	  s = b->cond_string.get ();
12704 	  try
12705 	    {
12706 	      new_loc->cond = parse_exp_1 (&s, sal.pc,
12707 					   block_for_pc (sal.pc),
12708 					   0);
12709 	    }
12710 	  catch (const gdb_exception_error &e)
12711 	    {
12712 	      new_loc->disabled_by_cond = true;
12713 	    }
12714 	}
12715 
12716       if (!sals_end.empty ())
12717 	{
12718 	  CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
12719 
12720 	  new_loc->length = end - sals[0].pc + 1;
12721 	}
12722     }
12723 
12724   /* If possible, carry over 'disable' status from existing
12725      breakpoints.  */
12726   {
12727     struct bp_location *e = existing_locations;
12728     /* If there are multiple breakpoints with the same function name,
12729        e.g. for inline functions, comparing function names won't work.
12730        Instead compare pc addresses; this is just a heuristic as things
12731        may have moved, but in practice it gives the correct answer
12732        often enough until a better solution is found.  */
12733     int have_ambiguous_names = ambiguous_names_p (b->loc);
12734 
12735     for (; e; e = e->next)
12736       {
12737 	if ((!e->enabled || e->disabled_by_cond) && e->function_name)
12738 	  {
12739 	    if (have_ambiguous_names)
12740 	      {
12741 		for (bp_location *l : b->locations ())
12742 		  {
12743 		    /* Ignore software vs hardware location type at
12744 		       this point, because with "set breakpoint
12745 		       auto-hw", after a re-set, locations that were
12746 		       hardware can end up as software, or vice versa.
12747 		       As mentioned above, this is an heuristic and in
12748 		       practice should give the correct answer often
12749 		       enough.  */
12750 		    if (breakpoint_locations_match (e, l, true))
12751 		      {
12752 			l->enabled = e->enabled;
12753 			l->disabled_by_cond = e->disabled_by_cond;
12754 			break;
12755 		      }
12756 		  }
12757 	      }
12758 	    else
12759 	      {
12760 		for (bp_location *l : b->locations ())
12761 		  if (l->function_name
12762 		      && strcmp (e->function_name.get (),
12763 				 l->function_name.get ()) == 0)
12764 		    {
12765 		      l->enabled = e->enabled;
12766 		      l->disabled_by_cond = e->disabled_by_cond;
12767 		      break;
12768 		    }
12769 	      }
12770 	  }
12771       }
12772   }
12773 
12774   if (!locations_are_equal (existing_locations, b->loc))
12775     gdb::observers::breakpoint_modified.notify (b);
12776 }
12777 
12778 /* Find the SaL locations corresponding to the given LOCSPEC.
12779    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
12780 
12781 std::vector<symtab_and_line>
12782 code_breakpoint::location_spec_to_sals (location_spec *locspec,
12783 					struct program_space *search_pspace,
12784 					int *found)
12785 {
12786   struct gdb_exception exception;
12787 
12788   std::vector<symtab_and_line> sals;
12789 
12790   try
12791     {
12792       sals = decode_location_spec (locspec, search_pspace);
12793     }
12794   catch (gdb_exception_error &e)
12795     {
12796       int not_found_and_ok = false;
12797 
12798       /* For pending breakpoints, it's expected that parsing will
12799 	 fail until the right shared library is loaded.  User has
12800 	 already told to create pending breakpoints and don't need
12801 	 extra messages.  If breakpoint is in bp_shlib_disabled
12802 	 state, then user already saw the message about that
12803 	 breakpoint being disabled, and don't want to see more
12804 	 errors.  */
12805       if (e.error == NOT_FOUND_ERROR
12806 	  && (condition_not_parsed
12807 	      || (loc != NULL
12808 		  && search_pspace != NULL
12809 		  && loc->pspace != search_pspace)
12810 	      || (loc && loc->shlib_disabled)
12811 	      || (loc && loc->pspace->executing_startup)
12812 	      || enable_state == bp_disabled))
12813 	not_found_and_ok = true;
12814 
12815       if (!not_found_and_ok)
12816 	{
12817 	  /* We surely don't want to warn about the same breakpoint
12818 	     10 times.  One solution, implemented here, is disable
12819 	     the breakpoint on error.  Another solution would be to
12820 	     have separate 'warning emitted' flag.  Since this
12821 	     happens only when a binary has changed, I don't know
12822 	     which approach is better.  */
12823 	  enable_state = bp_disabled;
12824 	  throw;
12825 	}
12826 
12827       exception = std::move (e);
12828     }
12829 
12830   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
12831     {
12832       for (auto &sal : sals)
12833 	resolve_sal_pc (&sal);
12834       if (condition_not_parsed && extra_string != NULL)
12835 	{
12836 	  gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
12837 	  int local_thread, local_task;
12838 
12839 	  find_condition_and_thread_for_sals (sals, extra_string.get (),
12840 					      &local_cond, &local_thread,
12841 					      &local_task, &local_extra);
12842 	  gdb_assert (cond_string == nullptr);
12843 	  if (local_cond != nullptr)
12844 	    cond_string = std::move (local_cond);
12845 	  thread = local_thread;
12846 	  task = local_task;
12847 	  if (local_extra != nullptr)
12848 	    extra_string = std::move (local_extra);
12849 	  condition_not_parsed = 0;
12850 	}
12851 
12852       if (type == bp_static_tracepoint)
12853 	sals[0] = update_static_tracepoint (this, sals[0]);
12854 
12855       *found = 1;
12856     }
12857   else
12858     *found = 0;
12859 
12860   return sals;
12861 }
12862 
12863 /* The default re_set method, for typical hardware or software
12864    breakpoints.  Reevaluate the breakpoint and recreate its
12865    locations.  */
12866 
12867 void
12868 code_breakpoint::re_set_default ()
12869 {
12870   struct program_space *filter_pspace = current_program_space;
12871   std::vector<symtab_and_line> expanded, expanded_end;
12872 
12873   int found;
12874   std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
12875 							     filter_pspace,
12876 							     &found);
12877   if (found)
12878     expanded = std::move (sals);
12879 
12880   if (locspec_range_end != nullptr)
12881     {
12882       std::vector<symtab_and_line> sals_end
12883 	= location_spec_to_sals (locspec_range_end.get (),
12884 				 filter_pspace, &found);
12885       if (found)
12886 	expanded_end = std::move (sals_end);
12887     }
12888 
12889   update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
12890 }
12891 
12892 /* Default method for creating SALs from an address string.  It basically
12893    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
12894 
12895 static void
12896 create_sals_from_location_spec_default (location_spec *locspec,
12897 					struct linespec_result *canonical)
12898 {
12899   parse_breakpoint_sals (locspec, canonical);
12900 }
12901 
12902 /* Reset a breakpoint.  */
12903 
12904 static void
12905 breakpoint_re_set_one (breakpoint *b)
12906 {
12907   input_radix = b->input_radix;
12908   set_language (b->language);
12909 
12910   b->re_set ();
12911 }
12912 
12913 /* Re-set breakpoint locations for the current program space.
12914    Locations bound to other program spaces are left untouched.  */
12915 
12916 void
12917 breakpoint_re_set (void)
12918 {
12919   {
12920     scoped_restore_current_language save_language;
12921     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
12922     scoped_restore_current_pspace_and_thread restore_pspace_thread;
12923 
12924     /* breakpoint_re_set_one sets the current_language to the language
12925        of the breakpoint it is resetting (see prepare_re_set_context)
12926        before re-evaluating the breakpoint's location.  This change can
12927        unfortunately get undone by accident if the language_mode is set
12928        to auto, and we either switch frames, or more likely in this context,
12929        we select the current frame.
12930 
12931        We prevent this by temporarily turning the language_mode to
12932        language_mode_manual.  We restore it once all breakpoints
12933        have been reset.  */
12934     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
12935     language_mode = language_mode_manual;
12936 
12937     /* Note: we must not try to insert locations until after all
12938        breakpoints have been re-set.  Otherwise, e.g., when re-setting
12939        breakpoint 1, we'd insert the locations of breakpoint 2, which
12940        hadn't been re-set yet, and thus may have stale locations.  */
12941 
12942     for (breakpoint *b : all_breakpoints_safe ())
12943       {
12944 	try
12945 	  {
12946 	    breakpoint_re_set_one (b);
12947 	  }
12948 	catch (const gdb_exception &ex)
12949 	  {
12950 	    exception_fprintf (gdb_stderr, ex,
12951 			       "Error in re-setting breakpoint %d: ",
12952 			       b->number);
12953 	  }
12954       }
12955 
12956     jit_breakpoint_re_set ();
12957   }
12958 
12959   create_overlay_event_breakpoint ();
12960   create_longjmp_master_breakpoint ();
12961   create_std_terminate_master_breakpoint ();
12962   create_exception_master_breakpoint ();
12963 
12964   /* Now we can insert.  */
12965   update_global_location_list (UGLL_MAY_INSERT);
12966 }
12967 
12968 /* Reset the thread number of this breakpoint:
12969 
12970    - If the breakpoint is for all threads, leave it as-is.
12971    - Else, reset it to the current thread for inferior_ptid.  */
12972 void
12973 breakpoint_re_set_thread (struct breakpoint *b)
12974 {
12975   if (b->thread != -1)
12976     {
12977       b->thread = inferior_thread ()->global_num;
12978 
12979       /* We're being called after following a fork.  The new fork is
12980 	 selected as current, and unless this was a vfork will have a
12981 	 different program space from the original thread.  Reset that
12982 	 as well.  */
12983       b->loc->pspace = current_program_space;
12984     }
12985 }
12986 
12987 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12988    If from_tty is nonzero, it prints a message to that effect,
12989    which ends with a period (no newline).  */
12990 
12991 void
12992 set_ignore_count (int bptnum, int count, int from_tty)
12993 {
12994   if (count < 0)
12995     count = 0;
12996 
12997   for (breakpoint *b : all_breakpoints ())
12998     if (b->number == bptnum)
12999       {
13000 	if (is_tracepoint (b))
13001 	  {
13002 	    if (from_tty && count != 0)
13003 	      gdb_printf (_("Ignore count ignored for tracepoint %d."),
13004 			  bptnum);
13005 	    return;
13006 	  }
13007 
13008 	b->ignore_count = count;
13009 	if (from_tty)
13010 	  {
13011 	    if (count == 0)
13012 	      gdb_printf (_("Will stop next time "
13013 			    "breakpoint %d is reached."),
13014 			  bptnum);
13015 	    else if (count == 1)
13016 	      gdb_printf (_("Will ignore next crossing of breakpoint %d."),
13017 			  bptnum);
13018 	    else
13019 	      gdb_printf (_("Will ignore next %d "
13020 			    "crossings of breakpoint %d."),
13021 			  count, bptnum);
13022 	  }
13023 	gdb::observers::breakpoint_modified.notify (b);
13024 	return;
13025       }
13026 
13027   error (_("No breakpoint number %d."), bptnum);
13028 }
13029 
13030 /* Command to set ignore-count of breakpoint N to COUNT.  */
13031 
13032 static void
13033 ignore_command (const char *args, int from_tty)
13034 {
13035   const char *p = args;
13036   int num;
13037 
13038   if (p == 0)
13039     error_no_arg (_("a breakpoint number"));
13040 
13041   num = get_number (&p);
13042   if (num == 0)
13043     error (_("bad breakpoint number: '%s'"), args);
13044   if (*p == 0)
13045     error (_("Second argument (specified ignore-count) is missing."));
13046 
13047   set_ignore_count (num,
13048 		    longest_to_int (value_as_long (parse_and_eval (p))),
13049 		    from_tty);
13050   if (from_tty)
13051     gdb_printf ("\n");
13052 }
13053 
13054 
13055 /* Call FUNCTION on each of the breakpoints with numbers in the range
13056    defined by BP_NUM_RANGE (an inclusive range).  */
13057 
13058 static void
13059 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13060 			     gdb::function_view<void (breakpoint *)> function)
13061 {
13062   if (bp_num_range.first == 0)
13063     {
13064       warning (_("bad breakpoint number at or near '%d'"),
13065 	       bp_num_range.first);
13066     }
13067   else
13068     {
13069       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
13070 	{
13071 	  bool match = false;
13072 
13073 	  for (breakpoint *b : all_breakpoints_safe ())
13074 	    if (b->number == i)
13075 	      {
13076 		match = true;
13077 		function (b);
13078 		break;
13079 	      }
13080 	  if (!match)
13081 	    gdb_printf (_("No breakpoint number %d.\n"), i);
13082 	}
13083     }
13084 }
13085 
13086 /* Call FUNCTION on each of the breakpoints whose numbers are given in
13087    ARGS.  */
13088 
13089 static void
13090 map_breakpoint_numbers (const char *args,
13091 			gdb::function_view<void (breakpoint *)> function)
13092 {
13093   if (args == NULL || *args == '\0')
13094     error_no_arg (_("one or more breakpoint numbers"));
13095 
13096   number_or_range_parser parser (args);
13097 
13098   while (!parser.finished ())
13099     {
13100       int num = parser.get_number ();
13101       map_breakpoint_number_range (std::make_pair (num, num), function);
13102     }
13103 }
13104 
13105 /* Return the breakpoint location structure corresponding to the
13106    BP_NUM and LOC_NUM values.  */
13107 
13108 static struct bp_location *
13109 find_location_by_number (int bp_num, int loc_num)
13110 {
13111   breakpoint *b = get_breakpoint (bp_num);
13112 
13113   if (!b || b->number != bp_num)
13114     error (_("Bad breakpoint number '%d'"), bp_num);
13115 
13116   if (loc_num == 0)
13117     error (_("Bad breakpoint location number '%d'"), loc_num);
13118 
13119   int n = 0;
13120   for (bp_location *loc : b->locations ())
13121     if (++n == loc_num)
13122       return loc;
13123 
13124   error (_("Bad breakpoint location number '%d'"), loc_num);
13125 }
13126 
13127 /* Modes of operation for extract_bp_num.  */
13128 enum class extract_bp_kind
13129 {
13130   /* Extracting a breakpoint number.  */
13131   bp,
13132 
13133   /* Extracting a location number.  */
13134   loc,
13135 };
13136 
13137 /* Extract a breakpoint or location number (as determined by KIND)
13138    from the string starting at START.  TRAILER is a character which
13139    can be found after the number.  If you don't want a trailer, use
13140    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
13141    string.  This always returns a positive integer.  */
13142 
13143 static int
13144 extract_bp_num (extract_bp_kind kind, const char *start,
13145 		int trailer, const char **end_out = NULL)
13146 {
13147   const char *end = start;
13148   int num = get_number_trailer (&end, trailer);
13149   if (num < 0)
13150     error (kind == extract_bp_kind::bp
13151 	   ? _("Negative breakpoint number '%.*s'")
13152 	   : _("Negative breakpoint location number '%.*s'"),
13153 	   int (end - start), start);
13154   if (num == 0)
13155     error (kind == extract_bp_kind::bp
13156 	   ? _("Bad breakpoint number '%.*s'")
13157 	   : _("Bad breakpoint location number '%.*s'"),
13158 	   int (end - start), start);
13159 
13160   if (end_out != NULL)
13161     *end_out = end;
13162   return num;
13163 }
13164 
13165 /* Extract a breakpoint or location range (as determined by KIND) in
13166    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
13167    representing the (inclusive) range.  The returned pair's elements
13168    are always positive integers.  */
13169 
13170 static std::pair<int, int>
13171 extract_bp_or_bp_range (extract_bp_kind kind,
13172 			const std::string &arg,
13173 			std::string::size_type arg_offset)
13174 {
13175   std::pair<int, int> range;
13176   const char *bp_loc = &arg[arg_offset];
13177   std::string::size_type dash = arg.find ('-', arg_offset);
13178   if (dash != std::string::npos)
13179     {
13180       /* bp_loc is a range (x-z).  */
13181       if (arg.length () == dash + 1)
13182 	error (kind == extract_bp_kind::bp
13183 	       ? _("Bad breakpoint number at or near: '%s'")
13184 	       : _("Bad breakpoint location number at or near: '%s'"),
13185 	       bp_loc);
13186 
13187       const char *end;
13188       const char *start_first = bp_loc;
13189       const char *start_second = &arg[dash + 1];
13190       range.first = extract_bp_num (kind, start_first, '-');
13191       range.second = extract_bp_num (kind, start_second, '\0', &end);
13192 
13193       if (range.first > range.second)
13194 	error (kind == extract_bp_kind::bp
13195 	       ? _("Inverted breakpoint range at '%.*s'")
13196 	       : _("Inverted breakpoint location range at '%.*s'"),
13197 	       int (end - start_first), start_first);
13198     }
13199   else
13200     {
13201       /* bp_loc is a single value.  */
13202       range.first = extract_bp_num (kind, bp_loc, '\0');
13203       range.second = range.first;
13204     }
13205   return range;
13206 }
13207 
13208 /* Extract the breakpoint/location range specified by ARG.  Returns
13209    the breakpoint range in BP_NUM_RANGE, and the location range in
13210    BP_LOC_RANGE.
13211 
13212    ARG may be in any of the following forms:
13213 
13214    x     where 'x' is a breakpoint number.
13215    x-y   where 'x' and 'y' specify a breakpoint numbers range.
13216    x.y   where 'x' is a breakpoint number and 'y' a location number.
13217    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
13218 	 location number range.
13219 */
13220 
13221 static void
13222 extract_bp_number_and_location (const std::string &arg,
13223 				std::pair<int, int> &bp_num_range,
13224 				std::pair<int, int> &bp_loc_range)
13225 {
13226   std::string::size_type dot = arg.find ('.');
13227 
13228   if (dot != std::string::npos)
13229     {
13230       /* Handle 'x.y' and 'x.y-z' cases.  */
13231 
13232       if (arg.length () == dot + 1 || dot == 0)
13233 	error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
13234 
13235       bp_num_range.first
13236 	= extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
13237       bp_num_range.second = bp_num_range.first;
13238 
13239       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
13240 					     arg, dot + 1);
13241     }
13242   else
13243     {
13244       /* Handle x and x-y cases.  */
13245 
13246       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
13247       bp_loc_range.first = 0;
13248       bp_loc_range.second = 0;
13249     }
13250 }
13251 
13252 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
13253    specifies whether to enable or disable.  */
13254 
13255 static void
13256 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
13257 {
13258   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
13259   if (loc != NULL)
13260     {
13261       if (loc->disabled_by_cond && enable)
13262 	error (_("Breakpoint %d's condition is invalid at location %d, "
13263 		 "cannot enable."), bp_num, loc_num);
13264 
13265       if (loc->enabled != enable)
13266 	{
13267 	  loc->enabled = enable;
13268 	  mark_breakpoint_location_modified (loc);
13269 	}
13270       if (target_supports_enable_disable_tracepoint ()
13271 	  && current_trace_status ()->running && loc->owner
13272 	  && is_tracepoint (loc->owner))
13273 	target_disable_tracepoint (loc);
13274     }
13275   update_global_location_list (UGLL_DONT_INSERT);
13276 
13277   gdb::observers::breakpoint_modified.notify (loc->owner);
13278 }
13279 
13280 /* Calculates LOC_NUM for LOC by traversing the bp_location chain of LOC's
13281    owner.  1-based indexing.  -1 signals NOT FOUND.  */
13282 
13283 static int
13284 find_loc_num_by_location (const bp_location *loc)
13285 {
13286   if (loc != nullptr && loc->owner != nullptr)
13287     {
13288       /* Locations use 1-based indexing.  */
13289       int loc_num = 1;
13290       for (bp_location *it : loc->owner->locations ())
13291 	{
13292 	  if (it == loc)
13293 	    return loc_num;
13294 	  loc_num++;
13295 	}
13296     }
13297   return -1;
13298 }
13299 
13300 /* Enable or disable a breakpoint location LOC.  ENABLE
13301    specifies whether to enable or disable.  */
13302 
13303 void
13304 enable_disable_bp_location (bp_location *loc, bool enable)
13305 {
13306   if (loc == nullptr)
13307     error (_("Breakpoint location is invalid."));
13308 
13309   if (loc->owner == nullptr)
13310     error (_("Breakpoint location does not have an owner breakpoint."));
13311 
13312   if (loc->disabled_by_cond && enable)
13313     {
13314       int loc_num = find_loc_num_by_location (loc);
13315       if (loc_num == -1)
13316 	error (_("Breakpoint location LOC_NUM could not be found."));
13317       else
13318 	error (_("Breakpoint %d's condition is invalid at location %d, "
13319 		 "cannot enable."), loc->owner->number, loc_num);
13320     }
13321 
13322   if (loc->enabled != enable)
13323     {
13324       loc->enabled = enable;
13325       mark_breakpoint_location_modified (loc);
13326     }
13327 
13328   if (target_supports_enable_disable_tracepoint ()
13329       && current_trace_status ()->running && loc->owner
13330       && is_tracepoint (loc->owner))
13331     target_disable_tracepoint (loc);
13332 
13333   update_global_location_list (UGLL_DONT_INSERT);
13334   gdb::observers::breakpoint_modified.notify (loc->owner);
13335 }
13336 
13337 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
13338    number of the breakpoint, and BP_LOC_RANGE specifies the
13339    (inclusive) range of location numbers of that breakpoint to
13340    enable/disable.  ENABLE specifies whether to enable or disable the
13341    location.  */
13342 
13343 static void
13344 enable_disable_breakpoint_location_range (int bp_num,
13345 					  std::pair<int, int> &bp_loc_range,
13346 					  bool enable)
13347 {
13348   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
13349     enable_disable_bp_num_loc (bp_num, i, enable);
13350 }
13351 
13352 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13353    If from_tty is nonzero, it prints a message to that effect,
13354    which ends with a period (no newline).  */
13355 
13356 void
13357 disable_breakpoint (struct breakpoint *bpt)
13358 {
13359   /* Never disable a watchpoint scope breakpoint; we want to
13360      hit them when we leave scope so we can delete both the
13361      watchpoint and its scope breakpoint at that time.  */
13362   if (bpt->type == bp_watchpoint_scope)
13363     return;
13364 
13365   bpt->enable_state = bp_disabled;
13366 
13367   /* Mark breakpoint locations modified.  */
13368   mark_breakpoint_modified (bpt);
13369 
13370   if (target_supports_enable_disable_tracepoint ()
13371       && current_trace_status ()->running && is_tracepoint (bpt))
13372     {
13373       for (bp_location *location : bpt->locations ())
13374 	target_disable_tracepoint (location);
13375     }
13376 
13377   update_global_location_list (UGLL_DONT_INSERT);
13378 
13379   gdb::observers::breakpoint_modified.notify (bpt);
13380 }
13381 
13382 /* Enable or disable the breakpoint(s) or breakpoint location(s)
13383    specified in ARGS.  ARGS may be in any of the formats handled by
13384    extract_bp_number_and_location.  ENABLE specifies whether to enable
13385    or disable the breakpoints/locations.  */
13386 
13387 static void
13388 enable_disable_command (const char *args, int from_tty, bool enable)
13389 {
13390   if (args == 0)
13391     {
13392       for (breakpoint *bpt : all_breakpoints ())
13393 	if (user_breakpoint_p (bpt))
13394 	  {
13395 	    if (enable)
13396 	      enable_breakpoint (bpt);
13397 	    else
13398 	      disable_breakpoint (bpt);
13399 	  }
13400     }
13401   else
13402     {
13403       std::string num = extract_arg (&args);
13404 
13405       while (!num.empty ())
13406 	{
13407 	  std::pair<int, int> bp_num_range, bp_loc_range;
13408 
13409 	  extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
13410 
13411 	  if (bp_loc_range.first == bp_loc_range.second
13412 	      && (bp_loc_range.first == 0
13413 		  || (bp_loc_range.first == 1
13414 		      && bp_num_range.first == bp_num_range.second
13415 		      && !has_multiple_locations (bp_num_range.first))))
13416 	    {
13417 	      /* Handle breakpoint ids with formats 'x' or 'x-z'
13418 		 or 'y.1' where y has only one code location.  */
13419 	      map_breakpoint_number_range (bp_num_range,
13420 					   enable
13421 					   ? enable_breakpoint
13422 					   : disable_breakpoint);
13423 	    }
13424 	  else
13425 	    {
13426 	      /* Handle breakpoint ids with formats 'x.y' or
13427 		 'x.y-z'.  */
13428 	      enable_disable_breakpoint_location_range
13429 		(bp_num_range.first, bp_loc_range, enable);
13430 	    }
13431 	  num = extract_arg (&args);
13432 	}
13433     }
13434 }
13435 
13436 /* The disable command disables the specified breakpoints/locations
13437    (or all defined breakpoints) so they're no longer effective in
13438    stopping the inferior.  ARGS may be in any of the forms defined in
13439    extract_bp_number_and_location.  */
13440 
13441 static void
13442 disable_command (const char *args, int from_tty)
13443 {
13444   enable_disable_command (args, from_tty, false);
13445 }
13446 
13447 static void
13448 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13449 			int count)
13450 {
13451   int target_resources_ok;
13452 
13453   if (bpt->type == bp_hardware_breakpoint)
13454     {
13455       int i;
13456       i = hw_breakpoint_used_count ();
13457       target_resources_ok =
13458 	target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
13459 					    i + 1, 0);
13460       if (target_resources_ok == 0)
13461 	error (_("No hardware breakpoint support in the target."));
13462       else if (target_resources_ok < 0)
13463 	error (_("Hardware breakpoints used exceeds limit."));
13464     }
13465 
13466   if (is_watchpoint (bpt))
13467     {
13468       /* Initialize it just to avoid a GCC false warning.  */
13469       enum enable_state orig_enable_state = bp_disabled;
13470 
13471       try
13472 	{
13473 	  struct watchpoint *w = (struct watchpoint *) bpt;
13474 
13475 	  orig_enable_state = bpt->enable_state;
13476 	  bpt->enable_state = bp_enabled;
13477 	  update_watchpoint (w, true /* reparse */);
13478 	}
13479       catch (const gdb_exception &e)
13480 	{
13481 	  bpt->enable_state = orig_enable_state;
13482 	  exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13483 			     bpt->number);
13484 	  return;
13485 	}
13486     }
13487 
13488   bpt->enable_state = bp_enabled;
13489 
13490   /* Mark breakpoint locations modified.  */
13491   mark_breakpoint_modified (bpt);
13492 
13493   if (target_supports_enable_disable_tracepoint ()
13494       && current_trace_status ()->running && is_tracepoint (bpt))
13495     {
13496       for (bp_location *location : bpt->locations ())
13497 	target_enable_tracepoint (location);
13498     }
13499 
13500   bpt->disposition = disposition;
13501   bpt->enable_count = count;
13502   update_global_location_list (UGLL_MAY_INSERT);
13503 
13504   gdb::observers::breakpoint_modified.notify (bpt);
13505 }
13506 
13507 
13508 void
13509 enable_breakpoint (struct breakpoint *bpt)
13510 {
13511   enable_breakpoint_disp (bpt, bpt->disposition, 0);
13512 }
13513 
13514 /* The enable command enables the specified breakpoints/locations (or
13515    all defined breakpoints) so they once again become (or continue to
13516    be) effective in stopping the inferior.  ARGS may be in any of the
13517    forms defined in extract_bp_number_and_location.  */
13518 
13519 static void
13520 enable_command (const char *args, int from_tty)
13521 {
13522   enable_disable_command (args, from_tty, true);
13523 }
13524 
13525 static void
13526 enable_once_command (const char *args, int from_tty)
13527 {
13528   map_breakpoint_numbers
13529     (args, [&] (breakpoint *b)
13530      {
13531        iterate_over_related_breakpoints
13532 	 (b, [&] (breakpoint *bpt)
13533 	  {
13534 	    enable_breakpoint_disp (bpt, disp_disable, 1);
13535 	  });
13536      });
13537 }
13538 
13539 static void
13540 enable_count_command (const char *args, int from_tty)
13541 {
13542   int count;
13543 
13544   if (args == NULL)
13545     error_no_arg (_("hit count"));
13546 
13547   count = get_number (&args);
13548 
13549   map_breakpoint_numbers
13550     (args, [&] (breakpoint *b)
13551      {
13552        iterate_over_related_breakpoints
13553 	 (b, [&] (breakpoint *bpt)
13554 	  {
13555 	    enable_breakpoint_disp (bpt, disp_disable, count);
13556 	  });
13557      });
13558 }
13559 
13560 static void
13561 enable_delete_command (const char *args, int from_tty)
13562 {
13563   map_breakpoint_numbers
13564     (args, [&] (breakpoint *b)
13565      {
13566        iterate_over_related_breakpoints
13567 	 (b, [&] (breakpoint *bpt)
13568 	  {
13569 	    enable_breakpoint_disp (bpt, disp_del, 1);
13570 	  });
13571      });
13572 }
13573 
13574 /* Invalidate last known value of any hardware watchpoint if
13575    the memory which that value represents has been written to by
13576    GDB itself.  */
13577 
13578 static void
13579 invalidate_bp_value_on_memory_change (struct inferior *inferior,
13580 				      CORE_ADDR addr, ssize_t len,
13581 				      const bfd_byte *data)
13582 {
13583   for (breakpoint *bp : all_breakpoints ())
13584     if (bp->enable_state == bp_enabled
13585 	&& bp->type == bp_hardware_watchpoint)
13586       {
13587 	struct watchpoint *wp = (struct watchpoint *) bp;
13588 
13589 	if (wp->val_valid && wp->val != nullptr)
13590 	  {
13591 	    for (bp_location *loc : bp->locations ())
13592 	      if (loc->loc_type == bp_loc_hardware_watchpoint
13593 		  && loc->address + loc->length > addr
13594 		  && addr + len > loc->address)
13595 		{
13596 		  wp->val = NULL;
13597 		  wp->val_valid = false;
13598 		}
13599 	  }
13600       }
13601 }
13602 
13603 /* Create and insert a breakpoint for software single step.  */
13604 
13605 void
13606 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13607 			       const address_space *aspace,
13608 			       CORE_ADDR next_pc)
13609 {
13610   struct thread_info *tp = inferior_thread ();
13611   struct symtab_and_line sal;
13612   CORE_ADDR pc = next_pc;
13613 
13614   if (tp->control.single_step_breakpoints == NULL)
13615     {
13616       std::unique_ptr<breakpoint> b
13617 	(new momentary_breakpoint (gdbarch, bp_single_step,
13618 				   current_program_space,
13619 				   null_frame_id,
13620 				   tp->global_num));
13621 
13622       tp->control.single_step_breakpoints
13623 	= add_to_breakpoint_chain (std::move (b));
13624     }
13625 
13626   sal = find_pc_line (pc, 0);
13627   sal.pc = pc;
13628   sal.section = find_pc_overlay (pc);
13629   sal.explicit_pc = 1;
13630 
13631   auto *ss_bp
13632     = (gdb::checked_static_cast<momentary_breakpoint *>
13633        (tp->control.single_step_breakpoints));
13634   ss_bp->add_location (sal);
13635 
13636   update_global_location_list (UGLL_INSERT);
13637 }
13638 
13639 /* Insert single step breakpoints according to the current state.  */
13640 
13641 int
13642 insert_single_step_breakpoints (struct gdbarch *gdbarch)
13643 {
13644   struct regcache *regcache = get_current_regcache ();
13645   std::vector<CORE_ADDR> next_pcs;
13646 
13647   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
13648 
13649   if (!next_pcs.empty ())
13650     {
13651       frame_info_ptr frame = get_current_frame ();
13652       const address_space *aspace = get_frame_address_space (frame);
13653 
13654       for (CORE_ADDR pc : next_pcs)
13655 	insert_single_step_breakpoint (gdbarch, aspace, pc);
13656 
13657       return 1;
13658     }
13659   else
13660     return 0;
13661 }
13662 
13663 /* See breakpoint.h.  */
13664 
13665 int
13666 breakpoint_has_location_inserted_here (struct breakpoint *bp,
13667 				       const address_space *aspace,
13668 				       CORE_ADDR pc)
13669 {
13670   for (bp_location *loc : bp->locations ())
13671     if (loc->inserted
13672 	&& breakpoint_location_address_match (loc, aspace, pc))
13673       return 1;
13674 
13675   return 0;
13676 }
13677 
13678 /* Check whether a software single-step breakpoint is inserted at
13679    PC.  */
13680 
13681 int
13682 single_step_breakpoint_inserted_here_p (const address_space *aspace,
13683 					CORE_ADDR pc)
13684 {
13685   for (breakpoint *bpt : all_breakpoints ())
13686     {
13687       if (bpt->type == bp_single_step
13688 	  && breakpoint_has_location_inserted_here (bpt, aspace, pc))
13689 	return 1;
13690     }
13691   return 0;
13692 }
13693 
13694 /* Tracepoint-specific operations.  */
13695 
13696 /* Set tracepoint count to NUM.  */
13697 static void
13698 set_tracepoint_count (int num)
13699 {
13700   tracepoint_count = num;
13701   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
13702 }
13703 
13704 static void
13705 trace_command (const char *arg, int from_tty)
13706 {
13707   location_spec_up locspec = string_to_location_spec (&arg,
13708 						      current_language);
13709   const struct breakpoint_ops *ops = breakpoint_ops_for_location_spec
13710     (locspec.get (), true /* is_tracepoint */);
13711 
13712   create_breakpoint (get_current_arch (),
13713 		     locspec.get (),
13714 		     NULL, 0, arg, false, 1 /* parse arg */,
13715 		     0 /* tempflag */,
13716 		     bp_tracepoint /* type_wanted */,
13717 		     0 /* Ignore count */,
13718 		     pending_break_support,
13719 		     ops,
13720 		     from_tty,
13721 		     1 /* enabled */,
13722 		     0 /* internal */, 0);
13723 }
13724 
13725 static void
13726 ftrace_command (const char *arg, int from_tty)
13727 {
13728   location_spec_up locspec = string_to_location_spec (&arg,
13729 						      current_language);
13730   create_breakpoint (get_current_arch (),
13731 		     locspec.get (),
13732 		     NULL, 0, arg, false, 1 /* parse arg */,
13733 		     0 /* tempflag */,
13734 		     bp_fast_tracepoint /* type_wanted */,
13735 		     0 /* Ignore count */,
13736 		     pending_break_support,
13737 		     &code_breakpoint_ops,
13738 		     from_tty,
13739 		     1 /* enabled */,
13740 		     0 /* internal */, 0);
13741 }
13742 
13743 /* strace command implementation.  Creates a static tracepoint.  */
13744 
13745 static void
13746 strace_command (const char *arg, int from_tty)
13747 {
13748   const struct breakpoint_ops *ops;
13749   location_spec_up locspec;
13750   enum bptype type;
13751 
13752   /* Decide if we are dealing with a static tracepoint marker (`-m'),
13753      or with a normal static tracepoint.  */
13754   if (arg && startswith (arg, "-m") && isspace (arg[2]))
13755     {
13756       ops = &strace_marker_breakpoint_ops;
13757       locspec = new_linespec_location_spec (&arg,
13758 					    symbol_name_match_type::FULL);
13759       type = bp_static_marker_tracepoint;
13760     }
13761   else
13762     {
13763       ops = &code_breakpoint_ops;
13764       locspec = string_to_location_spec (&arg, current_language);
13765       type = bp_static_tracepoint;
13766     }
13767 
13768   create_breakpoint (get_current_arch (),
13769 		     locspec.get (),
13770 		     NULL, 0, arg, false, 1 /* parse arg */,
13771 		     0 /* tempflag */,
13772 		     type /* type_wanted */,
13773 		     0 /* Ignore count */,
13774 		     pending_break_support,
13775 		     ops,
13776 		     from_tty,
13777 		     1 /* enabled */,
13778 		     0 /* internal */, 0);
13779 }
13780 
13781 /* Set up a fake reader function that gets command lines from a linked
13782    list that was acquired during tracepoint uploading.  */
13783 
13784 static struct uploaded_tp *this_utp;
13785 static int next_cmd;
13786 
13787 static const char *
13788 read_uploaded_action (std::string &buffer)
13789 {
13790   char *rslt = nullptr;
13791 
13792   if (next_cmd < this_utp->cmd_strings.size ())
13793     {
13794       rslt = this_utp->cmd_strings[next_cmd].get ();
13795       next_cmd++;
13796     }
13797 
13798   return rslt;
13799 }
13800 
13801 /* Given information about a tracepoint as recorded on a target (which
13802    can be either a live system or a trace file), attempt to create an
13803    equivalent GDB tracepoint.  This is not a reliable process, since
13804    the target does not necessarily have all the information used when
13805    the tracepoint was originally defined.  */
13806 
13807 struct tracepoint *
13808 create_tracepoint_from_upload (struct uploaded_tp *utp)
13809 {
13810   const char *addr_str;
13811   char small_buf[100];
13812   struct tracepoint *tp;
13813 
13814   if (utp->at_string)
13815     addr_str = utp->at_string.get ();
13816   else
13817     {
13818       /* In the absence of a source location, fall back to raw
13819 	 address.  Since there is no way to confirm that the address
13820 	 means the same thing as when the trace was started, warn the
13821 	 user.  */
13822       warning (_("Uploaded tracepoint %d has no "
13823 		 "source location, using raw address"),
13824 	       utp->number);
13825       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
13826       addr_str = small_buf;
13827     }
13828 
13829   /* There's not much we can do with a sequence of bytecodes.  */
13830   if (utp->cond && !utp->cond_string)
13831     warning (_("Uploaded tracepoint %d condition "
13832 	       "has no source form, ignoring it"),
13833 	     utp->number);
13834 
13835   location_spec_up locspec = string_to_location_spec (&addr_str,
13836 						      current_language);
13837   if (!create_breakpoint (get_current_arch (),
13838 			  locspec.get (),
13839 			  utp->cond_string.get (), -1, addr_str,
13840 			  false /* force_condition */,
13841 			  0 /* parse cond/thread */,
13842 			  0 /* tempflag */,
13843 			  utp->type /* type_wanted */,
13844 			  0 /* Ignore count */,
13845 			  pending_break_support,
13846 			  &code_breakpoint_ops,
13847 			  0 /* from_tty */,
13848 			  utp->enabled /* enabled */,
13849 			  0 /* internal */,
13850 			  CREATE_BREAKPOINT_FLAGS_INSERTED))
13851     return NULL;
13852 
13853   /* Get the tracepoint we just created.  */
13854   tp = get_tracepoint (tracepoint_count);
13855   gdb_assert (tp != NULL);
13856 
13857   if (utp->pass > 0)
13858     {
13859       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
13860 		 tp->number);
13861 
13862       trace_pass_command (small_buf, 0);
13863     }
13864 
13865   /* If we have uploaded versions of the original commands, set up a
13866      special-purpose "reader" function and call the usual command line
13867      reader, then pass the result to the breakpoint command-setting
13868      function.  */
13869   if (!utp->cmd_strings.empty ())
13870     {
13871       counted_command_line cmd_list;
13872 
13873       this_utp = utp;
13874       next_cmd = 0;
13875 
13876       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
13877 
13878       breakpoint_set_commands (tp, std::move (cmd_list));
13879     }
13880   else if (!utp->actions.empty ()
13881 	   || !utp->step_actions.empty ())
13882     warning (_("Uploaded tracepoint %d actions "
13883 	       "have no source form, ignoring them"),
13884 	     utp->number);
13885 
13886   /* Copy any status information that might be available.  */
13887   tp->hit_count = utp->hit_count;
13888   tp->traceframe_usage = utp->traceframe_usage;
13889 
13890   return tp;
13891 }
13892 
13893 /* Print information on tracepoint number TPNUM_EXP, or all if
13894    omitted.  */
13895 
13896 static void
13897 info_tracepoints_command (const char *args, int from_tty)
13898 {
13899   struct ui_out *uiout = current_uiout;
13900   int num_printed;
13901 
13902   num_printed = breakpoint_1 (args, false, is_tracepoint);
13903 
13904   if (num_printed == 0)
13905     {
13906       if (args == NULL || *args == '\0')
13907 	uiout->message ("No tracepoints.\n");
13908       else
13909 	uiout->message ("No tracepoint matching '%s'.\n", args);
13910     }
13911 
13912   default_collect_info ();
13913 }
13914 
13915 /* The 'enable trace' command enables tracepoints.
13916    Not supported by all targets.  */
13917 static void
13918 enable_trace_command (const char *args, int from_tty)
13919 {
13920   enable_command (args, from_tty);
13921 }
13922 
13923 /* The 'disable trace' command disables tracepoints.
13924    Not supported by all targets.  */
13925 static void
13926 disable_trace_command (const char *args, int from_tty)
13927 {
13928   disable_command (args, from_tty);
13929 }
13930 
13931 /* Remove a tracepoint (or all if no argument).  */
13932 static void
13933 delete_trace_command (const char *arg, int from_tty)
13934 {
13935   dont_repeat ();
13936 
13937   if (arg == 0)
13938     {
13939       int breaks_to_delete = 0;
13940 
13941       /* Delete all breakpoints if no argument.
13942 	 Do not delete internal or call-dummy breakpoints, these
13943 	 have to be deleted with an explicit breakpoint number
13944 	 argument.  */
13945       for (breakpoint *tp : all_tracepoints ())
13946 	if (is_tracepoint (tp) && user_breakpoint_p (tp))
13947 	  {
13948 	    breaks_to_delete = 1;
13949 	    break;
13950 	  }
13951 
13952       /* Ask user only if there are some breakpoints to delete.  */
13953       if (!from_tty
13954 	  || (breaks_to_delete && query (_("Delete all tracepoints? "))))
13955 	{
13956 	  for (breakpoint *b : all_breakpoints_safe ())
13957 	    if (is_tracepoint (b) && user_breakpoint_p (b))
13958 	      delete_breakpoint (b);
13959 	}
13960     }
13961   else
13962     map_breakpoint_numbers
13963       (arg, [&] (breakpoint *br)
13964        {
13965 	 iterate_over_related_breakpoints (br, delete_breakpoint);
13966        });
13967 }
13968 
13969 /* Helper function for trace_pass_command.  */
13970 
13971 static void
13972 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
13973 {
13974   tp->pass_count = count;
13975   gdb::observers::breakpoint_modified.notify (tp);
13976   if (from_tty)
13977     gdb_printf (_("Setting tracepoint %d's passcount to %d\n"),
13978 		tp->number, count);
13979 }
13980 
13981 /* Set passcount for tracepoint.
13982 
13983    First command argument is passcount, second is tracepoint number.
13984    If tracepoint number omitted, apply to most recently defined.
13985    Also accepts special argument "all".  */
13986 
13987 static void
13988 trace_pass_command (const char *args, int from_tty)
13989 {
13990   struct tracepoint *t1;
13991   ULONGEST count;
13992 
13993   if (args == 0 || *args == 0)
13994     error (_("passcount command requires an "
13995 	     "argument (count + optional TP num)"));
13996 
13997   count = strtoulst (args, &args, 10);	/* Count comes first, then TP num.  */
13998 
13999   args = skip_spaces (args);
14000   if (*args && strncasecmp (args, "all", 3) == 0)
14001     {
14002       args += 3;			/* Skip special argument "all".  */
14003       if (*args)
14004 	error (_("Junk at end of arguments."));
14005 
14006       for (breakpoint *b : all_tracepoints ())
14007 	{
14008 	  t1 = (struct tracepoint *) b;
14009 	  trace_pass_set_count (t1, count, from_tty);
14010 	}
14011     }
14012   else if (*args == '\0')
14013     {
14014       t1 = get_tracepoint_by_number (&args, NULL);
14015       if (t1)
14016 	trace_pass_set_count (t1, count, from_tty);
14017     }
14018   else
14019     {
14020       number_or_range_parser parser (args);
14021       while (!parser.finished ())
14022 	{
14023 	  t1 = get_tracepoint_by_number (&args, &parser);
14024 	  if (t1)
14025 	    trace_pass_set_count (t1, count, from_tty);
14026 	}
14027     }
14028 }
14029 
14030 struct tracepoint *
14031 get_tracepoint (int num)
14032 {
14033   for (breakpoint *t : all_tracepoints ())
14034     if (t->number == num)
14035       return (struct tracepoint *) t;
14036 
14037   return NULL;
14038 }
14039 
14040 /* Find the tracepoint with the given target-side number (which may be
14041    different from the tracepoint number after disconnecting and
14042    reconnecting).  */
14043 
14044 struct tracepoint *
14045 get_tracepoint_by_number_on_target (int num)
14046 {
14047   for (breakpoint *b : all_tracepoints ())
14048     {
14049       struct tracepoint *t = (struct tracepoint *) b;
14050 
14051       if (t->number_on_target == num)
14052 	return t;
14053     }
14054 
14055   return NULL;
14056 }
14057 
14058 /* Utility: parse a tracepoint number and look it up in the list.
14059    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14060    If the argument is missing, the most recent tracepoint
14061    (tracepoint_count) is returned.  */
14062 
14063 struct tracepoint *
14064 get_tracepoint_by_number (const char **arg,
14065 			  number_or_range_parser *parser)
14066 {
14067   int tpnum;
14068   const char *instring = arg == NULL ? NULL : *arg;
14069 
14070   if (parser != NULL)
14071     {
14072       gdb_assert (!parser->finished ());
14073       tpnum = parser->get_number ();
14074     }
14075   else if (arg == NULL || *arg == NULL || ! **arg)
14076     tpnum = tracepoint_count;
14077   else
14078     tpnum = get_number (arg);
14079 
14080   if (tpnum <= 0)
14081     {
14082       if (instring && *instring)
14083 	gdb_printf (_("bad tracepoint number at or near '%s'\n"),
14084 		    instring);
14085       else
14086 	gdb_printf (_("No previous tracepoint\n"));
14087       return NULL;
14088     }
14089 
14090   for (breakpoint *t : all_tracepoints ())
14091     if (t->number == tpnum)
14092       return (struct tracepoint *) t;
14093 
14094   gdb_printf ("No tracepoint number %d.\n", tpnum);
14095   return NULL;
14096 }
14097 
14098 void
14099 breakpoint::print_recreate_thread (struct ui_file *fp) const
14100 {
14101   if (thread != -1)
14102     gdb_printf (fp, " thread %d", thread);
14103 
14104   if (task != 0)
14105     gdb_printf (fp, " task %d", task);
14106 
14107   gdb_printf (fp, "\n");
14108 }
14109 
14110 /* Save information on user settable breakpoints (watchpoints, etc) to
14111    a new script file named FILENAME.  If FILTER is non-NULL, call it
14112    on each breakpoint and only include the ones for which it returns
14113    true.  */
14114 
14115 static void
14116 save_breakpoints (const char *filename, int from_tty,
14117 		  bool (*filter) (const struct breakpoint *))
14118 {
14119   bool any = false;
14120   int extra_trace_bits = 0;
14121 
14122   if (filename == 0 || *filename == 0)
14123     error (_("Argument required (file name in which to save)"));
14124 
14125   /* See if we have anything to save.  */
14126   for (breakpoint *tp : all_breakpoints ())
14127     {
14128       /* Skip internal and momentary breakpoints.  */
14129       if (!user_breakpoint_p (tp))
14130 	continue;
14131 
14132       /* If we have a filter, only save the breakpoints it accepts.  */
14133       if (filter && !filter (tp))
14134 	continue;
14135 
14136       any = true;
14137 
14138       if (is_tracepoint (tp))
14139 	{
14140 	  extra_trace_bits = 1;
14141 
14142 	  /* We can stop searching.  */
14143 	  break;
14144 	}
14145     }
14146 
14147   if (!any)
14148     {
14149       warning (_("Nothing to save."));
14150       return;
14151     }
14152 
14153   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
14154 
14155   stdio_file fp;
14156 
14157   if (!fp.open (expanded_filename.get (), "w"))
14158     error (_("Unable to open file '%s' for saving (%s)"),
14159 	   expanded_filename.get (), safe_strerror (errno));
14160 
14161   if (extra_trace_bits)
14162     save_trace_state_variables (&fp);
14163 
14164   for (breakpoint *tp : all_breakpoints ())
14165     {
14166       /* Skip internal and momentary breakpoints.  */
14167       if (!user_breakpoint_p (tp))
14168 	continue;
14169 
14170       /* If we have a filter, only save the breakpoints it accepts.  */
14171       if (filter && !filter (tp))
14172 	continue;
14173 
14174       tp->print_recreate (&fp);
14175 
14176       /* Note, we can't rely on tp->number for anything, as we can't
14177 	 assume the recreated breakpoint numbers will match.  Use $bpnum
14178 	 instead.  */
14179 
14180       if (tp->cond_string)
14181 	fp.printf ("  condition $bpnum %s\n", tp->cond_string.get ());
14182 
14183       if (tp->ignore_count)
14184 	fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
14185 
14186       if (tp->type != bp_dprintf && tp->commands)
14187 	{
14188 	  fp.puts ("  commands\n");
14189 
14190 	  ui_out_redirect_pop redir (current_uiout, &fp);
14191 	  print_command_lines (current_uiout, tp->commands.get (), 2);
14192 
14193 	  fp.puts ("  end\n");
14194 	}
14195 
14196       if (tp->enable_state == bp_disabled)
14197 	fp.puts ("disable $bpnum\n");
14198 
14199       /* If this is a multi-location breakpoint, check if the locations
14200 	 should be individually disabled.  Watchpoint locations are
14201 	 special, and not user visible.  */
14202       if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14203 	{
14204 	  int n = 1;
14205 
14206 	  for (bp_location *loc : tp->locations ())
14207 	    {
14208 	      if (!loc->enabled)
14209 		fp.printf ("disable $bpnum.%d\n", n);
14210 
14211 	      n++;
14212 	    }
14213 	}
14214     }
14215 
14216   if (extra_trace_bits && !default_collect.empty ())
14217     fp.printf ("set default-collect %s\n", default_collect.c_str ());
14218 
14219   if (from_tty)
14220     gdb_printf (_("Saved to file '%s'.\n"), expanded_filename.get ());
14221 }
14222 
14223 /* The `save breakpoints' command.  */
14224 
14225 static void
14226 save_breakpoints_command (const char *args, int from_tty)
14227 {
14228   save_breakpoints (args, from_tty, NULL);
14229 }
14230 
14231 /* The `save tracepoints' command.  */
14232 
14233 static void
14234 save_tracepoints_command (const char *args, int from_tty)
14235 {
14236   save_breakpoints (args, from_tty, is_tracepoint);
14237 }
14238 
14239 
14240 /* This help string is used to consolidate all the help string for specifying
14241    locations used by several commands.  */
14242 
14243 #define LOCATION_SPEC_HELP_STRING \
14244 "Linespecs are colon-separated lists of location parameters, such as\n\
14245 source filename, function name, label name, and line number.\n\
14246 Example: To specify the start of a label named \"the_top\" in the\n\
14247 function \"fact\" in the file \"factorial.c\", use\n\
14248 \"factorial.c:fact:the_top\".\n\
14249 \n\
14250 Address locations begin with \"*\" and specify an exact address in the\n\
14251 program.  Example: To specify the fourth byte past the start function\n\
14252 \"main\", use \"*main + 4\".\n\
14253 \n\
14254 Explicit locations are similar to linespecs but use an option/argument\n\
14255 syntax to specify location parameters.\n\
14256 Example: To specify the start of the label named \"the_top\" in the\n\
14257 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
14258 -function fact -label the_top\".\n\
14259 \n\
14260 By default, a specified function is matched against the program's\n\
14261 functions in all scopes.  For C++, this means in all namespaces and\n\
14262 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
14263 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
14264 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
14265 specified name as a complete fully-qualified name instead."
14266 
14267 /* This help string is used for the break, hbreak, tbreak and thbreak
14268    commands.  It is defined as a macro to prevent duplication.
14269    COMMAND should be a string constant containing the name of the
14270    command.  */
14271 
14272 #define BREAK_ARGS_HELP(command) \
14273 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
14274 \t[-force-condition] [if CONDITION]\n\
14275 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
14276 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
14277 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
14278 `-probe-dtrace' (for a DTrace probe).\n\
14279 LOCATION may be a linespec, address, or explicit location as described\n\
14280 below.\n\
14281 \n\
14282 With no LOCATION, uses current execution address of the selected\n\
14283 stack frame.  This is useful for breaking on return to a stack frame.\n\
14284 \n\
14285 THREADNUM is the number from \"info threads\".\n\
14286 CONDITION is a boolean expression.\n\
14287 \n\
14288 With the \"-force-condition\" flag, the condition is defined even when\n\
14289 it is invalid for all current locations.\n\
14290 \n" LOCATION_SPEC_HELP_STRING "\n\n\
14291 Multiple breakpoints at one place are permitted, and useful if their\n\
14292 conditions are different.\n\
14293 \n\
14294 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14295 
14296 /* List of subcommands for "catch".  */
14297 static struct cmd_list_element *catch_cmdlist;
14298 
14299 /* List of subcommands for "tcatch".  */
14300 static struct cmd_list_element *tcatch_cmdlist;
14301 
14302 void
14303 add_catch_command (const char *name, const char *docstring,
14304 		   cmd_func_ftype *func,
14305 		   completer_ftype *completer,
14306 		   void *user_data_catch,
14307 		   void *user_data_tcatch)
14308 {
14309   struct cmd_list_element *command;
14310 
14311   command = add_cmd (name, class_breakpoint, docstring,
14312 		     &catch_cmdlist);
14313   command->func = func;
14314   command->set_context (user_data_catch);
14315   set_cmd_completer (command, completer);
14316 
14317   command = add_cmd (name, class_breakpoint, docstring,
14318 		     &tcatch_cmdlist);
14319   command->func = func;
14320   command->set_context (user_data_tcatch);
14321   set_cmd_completer (command, completer);
14322 }
14323 
14324 /* False if any of the breakpoint's locations could be a location where
14325    functions have been inlined, true otherwise.  */
14326 
14327 static bool
14328 is_non_inline_function (struct breakpoint *b)
14329 {
14330   /* The shared library event breakpoint is set on the address of a
14331      non-inline function.  */
14332   return (b->type == bp_shlib_event);
14333 }
14334 
14335 /* Nonzero if the specified PC cannot be a location where functions
14336    have been inlined.  */
14337 
14338 int
14339 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
14340 			   const target_waitstatus &ws)
14341 {
14342   for (breakpoint *b : all_breakpoints ())
14343     {
14344       if (!is_non_inline_function (b))
14345 	continue;
14346 
14347       for (bp_location *bl : b->locations ())
14348 	{
14349 	  if (!bl->shlib_disabled
14350 	      && bpstat_check_location (bl, aspace, pc, ws))
14351 	    return 1;
14352 	}
14353     }
14354 
14355   return 0;
14356 }
14357 
14358 /* Remove any references to OBJFILE which is going to be freed.  */
14359 
14360 void
14361 breakpoint_free_objfile (struct objfile *objfile)
14362 {
14363   for (bp_location *loc : all_bp_locations ())
14364     if (loc->symtab != NULL && loc->symtab->compunit ()->objfile () == objfile)
14365       loc->symtab = NULL;
14366 }
14367 
14368 /* Chain containing all defined "enable breakpoint" subcommands.  */
14369 
14370 static struct cmd_list_element *enablebreaklist = NULL;
14371 
14372 /* See breakpoint.h.  */
14373 
14374 cmd_list_element *commands_cmd_element = nullptr;
14375 
14376 void _initialize_breakpoint ();
14377 void
14378 _initialize_breakpoint ()
14379 {
14380   struct cmd_list_element *c;
14381 
14382   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
14383 					 "breakpoint");
14384   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
14385 				       "breakpoint");
14386   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
14387 					 "breakpoint");
14388 
14389   breakpoint_chain = 0;
14390   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
14391      before a breakpoint is set.  */
14392   breakpoint_count = 0;
14393 
14394   tracepoint_count = 0;
14395 
14396   add_com ("ignore", class_breakpoint, ignore_command, _("\
14397 Set ignore-count of breakpoint number N to COUNT.\n\
14398 Usage is `ignore N COUNT'."));
14399 
14400   commands_cmd_element = add_com ("commands", class_breakpoint,
14401 				  commands_command, _("\
14402 Set commands to be executed when the given breakpoints are hit.\n\
14403 Give a space-separated breakpoint list as argument after \"commands\".\n\
14404 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
14405 (e.g. `5-7').\n\
14406 With no argument, the targeted breakpoint is the last one set.\n\
14407 The commands themselves follow starting on the next line.\n\
14408 Type a line containing \"end\" to indicate the end of them.\n\
14409 Give \"silent\" as the first line to make the breakpoint silent;\n\
14410 then no output is printed when it is hit, except what the commands print."));
14411 
14412   const auto cc_opts = make_condition_command_options_def_group (nullptr);
14413   static std::string condition_command_help
14414     = gdb::option::build_help (_("\
14415 Specify breakpoint number N to break only if COND is true.\n\
14416 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
14417 is an expression to be evaluated whenever breakpoint N is reached.\n\
14418 \n\
14419 Options:\n\
14420 %OPTIONS%"), cc_opts);
14421 
14422   c = add_com ("condition", class_breakpoint, condition_command,
14423 	       condition_command_help.c_str ());
14424   set_cmd_completer_handle_brkchars (c, condition_completer);
14425 
14426   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14427 Set a temporary breakpoint.\n\
14428 Like \"break\" except the breakpoint is only temporary,\n\
14429 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
14430 by using \"enable delete\" on the breakpoint number.\n\
14431 \n"
14432 BREAK_ARGS_HELP ("tbreak")));
14433   set_cmd_completer (c, location_completer);
14434 
14435   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
14436 Set a hardware assisted breakpoint.\n\
14437 Like \"break\" except the breakpoint requires hardware support,\n\
14438 some target hardware may not have this support.\n\
14439 \n"
14440 BREAK_ARGS_HELP ("hbreak")));
14441   set_cmd_completer (c, location_completer);
14442 
14443   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
14444 Set a temporary hardware assisted breakpoint.\n\
14445 Like \"hbreak\" except the breakpoint is only temporary,\n\
14446 so it will be deleted when hit.\n\
14447 \n"
14448 BREAK_ARGS_HELP ("thbreak")));
14449   set_cmd_completer (c, location_completer);
14450 
14451   cmd_list_element *enable_cmd
14452     = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
14453 Enable all or some breakpoints.\n\
14454 Usage: enable [BREAKPOINTNUM]...\n\
14455 Give breakpoint numbers (separated by spaces) as arguments.\n\
14456 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14457 This is used to cancel the effect of the \"disable\" command.\n\
14458 With a subcommand you can enable temporarily."),
14459 		      &enablelist, 1, &cmdlist);
14460 
14461   add_com_alias ("en", enable_cmd, class_breakpoint, 1);
14462 
14463   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
14464 Enable all or some breakpoints.\n\
14465 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
14466 Give breakpoint numbers (separated by spaces) as arguments.\n\
14467 This is used to cancel the effect of the \"disable\" command.\n\
14468 May be abbreviated to simply \"enable\"."),
14469 		   &enablebreaklist, 1, &enablelist);
14470 
14471   add_cmd ("once", no_class, enable_once_command, _("\
14472 Enable some breakpoints for one hit.\n\
14473 Usage: enable breakpoints once BREAKPOINTNUM...\n\
14474 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14475 	   &enablebreaklist);
14476 
14477   add_cmd ("delete", no_class, enable_delete_command, _("\
14478 Enable some breakpoints and delete when hit.\n\
14479 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
14480 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14481 	   &enablebreaklist);
14482 
14483   add_cmd ("count", no_class, enable_count_command, _("\
14484 Enable some breakpoints for COUNT hits.\n\
14485 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
14486 If a breakpoint is hit while enabled in this fashion,\n\
14487 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14488 	   &enablebreaklist);
14489 
14490   add_cmd ("delete", no_class, enable_delete_command, _("\
14491 Enable some breakpoints and delete when hit.\n\
14492 Usage: enable delete BREAKPOINTNUM...\n\
14493 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14494 	   &enablelist);
14495 
14496   add_cmd ("once", no_class, enable_once_command, _("\
14497 Enable some breakpoints for one hit.\n\
14498 Usage: enable once BREAKPOINTNUM...\n\
14499 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14500 	   &enablelist);
14501 
14502   add_cmd ("count", no_class, enable_count_command, _("\
14503 Enable some breakpoints for COUNT hits.\n\
14504 Usage: enable count COUNT BREAKPOINTNUM...\n\
14505 If a breakpoint is hit while enabled in this fashion,\n\
14506 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14507 	   &enablelist);
14508 
14509   cmd_list_element *disable_cmd
14510     = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
14511 Disable all or some breakpoints.\n\
14512 Usage: disable [BREAKPOINTNUM]...\n\
14513 Arguments are breakpoint numbers with spaces in between.\n\
14514 To disable all breakpoints, give no argument.\n\
14515 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
14516 		      &disablelist, 1, &cmdlist);
14517   add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
14518   add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
14519 
14520   add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
14521 Disable all or some breakpoints.\n\
14522 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
14523 Arguments are breakpoint numbers with spaces in between.\n\
14524 To disable all breakpoints, give no argument.\n\
14525 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
14526 This command may be abbreviated \"disable\"."),
14527 	   &disablelist);
14528 
14529   cmd_list_element *delete_cmd
14530     = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
14531 Delete all or some breakpoints.\n\
14532 Usage: delete [BREAKPOINTNUM]...\n\
14533 Arguments are breakpoint numbers with spaces in between.\n\
14534 To delete all breakpoints, give no argument.\n\
14535 \n\
14536 Also a prefix command for deletion of other GDB objects."),
14537 		      &deletelist, 1, &cmdlist);
14538   add_com_alias ("d", delete_cmd, class_breakpoint, 1);
14539   add_com_alias ("del", delete_cmd, class_breakpoint, 1);
14540 
14541   add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
14542 Delete all or some breakpoints or auto-display expressions.\n\
14543 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
14544 Arguments are breakpoint numbers with spaces in between.\n\
14545 To delete all breakpoints, give no argument.\n\
14546 This command may be abbreviated \"delete\"."),
14547 	   &deletelist);
14548 
14549   cmd_list_element *clear_cmd
14550    = add_com ("clear", class_breakpoint, clear_command, _("\
14551 Clear breakpoint at specified location.\n\
14552 Argument may be a linespec, explicit, or address location as described below.\n\
14553 \n\
14554 With no argument, clears all breakpoints in the line that the selected frame\n\
14555 is executing in.\n"
14556 "\n" LOCATION_SPEC_HELP_STRING "\n\n\
14557 See also the \"delete\" command which clears breakpoints by number."));
14558   add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
14559 
14560   cmd_list_element *break_cmd
14561     = add_com ("break", class_breakpoint, break_command, _("\
14562 Set breakpoint at specified location.\n"
14563 BREAK_ARGS_HELP ("break")));
14564   set_cmd_completer (break_cmd, location_completer);
14565 
14566   add_com_alias ("b", break_cmd, class_run, 1);
14567   add_com_alias ("br", break_cmd, class_run, 1);
14568   add_com_alias ("bre", break_cmd, class_run, 1);
14569   add_com_alias ("brea", break_cmd, class_run, 1);
14570 
14571   cmd_list_element *info_breakpoints_cmd
14572     = add_info ("breakpoints", info_breakpoints_command, _("\
14573 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14574 The \"Type\" column indicates one of:\n\
14575 \tbreakpoint     - normal breakpoint\n\
14576 \twatchpoint     - watchpoint\n\
14577 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14578 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14579 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14580 address and file/line number respectively.\n\
14581 \n\
14582 Convenience variable \"$_\" and default examine address for \"x\"\n\
14583 are set to the address of the last breakpoint listed unless the command\n\
14584 is prefixed with \"server \".\n\n\
14585 Convenience variable \"$bpnum\" contains the number of the last\n\
14586 breakpoint set."));
14587 
14588   add_info_alias ("b", info_breakpoints_cmd, 1);
14589 
14590   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14591 Status of all breakpoints, or breakpoint number NUMBER.\n\
14592 The \"Type\" column indicates one of:\n\
14593 \tbreakpoint     - normal breakpoint\n\
14594 \twatchpoint     - watchpoint\n\
14595 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
14596 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14597 \tuntil          - internal breakpoint used by the \"until\" command\n\
14598 \tfinish         - internal breakpoint used by the \"finish\" command\n\
14599 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14600 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14601 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14602 address and file/line number respectively.\n\
14603 \n\
14604 Convenience variable \"$_\" and default examine address for \"x\"\n\
14605 are set to the address of the last breakpoint listed unless the command\n\
14606 is prefixed with \"server \".\n\n\
14607 Convenience variable \"$bpnum\" contains the number of the last\n\
14608 breakpoint set."),
14609 	   &maintenanceinfolist);
14610 
14611   add_basic_prefix_cmd ("catch", class_breakpoint, _("\
14612 Set catchpoints to catch events."),
14613 			&catch_cmdlist,
14614 			0/*allow-unknown*/, &cmdlist);
14615 
14616   add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
14617 Set temporary catchpoints to catch events."),
14618 			&tcatch_cmdlist,
14619 			0/*allow-unknown*/, &cmdlist);
14620 
14621   const auto opts = make_watch_options_def_group (nullptr);
14622 
14623   static const std::string watch_help = gdb::option::build_help (_("\
14624 Set a watchpoint for EXPRESSION.\n\
14625 Usage: watch [-location] EXPRESSION\n\
14626 \n\
14627 Options:\n\
14628 %OPTIONS%\n\
14629 \n\
14630 A watchpoint stops execution of your program whenever the value of\n\
14631 an expression changes."), opts);
14632   c = add_com ("watch", class_breakpoint, watch_command,
14633 	       watch_help.c_str ());
14634   set_cmd_completer_handle_brkchars (c, watch_command_completer);
14635 
14636   static const std::string rwatch_help = gdb::option::build_help (_("\
14637 Set a read watchpoint for EXPRESSION.\n\
14638 Usage: rwatch [-location] EXPRESSION\n\
14639 \n\
14640 Options:\n\
14641 %OPTIONS%\n\
14642 \n\
14643 A read watchpoint stops execution of your program whenever the value of\n\
14644 an expression is read."), opts);
14645   c = add_com ("rwatch", class_breakpoint, rwatch_command,
14646 	       rwatch_help.c_str ());
14647   set_cmd_completer_handle_brkchars (c, watch_command_completer);
14648 
14649   static const std::string awatch_help = gdb::option::build_help (_("\
14650 Set an access watchpoint for EXPRESSION.\n\
14651 Usage: awatch [-location] EXPRESSION\n\
14652 \n\
14653 Options:\n\
14654 %OPTIONS%\n\
14655 \n\
14656 An access watchpoint stops execution of your program whenever the value\n\
14657 of an expression is either read or written."), opts);
14658   c = add_com ("awatch", class_breakpoint, awatch_command,
14659 	       awatch_help.c_str ());
14660   set_cmd_completer_handle_brkchars (c, watch_command_completer);
14661 
14662   add_info ("watchpoints", info_watchpoints_command, _("\
14663 Status of specified watchpoints (all watchpoints if no argument)."));
14664 
14665   /* XXX: cagney/2005-02-23: This should be a boolean, and should
14666      respond to changes - contrary to the description.  */
14667   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
14668 			    &can_use_hw_watchpoints, _("\
14669 Set debugger's willingness to use watchpoint hardware."), _("\
14670 Show debugger's willingness to use watchpoint hardware."), _("\
14671 If zero, gdb will not use hardware for new watchpoints, even if\n\
14672 such is available.  (However, any hardware watchpoints that were\n\
14673 created before setting this to nonzero, will continue to use watchpoint\n\
14674 hardware.)"),
14675 			    NULL,
14676 			    show_can_use_hw_watchpoints,
14677 			    &setlist, &showlist);
14678 
14679   can_use_hw_watchpoints = 1;
14680 
14681   /* Tracepoint manipulation commands.  */
14682 
14683   cmd_list_element *trace_cmd
14684     = add_com ("trace", class_breakpoint, trace_command, _("\
14685 Set a tracepoint at specified location.\n\
14686 \n"
14687 BREAK_ARGS_HELP ("trace") "\n\
14688 Do \"help tracepoints\" for info on other tracepoint commands."));
14689   set_cmd_completer (trace_cmd, location_completer);
14690 
14691   add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
14692   add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
14693   add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
14694   add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
14695 
14696   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
14697 Set a fast tracepoint at specified location.\n\
14698 \n"
14699 BREAK_ARGS_HELP ("ftrace") "\n\
14700 Do \"help tracepoints\" for info on other tracepoint commands."));
14701   set_cmd_completer (c, location_completer);
14702 
14703   c = add_com ("strace", class_breakpoint, strace_command, _("\
14704 Set a static tracepoint at location or marker.\n\
14705 \n\
14706 strace [LOCATION] [if CONDITION]\n\
14707 LOCATION may be a linespec, explicit, or address location (described below) \n\
14708 or -m MARKER_ID.\n\n\
14709 If a marker id is specified, probe the marker with that name.  With\n\
14710 no LOCATION, uses current execution address of the selected stack frame.\n\
14711 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
14712 This collects arbitrary user data passed in the probe point call to the\n\
14713 tracing library.  You can inspect it when analyzing the trace buffer,\n\
14714 by printing the $_sdata variable like any other convenience variable.\n\
14715 \n\
14716 CONDITION is a boolean expression.\n\
14717 \n" LOCATION_SPEC_HELP_STRING "\n\n\
14718 Multiple tracepoints at one place are permitted, and useful if their\n\
14719 conditions are different.\n\
14720 \n\
14721 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
14722 Do \"help tracepoints\" for info on other tracepoint commands."));
14723   set_cmd_completer (c, location_completer);
14724 
14725   cmd_list_element *info_tracepoints_cmd
14726     = add_info ("tracepoints", info_tracepoints_command, _("\
14727 Status of specified tracepoints (all tracepoints if no argument).\n\
14728 Convenience variable \"$tpnum\" contains the number of the\n\
14729 last tracepoint set."));
14730 
14731   add_info_alias ("tp", info_tracepoints_cmd, 1);
14732 
14733   cmd_list_element *delete_tracepoints_cmd
14734     = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
14735 Delete specified tracepoints.\n\
14736 Arguments are tracepoint numbers, separated by spaces.\n\
14737 No argument means delete all tracepoints."),
14738 	   &deletelist);
14739   add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
14740 
14741   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
14742 Disable specified tracepoints.\n\
14743 Arguments are tracepoint numbers, separated by spaces.\n\
14744 No argument means disable all tracepoints."),
14745 	   &disablelist);
14746   deprecate_cmd (c, "disable");
14747 
14748   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
14749 Enable specified tracepoints.\n\
14750 Arguments are tracepoint numbers, separated by spaces.\n\
14751 No argument means enable all tracepoints."),
14752 	   &enablelist);
14753   deprecate_cmd (c, "enable");
14754 
14755   add_com ("passcount", class_trace, trace_pass_command, _("\
14756 Set the passcount for a tracepoint.\n\
14757 The trace will end when the tracepoint has been passed 'count' times.\n\
14758 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
14759 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
14760 
14761   add_basic_prefix_cmd ("save", class_breakpoint,
14762 			_("Save breakpoint definitions as a script."),
14763 			&save_cmdlist,
14764 			0/*allow-unknown*/, &cmdlist);
14765 
14766   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
14767 Save current breakpoint definitions as a script.\n\
14768 This includes all types of breakpoints (breakpoints, watchpoints,\n\
14769 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
14770 session to restore them."),
14771 	       &save_cmdlist);
14772   set_cmd_completer (c, filename_completer);
14773 
14774   cmd_list_element *save_tracepoints_cmd
14775     = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
14776 Save current tracepoint definitions as a script.\n\
14777 Use the 'source' command in another debug session to restore them."),
14778 	       &save_cmdlist);
14779   set_cmd_completer (save_tracepoints_cmd, filename_completer);
14780 
14781   c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
14782   deprecate_cmd (c, "save tracepoints");
14783 
14784   add_setshow_prefix_cmd ("breakpoint", class_maintenance,
14785 			  _("\
14786 Breakpoint specific settings.\n\
14787 Configure various breakpoint-specific variables such as\n\
14788 pending breakpoint behavior."),
14789 			  _("\
14790 Breakpoint specific settings.\n\
14791 Configure various breakpoint-specific variables such as\n\
14792 pending breakpoint behavior."),
14793 			  &breakpoint_set_cmdlist, &breakpoint_show_cmdlist,
14794 			  &setlist, &showlist);
14795 
14796   add_setshow_auto_boolean_cmd ("pending", no_class,
14797 				&pending_break_support, _("\
14798 Set debugger's behavior regarding pending breakpoints."), _("\
14799 Show debugger's behavior regarding pending breakpoints."), _("\
14800 If on, an unrecognized breakpoint location will cause gdb to create a\n\
14801 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
14802 an error.  If auto, an unrecognized breakpoint location results in a\n\
14803 user-query to see if a pending breakpoint should be created."),
14804 				NULL,
14805 				show_pending_break_support,
14806 				&breakpoint_set_cmdlist,
14807 				&breakpoint_show_cmdlist);
14808 
14809   pending_break_support = AUTO_BOOLEAN_AUTO;
14810 
14811   add_setshow_boolean_cmd ("auto-hw", no_class,
14812 			   &automatic_hardware_breakpoints, _("\
14813 Set automatic usage of hardware breakpoints."), _("\
14814 Show automatic usage of hardware breakpoints."), _("\
14815 If set, the debugger will automatically use hardware breakpoints for\n\
14816 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
14817 a warning will be emitted for such breakpoints."),
14818 			   NULL,
14819 			   show_automatic_hardware_breakpoints,
14820 			   &breakpoint_set_cmdlist,
14821 			   &breakpoint_show_cmdlist);
14822 
14823   add_setshow_boolean_cmd ("always-inserted", class_support,
14824 			   &always_inserted_mode, _("\
14825 Set mode for inserting breakpoints."), _("\
14826 Show mode for inserting breakpoints."), _("\
14827 When this mode is on, breakpoints are inserted immediately as soon as\n\
14828 they're created, kept inserted even when execution stops, and removed\n\
14829 only when the user deletes them.  When this mode is off (the default),\n\
14830 breakpoints are inserted only when execution continues, and removed\n\
14831 when execution stops."),
14832 				NULL,
14833 				&show_always_inserted_mode,
14834 				&breakpoint_set_cmdlist,
14835 				&breakpoint_show_cmdlist);
14836 
14837   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
14838 			condition_evaluation_enums,
14839 			&condition_evaluation_mode_1, _("\
14840 Set mode of breakpoint condition evaluation."), _("\
14841 Show mode of breakpoint condition evaluation."), _("\
14842 When this is set to \"host\", breakpoint conditions will be\n\
14843 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
14844 breakpoint conditions will be downloaded to the target (if the target\n\
14845 supports such feature) and conditions will be evaluated on the target's side.\n\
14846 If this is set to \"auto\" (default), this will be automatically set to\n\
14847 \"target\" if it supports condition evaluation, otherwise it will\n\
14848 be set to \"host\"."),
14849 			   &set_condition_evaluation_mode,
14850 			   &show_condition_evaluation_mode,
14851 			   &breakpoint_set_cmdlist,
14852 			   &breakpoint_show_cmdlist);
14853 
14854   add_com ("break-range", class_breakpoint, break_range_command, _("\
14855 Set a breakpoint for an address range.\n\
14856 break-range START-LOCATION, END-LOCATION\n\
14857 where START-LOCATION and END-LOCATION can be one of the following:\n\
14858   LINENUM, for that line in the current file,\n\
14859   FILE:LINENUM, for that line in that file,\n\
14860   +OFFSET, for that number of lines after the current line\n\
14861 	   or the start of the range\n\
14862   FUNCTION, for the first line in that function,\n\
14863   FILE:FUNCTION, to distinguish among like-named static functions.\n\
14864   *ADDRESS, for the instruction at that address.\n\
14865 \n\
14866 The breakpoint will stop execution of the inferior whenever it executes\n\
14867 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
14868 range (including START-LOCATION and END-LOCATION)."));
14869 
14870   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
14871 Set a dynamic printf at specified location.\n\
14872 dprintf location,format string,arg1,arg2,...\n\
14873 location may be a linespec, explicit, or address location.\n"
14874 "\n" LOCATION_SPEC_HELP_STRING));
14875   set_cmd_completer (c, location_completer);
14876 
14877   add_setshow_enum_cmd ("dprintf-style", class_support,
14878 			dprintf_style_enums, &dprintf_style, _("\
14879 Set the style of usage for dynamic printf."), _("\
14880 Show the style of usage for dynamic printf."), _("\
14881 This setting chooses how GDB will do a dynamic printf.\n\
14882 If the value is \"gdb\", then the printing is done by GDB to its own\n\
14883 console, as with the \"printf\" command.\n\
14884 If the value is \"call\", the print is done by calling a function in your\n\
14885 program; by default printf(), but you can choose a different function or\n\
14886 output stream by setting dprintf-function and dprintf-channel."),
14887 			update_dprintf_commands, NULL,
14888 			&setlist, &showlist);
14889 
14890   add_setshow_string_cmd ("dprintf-function", class_support,
14891 			  &dprintf_function, _("\
14892 Set the function to use for dynamic printf."), _("\
14893 Show the function to use for dynamic printf."), NULL,
14894 			  update_dprintf_commands, NULL,
14895 			  &setlist, &showlist);
14896 
14897   add_setshow_string_cmd ("dprintf-channel", class_support,
14898 			  &dprintf_channel, _("\
14899 Set the channel to use for dynamic printf."), _("\
14900 Show the channel to use for dynamic printf."), NULL,
14901 			  update_dprintf_commands, NULL,
14902 			  &setlist, &showlist);
14903 
14904   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
14905 			   &disconnected_dprintf, _("\
14906 Set whether dprintf continues after GDB disconnects."), _("\
14907 Show whether dprintf continues after GDB disconnects."), _("\
14908 Use this to let dprintf commands continue to hit and produce output\n\
14909 even if GDB disconnects or detaches from the target."),
14910 			   NULL,
14911 			   NULL,
14912 			   &setlist, &showlist);
14913 
14914   add_com ("agent-printf", class_vars, agent_printf_command, _("\
14915 Target agent only formatted printing, like the C \"printf\" function.\n\
14916 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
14917 This supports most C printf format specifications, like %s, %d, etc.\n\
14918 This is useful for formatted output in user-defined commands."));
14919 
14920   automatic_hardware_breakpoints = true;
14921 
14922   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
14923 					   "breakpoint");
14924   gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
14925 				      "breakpoint");
14926 }
14927