Automatic date update in version.in
[binutils-gdb.git] / gdb / breakpoint.c
blob699919e32b3d5deffe06d938e63e5e19e2ba1ed7
1 /* Everything about breakpoints, for GDB.
3 Copyright (C) 1986-2023 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
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 "ui.h"
57 #include "valprint.h"
58 #include "jit.h"
59 #include "parser-defs.h"
60 #include "gdbsupport/gdb_regex.h"
61 #include "probe.h"
62 #include "cli/cli-utils.h"
63 #include "stack.h"
64 #include "ax-gdb.h"
65 #include "dummy-frame.h"
66 #include "interps.h"
67 #include "gdbsupport/format.h"
68 #include "thread-fsm.h"
69 #include "tid-parse.h"
70 #include "cli/cli-style.h"
71 #include "cli/cli-decode.h"
72 #include <unordered_set>
74 /* readline include files */
75 #include "readline/tilde.h"
77 /* readline defines this. */
78 #undef savestring
80 #include "mi/mi-common.h"
81 #include "extension.h"
82 #include <algorithm>
83 #include "progspace-and-thread.h"
84 #include "gdbsupport/array-view.h"
85 #include <optional>
86 #include "gdbsupport/common-utils.h"
88 /* Prototypes for local functions. */
90 static void map_breakpoint_numbers (const char *,
91 gdb::function_view<void (breakpoint *)>);
93 static void
94 create_sals_from_location_spec_default (location_spec *locspec,
95 linespec_result *canonical);
97 static void create_breakpoints_sal (struct gdbarch *,
98 struct linespec_result *,
99 gdb::unique_xmalloc_ptr<char>,
100 gdb::unique_xmalloc_ptr<char>,
101 enum bptype,
102 enum bpdisp, int, int, int,
103 int,
104 int, int, int, unsigned);
106 static int can_use_hardware_watchpoint
107 (const std::vector<value_ref_ptr> &vals);
109 static void mention (const breakpoint *);
111 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
113 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
115 static struct breakpoint *
116 momentary_breakpoint_from_master (struct breakpoint *orig,
117 enum bptype type,
118 int loc_enabled, int thread);
120 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, bool);
122 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
123 CORE_ADDR bpaddr,
124 enum bptype bptype,
125 struct program_space *pspace);
127 static bool watchpoint_locations_match (const struct bp_location *loc1,
128 const struct bp_location *loc2);
130 static bool breakpoint_locations_match (const struct bp_location *loc1,
131 const struct bp_location *loc2,
132 bool sw_hw_bps_match = false);
134 static bool breakpoint_location_address_match (struct bp_location *bl,
135 const struct address_space *aspace,
136 CORE_ADDR addr);
138 static bool breakpoint_location_address_range_overlap (struct bp_location *,
139 const address_space *,
140 CORE_ADDR, int);
142 static int remove_breakpoint (struct bp_location *);
143 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
145 static enum print_stop_action print_bp_stop_message (bpstat *bs);
147 static int hw_breakpoint_used_count (void);
149 static int hw_watchpoint_use_count (struct breakpoint *);
151 static int hw_watchpoint_used_count_others (struct breakpoint *except,
152 enum bptype type,
153 int *other_type_used);
155 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
156 int count);
158 static void decref_bp_location (struct bp_location **loc);
160 static std::vector<symtab_and_line> bkpt_probe_decode_location_spec
161 (struct breakpoint *b,
162 location_spec *locspec,
163 struct program_space *search_pspace);
165 static bool bl_address_is_meaningful (bp_location *loc);
167 static int find_loc_num_by_location (const bp_location *loc);
169 /* update_global_location_list's modes of operation wrt to whether to
170 insert locations now. */
171 enum ugll_insert_mode
173 /* Don't insert any breakpoint locations into the inferior, only
174 remove already-inserted locations that no longer should be
175 inserted. Functions that delete a breakpoint or breakpoints
176 should specify this mode, so that deleting a breakpoint doesn't
177 have the side effect of inserting the locations of other
178 breakpoints that are marked not-inserted, but should_be_inserted
179 returns true on them.
181 This behavior is useful is situations close to tear-down -- e.g.,
182 after an exec, while the target still has execution, but
183 breakpoint shadows of the previous executable image should *NOT*
184 be restored to the new image; or before detaching, where the
185 target still has execution and wants to delete breakpoints from
186 GDB's lists, and all breakpoints had already been removed from
187 the inferior. */
188 UGLL_DONT_INSERT,
190 /* May insert breakpoints iff breakpoints_should_be_inserted_now
191 claims breakpoints should be inserted now. */
192 UGLL_MAY_INSERT,
194 /* Insert locations now, irrespective of
195 breakpoints_should_be_inserted_now. E.g., say all threads are
196 stopped right now, and the user did "continue". We need to
197 insert breakpoints _before_ resuming the target, but
198 UGLL_MAY_INSERT wouldn't insert them, because
199 breakpoints_should_be_inserted_now returns false at that point,
200 as no thread is running yet. */
201 UGLL_INSERT
204 /* Return a textual version of INSERT_MODE. */
206 static const char *
207 ugll_insert_mode_text (ugll_insert_mode insert_mode)
209 /* Make sure the compiler warns if a new ugll_insert_mode enumerator is added
210 but not handled here. */
211 DIAGNOSTIC_PUSH
212 DIAGNOSTIC_ERROR_SWITCH
213 switch (insert_mode)
215 case UGLL_DONT_INSERT:
216 return "UGLL_DONT_INSERT";
217 case UGLL_MAY_INSERT:
218 return "UGLL_MAY_INSERT";
219 case UGLL_INSERT:
220 return "UGLL_INSERT";
222 DIAGNOSTIC_POP
224 gdb_assert_not_reached ("must handle all enum values");
227 /* Return a textual version of REASON. */
229 static const char *
230 remove_bp_reason_str (remove_bp_reason reason)
232 /* Make sure the compiler warns if a new remove_bp_reason enumerator is added
233 but not handled here. */
234 DIAGNOSTIC_PUSH
235 DIAGNOSTIC_ERROR_SWITCH
236 switch (reason)
238 case REMOVE_BREAKPOINT:
239 return "regular remove";
240 case DETACH_BREAKPOINT:
241 return "detach";
243 DIAGNOSTIC_POP
245 gdb_assert_not_reached ("must handle all enum values");
248 /* Return a textual version of breakpoint location BL describing number,
249 location and address. */
251 static std::string
252 breakpoint_location_address_str (const bp_location *bl)
254 std::string str = string_printf ("Breakpoint %d (%s) at address %s",
255 bl->owner->number,
256 host_address_to_string (bl),
257 paddress (bl->gdbarch, bl->address));
259 std::string loc_string = bl->to_string ();
260 if (!loc_string.empty ())
261 str += string_printf (" %s", loc_string.c_str ());
263 return str;
266 static void update_global_location_list (enum ugll_insert_mode);
268 static void update_global_location_list_nothrow (enum ugll_insert_mode);
270 static void insert_breakpoint_locations (void);
272 static void trace_pass_command (const char *, int);
274 static void set_tracepoint_count (int num);
276 static bool is_masked_watchpoint (const struct breakpoint *b);
278 /* Return true if B refers to a static tracepoint set by marker ("-m"),
279 zero otherwise. */
281 static bool strace_marker_p (struct breakpoint *b);
283 static void bkpt_probe_create_sals_from_location_spec
284 (location_spec *locspec,
285 struct linespec_result *canonical);
286 static void tracepoint_probe_create_sals_from_location_spec
287 (location_spec *locspec,
288 struct linespec_result *canonical);
290 const struct breakpoint_ops code_breakpoint_ops =
292 create_sals_from_location_spec_default,
293 create_breakpoints_sal,
296 /* Breakpoints set on probes. */
297 static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
299 bkpt_probe_create_sals_from_location_spec,
300 create_breakpoints_sal,
303 /* Tracepoints set on probes. */
304 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
306 tracepoint_probe_create_sals_from_location_spec,
307 create_breakpoints_sal,
310 /* Implementation of abstract dtors. These must exist to satisfy the
311 linker. */
313 breakpoint::~breakpoint ()
317 code_breakpoint::~code_breakpoint ()
321 catchpoint::~catchpoint ()
325 /* The structure to be used in regular breakpoints. */
326 struct ordinary_breakpoint : public code_breakpoint
328 using code_breakpoint::code_breakpoint;
330 int resources_needed (const struct bp_location *) override;
331 enum print_stop_action print_it (const bpstat *bs) const override;
332 void print_mention () const override;
333 void print_recreate (struct ui_file *fp) const override;
336 /* Internal breakpoints. These typically have a lifetime the same as
337 the program, and they end up installed on the breakpoint chain with
338 a negative breakpoint number. They're visible in "maint info
339 breakpoints", but not "info breakpoints". */
340 struct internal_breakpoint : public code_breakpoint
342 internal_breakpoint (struct gdbarch *gdbarch,
343 enum bptype type, CORE_ADDR address)
344 : code_breakpoint (gdbarch, type)
346 symtab_and_line sal;
347 sal.pc = address;
348 sal.section = find_pc_overlay (sal.pc);
349 sal.pspace = current_program_space;
350 add_location (sal);
352 pspace = current_program_space;
353 disposition = disp_donttouch;
356 void re_set () override;
357 void check_status (struct bpstat *bs) override;
358 enum print_stop_action print_it (const bpstat *bs) const override;
359 void print_mention () const override;
362 /* Momentary breakpoints. These typically have a lifetime of some run
363 control command only, are always thread-specific, and have 0 for
364 breakpoint number. I.e., there can be many momentary breakpoints
365 on the breakpoint chain and they all same the same number (zero).
366 They're visible in "maint info breakpoints", but not "info
367 breakpoints". */
368 struct momentary_breakpoint : public code_breakpoint
370 momentary_breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
371 program_space *pspace_,
372 const struct frame_id &frame_id_,
373 int thread_)
374 : code_breakpoint (gdbarch_, bptype)
376 /* If FRAME_ID is valid, it should be a real frame, not an inlined
377 or tail-called one. */
378 gdb_assert (!frame_id_artificial_p (frame_id));
380 /* Momentary breakpoints are always thread-specific. */
381 gdb_assert (thread_ > 0);
383 pspace = pspace_;
384 enable_state = bp_enabled;
385 disposition = disp_donttouch;
386 frame_id = frame_id_;
387 thread = thread_;
389 /* The inferior should have been set by the parent constructor. */
390 gdb_assert (inferior == -1);
393 void re_set () override;
394 void check_status (struct bpstat *bs) override;
395 enum print_stop_action print_it (const bpstat *bs) const override;
396 void print_mention () const override;
399 /* DPrintf breakpoints. */
400 struct dprintf_breakpoint : public ordinary_breakpoint
402 using ordinary_breakpoint::ordinary_breakpoint;
404 void re_set () override;
405 int breakpoint_hit (const struct bp_location *bl,
406 const address_space *aspace,
407 CORE_ADDR bp_addr,
408 const target_waitstatus &ws) override;
409 void print_recreate (struct ui_file *fp) const override;
410 void after_condition_true (struct bpstat *bs) override;
413 /* Ranged breakpoints. */
414 struct ranged_breakpoint : public ordinary_breakpoint
416 explicit ranged_breakpoint (struct gdbarch *gdbarch,
417 const symtab_and_line &sal_start,
418 int length,
419 location_spec_up start_locspec,
420 location_spec_up end_locspec)
421 : ordinary_breakpoint (gdbarch, bp_hardware_breakpoint)
423 bp_location *bl = add_location (sal_start);
424 bl->length = length;
426 disposition = disp_donttouch;
428 locspec = std::move (start_locspec);
429 locspec_range_end = std::move (end_locspec);
432 int breakpoint_hit (const struct bp_location *bl,
433 const address_space *aspace,
434 CORE_ADDR bp_addr,
435 const target_waitstatus &ws) override;
436 int resources_needed (const struct bp_location *) override;
437 enum print_stop_action print_it (const bpstat *bs) const override;
438 bool print_one (const bp_location **) const override;
439 void print_one_detail (struct ui_out *) const override;
440 void print_mention () const override;
441 void print_recreate (struct ui_file *fp) const override;
444 /* Static tracepoints with marker (`-m'). */
445 struct static_marker_tracepoint : public tracepoint
447 using tracepoint::tracepoint;
449 std::vector<symtab_and_line> decode_location_spec
450 (struct location_spec *locspec,
451 struct program_space *search_pspace) override;
454 /* The style in which to perform a dynamic printf. This is a user
455 option because different output options have different tradeoffs;
456 if GDB does the printing, there is better error handling if there
457 is a problem with any of the arguments, but using an inferior
458 function lets you have special-purpose printers and sending of
459 output to the same place as compiled-in print functions. */
461 static const char dprintf_style_gdb[] = "gdb";
462 static const char dprintf_style_call[] = "call";
463 static const char dprintf_style_agent[] = "agent";
464 static const char *const dprintf_style_enums[] = {
465 dprintf_style_gdb,
466 dprintf_style_call,
467 dprintf_style_agent,
468 NULL
470 static const char *dprintf_style = dprintf_style_gdb;
472 /* The function to use for dynamic printf if the preferred style is to
473 call into the inferior. The value is simply a string that is
474 copied into the command, so it can be anything that GDB can
475 evaluate to a callable address, not necessarily a function name. */
477 static std::string dprintf_function = "printf";
479 /* The channel to use for dynamic printf if the preferred style is to
480 call into the inferior; if a nonempty string, it will be passed to
481 the call as the first argument, with the format string as the
482 second. As with the dprintf function, this can be anything that
483 GDB knows how to evaluate, so in addition to common choices like
484 "stderr", this could be an app-specific expression like
485 "mystreams[curlogger]". */
487 static std::string dprintf_channel;
489 /* True if dprintf commands should continue to operate even if GDB
490 has disconnected. */
491 static bool disconnected_dprintf = true;
493 struct command_line *
494 breakpoint_commands (struct breakpoint *b)
496 return b->commands ? b->commands.get () : NULL;
499 /* Flag indicating that a command has proceeded the inferior past the
500 current breakpoint. */
502 static bool breakpoint_proceeded;
504 const char *
505 bpdisp_text (enum bpdisp disp)
507 /* NOTE: the following values are a part of MI protocol and
508 represent values of 'disp' field returned when inferior stops at
509 a breakpoint. */
510 static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
512 return bpdisps[(int) disp];
515 /* Prototypes for exported functions. */
516 /* If FALSE, gdb will not use hardware support for watchpoints, even
517 if such is available. */
518 static int can_use_hw_watchpoints;
520 static void
521 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
522 struct cmd_list_element *c,
523 const char *value)
525 gdb_printf (file,
526 _("Debugger's willingness to use "
527 "watchpoint hardware is %s.\n"),
528 value);
531 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
532 If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
533 for unrecognized breakpoint locations.
534 If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized. */
535 static enum auto_boolean pending_break_support;
536 static void
537 show_pending_break_support (struct ui_file *file, int from_tty,
538 struct cmd_list_element *c,
539 const char *value)
541 gdb_printf (file,
542 _("Debugger's behavior regarding "
543 "pending breakpoints is %s.\n"),
544 value);
547 /* If true, gdb will automatically use hardware breakpoints for breakpoints
548 set with "break" but falling in read-only memory.
549 If false, gdb will warn about such breakpoints, but won't automatically
550 use hardware breakpoints. */
551 static bool automatic_hardware_breakpoints;
552 static void
553 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
554 struct cmd_list_element *c,
555 const char *value)
557 gdb_printf (file,
558 _("Automatic usage of hardware breakpoints is %s.\n"),
559 value);
562 /* If on, GDB keeps breakpoints inserted even if the inferior is
563 stopped, and immediately inserts any new breakpoints as soon as
564 they're created. If off (default), GDB keeps breakpoints off of
565 the target as long as possible. That is, it delays inserting
566 breakpoints until the next resume, and removes them again when the
567 target fully stops. This is a bit safer in case GDB crashes while
568 processing user input. */
569 static bool always_inserted_mode = false;
571 static void
572 show_always_inserted_mode (struct ui_file *file, int from_tty,
573 struct cmd_list_element *c, const char *value)
575 gdb_printf (file, _("Always inserted breakpoint mode is %s.\n"),
576 value);
579 /* True if breakpoint debug output is enabled. */
580 static bool debug_breakpoint = false;
582 /* Print a "breakpoint" debug statement. */
583 #define breakpoint_debug_printf(fmt, ...) \
584 debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
585 ##__VA_ARGS__)
587 /* "show debug breakpoint" implementation. */
588 static void
589 show_debug_breakpoint (struct ui_file *file, int from_tty,
590 struct cmd_list_element *c, const char *value)
592 gdb_printf (file, _("Breakpoint location debugging is %s.\n"), value);
595 /* See breakpoint.h. */
598 breakpoints_should_be_inserted_now (void)
600 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
602 /* If breakpoints are global, they should be inserted even if no
603 thread under gdb's control is running, or even if there are
604 no threads under GDB's control yet. */
605 return 1;
607 else
609 if (always_inserted_mode)
611 /* The user wants breakpoints inserted even if all threads
612 are stopped. */
613 return 1;
616 for (inferior *inf : all_inferiors ())
617 if (inf->has_execution ()
618 && threads_are_executing (inf->process_target ()))
619 return 1;
621 /* Don't remove breakpoints yet if, even though all threads are
622 stopped, we still have events to process. */
623 for (thread_info *tp : all_non_exited_threads ())
624 if (tp->resumed () && tp->has_pending_waitstatus ())
625 return 1;
627 return 0;
630 static const char condition_evaluation_both[] = "host or target";
632 /* Modes for breakpoint condition evaluation. */
633 static const char condition_evaluation_auto[] = "auto";
634 static const char condition_evaluation_host[] = "host";
635 static const char condition_evaluation_target[] = "target";
636 static const char *const condition_evaluation_enums[] = {
637 condition_evaluation_auto,
638 condition_evaluation_host,
639 condition_evaluation_target,
640 NULL
643 /* Global that holds the current mode for breakpoint condition evaluation. */
644 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
646 /* Global that we use to display information to the user (gets its value from
647 condition_evaluation_mode_1. */
648 static const char *condition_evaluation_mode = condition_evaluation_auto;
650 /* Translate a condition evaluation mode MODE into either "host"
651 or "target". This is used mostly to translate from "auto" to the
652 real setting that is being used. It returns the translated
653 evaluation mode. */
655 static const char *
656 translate_condition_evaluation_mode (const char *mode)
658 if (mode == condition_evaluation_auto)
660 if (target_supports_evaluation_of_breakpoint_conditions ())
661 return condition_evaluation_target;
662 else
663 return condition_evaluation_host;
665 else
666 return mode;
669 /* Discovers what condition_evaluation_auto translates to. */
671 static const char *
672 breakpoint_condition_evaluation_mode (void)
674 return translate_condition_evaluation_mode (condition_evaluation_mode);
677 /* Return true if GDB should evaluate breakpoint conditions or false
678 otherwise. */
680 static bool
681 gdb_evaluates_breakpoint_condition_p (void)
683 const char *mode = breakpoint_condition_evaluation_mode ();
685 return (mode == condition_evaluation_host);
688 /* Are we executing breakpoint commands? */
689 static int executing_breakpoint_commands;
691 /* Are overlay event breakpoints enabled? */
692 static int overlay_events_enabled;
694 /* See description in breakpoint.h. */
695 bool target_exact_watchpoints = false;
697 /* Chains of all breakpoints defined. */
699 static intrusive_list<breakpoint> breakpoint_chain;
701 /* See breakpoint.h. */
703 breakpoint_range
704 all_breakpoints ()
706 return breakpoint_range (breakpoint_chain.begin (), breakpoint_chain.end ());
709 /* See breakpoint.h. */
711 breakpoint_safe_range
712 all_breakpoints_safe ()
714 return breakpoint_safe_range (all_breakpoints ());
717 /* See breakpoint.h. */
719 tracepoint_range
720 all_tracepoints ()
722 return tracepoint_range (tracepoint_iterator (breakpoint_chain.begin ()),
723 tracepoint_iterator (breakpoint_chain.end ()));
726 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS. */
728 static std::vector<bp_location *> bp_locations;
730 /* See breakpoint.h. */
732 const std::vector<bp_location *> &
733 all_bp_locations ()
735 return bp_locations;
738 /* Range to iterate over breakpoint locations at a given address. */
740 struct bp_locations_at_addr_range
742 using iterator = std::vector<bp_location *>::iterator;
744 bp_locations_at_addr_range (CORE_ADDR addr)
746 struct compare
748 bool operator() (const bp_location *loc, CORE_ADDR addr_) const
749 { return loc->address < addr_; }
751 bool operator() (CORE_ADDR addr_, const bp_location *loc) const
752 { return addr_ < loc->address; }
755 auto it_pair = std::equal_range (bp_locations.begin (), bp_locations.end (),
756 addr, compare ());
758 m_begin = it_pair.first;
759 m_end = it_pair.second;
762 iterator begin () const
763 { return m_begin; }
765 iterator end () const
766 { return m_end; }
768 private:
769 iterator m_begin;
770 iterator m_end;
773 /* Return a range to iterate over all breakpoint locations exactly at address
774 ADDR.
776 If it's needed to iterate multiple times on the same range, it's possible
777 to save the range in a local variable and use it multiple times:
779 auto range = all_bp_locations_at_addr (addr);
781 for (bp_location *loc : range)
782 // use loc
784 for (bp_location *loc : range)
785 // use loc
787 This saves a bit of time, as it avoids re-doing the binary searches to find
788 the range's boundaries. Just remember not to change the bp_locations vector
789 in the mean time, as it could make the range's iterators stale. */
791 static bp_locations_at_addr_range
792 all_bp_locations_at_addr (CORE_ADDR addr)
794 return bp_locations_at_addr_range (addr);
797 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
798 ADDRESS for the current elements of BP_LOCATIONS which get a valid
799 result from bp_location_has_shadow. You can use it for roughly
800 limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
801 an address you need to read. */
803 static CORE_ADDR bp_locations_placed_address_before_address_max;
805 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
806 + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
807 BP_LOCATIONS which get a valid result from bp_location_has_shadow.
808 You can use it for roughly limiting the subrange of BP_LOCATIONS to
809 scan for shadow bytes for an address you need to read. */
811 static CORE_ADDR bp_locations_shadow_len_after_address_max;
813 /* The locations that no longer correspond to any breakpoint, unlinked
814 from the bp_locations array, but for which a hit may still be
815 reported by a target. */
816 static std::vector<bp_location *> moribund_locations;
818 /* Number of last breakpoint made. */
820 static int breakpoint_count;
822 /* The value of `breakpoint_count' before the last command that
823 created breakpoints. If the last (break-like) command created more
824 than one breakpoint, then the difference between BREAKPOINT_COUNT
825 and PREV_BREAKPOINT_COUNT is more than one. */
826 static int prev_breakpoint_count;
828 /* Number of last tracepoint made. */
830 static int tracepoint_count;
832 static struct cmd_list_element *breakpoint_set_cmdlist;
833 static struct cmd_list_element *breakpoint_show_cmdlist;
834 struct cmd_list_element *save_cmdlist;
836 /* Return whether a breakpoint is an active enabled breakpoint. */
837 static bool
838 breakpoint_enabled (struct breakpoint *b)
840 return (b->enable_state == bp_enabled);
843 /* Set breakpoint count to NUM. */
845 static void
846 set_breakpoint_count (int num)
848 prev_breakpoint_count = breakpoint_count;
849 breakpoint_count = num;
850 set_internalvar_integer (lookup_internalvar ("bpnum"), num);
853 /* Used by `start_rbreak_breakpoints' below, to record the current
854 breakpoint count before "rbreak" creates any breakpoint. */
855 static int rbreak_start_breakpoint_count;
857 /* Called at the start an "rbreak" command to record the first
858 breakpoint made. */
860 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
862 rbreak_start_breakpoint_count = breakpoint_count;
865 /* Called at the end of an "rbreak" command to record the last
866 breakpoint made. */
868 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
870 prev_breakpoint_count = rbreak_start_breakpoint_count;
873 /* Used in run_command to zero the hit count when a new run starts. */
875 void
876 clear_breakpoint_hit_counts (void)
878 for (breakpoint &b : all_breakpoints ())
879 b.hit_count = 0;
883 /* Return the breakpoint with the specified number, or NULL
884 if the number does not refer to an existing breakpoint. */
886 struct breakpoint *
887 get_breakpoint (int num)
889 for (breakpoint &b : all_breakpoints ())
890 if (b.number == num)
891 return &b;
893 return nullptr;
896 /* Return TRUE if NUM refer to an existing breakpoint that has
897 multiple code locations. */
899 static bool
900 has_multiple_locations (int num)
902 for (breakpoint &b : all_breakpoints ())
903 if (b.number == num)
904 return b.has_multiple_locations ();
906 return false;
911 /* Mark locations as "conditions have changed" in case the target supports
912 evaluating conditions on its side. */
914 static void
915 mark_breakpoint_modified (struct breakpoint *b)
917 /* This is only meaningful if the target is
918 evaluating conditions and if the user has
919 opted for condition evaluation on the target's
920 side. */
921 if (gdb_evaluates_breakpoint_condition_p ()
922 || !target_supports_evaluation_of_breakpoint_conditions ())
923 return;
925 if (!is_breakpoint (b))
926 return;
928 for (bp_location &loc : b->locations ())
929 loc.condition_changed = condition_modified;
932 /* Mark location as "conditions have changed" in case the target supports
933 evaluating conditions on its side. */
935 static void
936 mark_breakpoint_location_modified (struct bp_location *loc)
938 /* This is only meaningful if the target is
939 evaluating conditions and if the user has
940 opted for condition evaluation on the target's
941 side. */
942 if (gdb_evaluates_breakpoint_condition_p ()
943 || !target_supports_evaluation_of_breakpoint_conditions ())
945 return;
947 if (!is_breakpoint (loc->owner))
948 return;
950 loc->condition_changed = condition_modified;
953 /* Sets the condition-evaluation mode using the static global
954 condition_evaluation_mode. */
956 static void
957 set_condition_evaluation_mode (const char *args, int from_tty,
958 struct cmd_list_element *c)
960 const char *old_mode, *new_mode;
962 if ((condition_evaluation_mode_1 == condition_evaluation_target)
963 && !target_supports_evaluation_of_breakpoint_conditions ())
965 condition_evaluation_mode_1 = condition_evaluation_mode;
966 warning (_("Target does not support breakpoint condition evaluation.\n"
967 "Using host evaluation mode instead."));
968 return;
971 new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
972 old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
974 /* Flip the switch. Flip it even if OLD_MODE == NEW_MODE as one of the
975 settings was "auto". */
976 condition_evaluation_mode = condition_evaluation_mode_1;
978 /* Only update the mode if the user picked a different one. */
979 if (new_mode != old_mode)
981 /* If the user switched to a different evaluation mode, we
982 need to synch the changes with the target as follows:
984 "host" -> "target": Send all (valid) conditions to the target.
985 "target" -> "host": Remove all the conditions from the target.
988 if (new_mode == condition_evaluation_target)
990 /* Mark everything modified and synch conditions with the
991 target. */
992 for (bp_location *loc : all_bp_locations ())
993 mark_breakpoint_location_modified (loc);
995 else
997 /* Manually mark non-duplicate locations to synch conditions
998 with the target. We do this to remove all the conditions the
999 target knows about. */
1000 for (bp_location *loc : all_bp_locations ())
1001 if (is_breakpoint (loc->owner) && loc->inserted)
1002 loc->needs_update = 1;
1005 /* Do the update. */
1006 update_global_location_list (UGLL_MAY_INSERT);
1009 return;
1012 /* Shows the current mode of breakpoint condition evaluation. Explicitly shows
1013 what "auto" is translating to. */
1015 static void
1016 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
1017 struct cmd_list_element *c, const char *value)
1019 if (condition_evaluation_mode == condition_evaluation_auto)
1020 gdb_printf (file,
1021 _("Breakpoint condition evaluation "
1022 "mode is %s (currently %s).\n"),
1023 value,
1024 breakpoint_condition_evaluation_mode ());
1025 else
1026 gdb_printf (file, _("Breakpoint condition evaluation mode is %s.\n"),
1027 value);
1030 /* Parse COND_STRING in the context of LOC and set as the condition
1031 expression of LOC. BP_NUM is the number of LOC's owner, LOC_NUM is
1032 the number of LOC within its owner. In case of parsing error, mark
1033 LOC as DISABLED_BY_COND. In case of success, unset DISABLED_BY_COND. */
1035 static void
1036 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
1037 int bp_num, int loc_num)
1039 bool has_junk = false;
1042 expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
1043 block_for_pc (loc->address), 0);
1044 if (*cond_string != 0)
1045 has_junk = true;
1046 else
1048 loc->cond = std::move (new_exp);
1049 if (loc->disabled_by_cond && loc->enabled)
1050 gdb_printf (_("Breakpoint %d's condition is now valid at "
1051 "location %d, enabling.\n"),
1052 bp_num, loc_num);
1054 loc->disabled_by_cond = false;
1057 catch (const gdb_exception_error &e)
1059 if (loc->enabled)
1061 /* Warn if a user-enabled location is now becoming disabled-by-cond.
1062 BP_NUM is 0 if the breakpoint is being defined for the first
1063 time using the "break ... if ..." command, and non-zero if
1064 already defined. */
1065 if (bp_num != 0)
1066 warning (_("failed to validate condition at location %d.%d, "
1067 "disabling:\n %s"), bp_num, loc_num, e.what ());
1068 else
1069 warning (_("failed to validate condition at location %d, "
1070 "disabling:\n %s"), loc_num, e.what ());
1073 loc->disabled_by_cond = true;
1076 if (has_junk)
1077 error (_("Garbage '%s' follows condition"), cond_string);
1080 /* See breakpoint.h. */
1082 void
1083 notify_breakpoint_modified (breakpoint *b)
1085 interps_notify_breakpoint_modified (b);
1086 gdb::observers::breakpoint_modified.notify (b);
1089 void
1090 set_breakpoint_condition (struct breakpoint *b, const char *exp,
1091 int from_tty, bool force)
1093 if (*exp == 0)
1095 b->cond_string.reset ();
1097 if (is_watchpoint (b))
1098 gdb::checked_static_cast<watchpoint *> (b)->cond_exp.reset ();
1099 else
1101 int loc_num = 1;
1102 for (bp_location &loc : b->locations ())
1104 loc.cond.reset ();
1105 if (loc.disabled_by_cond && loc.enabled)
1106 gdb_printf (_("Breakpoint %d's condition is now valid at "
1107 "location %d, enabling.\n"),
1108 b->number, loc_num);
1109 loc.disabled_by_cond = false;
1110 loc_num++;
1112 /* No need to free the condition agent expression
1113 bytecode (if we have one). We will handle this
1114 when we go through update_global_location_list. */
1118 if (from_tty)
1119 gdb_printf (_("Breakpoint %d now unconditional.\n"), b->number);
1121 else
1123 if (is_watchpoint (b))
1125 innermost_block_tracker tracker;
1126 const char *arg = exp;
1127 expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
1128 if (*arg != 0)
1129 error (_("Junk at end of expression"));
1130 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
1131 w->cond_exp = std::move (new_exp);
1132 w->cond_exp_valid_block = tracker.block ();
1134 else
1136 /* Parse and set condition expressions. We make two passes.
1137 In the first, we parse the condition string to see if it
1138 is valid in at least one location. If so, the condition
1139 would be accepted. So we go ahead and set the locations'
1140 conditions. In case no valid case is found, we throw
1141 the error and the condition string will be rejected.
1142 This two-pass approach is taken to avoid setting the
1143 state of locations in case of a reject. */
1144 for (const bp_location &loc : b->locations ())
1148 const char *arg = exp;
1149 parse_exp_1 (&arg, loc.address,
1150 block_for_pc (loc.address), 0);
1151 if (*arg != 0)
1152 error (_("Junk at end of expression"));
1153 break;
1155 catch (const gdb_exception_error &e)
1157 /* Condition string is invalid. If this happens to
1158 be the last loc, abandon (if not forced) or continue
1159 (if forced). */
1160 if (&loc == &b->last_loc () && !force)
1161 throw;
1165 /* If we reach here, the condition is valid at some locations. */
1166 int loc_num = 1;
1167 for (bp_location &loc : b->locations ())
1169 set_breakpoint_location_condition (exp, &loc, b->number, loc_num);
1170 loc_num++;
1174 /* We know that the new condition parsed successfully. The
1175 condition string of the breakpoint can be safely updated. */
1176 b->cond_string = make_unique_xstrdup (exp);
1177 b->condition_not_parsed = 0;
1179 mark_breakpoint_modified (b);
1181 notify_breakpoint_modified (b);
1184 /* See breakpoint.h. */
1186 void
1187 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
1188 bool force)
1190 for (breakpoint &b : all_breakpoints ())
1191 if (b.number == bpnum)
1193 /* Check if this breakpoint has a "stop" method implemented in an
1194 extension language. This method and conditions entered into GDB
1195 from the CLI are mutually exclusive. */
1196 const struct extension_language_defn *extlang
1197 = get_breakpoint_cond_ext_lang (&b, EXT_LANG_NONE);
1199 if (extlang != NULL)
1201 error (_("Only one stop condition allowed. There is currently"
1202 " a %s stop condition defined for this breakpoint."),
1203 ext_lang_capitalized_name (extlang));
1205 set_breakpoint_condition (&b, exp, from_tty, force);
1207 if (is_breakpoint (&b))
1208 update_global_location_list (UGLL_MAY_INSERT);
1210 return;
1213 error (_("No breakpoint number %d."), bpnum);
1216 /* The options for the "condition" command. */
1218 struct condition_command_opts
1220 /* For "-force". */
1221 bool force_condition = false;
1224 static const gdb::option::option_def condition_command_option_defs[] = {
1226 gdb::option::flag_option_def<condition_command_opts> {
1227 "force",
1228 [] (condition_command_opts *opts) { return &opts->force_condition; },
1229 N_("Set the condition even if it is invalid for all current locations."),
1234 /* Create an option_def_group for the "condition" options, with
1235 CC_OPTS as context. */
1237 static inline gdb::option::option_def_group
1238 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1240 return {{condition_command_option_defs}, cc_opts};
1243 /* Completion for the "condition" command. */
1245 static void
1246 condition_completer (struct cmd_list_element *cmd,
1247 completion_tracker &tracker,
1248 const char *text, const char * /*word*/)
1250 bool has_no_arguments = (*text == '\0');
1251 condition_command_opts cc_opts;
1252 const auto group = make_condition_command_options_def_group (&cc_opts);
1253 if (gdb::option::complete_options
1254 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1255 return;
1257 text = skip_spaces (text);
1258 const char *space = skip_to_space (text);
1259 if (*space == '\0')
1261 int len;
1263 if (text[0] == '$')
1265 tracker.advance_custom_word_point_by (1);
1266 /* We don't support completion of history indices. */
1267 if (!isdigit (text[1]))
1268 complete_internalvar (tracker, &text[1]);
1269 return;
1272 /* Suggest the "-force" flag if no arguments are given. If
1273 arguments were passed, they either already include the flag,
1274 or we are beyond the point of suggesting it because it's
1275 positionally the first argument. */
1276 if (has_no_arguments)
1277 gdb::option::complete_on_all_options (tracker, group);
1279 /* We're completing the breakpoint number. */
1280 len = strlen (text);
1282 for (breakpoint &b : all_breakpoints ())
1284 char number[50];
1286 xsnprintf (number, sizeof (number), "%d", b.number);
1288 if (strncmp (number, text, len) == 0)
1289 tracker.add_completion (make_unique_xstrdup (number));
1292 return;
1295 /* We're completing the expression part. Skip the breakpoint num. */
1296 const char *exp_start = skip_spaces (space);
1297 tracker.advance_custom_word_point_by (exp_start - text);
1298 text = exp_start;
1299 const char *word = advance_to_expression_complete_word_point (tracker, text);
1300 expression_completer (cmd, tracker, text, word);
1303 /* condition N EXP -- set break condition of breakpoint N to EXP. */
1305 static void
1306 condition_command (const char *arg, int from_tty)
1308 const char *p;
1309 int bnum;
1311 if (arg == 0)
1312 error_no_arg (_("breakpoint number"));
1314 p = arg;
1316 /* Check if the "-force" flag was passed. */
1317 condition_command_opts cc_opts;
1318 const auto group = make_condition_command_options_def_group (&cc_opts);
1319 gdb::option::process_options
1320 (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1322 bnum = get_number (&p);
1323 if (bnum == 0)
1324 error (_("Bad breakpoint argument: '%s'"), arg);
1326 set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1329 /* Check that COMMAND do not contain commands that are suitable
1330 only for tracepoints and not suitable for ordinary breakpoints.
1331 Throw if any such commands is found. */
1333 static void
1334 check_no_tracepoint_commands (struct command_line *commands)
1336 struct command_line *c;
1338 for (c = commands; c; c = c->next)
1340 if (c->control_type == while_stepping_control)
1341 error (_("The 'while-stepping' command can "
1342 "only be used for tracepoints"));
1344 check_no_tracepoint_commands (c->body_list_0.get ());
1345 check_no_tracepoint_commands (c->body_list_1.get ());
1347 /* Not that command parsing removes leading whitespace and comment
1348 lines and also empty lines. So, we only need to check for
1349 command directly. */
1350 if (strstr (c->line, "collect ") == c->line)
1351 error (_("The 'collect' command can only be used for tracepoints"));
1353 if (strstr (c->line, "teval ") == c->line)
1354 error (_("The 'teval' command can only be used for tracepoints"));
1358 struct longjmp_breakpoint : public momentary_breakpoint
1360 using momentary_breakpoint::momentary_breakpoint;
1362 ~longjmp_breakpoint () override;
1365 /* Encapsulate tests for different types of tracepoints. */
1367 static bool
1368 is_tracepoint_type (bptype type)
1370 return (type == bp_tracepoint
1371 || type == bp_fast_tracepoint
1372 || type == bp_static_tracepoint
1373 || type == bp_static_marker_tracepoint);
1376 /* See breakpoint.h. */
1378 bool
1379 is_tracepoint (const struct breakpoint *b)
1381 return is_tracepoint_type (b->type);
1384 /* Factory function to create an appropriate instance of breakpoint given
1385 TYPE. */
1387 template<typename... Arg>
1388 static std::unique_ptr<code_breakpoint>
1389 new_breakpoint_from_type (struct gdbarch *gdbarch, bptype type,
1390 Arg&&... args)
1392 code_breakpoint *b;
1394 switch (type)
1396 case bp_breakpoint:
1397 case bp_hardware_breakpoint:
1398 b = new ordinary_breakpoint (gdbarch, type,
1399 std::forward<Arg> (args)...);
1400 break;
1402 case bp_fast_tracepoint:
1403 case bp_static_tracepoint:
1404 case bp_tracepoint:
1405 b = new tracepoint (gdbarch, type,
1406 std::forward<Arg> (args)...);
1407 break;
1409 case bp_static_marker_tracepoint:
1410 b = new static_marker_tracepoint (gdbarch, type,
1411 std::forward<Arg> (args)...);
1412 break;
1414 case bp_dprintf:
1415 b = new dprintf_breakpoint (gdbarch, type,
1416 std::forward<Arg> (args)...);
1417 break;
1419 default:
1420 gdb_assert_not_reached ("invalid type");
1423 return std::unique_ptr<code_breakpoint> (b);
1426 /* A helper function that validates that COMMANDS are valid for a
1427 breakpoint. This function will throw an exception if a problem is
1428 found. */
1430 static void
1431 validate_commands_for_breakpoint (struct breakpoint *b,
1432 struct command_line *commands)
1434 if (is_tracepoint (b))
1436 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
1437 struct command_line *c;
1438 struct command_line *while_stepping = 0;
1440 /* Reset the while-stepping step count. The previous commands
1441 might have included a while-stepping action, while the new
1442 ones might not. */
1443 t->step_count = 0;
1445 /* We need to verify that each top-level element of commands is
1446 valid for tracepoints, that there's at most one
1447 while-stepping element, and that the while-stepping's body
1448 has valid tracing commands excluding nested while-stepping.
1449 We also need to validate the tracepoint action line in the
1450 context of the tracepoint --- validate_actionline actually
1451 has side effects, like setting the tracepoint's
1452 while-stepping STEP_COUNT, in addition to checking if the
1453 collect/teval actions parse and make sense in the
1454 tracepoint's context. */
1455 for (c = commands; c; c = c->next)
1457 if (c->control_type == while_stepping_control)
1459 if (b->type == bp_fast_tracepoint)
1460 error (_("The 'while-stepping' command "
1461 "cannot be used for fast tracepoint"));
1462 else if (b->type == bp_static_tracepoint
1463 || b->type == bp_static_marker_tracepoint)
1464 error (_("The 'while-stepping' command "
1465 "cannot be used for static tracepoint"));
1467 if (while_stepping)
1468 error (_("The 'while-stepping' command "
1469 "can be used only once"));
1470 else
1471 while_stepping = c;
1474 validate_actionline (c->line, t);
1476 if (while_stepping)
1478 struct command_line *c2;
1480 gdb_assert (while_stepping->body_list_1 == nullptr);
1481 c2 = while_stepping->body_list_0.get ();
1482 for (; c2; c2 = c2->next)
1484 if (c2->control_type == while_stepping_control)
1485 error (_("The 'while-stepping' command cannot be nested"));
1489 else
1491 check_no_tracepoint_commands (commands);
1495 /* Return a vector of all the static tracepoints set at ADDR. The
1496 caller is responsible for releasing the vector. */
1498 std::vector<breakpoint *>
1499 static_tracepoints_here (CORE_ADDR addr)
1501 std::vector<breakpoint *> found;
1503 for (breakpoint &b : all_breakpoints ())
1504 if (b.type == bp_static_tracepoint
1505 || b.type == bp_static_marker_tracepoint)
1507 for (bp_location &loc : b.locations ())
1508 if (loc.address == addr)
1509 found.push_back (&b);
1512 return found;
1515 /* Set the command list of B to COMMANDS. If breakpoint is tracepoint,
1516 validate that only allowed commands are included. */
1518 void
1519 breakpoint_set_commands (struct breakpoint *b,
1520 counted_command_line &&commands)
1522 validate_commands_for_breakpoint (b, commands.get ());
1524 b->commands = std::move (commands);
1525 notify_breakpoint_modified (b);
1528 /* Set the internal `silent' flag on the breakpoint. Note that this
1529 is not the same as the "silent" that may appear in the breakpoint's
1530 commands. */
1532 void
1533 breakpoint_set_silent (struct breakpoint *b, int silent)
1535 int old_silent = b->silent;
1537 b->silent = silent;
1538 if (old_silent != silent)
1539 notify_breakpoint_modified (b);
1542 /* See breakpoint.h. */
1544 void
1545 breakpoint_set_thread (struct breakpoint *b, int thread)
1547 /* THREAD should be -1, meaning no thread restriction, or it should be a
1548 valid global thread-id, which are greater than zero. */
1549 gdb_assert (thread == -1 || thread > 0);
1551 /* It is not valid to set a thread restriction for a breakpoint that
1552 already has task or inferior restriction. */
1553 gdb_assert (thread == -1 || (b->task == -1 && b->inferior == -1));
1555 int old_thread = b->thread;
1556 b->thread = thread;
1557 if (old_thread != thread)
1558 notify_breakpoint_modified (b);
1561 /* See breakpoint.h. */
1563 void
1564 breakpoint_set_inferior (struct breakpoint *b, int inferior)
1566 /* INFERIOR should be -1, meaning no inferior restriction, or it should
1567 be a valid inferior number, which are greater than zero. */
1568 gdb_assert (inferior == -1 || inferior > 0);
1570 /* It is not valid to set an inferior restriction for a breakpoint that
1571 already has a task or thread restriction. */
1572 gdb_assert (inferior == -1 || (b->task == -1 && b->thread == -1));
1574 int old_inferior = b->inferior;
1575 b->inferior = inferior;
1576 if (old_inferior != inferior)
1577 notify_breakpoint_modified (b);
1580 /* See breakpoint.h. */
1582 void
1583 breakpoint_set_task (struct breakpoint *b, int task)
1585 /* TASK should be -1, meaning no task restriction, or it should be a
1586 valid task-id, which are greater than zero. */
1587 gdb_assert (task == -1 || task > 0);
1589 /* It is not valid to set a task restriction for a breakpoint that
1590 already has a thread or inferior restriction. */
1591 gdb_assert (task == -1 || (b->thread == -1 && b->inferior == -1));
1593 int old_task = b->task;
1594 b->task = task;
1595 if (old_task != task)
1596 notify_breakpoint_modified (b);
1599 static void
1600 commands_command_1 (const char *arg, int from_tty,
1601 struct command_line *control)
1603 counted_command_line cmd;
1604 /* cmd_read will be true once we have read cmd. Note that cmd might still be
1605 NULL after the call to read_command_lines if the user provides an empty
1606 list of command by just typing "end". */
1607 bool cmd_read = false;
1609 std::string new_arg;
1611 if (arg == NULL || !*arg)
1613 /* Argument not explicitly given. Synthesize it. */
1614 if (breakpoint_count - prev_breakpoint_count > 1)
1615 new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1616 breakpoint_count);
1617 else if (breakpoint_count > 0)
1618 new_arg = string_printf ("%d", breakpoint_count);
1620 else
1622 /* Create a copy of ARG. This is needed because the "commands"
1623 command may be coming from a script. In that case, the read
1624 line buffer is going to be overwritten in the lambda of
1625 'map_breakpoint_numbers' below when reading the next line
1626 before we are are done parsing the breakpoint numbers. */
1627 new_arg = arg;
1629 arg = new_arg.c_str ();
1631 map_breakpoint_numbers
1632 (arg, [&] (breakpoint *b)
1634 if (!cmd_read)
1636 gdb_assert (cmd == NULL);
1637 if (control != NULL)
1638 cmd = control->body_list_0;
1639 else
1641 std::string str
1642 = string_printf (_("Type commands for breakpoint(s) "
1643 "%s, one per line."),
1644 arg);
1646 auto do_validate = [=] (const char *line)
1648 tracepoint *t
1649 = gdb::checked_static_cast<tracepoint *> (b);
1650 validate_actionline (line, t);
1652 gdb::function_view<void (const char *)> validator;
1653 if (is_tracepoint (b))
1654 validator = do_validate;
1656 cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1658 cmd_read = true;
1661 /* If a breakpoint was on the list more than once, we don't need to
1662 do anything. */
1663 if (b->commands != cmd)
1665 validate_commands_for_breakpoint (b, cmd.get ());
1666 b->commands = cmd;
1667 notify_breakpoint_modified (b);
1672 static void
1673 commands_command (const char *arg, int from_tty)
1675 commands_command_1 (arg, from_tty, NULL);
1678 /* Like commands_command, but instead of reading the commands from
1679 input stream, takes them from an already parsed command structure.
1681 This is used by cli-script.c to DTRT with breakpoint commands
1682 that are part of if and while bodies. */
1683 enum command_control_type
1684 commands_from_control_command (const char *arg, struct command_line *cmd)
1686 commands_command_1 (arg, 0, cmd);
1687 return simple_control;
1690 /* Return true if BL->TARGET_INFO contains valid information. */
1692 static bool
1693 bp_location_has_shadow (struct bp_location *bl)
1695 if (bl->loc_type != bp_loc_software_breakpoint)
1696 return false;
1697 if (!bl->inserted)
1698 return false;
1699 if (bl->target_info.shadow_len == 0)
1700 /* BL isn't valid, or doesn't shadow memory. */
1701 return false;
1702 return true;
1705 /* Update BUF, which is LEN bytes read from the target address
1706 MEMADDR, by replacing a memory breakpoint with its shadowed
1707 contents.
1709 If READBUF is not NULL, this buffer must not overlap with the of
1710 the breakpoint location's shadow_contents buffer. Otherwise, a
1711 failed assertion internal error will be raised. */
1713 static void
1714 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1715 const gdb_byte *writebuf_org,
1716 ULONGEST memaddr, LONGEST len,
1717 struct bp_target_info *target_info,
1718 struct gdbarch *gdbarch)
1720 /* Now do full processing of the found relevant range of elements. */
1721 CORE_ADDR bp_addr = 0;
1722 int bp_size = 0;
1723 int bptoffset = 0;
1725 if (!breakpoint_address_match (target_info->placed_address_space, 0,
1726 current_program_space->aspace.get (), 0))
1728 /* The breakpoint is inserted in a different address space. */
1729 return;
1732 /* Addresses and length of the part of the breakpoint that
1733 we need to copy. */
1734 bp_addr = target_info->placed_address;
1735 bp_size = target_info->shadow_len;
1737 if (bp_addr + bp_size <= memaddr)
1739 /* The breakpoint is entirely before the chunk of memory we are
1740 reading. */
1741 return;
1744 if (bp_addr >= memaddr + len)
1746 /* The breakpoint is entirely after the chunk of memory we are
1747 reading. */
1748 return;
1751 /* Offset within shadow_contents. */
1752 if (bp_addr < memaddr)
1754 /* Only copy the second part of the breakpoint. */
1755 bp_size -= memaddr - bp_addr;
1756 bptoffset = memaddr - bp_addr;
1757 bp_addr = memaddr;
1760 if (bp_addr + bp_size > memaddr + len)
1762 /* Only copy the first part of the breakpoint. */
1763 bp_size -= (bp_addr + bp_size) - (memaddr + len);
1766 if (readbuf != NULL)
1768 /* Verify that the readbuf buffer does not overlap with the
1769 shadow_contents buffer. */
1770 gdb_assert (target_info->shadow_contents >= readbuf + len
1771 || readbuf >= (target_info->shadow_contents
1772 + target_info->shadow_len));
1774 /* Update the read buffer with this inserted breakpoint's
1775 shadow. */
1776 memcpy (readbuf + bp_addr - memaddr,
1777 target_info->shadow_contents + bptoffset, bp_size);
1779 else
1781 const unsigned char *bp;
1782 CORE_ADDR addr = target_info->reqstd_address;
1783 int placed_size;
1785 /* Update the shadow with what we want to write to memory. */
1786 memcpy (target_info->shadow_contents + bptoffset,
1787 writebuf_org + bp_addr - memaddr, bp_size);
1789 /* Determine appropriate breakpoint contents and size for this
1790 address. */
1791 bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1793 /* Update the final write buffer with this inserted
1794 breakpoint's INSN. */
1795 memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1799 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1800 by replacing any memory breakpoints with their shadowed contents.
1802 If READBUF is not NULL, this buffer must not overlap with any of
1803 the breakpoint location's shadow_contents buffers. Otherwise,
1804 a failed assertion internal error will be raised.
1806 The range of shadowed area by each bp_location is:
1807 bl->address - bp_locations_placed_address_before_address_max
1808 up to bl->address + bp_locations_shadow_len_after_address_max
1809 The range we were requested to resolve shadows for is:
1810 memaddr ... memaddr + len
1811 Thus the safe cutoff boundaries for performance optimization are
1812 memaddr + len <= (bl->address
1813 - bp_locations_placed_address_before_address_max)
1814 and:
1815 bl->address + bp_locations_shadow_len_after_address_max <= memaddr */
1817 void
1818 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1819 const gdb_byte *writebuf_org,
1820 ULONGEST memaddr, LONGEST len)
1822 /* Left boundary, right boundary and median element of our binary
1823 search. */
1824 unsigned bc_l, bc_r, bc;
1826 /* Find BC_L which is a leftmost element which may affect BUF
1827 content. It is safe to report lower value but a failure to
1828 report higher one. */
1830 bc_l = 0;
1831 bc_r = bp_locations.size ();
1832 while (bc_l + 1 < bc_r)
1834 struct bp_location *bl;
1836 bc = (bc_l + bc_r) / 2;
1837 bl = bp_locations[bc];
1839 /* Check first BL->ADDRESS will not overflow due to the added
1840 constant. Then advance the left boundary only if we are sure
1841 the BC element can in no way affect the BUF content (MEMADDR
1842 to MEMADDR + LEN range).
1844 Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1845 offset so that we cannot miss a breakpoint with its shadow
1846 range tail still reaching MEMADDR. */
1848 if ((bl->address + bp_locations_shadow_len_after_address_max
1849 >= bl->address)
1850 && (bl->address + bp_locations_shadow_len_after_address_max
1851 <= memaddr))
1852 bc_l = bc;
1853 else
1854 bc_r = bc;
1857 /* Due to the binary search above, we need to make sure we pick the
1858 first location that's at BC_L's address. E.g., if there are
1859 multiple locations at the same address, BC_L may end up pointing
1860 at a duplicate location, and miss the "master"/"inserted"
1861 location. Say, given locations L1, L2 and L3 at addresses A and
1864 L1@A, L2@A, L3@B, ...
1866 BC_L could end up pointing at location L2, while the "master"
1867 location could be L1. Since the `loc->inserted' flag is only set
1868 on "master" locations, we'd forget to restore the shadow of L1
1869 and L2. */
1870 while (bc_l > 0
1871 && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1872 bc_l--;
1874 /* Now do full processing of the found relevant range of elements. */
1876 for (bc = bc_l; bc < bp_locations.size (); bc++)
1878 struct bp_location *bl = bp_locations[bc];
1880 /* bp_location array has BL->OWNER always non-NULL. */
1881 if (bl->owner->type == bp_none)
1882 warning (_("reading through apparently deleted breakpoint #%d?"),
1883 bl->owner->number);
1885 /* Performance optimization: any further element can no longer affect BUF
1886 content. */
1888 if (bl->address >= bp_locations_placed_address_before_address_max
1889 && (memaddr + len
1890 <= (bl->address
1891 - bp_locations_placed_address_before_address_max)))
1892 break;
1894 if (!bp_location_has_shadow (bl))
1895 continue;
1897 one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1898 memaddr, len, &bl->target_info, bl->gdbarch);
1902 /* See breakpoint.h. */
1904 bool
1905 is_breakpoint (const struct breakpoint *bpt)
1907 return (bpt->type == bp_breakpoint
1908 || bpt->type == bp_hardware_breakpoint
1909 || bpt->type == bp_dprintf);
1912 /* Return true if BPT is of any hardware watchpoint kind. */
1914 static bool
1915 is_hardware_watchpoint (const struct breakpoint *bpt)
1917 return (bpt->type == bp_hardware_watchpoint
1918 || bpt->type == bp_read_watchpoint
1919 || bpt->type == bp_access_watchpoint);
1922 /* See breakpoint.h. */
1924 bool
1925 is_watchpoint (const struct breakpoint *bpt)
1927 return (is_hardware_watchpoint (bpt)
1928 || bpt->type == bp_watchpoint);
1931 /* Returns true if the current thread and its running state are safe
1932 to evaluate or update watchpoint B. Watchpoints on local
1933 expressions need to be evaluated in the context of the thread that
1934 was current when the watchpoint was created, and, that thread needs
1935 to be stopped to be able to select the correct frame context.
1936 Watchpoints on global expressions can be evaluated on any thread,
1937 and in any state. It is presently left to the target allowing
1938 memory accesses when threads are running. */
1940 static bool
1941 watchpoint_in_thread_scope (struct watchpoint *b)
1943 return (b->pspace == current_program_space
1944 && (b->watchpoint_thread == null_ptid
1945 || (inferior_ptid == b->watchpoint_thread
1946 && !inferior_thread ()->executing ())));
1949 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1950 associated bp_watchpoint_scope breakpoint. */
1952 static void
1953 watchpoint_del_at_next_stop (struct watchpoint *w)
1955 if (w->related_breakpoint != w)
1957 gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1958 gdb_assert (w->related_breakpoint->related_breakpoint == w);
1959 w->related_breakpoint->disposition = disp_del_at_next_stop;
1960 w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1961 w->related_breakpoint = w;
1963 w->disposition = disp_del_at_next_stop;
1964 disable_breakpoint (w);
1967 /* Extract a bitfield value from value VAL using the bit parameters contained in
1968 watchpoint W. */
1970 static struct value *
1971 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1973 struct value *bit_val;
1975 if (val == NULL)
1976 return NULL;
1978 bit_val = value::allocate (val->type ());
1980 val->unpack_bitfield (bit_val,
1981 w->val_bitpos,
1982 w->val_bitsize,
1983 val->contents_for_printing ().data (),
1984 val->offset ());
1986 return bit_val;
1989 /* Allocate a dummy location and add it to B. This is required
1990 because bpstat_stop_status requires a location to be able to report
1991 stops. */
1993 static void
1994 add_dummy_location (struct breakpoint *b,
1995 struct program_space *pspace)
1997 gdb_assert (!b->has_locations ());
1999 bp_location *loc = new bp_location (b, bp_loc_other);
2000 loc->pspace = pspace;
2001 b->add_location (*loc);
2004 /* Assuming that B is a watchpoint:
2005 - Reparse watchpoint expression, if REPARSE is true
2006 - Evaluate expression and store the result in B->val
2007 - Evaluate the condition if there is one, and store the result
2008 in b->loc->cond.
2009 - Update the list of values that must be watched in B->loc.
2011 If the watchpoint disposition is disp_del_at_next_stop, then do
2012 nothing. If this is local watchpoint that is out of scope, delete
2015 Even with `set breakpoint always-inserted on' the watchpoints are
2016 removed + inserted on each stop here. Normal breakpoints must
2017 never be removed because they might be missed by a running thread
2018 when debugging in non-stop mode. On the other hand, hardware
2019 watchpoints (is_hardware_watchpoint; processed here) are specific
2020 to each LWP since they are stored in each LWP's hardware debug
2021 registers. Therefore, such LWP must be stopped first in order to
2022 be able to modify its hardware watchpoints.
2024 Hardware watchpoints must be reset exactly once after being
2025 presented to the user. It cannot be done sooner, because it would
2026 reset the data used to present the watchpoint hit to the user. And
2027 it must not be done later because it could display the same single
2028 watchpoint hit during multiple GDB stops. Note that the latter is
2029 relevant only to the hardware watchpoint types bp_read_watchpoint
2030 and bp_access_watchpoint. False hit by bp_hardware_watchpoint is
2031 not user-visible - its hit is suppressed if the memory content has
2032 not changed.
2034 The following constraints influence the location where we can reset
2035 hardware watchpoints:
2037 * target_stopped_by_watchpoint and target_stopped_data_address are
2038 called several times when GDB stops.
2040 [linux]
2041 * Multiple hardware watchpoints can be hit at the same time,
2042 causing GDB to stop. GDB only presents one hardware watchpoint
2043 hit at a time as the reason for stopping, and all the other hits
2044 are presented later, one after the other, each time the user
2045 requests the execution to be resumed. Execution is not resumed
2046 for the threads still having pending hit event stored in
2047 LWP_INFO->STATUS. While the watchpoint is already removed from
2048 the inferior on the first stop the thread hit event is kept being
2049 reported from its cached value by linux_nat_stopped_data_address
2050 until the real thread resume happens after the watchpoint gets
2051 presented and thus its LWP_INFO->STATUS gets reset.
2053 Therefore the hardware watchpoint hit can get safely reset on the
2054 watchpoint removal from inferior. */
2056 static void
2057 update_watchpoint (struct watchpoint *b, bool reparse)
2059 bool within_current_scope;
2061 /* If this is a local watchpoint, we only want to check if the
2062 watchpoint frame is in scope if the current thread is the thread
2063 that was used to create the watchpoint. */
2064 if (!watchpoint_in_thread_scope (b))
2065 return;
2067 if (b->disposition == disp_del_at_next_stop)
2068 return;
2070 std::optional<scoped_restore_selected_frame> restore_frame;
2072 /* Determine if the watchpoint is within scope. */
2073 if (b->exp_valid_block == NULL)
2074 within_current_scope = true;
2075 else
2077 frame_info_ptr fi = get_current_frame ();
2078 struct gdbarch *frame_arch = get_frame_arch (fi);
2079 CORE_ADDR frame_pc = get_frame_pc (fi);
2081 /* If we're at a point where the stack has been destroyed
2082 (e.g. in a function epilogue), unwinding may not work
2083 properly. Do not attempt to recreate locations at this
2084 point. See similar comments in watchpoint_check. */
2085 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
2086 return;
2088 /* Save the current frame's ID so we can restore it after
2089 evaluating the watchpoint expression on its own frame. */
2090 /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
2091 took a frame parameter, so that we didn't have to change the
2092 selected frame. */
2093 restore_frame.emplace ();
2095 fi = frame_find_by_id (b->watchpoint_frame);
2096 within_current_scope = (fi != NULL);
2097 if (within_current_scope)
2098 select_frame (fi);
2101 /* We don't free locations. They are stored in the bp_location array
2102 and update_global_location_list will eventually delete them and
2103 remove breakpoints if needed. */
2104 b->clear_locations ();
2106 if (within_current_scope && reparse)
2108 const char *s;
2110 b->exp.reset ();
2111 s = (b->exp_string_reparse
2112 ? b->exp_string_reparse.get ()
2113 : b->exp_string.get ());
2114 b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
2115 /* If the meaning of expression itself changed, the old value is
2116 no longer relevant. We don't want to report a watchpoint hit
2117 to the user when the old value and the new value may actually
2118 be completely different objects. */
2119 b->val = NULL;
2120 b->val_valid = false;
2122 /* Note that unlike with breakpoints, the watchpoint's condition
2123 expression is stored in the breakpoint object, not in the
2124 locations (re)created below. */
2125 if (b->cond_string != NULL)
2127 b->cond_exp.reset ();
2129 s = b->cond_string.get ();
2130 b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
2134 /* If we failed to parse the expression, for example because
2135 it refers to a global variable in a not-yet-loaded shared library,
2136 don't try to insert watchpoint. We don't automatically delete
2137 such watchpoint, though, since failure to parse expression
2138 is different from out-of-scope watchpoint. */
2139 if (!target_has_execution ())
2141 /* Without execution, memory can't change. No use to try and
2142 set watchpoint locations. The watchpoint will be reset when
2143 the target gains execution, through breakpoint_re_set. */
2144 if (!can_use_hw_watchpoints)
2146 if (b->works_in_software_mode ())
2147 b->type = bp_watchpoint;
2148 else
2149 error (_("Can't set read/access watchpoint when "
2150 "hardware watchpoints are disabled."));
2153 else if (within_current_scope && b->exp)
2155 std::vector<value_ref_ptr> val_chain;
2156 struct value *v, *result;
2157 struct program_space *frame_pspace;
2159 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
2160 &val_chain, false);
2162 /* Avoid setting b->val if it's already set. The meaning of
2163 b->val is 'the last value' user saw, and we should update
2164 it only if we reported that last value to user. As it
2165 happens, the code that reports it updates b->val directly.
2166 We don't keep track of the memory value for masked
2167 watchpoints. */
2168 if (!b->val_valid && !is_masked_watchpoint (b))
2170 if (b->val_bitsize != 0)
2171 v = extract_bitfield_from_watchpoint_value (b, v);
2172 b->val = release_value (v);
2173 b->val_valid = true;
2176 frame_pspace = get_frame_program_space (get_selected_frame (NULL));
2178 /* Look at each value on the value chain. */
2179 gdb_assert (!val_chain.empty ());
2180 for (const value_ref_ptr &iter : val_chain)
2182 v = iter.get ();
2184 /* If it's a memory location, and GDB actually needed
2185 its contents to evaluate the expression, then we
2186 must watch it. If the first value returned is
2187 still lazy, that means an error occurred reading it;
2188 watch it anyway in case it becomes readable. */
2189 if (v->lval () == lval_memory
2190 && (v == val_chain[0] || ! v->lazy ()))
2192 struct type *vtype = check_typedef (v->type ());
2194 /* We only watch structs and arrays if user asked
2195 for it explicitly, never if they just happen to
2196 appear in the middle of some value chain. */
2197 if (v == result
2198 || (vtype->code () != TYPE_CODE_STRUCT
2199 && vtype->code () != TYPE_CODE_ARRAY))
2201 CORE_ADDR addr;
2202 enum target_hw_bp_type type;
2203 int bitpos = 0, bitsize = 0;
2205 if (v->bitsize () != 0)
2207 /* Extract the bit parameters out from the bitfield
2208 sub-expression. */
2209 bitpos = v->bitpos ();
2210 bitsize = v->bitsize ();
2212 else if (v == result && b->val_bitsize != 0)
2214 /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2215 lvalue whose bit parameters are saved in the fields
2216 VAL_BITPOS and VAL_BITSIZE. */
2217 bitpos = b->val_bitpos;
2218 bitsize = b->val_bitsize;
2221 addr = v->address ();
2222 if (bitsize != 0)
2224 /* Skip the bytes that don't contain the bitfield. */
2225 addr += bitpos / 8;
2228 type = hw_write;
2229 if (b->type == bp_read_watchpoint)
2230 type = hw_read;
2231 else if (b->type == bp_access_watchpoint)
2232 type = hw_access;
2234 bp_location *loc = b->allocate_location ();
2235 loc->gdbarch = v->type ()->arch ();
2236 loc->pspace = frame_pspace;
2237 loc->address
2238 = gdbarch_remove_non_address_bits (loc->gdbarch, addr);
2239 b->add_location (*loc);
2241 if (bitsize != 0)
2243 /* Just cover the bytes that make up the bitfield. */
2244 loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2246 else
2247 loc->length = v->type ()->length ();
2249 loc->watchpoint_type = type;
2254 /* Helper function to bundle possibly emitting a warning along with
2255 changing the type of B to bp_watchpoint. */
2256 auto change_type_to_bp_watchpoint = [] (breakpoint *bp)
2258 /* Only warn for breakpoints that have been assigned a +ve number,
2259 anything else is either an internal watchpoint (which we don't
2260 currently create) or has not yet been finalized, in which case
2261 this change of type will be occurring before the user is told
2262 the type of this watchpoint. */
2263 if (bp->type == bp_hardware_watchpoint && bp->number > 0)
2264 warning (_("watchpoint %d downgraded to software watchpoint"),
2265 bp->number);
2266 bp->type = bp_watchpoint;
2269 /* Change the type of breakpoint between hardware assisted or
2270 an ordinary watchpoint depending on the hardware support and
2271 free hardware slots. Recheck the number of free hardware slots
2272 as the value chain may have changed. */
2274 int reg_cnt;
2275 enum bp_loc_type loc_type;
2277 reg_cnt = can_use_hardware_watchpoint (val_chain);
2279 if (reg_cnt)
2281 int i, target_resources_ok, other_type_used;
2282 enum bptype type;
2284 /* Use an exact watchpoint when there's only one memory region to be
2285 watched, and only one debug register is needed to watch it. */
2286 b->exact = target_exact_watchpoints && reg_cnt == 1;
2288 /* We need to determine how many resources are already
2289 used for all other hardware watchpoints plus this one
2290 to see if we still have enough resources to also fit
2291 this watchpoint in as well. */
2293 /* If this is a software watchpoint, we try to turn it
2294 to a hardware one -- count resources as if B was of
2295 hardware watchpoint type. */
2296 type = b->type;
2297 if (type == bp_watchpoint)
2298 type = bp_hardware_watchpoint;
2300 /* This watchpoint may or may not have been placed on
2301 the list yet at this point (it won't be in the list
2302 if we're trying to create it for the first time,
2303 through watch_command), so always account for it
2304 manually. */
2306 /* Count resources used by all watchpoints except B. */
2307 i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2309 /* Add in the resources needed for B. */
2310 i += hw_watchpoint_use_count (b);
2312 target_resources_ok
2313 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2314 if (target_resources_ok <= 0)
2316 bool sw_mode = b->works_in_software_mode ();
2318 if (target_resources_ok == 0 && !sw_mode)
2319 error (_("Target does not support this type of "
2320 "hardware watchpoint."));
2321 else if (target_resources_ok < 0 && !sw_mode)
2322 error (_("There are not enough available hardware "
2323 "resources for this watchpoint."));
2325 /* Downgrade to software watchpoint. */
2326 change_type_to_bp_watchpoint (b);
2328 else
2330 /* If this was a software watchpoint, we've just
2331 found we have enough resources to turn it to a
2332 hardware watchpoint. Otherwise, this is a
2333 nop. */
2334 b->type = type;
2337 else if (!b->works_in_software_mode ())
2339 if (!can_use_hw_watchpoints)
2340 error (_("Can't set read/access watchpoint when "
2341 "hardware watchpoints are disabled."));
2342 else
2343 error (_("Expression cannot be implemented with "
2344 "read/access watchpoint."));
2346 else
2347 change_type_to_bp_watchpoint (b);
2349 loc_type = (b->type == bp_watchpoint? bp_loc_software_watchpoint
2350 : bp_loc_hardware_watchpoint);
2352 for (bp_location &bl : b->locations ())
2353 bl.loc_type = loc_type;
2356 /* If a software watchpoint is not watching any memory, then the
2357 above left it without any location set up. But,
2358 bpstat_stop_status requires a location to be able to report
2359 stops, so make sure there's at least a dummy one. */
2360 if (b->type == bp_watchpoint && !b->has_locations ())
2361 add_dummy_location (b, frame_pspace);
2363 else if (!within_current_scope)
2365 gdb_printf (_("\
2366 Watchpoint %d deleted because the program has left the block\n\
2367 in which its expression is valid.\n"),
2368 b->number);
2369 watchpoint_del_at_next_stop (b);
2373 /* Returns true iff breakpoint location should be
2374 inserted in the inferior. We don't differentiate the type of BL's owner
2375 (breakpoint vs. tracepoint), although insert_location in tracepoint's
2376 breakpoint_ops is not defined, because in insert_bp_location,
2377 tracepoint's insert_location will not be called. */
2379 static bool
2380 should_be_inserted (struct bp_location *bl)
2382 if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2383 return false;
2385 if (bl->owner->disposition == disp_del_at_next_stop)
2386 return false;
2388 if (!bl->enabled || bl->disabled_by_cond
2389 || bl->shlib_disabled || bl->duplicate)
2390 return false;
2392 if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2393 return false;
2395 /* This is set for example, when we're attached to the parent of a
2396 vfork, and have detached from the child. The child is running
2397 free, and we expect it to do an exec or exit, at which point the
2398 OS makes the parent schedulable again (and the target reports
2399 that the vfork is done). Until the child is done with the shared
2400 memory region, do not insert breakpoints in the parent, otherwise
2401 the child could still trip on the parent's breakpoints. Since
2402 the parent is blocked anyway, it won't miss any breakpoint. */
2403 if (bl->pspace->breakpoints_not_allowed)
2404 return false;
2406 /* Don't insert a breakpoint if we're trying to step past its
2407 location, except if the breakpoint is a single-step breakpoint,
2408 and the breakpoint's thread is the thread which is stepping past
2409 a breakpoint. */
2410 if ((bl->loc_type == bp_loc_software_breakpoint
2411 || bl->loc_type == bp_loc_hardware_breakpoint)
2412 && stepping_past_instruction_at (bl->pspace->aspace.get (),
2413 bl->address)
2414 /* The single-step breakpoint may be inserted at the location
2415 we're trying to step if the instruction branches to itself.
2416 However, the instruction won't be executed at all and it may
2417 break the semantics of the instruction, for example, the
2418 instruction is a conditional branch or updates some flags.
2419 We can't fix it unless GDB is able to emulate the instruction
2420 or switch to displaced stepping. */
2421 && !(bl->owner->type == bp_single_step
2422 && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2424 infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2425 paddress (bl->gdbarch, bl->address));
2426 return false;
2429 /* Don't insert watchpoints if we're trying to step past the
2430 instruction that triggered one. */
2431 if ((bl->loc_type == bp_loc_hardware_watchpoint)
2432 && stepping_past_nonsteppable_watchpoint ())
2434 infrun_debug_printf ("stepping past non-steppable watchpoint. "
2435 "skipping watchpoint at %s:%d",
2436 paddress (bl->gdbarch, bl->address), bl->length);
2437 return false;
2440 return true;
2443 /* Same as should_be_inserted but does the check assuming
2444 that the location is not duplicated. */
2446 static bool
2447 unduplicated_should_be_inserted (struct bp_location *bl)
2449 scoped_restore restore_bl_duplicate
2450 = make_scoped_restore (&bl->duplicate, 0);
2452 return should_be_inserted (bl);
2455 /* Parses a conditional described by an expression COND into an
2456 agent expression bytecode suitable for evaluation
2457 by the bytecode interpreter. Return NULL if there was
2458 any error during parsing. */
2460 static agent_expr_up
2461 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2463 if (cond == NULL)
2464 return NULL;
2466 agent_expr_up aexpr;
2468 /* We don't want to stop processing, so catch any errors
2469 that may show up. */
2472 aexpr = gen_eval_for_expr (scope, cond);
2475 catch (const gdb_exception_error &ex)
2477 /* If we got here, it means the condition could not be parsed to a valid
2478 bytecode expression and thus can't be evaluated on the target's side.
2479 It's no use iterating through the conditions. */
2482 /* We have a valid agent expression. */
2483 return aexpr;
2486 /* Based on location BL, create a list of breakpoint conditions to be
2487 passed on to the target. If we have duplicated locations with different
2488 conditions, we will add such conditions to the list. The idea is that the
2489 target will evaluate the list of conditions and will only notify GDB when
2490 one of them is true. */
2492 static void
2493 build_target_condition_list (struct bp_location *bl)
2495 bool null_condition_or_parse_error = false;
2496 int modified = bl->needs_update;
2498 /* Release conditions left over from a previous insert. */
2499 bl->target_info.conditions.clear ();
2501 /* This is only meaningful if the target is
2502 evaluating conditions and if the user has
2503 opted for condition evaluation on the target's
2504 side. */
2505 if (gdb_evaluates_breakpoint_condition_p ()
2506 || !target_supports_evaluation_of_breakpoint_conditions ())
2507 return;
2509 auto loc_range = all_bp_locations_at_addr (bl->address);
2511 /* Do a first pass to check for locations with no assigned
2512 conditions or conditions that fail to parse to a valid agent
2513 expression bytecode. If any of these happen, then it's no use to
2514 send conditions to the target since this location will always
2515 trigger and generate a response back to GDB. Note we consider
2516 all locations at the same address irrespective of type, i.e.,
2517 even if the locations aren't considered duplicates (e.g.,
2518 software breakpoint and hardware breakpoint at the same
2519 address). */
2520 for (bp_location *loc : loc_range)
2522 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2524 if (modified)
2526 /* Re-parse the conditions since something changed. In that
2527 case we already freed the condition bytecodes (see
2528 force_breakpoint_reinsertion). We just
2529 need to parse the condition to bytecodes again. */
2530 loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2531 loc->cond.get ());
2534 /* If we have a NULL bytecode expression, it means something
2535 went wrong or we have a null condition expression. */
2536 if (!loc->cond_bytecode)
2538 null_condition_or_parse_error = true;
2539 break;
2544 /* If any of these happened, it means we will have to evaluate the conditions
2545 for the location's address on gdb's side. It is no use keeping bytecodes
2546 for all the other duplicate locations, thus we free all of them here.
2548 This is so we have a finer control over which locations' conditions are
2549 being evaluated by GDB or the remote stub. */
2550 if (null_condition_or_parse_error)
2552 for (bp_location *loc : loc_range)
2554 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2556 /* Only go as far as the first NULL bytecode is
2557 located. */
2558 if (!loc->cond_bytecode)
2559 return;
2561 loc->cond_bytecode.reset ();
2566 /* No NULL conditions or failed bytecode generation. Build a
2567 condition list for this location's address. If we have software
2568 and hardware locations at the same address, they aren't
2569 considered duplicates, but we still merge all the conditions
2570 anyway, as it's simpler, and doesn't really make a practical
2571 difference. */
2572 for (bp_location *loc : loc_range)
2573 if (loc->cond
2574 && is_breakpoint (loc->owner)
2575 && loc->pspace->num == bl->pspace->num
2576 && loc->owner->enable_state == bp_enabled
2577 && loc->enabled
2578 && !loc->disabled_by_cond)
2580 /* Add the condition to the vector. This will be used later
2581 to send the conditions to the target. */
2582 bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2585 return;
2588 /* Parses a command described by string CMD into an agent expression
2589 bytecode suitable for evaluation by the bytecode interpreter.
2590 Return NULL if there was any error during parsing. */
2592 static agent_expr_up
2593 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2595 const char *cmdrest;
2596 const char *format_start, *format_end;
2597 struct gdbarch *gdbarch = get_current_arch ();
2599 if (cmd == NULL)
2600 return NULL;
2602 cmdrest = cmd;
2604 if (*cmdrest == ',')
2605 ++cmdrest;
2606 cmdrest = skip_spaces (cmdrest);
2608 if (*cmdrest++ != '"')
2609 error (_("No format string following the location"));
2611 format_start = cmdrest;
2613 format_pieces fpieces (&cmdrest);
2615 format_end = cmdrest;
2617 if (*cmdrest++ != '"')
2618 error (_("Bad format string, non-terminated '\"'."));
2620 cmdrest = skip_spaces (cmdrest);
2622 if (!(*cmdrest == ',' || *cmdrest == '\0'))
2623 error (_("Invalid argument syntax"));
2625 if (*cmdrest == ',')
2626 cmdrest++;
2627 cmdrest = skip_spaces (cmdrest);
2629 /* For each argument, make an expression. */
2631 std::vector<struct expression *> argvec;
2632 while (*cmdrest != '\0')
2634 const char *cmd1;
2636 cmd1 = cmdrest;
2637 expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope),
2638 PARSER_COMMA_TERMINATES);
2639 argvec.push_back (expr.release ());
2640 cmdrest = cmd1;
2641 if (*cmdrest == ',')
2642 ++cmdrest;
2645 agent_expr_up aexpr;
2647 /* We don't want to stop processing, so catch any errors
2648 that may show up. */
2651 aexpr = gen_printf (scope, gdbarch, 0, 0,
2652 format_start, format_end - format_start,
2653 argvec.size (), argvec.data ());
2655 catch (const gdb_exception_error &ex)
2657 /* If we got here, it means the command could not be parsed to a valid
2658 bytecode expression and thus can't be evaluated on the target's side.
2659 It's no use iterating through the other commands. */
2662 /* We have a valid agent expression, return it. */
2663 return aexpr;
2666 /* Based on location BL, create a list of breakpoint commands to be
2667 passed on to the target. If we have duplicated locations with
2668 different commands, we will add any such to the list. */
2670 static void
2671 build_target_command_list (struct bp_location *bl)
2673 bool null_command_or_parse_error = false;
2674 int modified = bl->needs_update;
2676 /* Clear commands left over from a previous insert. */
2677 bl->target_info.tcommands.clear ();
2679 if (!target_can_run_breakpoint_commands ())
2680 return;
2682 /* For now, limit to agent-style dprintf breakpoints. */
2683 if (dprintf_style != dprintf_style_agent)
2684 return;
2686 auto loc_range = all_bp_locations_at_addr (bl->address);
2688 /* For now, if we have any location at the same address that isn't a
2689 dprintf, don't install the target-side commands, as that would
2690 make the breakpoint not be reported to the core, and we'd lose
2691 control. */
2692 for (bp_location *loc : loc_range)
2693 if (is_breakpoint (loc->owner)
2694 && loc->pspace->num == bl->pspace->num
2695 && loc->owner->type != bp_dprintf)
2696 return;
2698 /* Do a first pass to check for locations with no assigned
2699 conditions or conditions that fail to parse to a valid agent expression
2700 bytecode. If any of these happen, then it's no use to send conditions
2701 to the target since this location will always trigger and generate a
2702 response back to GDB. */
2703 for (bp_location *loc : loc_range)
2705 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2707 if (modified)
2709 /* Re-parse the commands since something changed. In that
2710 case we already freed the command bytecodes (see
2711 force_breakpoint_reinsertion). We just
2712 need to parse the command to bytecodes again. */
2713 loc->cmd_bytecode
2714 = parse_cmd_to_aexpr (bl->address,
2715 loc->owner->extra_string.get ());
2718 /* If we have a NULL bytecode expression, it means something
2719 went wrong or we have a null command expression. */
2720 if (!loc->cmd_bytecode)
2722 null_command_or_parse_error = true;
2723 break;
2728 /* If anything failed, then we're not doing target-side commands,
2729 and so clean up. */
2730 if (null_command_or_parse_error)
2732 for (bp_location *loc : loc_range)
2733 if (is_breakpoint (loc->owner)
2734 && loc->pspace->num == bl->pspace->num)
2736 /* Only go as far as the first NULL bytecode is
2737 located. */
2738 if (loc->cmd_bytecode == NULL)
2739 return;
2741 loc->cmd_bytecode.reset ();
2745 /* No NULL commands or failed bytecode generation. Build a command
2746 list for all duplicate locations at this location's address.
2747 Note that here we must care for whether the breakpoint location
2748 types are considered duplicates, otherwise, say, if we have a
2749 software and hardware location at the same address, the target
2750 could end up running the commands twice. For the moment, we only
2751 support targets-side commands with dprintf, but it doesn't hurt
2752 to be pedantically correct in case that changes. */
2753 for (bp_location *loc : loc_range)
2754 if (breakpoint_locations_match (bl, loc)
2755 && loc->owner->extra_string
2756 && is_breakpoint (loc->owner)
2757 && loc->pspace->num == bl->pspace->num
2758 && loc->owner->enable_state == bp_enabled
2759 && loc->enabled
2760 && !loc->disabled_by_cond)
2762 /* Add the command to the vector. This will be used later
2763 to send the commands to the target. */
2764 bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2767 bl->target_info.persist = 0;
2768 /* Maybe flag this location as persistent. */
2769 if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2770 bl->target_info.persist = 1;
2773 /* Return the kind of breakpoint on address *ADDR. Get the kind
2774 of breakpoint according to ADDR except single-step breakpoint.
2775 Get the kind of single-step breakpoint according to the current
2776 registers state. */
2778 static int
2779 breakpoint_kind (const struct bp_location *bl, CORE_ADDR *addr)
2781 if (bl->owner->type == bp_single_step)
2783 struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2784 struct regcache *regcache;
2786 regcache = get_thread_regcache (thr);
2788 return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2789 regcache, addr);
2791 else
2792 return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2795 /* Rethrow the currently handled exception, if it's a TARGET_CLOSE_ERROR.
2796 E is either the currently handled exception, or a copy, or a sliced copy,
2797 so we can't rethrow that one, but we can use it to inspect the properties
2798 of the currently handled exception. */
2800 static void
2801 rethrow_on_target_close_error (const gdb_exception &e)
2803 if (e.reason == 0)
2804 return;
2805 /* Can't set the breakpoint. */
2807 if (e.error != TARGET_CLOSE_ERROR)
2808 return;
2810 /* If the target has closed then it will have deleted any breakpoints
2811 inserted within the target inferior, as a result any further attempts
2812 to interact with the breakpoint objects is not possible. Just rethrow
2813 the error. Don't use e to rethrow, to prevent object slicing of the
2814 exception. */
2815 throw;
2818 /* Insert a low-level "breakpoint" of some type. BL is the breakpoint
2819 location. Any error messages are printed to TMP_ERROR_STREAM; and
2820 DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2821 Returns 0 for success, 1 if the bp_location type is not supported or
2822 -1 for failure.
2824 NOTE drow/2003-09-09: This routine could be broken down to an
2825 object-style method for each breakpoint or catchpoint type. */
2826 static int
2827 insert_bp_location (struct bp_location *bl,
2828 struct ui_file *tmp_error_stream,
2829 int *disabled_breaks,
2830 int *hw_breakpoint_error,
2831 int *hw_bp_error_explained_already)
2833 gdb_exception bp_excpt;
2835 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2836 return 0;
2838 breakpoint_debug_printf ("%s", breakpoint_location_address_str (bl).c_str ());
2840 /* Note we don't initialize bl->target_info, as that wipes out
2841 the breakpoint location's shadow_contents if the breakpoint
2842 is still inserted at that location. This in turn breaks
2843 target_read_memory which depends on these buffers when
2844 a memory read is requested at the breakpoint location:
2845 Once the target_info has been wiped, we fail to see that
2846 we have a breakpoint inserted at that address and thus
2847 read the breakpoint instead of returning the data saved in
2848 the breakpoint location's shadow contents. */
2849 bl->target_info.reqstd_address = bl->address;
2850 bl->target_info.placed_address_space = bl->pspace->aspace.get ();
2851 bl->target_info.length = bl->length;
2853 /* When working with target-side conditions, we must pass all the conditions
2854 for the same breakpoint address down to the target since GDB will not
2855 insert those locations. With a list of breakpoint conditions, the target
2856 can decide when to stop and notify GDB. */
2858 if (is_breakpoint (bl->owner))
2860 build_target_condition_list (bl);
2861 build_target_command_list (bl);
2862 /* Reset the modification marker. */
2863 bl->needs_update = 0;
2866 /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2867 set at a read-only address, then a breakpoint location will have
2868 been changed to hardware breakpoint before we get here. If it is
2869 "off" however, error out before actually trying to insert the
2870 breakpoint, with a nicer error message. */
2871 if (bl->loc_type == bp_loc_software_breakpoint
2872 && !automatic_hardware_breakpoints)
2874 mem_region *mr = lookup_mem_region (bl->address);
2876 if (mr != nullptr && mr->attrib.mode != MEM_RW)
2878 gdb_printf (tmp_error_stream,
2879 _("Cannot insert breakpoint %d.\n"
2880 "Cannot set software breakpoint "
2881 "at read-only address %s\n"),
2882 bl->owner->number,
2883 paddress (bl->gdbarch, bl->address));
2884 return 1;
2888 if (bl->loc_type == bp_loc_software_breakpoint
2889 || bl->loc_type == bp_loc_hardware_breakpoint)
2891 /* First check to see if we have to handle an overlay. */
2892 if (overlay_debugging == ovly_off
2893 || bl->section == NULL
2894 || !(section_is_overlay (bl->section)))
2896 /* No overlay handling: just set the breakpoint. */
2899 int val;
2901 val = bl->owner->insert_location (bl);
2902 if (val)
2903 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2905 catch (gdb_exception &e)
2907 rethrow_on_target_close_error (e);
2908 bp_excpt = std::move (e);
2911 else
2913 /* This breakpoint is in an overlay section.
2914 Shall we set a breakpoint at the LMA? */
2915 if (!overlay_events_enabled)
2917 /* Yes -- overlay event support is not active,
2918 so we must try to set a breakpoint at the LMA.
2919 This will not work for a hardware breakpoint. */
2920 if (bl->loc_type == bp_loc_hardware_breakpoint)
2921 warning (_("hardware breakpoint %d not supported in overlay!"),
2922 bl->owner->number);
2923 else
2925 CORE_ADDR addr = overlay_unmapped_address (bl->address,
2926 bl->section);
2927 /* Set a software (trap) breakpoint at the LMA. */
2928 bl->overlay_target_info = bl->target_info;
2929 bl->overlay_target_info.reqstd_address = addr;
2931 /* No overlay handling: just set the breakpoint. */
2934 int val;
2936 bl->overlay_target_info.kind
2937 = breakpoint_kind (bl, &addr);
2938 bl->overlay_target_info.placed_address = addr;
2939 val = target_insert_breakpoint (bl->gdbarch,
2940 &bl->overlay_target_info);
2941 if (val)
2942 bp_excpt
2943 = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2945 catch (gdb_exception &e)
2947 rethrow_on_target_close_error (e);
2948 bp_excpt = std::move (e);
2951 if (bp_excpt.reason != 0)
2952 gdb_printf (tmp_error_stream,
2953 "Overlay breakpoint %d "
2954 "failed: in ROM?\n",
2955 bl->owner->number);
2958 /* Shall we set a breakpoint at the VMA? */
2959 if (section_is_mapped (bl->section))
2961 /* Yes. This overlay section is mapped into memory. */
2964 int val;
2966 val = bl->owner->insert_location (bl);
2967 if (val)
2968 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2970 catch (gdb_exception_error &e)
2972 rethrow_on_target_close_error (e);
2973 bp_excpt = std::move (e);
2976 else
2978 /* No. This breakpoint will not be inserted.
2979 No error, but do not mark the bp as 'inserted'. */
2980 return 0;
2984 if (bp_excpt.reason != 0)
2986 /* Can't set the breakpoint. */
2987 gdb_assert (bl->owner != nullptr);
2989 /* In some cases, we might not be able to insert a
2990 breakpoint in a shared library that has already been
2991 removed, but we have not yet processed the shlib unload
2992 event. Unfortunately, some targets that implement
2993 breakpoint insertion themselves can't tell why the
2994 breakpoint insertion failed (e.g., the remote target
2995 doesn't define error codes), so we must treat generic
2996 errors as memory errors. */
2997 if (bp_excpt.reason == RETURN_ERROR
2998 && (bp_excpt.error == GENERIC_ERROR
2999 || bp_excpt.error == MEMORY_ERROR)
3000 && bl->loc_type == bp_loc_software_breakpoint
3001 && (solib_name_from_address (bl->pspace, bl->address)
3002 || shared_objfile_contains_address_p (bl->pspace,
3003 bl->address)))
3005 /* See also: disable_breakpoints_in_shlibs. */
3006 bl->shlib_disabled = 1;
3007 notify_breakpoint_modified (bl->owner);
3008 if (!*disabled_breaks)
3010 gdb_printf (tmp_error_stream,
3011 "Cannot insert breakpoint %d.\n",
3012 bl->owner->number);
3013 gdb_printf (tmp_error_stream,
3014 "Temporarily disabling shared "
3015 "library breakpoints:\n");
3017 *disabled_breaks = 1;
3018 gdb_printf (tmp_error_stream,
3019 "breakpoint #%d\n", bl->owner->number);
3020 return 0;
3022 else
3024 if (bl->loc_type == bp_loc_hardware_breakpoint)
3026 *hw_breakpoint_error = 1;
3027 *hw_bp_error_explained_already = bp_excpt.message != NULL;
3028 gdb_printf (tmp_error_stream,
3029 "Cannot insert hardware breakpoint %d%s",
3030 bl->owner->number,
3031 bp_excpt.message ? ":" : ".\n");
3032 if (bp_excpt.message != NULL)
3033 gdb_printf (tmp_error_stream, "%s.\n",
3034 bp_excpt.what ());
3036 else
3038 if (bp_excpt.message == NULL)
3040 std::string message
3041 = memory_error_message (TARGET_XFER_E_IO,
3042 bl->gdbarch, bl->address);
3044 gdb_printf (tmp_error_stream,
3045 "Cannot insert breakpoint %d.\n"
3046 "%s\n",
3047 bl->owner->number, message.c_str ());
3049 else
3051 gdb_printf (tmp_error_stream,
3052 "Cannot insert breakpoint %d: %s\n",
3053 bl->owner->number,
3054 bp_excpt.what ());
3057 return 1;
3061 else
3062 bl->inserted = 1;
3064 return 0;
3067 else if (bl->loc_type == bp_loc_hardware_watchpoint
3068 && bl->owner->disposition != disp_del_at_next_stop)
3070 int val;
3072 val = bl->owner->insert_location (bl);
3074 /* If trying to set a read-watchpoint, and it turns out it's not
3075 supported, try emulating one with an access watchpoint. */
3076 if (val == 1 && bl->watchpoint_type == hw_read)
3078 /* But don't try to insert it, if there's already another
3079 hw_access location that would be considered a duplicate
3080 of this one. */
3081 for (bp_location *loc : all_bp_locations ())
3082 if (loc != bl
3083 && loc->watchpoint_type == hw_access
3084 && watchpoint_locations_match (bl, loc))
3086 bl->duplicate = 1;
3087 bl->inserted = 1;
3088 bl->target_info = loc->target_info;
3089 bl->watchpoint_type = hw_access;
3090 val = 0;
3091 break;
3094 if (val == 1)
3096 bl->watchpoint_type = hw_access;
3097 val = bl->owner->insert_location (bl);
3099 if (val)
3100 /* Back to the original value. */
3101 bl->watchpoint_type = hw_read;
3105 bl->inserted = (val == 0);
3108 else if (bl->owner->type == bp_catchpoint)
3110 int val;
3112 val = bl->owner->insert_location (bl);
3113 if (val)
3115 bl->owner->enable_state = bp_disabled;
3117 if (val == 1)
3118 warning (_("\
3119 Error inserting catchpoint %d: Your system does not support this type\n\
3120 of catchpoint."), bl->owner->number);
3121 else
3122 warning (_("Error inserting catchpoint %d."), bl->owner->number);
3125 bl->inserted = (val == 0);
3127 /* We've already printed an error message if there was a problem
3128 inserting this catchpoint, and we've disabled the catchpoint,
3129 so just return success. */
3130 return 0;
3133 return 0;
3136 /* This function is called when program space PSPACE is about to be
3137 deleted. It takes care of updating breakpoints to not reference
3138 PSPACE anymore. */
3140 void
3141 breakpoint_program_space_exit (struct program_space *pspace)
3143 /* Remove any breakpoint that was set through this program space. */
3144 for (breakpoint &b : all_breakpoints_safe ())
3145 if (b.pspace == pspace)
3146 delete_breakpoint (&b);
3148 /* Breakpoints set through other program spaces could have locations
3149 bound to PSPACE as well. Remove those. */
3150 for (bp_location *loc : all_bp_locations ())
3151 if (loc->pspace == pspace)
3153 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
3154 loc->owner->unadd_location (*loc);
3157 /* Now update the global location list to permanently delete the
3158 removed locations above. */
3159 update_global_location_list (UGLL_DONT_INSERT);
3162 /* Make sure all breakpoints are inserted in inferior.
3163 Throws exception on any error.
3164 A breakpoint that is already inserted won't be inserted
3165 again, so calling this function twice is safe. */
3166 void
3167 insert_breakpoints (void)
3169 for (breakpoint &bpt : all_breakpoints ())
3170 if (is_hardware_watchpoint (&bpt))
3172 watchpoint &w = gdb::checked_static_cast<watchpoint &> (bpt);
3174 update_watchpoint (&w, false /* don't reparse. */);
3177 /* Updating watchpoints creates new locations, so update the global
3178 location list. Explicitly tell ugll to insert locations and
3179 ignore breakpoints_always_inserted_mode. Also,
3180 update_global_location_list tries to "upgrade" software
3181 breakpoints to hardware breakpoints to handle "set breakpoint
3182 auto-hw", so we need to call it even if we don't have new
3183 locations. */
3184 update_global_location_list (UGLL_INSERT);
3187 /* This is used when we need to synch breakpoint conditions between GDB and the
3188 target. It is the case with deleting and disabling of breakpoints when using
3189 always-inserted mode. */
3191 static void
3192 update_inserted_breakpoint_locations (void)
3194 int error_flag = 0;
3195 int val = 0;
3196 int disabled_breaks = 0;
3197 int hw_breakpoint_error = 0;
3198 int hw_bp_details_reported = 0;
3200 string_file tmp_error_stream;
3202 /* Explicitly mark the warning -- this will only be printed if
3203 there was an error. */
3204 tmp_error_stream.puts ("Warning:\n");
3206 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3208 for (bp_location *bl : all_bp_locations ())
3210 /* We only want to update software breakpoints and hardware
3211 breakpoints. */
3212 if (!is_breakpoint (bl->owner))
3213 continue;
3215 /* We only want to update locations that are already inserted
3216 and need updating. This is to avoid unwanted insertion during
3217 deletion of breakpoints. */
3218 if (!bl->inserted || !bl->needs_update)
3219 continue;
3221 switch_to_program_space_and_thread (bl->pspace);
3223 /* For targets that support global breakpoints, there's no need
3224 to select an inferior to insert breakpoint to. In fact, even
3225 if we aren't attached to any process yet, we should still
3226 insert breakpoints. */
3227 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
3228 && (inferior_ptid == null_ptid || !target_has_execution ()))
3229 continue;
3231 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3232 &hw_breakpoint_error, &hw_bp_details_reported);
3233 if (val)
3234 error_flag = val;
3237 if (error_flag)
3239 target_terminal::ours_for_output ();
3240 error (("%s"), tmp_error_stream.c_str ());
3244 /* Used when starting or continuing the program. */
3246 static void
3247 insert_breakpoint_locations (void)
3249 int error_flag = 0;
3250 int val = 0;
3251 int disabled_breaks = 0;
3252 int hw_breakpoint_error = 0;
3253 int hw_bp_error_explained_already = 0;
3255 string_file tmp_error_stream;
3257 /* Explicitly mark the warning -- this will only be printed if
3258 there was an error. */
3259 tmp_error_stream.puts ("Warning:\n");
3261 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3263 for (bp_location *bl : all_bp_locations ())
3265 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3266 continue;
3268 /* There is no point inserting thread-specific breakpoints if
3269 the thread no longer exists. ALL_BP_LOCATIONS bp_location
3270 has BL->OWNER always non-NULL. */
3271 if (bl->owner->thread != -1
3272 && !valid_global_thread_id (bl->owner->thread))
3273 continue;
3275 /* Or inferior specific breakpoints if the inferior no longer
3276 exists. */
3277 if (bl->owner->inferior != -1
3278 && !valid_global_inferior_id (bl->owner->inferior))
3279 continue;
3281 switch_to_program_space_and_thread (bl->pspace);
3283 /* For targets that support global breakpoints, there's no need
3284 to select an inferior to insert breakpoint to. In fact, even
3285 if we aren't attached to any process yet, we should still
3286 insert breakpoints. */
3287 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
3288 && (inferior_ptid == null_ptid || !target_has_execution ()))
3289 continue;
3291 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3292 &hw_breakpoint_error, &hw_bp_error_explained_already);
3293 if (val)
3294 error_flag = val;
3297 /* If we failed to insert all locations of a watchpoint, remove
3298 them, as half-inserted watchpoint is of limited use. */
3299 for (breakpoint &bpt : all_breakpoints ())
3301 bool some_failed = false;
3303 if (!is_hardware_watchpoint (&bpt))
3304 continue;
3306 if (!breakpoint_enabled (&bpt))
3307 continue;
3309 if (bpt.disposition == disp_del_at_next_stop)
3310 continue;
3312 for (bp_location &loc : bpt.locations ())
3313 if (!loc.inserted && should_be_inserted (&loc))
3315 some_failed = true;
3316 break;
3319 if (some_failed)
3321 for (bp_location &loc : bpt.locations ())
3322 if (loc.inserted)
3323 remove_breakpoint (&loc);
3325 hw_breakpoint_error = 1;
3326 tmp_error_stream.printf ("Could not insert "
3327 "hardware watchpoint %d.\n",
3328 bpt.number);
3329 error_flag = -1;
3333 if (error_flag)
3335 /* If a hardware breakpoint or watchpoint was inserted, add a
3336 message about possibly exhausted resources. */
3337 if (hw_breakpoint_error && !hw_bp_error_explained_already)
3339 tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3340 You may have requested too many hardware breakpoints/watchpoints.\n");
3342 target_terminal::ours_for_output ();
3343 error (("%s"), tmp_error_stream.c_str ());
3347 /* Used when the program stops.
3348 Returns zero if successful, or non-zero if there was a problem
3349 removing a breakpoint location. */
3352 remove_breakpoints (void)
3354 int val = 0;
3356 for (bp_location *bl : all_bp_locations ())
3357 if (bl->inserted && !is_tracepoint (bl->owner))
3358 val |= remove_breakpoint (bl);
3360 return val;
3363 /* When a thread exits, remove breakpoints that are related to
3364 that thread. */
3366 static void
3367 remove_threaded_breakpoints (thread_info *tp,
3368 std::optional<ULONGEST> /* exit_code */,
3369 int /* silent */)
3371 for (breakpoint &b : all_breakpoints_safe ())
3373 if (b.thread == tp->global_num && user_breakpoint_p (&b))
3375 gdb_printf (_("\
3376 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3377 b.number, print_thread_id (tp));
3378 delete_breakpoint (&b);
3383 /* Called when inferior INF has been removed from GDB. Remove associated
3384 per-inferior breakpoints. */
3386 static void
3387 remove_inferior_breakpoints (struct inferior *inf)
3389 for (breakpoint &b : all_breakpoints_safe ())
3391 if (b.inferior == inf->num && user_breakpoint_p (&b))
3393 /* Tell the user the breakpoint has been deleted. But only for
3394 breakpoints that would not normally have been deleted at the
3395 next stop anyway. */
3396 if (b.disposition != disp_del
3397 && b.disposition != disp_del_at_next_stop)
3398 gdb_printf (_("\
3399 Inferior-specific breakpoint %d deleted - inferior %d has been removed.\n"),
3400 b.number, inf->num);
3401 delete_breakpoint (&b);
3406 /* See breakpoint.h. */
3408 void
3409 remove_breakpoints_inf (inferior *inf)
3411 int val;
3413 breakpoint_debug_printf ("inf->num = %d", inf->num);
3415 for (bp_location *bl : all_bp_locations ())
3417 if (bl->pspace != inf->pspace)
3418 continue;
3420 if (bl->inserted && !bl->target_info.persist)
3422 val = remove_breakpoint (bl);
3423 if (val != 0)
3424 return;
3429 static int internal_breakpoint_number = -1;
3431 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3432 If INTERNAL is non-zero, the breakpoint number will be populated
3433 from internal_breakpoint_number and that variable decremented.
3434 Otherwise the breakpoint number will be populated from
3435 breakpoint_count and that value incremented. Internal breakpoints
3436 do not set the internal var bpnum. */
3437 static void
3438 set_breakpoint_number (int internal, struct breakpoint *b)
3440 if (internal)
3441 b->number = internal_breakpoint_number--;
3442 else
3444 set_breakpoint_count (breakpoint_count + 1);
3445 b->number = breakpoint_count;
3449 /* Create a TYPE breakpoint on ADDRESS from an object file with GDBARCH. */
3451 static struct breakpoint *
3452 create_internal_breakpoint (struct gdbarch *gdbarch,
3453 CORE_ADDR address, enum bptype type)
3455 std::unique_ptr<internal_breakpoint> b
3456 (new internal_breakpoint (gdbarch, type, address));
3458 b->number = internal_breakpoint_number--;
3460 return add_to_breakpoint_chain (std::move (b));
3463 /* Create a TYPE breakpoint on minimal symbol MSYM from an object file with
3464 GDBARCH. */
3466 static struct breakpoint *
3467 create_internal_breakpoint (struct gdbarch *gdbarch,
3468 struct bound_minimal_symbol &msym, enum bptype type)
3470 CORE_ADDR address;
3472 address = msym.value_address ();
3474 address = gdbarch_convert_from_func_ptr_addr
3475 (gdbarch, address, current_inferior ()->top_target ());
3477 /* Note that we're not using gdbarch_addr_bits_remove here, because that's
3478 related to addresses in $pc. We're getting the address from the
3479 minimal symbol table. */
3481 /* Is gdbarch_deprecated_function_start_offset needed here? Or is that dealt
3482 with elsewhere? Needs testing on vax. */
3484 if (gdbarch_skip_entrypoint_p (gdbarch))
3485 address = gdbarch_skip_entrypoint (gdbarch, address);
3487 return create_internal_breakpoint (gdbarch, address, type);
3490 static const char *const longjmp_names[] =
3492 "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3494 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3496 /* Per-objfile data private to breakpoint.c. */
3497 struct breakpoint_objfile_data
3499 /* Minimal symbol for "_ovly_debug_event" (if any). */
3500 struct bound_minimal_symbol overlay_msym;
3502 /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any). */
3503 struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3505 /* True if we have looked for longjmp probes. */
3506 int longjmp_searched = 0;
3508 /* SystemTap probe points for longjmp (if any). These are non-owning
3509 references. */
3510 std::vector<probe *> longjmp_probes;
3512 /* Minimal symbol for "std::terminate()" (if any). */
3513 struct bound_minimal_symbol terminate_msym;
3515 /* Minimal symbol for "_Unwind_DebugHook" (if any). */
3516 struct bound_minimal_symbol exception_msym;
3518 /* True if we have looked for exception probes. */
3519 int exception_searched = 0;
3521 /* SystemTap probe points for unwinding (if any). These are non-owning
3522 references. */
3523 std::vector<probe *> exception_probes;
3526 static const registry<objfile>::key<breakpoint_objfile_data>
3527 breakpoint_objfile_key;
3529 /* Minimal symbol not found sentinel. */
3530 static struct minimal_symbol msym_not_found;
3532 /* Returns TRUE if MSYM point to the "not found" sentinel. */
3534 static bool
3535 msym_not_found_p (const struct minimal_symbol *msym)
3537 return msym == &msym_not_found;
3540 /* Return per-objfile data needed by breakpoint.c.
3541 Allocate the data if necessary. */
3543 static struct breakpoint_objfile_data *
3544 get_breakpoint_objfile_data (struct objfile *objfile)
3546 struct breakpoint_objfile_data *bp_objfile_data;
3548 bp_objfile_data = breakpoint_objfile_key.get (objfile);
3549 if (bp_objfile_data == NULL)
3550 bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3551 return bp_objfile_data;
3554 static void
3555 create_overlay_event_breakpoint (void)
3557 const char *const func_name = "_ovly_debug_event";
3559 for (objfile *objfile : current_program_space->objfiles ())
3561 struct breakpoint *b;
3562 struct breakpoint_objfile_data *bp_objfile_data;
3563 CORE_ADDR addr;
3565 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3567 if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3568 continue;
3570 if (bp_objfile_data->overlay_msym.minsym == NULL)
3572 struct bound_minimal_symbol m;
3574 m = lookup_minimal_symbol_text (func_name, objfile);
3575 if (m.minsym == NULL)
3577 /* Avoid future lookups in this objfile. */
3578 bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3579 continue;
3581 bp_objfile_data->overlay_msym = m;
3584 addr = bp_objfile_data->overlay_msym.value_address ();
3585 b = create_internal_breakpoint (objfile->arch (), addr,
3586 bp_overlay_event);
3587 b->locspec = new_explicit_location_spec_function (func_name);
3589 if (overlay_debugging == ovly_auto)
3591 b->enable_state = bp_enabled;
3592 overlay_events_enabled = 1;
3594 else
3596 b->enable_state = bp_disabled;
3597 overlay_events_enabled = 0;
3602 /* Install a master longjmp breakpoint for OBJFILE using a probe. Return
3603 true if a breakpoint was installed. */
3605 static bool
3606 create_longjmp_master_breakpoint_probe (objfile *objfile)
3608 struct gdbarch *gdbarch = objfile->arch ();
3609 struct breakpoint_objfile_data *bp_objfile_data
3610 = get_breakpoint_objfile_data (objfile);
3612 if (!bp_objfile_data->longjmp_searched)
3614 std::vector<probe *> ret
3615 = find_probes_in_objfile (objfile, "libc", "longjmp");
3617 if (!ret.empty ())
3619 /* We are only interested in checking one element. */
3620 probe *p = ret[0];
3622 if (!p->can_evaluate_arguments ())
3624 /* We cannot use the probe interface here,
3625 because it does not know how to evaluate
3626 arguments. */
3627 ret.clear ();
3630 bp_objfile_data->longjmp_probes = ret;
3631 bp_objfile_data->longjmp_searched = 1;
3634 if (bp_objfile_data->longjmp_probes.empty ())
3635 return false;
3637 for (probe *p : bp_objfile_data->longjmp_probes)
3639 struct breakpoint *b;
3641 b = create_internal_breakpoint (gdbarch,
3642 p->get_relocated_address (objfile),
3643 bp_longjmp_master);
3644 b->locspec = new_probe_location_spec ("-probe-stap libc:longjmp");
3645 b->enable_state = bp_disabled;
3648 return true;
3651 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3652 Return true if at least one breakpoint was installed. */
3654 static bool
3655 create_longjmp_master_breakpoint_names (objfile *objfile)
3657 struct gdbarch *gdbarch = objfile->arch ();
3658 if (!gdbarch_get_longjmp_target_p (gdbarch))
3659 return false;
3661 struct breakpoint_objfile_data *bp_objfile_data
3662 = get_breakpoint_objfile_data (objfile);
3663 unsigned int installed_bp = 0;
3665 for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3667 struct breakpoint *b;
3668 const char *func_name;
3669 CORE_ADDR addr;
3671 if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3672 continue;
3674 func_name = longjmp_names[i];
3675 if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3677 struct bound_minimal_symbol m;
3679 m = lookup_minimal_symbol_text (func_name, objfile);
3680 if (m.minsym == NULL)
3682 /* Prevent future lookups in this objfile. */
3683 bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3684 continue;
3686 bp_objfile_data->longjmp_msym[i] = m;
3689 addr = bp_objfile_data->longjmp_msym[i].value_address ();
3690 b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master);
3691 b->locspec = new_explicit_location_spec_function (func_name);
3692 b->enable_state = bp_disabled;
3693 installed_bp++;
3696 return installed_bp > 0;
3699 /* Create a master longjmp breakpoint. */
3701 static void
3702 create_longjmp_master_breakpoint (void)
3704 scoped_restore_current_program_space restore_pspace;
3706 for (struct program_space *pspace : program_spaces)
3708 set_current_program_space (pspace);
3710 for (objfile *obj : current_program_space->objfiles ())
3712 /* Skip separate debug object, it's handled in the loop below. */
3713 if (obj->separate_debug_objfile_backlink != nullptr)
3714 continue;
3716 /* Try a probe kind breakpoint on main objfile. */
3717 if (create_longjmp_master_breakpoint_probe (obj))
3718 continue;
3720 /* Try longjmp_names kind breakpoints on main and separate_debug
3721 objfiles. */
3722 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3723 if (create_longjmp_master_breakpoint_names (debug_objfile))
3724 break;
3729 /* Create a master std::terminate breakpoint. */
3730 static void
3731 create_std_terminate_master_breakpoint (void)
3733 const char *const func_name = "std::terminate()";
3735 scoped_restore_current_program_space restore_pspace;
3737 for (struct program_space *pspace : program_spaces)
3739 set_current_program_space (pspace);
3741 for (objfile *objfile : current_program_space->objfiles ())
3743 struct breakpoint *b;
3744 struct breakpoint_objfile_data *bp_objfile_data;
3746 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3748 if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3749 continue;
3751 if (bp_objfile_data->terminate_msym.minsym == NULL)
3753 struct bound_minimal_symbol m;
3755 m = lookup_minimal_symbol (func_name, NULL, objfile);
3756 if (m.minsym == NULL || (m.minsym->type () != mst_text
3757 && m.minsym->type () != mst_file_text))
3759 /* Prevent future lookups in this objfile. */
3760 bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3761 continue;
3763 bp_objfile_data->terminate_msym = m;
3766 b = create_internal_breakpoint (objfile->arch (),
3767 bp_objfile_data->terminate_msym,
3768 bp_std_terminate_master);
3769 b->locspec = new_explicit_location_spec_function (func_name);
3770 b->enable_state = bp_disabled;
3775 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3776 probe. Return true if a breakpoint was installed. */
3778 static bool
3779 create_exception_master_breakpoint_probe (objfile *objfile)
3781 struct breakpoint *b;
3782 struct gdbarch *gdbarch;
3783 struct breakpoint_objfile_data *bp_objfile_data;
3785 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3787 /* We prefer the SystemTap probe point if it exists. */
3788 if (!bp_objfile_data->exception_searched)
3790 std::vector<probe *> ret
3791 = find_probes_in_objfile (objfile, "libgcc", "unwind");
3793 if (!ret.empty ())
3795 /* We are only interested in checking one element. */
3796 probe *p = ret[0];
3798 if (!p->can_evaluate_arguments ())
3800 /* We cannot use the probe interface here, because it does
3801 not know how to evaluate arguments. */
3802 ret.clear ();
3805 bp_objfile_data->exception_probes = ret;
3806 bp_objfile_data->exception_searched = 1;
3809 if (bp_objfile_data->exception_probes.empty ())
3810 return false;
3812 gdbarch = objfile->arch ();
3814 for (probe *p : bp_objfile_data->exception_probes)
3816 b = create_internal_breakpoint (gdbarch,
3817 p->get_relocated_address (objfile),
3818 bp_exception_master);
3819 b->locspec = new_probe_location_spec ("-probe-stap libgcc:unwind");
3820 b->enable_state = bp_disabled;
3823 return true;
3826 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3827 _Unwind_DebugHook. Return true if a breakpoint was installed. */
3829 static bool
3830 create_exception_master_breakpoint_hook (objfile *objfile)
3832 const char *const func_name = "_Unwind_DebugHook";
3833 struct breakpoint *b;
3834 struct gdbarch *gdbarch;
3835 struct breakpoint_objfile_data *bp_objfile_data;
3837 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3839 if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3840 return false;
3842 gdbarch = objfile->arch ();
3844 if (bp_objfile_data->exception_msym.minsym == NULL)
3846 struct bound_minimal_symbol debug_hook;
3848 debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3849 if (debug_hook.minsym == NULL)
3851 bp_objfile_data->exception_msym.minsym = &msym_not_found;
3852 return false;
3855 bp_objfile_data->exception_msym = debug_hook;
3858 b = create_internal_breakpoint (gdbarch, bp_objfile_data->exception_msym,
3859 bp_exception_master);
3860 b->locspec = new_explicit_location_spec_function (func_name);
3861 b->enable_state = bp_disabled;
3863 return true;
3866 /* Install a master breakpoint on the unwinder's debug hook. */
3868 static void
3869 create_exception_master_breakpoint (void)
3871 for (objfile *obj : current_program_space->objfiles ())
3873 /* Skip separate debug object. */
3874 if (obj->separate_debug_objfile_backlink)
3875 continue;
3877 /* Try a probe kind breakpoint. */
3878 if (create_exception_master_breakpoint_probe (obj))
3879 continue;
3881 /* Iterate over main and separate debug objects and try an
3882 _Unwind_DebugHook kind breakpoint. */
3883 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3884 if (create_exception_master_breakpoint_hook (debug_objfile))
3885 break;
3889 /* Does B have a location spec? */
3891 static bool
3892 breakpoint_location_spec_empty_p (const struct breakpoint *b)
3894 return (b->locspec != nullptr && b->locspec->empty_p ());
3897 void
3898 update_breakpoints_after_exec (void)
3900 /* We're about to delete breakpoints from GDB's lists. If the
3901 INSERTED flag is true, GDB will try to lift the breakpoints by
3902 writing the breakpoints' "shadow contents" back into memory. The
3903 "shadow contents" are NOT valid after an exec, so GDB should not
3904 do that. Instead, the target is responsible from marking
3905 breakpoints out as soon as it detects an exec. We don't do that
3906 here instead, because there may be other attempts to delete
3907 breakpoints after detecting an exec and before reaching here. */
3908 for (bp_location *bploc : all_bp_locations ())
3909 if (bploc->pspace == current_program_space)
3910 gdb_assert (!bploc->inserted);
3912 for (breakpoint &b : all_breakpoints_safe ())
3914 if (b.pspace != current_program_space)
3915 continue;
3917 /* Solib breakpoints must be explicitly reset after an exec(). */
3918 if (b.type == bp_shlib_event)
3920 delete_breakpoint (&b);
3921 continue;
3924 /* JIT breakpoints must be explicitly reset after an exec(). */
3925 if (b.type == bp_jit_event)
3927 delete_breakpoint (&b);
3928 continue;
3931 /* Thread event breakpoints must be set anew after an exec(),
3932 as must overlay event and longjmp master breakpoints. */
3933 if (b.type == bp_thread_event || b.type == bp_overlay_event
3934 || b.type == bp_longjmp_master || b.type == bp_std_terminate_master
3935 || b.type == bp_exception_master)
3937 delete_breakpoint (&b);
3938 continue;
3941 /* Step-resume breakpoints are meaningless after an exec(). */
3942 if (b.type == bp_step_resume || b.type == bp_hp_step_resume)
3944 delete_breakpoint (&b);
3945 continue;
3948 /* Just like single-step breakpoints. */
3949 if (b.type == bp_single_step)
3951 delete_breakpoint (&b);
3952 continue;
3955 /* Longjmp and longjmp-resume breakpoints are also meaningless
3956 after an exec. */
3957 if (b.type == bp_longjmp || b.type == bp_longjmp_resume
3958 || b.type == bp_longjmp_call_dummy
3959 || b.type == bp_exception || b.type == bp_exception_resume)
3961 delete_breakpoint (&b);
3962 continue;
3965 if (b.type == bp_catchpoint)
3967 /* For now, none of the bp_catchpoint breakpoints need to
3968 do anything at this point. In the future, if some of
3969 the catchpoints need to something, we will need to add
3970 a new method, and call this method from here. */
3971 continue;
3974 /* bp_finish is a special case. The only way we ought to be able
3975 to see one of these when an exec() has happened, is if the user
3976 caught a vfork, and then said "finish". Ordinarily a finish just
3977 carries them to the call-site of the current callee, by setting
3978 a temporary bp there and resuming. But in this case, the finish
3979 will carry them entirely through the vfork & exec.
3981 We don't want to allow a bp_finish to remain inserted now. But
3982 we can't safely delete it, 'cause finish_command has a handle to
3983 the bp on a bpstat, and will later want to delete it. There's a
3984 chance (and I've seen it happen) that if we delete the bp_finish
3985 here, that its storage will get reused by the time finish_command
3986 gets 'round to deleting the "use to be a bp_finish" breakpoint.
3987 We really must allow finish_command to delete a bp_finish.
3989 In the absence of a general solution for the "how do we know
3990 it's safe to delete something others may have handles to?"
3991 problem, what we'll do here is just uninsert the bp_finish, and
3992 let finish_command delete it.
3994 (We know the bp_finish is "doomed" in the sense that it's
3995 momentary, and will be deleted as soon as finish_command sees
3996 the inferior stopped. So it doesn't matter that the bp's
3997 address is probably bogus in the new a.out, unlike e.g., the
3998 solib breakpoints.) */
4000 if (b.type == bp_finish)
4002 continue;
4005 /* Without a symbolic address, we have little hope of the
4006 pre-exec() address meaning the same thing in the post-exec()
4007 a.out. */
4008 if (breakpoint_location_spec_empty_p (&b))
4010 delete_breakpoint (&b);
4011 continue;
4017 detach_breakpoints (ptid_t ptid)
4019 int val = 0;
4020 scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
4021 struct inferior *inf = current_inferior ();
4023 if (ptid.pid () == inferior_ptid.pid ())
4024 error (_("Cannot detach breakpoints of inferior_ptid"));
4026 /* Set inferior_ptid; remove_breakpoint_1 uses this global. */
4027 inferior_ptid = ptid;
4028 for (bp_location *bl : all_bp_locations ())
4030 if (bl->pspace != inf->pspace)
4031 continue;
4033 /* This function must physically remove breakpoints locations
4034 from the specified ptid, without modifying the breakpoint
4035 package's state. Locations of type bp_loc_other and
4036 bp_loc_software_watchpoint are only maintained at GDB side,
4037 so there is no need to remove them. Moreover, removing these
4038 would modify the breakpoint package's state. */
4039 if (bl->loc_type == bp_loc_other
4040 || bl->loc_type == bp_loc_software_watchpoint)
4041 continue;
4043 if (bl->inserted)
4044 val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
4047 return val;
4050 /* Remove the breakpoint location BL from the current address space.
4051 Note that this is used to detach breakpoints from a child fork.
4052 When we get here, the child isn't in the inferior list, and neither
4053 do we have objects to represent its address space --- we should
4054 *not* look at bl->pspace->aspace here. */
4056 static int
4057 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
4059 breakpoint_debug_printf ("%s due to %s",
4060 breakpoint_location_address_str (bl).c_str (),
4061 remove_bp_reason_str (reason));
4063 int val;
4065 /* BL is never in moribund_locations by our callers. */
4066 gdb_assert (bl->owner != NULL);
4068 /* The type of none suggests that owner is actually deleted.
4069 This should not ever happen. */
4070 gdb_assert (bl->owner->type != bp_none);
4072 if (bl->loc_type == bp_loc_software_breakpoint
4073 || bl->loc_type == bp_loc_hardware_breakpoint)
4075 /* "Normal" instruction breakpoint: either the standard
4076 trap-instruction bp (bp_breakpoint), or a
4077 bp_hardware_breakpoint. */
4079 /* First check to see if we have to handle an overlay. */
4080 if (overlay_debugging == ovly_off
4081 || bl->section == NULL
4082 || !(section_is_overlay (bl->section)))
4084 /* No overlay handling: just remove the breakpoint. */
4086 /* If we're trying to uninsert a memory breakpoint that we
4087 know is set in a dynamic object that is marked
4088 shlib_disabled, then either the dynamic object was
4089 removed with "remove-symbol-file" or with
4090 "nosharedlibrary". In the former case, we don't know
4091 whether another dynamic object might have loaded over the
4092 breakpoint's address -- the user might well let us know
4093 about it next with add-symbol-file (the whole point of
4094 add-symbol-file is letting the user manually maintain a
4095 list of dynamically loaded objects). If we have the
4096 breakpoint's shadow memory, that is, this is a software
4097 breakpoint managed by GDB, check whether the breakpoint
4098 is still inserted in memory, to avoid overwriting wrong
4099 code with stale saved shadow contents. Note that HW
4100 breakpoints don't have shadow memory, as they're
4101 implemented using a mechanism that is not dependent on
4102 being able to modify the target's memory, and as such
4103 they should always be removed. */
4104 if (bl->shlib_disabled
4105 && bl->target_info.shadow_len != 0
4106 && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
4107 val = 0;
4108 else
4109 val = bl->owner->remove_location (bl, reason);
4111 else
4113 /* This breakpoint is in an overlay section.
4114 Did we set a breakpoint at the LMA? */
4115 if (!overlay_events_enabled)
4117 /* Yes -- overlay event support is not active, so we
4118 should have set a breakpoint at the LMA. Remove it.
4120 /* Ignore any failures: if the LMA is in ROM, we will
4121 have already warned when we failed to insert it. */
4122 if (bl->loc_type == bp_loc_hardware_breakpoint)
4123 target_remove_hw_breakpoint (bl->gdbarch,
4124 &bl->overlay_target_info);
4125 else
4126 target_remove_breakpoint (bl->gdbarch,
4127 &bl->overlay_target_info,
4128 reason);
4130 /* Did we set a breakpoint at the VMA?
4131 If so, we will have marked the breakpoint 'inserted'. */
4132 if (bl->inserted)
4134 /* Yes -- remove it. Previously we did not bother to
4135 remove the breakpoint if the section had been
4136 unmapped, but let's not rely on that being safe. We
4137 don't know what the overlay manager might do. */
4139 /* However, we should remove *software* breakpoints only
4140 if the section is still mapped, or else we overwrite
4141 wrong code with the saved shadow contents. */
4142 if (bl->loc_type == bp_loc_hardware_breakpoint
4143 || section_is_mapped (bl->section))
4144 val = bl->owner->remove_location (bl, reason);
4145 else
4146 val = 0;
4148 else
4150 /* No -- not inserted, so no need to remove. No error. */
4151 val = 0;
4155 /* In some cases, we might not be able to remove a breakpoint in
4156 a shared library that has already been removed, but we have
4157 not yet processed the shlib unload event. Similarly for an
4158 unloaded add-symbol-file object - the user might not yet have
4159 had the chance to remove-symbol-file it. shlib_disabled will
4160 be set if the library/object has already been removed, but
4161 the breakpoint hasn't been uninserted yet, e.g., after
4162 "nosharedlibrary" or "remove-symbol-file" with breakpoints
4163 always-inserted mode. */
4164 if (val
4165 && (bl->loc_type == bp_loc_software_breakpoint
4166 && (bl->shlib_disabled
4167 || solib_name_from_address (bl->pspace, bl->address)
4168 || shared_objfile_contains_address_p (bl->pspace,
4169 bl->address))))
4170 val = 0;
4172 if (val)
4173 return val;
4174 bl->inserted = (reason == DETACH_BREAKPOINT);
4176 else if (bl->loc_type == bp_loc_hardware_watchpoint)
4178 bl->inserted = (reason == DETACH_BREAKPOINT);
4179 bl->owner->remove_location (bl, reason);
4181 /* Failure to remove any of the hardware watchpoints comes here. */
4182 if (reason == REMOVE_BREAKPOINT && bl->inserted)
4183 warning (_("Could not remove hardware watchpoint %d."),
4184 bl->owner->number);
4186 else if (bl->owner->type == bp_catchpoint
4187 && breakpoint_enabled (bl->owner)
4188 && !bl->duplicate)
4190 val = bl->owner->remove_location (bl, reason);
4191 if (val)
4192 return val;
4194 bl->inserted = (reason == DETACH_BREAKPOINT);
4197 return 0;
4200 static int
4201 remove_breakpoint (struct bp_location *bl)
4203 /* BL is never in moribund_locations by our callers. */
4204 gdb_assert (bl->owner != NULL);
4206 /* The type of none suggests that owner is actually deleted.
4207 This should not ever happen. */
4208 gdb_assert (bl->owner->type != bp_none);
4210 scoped_restore_current_pspace_and_thread restore_pspace_thread;
4212 switch_to_program_space_and_thread (bl->pspace);
4214 return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4217 /* Clear the "inserted" flag in all breakpoints. */
4219 void
4220 mark_breakpoints_out (void)
4222 for (bp_location *bl : all_bp_locations ())
4223 if (bl->pspace == current_program_space)
4224 bl->inserted = 0;
4227 /* Clear the "inserted" flag in all breakpoints and delete any
4228 breakpoints which should go away between runs of the program.
4230 Plus other such housekeeping that has to be done for breakpoints
4231 between runs.
4233 Note: this function gets called at the end of a run (by
4234 generic_mourn_inferior) and when a run begins (by
4235 init_wait_for_inferior). */
4239 void
4240 breakpoint_init_inferior (enum inf_context context)
4242 struct program_space *pspace = current_program_space;
4244 /* If breakpoint locations are shared across processes, then there's
4245 nothing to do. */
4246 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
4247 return;
4249 mark_breakpoints_out ();
4251 for (breakpoint &b : all_breakpoints_safe ())
4253 if (b.has_locations () && b.first_loc ().pspace != pspace)
4254 continue;
4256 switch (b.type)
4258 case bp_call_dummy:
4259 case bp_longjmp_call_dummy:
4261 /* If the call dummy breakpoint is at the entry point it will
4262 cause problems when the inferior is rerun, so we better get
4263 rid of it. */
4265 case bp_watchpoint_scope:
4267 /* Also get rid of scope breakpoints. */
4269 case bp_shlib_event:
4271 /* Also remove solib event breakpoints. Their addresses may
4272 have changed since the last time we ran the program.
4273 Actually we may now be debugging against different target;
4274 and so the solib backend that installed this breakpoint may
4275 not be used in by the target. E.g.,
4277 (gdb) file prog-linux
4278 (gdb) run # native linux target
4280 (gdb) kill
4281 (gdb) file prog-win.exe
4282 (gdb) tar rem :9999 # remote Windows gdbserver.
4285 case bp_step_resume:
4287 /* Also remove step-resume breakpoints. */
4289 case bp_single_step:
4291 /* Also remove single-step breakpoints. */
4293 delete_breakpoint (&b);
4294 break;
4296 case bp_watchpoint:
4297 case bp_hardware_watchpoint:
4298 case bp_read_watchpoint:
4299 case bp_access_watchpoint:
4301 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
4303 /* Likewise for watchpoints on local expressions. */
4304 if (w.exp_valid_block != NULL)
4305 delete_breakpoint (&b);
4306 else
4308 /* Get rid of existing locations, which are no longer
4309 valid. New ones will be created in
4310 update_watchpoint, when the inferior is restarted.
4311 The next update_global_location_list call will
4312 garbage collect them. */
4313 b.clear_locations ();
4315 if (context == inf_starting)
4317 /* Reset val field to force reread of starting value in
4318 insert_breakpoints. */
4319 w.val.reset (nullptr);
4320 w.val_valid = false;
4324 break;
4325 default:
4326 break;
4330 /* Get rid of the moribund locations. */
4331 for (bp_location *bl : moribund_locations)
4332 decref_bp_location (&bl);
4333 moribund_locations.clear ();
4336 /* These functions concern about actual breakpoints inserted in the
4337 target --- to e.g. check if we need to do decr_pc adjustment or if
4338 we need to hop over the bkpt --- so we check for address space
4339 match, not program space. */
4341 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4342 exists at PC. It returns ordinary_breakpoint_here if it's an
4343 ordinary breakpoint, or permanent_breakpoint_here if it's a
4344 permanent breakpoint.
4345 - When continuing from a location with an ordinary breakpoint, we
4346 actually single step once before calling insert_breakpoints.
4347 - When continuing from a location with a permanent breakpoint, we
4348 need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4349 the target, to advance the PC past the breakpoint. */
4351 enum breakpoint_here
4352 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4354 bool any_breakpoint_here = false;
4356 for (bp_location *bl : all_bp_locations ())
4358 if (bl->loc_type != bp_loc_software_breakpoint
4359 && bl->loc_type != bp_loc_hardware_breakpoint)
4360 continue;
4362 /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL. */
4363 if ((breakpoint_enabled (bl->owner)
4364 || bl->permanent)
4365 && breakpoint_location_address_match (bl, aspace, pc))
4367 if (overlay_debugging
4368 && section_is_overlay (bl->section)
4369 && !section_is_mapped (bl->section))
4370 continue; /* unmapped overlay -- can't be a match */
4371 else if (bl->permanent)
4372 return permanent_breakpoint_here;
4373 else
4374 any_breakpoint_here = true;
4378 return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4381 /* See breakpoint.h. */
4384 breakpoint_in_range_p (const address_space *aspace,
4385 CORE_ADDR addr, ULONGEST len)
4387 for (bp_location *bl : all_bp_locations ())
4389 if (bl->loc_type != bp_loc_software_breakpoint
4390 && bl->loc_type != bp_loc_hardware_breakpoint)
4391 continue;
4393 if ((breakpoint_enabled (bl->owner)
4394 || bl->permanent)
4395 && breakpoint_location_address_range_overlap (bl, aspace,
4396 addr, len))
4398 if (overlay_debugging
4399 && section_is_overlay (bl->section)
4400 && !section_is_mapped (bl->section))
4402 /* Unmapped overlay -- can't be a match. */
4403 continue;
4406 return 1;
4410 return 0;
4413 /* Return true if there's a moribund breakpoint at PC. */
4416 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4418 for (bp_location *loc : moribund_locations)
4419 if (breakpoint_location_address_match (loc, aspace, pc))
4420 return 1;
4422 return 0;
4425 /* Returns true iff BL is inserted at PC, in address space ASPACE. */
4427 static bool
4428 bp_location_inserted_here_p (const struct bp_location *bl,
4429 const address_space *aspace, CORE_ADDR pc)
4431 if (bl->inserted
4432 && breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
4433 aspace, pc))
4435 /* An unmapped overlay can't be a match. */
4436 return !(overlay_debugging
4437 && section_is_overlay (bl->section)
4438 && !section_is_mapped (bl->section));
4440 return false;
4443 /* Returns non-zero iff there's a breakpoint inserted at PC. */
4446 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4448 for (bp_location *bl : all_bp_locations_at_addr (pc))
4450 if (bl->loc_type != bp_loc_software_breakpoint
4451 && bl->loc_type != bp_loc_hardware_breakpoint)
4452 continue;
4454 if (bp_location_inserted_here_p (bl, aspace, pc))
4455 return 1;
4457 return 0;
4460 /* This function returns non-zero iff there is a software breakpoint
4461 inserted at PC. */
4464 software_breakpoint_inserted_here_p (const address_space *aspace,
4465 CORE_ADDR pc)
4467 for (bp_location *bl : all_bp_locations_at_addr (pc))
4469 if (bl->loc_type != bp_loc_software_breakpoint)
4470 continue;
4472 if (bp_location_inserted_here_p (bl, aspace, pc))
4473 return 1;
4476 return 0;
4479 /* See breakpoint.h. */
4482 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4483 CORE_ADDR pc)
4485 for (bp_location *bl : all_bp_locations_at_addr (pc))
4487 if (bl->loc_type != bp_loc_hardware_breakpoint)
4488 continue;
4490 if (bp_location_inserted_here_p (bl, aspace, pc))
4491 return 1;
4494 return 0;
4498 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4499 CORE_ADDR addr, ULONGEST len)
4501 for (breakpoint &bpt : all_breakpoints ())
4503 if (bpt.type != bp_hardware_watchpoint
4504 && bpt.type != bp_access_watchpoint)
4505 continue;
4507 if (!breakpoint_enabled (&bpt))
4508 continue;
4510 for (bp_location &loc : bpt.locations ())
4511 if (loc.pspace->aspace.get () == aspace && loc.inserted)
4513 CORE_ADDR l, h;
4515 /* Check for intersection. */
4516 l = std::max<CORE_ADDR> (loc.address, addr);
4517 h = std::min<CORE_ADDR> (loc.address + loc.length, addr + len);
4518 if (l < h)
4519 return 1;
4522 return 0;
4525 /* See breakpoint.h. */
4527 bool
4528 is_catchpoint (struct breakpoint *b)
4530 return (b->type == bp_catchpoint);
4533 /* Clear a bpstat so that it says we are not at any breakpoint.
4534 Also free any storage that is part of a bpstat. */
4536 void
4537 bpstat_clear (bpstat **bsp)
4539 bpstat *p;
4540 bpstat *q;
4542 if (bsp == 0)
4543 return;
4544 p = *bsp;
4545 while (p != NULL)
4547 q = p->next;
4548 delete p;
4549 p = q;
4551 *bsp = NULL;
4554 bpstat::bpstat (const bpstat &other)
4555 : next (NULL),
4556 bp_location_at (other.bp_location_at),
4557 breakpoint_at (other.breakpoint_at),
4558 commands (other.commands),
4559 print (other.print),
4560 stop (other.stop),
4561 print_it (other.print_it)
4563 if (other.old_val != NULL)
4564 old_val = release_value (other.old_val->copy ());
4567 /* Return a copy of a bpstat. Like "bs1 = bs2" but all storage that
4568 is part of the bpstat is copied as well. */
4570 bpstat *
4571 bpstat_copy (bpstat *bs)
4573 bpstat *p = nullptr;
4574 bpstat *tmp;
4575 bpstat *retval = nullptr;
4577 if (bs == NULL)
4578 return bs;
4580 for (; bs != NULL; bs = bs->next)
4582 tmp = new bpstat (*bs);
4584 if (p == NULL)
4585 /* This is the first thing in the chain. */
4586 retval = tmp;
4587 else
4588 p->next = tmp;
4589 p = tmp;
4591 p->next = NULL;
4592 return retval;
4595 /* Find the bpstat associated with this breakpoint. */
4597 bpstat *
4598 bpstat_find_breakpoint (bpstat *bsp, struct breakpoint *breakpoint)
4600 if (bsp == NULL)
4601 return NULL;
4603 for (; bsp != NULL; bsp = bsp->next)
4605 if (bsp->breakpoint_at == breakpoint)
4606 return bsp;
4608 return NULL;
4611 /* See breakpoint.h. */
4613 bool
4614 bpstat_explains_signal (bpstat *bsp, enum gdb_signal sig)
4616 for (; bsp != NULL; bsp = bsp->next)
4618 if (bsp->breakpoint_at == NULL)
4620 /* A moribund location can never explain a signal other than
4621 GDB_SIGNAL_TRAP. */
4622 if (sig == GDB_SIGNAL_TRAP)
4623 return true;
4625 else
4627 if (bsp->breakpoint_at->explains_signal (sig))
4628 return true;
4632 return false;
4635 /* See breakpoint.h. */
4638 bpstat_num (bpstat **bsp, int *num)
4640 struct breakpoint *b;
4642 if ((*bsp) == NULL)
4643 return 0; /* No more breakpoint values */
4645 /* We assume we'll never have several bpstats that correspond to a
4646 single breakpoint -- otherwise, this function might return the
4647 same number more than once and this will look ugly. */
4648 b = (*bsp)->breakpoint_at;
4649 *bsp = (*bsp)->next;
4650 if (b == NULL)
4651 return -1; /* breakpoint that's been deleted since */
4653 *num = b->number; /* We have its number */
4654 return 1;
4657 /* See breakpoint.h */
4660 bpstat_locno (const bpstat *bs)
4662 const struct breakpoint *b = bs->breakpoint_at;
4663 const struct bp_location *bl = bs->bp_location_at.get ();
4665 if (b != nullptr && b->has_multiple_locations ())
4667 int locno = 1;
4669 for (bp_location &loc : b->locations ())
4671 if (bl == &loc)
4672 return locno;
4674 ++locno;
4677 warning (_("location number not found for breakpoint %d address %s."),
4678 b->number, paddress (bl->gdbarch, bl->address));
4681 return 0;
4684 /* See breakpoint.h. */
4686 void
4687 print_num_locno (const bpstat *bs, struct ui_out *uiout)
4689 struct breakpoint *b = bs->breakpoint_at;
4691 if (b == nullptr)
4692 uiout->text (_("deleted breakpoint"));
4693 else
4695 uiout->field_signed ("bkptno", b->number);
4697 int locno = bpstat_locno (bs);
4698 if (locno != 0)
4699 uiout->message (".%pF", signed_field ("locno", locno));
4703 /* See breakpoint.h. */
4705 void
4706 bpstat_clear_actions (void)
4708 bpstat *bs;
4710 if (inferior_ptid == null_ptid)
4711 return;
4713 thread_info *tp = inferior_thread ();
4714 for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4716 bs->commands = NULL;
4717 bs->old_val.reset (nullptr);
4721 /* Called when a command is about to proceed the inferior. */
4723 static void
4724 breakpoint_about_to_proceed (void)
4726 if (inferior_ptid != null_ptid)
4728 struct thread_info *tp = inferior_thread ();
4730 /* Allow inferior function calls in breakpoint commands to not
4731 interrupt the command list. When the call finishes
4732 successfully, the inferior will be standing at the same
4733 breakpoint as if nothing happened. */
4734 if (tp->control.in_infcall)
4735 return;
4738 breakpoint_proceeded = 1;
4741 /* Return true iff CMD as the first line of a command sequence is `silent'
4742 or its equivalent. */
4744 static bool
4745 command_line_is_silent (struct command_line *cmd)
4747 return cmd && (strcmp ("silent", cmd->line) == 0);
4750 /* Sets the $_hit_bpnum and $_hit_locno to bpnum and locno.
4751 A locno 0 is changed to 1 to e.g. let the user do
4752 (gdb) disable $_hit_bpnum.$_hit_locno
4753 for a single location breakpoint. */
4755 static void
4756 set_hit_convenience_vars (int bpnum, int locno)
4758 set_internalvar_integer (lookup_internalvar ("_hit_bpnum"), bpnum);
4759 set_internalvar_integer (lookup_internalvar ("_hit_locno"),
4760 (locno > 0 ? locno : 1));
4763 /* Execute all the commands associated with all the breakpoints at
4764 this location. Any of these commands could cause the process to
4765 proceed beyond this point, etc. We look out for such changes by
4766 checking the global "breakpoint_proceeded" after each command.
4768 Returns true if a breakpoint command resumed the inferior. In that
4769 case, it is the caller's responsibility to recall it again with the
4770 bpstat of the current thread. */
4772 static bool
4773 bpstat_do_actions_1 (bpstat **bsp)
4775 bpstat *bs;
4776 bool again = false;
4778 /* Avoid endless recursion if a `source' command is contained
4779 in bs->commands. */
4780 if (executing_breakpoint_commands)
4781 return false;
4783 scoped_restore save_executing
4784 = make_scoped_restore (&executing_breakpoint_commands, 1);
4786 scoped_restore preventer = prevent_dont_repeat ();
4788 /* This pointer will iterate over the list of bpstat's. */
4789 bs = *bsp;
4791 /* The $_hit_* convenience variables are set before running the
4792 commands of BS. In case we have several bs, after the loop,
4793 we set again the variables to the first printed bpnum and locno.
4794 For multiple breakpoints, this ensures the variables are set to the
4795 breakpoint printed for the user. */
4796 int printed_hit_bpnum = -1;
4797 int printed_hit_locno = -1;
4799 breakpoint_proceeded = 0;
4800 for (; bs != NULL; bs = bs->next)
4802 struct command_line *cmd = NULL;
4804 /* Set the _hit_* convenience variables before running BS's commands. */
4806 const struct breakpoint *b = bs->breakpoint_at;
4807 if (b != nullptr)
4809 int locno = bpstat_locno (bs);
4811 set_hit_convenience_vars (b->number, locno);
4812 if (printed_hit_locno == -1 && bs->print)
4814 printed_hit_bpnum = b->number;
4815 printed_hit_locno = locno;
4820 /* Take ownership of the BSP's command tree, if it has one.
4822 The command tree could legitimately contain commands like
4823 'step' and 'next', which call clear_proceed_status, which
4824 frees the bpstat BS and its command tree. To make sure this doesn't
4825 free the tree we're executing out from under us, we need to
4826 take ownership of the tree ourselves. Since a given bpstat's
4827 commands are only executed once, we don't need to copy it; we
4828 can clear the pointer in the bpstat, and make sure we free
4829 the tree when we're done. */
4830 counted_command_line ccmd = bs->commands;
4831 bs->commands = NULL;
4832 if (ccmd != NULL)
4833 cmd = ccmd.get ();
4834 if (command_line_is_silent (cmd))
4836 /* The action has been already done by bpstat_stop_status. */
4837 cmd = cmd->next;
4840 while (cmd != NULL)
4842 execute_control_command (cmd);
4843 /* After execute_control_command, if breakpoint_proceeded is true,
4844 BS has been freed and cannot be accessed anymore. */
4846 if (breakpoint_proceeded)
4847 break;
4848 else
4849 cmd = cmd->next;
4852 if (breakpoint_proceeded)
4854 if (current_ui->async)
4855 /* If we are in async mode, then the target might be still
4856 running, not stopped at any breakpoint, so nothing for
4857 us to do here -- just return to the event loop. */
4859 else
4860 /* In sync mode, when execute_control_command returns
4861 we're already standing on the next breakpoint.
4862 Breakpoint commands for that stop were not run, since
4863 execute_command does not run breakpoint commands --
4864 only command_line_handler does, but that one is not
4865 involved in execution of breakpoint commands. So, we
4866 can now execute breakpoint commands. It should be
4867 noted that making execute_command do bpstat actions is
4868 not an option -- in this case we'll have recursive
4869 invocation of bpstat for each breakpoint with a
4870 command, and can easily blow up GDB stack. Instead, we
4871 return true, which will trigger the caller to recall us
4872 with the new stop_bpstat. */
4873 again = true;
4874 break;
4878 /* Now that we have executed the commands of all bs, set the _hit_*
4879 convenience variables to the printed values. */
4880 if (printed_hit_locno != -1)
4881 set_hit_convenience_vars (printed_hit_bpnum, printed_hit_locno);
4883 return again;
4886 /* Helper for bpstat_do_actions. Get the current thread, if there's
4887 one, is alive and has execution. Return NULL otherwise. */
4889 static thread_info *
4890 get_bpstat_thread ()
4892 if (inferior_ptid == null_ptid || !target_has_execution ())
4893 return NULL;
4895 thread_info *tp = inferior_thread ();
4896 if (tp->state == THREAD_EXITED || tp->executing ())
4897 return NULL;
4898 return tp;
4901 void
4902 bpstat_do_actions (void)
4904 auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4905 thread_info *tp;
4907 /* Do any commands attached to breakpoint we are stopped at. */
4908 while ((tp = get_bpstat_thread ()) != NULL)
4910 /* Since in sync mode, bpstat_do_actions may resume the
4911 inferior, and only return when it is stopped at the next
4912 breakpoint, we keep doing breakpoint actions until it returns
4913 false to indicate the inferior was not resumed. */
4914 if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4915 break;
4918 cleanup_if_error.release ();
4921 /* Print out the (old or new) value associated with a watchpoint. */
4923 static void
4924 watchpoint_value_print (struct value *val, struct ui_file *stream)
4926 if (val == NULL)
4927 fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4928 else
4930 struct value_print_options opts;
4931 get_user_print_options (&opts);
4932 value_print (val, stream, &opts);
4936 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4937 debugging multiple threads. */
4939 void
4940 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4942 if (uiout->is_mi_like_p ())
4943 return;
4945 uiout->text ("\n");
4947 if (show_thread_that_caused_stop ())
4949 struct thread_info *thr = inferior_thread ();
4951 uiout->text ("Thread ");
4952 uiout->field_string ("thread-id", print_thread_id (thr));
4954 const char *name = thread_name (thr);
4955 if (name != NULL)
4957 uiout->text (" \"");
4958 uiout->field_string ("name", name);
4959 uiout->text ("\"");
4962 uiout->text (" hit ");
4966 /* Generic routine for printing messages indicating why we
4967 stopped. The behavior of this function depends on the value
4968 'print_it' in the bpstat structure. Under some circumstances we
4969 may decide not to print anything here and delegate the task to
4970 normal_stop(). */
4972 static enum print_stop_action
4973 print_bp_stop_message (bpstat *bs)
4975 switch (bs->print_it)
4977 case print_it_noop:
4978 /* Nothing should be printed for this bpstat entry. */
4979 return PRINT_UNKNOWN;
4981 case print_it_done:
4982 /* We still want to print the frame, but we already printed the
4983 relevant messages. */
4984 return PRINT_SRC_AND_LOC;
4986 case print_it_normal:
4988 struct breakpoint *b = bs->breakpoint_at;
4990 /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4991 which has since been deleted. */
4992 if (b == NULL)
4993 return PRINT_UNKNOWN;
4995 /* Normal case. Call the breakpoint's print_it method. */
4996 return b->print_it (bs);
4999 default:
5000 internal_error (_("print_bp_stop_message: unrecognized enum value"));
5004 /* See breakpoint.h. */
5006 void
5007 print_solib_event (bool is_catchpoint)
5009 bool any_deleted = !current_program_space->deleted_solibs.empty ();
5010 bool any_added = !current_program_space->added_solibs.empty ();
5012 if (!is_catchpoint)
5014 if (any_added || any_deleted)
5015 current_uiout->text (_("Stopped due to shared library event:\n"));
5016 else
5017 current_uiout->text (_("Stopped due to shared library event (no "
5018 "libraries added or removed)\n"));
5021 if (current_uiout->is_mi_like_p ())
5022 current_uiout->field_string ("reason",
5023 async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
5025 if (any_deleted)
5027 current_uiout->text (_(" Inferior unloaded "));
5028 ui_out_emit_list list_emitter (current_uiout, "removed");
5029 for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
5031 const std::string &name = current_program_space->deleted_solibs[ix];
5033 if (ix > 0)
5034 current_uiout->text (" ");
5035 current_uiout->field_string ("library", name);
5036 current_uiout->text ("\n");
5040 if (any_added)
5042 current_uiout->text (_(" Inferior loaded "));
5043 ui_out_emit_list list_emitter (current_uiout, "added");
5044 bool first = true;
5045 for (shobj *iter : current_program_space->added_solibs)
5047 if (!first)
5048 current_uiout->text (" ");
5049 first = false;
5050 current_uiout->field_string ("library", iter->so_name);
5051 current_uiout->text ("\n");
5056 /* Print a message indicating what happened. This is called from
5057 normal_stop(). The input to this routine is the head of the bpstat
5058 list - a list of the eventpoints that caused this stop. KIND is
5059 the target_waitkind for the stopping event. This
5060 routine calls the generic print routine for printing a message
5061 about reasons for stopping. This will print (for example) the
5062 "Breakpoint n," part of the output. The return value of this
5063 routine is one of:
5065 PRINT_UNKNOWN: Means we printed nothing.
5066 PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
5067 code to print the location. An example is
5068 "Breakpoint 1, " which should be followed by
5069 the location.
5070 PRINT_SRC_ONLY: Means we printed something, but there is no need
5071 to also print the location part of the message.
5072 An example is the catch/throw messages, which
5073 don't require a location appended to the end.
5074 PRINT_NOTHING: We have done some printing and we don't need any
5075 further info to be printed. */
5077 enum print_stop_action
5078 bpstat_print (bpstat *bs, target_waitkind kind)
5080 enum print_stop_action val;
5082 /* Maybe another breakpoint in the chain caused us to stop.
5083 (Currently all watchpoints go on the bpstat whether hit or not.
5084 That probably could (should) be changed, provided care is taken
5085 with respect to bpstat_explains_signal). */
5086 for (; bs; bs = bs->next)
5088 val = print_bp_stop_message (bs);
5089 if (val == PRINT_SRC_ONLY
5090 || val == PRINT_SRC_AND_LOC
5091 || val == PRINT_NOTHING)
5092 return val;
5095 /* If we had hit a shared library event breakpoint,
5096 print_bp_stop_message would print out this message. If we hit an
5097 OS-level shared library event, do the same thing. */
5098 if (kind == TARGET_WAITKIND_LOADED)
5100 print_solib_event (false);
5101 return PRINT_NOTHING;
5104 /* We reached the end of the chain, or we got a null BS to start
5105 with and nothing was printed. */
5106 return PRINT_UNKNOWN;
5109 /* Evaluate the boolean expression EXP and return the result. */
5111 static bool
5112 breakpoint_cond_eval (expression *exp)
5114 scoped_value_mark mark;
5115 return value_true (exp->evaluate ());
5118 /* Allocate a new bpstat. Link it to the FIFO list by BS_LINK_POINTER. */
5120 bpstat::bpstat (struct bp_location *bl, bpstat ***bs_link_pointer)
5121 : next (NULL),
5122 bp_location_at (bp_location_ref_ptr::new_reference (bl)),
5123 breakpoint_at (bl->owner),
5124 commands (NULL),
5125 print (0),
5126 stop (0),
5127 print_it (print_it_normal)
5129 **bs_link_pointer = this;
5130 *bs_link_pointer = &next;
5133 bpstat::bpstat ()
5134 : next (NULL),
5135 breakpoint_at (NULL),
5136 commands (NULL),
5137 print (0),
5138 stop (0),
5139 print_it (print_it_normal)
5143 /* The target has stopped with waitstatus WS. Check if any hardware
5144 watchpoints have triggered, according to the target. */
5147 watchpoints_triggered (const target_waitstatus &ws)
5149 bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
5150 CORE_ADDR addr;
5152 if (!stopped_by_watchpoint)
5154 /* We were not stopped by a watchpoint. Mark all watchpoints
5155 as not triggered. */
5156 for (breakpoint &b : all_breakpoints ())
5157 if (is_hardware_watchpoint (&b))
5159 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5161 w.watchpoint_triggered = watch_triggered_no;
5164 return 0;
5167 if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
5169 /* We were stopped by a watchpoint, but we don't know where.
5170 Mark all watchpoints as unknown. */
5171 for (breakpoint &b : all_breakpoints ())
5172 if (is_hardware_watchpoint (&b))
5174 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5176 w.watchpoint_triggered = watch_triggered_unknown;
5179 return 1;
5182 /* The target could report the data address. Mark watchpoints
5183 affected by this data address as triggered, and all others as not
5184 triggered. */
5186 for (breakpoint &b : all_breakpoints ())
5187 if (is_hardware_watchpoint (&b))
5189 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5191 w.watchpoint_triggered = watch_triggered_no;
5192 for (bp_location &loc : b.locations ())
5194 if (is_masked_watchpoint (&b))
5196 CORE_ADDR newaddr = addr & w.hw_wp_mask;
5197 CORE_ADDR start = loc.address & w.hw_wp_mask;
5199 if (newaddr == start)
5201 w.watchpoint_triggered = watch_triggered_yes;
5202 break;
5205 /* Exact match not required. Within range is sufficient. */
5206 else if (target_watchpoint_addr_within_range
5207 (current_inferior ()->top_target (), addr, loc.address,
5208 loc.length))
5210 w.watchpoint_triggered = watch_triggered_yes;
5211 break;
5216 return 1;
5219 /* Possible return values for watchpoint_check. */
5220 enum wp_check_result
5222 /* The watchpoint has been deleted. */
5223 WP_DELETED = 1,
5225 /* The value has changed. */
5226 WP_VALUE_CHANGED = 2,
5228 /* The value has not changed. */
5229 WP_VALUE_NOT_CHANGED = 3,
5231 /* Ignore this watchpoint, no matter if the value changed or not. */
5232 WP_IGNORE = 4,
5235 #define BP_TEMPFLAG 1
5236 #define BP_HARDWAREFLAG 2
5238 /* Evaluate watchpoint condition expression and check if its value
5239 changed. */
5241 static wp_check_result
5242 watchpoint_check (bpstat *bs)
5244 frame_info_ptr fr;
5245 bool within_current_scope;
5247 /* BS is built from an existing struct breakpoint. */
5248 gdb_assert (bs->breakpoint_at != NULL);
5249 watchpoint *b = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5251 /* If this is a local watchpoint, we only want to check if the
5252 watchpoint frame is in scope if the current thread is the thread
5253 that was used to create the watchpoint. */
5254 if (!watchpoint_in_thread_scope (b))
5255 return WP_IGNORE;
5257 if (b->exp_valid_block == NULL)
5258 within_current_scope = true;
5259 else
5261 frame_info_ptr frame = get_current_frame ();
5262 struct gdbarch *frame_arch = get_frame_arch (frame);
5263 CORE_ADDR frame_pc = get_frame_pc (frame);
5265 /* stack_frame_destroyed_p() returns a non-zero value if we're
5266 still in the function but the stack frame has already been
5267 invalidated. Since we can't rely on the values of local
5268 variables after the stack has been destroyed, we are treating
5269 the watchpoint in that state as `not changed' without further
5270 checking. Don't mark watchpoints as changed if the current
5271 frame is in an epilogue - even if they are in some other
5272 frame, our view of the stack is likely to be wrong and
5273 frame_find_by_id could error out. */
5274 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5275 return WP_IGNORE;
5277 fr = frame_find_by_id (b->watchpoint_frame);
5278 within_current_scope = (fr != NULL);
5280 /* If we've gotten confused in the unwinder, we might have
5281 returned a frame that can't describe this variable. */
5282 if (within_current_scope)
5284 struct symbol *function;
5286 function = get_frame_function (fr);
5287 if (function == NULL
5288 || !function->value_block ()->contains (b->exp_valid_block))
5289 within_current_scope = false;
5292 if (within_current_scope)
5293 /* If we end up stopping, the current frame will get selected
5294 in normal_stop. So this call to select_frame won't affect
5295 the user. */
5296 select_frame (fr);
5299 if (within_current_scope)
5301 /* We use value_{,free_to_}mark because it could be a *long*
5302 time before we return to the command level and call
5303 free_all_values. We can't call free_all_values because we
5304 might be in the middle of evaluating a function call. */
5306 struct value *mark;
5307 struct value *new_val;
5309 if (is_masked_watchpoint (b))
5310 /* Since we don't know the exact trigger address (from
5311 stopped_data_address), just tell the user we've triggered
5312 a mask watchpoint. */
5313 return WP_VALUE_CHANGED;
5315 mark = value_mark ();
5316 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
5317 NULL, NULL, false);
5319 if (b->val_bitsize != 0)
5320 new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5322 /* We use value_equal_contents instead of value_equal because
5323 the latter coerces an array to a pointer, thus comparing just
5324 the address of the array instead of its contents. This is
5325 not what we want. */
5326 if ((b->val != NULL) != (new_val != NULL)
5327 || (b->val != NULL && !value_equal_contents (b->val.get (),
5328 new_val)))
5330 bs->old_val = b->val;
5331 b->val = release_value (new_val);
5332 b->val_valid = true;
5333 if (new_val != NULL)
5334 value_free_to_mark (mark);
5335 return WP_VALUE_CHANGED;
5337 else
5339 /* Nothing changed. */
5340 value_free_to_mark (mark);
5341 return WP_VALUE_NOT_CHANGED;
5344 else
5346 /* This seems like the only logical thing to do because
5347 if we temporarily ignored the watchpoint, then when
5348 we reenter the block in which it is valid it contains
5349 garbage (in the case of a function, it may have two
5350 garbage values, one before and one after the prologue).
5351 So we can't even detect the first assignment to it and
5352 watch after that (since the garbage may or may not equal
5353 the first value assigned). */
5354 /* We print all the stop information in
5355 breakpointprint_it, but in this case, by the time we
5356 call breakpoint->print_it this bp will be deleted
5357 already. So we have no choice but print the information
5358 here. */
5360 SWITCH_THRU_ALL_UIS ()
5362 struct ui_out *uiout = current_uiout;
5364 if (uiout->is_mi_like_p ())
5365 uiout->field_string
5366 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5367 uiout->message ("\nWatchpoint %pF deleted because the program has "
5368 "left the block in\n"
5369 "which its expression is valid.\n",
5370 signed_field ("wpnum", b->number));
5373 /* Make sure the watchpoint's commands aren't executed. */
5374 b->commands = NULL;
5375 watchpoint_del_at_next_stop (b);
5377 return WP_DELETED;
5381 /* Return true if it looks like target has stopped due to hitting
5382 breakpoint location BL. This function does not check if we should
5383 stop, only if BL explains the stop. */
5385 static bool
5386 bpstat_check_location (const struct bp_location *bl,
5387 const address_space *aspace, CORE_ADDR bp_addr,
5388 const target_waitstatus &ws)
5390 struct breakpoint *b = bl->owner;
5392 /* BL is from an existing breakpoint. */
5393 gdb_assert (b != NULL);
5395 return b->breakpoint_hit (bl, aspace, bp_addr, ws);
5398 /* Determine if the watched values have actually changed, and we
5399 should stop. If not, set BS->stop to false. */
5401 static void
5402 bpstat_check_watchpoint (bpstat *bs)
5404 const struct bp_location *bl;
5406 /* BS is built for existing struct breakpoint. */
5407 bl = bs->bp_location_at.get ();
5408 gdb_assert (bl != NULL);
5409 watchpoint *b = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5411 bool must_check_value = false;
5413 if (b->type == bp_watchpoint)
5414 /* For a software watchpoint, we must always check the
5415 watched value. */
5416 must_check_value = true;
5417 else if (b->watchpoint_triggered == watch_triggered_yes)
5418 /* We have a hardware watchpoint (read, write, or access)
5419 and the target earlier reported an address watched by
5420 this watchpoint. */
5421 must_check_value = true;
5422 else if (b->watchpoint_triggered == watch_triggered_unknown
5423 && b->type == bp_hardware_watchpoint)
5424 /* We were stopped by a hardware watchpoint, but the target could
5425 not report the data address. We must check the watchpoint's
5426 value. Access and read watchpoints are out of luck; without
5427 a data address, we can't figure it out. */
5428 must_check_value = true;
5430 if (must_check_value)
5432 wp_check_result e;
5436 e = watchpoint_check (bs);
5438 catch (const gdb_exception_error &ex)
5440 exception_fprintf (gdb_stderr, ex,
5441 "Error evaluating expression "
5442 "for watchpoint %d\n",
5443 b->number);
5445 SWITCH_THRU_ALL_UIS ()
5447 gdb_printf (_("Watchpoint %d deleted.\n"),
5448 b->number);
5450 watchpoint_del_at_next_stop (b);
5451 e = WP_DELETED;
5454 switch (e)
5456 case WP_DELETED:
5457 /* We've already printed what needs to be printed. */
5458 bs->print_it = print_it_done;
5459 /* Stop. */
5460 break;
5461 case WP_IGNORE:
5462 bs->print_it = print_it_noop;
5463 bs->stop = false;
5464 break;
5465 case WP_VALUE_CHANGED:
5466 if (b->type == bp_read_watchpoint)
5468 /* There are two cases to consider here:
5470 1. We're watching the triggered memory for reads.
5471 In that case, trust the target, and always report
5472 the watchpoint hit to the user. Even though
5473 reads don't cause value changes, the value may
5474 have changed since the last time it was read, and
5475 since we're not trapping writes, we will not see
5476 those, and as such we should ignore our notion of
5477 old value.
5479 2. We're watching the triggered memory for both
5480 reads and writes. There are two ways this may
5481 happen:
5483 2.1. This is a target that can't break on data
5484 reads only, but can break on accesses (reads or
5485 writes), such as e.g., x86. We detect this case
5486 at the time we try to insert read watchpoints.
5488 2.2. Otherwise, the target supports read
5489 watchpoints, but, the user set an access or write
5490 watchpoint watching the same memory as this read
5491 watchpoint.
5493 If we're watching memory writes as well as reads,
5494 ignore watchpoint hits when we find that the
5495 value hasn't changed, as reads don't cause
5496 changes. This still gives false positives when
5497 the program writes the same value to memory as
5498 what there was already in memory (we will confuse
5499 it for a read), but it's much better than
5500 nothing. */
5502 int other_write_watchpoint = 0;
5504 if (bl->watchpoint_type == hw_read)
5506 for (breakpoint &other_b : all_breakpoints ())
5507 if (other_b.type == bp_hardware_watchpoint
5508 || other_b.type == bp_access_watchpoint)
5510 watchpoint &other_w =
5511 gdb::checked_static_cast<watchpoint &> (other_b);
5513 if (other_w.watchpoint_triggered
5514 == watch_triggered_yes)
5516 other_write_watchpoint = 1;
5517 break;
5522 if (other_write_watchpoint
5523 || bl->watchpoint_type == hw_access)
5525 /* We're watching the same memory for writes,
5526 and the value changed since the last time we
5527 updated it, so this trap must be for a write.
5528 Ignore it. */
5529 bs->print_it = print_it_noop;
5530 bs->stop = false;
5533 break;
5534 case WP_VALUE_NOT_CHANGED:
5535 if (b->type == bp_hardware_watchpoint
5536 || b->type == bp_watchpoint)
5538 /* Don't stop: write watchpoints shouldn't fire if
5539 the value hasn't changed. */
5540 bs->print_it = print_it_noop;
5541 bs->stop = false;
5543 /* Stop. */
5544 break;
5545 default:
5546 /* Can't happen. */
5547 break;
5550 else /* !must_check_value */
5552 /* This is a case where some watchpoint(s) triggered, but
5553 not at the address of this watchpoint, or else no
5554 watchpoint triggered after all. So don't print
5555 anything for this watchpoint. */
5556 bs->print_it = print_it_noop;
5557 bs->stop = false;
5561 /* For breakpoints that are currently marked as telling gdb to stop,
5562 check conditions (condition proper, frame, thread and ignore count)
5563 of breakpoint referred to by BS. If we should not stop for this
5564 breakpoint, set BS->stop to 0. */
5566 static void
5567 bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
5569 INFRUN_SCOPED_DEBUG_ENTER_EXIT;
5571 const struct bp_location *bl;
5572 struct breakpoint *b;
5573 /* Assume stop. */
5574 bool condition_result = true;
5575 struct expression *cond;
5577 gdb_assert (bs->stop);
5579 /* BS is built for existing struct breakpoint. */
5580 bl = bs->bp_location_at.get ();
5581 gdb_assert (bl != NULL);
5582 b = bs->breakpoint_at;
5583 gdb_assert (b != NULL);
5585 infrun_debug_printf ("thread = %s, breakpoint %d.%d",
5586 thread->ptid.to_string ().c_str (),
5587 b->number, find_loc_num_by_location (bl));
5589 /* Even if the target evaluated the condition on its end and notified GDB, we
5590 need to do so again since GDB does not know if we stopped due to a
5591 breakpoint or a single step breakpoint. */
5593 if (frame_id_p (b->frame_id)
5594 && b->frame_id != get_stack_frame_id (get_current_frame ()))
5596 infrun_debug_printf ("incorrect frame %s not %s, not stopping",
5597 get_stack_frame_id (get_current_frame ()).to_string ().c_str (),
5598 b->frame_id.to_string ().c_str ());
5599 bs->stop = false;
5600 return;
5603 /* If this is a thread/task-specific breakpoint, don't waste cpu
5604 evaluating the condition if this isn't the specified
5605 thread/task. */
5606 if ((b->thread != -1 && b->thread != thread->global_num)
5607 || (b->inferior != -1 && b->inferior != thread->inf->num)
5608 || (b->task != -1 && b->task != ada_get_task_number (thread)))
5610 infrun_debug_printf ("incorrect thread or task, not stopping");
5611 bs->stop = false;
5612 return;
5615 /* Evaluate extension language breakpoints that have a "stop" method
5616 implemented. */
5617 bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5619 if (is_watchpoint (b))
5621 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
5623 cond = w->cond_exp.get ();
5625 else
5626 cond = bl->cond.get ();
5628 if (cond != nullptr && b->disposition != disp_del_at_next_stop)
5630 bool within_current_scope = true;
5632 /* We use scoped_value_mark because it could be a long time
5633 before we return to the command level and call
5634 free_all_values. We can't call free_all_values because we
5635 might be in the middle of evaluating a function call. */
5636 scoped_value_mark mark;
5638 watchpoint *w = nullptr;
5639 if (is_watchpoint (b))
5640 w = gdb::checked_static_cast<watchpoint *> (b);
5642 /* Need to select the frame, with all that implies so that
5643 the conditions will have the right context. Because we
5644 use the frame, we will not see an inlined function's
5645 variables when we arrive at a breakpoint at the start
5646 of the inlined function; the current frame will be the
5647 call site. */
5648 if (w == NULL || w->cond_exp_valid_block == NULL)
5649 select_frame (get_current_frame ());
5650 else
5652 frame_info_ptr frame;
5654 /* For local watchpoint expressions, which particular
5655 instance of a local is being watched matters, so we
5656 keep track of the frame to evaluate the expression
5657 in. To evaluate the condition however, it doesn't
5658 really matter which instantiation of the function
5659 where the condition makes sense triggers the
5660 watchpoint. This allows an expression like "watch
5661 global if q > 10" set in `func', catch writes to
5662 global on all threads that call `func', or catch
5663 writes on all recursive calls of `func' by a single
5664 thread. We simply always evaluate the condition in
5665 the innermost frame that's executing where it makes
5666 sense to evaluate the condition. It seems
5667 intuitive. */
5668 frame = block_innermost_frame (w->cond_exp_valid_block);
5669 if (frame != NULL)
5670 select_frame (frame);
5671 else
5672 within_current_scope = false;
5674 if (within_current_scope)
5678 condition_result = breakpoint_cond_eval (cond);
5680 catch (const gdb_exception_error &ex)
5682 int locno = bpstat_locno (bs);
5683 if (locno != 0)
5684 exception_fprintf
5685 (gdb_stderr, ex,
5686 "Error in testing condition for breakpoint %d.%d:\n",
5687 b->number, locno);
5688 else
5689 exception_fprintf
5690 (gdb_stderr, ex,
5691 "Error in testing condition for breakpoint %d:\n",
5692 b->number);
5695 else
5697 warning (_("Watchpoint condition cannot be tested "
5698 "in the current scope"));
5699 /* If we failed to set the right context for this
5700 watchpoint, unconditionally report it. */
5702 /* FIXME-someday, should give breakpoint #. */
5705 if (cond != nullptr && !condition_result)
5707 infrun_debug_printf ("condition_result = false, not stopping");
5708 bs->stop = false;
5709 return;
5711 else if (b->ignore_count > 0)
5713 infrun_debug_printf ("ignore count %d, not stopping",
5714 b->ignore_count);
5715 b->ignore_count--;
5716 bs->stop = false;
5717 /* Increase the hit count even though we don't stop. */
5718 ++(b->hit_count);
5719 notify_breakpoint_modified (b);
5720 return;
5723 if (bs->stop)
5724 infrun_debug_printf ("stopping at this breakpoint");
5725 else
5726 infrun_debug_printf ("not stopping at this breakpoint");
5729 /* Returns true if we need to track moribund locations of LOC's type
5730 on the current target. */
5732 static bool
5733 need_moribund_for_location_type (const struct bp_location *loc)
5735 return ((loc->loc_type == bp_loc_software_breakpoint
5736 && !target_supports_stopped_by_sw_breakpoint ())
5737 || (loc->loc_type == bp_loc_hardware_breakpoint
5738 && !target_supports_stopped_by_hw_breakpoint ()));
5741 /* See breakpoint.h. */
5743 bpstat *
5744 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5745 const target_waitstatus &ws)
5747 bpstat *bs_head = nullptr, **bs_link = &bs_head;
5749 for (breakpoint &b : all_breakpoints ())
5751 if (!breakpoint_enabled (&b))
5752 continue;
5754 for (bp_location &bl : b.locations ())
5756 /* For hardware watchpoints, we look only at the first
5757 location. The watchpoint_check function will work on the
5758 entire expression, not the individual locations. For
5759 read watchpoints, the watchpoints_triggered function has
5760 checked all locations already. */
5761 if (b.type == bp_hardware_watchpoint && &bl != &b.first_loc ())
5762 break;
5764 if (!bl.enabled || bl.disabled_by_cond || bl.shlib_disabled)
5765 continue;
5767 if (!bpstat_check_location (&bl, aspace, bp_addr, ws))
5768 continue;
5770 /* Come here if it's a watchpoint, or if the break address
5771 matches. */
5773 bpstat *bs = new bpstat (&bl, &bs_link); /* Alloc a bpstat to
5774 explain stop. */
5776 /* Assume we stop. Should we find a watchpoint that is not
5777 actually triggered, or if the condition of the breakpoint
5778 evaluates as false, we'll reset 'stop' to 0. */
5779 bs->stop = true;
5780 bs->print = true;
5782 /* If this is a scope breakpoint, mark the associated
5783 watchpoint as triggered so that we will handle the
5784 out-of-scope event. We'll get to the watchpoint next
5785 iteration. */
5786 if (b.type == bp_watchpoint_scope && b.related_breakpoint != &b)
5788 watchpoint *w
5789 = gdb::checked_static_cast<watchpoint *> (b.related_breakpoint);
5791 w->watchpoint_triggered = watch_triggered_yes;
5796 /* Check if a moribund breakpoint explains the stop. */
5797 if (!target_supports_stopped_by_sw_breakpoint ()
5798 || !target_supports_stopped_by_hw_breakpoint ())
5800 for (bp_location *loc : moribund_locations)
5802 if (breakpoint_location_address_match (loc, aspace, bp_addr)
5803 && need_moribund_for_location_type (loc))
5805 bpstat *bs = new bpstat (loc, &bs_link);
5806 /* For hits of moribund locations, we should just proceed. */
5807 bs->stop = false;
5808 bs->print = false;
5809 bs->print_it = print_it_noop;
5814 return bs_head;
5817 /* See breakpoint.h. */
5819 bpstat *
5820 bpstat_stop_status (const address_space *aspace,
5821 CORE_ADDR bp_addr, thread_info *thread,
5822 const target_waitstatus &ws,
5823 bpstat *stop_chain)
5825 struct breakpoint *b = NULL;
5826 /* First item of allocated bpstat's. */
5827 bpstat *bs_head = stop_chain;
5828 bpstat *bs;
5829 int need_remove_insert;
5830 int removed_any;
5832 /* First, build the bpstat chain with locations that explain a
5833 target stop, while being careful to not set the target running,
5834 as that may invalidate locations (in particular watchpoint
5835 locations are recreated). Resuming will happen here with
5836 breakpoint conditions or watchpoint expressions that include
5837 inferior function calls. */
5838 if (bs_head == NULL)
5839 bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5841 /* A bit of special processing for shlib breakpoints. We need to
5842 process solib loading here, so that the lists of loaded and
5843 unloaded libraries are correct before we handle "catch load" and
5844 "catch unload". */
5845 for (bs = bs_head; bs != NULL; bs = bs->next)
5847 if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5849 handle_solib_event ();
5850 break;
5854 /* Now go through the locations that caused the target to stop, and
5855 check whether we're interested in reporting this stop to higher
5856 layers, or whether we should resume the target transparently. */
5858 removed_any = 0;
5860 for (bs = bs_head; bs != NULL; bs = bs->next)
5862 if (!bs->stop)
5863 continue;
5865 b = bs->breakpoint_at;
5866 b->check_status (bs);
5867 if (bs->stop)
5869 bpstat_check_breakpoint_conditions (bs, thread);
5871 if (bs->stop)
5873 ++(b->hit_count);
5875 /* We will stop here. */
5876 if (b->disposition == disp_disable)
5878 --(b->enable_count);
5879 if (b->enable_count <= 0)
5880 b->enable_state = bp_disabled;
5881 removed_any = 1;
5883 notify_breakpoint_modified (b);
5884 if (b->silent)
5885 bs->print = false;
5886 bs->commands = b->commands;
5887 if (command_line_is_silent (bs->commands
5888 ? bs->commands.get () : NULL))
5889 bs->print = false;
5891 b->after_condition_true (bs);
5896 /* Print nothing for this entry if we don't stop or don't
5897 print. */
5898 if (!bs->stop || !bs->print)
5899 bs->print_it = print_it_noop;
5902 /* If we aren't stopping, the value of some hardware watchpoint may
5903 not have changed, but the intermediate memory locations we are
5904 watching may have. Don't bother if we're stopping; this will get
5905 done later. */
5906 need_remove_insert = 0;
5907 if (! bpstat_causes_stop (bs_head))
5908 for (bs = bs_head; bs != NULL; bs = bs->next)
5909 if (!bs->stop
5910 && bs->breakpoint_at
5911 && is_hardware_watchpoint (bs->breakpoint_at))
5913 watchpoint *w
5914 = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5916 update_watchpoint (w, false /* don't reparse. */);
5917 need_remove_insert = 1;
5920 if (need_remove_insert)
5921 update_global_location_list (UGLL_MAY_INSERT);
5922 else if (removed_any)
5923 update_global_location_list (UGLL_DONT_INSERT);
5925 return bs_head;
5928 /* See breakpoint.h. */
5930 bpstat *
5931 bpstat_stop_status_nowatch (const address_space *aspace, CORE_ADDR bp_addr,
5932 thread_info *thread, const target_waitstatus &ws)
5934 gdb_assert (!target_stopped_by_watchpoint ());
5936 /* Clear all watchpoints' 'watchpoint_triggered' value from a
5937 previous stop to avoid confusing bpstat_stop_status. */
5938 watchpoints_triggered (ws);
5940 return bpstat_stop_status (aspace, bp_addr, thread, ws);
5943 static void
5944 handle_jit_event (CORE_ADDR address)
5946 struct gdbarch *gdbarch;
5948 infrun_debug_printf ("handling bp_jit_event");
5950 /* Switch terminal for any messages produced by
5951 breakpoint_re_set. */
5952 target_terminal::ours_for_output ();
5954 gdbarch = get_frame_arch (get_current_frame ());
5955 /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5956 thus it is expected that its objectfile can be found through
5957 minimal symbol lookup. If it doesn't work (and assert fails), it
5958 most likely means that `jit_breakpoint_re_set` was changes and this
5959 function needs to be updated too. */
5960 bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5961 gdb_assert (jit_bp_sym.objfile != nullptr);
5962 objfile *objfile = jit_bp_sym.objfile;
5963 if (objfile->separate_debug_objfile_backlink)
5964 objfile = objfile->separate_debug_objfile_backlink;
5965 jit_event_handler (gdbarch, objfile);
5967 target_terminal::inferior ();
5970 /* Prepare WHAT final decision for infrun. */
5972 /* Decide what infrun needs to do with this bpstat. */
5974 struct bpstat_what
5975 bpstat_what (bpstat *bs_head)
5977 struct bpstat_what retval;
5978 bpstat *bs;
5980 retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5981 retval.call_dummy = STOP_NONE;
5982 retval.is_longjmp = false;
5984 for (bs = bs_head; bs != NULL; bs = bs->next)
5986 /* Extract this BS's action. After processing each BS, we check
5987 if its action overrides all we've seem so far. */
5988 enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5989 enum bptype bptype;
5991 if (bs->breakpoint_at == NULL)
5993 /* I suspect this can happen if it was a momentary
5994 breakpoint which has since been deleted. */
5995 bptype = bp_none;
5997 else
5998 bptype = bs->breakpoint_at->type;
6000 switch (bptype)
6002 case bp_none:
6003 break;
6004 case bp_breakpoint:
6005 case bp_hardware_breakpoint:
6006 case bp_single_step:
6007 case bp_until:
6008 case bp_finish:
6009 case bp_shlib_event:
6010 if (bs->stop)
6012 if (bs->print)
6013 this_action = BPSTAT_WHAT_STOP_NOISY;
6014 else
6015 this_action = BPSTAT_WHAT_STOP_SILENT;
6017 else
6018 this_action = BPSTAT_WHAT_SINGLE;
6019 break;
6020 case bp_watchpoint:
6021 case bp_hardware_watchpoint:
6022 case bp_read_watchpoint:
6023 case bp_access_watchpoint:
6024 if (bs->stop)
6026 if (bs->print)
6027 this_action = BPSTAT_WHAT_STOP_NOISY;
6028 else
6029 this_action = BPSTAT_WHAT_STOP_SILENT;
6031 else
6033 /* There was a watchpoint, but we're not stopping.
6034 This requires no further action. */
6036 break;
6037 case bp_longjmp:
6038 case bp_longjmp_call_dummy:
6039 case bp_exception:
6040 if (bs->stop)
6042 this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
6043 retval.is_longjmp = bptype != bp_exception;
6045 else
6046 this_action = BPSTAT_WHAT_SINGLE;
6047 break;
6048 case bp_longjmp_resume:
6049 case bp_exception_resume:
6050 if (bs->stop)
6052 this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
6053 retval.is_longjmp = bptype == bp_longjmp_resume;
6055 else
6056 this_action = BPSTAT_WHAT_SINGLE;
6057 break;
6058 case bp_step_resume:
6059 if (bs->stop)
6060 this_action = BPSTAT_WHAT_STEP_RESUME;
6061 else
6063 /* It is for the wrong frame. */
6064 this_action = BPSTAT_WHAT_SINGLE;
6066 break;
6067 case bp_hp_step_resume:
6068 if (bs->stop)
6069 this_action = BPSTAT_WHAT_HP_STEP_RESUME;
6070 else
6072 /* It is for the wrong frame. */
6073 this_action = BPSTAT_WHAT_SINGLE;
6075 break;
6076 case bp_watchpoint_scope:
6077 case bp_thread_event:
6078 case bp_overlay_event:
6079 case bp_longjmp_master:
6080 case bp_std_terminate_master:
6081 case bp_exception_master:
6082 this_action = BPSTAT_WHAT_SINGLE;
6083 break;
6084 case bp_catchpoint:
6085 if (bs->stop)
6087 if (bs->print)
6088 this_action = BPSTAT_WHAT_STOP_NOISY;
6089 else
6090 this_action = BPSTAT_WHAT_STOP_SILENT;
6092 else
6094 /* Some catchpoints are implemented with breakpoints.
6095 For those, we need to step over the breakpoint. */
6096 if (bs->bp_location_at->loc_type == bp_loc_software_breakpoint
6097 || bs->bp_location_at->loc_type == bp_loc_hardware_breakpoint)
6098 this_action = BPSTAT_WHAT_SINGLE;
6100 break;
6101 case bp_jit_event:
6102 this_action = BPSTAT_WHAT_SINGLE;
6103 break;
6104 case bp_call_dummy:
6105 /* Make sure the action is stop (silent or noisy),
6106 so infrun.c pops the dummy frame. */
6107 retval.call_dummy = STOP_STACK_DUMMY;
6108 this_action = BPSTAT_WHAT_STOP_SILENT;
6109 break;
6110 case bp_std_terminate:
6111 /* Make sure the action is stop (silent or noisy),
6112 so infrun.c pops the dummy frame. */
6113 retval.call_dummy = STOP_STD_TERMINATE;
6114 this_action = BPSTAT_WHAT_STOP_SILENT;
6115 break;
6116 case bp_tracepoint:
6117 case bp_fast_tracepoint:
6118 case bp_static_tracepoint:
6119 case bp_static_marker_tracepoint:
6120 /* Tracepoint hits should not be reported back to GDB, and
6121 if one got through somehow, it should have been filtered
6122 out already. */
6123 internal_error (_("bpstat_what: tracepoint encountered"));
6124 break;
6125 case bp_gnu_ifunc_resolver:
6126 /* Step over it (and insert bp_gnu_ifunc_resolver_return). */
6127 this_action = BPSTAT_WHAT_SINGLE;
6128 break;
6129 case bp_gnu_ifunc_resolver_return:
6130 /* The breakpoint will be removed, execution will restart from the
6131 PC of the former breakpoint. */
6132 this_action = BPSTAT_WHAT_KEEP_CHECKING;
6133 break;
6135 case bp_dprintf:
6136 if (bs->stop)
6137 this_action = BPSTAT_WHAT_STOP_SILENT;
6138 else
6139 this_action = BPSTAT_WHAT_SINGLE;
6140 break;
6142 default:
6143 internal_error (_("bpstat_what: unhandled bptype %d"), (int) bptype);
6146 retval.main_action = std::max (retval.main_action, this_action);
6149 return retval;
6152 void
6153 bpstat_run_callbacks (bpstat *bs_head)
6155 bpstat *bs;
6157 for (bs = bs_head; bs != NULL; bs = bs->next)
6159 struct breakpoint *b = bs->breakpoint_at;
6161 if (b == NULL)
6162 continue;
6163 switch (b->type)
6165 case bp_jit_event:
6166 handle_jit_event (bs->bp_location_at->address);
6167 break;
6168 case bp_gnu_ifunc_resolver:
6169 gnu_ifunc_resolver_stop
6170 (gdb::checked_static_cast<code_breakpoint *> (b));
6171 break;
6172 case bp_gnu_ifunc_resolver_return:
6173 gnu_ifunc_resolver_return_stop
6174 (gdb::checked_static_cast<code_breakpoint *> (b));
6175 break;
6180 /* See breakpoint.h. */
6182 bool
6183 bpstat_should_step ()
6185 for (breakpoint &b : all_breakpoints ())
6186 if (breakpoint_enabled (&b)
6187 && b.type == bp_watchpoint
6188 && b.has_locations ())
6189 return true;
6191 return false;
6194 /* See breakpoint.h. */
6196 bool
6197 bpstat_causes_stop (bpstat *bs)
6199 for (; bs != NULL; bs = bs->next)
6200 if (bs->stop)
6201 return true;
6203 return false;
6208 /* Compute a number of spaces suitable to indent the next line
6209 so it starts at the position corresponding to the table column
6210 named COL_NAME in the currently active table of UIOUT. */
6212 static int
6213 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6215 int i, total_width, width, align;
6216 const char *text;
6218 total_width = 0;
6219 for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
6221 if (strcmp (text, col_name) == 0)
6222 return total_width;
6224 total_width += width + 1;
6227 return 0;
6230 /* Determine if the locations of this breakpoint will have their conditions
6231 evaluated by the target, host or a mix of both. Returns the following:
6233 "host": Host evals condition.
6234 "host or target": Host or Target evals condition.
6235 "target": Target evals condition.
6238 static const char *
6239 bp_condition_evaluator (const breakpoint *b)
6241 char host_evals = 0;
6242 char target_evals = 0;
6244 if (!b)
6245 return NULL;
6247 if (!is_breakpoint (b))
6248 return NULL;
6250 if (gdb_evaluates_breakpoint_condition_p ()
6251 || !target_supports_evaluation_of_breakpoint_conditions ())
6252 return condition_evaluation_host;
6254 for (bp_location &bl : b->locations ())
6256 if (bl.cond_bytecode)
6257 target_evals++;
6258 else
6259 host_evals++;
6262 if (host_evals && target_evals)
6263 return condition_evaluation_both;
6264 else if (target_evals)
6265 return condition_evaluation_target;
6266 else
6267 return condition_evaluation_host;
6270 /* Determine the breakpoint location's condition evaluator. This is
6271 similar to bp_condition_evaluator, but for locations. */
6273 static const char *
6274 bp_location_condition_evaluator (const struct bp_location *bl)
6276 if (bl && !is_breakpoint (bl->owner))
6277 return NULL;
6279 if (gdb_evaluates_breakpoint_condition_p ()
6280 || !target_supports_evaluation_of_breakpoint_conditions ())
6281 return condition_evaluation_host;
6283 if (bl && bl->cond_bytecode)
6284 return condition_evaluation_target;
6285 else
6286 return condition_evaluation_host;
6289 /* Print the LOC location out of the list of B->LOC locations. */
6291 static void
6292 print_breakpoint_location (const breakpoint *b, const bp_location *loc)
6294 struct ui_out *uiout = current_uiout;
6296 scoped_restore_current_program_space restore_pspace;
6298 if (loc != NULL && loc->shlib_disabled)
6299 loc = NULL;
6301 if (loc != NULL)
6302 set_current_program_space (loc->pspace);
6304 if (b->display_canonical)
6305 uiout->field_string ("what", b->locspec->to_string ());
6306 else if (loc && loc->symtab)
6308 const struct symbol *sym = loc->symbol;
6310 if (sym)
6312 uiout->text ("in ");
6313 uiout->field_string ("func", sym->print_name (),
6314 function_name_style.style ());
6315 uiout->text (" ");
6316 uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6317 uiout->text ("at ");
6319 uiout->field_string ("file",
6320 symtab_to_filename_for_display (loc->symtab),
6321 file_name_style.style ());
6322 uiout->text (":");
6324 if (uiout->is_mi_like_p ())
6325 uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6327 uiout->field_signed ("line", loc->line_number);
6329 else if (loc)
6331 string_file stb;
6333 print_address_symbolic (loc->gdbarch, loc->address, &stb,
6334 demangle, "");
6335 uiout->field_stream ("at", stb);
6337 else
6339 uiout->field_string ("pending", b->locspec->to_string ());
6340 /* If extra_string is available, it could be holding a condition
6341 or dprintf arguments. In either case, make sure it is printed,
6342 too, but only for non-MI streams. */
6343 if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6345 if (b->type == bp_dprintf)
6346 uiout->text (",");
6347 else
6348 uiout->text (" ");
6349 uiout->text (b->extra_string.get ());
6353 if (loc && is_breakpoint (b)
6354 && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6355 && bp_condition_evaluator (b) == condition_evaluation_both)
6357 uiout->text (" (");
6358 uiout->field_string ("evaluated-by",
6359 bp_location_condition_evaluator (loc));
6360 uiout->text (")");
6364 static const char *
6365 bptype_string (enum bptype type)
6367 struct ep_type_description
6369 enum bptype type;
6370 const char *description;
6372 static struct ep_type_description bptypes[] =
6374 {bp_none, "?deleted?"},
6375 {bp_breakpoint, "breakpoint"},
6376 {bp_hardware_breakpoint, "hw breakpoint"},
6377 {bp_single_step, "sw single-step"},
6378 {bp_until, "until"},
6379 {bp_finish, "finish"},
6380 {bp_watchpoint, "watchpoint"},
6381 {bp_hardware_watchpoint, "hw watchpoint"},
6382 {bp_read_watchpoint, "read watchpoint"},
6383 {bp_access_watchpoint, "acc watchpoint"},
6384 {bp_longjmp, "longjmp"},
6385 {bp_longjmp_resume, "longjmp resume"},
6386 {bp_longjmp_call_dummy, "longjmp for call dummy"},
6387 {bp_exception, "exception"},
6388 {bp_exception_resume, "exception resume"},
6389 {bp_step_resume, "step resume"},
6390 {bp_hp_step_resume, "high-priority step resume"},
6391 {bp_watchpoint_scope, "watchpoint scope"},
6392 {bp_call_dummy, "call dummy"},
6393 {bp_std_terminate, "std::terminate"},
6394 {bp_shlib_event, "shlib events"},
6395 {bp_thread_event, "thread events"},
6396 {bp_overlay_event, "overlay events"},
6397 {bp_longjmp_master, "longjmp master"},
6398 {bp_std_terminate_master, "std::terminate master"},
6399 {bp_exception_master, "exception master"},
6400 {bp_catchpoint, "catchpoint"},
6401 {bp_tracepoint, "tracepoint"},
6402 {bp_fast_tracepoint, "fast tracepoint"},
6403 {bp_static_tracepoint, "static tracepoint"},
6404 {bp_static_marker_tracepoint, "static marker tracepoint"},
6405 {bp_dprintf, "dprintf"},
6406 {bp_jit_event, "jit events"},
6407 {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6408 {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6411 if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6412 || ((int) type != bptypes[(int) type].type))
6413 internal_error (_("bptypes table does not describe type #%d."),
6414 (int) type);
6416 return bptypes[(int) type].description;
6419 /* For MI, output a field named 'thread-groups' with a list as the value.
6420 For CLI, prefix the list with the string 'inf'. */
6422 static void
6423 output_thread_groups (struct ui_out *uiout,
6424 const char *field_name,
6425 const std::vector<int> &inf_nums,
6426 int mi_only)
6428 int is_mi = uiout->is_mi_like_p ();
6430 /* For backward compatibility, don't display inferiors in CLI unless
6431 there are several. Always display them for MI. */
6432 if (!is_mi && mi_only)
6433 return;
6435 ui_out_emit_list list_emitter (uiout, field_name);
6437 for (size_t i = 0; i < inf_nums.size (); i++)
6439 if (is_mi)
6441 char mi_group[10];
6443 xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6444 uiout->field_string (NULL, mi_group);
6446 else
6448 if (i == 0)
6449 uiout->text (" inf ");
6450 else
6451 uiout->text (", ");
6453 uiout->text (plongest (inf_nums[i]));
6458 /* See breakpoint.h. */
6460 bool fix_breakpoint_script_output_globally = false;
6462 /* Print B to gdb_stdout. If RAW_LOC, print raw breakpoint locations
6463 instead of going via breakpoint_ops::print_one. This makes "maint
6464 info breakpoints" show the software breakpoint locations of
6465 catchpoints, which are considered internal implementation
6466 detail. Returns true if RAW_LOC is false and if the breakpoint's
6467 print_one method did something; false otherwise. */
6469 static bool
6470 print_one_breakpoint_location (struct breakpoint *b,
6471 struct bp_location *loc,
6472 int loc_number,
6473 const bp_location **last_loc,
6474 int allflag, bool raw_loc)
6476 struct command_line *l;
6477 static char bpenables[] = "nynny";
6479 struct ui_out *uiout = current_uiout;
6480 bool header_of_multiple = false;
6481 bool part_of_multiple = (loc != NULL);
6482 struct value_print_options opts;
6484 get_user_print_options (&opts);
6486 gdb_assert (!loc || loc_number != 0);
6487 /* See comment in print_one_breakpoint concerning treatment of
6488 breakpoints with single disabled location. */
6489 if (loc == NULL
6490 && (b->has_locations ()
6491 && (b->has_multiple_locations ()
6492 || !b->first_loc ().enabled || b->first_loc ().disabled_by_cond)))
6493 header_of_multiple = true;
6495 if (loc == NULL && b->has_locations ())
6496 loc = &b->first_loc ();
6498 annotate_record ();
6500 /* 1 */
6501 annotate_field (0);
6502 if (part_of_multiple)
6503 uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6504 else
6505 uiout->field_signed ("number", b->number);
6507 /* 2 */
6508 annotate_field (1);
6509 if (part_of_multiple)
6510 uiout->field_skip ("type");
6511 else
6512 uiout->field_string ("type", bptype_string (b->type));
6514 /* 3 */
6515 annotate_field (2);
6516 if (part_of_multiple)
6517 uiout->field_skip ("disp");
6518 else
6519 uiout->field_string ("disp", bpdisp_text (b->disposition));
6521 /* 4 */
6522 annotate_field (3);
6523 if (part_of_multiple)
6525 /* For locations that are disabled because of an invalid
6526 condition, display "N*" on the CLI, where "*" refers to a
6527 footnote below the table. For MI, simply display a "N"
6528 without a footnote. On the CLI, for enabled locations whose
6529 breakpoint is disabled, display "y-". */
6530 auto get_enable_state = [uiout, loc] () -> const char *
6532 if (uiout->is_mi_like_p ())
6534 if (loc->disabled_by_cond)
6535 return "N";
6536 else if (!loc->enabled)
6537 return "n";
6538 else
6539 return "y";
6541 else
6543 if (loc->disabled_by_cond)
6544 return "N*";
6545 else if (!loc->enabled)
6546 return "n";
6547 else if (!breakpoint_enabled (loc->owner))
6548 return "y-";
6549 else
6550 return "y";
6553 uiout->field_string ("enabled", get_enable_state ());
6555 else
6556 uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6558 /* 5 and 6 */
6559 bool result = false;
6560 if (!raw_loc && b->print_one (last_loc))
6561 result = true;
6562 else
6564 if (is_watchpoint (b))
6566 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
6568 /* Field 4, the address, is omitted (which makes the columns
6569 not line up too nicely with the headers, but the effect
6570 is relatively readable). */
6571 if (opts.addressprint)
6572 uiout->field_skip ("addr");
6573 annotate_field (5);
6574 uiout->field_string ("what", w->exp_string.get ());
6576 else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6577 || is_ada_exception_catchpoint (b))
6579 if (opts.addressprint)
6581 annotate_field (4);
6582 if (header_of_multiple)
6583 uiout->field_string ("addr", "<MULTIPLE>",
6584 metadata_style.style ());
6585 else if (!b->has_locations () || loc->shlib_disabled)
6586 uiout->field_string ("addr", "<PENDING>",
6587 metadata_style.style ());
6588 else
6589 uiout->field_core_addr ("addr",
6590 loc->gdbarch, loc->address);
6592 annotate_field (5);
6593 if (!header_of_multiple)
6594 print_breakpoint_location (b, loc);
6595 if (b->has_locations ())
6596 *last_loc = &b->first_loc ();
6600 if (loc != NULL && !header_of_multiple)
6602 std::vector<int> inf_nums;
6603 int mi_only = 1;
6605 for (inferior *inf : all_inferiors ())
6607 if (inf->pspace == loc->pspace)
6608 inf_nums.push_back (inf->num);
6611 /* For backward compatibility, don't display inferiors in CLI unless
6612 there are several. Always display for MI. */
6613 if (allflag
6614 || (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
6615 && (program_spaces.size () > 1
6616 || number_of_inferiors () > 1)
6617 /* LOC is for existing B, it cannot be in
6618 moribund_locations and thus having NULL OWNER. */
6619 && loc->owner->type != bp_catchpoint))
6620 mi_only = 0;
6621 output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6624 /* In the MI output, each location of a thread or task specific
6625 breakpoint includes the relevant thread or task ID. This is done for
6626 backwards compatibility reasons.
6628 For the CLI output, the thread/task information is printed on a
6629 separate line, see the 'stop only in thread' and 'stop only in task'
6630 output below. */
6631 if (part_of_multiple && uiout->is_mi_like_p ())
6633 if (b->thread != -1)
6634 uiout->field_signed ("thread", b->thread);
6635 else if (b->task != -1)
6636 uiout->field_signed ("task", b->task);
6637 else if (b->inferior != -1)
6638 uiout->field_signed ("inferior", b->inferior);
6641 uiout->text ("\n");
6643 if (!part_of_multiple)
6644 b->print_one_detail (uiout);
6646 if (part_of_multiple && frame_id_p (b->frame_id))
6648 annotate_field (6);
6649 uiout->text ("\tstop only in stack frame at ");
6650 /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6651 the frame ID. */
6652 uiout->field_core_addr ("frame",
6653 b->gdbarch, b->frame_id.stack_addr);
6654 uiout->text ("\n");
6657 if (!part_of_multiple && b->cond_string)
6659 annotate_field (7);
6660 if (is_tracepoint (b))
6661 uiout->text ("\ttrace only if ");
6662 else
6663 uiout->text ("\tstop only if ");
6664 uiout->field_string ("cond", b->cond_string.get ());
6666 /* Print whether the target is doing the breakpoint's condition
6667 evaluation. If GDB is doing the evaluation, don't print anything. */
6668 if (is_breakpoint (b)
6669 && breakpoint_condition_evaluation_mode ()
6670 == condition_evaluation_target)
6672 uiout->message (" (%pF evals)",
6673 string_field ("evaluated-by",
6674 bp_condition_evaluator (b)));
6676 uiout->text ("\n");
6679 if (!part_of_multiple && b->thread != -1)
6681 /* FIXME should make an annotation for this. */
6682 uiout->text ("\tstop only in thread ");
6683 if (uiout->is_mi_like_p ())
6684 uiout->field_signed ("thread", b->thread);
6685 else
6687 struct thread_info *thr = find_thread_global_id (b->thread);
6689 uiout->field_string ("thread", print_thread_id (thr));
6691 uiout->text ("\n");
6694 if (!part_of_multiple && b->task != -1)
6696 uiout->text ("\tstop only in task ");
6697 uiout->field_signed ("task", b->task);
6698 uiout->text ("\n");
6701 if (!part_of_multiple && b->inferior != -1)
6703 uiout->text ("\tstop only in inferior ");
6704 uiout->field_signed ("inferior", b->inferior);
6705 uiout->text ("\n");
6708 if (!part_of_multiple)
6710 if (b->hit_count)
6712 /* FIXME should make an annotation for this. */
6713 if (is_catchpoint (b))
6714 uiout->text ("\tcatchpoint");
6715 else if (is_tracepoint (b))
6716 uiout->text ("\ttracepoint");
6717 else
6718 uiout->text ("\tbreakpoint");
6719 uiout->text (" already hit ");
6720 uiout->field_signed ("times", b->hit_count);
6721 if (b->hit_count == 1)
6722 uiout->text (" time\n");
6723 else
6724 uiout->text (" times\n");
6726 else
6728 /* Output the count also if it is zero, but only if this is mi. */
6729 if (uiout->is_mi_like_p ())
6730 uiout->field_signed ("times", b->hit_count);
6734 if (!part_of_multiple && b->ignore_count)
6736 annotate_field (8);
6737 uiout->message ("\tignore next %pF hits\n",
6738 signed_field ("ignore", b->ignore_count));
6741 /* Note that an enable count of 1 corresponds to "enable once"
6742 behavior, which is reported by the combination of enablement and
6743 disposition, so we don't need to mention it here. */
6744 if (!part_of_multiple && b->enable_count > 1)
6746 annotate_field (8);
6747 uiout->text ("\tdisable after ");
6748 /* Tweak the wording to clarify that ignore and enable counts
6749 are distinct, and have additive effect. */
6750 if (b->ignore_count)
6751 uiout->text ("additional ");
6752 else
6753 uiout->text ("next ");
6754 uiout->field_signed ("enable", b->enable_count);
6755 uiout->text (" hits\n");
6758 if (!part_of_multiple && is_tracepoint (b))
6760 tracepoint *tp = gdb::checked_static_cast<tracepoint *> (b);
6762 if (tp->traceframe_usage)
6764 uiout->text ("\ttrace buffer usage ");
6765 uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6766 uiout->text (" bytes\n");
6770 l = b->commands ? b->commands.get () : NULL;
6771 if (!part_of_multiple && l)
6773 annotate_field (9);
6775 bool use_fixed_output =
6776 (uiout->test_flags (fix_breakpoint_script_output)
6777 || fix_breakpoint_script_output_globally);
6779 std::optional<ui_out_emit_tuple> tuple_emitter;
6780 std::optional<ui_out_emit_list> list_emitter;
6782 if (use_fixed_output)
6783 list_emitter.emplace (uiout, "script");
6784 else
6785 tuple_emitter.emplace (uiout, "script");
6787 print_command_lines (uiout, l, 4);
6790 if (is_tracepoint (b))
6792 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
6794 if (!part_of_multiple && t->pass_count)
6796 annotate_field (10);
6797 uiout->text ("\tpass count ");
6798 uiout->field_signed ("pass", t->pass_count);
6799 uiout->text (" \n");
6802 /* Don't display it when tracepoint or tracepoint location is
6803 pending. */
6804 if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6806 annotate_field (11);
6808 if (uiout->is_mi_like_p ())
6809 uiout->field_string ("installed",
6810 loc->inserted ? "y" : "n");
6811 else
6813 if (loc->inserted)
6814 uiout->text ("\t");
6815 else
6816 uiout->text ("\tnot ");
6817 uiout->text ("installed on target\n");
6822 if (uiout->is_mi_like_p () && !part_of_multiple)
6824 if (is_watchpoint (b))
6826 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
6828 uiout->field_string ("original-location", w->exp_string.get ());
6830 else if (b->locspec != nullptr)
6832 const char *str = b->locspec->to_string ();
6833 if (str != nullptr)
6834 uiout->field_string ("original-location", str);
6838 return result;
6841 /* See breakpoint.h. */
6843 bool fix_multi_location_breakpoint_output_globally = false;
6845 static void
6846 print_one_breakpoint (breakpoint *b, const bp_location **last_loc, int allflag)
6848 struct ui_out *uiout = current_uiout;
6849 bool use_fixed_output
6850 = (uiout->test_flags (fix_multi_location_breakpoint_output)
6851 || fix_multi_location_breakpoint_output_globally);
6853 std::optional<ui_out_emit_tuple> bkpt_tuple_emitter (std::in_place, uiout,
6854 "bkpt");
6855 bool printed = print_one_breakpoint_location (b, NULL, 0, last_loc,
6856 allflag, false);
6858 /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6859 are outside. */
6860 if (!use_fixed_output)
6861 bkpt_tuple_emitter.reset ();
6863 /* If this breakpoint has custom print function,
6864 it's already printed. Otherwise, print individual
6865 locations, if any. */
6866 if (!printed || allflag)
6868 /* If breakpoint has a single location that is disabled, we
6869 print it as if it had several locations, since otherwise it's
6870 hard to represent "breakpoint enabled, location disabled"
6871 situation.
6873 Note that while hardware watchpoints have several locations
6874 internally, that's not a property exposed to users.
6876 Likewise, while catchpoints may be implemented with
6877 breakpoints (e.g., catch throw), that's not a property
6878 exposed to users. We do however display the internal
6879 breakpoint locations with "maint info breakpoints". */
6880 if (!is_hardware_watchpoint (b)
6881 && (!is_catchpoint (b) || is_exception_catchpoint (b)
6882 || is_ada_exception_catchpoint (b))
6883 && (allflag
6884 || (b->has_locations ()
6885 && (b->has_multiple_locations ()
6886 || !b->first_loc ().enabled
6887 || b->first_loc ().disabled_by_cond))))
6889 std::optional<ui_out_emit_list> locations_list;
6891 /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6892 MI record. For later versions, place breakpoint locations in a
6893 list. */
6894 if (uiout->is_mi_like_p () && use_fixed_output)
6895 locations_list.emplace (uiout, "locations");
6897 int n = 1;
6898 for (bp_location &loc : b->locations ())
6900 ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6901 print_one_breakpoint_location (b, &loc, n, last_loc,
6902 allflag, allflag);
6903 n++;
6909 static int
6910 breakpoint_address_bits (struct breakpoint *b)
6912 int print_address_bits = 0;
6914 for (bp_location &loc : b->locations ())
6916 if (!bl_address_is_meaningful (&loc))
6917 continue;
6919 int addr_bit = gdbarch_addr_bit (loc.gdbarch);
6920 if (addr_bit > print_address_bits)
6921 print_address_bits = addr_bit;
6924 return print_address_bits;
6927 /* See breakpoint.h. */
6929 void
6930 print_breakpoint (breakpoint *b)
6932 const bp_location *dummy_loc = nullptr;
6933 print_one_breakpoint (b, &dummy_loc, 0);
6936 /* Return true if this breakpoint was set by the user, false if it is
6937 internal or momentary. */
6940 user_breakpoint_p (struct breakpoint *b)
6942 return b->number > 0;
6945 /* See breakpoint.h. */
6948 pending_breakpoint_p (struct breakpoint *b)
6950 return !b->has_locations ();
6953 /* Print information on breakpoints (including watchpoints and tracepoints).
6955 If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6956 understood by number_or_range_parser. Only breakpoints included in this
6957 list are then printed.
6959 If SHOW_INTERNAL is true, print internal breakpoints.
6961 If FILTER is non-NULL, call it on each breakpoint and only include the
6962 ones for which it returns true.
6964 Return the total number of breakpoints listed. */
6966 static int
6967 breakpoint_1 (const char *bp_num_list, bool show_internal,
6968 bool (*filter) (const struct breakpoint *))
6970 const bp_location *last_loc = nullptr;
6971 int nr_printable_breakpoints;
6972 struct value_print_options opts;
6973 int print_address_bits = 0;
6974 int print_type_col_width = 14;
6975 struct ui_out *uiout = current_uiout;
6976 bool has_disabled_by_cond_location = false;
6978 get_user_print_options (&opts);
6980 /* Compute the number of rows in the table, as well as the size
6981 required for address fields. */
6982 nr_printable_breakpoints = 0;
6983 for (breakpoint &b : all_breakpoints ())
6985 /* If we have a filter, only list the breakpoints it accepts. */
6986 if (filter && !filter (&b))
6987 continue;
6989 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6990 accept. Skip the others. */
6991 if (bp_num_list != NULL && *bp_num_list != '\0')
6993 if (show_internal && parse_and_eval_long (bp_num_list) != b.number)
6994 continue;
6995 if (!show_internal && !number_is_in_list (bp_num_list, b.number))
6996 continue;
6999 if (show_internal || user_breakpoint_p (&b))
7001 int addr_bit, type_len;
7003 addr_bit = breakpoint_address_bits (&b);
7004 if (addr_bit > print_address_bits)
7005 print_address_bits = addr_bit;
7007 type_len = strlen (bptype_string (b.type));
7008 if (type_len > print_type_col_width)
7009 print_type_col_width = type_len;
7011 nr_printable_breakpoints++;
7016 ui_out_emit_table table_emitter (uiout,
7017 opts.addressprint ? 6 : 5,
7018 nr_printable_breakpoints,
7019 "BreakpointTable");
7021 if (nr_printable_breakpoints > 0)
7022 annotate_breakpoints_headers ();
7023 if (nr_printable_breakpoints > 0)
7024 annotate_field (0);
7025 uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
7026 if (nr_printable_breakpoints > 0)
7027 annotate_field (1);
7028 uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
7029 if (nr_printable_breakpoints > 0)
7030 annotate_field (2);
7031 uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
7032 if (nr_printable_breakpoints > 0)
7033 annotate_field (3);
7034 uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
7035 if (opts.addressprint)
7037 if (nr_printable_breakpoints > 0)
7038 annotate_field (4);
7039 if (print_address_bits <= 32)
7040 uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
7041 else
7042 uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
7044 if (nr_printable_breakpoints > 0)
7045 annotate_field (5);
7046 uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
7047 uiout->table_body ();
7048 if (nr_printable_breakpoints > 0)
7049 annotate_breakpoints_table ();
7051 for (breakpoint &b : all_breakpoints ())
7053 QUIT;
7054 /* If we have a filter, only list the breakpoints it accepts. */
7055 if (filter && !filter (&b))
7056 continue;
7058 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
7059 accept. Skip the others. */
7061 if (bp_num_list != NULL && *bp_num_list != '\0')
7063 if (show_internal) /* maintenance info breakpoint */
7065 if (parse_and_eval_long (bp_num_list) != b.number)
7066 continue;
7068 else /* all others */
7070 if (!number_is_in_list (bp_num_list, b.number))
7071 continue;
7074 /* We only print out user settable breakpoints unless the
7075 show_internal is set. */
7076 if (show_internal || user_breakpoint_p (&b))
7078 print_one_breakpoint (&b, &last_loc, show_internal);
7079 for (bp_location &loc : b.locations ())
7080 if (loc.disabled_by_cond)
7081 has_disabled_by_cond_location = true;
7086 if (nr_printable_breakpoints == 0)
7088 /* If there's a filter, let the caller decide how to report
7089 empty list. */
7090 if (!filter)
7092 if (bp_num_list == NULL || *bp_num_list == '\0')
7093 uiout->message ("No breakpoints or watchpoints.\n");
7094 else
7095 uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
7096 bp_num_list);
7099 else
7101 if (last_loc && !server_command)
7102 set_next_address (last_loc->gdbarch, last_loc->address);
7104 if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
7105 uiout->message (_("(*): Breakpoint condition is invalid at this "
7106 "location.\n"));
7109 /* FIXME? Should this be moved up so that it is only called when
7110 there have been breakpoints? */
7111 annotate_breakpoints_table_end ();
7113 return nr_printable_breakpoints;
7116 /* Display the value of default-collect in a way that is generally
7117 compatible with the breakpoint list. */
7119 static void
7120 default_collect_info (void)
7122 struct ui_out *uiout = current_uiout;
7124 /* If it has no value (which is frequently the case), say nothing; a
7125 message like "No default-collect." gets in user's face when it's
7126 not wanted. */
7127 if (default_collect.empty ())
7128 return;
7130 /* The following phrase lines up nicely with per-tracepoint collect
7131 actions. */
7132 uiout->text ("default collect ");
7133 uiout->field_string ("default-collect", default_collect);
7134 uiout->text (" \n");
7137 static void
7138 info_breakpoints_command (const char *args, int from_tty)
7140 breakpoint_1 (args, false, NULL);
7142 default_collect_info ();
7145 static void
7146 info_watchpoints_command (const char *args, int from_tty)
7148 int num_printed = breakpoint_1 (args, false, is_watchpoint);
7149 struct ui_out *uiout = current_uiout;
7151 if (num_printed == 0)
7153 if (args == NULL || *args == '\0')
7154 uiout->message ("No watchpoints.\n");
7155 else
7156 uiout->message ("No watchpoint matching '%s'.\n", args);
7160 static void
7161 maintenance_info_breakpoints (const char *args, int from_tty)
7163 breakpoint_1 (args, true, NULL);
7165 default_collect_info ();
7168 static bool
7169 breakpoint_has_pc (struct breakpoint *b,
7170 struct program_space *pspace,
7171 CORE_ADDR pc, struct obj_section *section)
7173 for (bp_location &bl : b->locations ())
7175 if (bl.pspace == pspace
7176 && bl.address == pc
7177 && (!overlay_debugging || bl.section == section))
7178 return true;
7180 return false;
7183 /* See breakpoint.h. */
7185 void
7186 describe_other_breakpoints (struct gdbarch *gdbarch,
7187 struct program_space *pspace, CORE_ADDR pc,
7188 struct obj_section *section, int thread)
7190 int others = 0;
7192 for (breakpoint &b : all_breakpoints ())
7193 others += (user_breakpoint_p (&b)
7194 && breakpoint_has_pc (&b, pspace, pc, section));
7196 if (others > 0)
7198 if (others == 1)
7199 gdb_printf (_("Note: breakpoint "));
7200 else /* if (others == ???) */
7201 gdb_printf (_("Note: breakpoints "));
7202 for (breakpoint &b : all_breakpoints ())
7203 if (user_breakpoint_p (&b)
7204 && breakpoint_has_pc (&b, pspace, pc, section))
7206 others--;
7207 gdb_printf ("%d", b.number);
7208 if (b.thread == -1 && thread != -1)
7209 gdb_printf (" (all threads)");
7210 else if (b.thread != -1)
7212 struct thread_info *thr = find_thread_global_id (b.thread);
7213 gdb_printf (" (thread %s)", print_thread_id (thr));
7215 else if (b.task != -1)
7216 gdb_printf (" (task %d)", b.task);
7217 gdb_printf ("%s%s ",
7218 ((b.enable_state == bp_disabled
7219 || b.enable_state == bp_call_disabled)
7220 ? " (disabled)"
7221 : ""),
7222 (others > 1) ? ","
7223 : ((others == 1) ? " and" : ""));
7225 current_uiout->message (_("also set at pc %ps.\n"),
7226 styled_string (address_style.style (),
7227 paddress (gdbarch, pc)));
7232 /* Return true iff it is meaningful to use the address member of LOC.
7233 For some breakpoint types, the locations' address members are
7234 irrelevant and it makes no sense to attempt to compare them to
7235 other addresses (or use them for any other purpose either).
7237 More specifically, software watchpoints and catchpoints that are
7238 not backed by breakpoints always have a zero valued location
7239 address and we don't want to mark breakpoints of any of these types
7240 to be a duplicate of an actual breakpoint location at address
7241 zero. */
7243 static bool
7244 bl_address_is_meaningful (bp_location *loc)
7246 return loc->loc_type != bp_loc_other;
7249 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7250 true if LOC1 and LOC2 represent the same watchpoint location. */
7252 static bool
7253 watchpoint_locations_match (const struct bp_location *loc1,
7254 const struct bp_location *loc2)
7256 watchpoint *w1 = gdb::checked_static_cast<watchpoint *> (loc1->owner);
7257 watchpoint *w2 = gdb::checked_static_cast<watchpoint *> (loc2->owner);
7259 /* Both of them must exist. */
7260 gdb_assert (w1 != NULL);
7261 gdb_assert (w2 != NULL);
7263 /* If the target can evaluate the condition expression in hardware,
7264 then we we need to insert both watchpoints even if they are at
7265 the same place. Otherwise the watchpoint will only trigger when
7266 the condition of whichever watchpoint was inserted evaluates to
7267 true, not giving a chance for GDB to check the condition of the
7268 other watchpoint. */
7269 if ((w1->cond_exp
7270 && target_can_accel_watchpoint_condition (loc1->address,
7271 loc1->length,
7272 loc1->watchpoint_type,
7273 w1->cond_exp.get ()))
7274 || (w2->cond_exp
7275 && target_can_accel_watchpoint_condition (loc2->address,
7276 loc2->length,
7277 loc2->watchpoint_type,
7278 w2->cond_exp.get ())))
7279 return false;
7281 /* Note that this checks the owner's type, not the location's. In
7282 case the target does not support read watchpoints, but does
7283 support access watchpoints, we'll have bp_read_watchpoint
7284 watchpoints with hw_access locations. Those should be considered
7285 duplicates of hw_read locations. The hw_read locations will
7286 become hw_access locations later. */
7287 return (loc1->owner->type == loc2->owner->type
7288 && loc1->pspace->aspace == loc2->pspace->aspace
7289 && loc1->address == loc2->address
7290 && loc1->length == loc2->length);
7293 /* See breakpoint.h. */
7296 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
7297 const address_space *aspace2, CORE_ADDR addr2)
7299 return ((gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7300 || aspace1 == aspace2)
7301 && addr1 == addr2);
7304 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7305 {ASPACE1,ADDR1,LEN1}. In most targets, this can only be true if ASPACE1
7306 matches ASPACE2. On targets that have global breakpoints, the address
7307 space doesn't really matter. */
7309 static bool
7310 breakpoint_address_match_range (const address_space *aspace1,
7311 CORE_ADDR addr1,
7312 int len1, const address_space *aspace2,
7313 CORE_ADDR addr2)
7315 return ((gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7316 || aspace1 == aspace2)
7317 && addr2 >= addr1 && addr2 < addr1 + len1);
7320 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL. BL may be
7321 a ranged breakpoint. In most targets, a match happens only if ASPACE
7322 matches the breakpoint's address space. On targets that have global
7323 breakpoints, the address space doesn't really matter. */
7325 static bool
7326 breakpoint_location_address_match (struct bp_location *bl,
7327 const address_space *aspace,
7328 CORE_ADDR addr)
7330 return (breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
7331 aspace, addr)
7332 || (bl->length
7333 && breakpoint_address_match_range (bl->pspace->aspace.get (),
7334 bl->address, bl->length,
7335 aspace, addr)));
7338 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7339 breakpoint BL. BL may be a ranged breakpoint. In most targets, a
7340 match happens only if ASPACE matches the breakpoint's address
7341 space. On targets that have global breakpoints, the address space
7342 doesn't really matter. */
7344 static bool
7345 breakpoint_location_address_range_overlap (struct bp_location *bl,
7346 const address_space *aspace,
7347 CORE_ADDR addr, int len)
7349 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7350 || bl->pspace->aspace.get () == aspace)
7352 int bl_len = bl->length != 0 ? bl->length : 1;
7354 if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7355 return 1;
7357 return 0;
7360 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7361 Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7362 true, otherwise returns false. */
7364 static bool
7365 tracepoint_locations_match (const struct bp_location *loc1,
7366 const struct bp_location *loc2)
7368 if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7369 /* Since tracepoint locations are never duplicated with others', tracepoint
7370 locations at the same address of different tracepoints are regarded as
7371 different locations. */
7372 return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7373 else
7374 return false;
7377 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7378 (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
7379 the same location. If SW_HW_BPS_MATCH is true, then software
7380 breakpoint locations and hardware breakpoint locations match,
7381 otherwise they don't. */
7383 static bool
7384 breakpoint_locations_match (const struct bp_location *loc1,
7385 const struct bp_location *loc2,
7386 bool sw_hw_bps_match)
7388 int hw_point1, hw_point2;
7390 /* Both of them must not be in moribund_locations. */
7391 gdb_assert (loc1->owner != NULL);
7392 gdb_assert (loc2->owner != NULL);
7394 hw_point1 = is_hardware_watchpoint (loc1->owner);
7395 hw_point2 = is_hardware_watchpoint (loc2->owner);
7397 if (hw_point1 != hw_point2)
7398 return false;
7399 else if (hw_point1)
7400 return watchpoint_locations_match (loc1, loc2);
7401 else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7402 return tracepoint_locations_match (loc1, loc2);
7403 else
7404 /* We compare bp_location.length in order to cover ranged
7405 breakpoints. Keep this in sync with
7406 bp_location_is_less_than. */
7407 return (breakpoint_address_match (loc1->pspace->aspace.get (),
7408 loc1->address,
7409 loc2->pspace->aspace.get (),
7410 loc2->address)
7411 && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
7412 && loc1->length == loc2->length);
7415 static void
7416 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7417 int bnum, bool have_bnum)
7419 /* The longest string possibly returned by hex_string_custom
7420 is 50 chars. These must be at least that big for safety. */
7421 char astr1[64];
7422 char astr2[64];
7424 strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7425 strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7426 if (have_bnum)
7427 warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7428 bnum, astr1, astr2);
7429 else
7430 warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7433 /* Adjust a breakpoint's address to account for architectural
7434 constraints on breakpoint placement. Return the adjusted address.
7435 Note: Very few targets require this kind of adjustment. For most
7436 targets, this function is simply the identity function. */
7438 static CORE_ADDR
7439 adjust_breakpoint_address (struct gdbarch *gdbarch,
7440 CORE_ADDR bpaddr, enum bptype bptype,
7441 struct program_space *pspace)
7443 gdb_assert (pspace != nullptr);
7445 if (bptype == bp_watchpoint
7446 || bptype == bp_hardware_watchpoint
7447 || bptype == bp_read_watchpoint
7448 || bptype == bp_access_watchpoint
7449 || bptype == bp_catchpoint)
7451 /* Watchpoints and the various bp_catch_* eventpoints should not
7452 have their addresses modified. */
7453 return bpaddr;
7455 else if (bptype == bp_single_step)
7457 /* Single-step breakpoints should not have their addresses
7458 modified. If there's any architectural constrain that
7459 applies to this address, then it should have already been
7460 taken into account when the breakpoint was created in the
7461 first place. If we didn't do this, stepping through e.g.,
7462 Thumb-2 IT blocks would break. */
7463 return bpaddr;
7465 else
7467 CORE_ADDR adjusted_bpaddr = bpaddr;
7469 /* Some targets have architectural constraints on the placement
7470 of breakpoint instructions. Obtain the adjusted address. */
7471 if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7473 /* Targets that implement this adjustment function will likely
7474 inspect either the symbol table, target memory at BPADDR, or
7475 even state registers, so ensure a suitable thread (and its
7476 associated program space) are currently selected. */
7477 scoped_restore_current_pspace_and_thread restore_pspace_thread;
7478 switch_to_program_space_and_thread (pspace);
7479 adjusted_bpaddr
7480 = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7483 adjusted_bpaddr
7484 = gdbarch_remove_non_address_bits (gdbarch, adjusted_bpaddr);
7486 /* An adjusted breakpoint address can significantly alter
7487 a user's expectations. Print a warning if an adjustment
7488 is required. */
7489 if (adjusted_bpaddr != bpaddr)
7490 breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, false);
7492 return adjusted_bpaddr;
7496 static bp_loc_type
7497 bp_location_from_bp_type (bptype type)
7499 switch (type)
7501 case bp_breakpoint:
7502 case bp_single_step:
7503 case bp_until:
7504 case bp_finish:
7505 case bp_longjmp:
7506 case bp_longjmp_resume:
7507 case bp_longjmp_call_dummy:
7508 case bp_exception:
7509 case bp_exception_resume:
7510 case bp_step_resume:
7511 case bp_hp_step_resume:
7512 case bp_watchpoint_scope:
7513 case bp_call_dummy:
7514 case bp_std_terminate:
7515 case bp_shlib_event:
7516 case bp_thread_event:
7517 case bp_overlay_event:
7518 case bp_jit_event:
7519 case bp_longjmp_master:
7520 case bp_std_terminate_master:
7521 case bp_exception_master:
7522 case bp_gnu_ifunc_resolver:
7523 case bp_gnu_ifunc_resolver_return:
7524 case bp_dprintf:
7525 return bp_loc_software_breakpoint;
7527 case bp_hardware_breakpoint:
7528 return bp_loc_hardware_breakpoint;
7530 case bp_hardware_watchpoint:
7531 case bp_read_watchpoint:
7532 case bp_access_watchpoint:
7533 return bp_loc_hardware_watchpoint;
7535 case bp_watchpoint:
7536 return bp_loc_software_watchpoint;
7538 case bp_tracepoint:
7539 case bp_fast_tracepoint:
7540 case bp_static_tracepoint:
7541 case bp_static_marker_tracepoint:
7542 return bp_loc_tracepoint;
7544 case bp_catchpoint:
7545 return bp_loc_other;
7547 default:
7548 internal_error (_("unknown breakpoint type"));
7552 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7554 this->owner = owner;
7555 this->cond_bytecode = NULL;
7556 this->shlib_disabled = 0;
7557 this->enabled = 1;
7558 this->disabled_by_cond = false;
7560 this->loc_type = type;
7562 if (this->loc_type == bp_loc_software_breakpoint
7563 || this->loc_type == bp_loc_hardware_breakpoint)
7564 mark_breakpoint_location_modified (this);
7566 incref ();
7569 bp_location::bp_location (breakpoint *owner)
7570 : bp_location::bp_location (owner,
7571 bp_location_from_bp_type (owner->type))
7575 /* See breakpoint.h. */
7577 std::string
7578 bp_location::to_string () const
7580 string_file stb;
7581 ui_out_redirect_pop redir (current_uiout, &stb);
7582 print_breakpoint_location (this->owner, this);
7583 return stb.release ();
7586 /* Decrement reference count. If the reference count reaches 0,
7587 destroy the bp_location. Sets *BLP to NULL. */
7589 static void
7590 decref_bp_location (struct bp_location **blp)
7592 bp_location_ref_policy::decref (*blp);
7593 *blp = NULL;
7596 /* Add breakpoint B at the end of the global breakpoint chain. */
7598 static breakpoint *
7599 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7601 /* Add this breakpoint to the end of the chain so that a list of
7602 breakpoints will come out in order of increasing numbers. */
7604 breakpoint_chain.push_back (*b.release ());
7606 return &breakpoint_chain.back ();
7609 /* Initialize loc->function_name. */
7611 static void
7612 set_breakpoint_location_function (struct bp_location *loc)
7614 gdb_assert (loc->owner != NULL);
7616 if (loc->owner->type == bp_breakpoint
7617 || loc->owner->type == bp_hardware_breakpoint
7618 || is_tracepoint (loc->owner))
7620 const char *function_name;
7622 if (loc->msymbol != NULL
7623 && (loc->msymbol->type () == mst_text_gnu_ifunc
7624 || loc->msymbol->type () == mst_data_gnu_ifunc))
7626 struct breakpoint *b = loc->owner;
7628 function_name = loc->msymbol->linkage_name ();
7630 if (b->type == bp_breakpoint
7631 && b->has_single_location ()
7632 && b->related_breakpoint == b)
7634 /* Create only the whole new breakpoint of this type but do not
7635 mess more complicated breakpoints with multiple locations. */
7636 b->type = bp_gnu_ifunc_resolver;
7637 /* Remember the resolver's address for use by the return
7638 breakpoint. */
7639 loc->related_address = loc->address;
7642 else
7643 find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7645 if (function_name)
7646 loc->function_name = make_unique_xstrdup (function_name);
7650 /* Attempt to determine architecture of location identified by SAL. */
7651 struct gdbarch *
7652 get_sal_arch (struct symtab_and_line sal)
7654 if (sal.section)
7655 return sal.section->objfile->arch ();
7656 if (sal.symtab)
7657 return sal.symtab->compunit ()->objfile ()->arch ();
7659 return NULL;
7662 /* Call this routine when stepping and nexting to enable a breakpoint
7663 if we do a longjmp() or 'throw' in TP. FRAME is the frame which
7664 initiated the operation. */
7666 void
7667 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7669 int thread = tp->global_num;
7671 /* To avoid having to rescan all objfile symbols at every step,
7672 we maintain a list of continually-inserted but always disabled
7673 longjmp "master" breakpoints. Here, we simply create momentary
7674 clones of those and enable them for the requested thread. */
7675 for (breakpoint &b : all_breakpoints_safe ())
7676 if (b.pspace == current_program_space
7677 && (b.type == bp_longjmp_master
7678 || b.type == bp_exception_master))
7680 bptype type = b.type == bp_longjmp_master ? bp_longjmp : bp_exception;
7681 /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7682 after their removal. */
7683 momentary_breakpoint_from_master (&b, type, 1, thread);
7686 tp->initiating_frame = frame;
7689 /* Delete all longjmp breakpoints from THREAD. */
7690 void
7691 delete_longjmp_breakpoint (int thread)
7693 for (breakpoint &b : all_breakpoints_safe ())
7694 if (b.type == bp_longjmp || b.type == bp_exception)
7696 if (b.thread == thread)
7698 gdb_assert (b.inferior == -1);
7699 delete_breakpoint (&b);
7704 void
7705 delete_longjmp_breakpoint_at_next_stop (int thread)
7707 for (breakpoint &b : all_breakpoints_safe ())
7708 if (b.type == bp_longjmp || b.type == bp_exception)
7710 if (b.thread == thread)
7712 gdb_assert (b.inferior == -1);
7713 b.disposition = disp_del_at_next_stop;
7718 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7719 INFERIOR_PTID thread. Chain them all by RELATED_BREAKPOINT and return
7720 pointer to any of them. Return NULL if this system cannot place longjmp
7721 breakpoints. */
7723 struct breakpoint *
7724 set_longjmp_breakpoint_for_call_dummy (void)
7726 breakpoint *retval = nullptr;
7728 for (breakpoint &b : all_breakpoints ())
7729 if (b.pspace == current_program_space && b.type == bp_longjmp_master)
7731 int thread = inferior_thread ()->global_num;
7732 breakpoint *new_b
7733 = momentary_breakpoint_from_master (&b, bp_longjmp_call_dummy,
7734 1, thread);
7736 /* Link NEW_B into the chain of RETVAL breakpoints. */
7738 gdb_assert (new_b->related_breakpoint == new_b);
7739 if (retval == NULL)
7740 retval = new_b;
7741 new_b->related_breakpoint = retval;
7742 while (retval->related_breakpoint != new_b->related_breakpoint)
7743 retval = retval->related_breakpoint;
7744 retval->related_breakpoint = new_b;
7747 return retval;
7750 /* Verify all existing dummy frames and their associated breakpoints for
7751 TP. Remove those which can no longer be found in the current frame
7752 stack.
7754 If the unwind fails then there is not sufficient information to discard
7755 dummy frames. In this case, elide the clean up and the dummy frames will
7756 be cleaned up next time this function is called from a location where
7757 unwinding is possible. */
7759 void
7760 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7762 /* We would need to delete breakpoints other than the current one while
7763 iterating, so all_breakpoints_safe is not sufficient to make that safe.
7764 Save all breakpoints to delete in that set and delete them at the end. */
7765 std::unordered_set<breakpoint *> to_delete;
7767 for (struct breakpoint &b : all_breakpoints ())
7769 if (b.type == bp_longjmp_call_dummy && b.thread == tp->global_num)
7771 gdb_assert (b.inferior == -1);
7772 struct breakpoint *dummy_b = b.related_breakpoint;
7774 /* Find the bp_call_dummy breakpoint in the list of breakpoints
7775 chained off b->related_breakpoint. */
7776 while (dummy_b != &b && dummy_b->type != bp_call_dummy)
7777 dummy_b = dummy_b->related_breakpoint;
7779 /* If there was no bp_call_dummy breakpoint then there's nothing
7780 more to do. Or, if the dummy frame associated with the
7781 bp_call_dummy is still on the stack then we need to leave this
7782 bp_call_dummy in place. */
7783 if (dummy_b->type != bp_call_dummy
7784 || frame_find_by_id (dummy_b->frame_id) != NULL)
7785 continue;
7787 /* We didn't find the dummy frame on the stack, this could be
7788 because we have longjmp'd to a stack frame that is previous to
7789 the dummy frame, or it could be because the stack unwind is
7790 broken at some point between the longjmp frame and the dummy
7791 frame.
7793 Next we figure out why the stack unwind stopped. If it looks
7794 like the unwind is complete then we assume the dummy frame has
7795 been jumped over, however, if the unwind stopped for an
7796 unexpected reason then we assume the stack unwind is currently
7797 broken, and that we will (eventually) return to the dummy
7798 frame.
7800 It might be tempting to consider using frame_id_inner here, but
7801 that is not safe. There is no guarantee that the stack frames
7802 we are looking at here are even on the same stack as the
7803 original dummy frame, hence frame_id_inner can't be used. See
7804 the comments on frame_id_inner for more details. */
7805 bool unwind_finished_unexpectedly = false;
7806 for (frame_info_ptr fi = get_current_frame (); fi != nullptr; )
7808 frame_info_ptr prev = get_prev_frame (fi);
7809 if (prev == nullptr)
7811 /* FI is the last stack frame. Why did this frame not
7812 unwind further? */
7813 auto stop_reason = get_frame_unwind_stop_reason (fi);
7814 if (stop_reason != UNWIND_NO_REASON
7815 && stop_reason != UNWIND_OUTERMOST)
7816 unwind_finished_unexpectedly = true;
7818 fi = prev;
7820 if (unwind_finished_unexpectedly)
7821 continue;
7823 dummy_frame_discard (dummy_b->frame_id, tp);
7825 for (breakpoint *related_breakpoint = b.related_breakpoint;
7826 related_breakpoint != &b;
7827 related_breakpoint = related_breakpoint->related_breakpoint)
7828 to_delete.insert (b.related_breakpoint);
7830 to_delete.insert (&b);
7834 for (breakpoint *b : to_delete)
7835 delete_breakpoint (b);
7838 void
7839 enable_overlay_breakpoints (void)
7841 for (breakpoint &b : all_breakpoints ())
7842 if (b.type == bp_overlay_event)
7844 b.enable_state = bp_enabled;
7845 update_global_location_list (UGLL_MAY_INSERT);
7846 overlay_events_enabled = 1;
7850 void
7851 disable_overlay_breakpoints (void)
7853 for (breakpoint &b : all_breakpoints ())
7854 if (b.type == bp_overlay_event)
7856 b.enable_state = bp_disabled;
7857 update_global_location_list (UGLL_DONT_INSERT);
7858 overlay_events_enabled = 0;
7862 /* Set an active std::terminate breakpoint for each std::terminate
7863 master breakpoint. */
7864 void
7865 set_std_terminate_breakpoint (void)
7867 for (breakpoint &b : all_breakpoints_safe ())
7868 if (b.pspace == current_program_space
7869 && b.type == bp_std_terminate_master)
7871 momentary_breakpoint_from_master (&b, bp_std_terminate, 1,
7872 inferior_thread ()->global_num);
7876 /* Delete all the std::terminate breakpoints. */
7877 void
7878 delete_std_terminate_breakpoint (void)
7880 for (breakpoint &b : all_breakpoints_safe ())
7881 if (b.type == bp_std_terminate)
7882 delete_breakpoint (&b);
7885 struct breakpoint *
7886 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7888 struct breakpoint *b;
7890 b = create_internal_breakpoint (gdbarch, address, bp_thread_event);
7892 b->enable_state = bp_enabled;
7893 /* locspec has to be used or breakpoint_re_set will delete me. */
7894 b->locspec = new_address_location_spec (b->first_loc ().address, NULL, 0);
7896 update_global_location_list_nothrow (UGLL_MAY_INSERT);
7898 return b;
7901 struct lang_and_radix
7903 enum language lang;
7904 int radix;
7907 /* Create a breakpoint for JIT code registration and unregistration. */
7909 struct breakpoint *
7910 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7912 return create_internal_breakpoint (gdbarch, address, bp_jit_event);
7915 /* Remove JIT code registration and unregistration breakpoint(s). */
7917 void
7918 remove_jit_event_breakpoints (void)
7920 for (breakpoint &b : all_breakpoints_safe ())
7921 if (b.type == bp_jit_event
7922 && b.first_loc ().pspace == current_program_space)
7923 delete_breakpoint (&b);
7926 void
7927 remove_solib_event_breakpoints (void)
7929 for (breakpoint &b : all_breakpoints_safe ())
7930 if (b.type == bp_shlib_event
7931 && b.first_loc ().pspace == current_program_space)
7932 delete_breakpoint (&b);
7935 /* See breakpoint.h. */
7937 void
7938 remove_solib_event_breakpoints_at_next_stop (void)
7940 for (breakpoint &b : all_breakpoints_safe ())
7941 if (b.type == bp_shlib_event
7942 && b.first_loc ().pspace == current_program_space)
7943 b.disposition = disp_del_at_next_stop;
7946 /* Helper for create_solib_event_breakpoint /
7947 create_and_insert_solib_event_breakpoint. Allows specifying which
7948 INSERT_MODE to pass through to update_global_location_list. */
7950 static struct breakpoint *
7951 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7952 enum ugll_insert_mode insert_mode)
7954 struct breakpoint *b;
7956 b = create_internal_breakpoint (gdbarch, address, bp_shlib_event);
7957 update_global_location_list_nothrow (insert_mode);
7958 return b;
7961 struct breakpoint *
7962 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7964 return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7967 /* See breakpoint.h. */
7969 struct breakpoint *
7970 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7972 struct breakpoint *b;
7974 /* Explicitly tell update_global_location_list to insert
7975 locations. */
7976 b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7977 if (!b->first_loc ().inserted)
7979 delete_breakpoint (b);
7980 return NULL;
7982 return b;
7985 /* Disable any breakpoints that are on code in shared libraries. Only
7986 apply to enabled breakpoints, disabled ones can just stay disabled. */
7988 void
7989 disable_breakpoints_in_shlibs (void)
7991 for (bp_location *loc : all_bp_locations ())
7993 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
7994 struct breakpoint *b = loc->owner;
7996 /* We apply the check to all breakpoints, including disabled for
7997 those with loc->duplicate set. This is so that when breakpoint
7998 becomes enabled, or the duplicate is removed, gdb will try to
7999 insert all breakpoints. If we don't set shlib_disabled here,
8000 we'll try to insert those breakpoints and fail. */
8001 if (((b->type == bp_breakpoint)
8002 || (b->type == bp_jit_event)
8003 || (b->type == bp_hardware_breakpoint)
8004 || (is_tracepoint (b)))
8005 && loc->pspace == current_program_space
8006 && !loc->shlib_disabled
8007 && solib_name_from_address (loc->pspace, loc->address)
8010 loc->shlib_disabled = 1;
8015 /* Disable any breakpoints and tracepoints that are in SOLIB upon
8016 notification of unloaded_shlib. Only apply to enabled breakpoints,
8017 disabled ones can just stay disabled. */
8019 static void
8020 disable_breakpoints_in_unloaded_shlib (program_space *pspace, const shobj &solib)
8022 bool disabled_shlib_breaks = false;
8024 for (bp_location *loc : all_bp_locations ())
8026 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
8027 struct breakpoint *b = loc->owner;
8029 if (pspace == loc->pspace
8030 && !loc->shlib_disabled
8031 && (((b->type == bp_breakpoint
8032 || b->type == bp_jit_event
8033 || b->type == bp_hardware_breakpoint)
8034 && (loc->loc_type == bp_loc_hardware_breakpoint
8035 || loc->loc_type == bp_loc_software_breakpoint))
8036 || is_tracepoint (b))
8037 && solib_contains_address_p (solib, loc->address))
8039 loc->shlib_disabled = 1;
8040 /* At this point, we cannot rely on remove_breakpoint
8041 succeeding so we must mark the breakpoint as not inserted
8042 to prevent future errors occurring in remove_breakpoints. */
8043 loc->inserted = 0;
8045 /* This may cause duplicate notifications for the same breakpoint. */
8046 notify_breakpoint_modified (b);
8048 if (!disabled_shlib_breaks)
8050 target_terminal::ours_for_output ();
8051 warning (_("Temporarily disabling breakpoints "
8052 "for unloaded shared library \"%s\""),
8053 solib.so_name.c_str ());
8055 disabled_shlib_breaks = true;
8060 /* Disable any breakpoints and tracepoints in OBJFILE upon
8061 notification of free_objfile. Only apply to enabled breakpoints,
8062 disabled ones can just stay disabled. */
8064 static void
8065 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
8067 /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
8068 managed by the user with add-symbol-file/remove-symbol-file.
8069 Similarly to how breakpoints in shared libraries are handled in
8070 response to "nosharedlibrary", mark breakpoints in such modules
8071 shlib_disabled so they end up uninserted on the next global
8072 location list update. Shared libraries not loaded by the user
8073 aren't handled here -- they're already handled in
8074 disable_breakpoints_in_unloaded_shlib, called by solib.c's
8075 solib_unloaded observer. We skip objfiles that are not
8076 OBJF_SHARED as those aren't considered dynamic objects (e.g. the
8077 main objfile). */
8078 if ((objfile->flags & OBJF_SHARED) == 0
8079 || (objfile->flags & OBJF_USERLOADED) == 0)
8080 return;
8082 for (breakpoint &b : all_breakpoints ())
8084 bool bp_modified = false;
8086 if (!is_breakpoint (&b) && !is_tracepoint (&b))
8087 continue;
8089 for (bp_location &loc : b.locations ())
8091 CORE_ADDR loc_addr = loc.address;
8093 if (loc.loc_type != bp_loc_hardware_breakpoint
8094 && loc.loc_type != bp_loc_software_breakpoint)
8095 continue;
8097 if (loc.shlib_disabled != 0)
8098 continue;
8100 if (objfile->pspace != loc.pspace)
8101 continue;
8103 if (loc.loc_type != bp_loc_hardware_breakpoint
8104 && loc.loc_type != bp_loc_software_breakpoint)
8105 continue;
8107 if (is_addr_in_objfile (loc_addr, objfile))
8109 loc.shlib_disabled = 1;
8110 /* At this point, we don't know whether the object was
8111 unmapped from the inferior or not, so leave the
8112 inserted flag alone. We'll handle failure to
8113 uninsert quietly, in case the object was indeed
8114 unmapped. */
8116 mark_breakpoint_location_modified (&loc);
8118 bp_modified = true;
8122 if (bp_modified)
8123 notify_breakpoint_modified (&b);
8127 /* See breakpoint.h. */
8129 breakpoint::breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
8130 bool temp, const char *cond_string_)
8131 : type (bptype),
8132 disposition (temp ? disp_del : disp_donttouch),
8133 gdbarch (gdbarch_),
8134 language (current_language->la_language),
8135 input_radix (::input_radix),
8136 cond_string (cond_string_ != nullptr
8137 ? make_unique_xstrdup (cond_string_)
8138 : nullptr),
8139 related_breakpoint (this)
8143 /* See breakpoint.h. */
8145 catchpoint::catchpoint (struct gdbarch *gdbarch, bool temp,
8146 const char *cond_string)
8147 : breakpoint (gdbarch, bp_catchpoint, temp, cond_string)
8149 add_dummy_location (this, current_program_space);
8151 pspace = current_program_space;
8154 /* Notify interpreters and observers that breakpoint B was created. */
8156 static void
8157 notify_breakpoint_created (breakpoint *b)
8159 interps_notify_breakpoint_created (b);
8160 gdb::observers::breakpoint_created.notify (b);
8163 breakpoint *
8164 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8166 breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8167 set_breakpoint_number (internal, b);
8168 if (is_tracepoint (b))
8169 set_tracepoint_count (breakpoint_count);
8170 if (!internal)
8171 mention (b);
8173 notify_breakpoint_created (b);
8175 if (update_gll)
8176 update_global_location_list (UGLL_MAY_INSERT);
8178 return b;
8181 static int
8182 hw_breakpoint_used_count (void)
8184 int i = 0;
8186 for (breakpoint &b : all_breakpoints ())
8187 if (b.type == bp_hardware_breakpoint && breakpoint_enabled (&b))
8188 for (bp_location &bl : b.locations ())
8190 /* Special types of hardware breakpoints may use more than
8191 one register. */
8192 i += b.resources_needed (&bl);
8195 return i;
8198 /* Returns the resources B would use if it were a hardware
8199 watchpoint. */
8201 static int
8202 hw_watchpoint_use_count (struct breakpoint *b)
8204 int i = 0;
8206 if (!breakpoint_enabled (b))
8207 return 0;
8209 for (bp_location &bl : b->locations ())
8211 /* Special types of hardware watchpoints may use more than
8212 one register. */
8213 i += b->resources_needed (&bl);
8216 return i;
8219 /* Returns the sum the used resources of all hardware watchpoints of
8220 type TYPE in the breakpoints list. Also returns in OTHER_TYPE_USED
8221 the sum of the used resources of all hardware watchpoints of other
8222 types _not_ TYPE. */
8224 static int
8225 hw_watchpoint_used_count_others (struct breakpoint *except,
8226 enum bptype type, int *other_type_used)
8228 int i = 0;
8230 *other_type_used = 0;
8231 for (breakpoint &b : all_breakpoints ())
8233 if (&b == except)
8234 continue;
8235 if (!breakpoint_enabled (&b))
8236 continue;
8238 if (b.type == type)
8239 i += hw_watchpoint_use_count (&b);
8240 else if (is_hardware_watchpoint (&b))
8241 *other_type_used = 1;
8244 return i;
8247 void
8248 disable_watchpoints_before_interactive_call_start (void)
8250 for (breakpoint &b : all_breakpoints ())
8251 if (is_watchpoint (&b) && breakpoint_enabled (&b))
8253 b.enable_state = bp_call_disabled;
8254 update_global_location_list (UGLL_DONT_INSERT);
8258 void
8259 enable_watchpoints_after_interactive_call_stop (void)
8261 for (breakpoint &b : all_breakpoints ())
8262 if (is_watchpoint (&b) && b.enable_state == bp_call_disabled)
8264 b.enable_state = bp_enabled;
8265 update_global_location_list (UGLL_MAY_INSERT);
8269 void
8270 disable_breakpoints_before_startup (void)
8272 current_program_space->executing_startup = 1;
8273 update_global_location_list (UGLL_DONT_INSERT);
8276 void
8277 enable_breakpoints_after_startup (void)
8279 current_program_space->executing_startup = 0;
8280 breakpoint_re_set ();
8283 /* Allocate a new momentary breakpoint. */
8285 template<typename... Arg>
8286 static momentary_breakpoint *
8287 new_momentary_breakpoint (struct gdbarch *gdbarch, enum bptype type,
8288 Arg&&... args)
8290 if (type == bp_longjmp || type == bp_exception)
8291 return new longjmp_breakpoint (gdbarch, type,
8292 std::forward<Arg> (args)...);
8293 else
8294 return new momentary_breakpoint (gdbarch, type,
8295 std::forward<Arg> (args)...);
8298 /* Set a momentary breakpoint of type TYPE at address specified by
8299 SAL. If FRAME_ID is valid, the breakpoint is restricted to that
8300 frame. */
8302 breakpoint_up
8303 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8304 struct frame_id frame_id, enum bptype type)
8306 /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8307 tail-called one. */
8308 gdb_assert (!frame_id_artificial_p (frame_id));
8310 std::unique_ptr<momentary_breakpoint> b
8311 (new_momentary_breakpoint (gdbarch, type, sal.pspace, frame_id,
8312 inferior_thread ()->global_num));
8314 b->add_location (sal);
8316 breakpoint_up bp (add_to_breakpoint_chain (std::move (b)));
8318 update_global_location_list_nothrow (UGLL_MAY_INSERT);
8320 return bp;
8323 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8324 The new breakpoint will have type TYPE, use OPS as its
8325 breakpoint_ops, and will set enabled to LOC_ENABLED. */
8327 static struct breakpoint *
8328 momentary_breakpoint_from_master (struct breakpoint *orig,
8329 enum bptype type,
8330 int loc_enabled,
8331 int thread)
8333 std::unique_ptr<breakpoint> copy
8334 (new_momentary_breakpoint (orig->gdbarch, type, orig->pspace,
8335 orig->frame_id, thread));
8336 const bp_location &orig_loc = orig->first_loc ();
8337 bp_location *copy_loc = copy->allocate_location ();
8338 copy->add_location (*copy_loc);
8339 set_breakpoint_location_function (copy_loc);
8341 copy_loc->gdbarch = orig_loc.gdbarch;
8342 copy_loc->requested_address = orig_loc.requested_address;
8343 copy_loc->address = orig_loc.address;
8344 copy_loc->section = orig_loc.section;
8345 copy_loc->pspace = orig_loc.pspace;
8346 copy_loc->probe = orig_loc.probe;
8347 copy_loc->line_number = orig_loc.line_number;
8348 copy_loc->symtab = orig_loc.symtab;
8349 copy_loc->enabled = loc_enabled;
8351 breakpoint *b = add_to_breakpoint_chain (std::move (copy));
8352 update_global_location_list_nothrow (UGLL_DONT_INSERT);
8353 return b;
8356 /* Make a deep copy of momentary breakpoint ORIG. Returns NULL if
8357 ORIG is NULL. */
8359 struct breakpoint *
8360 clone_momentary_breakpoint (struct breakpoint *orig)
8362 /* If there's nothing to clone, then return nothing. */
8363 if (orig == NULL)
8364 return NULL;
8366 return momentary_breakpoint_from_master (orig, orig->type, 0,
8367 orig->thread);
8370 breakpoint_up
8371 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8372 enum bptype type)
8374 struct symtab_and_line sal;
8376 sal = find_pc_line (pc, 0);
8377 sal.pc = pc;
8378 sal.section = find_pc_overlay (pc);
8379 sal.explicit_pc = 1;
8381 return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8385 /* Tell the user we have just set a breakpoint B. */
8387 static void
8388 mention (const breakpoint *b)
8390 b->print_mention ();
8391 current_uiout->text ("\n");
8395 static bool bp_loc_is_permanent (struct bp_location *loc);
8397 /* Handle "set breakpoint auto-hw on".
8399 If the explicitly specified breakpoint type is not hardware
8400 breakpoint, check the memory map to see whether the breakpoint
8401 address is in read-only memory.
8403 - location type is not hardware breakpoint, memory is read-only.
8404 We change the type of the location to hardware breakpoint.
8406 - location type is hardware breakpoint, memory is read-write. This
8407 means we've previously made the location hardware one, but then the
8408 memory map changed, so we undo.
8411 static void
8412 handle_automatic_hardware_breakpoints (bp_location *bl)
8414 if (automatic_hardware_breakpoints
8415 && bl->owner->type != bp_hardware_breakpoint
8416 && (bl->loc_type == bp_loc_software_breakpoint
8417 || bl->loc_type == bp_loc_hardware_breakpoint))
8419 /* When breakpoints are removed, remove_breakpoints will use
8420 location types we've just set here, the only possible problem
8421 is that memory map has changed during running program, but
8422 it's not going to work anyway with current gdb. */
8423 mem_region *mr = lookup_mem_region (bl->address);
8425 if (mr != nullptr)
8427 enum bp_loc_type new_type;
8429 if (mr->attrib.mode != MEM_RW)
8430 new_type = bp_loc_hardware_breakpoint;
8431 else
8432 new_type = bp_loc_software_breakpoint;
8434 if (new_type != bl->loc_type)
8436 static bool said = false;
8438 bl->loc_type = new_type;
8439 if (!said)
8441 gdb_printf (_("Note: automatically using "
8442 "hardware breakpoints for "
8443 "read-only addresses.\n"));
8444 said = true;
8451 bp_location *
8452 code_breakpoint::add_location (const symtab_and_line &sal)
8454 CORE_ADDR adjusted_address;
8455 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8457 if (loc_gdbarch == NULL)
8458 loc_gdbarch = gdbarch;
8460 /* Adjust the breakpoint's address prior to allocating a location.
8461 Once we call allocate_location(), that mostly uninitialized
8462 location will be placed on the location chain. Adjustment of the
8463 breakpoint may cause target_read_memory() to be called and we do
8464 not want its scan of the location chain to find a breakpoint and
8465 location that's only been partially initialized. */
8466 adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8467 sal.pc, type,
8468 sal.pspace);
8470 /* Sort the locations by their ADDRESS. */
8471 bp_location *new_loc = this->allocate_location ();
8473 new_loc->requested_address = sal.pc;
8474 new_loc->address = adjusted_address;
8475 new_loc->pspace = sal.pspace;
8476 new_loc->probe.prob = sal.prob;
8477 new_loc->probe.objfile = sal.objfile;
8478 gdb_assert (new_loc->pspace != NULL);
8479 new_loc->section = sal.section;
8480 new_loc->gdbarch = loc_gdbarch;
8481 new_loc->line_number = sal.line;
8482 new_loc->symtab = sal.symtab;
8483 new_loc->symbol = sal.symbol;
8484 new_loc->msymbol = sal.msymbol;
8485 new_loc->objfile = sal.objfile;
8487 breakpoint::add_location (*new_loc);
8489 set_breakpoint_location_function (new_loc);
8491 /* While by definition, permanent breakpoints are already present in the
8492 code, we don't mark the location as inserted. Normally one would expect
8493 that GDB could rely on that breakpoint instruction to stop the program,
8494 thus removing the need to insert its own breakpoint, except that executing
8495 the breakpoint instruction can kill the target instead of reporting a
8496 SIGTRAP. E.g., on SPARC, when interrupts are disabled, executing the
8497 instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8498 with "Trap 0x02 while interrupts disabled, Error state". Letting the
8499 breakpoint be inserted normally results in QEMU knowing about the GDB
8500 breakpoint, and thus trap before the breakpoint instruction is executed.
8501 (If GDB later needs to continue execution past the permanent breakpoint,
8502 it manually increments the PC, thus avoiding executing the breakpoint
8503 instruction.) */
8504 if (bp_loc_is_permanent (new_loc))
8505 new_loc->permanent = 1;
8507 return new_loc;
8511 /* Return true if LOC is pointing to a permanent breakpoint,
8512 return false otherwise. */
8514 static bool
8515 bp_loc_is_permanent (struct bp_location *loc)
8517 gdb_assert (loc != NULL);
8519 /* If we have a non-breakpoint-backed catchpoint or a software
8520 watchpoint, just return 0. We should not attempt to read from
8521 the addresses the locations of these breakpoint types point to.
8522 gdbarch_program_breakpoint_here_p, below, will attempt to read
8523 memory. */
8524 if (!bl_address_is_meaningful (loc))
8525 return false;
8527 scoped_restore_current_pspace_and_thread restore_pspace_thread;
8528 switch_to_program_space_and_thread (loc->pspace);
8529 return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8532 /* Build a command list for the dprintf corresponding to the current
8533 settings of the dprintf style options. */
8535 static void
8536 update_dprintf_command_list (struct breakpoint *b)
8538 const char *dprintf_args = b->extra_string.get ();
8539 gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
8541 if (!dprintf_args)
8542 return;
8544 dprintf_args = skip_spaces (dprintf_args);
8546 /* Allow a comma, as it may have terminated a location, but don't
8547 insist on it. */
8548 if (*dprintf_args == ',')
8549 ++dprintf_args;
8550 dprintf_args = skip_spaces (dprintf_args);
8552 if (*dprintf_args != '"')
8553 error (_("Bad format string, missing '\"'."));
8555 if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8556 printf_line = xstrprintf ("printf %s", dprintf_args);
8557 else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8559 if (dprintf_function.empty ())
8560 error (_("No function supplied for dprintf call"));
8562 if (!dprintf_channel.empty ())
8563 printf_line = xstrprintf ("call (void) %s (%s,%s)",
8564 dprintf_function.c_str (),
8565 dprintf_channel.c_str (),
8566 dprintf_args);
8567 else
8568 printf_line = xstrprintf ("call (void) %s (%s)",
8569 dprintf_function.c_str (),
8570 dprintf_args);
8572 else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8574 if (target_can_run_breakpoint_commands ())
8575 printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8576 else
8578 warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8579 printf_line = xstrprintf ("printf %s", dprintf_args);
8582 else
8583 internal_error (_("Invalid dprintf style."));
8585 gdb_assert (printf_line != NULL);
8587 /* Manufacture a printf sequence. */
8588 struct command_line *printf_cmd_line
8589 = new struct command_line (simple_control, printf_line.release ());
8590 breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8591 command_lines_deleter ()));
8594 /* Update all dprintf commands, making their command lists reflect
8595 current style settings. */
8597 static void
8598 update_dprintf_commands (const char *args, int from_tty,
8599 struct cmd_list_element *c)
8601 for (breakpoint &b : all_breakpoints ())
8602 if (b.type == bp_dprintf)
8603 update_dprintf_command_list (&b);
8606 code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
8607 enum bptype type_,
8608 gdb::array_view<const symtab_and_line> sals,
8609 location_spec_up &&locspec_,
8610 gdb::unique_xmalloc_ptr<char> filter_,
8611 gdb::unique_xmalloc_ptr<char> cond_string_,
8612 gdb::unique_xmalloc_ptr<char> extra_string_,
8613 enum bpdisp disposition_,
8614 int thread_, int task_, int inferior_,
8615 int ignore_count_,
8616 int from_tty,
8617 int enabled_, unsigned flags,
8618 int display_canonical_)
8619 : breakpoint (gdbarch_, type_)
8621 int i;
8623 if (type == bp_hardware_breakpoint)
8625 int target_resources_ok;
8627 i = hw_breakpoint_used_count ();
8628 target_resources_ok =
8629 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8630 i + 1, 0);
8631 if (target_resources_ok == 0)
8632 error (_("No hardware breakpoint support in the target."));
8633 else if (target_resources_ok < 0)
8634 error (_("Hardware breakpoints used exceeds limit."));
8637 gdb_assert (!sals.empty ());
8639 /* At most one of thread, task, or inferior can be set on any breakpoint. */
8640 gdb_assert (((thread == -1 ? 0 : 1)
8641 + (task == -1 ? 0 : 1)
8642 + (inferior == -1 ? 0 : 1)) <= 1);
8644 thread = thread_;
8645 task = task_;
8646 inferior = inferior_;
8648 cond_string = std::move (cond_string_);
8649 extra_string = std::move (extra_string_);
8650 ignore_count = ignore_count_;
8651 enable_state = enabled_ ? bp_enabled : bp_disabled;
8652 disposition = disposition_;
8654 if (type == bp_static_tracepoint
8655 || type == bp_static_marker_tracepoint)
8657 auto *t = gdb::checked_static_cast<tracepoint *> (this);
8658 struct static_tracepoint_marker marker;
8660 if (strace_marker_p (this))
8662 /* We already know the marker exists, otherwise, we wouldn't
8663 see a sal for it. */
8664 const char *p = &locspec_->to_string ()[3];
8665 const char *endp;
8667 p = skip_spaces (p);
8669 endp = skip_to_space (p);
8671 t->static_trace_marker_id.assign (p, endp - p);
8673 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8674 t->static_trace_marker_id.c_str ());
8676 else if (target_static_tracepoint_marker_at (sals[0].pc, &marker))
8678 t->static_trace_marker_id = std::move (marker.str_id);
8680 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8681 t->static_trace_marker_id.c_str ());
8683 else
8684 warning (_("Couldn't determine the static tracepoint marker to probe"));
8687 for (const auto &sal : sals)
8689 if (from_tty)
8691 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8692 if (loc_gdbarch == nullptr)
8693 loc_gdbarch = gdbarch;
8695 describe_other_breakpoints (loc_gdbarch,
8696 sal.pspace, sal.pc, sal.section, thread);
8699 bp_location *new_loc = add_location (sal);
8700 if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8701 new_loc->inserted = 1;
8703 /* Do not set breakpoint locations conditions yet. As locations
8704 are inserted, they get sorted based on their addresses. Let
8705 the list stabilize to have reliable location numbers. */
8707 /* Dynamic printf requires and uses additional arguments on the
8708 command line, otherwise it's an error. */
8709 if (type == bp_dprintf)
8711 if (extra_string != nullptr)
8712 update_dprintf_command_list (this);
8713 else
8714 error (_("Format string required"));
8716 else if (extra_string != nullptr)
8717 error (_("Garbage '%s' at end of command"), extra_string.get ());
8720 /* The order of the locations is now stable. Set the location
8721 condition using the location's number. */
8722 int loc_num = 1;
8723 for (bp_location &bl : locations ())
8725 if (cond_string != nullptr)
8726 set_breakpoint_location_condition (cond_string.get (), &bl,
8727 number, loc_num);
8729 ++loc_num;
8732 display_canonical = display_canonical_;
8733 if (locspec_ != nullptr)
8734 locspec = std::move (locspec_);
8735 else
8736 locspec = new_address_location_spec (this->first_loc ().address, NULL, 0);
8737 filter = std::move (filter_);
8740 static void
8741 create_breakpoint_sal (struct gdbarch *gdbarch,
8742 gdb::array_view<const symtab_and_line> sals,
8743 location_spec_up &&locspec,
8744 gdb::unique_xmalloc_ptr<char> filter,
8745 gdb::unique_xmalloc_ptr<char> cond_string,
8746 gdb::unique_xmalloc_ptr<char> extra_string,
8747 enum bptype type, enum bpdisp disposition,
8748 int thread, int task, int inferior, int ignore_count,
8749 int from_tty,
8750 int enabled, int internal, unsigned flags,
8751 int display_canonical)
8753 std::unique_ptr<code_breakpoint> b
8754 = new_breakpoint_from_type (gdbarch,
8755 type,
8756 sals,
8757 std::move (locspec),
8758 std::move (filter),
8759 std::move (cond_string),
8760 std::move (extra_string),
8761 disposition,
8762 thread, task, inferior, ignore_count,
8763 from_tty,
8764 enabled, flags,
8765 display_canonical);
8767 install_breakpoint (internal, std::move (b), 0);
8770 /* Add SALS.nelts breakpoints to the breakpoint table. For each
8771 SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8772 value. COND_STRING, if not NULL, specified the condition to be
8773 used for all breakpoints. Essentially the only case where
8774 SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8775 function. In that case, it's still not possible to specify
8776 separate conditions for different overloaded functions, so
8777 we take just a single condition string.
8779 NOTE: If the function succeeds, the caller is expected to cleanup
8780 the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8781 array contents). If the function fails (error() is called), the
8782 caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8783 COND and SALS arrays and each of those arrays contents. */
8785 static void
8786 create_breakpoints_sal (struct gdbarch *gdbarch,
8787 struct linespec_result *canonical,
8788 gdb::unique_xmalloc_ptr<char> cond_string,
8789 gdb::unique_xmalloc_ptr<char> extra_string,
8790 enum bptype type, enum bpdisp disposition,
8791 int thread, int task, int inferior,
8792 int ignore_count,
8793 int from_tty,
8794 int enabled, int internal, unsigned flags)
8796 if (canonical->pre_expanded)
8797 gdb_assert (canonical->lsals.size () == 1);
8799 for (const auto &lsal : canonical->lsals)
8801 /* Note that 'location' can be NULL in the case of a plain
8802 'break', without arguments. */
8803 location_spec_up locspec
8804 = (canonical->locspec != nullptr
8805 ? canonical->locspec->clone ()
8806 : nullptr);
8807 gdb::unique_xmalloc_ptr<char> filter_string
8808 (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8810 create_breakpoint_sal (gdbarch, lsal.sals,
8811 std::move (locspec),
8812 std::move (filter_string),
8813 std::move (cond_string),
8814 std::move (extra_string),
8815 type, disposition,
8816 thread, task, inferior, ignore_count,
8817 from_tty, enabled, internal, flags,
8818 canonical->special_display);
8822 /* Parse LOCSPEC which is assumed to be a SAL specification possibly
8823 followed by conditionals. On return, SALS contains an array of SAL
8824 addresses found. LOCSPEC points to the end of the SAL (for
8825 linespec locspecs).
8827 The array and the line spec strings are allocated on the heap, it is
8828 the caller's responsibility to free them. */
8830 static void
8831 parse_breakpoint_sals (location_spec *locspec,
8832 struct linespec_result *canonical)
8834 struct symtab_and_line cursal;
8836 if (locspec->type () == LINESPEC_LOCATION_SPEC)
8838 const char *spec = as_linespec_location_spec (locspec)->spec_string;
8840 if (spec == NULL)
8842 /* The last displayed codepoint, if it's valid, is our default
8843 breakpoint address. */
8844 if (last_displayed_sal_is_valid ())
8846 /* Set sal's pspace, pc, symtab, and line to the values
8847 corresponding to the last call to print_frame_info.
8848 Be sure to reinitialize LINE with NOTCURRENT == 0
8849 as the breakpoint line number is inappropriate otherwise.
8850 find_pc_line would adjust PC, re-set it back. */
8851 symtab_and_line sal = get_last_displayed_sal ();
8852 CORE_ADDR pc = sal.pc;
8854 sal = find_pc_line (pc, 0);
8856 /* "break" without arguments is equivalent to "break *PC"
8857 where PC is the last displayed codepoint's address. So
8858 make sure to set sal.explicit_pc to prevent GDB from
8859 trying to expand the list of sals to include all other
8860 instances with the same symtab and line. */
8861 sal.pc = pc;
8862 sal.explicit_pc = 1;
8864 struct linespec_sals lsal;
8865 lsal.sals = {sal};
8866 lsal.canonical = NULL;
8868 canonical->lsals.push_back (std::move (lsal));
8869 return;
8871 else
8872 error (_("No default breakpoint address now."));
8876 /* Force almost all breakpoints to be in terms of the
8877 current_source_symtab (which is decode_line_1's default).
8878 This should produce the results we want almost all of the
8879 time while leaving default_breakpoint_* alone.
8881 ObjC: However, don't match an Objective-C method name which
8882 may have a '+' or '-' succeeded by a '['. */
8883 cursal = get_current_source_symtab_and_line ();
8884 if (last_displayed_sal_is_valid ())
8886 const char *spec = NULL;
8888 if (locspec->type () == LINESPEC_LOCATION_SPEC)
8889 spec = as_linespec_location_spec (locspec)->spec_string;
8891 if (!cursal.symtab
8892 || (spec != NULL
8893 && strchr ("+-", spec[0]) != NULL
8894 && spec[1] != '['))
8896 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8897 get_last_displayed_symtab (),
8898 get_last_displayed_line (),
8899 canonical, NULL, NULL);
8900 return;
8904 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8905 cursal.symtab, cursal.line, canonical, NULL, NULL);
8909 /* Convert each SAL into a real PC. Verify that the PC can be
8910 inserted as a breakpoint. If it can't throw an error. */
8912 static void
8913 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
8915 for (auto &sal : sals)
8916 resolve_sal_pc (&sal);
8919 /* Fast tracepoints may have restrictions on valid locations. For
8920 instance, a fast tracepoint using a jump instead of a trap will
8921 likely have to overwrite more bytes than a trap would, and so can
8922 only be placed where the instruction is longer than the jump, or a
8923 multi-instruction sequence does not have a jump into the middle of
8924 it, etc. */
8926 static void
8927 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8928 gdb::array_view<const symtab_and_line> sals)
8930 for (const auto &sal : sals)
8932 struct gdbarch *sarch;
8934 sarch = get_sal_arch (sal);
8935 /* We fall back to GDBARCH if there is no architecture
8936 associated with SAL. */
8937 if (sarch == NULL)
8938 sarch = gdbarch;
8939 std::string msg;
8940 if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
8941 error (_("May not have a fast tracepoint at %s%s"),
8942 paddress (sarch, sal.pc), msg.c_str ());
8946 /* Given TOK, a string specification of condition and thread, as accepted
8947 by the 'break' command, extract the condition string into *COND_STRING.
8948 If no condition string is found then *COND_STRING is set to nullptr.
8950 If the breakpoint specification has an associated thread, task, or
8951 inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
8952 respectively, otherwise these arguments are set to -1 (for THREAD and
8953 INFERIOR) or 0 (for TASK).
8955 PC identifies the context at which the condition should be parsed. */
8957 static void
8958 find_condition_and_thread (const char *tok, CORE_ADDR pc,
8959 gdb::unique_xmalloc_ptr<char> *cond_string,
8960 int *thread, int *inferior, int *task,
8961 gdb::unique_xmalloc_ptr<char> *rest)
8963 cond_string->reset ();
8964 *thread = -1;
8965 *inferior = -1;
8966 *task = -1;
8967 rest->reset ();
8968 bool force = false;
8970 while (tok && *tok)
8972 const char *end_tok;
8973 int toklen;
8974 const char *cond_start = NULL;
8975 const char *cond_end = NULL;
8977 tok = skip_spaces (tok);
8979 if ((*tok == '"' || *tok == ',') && rest)
8981 rest->reset (savestring (tok, strlen (tok)));
8982 break;
8985 end_tok = skip_to_space (tok);
8987 toklen = end_tok - tok;
8989 if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8991 tok = cond_start = end_tok + 1;
8994 parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
8996 catch (const gdb_exception_error &)
8998 if (!force)
8999 throw;
9000 else
9001 tok = tok + strlen (tok);
9003 cond_end = tok;
9004 cond_string->reset (savestring (cond_start, cond_end - cond_start));
9006 else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
9008 tok = tok + toklen;
9009 force = true;
9011 else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9013 const char *tmptok;
9014 struct thread_info *thr;
9016 if (*thread != -1)
9017 error(_("You can specify only one thread."));
9019 if (*task != -1)
9020 error (_("You can specify only one of thread or task."));
9022 if (*inferior != -1)
9023 error (_("You can specify only one of inferior or thread."));
9025 tok = end_tok + 1;
9026 thr = parse_thread_id (tok, &tmptok);
9027 if (tok == tmptok)
9028 error (_("Junk after thread keyword."));
9029 *thread = thr->global_num;
9030 tok = tmptok;
9032 else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
9034 if (*inferior != -1)
9035 error(_("You can specify only one inferior."));
9037 if (*task != -1)
9038 error (_("You can specify only one of inferior or task."));
9040 if (*thread != -1)
9041 error (_("You can specify only one of inferior or thread."));
9043 char *tmptok;
9044 tok = end_tok + 1;
9045 *inferior = strtol (tok, &tmptok, 0);
9046 if (tok == tmptok)
9047 error (_("Junk after inferior keyword."));
9048 if (!valid_global_inferior_id (*inferior))
9049 error (_("Unknown inferior number %d."), *inferior);
9050 tok = tmptok;
9052 else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9054 char *tmptok;
9056 if (*task != -1)
9057 error(_("You can specify only one task."));
9059 if (*thread != -1)
9060 error (_("You can specify only one of thread or task."));
9062 if (*inferior != -1)
9063 error (_("You can specify only one of inferior or task."));
9065 tok = end_tok + 1;
9066 *task = strtol (tok, &tmptok, 0);
9067 if (tok == tmptok)
9068 error (_("Junk after task keyword."));
9069 if (!valid_task_id (*task))
9070 error (_("Unknown task %d."), *task);
9071 tok = tmptok;
9073 else if (rest)
9075 rest->reset (savestring (tok, strlen (tok)));
9076 break;
9078 else
9079 error (_("Junk at end of arguments."));
9083 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
9084 succeeds. The parsed values are written to COND_STRING, THREAD,
9085 TASK, and REST. See the comment of 'find_condition_and_thread'
9086 for the description of these parameters and INPUT. */
9088 static void
9089 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
9090 const char *input,
9091 gdb::unique_xmalloc_ptr<char> *cond_string,
9092 int *thread, int *inferior, int *task,
9093 gdb::unique_xmalloc_ptr<char> *rest)
9095 int num_failures = 0;
9096 for (auto &sal : sals)
9098 gdb::unique_xmalloc_ptr<char> cond;
9099 int thread_id = -1;
9100 int inferior_id = -1;
9101 int task_id = -1;
9102 gdb::unique_xmalloc_ptr<char> remaining;
9104 /* Here we want to parse 'arg' to separate condition from thread
9105 number. But because parsing happens in a context and the
9106 contexts of sals might be different, try each until there is
9107 success. Finding one successful parse is sufficient for our
9108 goal. When setting the breakpoint we'll re-parse the
9109 condition in the context of each sal. */
9112 find_condition_and_thread (input, sal.pc, &cond, &thread_id,
9113 &inferior_id, &task_id, &remaining);
9114 *cond_string = std::move (cond);
9115 /* A value of -1 indicates that these fields are unset. At most
9116 one of these fields should be set (to a value other than -1)
9117 at this point. */
9118 gdb_assert (((thread_id == -1 ? 1 : 0)
9119 + (task_id == -1 ? 1 : 0)
9120 + (inferior_id == -1 ? 1 : 0)) >= 2);
9121 *thread = thread_id;
9122 *inferior = inferior_id;
9123 *task = task_id;
9124 *rest = std::move (remaining);
9125 break;
9127 catch (const gdb_exception_error &e)
9129 num_failures++;
9130 /* If no sal remains, do not continue. */
9131 if (num_failures == sals.size ())
9132 throw;
9137 /* Decode a static tracepoint marker spec. */
9139 static std::vector<symtab_and_line>
9140 decode_static_tracepoint_spec (const char **arg_p)
9142 const char *p = &(*arg_p)[3];
9143 const char *endp;
9145 p = skip_spaces (p);
9147 endp = skip_to_space (p);
9149 std::string marker_str (p, endp - p);
9151 std::vector<static_tracepoint_marker> markers
9152 = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9153 if (markers.empty ())
9154 error (_("No known static tracepoint marker named %s"),
9155 marker_str.c_str ());
9157 std::vector<symtab_and_line> sals;
9158 sals.reserve (markers.size ());
9160 for (const static_tracepoint_marker &marker : markers)
9162 symtab_and_line sal = find_pc_line (marker.address, 0);
9163 sal.pc = marker.address;
9164 sals.push_back (sal);
9167 *arg_p = endp;
9168 return sals;
9171 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
9172 according to IS_TRACEPOINT. */
9174 static const struct breakpoint_ops *
9175 breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
9176 bool is_tracepoint)
9178 if (is_tracepoint)
9180 if (locspec_type == PROBE_LOCATION_SPEC)
9181 return &tracepoint_probe_breakpoint_ops;
9182 else
9183 return &code_breakpoint_ops;
9185 else
9187 if (locspec_type == PROBE_LOCATION_SPEC)
9188 return &bkpt_probe_breakpoint_ops;
9189 else
9190 return &code_breakpoint_ops;
9194 /* See breakpoint.h. */
9196 const struct breakpoint_ops *
9197 breakpoint_ops_for_location_spec (const location_spec *locspec,
9198 bool is_tracepoint)
9200 if (locspec != nullptr)
9201 return (breakpoint_ops_for_location_spec_type
9202 (locspec->type (), is_tracepoint));
9203 return &code_breakpoint_ops;
9206 /* See breakpoint.h. */
9209 create_breakpoint (struct gdbarch *gdbarch,
9210 location_spec *locspec,
9211 const char *cond_string,
9212 int thread, int inferior,
9213 const char *extra_string,
9214 bool force_condition, int parse_extra,
9215 int tempflag, enum bptype type_wanted,
9216 int ignore_count,
9217 enum auto_boolean pending_break_support,
9218 const struct breakpoint_ops *ops,
9219 int from_tty, int enabled, int internal,
9220 unsigned flags)
9222 struct linespec_result canonical;
9223 bool pending = false;
9224 int task = -1;
9225 int prev_bkpt_count = breakpoint_count;
9227 gdb_assert (thread == -1 || thread > 0);
9228 gdb_assert (inferior == -1 || inferior > 0);
9229 gdb_assert (thread == -1 || inferior == -1);
9231 gdb_assert (ops != NULL);
9233 /* If extra_string isn't useful, set it to NULL. */
9234 if (extra_string != NULL && *extra_string == '\0')
9235 extra_string = NULL;
9239 ops->create_sals_from_location_spec (locspec, &canonical);
9241 catch (const gdb_exception_error &e)
9243 /* If caller is interested in rc value from parse, set
9244 value. */
9245 if (e.error == NOT_FOUND_ERROR)
9247 /* If pending breakpoint support is turned off, throw
9248 error. */
9250 if (pending_break_support == AUTO_BOOLEAN_FALSE)
9251 throw;
9253 exception_print (gdb_stderr, e);
9255 /* If pending breakpoint support is auto query and the user
9256 selects no, then simply return the error code. */
9257 if (pending_break_support == AUTO_BOOLEAN_AUTO
9258 && !nquery (_("Make %s pending on future shared library load? "),
9259 bptype_string (type_wanted)))
9260 return 0;
9262 /* At this point, either the user was queried about setting
9263 a pending breakpoint and selected yes, or pending
9264 breakpoint behavior is on and thus a pending breakpoint
9265 is defaulted on behalf of the user. */
9266 pending = true;
9268 else
9269 throw;
9272 if (!pending && canonical.lsals.empty ())
9273 return 0;
9275 /* Resolve all line numbers to PC's and verify that the addresses
9276 are ok for the target. */
9277 if (!pending)
9279 for (auto &lsal : canonical.lsals)
9280 breakpoint_sals_to_pc (lsal.sals);
9283 /* Fast tracepoints may have additional restrictions on location. */
9284 if (!pending && type_wanted == bp_fast_tracepoint)
9286 for (const auto &lsal : canonical.lsals)
9287 check_fast_tracepoint_sals (gdbarch, lsal.sals);
9290 /* Verify that condition can be parsed, before setting any
9291 breakpoints. Allocate a separate condition expression for each
9292 breakpoint. */
9293 if (!pending)
9295 gdb::unique_xmalloc_ptr<char> cond_string_copy;
9296 gdb::unique_xmalloc_ptr<char> extra_string_copy;
9298 if (parse_extra)
9300 gdb::unique_xmalloc_ptr<char> rest;
9301 gdb::unique_xmalloc_ptr<char> cond;
9303 const linespec_sals &lsal = canonical.lsals[0];
9305 find_condition_and_thread_for_sals (lsal.sals, extra_string,
9306 &cond, &thread, &inferior,
9307 &task, &rest);
9308 cond_string_copy = std::move (cond);
9309 extra_string_copy = std::move (rest);
9311 else
9313 if (type_wanted != bp_dprintf
9314 && extra_string != NULL && *extra_string != '\0')
9315 error (_("Garbage '%s' at end of location"), extra_string);
9317 /* Check the validity of the condition. We should error out
9318 if the condition is invalid at all of the locations and
9319 if it is not forced. In the PARSE_EXTRA case above, this
9320 check is done when parsing the EXTRA_STRING. */
9321 if (cond_string != nullptr && !force_condition)
9323 int num_failures = 0;
9324 const linespec_sals &lsal = canonical.lsals[0];
9325 for (const auto &sal : lsal.sals)
9327 const char *cond = cond_string;
9330 parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
9331 /* One success is sufficient to keep going. */
9332 break;
9334 catch (const gdb_exception_error &)
9336 num_failures++;
9337 /* If this is the last sal, error out. */
9338 if (num_failures == lsal.sals.size ())
9339 throw;
9344 /* Create a private copy of condition string. */
9345 if (cond_string)
9346 cond_string_copy.reset (xstrdup (cond_string));
9347 /* Create a private copy of any extra string. */
9348 if (extra_string)
9349 extra_string_copy.reset (xstrdup (extra_string));
9352 ops->create_breakpoints_sal (gdbarch, &canonical,
9353 std::move (cond_string_copy),
9354 std::move (extra_string_copy),
9355 type_wanted,
9356 tempflag ? disp_del : disp_donttouch,
9357 thread, task, inferior, ignore_count,
9358 from_tty, enabled, internal, flags);
9360 else
9362 std::unique_ptr <breakpoint> b = new_breakpoint_from_type (gdbarch,
9363 type_wanted);
9364 b->locspec = locspec->clone ();
9366 if (parse_extra)
9367 b->cond_string = NULL;
9368 else
9370 /* Create a private copy of condition string. */
9371 b->cond_string.reset (cond_string != NULL
9372 ? xstrdup (cond_string)
9373 : NULL);
9374 b->thread = thread;
9377 /* Create a private copy of any extra string. */
9378 b->extra_string.reset (extra_string != NULL
9379 ? xstrdup (extra_string)
9380 : NULL);
9381 b->ignore_count = ignore_count;
9382 b->disposition = tempflag ? disp_del : disp_donttouch;
9383 b->condition_not_parsed = 1;
9384 b->enable_state = enabled ? bp_enabled : bp_disabled;
9385 if ((type_wanted != bp_breakpoint
9386 && type_wanted != bp_hardware_breakpoint) || thread != -1)
9387 b->pspace = current_program_space;
9389 install_breakpoint (internal, std::move (b), 0);
9392 if (canonical.lsals.size () > 1)
9394 warning (_("Multiple breakpoints were set.\nUse the "
9395 "\"delete\" command to delete unwanted breakpoints."));
9396 prev_breakpoint_count = prev_bkpt_count;
9399 update_global_location_list (UGLL_MAY_INSERT);
9401 return 1;
9404 /* Set a breakpoint.
9405 ARG is a string describing breakpoint address,
9406 condition, and thread.
9407 FLAG specifies if a breakpoint is hardware on,
9408 and if breakpoint is temporary, using BP_HARDWARE_FLAG
9409 and BP_TEMPFLAG. */
9411 static void
9412 break_command_1 (const char *arg, int flag, int from_tty)
9414 int tempflag = flag & BP_TEMPFLAG;
9415 enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9416 ? bp_hardware_breakpoint
9417 : bp_breakpoint);
9419 location_spec_up locspec = string_to_location_spec (&arg, current_language);
9420 const struct breakpoint_ops *ops
9421 = breakpoint_ops_for_location_spec (locspec.get (),
9422 false /* is_tracepoint */);
9424 create_breakpoint (get_current_arch (),
9425 locspec.get (),
9426 NULL,
9427 -1 /* thread */, -1 /* inferior */,
9428 arg, false, 1 /* parse arg */,
9429 tempflag, type_wanted,
9430 0 /* Ignore count */,
9431 pending_break_support,
9432 ops,
9433 from_tty,
9434 1 /* enabled */,
9435 0 /* internal */,
9439 /* Helper function for break_command_1 and disassemble_command. */
9441 void
9442 resolve_sal_pc (struct symtab_and_line *sal)
9444 CORE_ADDR pc;
9446 if (sal->pc == 0 && sal->symtab != NULL)
9448 if (!find_line_pc (sal->symtab, sal->line, &pc))
9449 error (_("No line %d in file \"%s\"."),
9450 sal->line, symtab_to_filename_for_display (sal->symtab));
9451 sal->pc = pc;
9453 /* If this SAL corresponds to a breakpoint inserted using a line
9454 number, then skip the function prologue if necessary. */
9455 if (sal->explicit_line)
9456 skip_prologue_sal (sal);
9459 if (sal->section == 0 && sal->symtab != NULL)
9461 const struct blockvector *bv;
9462 const struct block *b;
9463 struct symbol *sym;
9465 bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9466 sal->symtab->compunit ());
9467 if (bv != NULL)
9469 sym = b->linkage_function ();
9470 if (sym != NULL)
9471 sal->section
9472 = sym->obj_section (sal->symtab->compunit ()->objfile ());
9473 else
9475 /* It really is worthwhile to have the section, so we'll
9476 just have to look harder. This case can be executed
9477 if we have line numbers but no functions (as can
9478 happen in assembly source). */
9480 scoped_restore_current_pspace_and_thread restore_pspace_thread;
9481 switch_to_program_space_and_thread (sal->pspace);
9483 bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9484 if (msym.minsym)
9485 sal->section = msym.obj_section ();
9491 void
9492 break_command (const char *arg, int from_tty)
9494 break_command_1 (arg, 0, from_tty);
9497 void
9498 tbreak_command (const char *arg, int from_tty)
9500 break_command_1 (arg, BP_TEMPFLAG, from_tty);
9503 static void
9504 hbreak_command (const char *arg, int from_tty)
9506 break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9509 static void
9510 thbreak_command (const char *arg, int from_tty)
9512 break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9515 /* The dynamic printf command is mostly like a regular breakpoint, but
9516 with a prewired command list consisting of a single output command,
9517 built from extra arguments supplied on the dprintf command
9518 line. */
9520 static void
9521 dprintf_command (const char *arg, int from_tty)
9523 location_spec_up locspec = string_to_location_spec (&arg, current_language);
9525 /* If non-NULL, ARG should have been advanced past the location;
9526 the next character must be ','. */
9527 if (arg != NULL)
9529 if (arg[0] != ',' || arg[1] == '\0')
9530 error (_("Format string required"));
9531 else
9533 /* Skip the comma. */
9534 ++arg;
9538 create_breakpoint (get_current_arch (),
9539 locspec.get (),
9540 NULL, -1, -1,
9541 arg, false, 1 /* parse arg */,
9542 0, bp_dprintf,
9543 0 /* Ignore count */,
9544 pending_break_support,
9545 &code_breakpoint_ops,
9546 from_tty,
9547 1 /* enabled */,
9548 0 /* internal */,
9552 static void
9553 agent_printf_command (const char *arg, int from_tty)
9555 error (_("May only run agent-printf on the target"));
9558 /* Implement the "breakpoint_hit" method for ranged breakpoints. */
9561 ranged_breakpoint::breakpoint_hit (const struct bp_location *bl,
9562 const address_space *aspace,
9563 CORE_ADDR bp_addr,
9564 const target_waitstatus &ws)
9566 if (ws.kind () != TARGET_WAITKIND_STOPPED
9567 || ws.sig () != GDB_SIGNAL_TRAP)
9568 return 0;
9570 return breakpoint_address_match_range (bl->pspace->aspace.get (),
9571 bl->address, bl->length, aspace,
9572 bp_addr);
9575 /* Implement the "resources_needed" method for ranged breakpoints. */
9578 ranged_breakpoint::resources_needed (const struct bp_location *bl)
9580 return target_ranged_break_num_registers ();
9583 /* Implement the "print_it" method for ranged breakpoints. */
9585 enum print_stop_action
9586 ranged_breakpoint::print_it (const bpstat *bs) const
9588 struct ui_out *uiout = current_uiout;
9590 gdb_assert (type == bp_hardware_breakpoint);
9592 /* Ranged breakpoints have only one location. */
9593 gdb_assert (this->has_single_location ());
9595 annotate_breakpoint (number);
9597 maybe_print_thread_hit_breakpoint (uiout);
9599 if (disposition == disp_del)
9600 uiout->text ("Temporary ranged breakpoint ");
9601 else
9602 uiout->text ("Ranged breakpoint ");
9603 if (uiout->is_mi_like_p ())
9605 uiout->field_string ("reason",
9606 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9607 uiout->field_string ("disp", bpdisp_text (disposition));
9609 print_num_locno (bs, uiout);
9610 uiout->text (", ");
9612 return PRINT_SRC_AND_LOC;
9615 /* Implement the "print_one" method for ranged breakpoints. */
9617 bool
9618 ranged_breakpoint::print_one (const bp_location **last_loc) const
9620 struct value_print_options opts;
9621 struct ui_out *uiout = current_uiout;
9623 /* Ranged breakpoints have only one location. */
9624 gdb_assert (this->has_single_location ());
9626 get_user_print_options (&opts);
9628 if (opts.addressprint)
9629 /* We don't print the address range here, it will be printed later
9630 by ranged_breakpoint::print_one_detail. */
9631 uiout->field_skip ("addr");
9632 annotate_field (5);
9633 print_breakpoint_location (this, &this->first_loc ());
9634 *last_loc = &this->first_loc ();
9636 return true;
9639 /* Implement the "print_one_detail" method for ranged breakpoints. */
9641 void
9642 ranged_breakpoint::print_one_detail (struct ui_out *uiout) const
9644 CORE_ADDR address_start, address_end;
9645 const bp_location &bl = this->first_loc ();
9646 string_file stb;
9648 address_start = bl.address;
9649 address_end = address_start + bl.length - 1;
9651 uiout->text ("\taddress range: ");
9652 stb.printf ("[%s, %s]",
9653 print_core_address (bl.gdbarch, address_start),
9654 print_core_address (bl.gdbarch, address_end));
9655 uiout->field_stream ("addr", stb);
9656 uiout->text ("\n");
9659 /* Implement the "print_mention" method for ranged breakpoints. */
9661 void
9662 ranged_breakpoint::print_mention () const
9664 const bp_location &bl = this->first_loc ();
9665 struct ui_out *uiout = current_uiout;
9667 gdb_assert (type == bp_hardware_breakpoint);
9669 uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9670 number, paddress (bl.gdbarch, bl.address),
9671 paddress (bl.gdbarch, bl.address + bl.length - 1));
9674 /* Implement the "print_recreate" method for ranged breakpoints. */
9676 void
9677 ranged_breakpoint::print_recreate (struct ui_file *fp) const
9679 gdb_printf (fp, "break-range %s, %s",
9680 locspec->to_string (),
9681 locspec_range_end->to_string ());
9682 print_recreate_thread (fp);
9685 /* Find the address where the end of the breakpoint range should be
9686 placed, given the SAL of the end of the range. This is so that if
9687 the user provides a line number, the end of the range is set to the
9688 last instruction of the given line. */
9690 static CORE_ADDR
9691 find_breakpoint_range_end (struct symtab_and_line sal)
9693 CORE_ADDR end;
9695 /* If the user provided a PC value, use it. Otherwise,
9696 find the address of the end of the given location. */
9697 if (sal.explicit_pc)
9698 end = sal.pc;
9699 else
9701 int ret;
9702 CORE_ADDR start;
9704 ret = find_line_pc_range (sal, &start, &end);
9705 if (!ret)
9706 error (_("Could not find location of the end of the range."));
9708 /* find_line_pc_range returns the start of the next line. */
9709 end--;
9712 return end;
9715 /* Implement the "break-range" CLI command. */
9717 static void
9718 break_range_command (const char *arg, int from_tty)
9720 const char *arg_start;
9721 struct linespec_result canonical_start, canonical_end;
9722 int bp_count, can_use_bp, length;
9723 CORE_ADDR end;
9725 /* We don't support software ranged breakpoints. */
9726 if (target_ranged_break_num_registers () < 0)
9727 error (_("This target does not support hardware ranged breakpoints."));
9729 bp_count = hw_breakpoint_used_count ();
9730 bp_count += target_ranged_break_num_registers ();
9731 can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9732 bp_count, 0);
9733 if (can_use_bp < 0)
9734 error (_("Hardware breakpoints used exceeds limit."));
9736 arg = skip_spaces (arg);
9737 if (arg == NULL || arg[0] == '\0')
9738 error(_("No address range specified."));
9740 arg_start = arg;
9741 location_spec_up start_locspec
9742 = string_to_location_spec (&arg, current_language);
9743 parse_breakpoint_sals (start_locspec.get (), &canonical_start);
9745 if (arg[0] != ',')
9746 error (_("Too few arguments."));
9747 else if (canonical_start.lsals.empty ())
9748 error (_("Could not find location of the beginning of the range."));
9750 const linespec_sals &lsal_start = canonical_start.lsals[0];
9752 if (canonical_start.lsals.size () > 1
9753 || lsal_start.sals.size () != 1)
9754 error (_("Cannot create a ranged breakpoint with multiple locations."));
9756 const symtab_and_line &sal_start = lsal_start.sals[0];
9757 std::string addr_string_start (arg_start, arg - arg_start);
9759 arg++; /* Skip the comma. */
9760 arg = skip_spaces (arg);
9762 /* Parse the end location specification. */
9764 arg_start = arg;
9766 /* We call decode_line_full directly here instead of using
9767 parse_breakpoint_sals because we need to specify the start
9768 location spec's symtab and line as the default symtab and line
9769 for the end of the range. This makes it possible to have ranges
9770 like "foo.c:27, +14", where +14 means 14 lines from the start
9771 location spec. */
9772 location_spec_up end_locspec
9773 = string_to_location_spec (&arg, current_language);
9774 decode_line_full (end_locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9775 sal_start.symtab, sal_start.line,
9776 &canonical_end, NULL, NULL);
9778 if (canonical_end.lsals.empty ())
9779 error (_("Could not find location of the end of the range."));
9781 const linespec_sals &lsal_end = canonical_end.lsals[0];
9782 if (canonical_end.lsals.size () > 1
9783 || lsal_end.sals.size () != 1)
9784 error (_("Cannot create a ranged breakpoint with multiple locations."));
9786 const symtab_and_line &sal_end = lsal_end.sals[0];
9788 end = find_breakpoint_range_end (sal_end);
9789 if (sal_start.pc > end)
9790 error (_("Invalid address range, end precedes start."));
9792 length = end - sal_start.pc + 1;
9793 if (length < 0)
9794 /* Length overflowed. */
9795 error (_("Address range too large."));
9796 else if (length == 1)
9798 /* This range is simple enough to be handled by
9799 the `hbreak' command. */
9800 hbreak_command (&addr_string_start[0], 1);
9802 return;
9805 /* Now set up the breakpoint and install it. */
9807 std::unique_ptr<breakpoint> br
9808 (new ranged_breakpoint (get_current_arch (),
9809 sal_start, length,
9810 std::move (start_locspec),
9811 std::move (end_locspec)));
9813 install_breakpoint (false, std::move (br), true);
9816 /* See breakpoint.h. */
9818 watchpoint::~watchpoint ()
9820 /* Make sure to unlink the destroyed watchpoint from the related
9821 breakpoint ring. */
9823 breakpoint *bpt = this;
9824 while (bpt->related_breakpoint != this)
9825 bpt = bpt->related_breakpoint;
9827 bpt->related_breakpoint = this->related_breakpoint;
9830 /* Return non-zero if EXP is verified as constant. Returned zero
9831 means EXP is variable. Also the constant detection may fail for
9832 some constant expressions and in such case still falsely return
9833 zero. */
9835 static bool
9836 watchpoint_exp_is_const (const struct expression *exp)
9838 return exp->op->constant_p ();
9841 /* Implement the "re_set" method for watchpoints. */
9843 void
9844 watchpoint::re_set ()
9846 /* Watchpoint can be either on expression using entirely global
9847 variables, or it can be on local variables.
9849 Watchpoints of the first kind are never auto-deleted, and even
9850 persist across program restarts. Since they can use variables
9851 from shared libraries, we need to reparse expression as libraries
9852 are loaded and unloaded.
9854 Watchpoints on local variables can also change meaning as result
9855 of solib event. For example, if a watchpoint uses both a local
9856 and a global variables in expression, it's a local watchpoint,
9857 but unloading of a shared library will make the expression
9858 invalid. This is not a very common use case, but we still
9859 re-evaluate expression, to avoid surprises to the user.
9861 Note that for local watchpoints, we re-evaluate it only if
9862 watchpoints frame id is still valid. If it's not, it means the
9863 watchpoint is out of scope and will be deleted soon. In fact,
9864 I'm not sure we'll ever be called in this case.
9866 If a local watchpoint's frame id is still valid, then
9867 exp_valid_block is likewise valid, and we can safely use it.
9869 Don't do anything about disabled watchpoints, since they will be
9870 reevaluated again when enabled. */
9871 update_watchpoint (this, true /* reparse */);
9874 /* Implement the "insert" method for hardware watchpoints. */
9877 watchpoint::insert_location (struct bp_location *bl)
9879 int length = exact ? 1 : bl->length;
9881 return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9882 cond_exp.get ());
9885 /* Implement the "remove" method for hardware watchpoints. */
9888 watchpoint::remove_location (struct bp_location *bl,
9889 enum remove_bp_reason reason)
9891 int length = exact ? 1 : bl->length;
9893 return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9894 cond_exp.get ());
9898 watchpoint::breakpoint_hit (const struct bp_location *bl,
9899 const address_space *aspace, CORE_ADDR bp_addr,
9900 const target_waitstatus &ws)
9902 struct breakpoint *b = bl->owner;
9904 /* Continuable hardware watchpoints are treated as non-existent if the
9905 reason we stopped wasn't a hardware watchpoint (we didn't stop on
9906 some data address). Otherwise gdb won't stop on a break instruction
9907 in the code (not from a breakpoint) when a hardware watchpoint has
9908 been defined. Also skip watchpoints which we know did not trigger
9909 (did not match the data address). */
9910 if (is_hardware_watchpoint (b)
9911 && watchpoint_triggered == watch_triggered_no)
9912 return 0;
9914 return 1;
9917 void
9918 watchpoint::check_status (bpstat *bs)
9920 bpstat_check_watchpoint (bs);
9923 /* Implement the "resources_needed" method for hardware
9924 watchpoints. */
9927 watchpoint::resources_needed (const struct bp_location *bl)
9929 int length = exact? 1 : bl->length;
9931 return target_region_ok_for_hw_watchpoint (bl->address, length);
9934 /* Implement the "works_in_software_mode" method for hardware
9935 watchpoints. */
9937 bool
9938 watchpoint::works_in_software_mode () const
9940 /* Read and access watchpoints only work with hardware support. */
9941 return type == bp_watchpoint || type == bp_hardware_watchpoint;
9944 enum print_stop_action
9945 watchpoint::print_it (const bpstat *bs) const
9947 enum print_stop_action result;
9948 struct ui_out *uiout = current_uiout;
9950 gdb_assert (bs->bp_location_at != NULL);
9952 annotate_watchpoint (this->number);
9953 maybe_print_thread_hit_breakpoint (uiout);
9955 string_file stb;
9957 std::optional<ui_out_emit_tuple> tuple_emitter;
9958 switch (this->type)
9960 case bp_watchpoint:
9961 case bp_hardware_watchpoint:
9962 if (uiout->is_mi_like_p ())
9963 uiout->field_string
9964 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9965 mention (this);
9966 tuple_emitter.emplace (uiout, "value");
9967 uiout->text ("\nOld value = ");
9968 watchpoint_value_print (bs->old_val.get (), &stb);
9969 uiout->field_stream ("old", stb);
9970 uiout->text ("\nNew value = ");
9971 watchpoint_value_print (val.get (), &stb);
9972 uiout->field_stream ("new", stb);
9973 uiout->text ("\n");
9974 /* More than one watchpoint may have been triggered. */
9975 result = PRINT_UNKNOWN;
9976 break;
9978 case bp_read_watchpoint:
9979 if (uiout->is_mi_like_p ())
9980 uiout->field_string
9981 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9982 mention (this);
9983 tuple_emitter.emplace (uiout, "value");
9984 uiout->text ("\nValue = ");
9985 watchpoint_value_print (val.get (), &stb);
9986 uiout->field_stream ("value", stb);
9987 uiout->text ("\n");
9988 result = PRINT_UNKNOWN;
9989 break;
9991 case bp_access_watchpoint:
9992 if (bs->old_val != NULL)
9994 if (uiout->is_mi_like_p ())
9995 uiout->field_string
9996 ("reason",
9997 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9998 mention (this);
9999 tuple_emitter.emplace (uiout, "value");
10000 uiout->text ("\nOld value = ");
10001 watchpoint_value_print (bs->old_val.get (), &stb);
10002 uiout->field_stream ("old", stb);
10003 uiout->text ("\nNew value = ");
10005 else
10007 mention (this);
10008 if (uiout->is_mi_like_p ())
10009 uiout->field_string
10010 ("reason",
10011 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10012 tuple_emitter.emplace (uiout, "value");
10013 uiout->text ("\nValue = ");
10015 watchpoint_value_print (val.get (), &stb);
10016 uiout->field_stream ("new", stb);
10017 uiout->text ("\n");
10018 result = PRINT_UNKNOWN;
10019 break;
10020 default:
10021 result = PRINT_UNKNOWN;
10024 return result;
10027 /* Implement the "print_mention" method for hardware watchpoints. */
10029 void
10030 watchpoint::print_mention () const
10032 struct ui_out *uiout = current_uiout;
10033 const char *tuple_name;
10035 switch (type)
10037 case bp_watchpoint:
10038 uiout->text ("Watchpoint ");
10039 tuple_name = "wpt";
10040 break;
10041 case bp_hardware_watchpoint:
10042 uiout->text ("Hardware watchpoint ");
10043 tuple_name = "wpt";
10044 break;
10045 case bp_read_watchpoint:
10046 uiout->text ("Hardware read watchpoint ");
10047 tuple_name = "hw-rwpt";
10048 break;
10049 case bp_access_watchpoint:
10050 uiout->text ("Hardware access (read/write) watchpoint ");
10051 tuple_name = "hw-awpt";
10052 break;
10053 default:
10054 internal_error (_("Invalid hardware watchpoint type."));
10057 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10058 uiout->field_signed ("number", number);
10059 uiout->text (": ");
10060 uiout->field_string ("exp", exp_string.get ());
10063 /* Implement the "print_recreate" method for watchpoints. */
10065 void
10066 watchpoint::print_recreate (struct ui_file *fp) const
10068 switch (type)
10070 case bp_watchpoint:
10071 case bp_hardware_watchpoint:
10072 gdb_printf (fp, "watch");
10073 break;
10074 case bp_read_watchpoint:
10075 gdb_printf (fp, "rwatch");
10076 break;
10077 case bp_access_watchpoint:
10078 gdb_printf (fp, "awatch");
10079 break;
10080 default:
10081 internal_error (_("Invalid watchpoint type."));
10084 gdb_printf (fp, " %s", exp_string.get ());
10085 print_recreate_thread (fp);
10088 /* Implement the "explains_signal" method for watchpoints. */
10090 bool
10091 watchpoint::explains_signal (enum gdb_signal sig)
10093 /* A software watchpoint cannot cause a signal other than
10094 GDB_SIGNAL_TRAP. */
10095 if (type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10096 return false;
10098 return true;
10101 struct masked_watchpoint : public watchpoint
10103 using watchpoint::watchpoint;
10105 int insert_location (struct bp_location *) override;
10106 int remove_location (struct bp_location *,
10107 enum remove_bp_reason reason) override;
10108 int resources_needed (const struct bp_location *) override;
10109 bool works_in_software_mode () const override;
10110 enum print_stop_action print_it (const bpstat *bs) const override;
10111 void print_one_detail (struct ui_out *) const override;
10112 void print_mention () const override;
10113 void print_recreate (struct ui_file *fp) const override;
10116 /* Implement the "insert" method for masked hardware watchpoints. */
10119 masked_watchpoint::insert_location (struct bp_location *bl)
10121 return target_insert_mask_watchpoint (bl->address, hw_wp_mask,
10122 bl->watchpoint_type);
10125 /* Implement the "remove" method for masked hardware watchpoints. */
10128 masked_watchpoint::remove_location (struct bp_location *bl,
10129 enum remove_bp_reason reason)
10131 return target_remove_mask_watchpoint (bl->address, hw_wp_mask,
10132 bl->watchpoint_type);
10135 /* Implement the "resources_needed" method for masked hardware
10136 watchpoints. */
10139 masked_watchpoint::resources_needed (const struct bp_location *bl)
10141 return target_masked_watch_num_registers (bl->address, hw_wp_mask);
10144 /* Implement the "works_in_software_mode" method for masked hardware
10145 watchpoints. */
10147 bool
10148 masked_watchpoint::works_in_software_mode () const
10150 return false;
10153 /* Implement the "print_it" method for masked hardware
10154 watchpoints. */
10156 enum print_stop_action
10157 masked_watchpoint::print_it (const bpstat *bs) const
10159 struct ui_out *uiout = current_uiout;
10161 /* Masked watchpoints have only one location. */
10162 gdb_assert (this->has_single_location ());
10164 annotate_watchpoint (this->number);
10165 maybe_print_thread_hit_breakpoint (uiout);
10167 switch (this->type)
10169 case bp_hardware_watchpoint:
10170 if (uiout->is_mi_like_p ())
10171 uiout->field_string
10172 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10173 break;
10175 case bp_read_watchpoint:
10176 if (uiout->is_mi_like_p ())
10177 uiout->field_string
10178 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10179 break;
10181 case bp_access_watchpoint:
10182 if (uiout->is_mi_like_p ())
10183 uiout->field_string
10184 ("reason",
10185 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10186 break;
10187 default:
10188 internal_error (_("Invalid hardware watchpoint type."));
10191 mention (this);
10192 uiout->text (_("\n\
10193 Check the underlying instruction at PC for the memory\n\
10194 address and value which triggered this watchpoint.\n"));
10195 uiout->text ("\n");
10197 /* More than one watchpoint may have been triggered. */
10198 return PRINT_UNKNOWN;
10201 /* Implement the "print_one_detail" method for masked hardware
10202 watchpoints. */
10204 void
10205 masked_watchpoint::print_one_detail (struct ui_out *uiout) const
10207 /* Masked watchpoints have only one location. */
10208 gdb_assert (this->has_single_location ());
10210 uiout->text ("\tmask ");
10211 uiout->field_core_addr ("mask", this->first_loc ().gdbarch, hw_wp_mask);
10212 uiout->text ("\n");
10215 /* Implement the "print_mention" method for masked hardware
10216 watchpoints. */
10218 void
10219 masked_watchpoint::print_mention () const
10221 struct ui_out *uiout = current_uiout;
10222 const char *tuple_name;
10224 switch (type)
10226 case bp_hardware_watchpoint:
10227 uiout->text ("Masked hardware watchpoint ");
10228 tuple_name = "wpt";
10229 break;
10230 case bp_read_watchpoint:
10231 uiout->text ("Masked hardware read watchpoint ");
10232 tuple_name = "hw-rwpt";
10233 break;
10234 case bp_access_watchpoint:
10235 uiout->text ("Masked hardware access (read/write) watchpoint ");
10236 tuple_name = "hw-awpt";
10237 break;
10238 default:
10239 internal_error (_("Invalid hardware watchpoint type."));
10242 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10243 uiout->field_signed ("number", number);
10244 uiout->text (": ");
10245 uiout->field_string ("exp", exp_string.get ());
10248 /* Implement the "print_recreate" method for masked hardware
10249 watchpoints. */
10251 void
10252 masked_watchpoint::print_recreate (struct ui_file *fp) const
10254 switch (type)
10256 case bp_hardware_watchpoint:
10257 gdb_printf (fp, "watch");
10258 break;
10259 case bp_read_watchpoint:
10260 gdb_printf (fp, "rwatch");
10261 break;
10262 case bp_access_watchpoint:
10263 gdb_printf (fp, "awatch");
10264 break;
10265 default:
10266 internal_error (_("Invalid hardware watchpoint type."));
10269 gdb_printf (fp, " %s mask 0x%s", exp_string.get (),
10270 phex (hw_wp_mask, sizeof (CORE_ADDR)));
10271 print_recreate_thread (fp);
10274 /* Tell whether the given watchpoint is a masked hardware watchpoint. */
10276 static bool
10277 is_masked_watchpoint (const struct breakpoint *b)
10279 return dynamic_cast<const masked_watchpoint *> (b) != nullptr;
10282 /* accessflag: hw_write: watch write,
10283 hw_read: watch read,
10284 hw_access: watch access (read or write) */
10285 static void
10286 watch_command_1 (const char *arg, int accessflag, int from_tty,
10287 bool just_location, bool internal)
10289 struct breakpoint *scope_breakpoint = NULL;
10290 const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10291 struct value *result;
10292 int saved_bitpos = 0, saved_bitsize = 0;
10293 const char *exp_start = NULL;
10294 const char *exp_end = NULL;
10295 const char *tok, *end_tok;
10296 int toklen = -1;
10297 const char *cond_start = NULL;
10298 const char *cond_end = NULL;
10299 enum bptype bp_type;
10300 int thread = -1;
10301 int inferior = -1;
10302 /* Flag to indicate whether we are going to use masks for
10303 the hardware watchpoint. */
10304 bool use_mask = false;
10305 CORE_ADDR mask = 0;
10306 int task = -1;
10308 /* Make sure that we actually have parameters to parse. */
10309 if (arg != NULL && arg[0] != '\0')
10311 const char *value_start;
10313 exp_end = arg + strlen (arg);
10315 /* Look for "parameter value" pairs at the end
10316 of the arguments string. */
10317 for (tok = exp_end - 1; tok > arg; tok--)
10319 /* Skip whitespace at the end of the argument list. */
10320 while (tok > arg && (*tok == ' ' || *tok == '\t'))
10321 tok--;
10323 /* Find the beginning of the last token.
10324 This is the value of the parameter. */
10325 while (tok > arg && (*tok != ' ' && *tok != '\t'))
10326 tok--;
10327 value_start = tok + 1;
10329 /* Skip whitespace. */
10330 while (tok > arg && (*tok == ' ' || *tok == '\t'))
10331 tok--;
10333 end_tok = tok;
10335 /* Find the beginning of the second to last token.
10336 This is the parameter itself. */
10337 while (tok > arg && (*tok != ' ' && *tok != '\t'))
10338 tok--;
10339 tok++;
10340 toklen = end_tok - tok + 1;
10342 if (toklen == 6 && startswith (tok, "thread"))
10344 struct thread_info *thr;
10345 /* At this point we've found a "thread" token, which means
10346 the user is trying to set a watchpoint that triggers
10347 only in a specific thread. */
10348 const char *endp;
10350 if (thread != -1)
10351 error(_("You can specify only one thread."));
10353 if (task != -1)
10354 error (_("You can specify only one of thread or task."));
10356 if (inferior != -1)
10357 error (_("You can specify only one of inferior or thread."));
10359 /* Extract the thread ID from the next token. */
10360 thr = parse_thread_id (value_start, &endp);
10361 if (value_start == endp)
10362 error (_("Junk after thread keyword."));
10364 thread = thr->global_num;
10366 else if (toklen == 4 && startswith (tok, "task"))
10368 char *tmp;
10370 if (task != -1)
10371 error(_("You can specify only one task."));
10373 if (thread != -1)
10374 error (_("You can specify only one of thread or task."));
10376 if (inferior != -1)
10377 error (_("You can specify only one of inferior or task."));
10379 task = strtol (value_start, &tmp, 0);
10380 if (tmp == value_start)
10381 error (_("Junk after task keyword."));
10382 if (!valid_task_id (task))
10383 error (_("Unknown task %d."), task);
10385 else if (toklen == 8 && startswith (tok, "inferior"))
10387 /* Support for watchpoints will be added in a later commit. */
10388 error (_("Cannot use 'inferior' keyword with watchpoints"));
10390 else if (toklen == 4 && startswith (tok, "mask"))
10392 /* We've found a "mask" token, which means the user wants to
10393 create a hardware watchpoint that is going to have the mask
10394 facility. */
10395 struct value *mask_value;
10397 if (use_mask)
10398 error(_("You can specify only one mask."));
10400 use_mask = just_location = true;
10402 scoped_value_mark mark;
10403 mask_value = parse_to_comma_and_eval (&value_start);
10404 mask = value_as_address (mask_value);
10406 else
10407 /* We didn't recognize what we found. We should stop here. */
10408 break;
10410 /* Truncate the string and get rid of the "parameter value" pair before
10411 the arguments string is parsed by the parse_exp_1 function. */
10412 exp_end = tok;
10415 else
10416 exp_end = arg;
10418 /* Parse the rest of the arguments. From here on out, everything
10419 is in terms of a newly allocated string instead of the original
10420 ARG. */
10421 std::string expression (arg, exp_end - arg);
10422 exp_start = arg = expression.c_str ();
10423 innermost_block_tracker tracker;
10424 expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10425 exp_end = arg;
10426 /* Remove trailing whitespace from the expression before saving it.
10427 This makes the eventual display of the expression string a bit
10428 prettier. */
10429 while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10430 --exp_end;
10432 /* Checking if the expression is not constant. */
10433 if (watchpoint_exp_is_const (exp.get ()))
10435 int len;
10437 len = exp_end - exp_start;
10438 while (len > 0 && isspace (exp_start[len - 1]))
10439 len--;
10440 error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10443 exp_valid_block = tracker.block ();
10444 struct value *mark = value_mark ();
10445 struct value *val_as_value = nullptr;
10446 fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
10447 just_location);
10449 if (val_as_value != NULL && just_location)
10451 saved_bitpos = val_as_value->bitpos ();
10452 saved_bitsize = val_as_value->bitsize ();
10455 value_ref_ptr val;
10456 if (just_location)
10458 int ret;
10460 exp_valid_block = NULL;
10461 val = release_value (value_addr (result));
10462 value_free_to_mark (mark);
10464 if (use_mask)
10466 ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10467 mask);
10468 if (ret == -1)
10469 error (_("This target does not support masked watchpoints."));
10470 else if (ret == -2)
10471 error (_("Invalid mask or memory region."));
10474 else if (val_as_value != NULL)
10475 val = release_value (val_as_value);
10477 tok = skip_spaces (arg);
10478 end_tok = skip_to_space (tok);
10480 toklen = end_tok - tok;
10481 if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10483 tok = cond_start = end_tok + 1;
10484 innermost_block_tracker if_tracker;
10485 parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10487 /* The watchpoint expression may not be local, but the condition
10488 may still be. E.g.: `watch global if local > 0'. */
10489 cond_exp_valid_block = if_tracker.block ();
10491 cond_end = tok;
10493 if (*tok)
10494 error (_("Junk at end of command."));
10496 frame_info_ptr wp_frame = block_innermost_frame (exp_valid_block);
10498 /* Save this because create_internal_breakpoint below invalidates
10499 'wp_frame'. */
10500 frame_id watchpoint_frame = get_frame_id (wp_frame);
10502 /* If the expression is "local", then set up a "watchpoint scope"
10503 breakpoint at the point where we've left the scope of the watchpoint
10504 expression. Create the scope breakpoint before the watchpoint, so
10505 that we will encounter it first in bpstat_stop_status. */
10506 if (exp_valid_block != NULL && wp_frame != NULL)
10508 frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10510 if (frame_id_p (caller_frame_id))
10512 gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10513 CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10515 scope_breakpoint
10516 = create_internal_breakpoint (caller_arch, caller_pc,
10517 bp_watchpoint_scope);
10519 /* create_internal_breakpoint could invalidate WP_FRAME. */
10520 wp_frame = NULL;
10522 scope_breakpoint->enable_state = bp_enabled;
10524 /* Automatically delete the breakpoint when it hits. */
10525 scope_breakpoint->disposition = disp_del;
10527 /* Only break in the proper frame (help with recursion). */
10528 scope_breakpoint->frame_id = caller_frame_id;
10530 /* Set the address at which we will stop. */
10531 bp_location &loc = scope_breakpoint->first_loc ();
10532 loc.gdbarch = caller_arch;
10533 loc.requested_address = caller_pc;
10534 loc.address
10535 = adjust_breakpoint_address (loc.gdbarch, loc.requested_address,
10536 scope_breakpoint->type,
10537 current_program_space);
10541 /* Now set up the breakpoint. We create all watchpoints as hardware
10542 watchpoints here even if hardware watchpoints are turned off, a call
10543 to update_watchpoint later in this function will cause the type to
10544 drop back to bp_watchpoint (software watchpoint) if required. */
10546 if (accessflag == hw_read)
10547 bp_type = bp_read_watchpoint;
10548 else if (accessflag == hw_access)
10549 bp_type = bp_access_watchpoint;
10550 else
10551 bp_type = bp_hardware_watchpoint;
10553 std::unique_ptr<watchpoint> w;
10554 if (use_mask)
10555 w.reset (new masked_watchpoint (nullptr, bp_type));
10556 else
10557 w.reset (new watchpoint (nullptr, bp_type));
10559 /* At most one of thread or task can be set on a watchpoint. */
10560 gdb_assert (thread == -1 || task == -1);
10561 w->thread = thread;
10562 w->inferior = inferior;
10563 w->task = task;
10564 w->disposition = disp_donttouch;
10565 w->pspace = current_program_space;
10566 w->exp = std::move (exp);
10567 w->exp_valid_block = exp_valid_block;
10568 w->cond_exp_valid_block = cond_exp_valid_block;
10569 if (just_location)
10571 struct type *t = val->type ();
10572 CORE_ADDR addr = value_as_address (val.get ());
10574 w->exp_string_reparse
10575 = current_language->watch_location_expression (t, addr);
10577 w->exp_string = xstrprintf ("-location %.*s",
10578 (int) (exp_end - exp_start), exp_start);
10580 else
10581 w->exp_string.reset (savestring (exp_start, exp_end - exp_start));
10583 if (use_mask)
10585 w->hw_wp_mask = mask;
10587 else
10589 w->val = val;
10590 w->val_bitpos = saved_bitpos;
10591 w->val_bitsize = saved_bitsize;
10592 w->val_valid = true;
10595 if (cond_start)
10596 w->cond_string.reset (savestring (cond_start, cond_end - cond_start));
10597 else
10598 w->cond_string = 0;
10600 if (frame_id_p (watchpoint_frame))
10602 w->watchpoint_frame = watchpoint_frame;
10603 w->watchpoint_thread = inferior_ptid;
10605 else
10607 w->watchpoint_frame = null_frame_id;
10608 w->watchpoint_thread = null_ptid;
10611 if (scope_breakpoint != NULL)
10613 /* The scope breakpoint is related to the watchpoint. We will
10614 need to act on them together. */
10615 w->related_breakpoint = scope_breakpoint;
10616 scope_breakpoint->related_breakpoint = w.get ();
10619 if (!just_location)
10620 value_free_to_mark (mark);
10622 /* Finally update the new watchpoint. This creates the locations
10623 that should be inserted. */
10624 update_watchpoint (w.get (), true /* reparse */);
10626 install_breakpoint (internal, std::move (w), 1);
10629 /* Return count of debug registers needed to watch the given expression.
10630 If the watchpoint cannot be handled in hardware return zero. */
10632 static int
10633 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10635 int found_memory_cnt = 0;
10637 /* Did the user specifically forbid us to use hardware watchpoints? */
10638 if (!can_use_hw_watchpoints)
10639 return 0;
10641 gdb_assert (!vals.empty ());
10642 struct value *head = vals[0].get ();
10644 /* Make sure that the value of the expression depends only upon
10645 memory contents, and values computed from them within GDB. If we
10646 find any register references or function calls, we can't use a
10647 hardware watchpoint.
10649 The idea here is that evaluating an expression generates a series
10650 of values, one holding the value of every subexpression. (The
10651 expression a*b+c has five subexpressions: a, b, a*b, c, and
10652 a*b+c.) GDB's values hold almost enough information to establish
10653 the criteria given above --- they identify memory lvalues,
10654 register lvalues, computed values, etcetera. So we can evaluate
10655 the expression, and then scan the chain of values that leaves
10656 behind to decide whether we can detect any possible change to the
10657 expression's final value using only hardware watchpoints.
10659 However, I don't think that the values returned by inferior
10660 function calls are special in any way. So this function may not
10661 notice that an expression involving an inferior function call
10662 can't be watched with hardware watchpoints. FIXME. */
10663 for (const value_ref_ptr &iter : vals)
10665 struct value *v = iter.get ();
10667 if (v->lval () == lval_memory)
10669 if (v != head && v->lazy ())
10670 /* A lazy memory lvalue in the chain is one that GDB never
10671 needed to fetch; we either just used its address (e.g.,
10672 `a' in `a.b') or we never needed it at all (e.g., `a'
10673 in `a,b'). This doesn't apply to HEAD; if that is
10674 lazy then it was not readable, but watch it anyway. */
10676 else
10678 /* Ahh, memory we actually used! Check if we can cover
10679 it with hardware watchpoints. */
10680 struct type *vtype = check_typedef (v->type ());
10682 /* We only watch structs and arrays if user asked for it
10683 explicitly, never if they just happen to appear in a
10684 middle of some value chain. */
10685 if (v == head
10686 || (vtype->code () != TYPE_CODE_STRUCT
10687 && vtype->code () != TYPE_CODE_ARRAY))
10689 CORE_ADDR vaddr = v->address ();
10690 int len;
10691 int num_regs;
10693 len = (target_exact_watchpoints
10694 && is_scalar_type_recursive (vtype))?
10695 1 : v->type ()->length ();
10697 num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10698 if (!num_regs)
10699 return 0;
10700 else
10701 found_memory_cnt += num_regs;
10705 else if (v->lval () != not_lval && !v->deprecated_modifiable ())
10706 return 0; /* These are values from the history (e.g., $1). */
10707 else if (v->lval () == lval_register)
10708 return 0; /* Cannot watch a register with a HW watchpoint. */
10711 /* The expression itself looks suitable for using a hardware
10712 watchpoint, but give the target machine a chance to reject it. */
10713 return found_memory_cnt;
10716 void
10717 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10719 watch_command_1 (arg, hw_write, from_tty, 0, internal);
10722 /* Options for the watch, awatch, and rwatch commands. */
10724 struct watch_options
10726 /* For -location. */
10727 bool location = false;
10730 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10732 Historically GDB always accepted both '-location' and '-l' flags for
10733 these commands (both flags being synonyms). When converting to the
10734 newer option scheme only '-location' is added here. That's fine (for
10735 backward compatibility) as any non-ambiguous prefix of a flag will be
10736 accepted, so '-l', '-loc', are now all accepted.
10738 What this means is that, if in the future, we add any new flag here
10739 that starts with '-l' then this will break backward compatibility, so
10740 please, don't do that! */
10742 static const gdb::option::option_def watch_option_defs[] = {
10743 gdb::option::flag_option_def<watch_options> {
10744 "location",
10745 [] (watch_options *opt) { return &opt->location; },
10746 N_("\
10747 This evaluates EXPRESSION and watches the memory to which is refers.\n\
10748 -l can be used as a short form of -location."),
10752 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
10753 commands. */
10755 static gdb::option::option_def_group
10756 make_watch_options_def_group (watch_options *opts)
10758 return {{watch_option_defs}, opts};
10761 /* A helper function that looks for the "-location" argument and then
10762 calls watch_command_1. */
10764 static void
10765 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10767 watch_options opts;
10768 auto grp = make_watch_options_def_group (&opts);
10769 gdb::option::process_options
10770 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
10771 if (arg != nullptr && *arg == '\0')
10772 arg = nullptr;
10774 watch_command_1 (arg, accessflag, from_tty, opts.location, false);
10777 /* Command completion for 'watch', 'awatch', and 'rwatch' commands. */
10778 static void
10779 watch_command_completer (struct cmd_list_element *ignore,
10780 completion_tracker &tracker,
10781 const char *text, const char * /*word*/)
10783 const auto group = make_watch_options_def_group (nullptr);
10784 if (gdb::option::complete_options
10785 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
10786 return;
10788 const char *word = advance_to_expression_complete_word_point (tracker, text);
10789 expression_completer (ignore, tracker, text, word);
10792 static void
10793 watch_command (const char *arg, int from_tty)
10795 watch_maybe_just_location (arg, hw_write, from_tty);
10798 void
10799 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
10801 watch_command_1 (arg, hw_read, from_tty, 0, internal);
10804 static void
10805 rwatch_command (const char *arg, int from_tty)
10807 watch_maybe_just_location (arg, hw_read, from_tty);
10810 void
10811 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
10813 watch_command_1 (arg, hw_access, from_tty, 0, internal);
10816 static void
10817 awatch_command (const char *arg, int from_tty)
10819 watch_maybe_just_location (arg, hw_access, from_tty);
10823 /* Data for the FSM that manages the until(location)/advance commands
10824 in infcmd.c. Here because it uses the mechanisms of
10825 breakpoints. */
10827 struct until_break_fsm : public thread_fsm
10829 /* The thread that was current when the command was executed. */
10830 int thread;
10832 /* The breakpoint set at the return address in the caller frame,
10833 plus breakpoints at all the destination locations. */
10834 std::vector<breakpoint_up> breakpoints;
10836 until_break_fsm (struct interp *cmd_interp, int thread,
10837 std::vector<breakpoint_up> &&breakpoints)
10838 : thread_fsm (cmd_interp),
10839 thread (thread),
10840 breakpoints (std::move (breakpoints))
10844 void clean_up (struct thread_info *thread) override;
10845 bool should_stop (struct thread_info *thread) override;
10846 enum async_reply_reason do_async_reply_reason () override;
10849 /* Implementation of the 'should_stop' FSM method for the
10850 until(location)/advance commands. */
10852 bool
10853 until_break_fsm::should_stop (struct thread_info *tp)
10855 for (const breakpoint_up &bp : breakpoints)
10856 if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10857 bp.get ()) != NULL)
10859 set_finished ();
10860 break;
10863 return true;
10866 /* Implementation of the 'clean_up' FSM method for the
10867 until(location)/advance commands. */
10869 void
10870 until_break_fsm::clean_up (struct thread_info *)
10872 /* Clean up our temporary breakpoints. */
10873 breakpoints.clear ();
10874 delete_longjmp_breakpoint (thread);
10877 /* Implementation of the 'async_reply_reason' FSM method for the
10878 until(location)/advance commands. */
10880 enum async_reply_reason
10881 until_break_fsm::do_async_reply_reason ()
10883 return EXEC_ASYNC_LOCATION_REACHED;
10886 void
10887 until_break_command (const char *arg, int from_tty, int anywhere)
10889 frame_info_ptr frame;
10890 struct gdbarch *frame_gdbarch;
10891 struct frame_id stack_frame_id;
10892 struct frame_id caller_frame_id;
10893 int thread;
10894 struct thread_info *tp;
10896 clear_proceed_status (0);
10898 /* Set a breakpoint where the user wants it and at return from
10899 this function. */
10901 location_spec_up locspec = string_to_location_spec (&arg, current_language);
10903 std::vector<symtab_and_line> sals
10904 = (last_displayed_sal_is_valid ()
10905 ? decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10906 get_last_displayed_symtab (),
10907 get_last_displayed_line ())
10908 : decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE,
10909 NULL, NULL, 0));
10911 if (sals.empty ())
10912 error (_("Couldn't get information on specified line."));
10914 if (*arg)
10915 error (_("Junk at end of arguments."));
10917 tp = inferior_thread ();
10918 thread = tp->global_num;
10920 /* Note linespec handling above invalidates the frame chain.
10921 Installing a breakpoint also invalidates the frame chain (as it
10922 may need to switch threads), so do any frame handling before
10923 that. */
10925 frame = get_selected_frame (NULL);
10926 frame_gdbarch = get_frame_arch (frame);
10927 stack_frame_id = get_stack_frame_id (frame);
10928 caller_frame_id = frame_unwind_caller_id (frame);
10930 /* Keep within the current frame, or in frames called by the current
10931 one. */
10933 std::vector<breakpoint_up> breakpoints;
10935 std::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
10937 if (frame_id_p (caller_frame_id))
10939 struct symtab_and_line sal2;
10940 struct gdbarch *caller_gdbarch;
10942 sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10943 sal2.pc = frame_unwind_caller_pc (frame);
10944 caller_gdbarch = frame_unwind_caller_arch (frame);
10946 breakpoint_up caller_breakpoint
10947 = set_momentary_breakpoint (caller_gdbarch, sal2,
10948 caller_frame_id, bp_until);
10949 breakpoints.emplace_back (std::move (caller_breakpoint));
10951 set_longjmp_breakpoint (tp, stack_frame_id);
10952 lj_deleter.emplace (thread);
10955 /* If the user told us to continue until a specified location, we
10956 don't specify a frame at which we need to stop. Otherwise,
10957 specify the selected frame, because we want to stop only at the
10958 very same frame. */
10959 frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
10961 for (symtab_and_line &sal : sals)
10963 resolve_sal_pc (&sal);
10965 breakpoint_up location_breakpoint
10966 = set_momentary_breakpoint (frame_gdbarch, sal,
10967 stop_frame_id, bp_until);
10968 breakpoints.emplace_back (std::move (location_breakpoint));
10971 tp->set_thread_fsm
10972 (std::unique_ptr<thread_fsm>
10973 (new until_break_fsm (command_interp (), tp->global_num,
10974 std::move (breakpoints))));
10976 if (lj_deleter)
10977 lj_deleter->release ();
10979 proceed (-1, GDB_SIGNAL_DEFAULT);
10984 /* Compare two breakpoints and return a strcmp-like result. */
10986 static int
10987 compare_breakpoints (const breakpoint *a, const breakpoint *b)
10989 uintptr_t ua = (uintptr_t) a;
10990 uintptr_t ub = (uintptr_t) b;
10992 if (a->number < b->number)
10993 return -1;
10994 else if (a->number > b->number)
10995 return 1;
10997 /* Now sort by address, in case we see, e..g, two breakpoints with
10998 the number 0. */
10999 if (ua < ub)
11000 return -1;
11001 return ua > ub ? 1 : 0;
11004 /* Delete breakpoints by address or line. */
11006 static void
11007 clear_command (const char *arg, int from_tty)
11009 int default_match;
11011 std::vector<symtab_and_line> decoded_sals;
11012 symtab_and_line last_sal;
11013 gdb::array_view<symtab_and_line> sals;
11014 if (arg)
11016 decoded_sals
11017 = decode_line_with_current_source (arg,
11018 (DECODE_LINE_FUNFIRSTLINE
11019 | DECODE_LINE_LIST_MODE));
11020 default_match = 0;
11021 sals = decoded_sals;
11023 else
11025 /* Set sal's line, symtab, pc, and pspace to the values
11026 corresponding to the last call to print_frame_info. If the
11027 codepoint is not valid, this will set all the fields to 0. */
11028 last_sal = get_last_displayed_sal ();
11029 if (last_sal.symtab == 0)
11030 error (_("No source file specified."));
11032 default_match = 1;
11033 sals = last_sal;
11036 /* We don't call resolve_sal_pc here. That's not as bad as it
11037 seems, because all existing breakpoints typically have both
11038 file/line and pc set. So, if clear is given file/line, we can
11039 match this to existing breakpoint without obtaining pc at all.
11041 We only support clearing given the address explicitly
11042 present in breakpoint table. Say, we've set breakpoint
11043 at file:line. There were several PC values for that file:line,
11044 due to optimization, all in one block.
11046 We've picked one PC value. If "clear" is issued with another
11047 PC corresponding to the same file:line, the breakpoint won't
11048 be cleared. We probably can still clear the breakpoint, but
11049 since the other PC value is never presented to user, user
11050 can only find it by guessing, and it does not seem important
11051 to support that. */
11053 /* For each line spec given, delete bps which correspond to it. Do
11054 it in two passes, solely to preserve the current behavior that
11055 from_tty is forced true if we delete more than one
11056 breakpoint. */
11058 std::vector<struct breakpoint *> found;
11059 for (const auto &sal : sals)
11061 const char *sal_fullname;
11063 /* If exact pc given, clear bpts at that pc.
11064 If line given (pc == 0), clear all bpts on specified line.
11065 If defaulting, clear all bpts on default line
11066 or at default pc.
11068 defaulting sal.pc != 0 tests to do
11070 0 1 pc
11071 1 1 pc _and_ line
11072 0 0 line
11073 1 0 <can't happen> */
11075 sal_fullname = (sal.symtab == NULL
11076 ? NULL : symtab_to_fullname (sal.symtab));
11078 /* Find all matching breakpoints and add them to 'found'. */
11079 for (breakpoint &b : all_breakpoints ())
11081 int match = 0;
11082 /* Are we going to delete b? */
11083 if (b.type != bp_none && !is_watchpoint (&b)
11084 && user_breakpoint_p (&b))
11086 for (bp_location &loc : b.locations ())
11088 /* If the user specified file:line, don't allow a PC
11089 match. This matches historical gdb behavior. */
11090 int pc_match = (!sal.explicit_line
11091 && sal.pc
11092 && (loc.pspace == sal.pspace)
11093 && (loc.address == sal.pc)
11094 && (!section_is_overlay (loc.section)
11095 || loc.section == sal.section));
11096 int line_match = 0;
11098 if ((default_match || sal.explicit_line)
11099 && loc.symtab != NULL
11100 && sal_fullname != NULL
11101 && sal.pspace == loc.pspace
11102 && loc.line_number == sal.line
11103 && filename_cmp (symtab_to_fullname (loc.symtab),
11104 sal_fullname) == 0)
11105 line_match = 1;
11107 if (pc_match || line_match)
11109 match = 1;
11110 break;
11115 if (match)
11116 found.push_back (&b);
11120 /* Now go thru the 'found' chain and delete them. */
11121 if (found.empty ())
11123 if (arg)
11124 error (_("No breakpoint at %s."), arg);
11125 else
11126 error (_("No breakpoint at this line."));
11129 /* Remove duplicates from the vec. */
11130 std::sort (found.begin (), found.end (),
11131 [] (const breakpoint *bp_a, const breakpoint *bp_b)
11133 return compare_breakpoints (bp_a, bp_b) < 0;
11135 found.erase (std::unique (found.begin (), found.end (),
11136 [] (const breakpoint *bp_a, const breakpoint *bp_b)
11138 return compare_breakpoints (bp_a, bp_b) == 0;
11140 found.end ());
11142 if (found.size () > 1)
11143 from_tty = 1; /* Always report if deleted more than one. */
11144 if (from_tty)
11146 if (found.size () == 1)
11147 gdb_printf (_("Deleted breakpoint "));
11148 else
11149 gdb_printf (_("Deleted breakpoints "));
11152 for (breakpoint *iter : found)
11154 if (from_tty)
11155 gdb_printf ("%d ", iter->number);
11156 delete_breakpoint (iter);
11158 if (from_tty)
11159 gdb_putc ('\n');
11162 /* Delete breakpoint in BS if they are `delete' breakpoints and
11163 all breakpoints that are marked for deletion, whether hit or not.
11164 This is called after any breakpoint is hit, or after errors. */
11166 void
11167 breakpoint_auto_delete (bpstat *bs)
11169 for (; bs; bs = bs->next)
11170 if (bs->breakpoint_at
11171 && bs->breakpoint_at->disposition == disp_del
11172 && bs->stop)
11173 delete_breakpoint (bs->breakpoint_at);
11175 for (breakpoint &b : all_breakpoints_safe ())
11176 if (b.disposition == disp_del_at_next_stop)
11177 delete_breakpoint (&b);
11180 /* A comparison function for bp_location AP and BP being interfaced to
11181 std::sort. Sort elements primarily by their ADDRESS (no matter what
11182 bl_address_is_meaningful says), secondarily by ordering first
11183 permanent elements and tertiarily just ensuring the array is sorted
11184 stable way despite std::sort being an unstable algorithm. */
11186 static int
11187 bp_location_is_less_than (const bp_location *a, const bp_location *b)
11189 if (a->address != b->address)
11190 return a->address < b->address;
11192 /* Sort locations at the same address by their pspace number, keeping
11193 locations of the same inferior (in a multi-inferior environment)
11194 grouped. */
11196 if (a->pspace->num != b->pspace->num)
11197 return a->pspace->num < b->pspace->num;
11199 /* Sort permanent breakpoints first. */
11200 if (a->permanent != b->permanent)
11201 return a->permanent > b->permanent;
11203 /* Sort by type in order to make duplicate determination easier.
11204 See update_global_location_list. This is kept in sync with
11205 breakpoint_locations_match. */
11206 if (a->loc_type < b->loc_type)
11207 return true;
11209 /* Likewise, for range-breakpoints, sort by length. */
11210 if (a->loc_type == bp_loc_hardware_breakpoint
11211 && b->loc_type == bp_loc_hardware_breakpoint
11212 && a->length < b->length)
11213 return true;
11215 /* Make the internal GDB representation stable across GDB runs
11216 where A and B memory inside GDB can differ. Breakpoint locations of
11217 the same type at the same address can be sorted in arbitrary order. */
11219 if (a->owner->number != b->owner->number)
11220 return a->owner->number < b->owner->number;
11222 return a < b;
11225 /* Set bp_locations_placed_address_before_address_max and
11226 bp_locations_shadow_len_after_address_max according to the current
11227 content of the bp_locations array. */
11229 static void
11230 bp_locations_target_extensions_update (void)
11232 bp_locations_placed_address_before_address_max = 0;
11233 bp_locations_shadow_len_after_address_max = 0;
11235 for (bp_location *bl : all_bp_locations ())
11237 CORE_ADDR start, end, addr;
11239 if (!bp_location_has_shadow (bl))
11240 continue;
11242 start = bl->target_info.placed_address;
11243 end = start + bl->target_info.shadow_len;
11245 gdb_assert (bl->address >= start);
11246 addr = bl->address - start;
11247 if (addr > bp_locations_placed_address_before_address_max)
11248 bp_locations_placed_address_before_address_max = addr;
11250 /* Zero SHADOW_LEN would not pass bp_location_has_shadow. */
11252 gdb_assert (bl->address < end);
11253 addr = end - bl->address;
11254 if (addr > bp_locations_shadow_len_after_address_max)
11255 bp_locations_shadow_len_after_address_max = addr;
11259 /* Download tracepoint locations if they haven't been. */
11261 static void
11262 download_tracepoint_locations (void)
11264 enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11266 scoped_restore_current_pspace_and_thread restore_pspace_thread;
11268 for (breakpoint &b : all_tracepoints ())
11270 bool bp_location_downloaded = false;
11272 if ((b.type == bp_fast_tracepoint
11273 ? !may_insert_fast_tracepoints
11274 : !may_insert_tracepoints))
11275 continue;
11277 if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11279 if (target_can_download_tracepoint ())
11280 can_download_tracepoint = TRIBOOL_TRUE;
11281 else
11282 can_download_tracepoint = TRIBOOL_FALSE;
11285 if (can_download_tracepoint == TRIBOOL_FALSE)
11286 break;
11288 for (bp_location &bl : b.locations ())
11290 /* In tracepoint, locations are _never_ duplicated, so
11291 should_be_inserted is equivalent to
11292 unduplicated_should_be_inserted. */
11293 if (!should_be_inserted (&bl) || bl.inserted)
11294 continue;
11296 switch_to_program_space_and_thread (bl.pspace);
11298 target_download_tracepoint (&bl);
11300 bl.inserted = 1;
11301 bp_location_downloaded = true;
11304 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
11305 t.number_on_target = b.number;
11306 if (bp_location_downloaded)
11307 notify_breakpoint_modified (&b);
11311 /* Swap the insertion/duplication state between two locations. */
11313 static void
11314 swap_insertion (struct bp_location *left, struct bp_location *right)
11316 const int left_inserted = left->inserted;
11317 const int left_duplicate = left->duplicate;
11318 const int left_needs_update = left->needs_update;
11319 const struct bp_target_info left_target_info = left->target_info;
11321 /* Locations of tracepoints can never be duplicated. */
11322 if (is_tracepoint (left->owner))
11323 gdb_assert (!left->duplicate);
11324 if (is_tracepoint (right->owner))
11325 gdb_assert (!right->duplicate);
11327 left->inserted = right->inserted;
11328 left->duplicate = right->duplicate;
11329 left->needs_update = right->needs_update;
11330 left->target_info = right->target_info;
11331 right->inserted = left_inserted;
11332 right->duplicate = left_duplicate;
11333 right->needs_update = left_needs_update;
11334 right->target_info = left_target_info;
11337 /* Force the re-insertion of the locations at ADDRESS. This is called
11338 once a new/deleted/modified duplicate location is found and we are evaluating
11339 conditions on the target's side. Such conditions need to be updated on
11340 the target. */
11342 static void
11343 force_breakpoint_reinsertion (struct bp_location *bl)
11345 CORE_ADDR address = 0;
11346 int pspace_num;
11348 address = bl->address;
11349 pspace_num = bl->pspace->num;
11351 /* This is only meaningful if the target is
11352 evaluating conditions and if the user has
11353 opted for condition evaluation on the target's
11354 side. */
11355 if (gdb_evaluates_breakpoint_condition_p ()
11356 || !target_supports_evaluation_of_breakpoint_conditions ())
11357 return;
11359 /* Flag all breakpoint locations with this address and
11360 the same program space as the location
11361 as "its condition has changed". We need to
11362 update the conditions on the target's side. */
11363 for (bp_location *loc : all_bp_locations_at_addr (address))
11365 if (!is_breakpoint (loc->owner)
11366 || pspace_num != loc->pspace->num)
11367 continue;
11369 /* Flag the location appropriately. We use a different state to
11370 let everyone know that we already updated the set of locations
11371 with addr bl->address and program space bl->pspace. This is so
11372 we don't have to keep calling these functions just to mark locations
11373 that have already been marked. */
11374 loc->condition_changed = condition_updated;
11376 /* Free the agent expression bytecode as well. We will compute
11377 it later on. */
11378 loc->cond_bytecode.reset ();
11382 /* Called whether new breakpoints are created, or existing breakpoints
11383 deleted, to update the global location list and recompute which
11384 locations are duplicate of which.
11386 The INSERT_MODE flag determines whether locations may not, may, or
11387 shall be inserted now. See 'enum ugll_insert_mode' for more
11388 info. */
11390 static void
11391 update_global_location_list (enum ugll_insert_mode insert_mode)
11393 /* Last breakpoint location address that was marked for update. */
11394 CORE_ADDR last_addr = 0;
11395 /* Last breakpoint location program space that was marked for update. */
11396 int last_pspace_num = -1;
11398 breakpoint_debug_printf ("insert_mode = %s",
11399 ugll_insert_mode_text (insert_mode));
11401 /* Used in the duplicates detection below. When iterating over all
11402 bp_locations, points to the first bp_location of a given address.
11403 Breakpoints and watchpoints of different types are never
11404 duplicates of each other. Keep one pointer for each type of
11405 breakpoint/watchpoint, so we only need to loop over all locations
11406 once. */
11407 struct bp_location *bp_loc_first; /* breakpoint */
11408 struct bp_location *wp_loc_first; /* hardware watchpoint */
11409 struct bp_location *awp_loc_first; /* access watchpoint */
11410 struct bp_location *rwp_loc_first; /* read watchpoint */
11412 /* Saved former bp_locations array which we compare against the newly
11413 built bp_locations from the current state of ALL_BREAKPOINTS. */
11414 std::vector<bp_location *> old_locations = std::move (bp_locations);
11415 bp_locations.clear ();
11417 for (breakpoint &b : all_breakpoints ())
11418 for (bp_location &loc : b.locations ())
11419 bp_locations.push_back (&loc);
11421 /* See if we need to "upgrade" a software breakpoint to a hardware
11422 breakpoint. Do this before deciding whether locations are
11423 duplicates. Also do this before sorting because sorting order
11424 depends on location type. */
11425 for (bp_location *loc : bp_locations)
11426 if (!loc->inserted && should_be_inserted (loc))
11427 handle_automatic_hardware_breakpoints (loc);
11429 std::sort (bp_locations.begin (), bp_locations.end (),
11430 bp_location_is_less_than);
11432 bp_locations_target_extensions_update ();
11434 /* Identify bp_location instances that are no longer present in the
11435 new list, and therefore should be freed. Note that it's not
11436 necessary that those locations should be removed from inferior --
11437 if there's another location at the same address (previously
11438 marked as duplicate), we don't need to remove/insert the
11439 location.
11441 LOCP is kept in sync with OLD_LOCP, each pointing to the current
11442 and former bp_location array state respectively. */
11444 size_t loc_i = 0;
11445 for (bp_location *old_loc : old_locations)
11447 /* Tells if 'old_loc' is found among the new locations. If
11448 not, we have to free it. */
11449 bool found_object = false;
11450 /* Tells if the location should remain inserted in the target. */
11451 bool keep_in_target = false;
11452 bool removed = false;
11454 /* Skip LOCP entries which will definitely never be needed.
11455 Stop either at or being the one matching OLD_LOC. */
11456 while (loc_i < bp_locations.size ()
11457 && bp_locations[loc_i]->address < old_loc->address)
11458 loc_i++;
11460 for (size_t loc2_i = loc_i;
11461 (loc2_i < bp_locations.size ()
11462 && bp_locations[loc2_i]->address == old_loc->address);
11463 loc2_i++)
11465 /* Check if this is a new/duplicated location or a duplicated
11466 location that had its condition modified. If so, we want to send
11467 its condition to the target if evaluation of conditions is taking
11468 place there. */
11469 if (bp_locations[loc2_i]->condition_changed == condition_modified
11470 && (last_addr != old_loc->address
11471 || last_pspace_num != old_loc->pspace->num))
11473 force_breakpoint_reinsertion (bp_locations[loc2_i]);
11474 last_pspace_num = old_loc->pspace->num;
11477 if (bp_locations[loc2_i] == old_loc)
11478 found_object = true;
11481 /* We have already handled this address, update it so that we don't
11482 have to go through updates again. */
11483 last_addr = old_loc->address;
11485 /* Target-side condition evaluation: Handle deleted locations. */
11486 if (!found_object)
11487 force_breakpoint_reinsertion (old_loc);
11489 /* If this location is no longer present, and inserted, look if
11490 there's maybe a new location at the same address. If so,
11491 mark that one inserted, and don't remove this one. This is
11492 needed so that we don't have a time window where a breakpoint
11493 at certain location is not inserted. */
11495 if (old_loc->inserted)
11497 /* If the location is inserted now, we might have to remove
11498 it. */
11500 if (found_object && should_be_inserted (old_loc))
11502 /* The location is still present in the location list,
11503 and still should be inserted. Don't do anything. */
11504 keep_in_target = true;
11506 else
11508 /* This location still exists, but it won't be kept in the
11509 target since it may have been disabled. We proceed to
11510 remove its target-side condition. */
11512 /* The location is either no longer present, or got
11513 disabled. See if there's another location at the
11514 same address, in which case we don't need to remove
11515 this one from the target. */
11517 /* OLD_LOC comes from existing struct breakpoint. */
11518 if (bl_address_is_meaningful (old_loc))
11520 for (size_t loc2_i = loc_i;
11521 (loc2_i < bp_locations.size ()
11522 && bp_locations[loc2_i]->address == old_loc->address);
11523 loc2_i++)
11525 bp_location *loc2 = bp_locations[loc2_i];
11527 if (loc2 == old_loc)
11528 continue;
11530 if (breakpoint_locations_match (loc2, old_loc))
11532 /* Read watchpoint locations are switched to
11533 access watchpoints, if the former are not
11534 supported, but the latter are. */
11535 if (is_hardware_watchpoint (old_loc->owner))
11537 gdb_assert (is_hardware_watchpoint (loc2->owner));
11538 loc2->watchpoint_type = old_loc->watchpoint_type;
11541 /* loc2 is a duplicated location. We need to check
11542 if it should be inserted in case it will be
11543 unduplicated. */
11544 if (unduplicated_should_be_inserted (loc2))
11546 swap_insertion (old_loc, loc2);
11547 keep_in_target = true;
11548 break;
11555 if (!keep_in_target)
11557 if (remove_breakpoint (old_loc))
11559 /* This is just about all we can do. We could keep
11560 this location on the global list, and try to
11561 remove it next time, but there's no particular
11562 reason why we will succeed next time.
11564 Note that at this point, old_loc->owner is still
11565 valid, as delete_breakpoint frees the breakpoint
11566 only after calling us. */
11567 warning (_("error removing breakpoint %d at %s"),
11568 old_loc->owner->number,
11569 paddress (old_loc->gdbarch, old_loc->address));
11571 removed = true;
11575 if (!found_object)
11577 if (removed && target_is_non_stop_p ()
11578 && need_moribund_for_location_type (old_loc))
11580 /* This location was removed from the target. In
11581 non-stop mode, a race condition is possible where
11582 we've removed a breakpoint, but stop events for that
11583 breakpoint are already queued and will arrive later.
11584 We apply an heuristic to be able to distinguish such
11585 SIGTRAPs from other random SIGTRAPs: we keep this
11586 breakpoint location for a bit, and will retire it
11587 after we see some number of events. The theory here
11588 is that reporting of events should, "on the average",
11589 be fair, so after a while we'll see events from all
11590 threads that have anything of interest, and no longer
11591 need to keep this breakpoint location around. We
11592 don't hold locations forever so to reduce chances of
11593 mistaking a non-breakpoint SIGTRAP for a breakpoint
11594 SIGTRAP.
11596 The heuristic failing can be disastrous on
11597 decr_pc_after_break targets.
11599 On decr_pc_after_break targets, like e.g., x86-linux,
11600 if we fail to recognize a late breakpoint SIGTRAP,
11601 because events_till_retirement has reached 0 too
11602 soon, we'll fail to do the PC adjustment, and report
11603 a random SIGTRAP to the user. When the user resumes
11604 the inferior, it will most likely immediately crash
11605 with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11606 corrupted, because of being resumed e.g., in the
11607 middle of a multi-byte instruction, or skipped a
11608 one-byte instruction. This was actually seen happen
11609 on native x86-linux, and should be less rare on
11610 targets that do not support new thread events, like
11611 remote, due to the heuristic depending on
11612 thread_count.
11614 Mistaking a random SIGTRAP for a breakpoint trap
11615 causes similar symptoms (PC adjustment applied when
11616 it shouldn't), but then again, playing with SIGTRAPs
11617 behind the debugger's back is asking for trouble.
11619 Since hardware watchpoint traps are always
11620 distinguishable from other traps, so we don't need to
11621 apply keep hardware watchpoint moribund locations
11622 around. We simply always ignore hardware watchpoint
11623 traps we can no longer explain. */
11625 process_stratum_target *proc_target = nullptr;
11626 for (inferior *inf : all_inferiors ())
11627 if (inf->pspace == old_loc->pspace)
11629 proc_target = inf->process_target ();
11630 break;
11632 if (proc_target != nullptr)
11633 old_loc->events_till_retirement
11634 = 3 * (thread_count (proc_target) + 1);
11635 else
11636 old_loc->events_till_retirement = 1;
11637 old_loc->owner = NULL;
11639 moribund_locations.push_back (old_loc);
11641 else
11643 old_loc->owner = NULL;
11644 decref_bp_location (&old_loc);
11649 /* Rescan breakpoints at the same address and section, marking the
11650 first one as "first" and any others as "duplicates". This is so
11651 that the bpt instruction is only inserted once. If we have a
11652 permanent breakpoint at the same place as BPT, make that one the
11653 official one, and the rest as duplicates. Permanent breakpoints
11654 are sorted first for the same address.
11656 Do the same for hardware watchpoints, but also considering the
11657 watchpoint's type (regular/access/read) and length. */
11659 bp_loc_first = NULL;
11660 wp_loc_first = NULL;
11661 awp_loc_first = NULL;
11662 rwp_loc_first = NULL;
11664 for (bp_location *loc : all_bp_locations ())
11666 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11667 non-NULL. */
11668 struct bp_location **loc_first_p;
11669 breakpoint *b = loc->owner;
11671 if (!unduplicated_should_be_inserted (loc)
11672 || !bl_address_is_meaningful (loc)
11673 /* Don't detect duplicate for tracepoint locations because they are
11674 never duplicated. See the comments in field `duplicate' of
11675 `struct bp_location'. */
11676 || is_tracepoint (b))
11678 /* Clear the condition modification flag. */
11679 loc->condition_changed = condition_unchanged;
11680 continue;
11683 if (b->type == bp_hardware_watchpoint)
11684 loc_first_p = &wp_loc_first;
11685 else if (b->type == bp_read_watchpoint)
11686 loc_first_p = &rwp_loc_first;
11687 else if (b->type == bp_access_watchpoint)
11688 loc_first_p = &awp_loc_first;
11689 else
11690 loc_first_p = &bp_loc_first;
11692 if (*loc_first_p == NULL
11693 || (overlay_debugging && loc->section != (*loc_first_p)->section)
11694 || !breakpoint_locations_match (loc, *loc_first_p))
11696 *loc_first_p = loc;
11697 loc->duplicate = 0;
11699 if (is_breakpoint (loc->owner) && loc->condition_changed)
11701 loc->needs_update = 1;
11702 /* Clear the condition modification flag. */
11703 loc->condition_changed = condition_unchanged;
11705 continue;
11709 /* This and the above ensure the invariant that the first location
11710 is not duplicated, and is the inserted one.
11711 All following are marked as duplicated, and are not inserted. */
11712 if (loc->inserted)
11713 swap_insertion (loc, *loc_first_p);
11714 loc->duplicate = 1;
11716 /* Clear the condition modification flag. */
11717 loc->condition_changed = condition_unchanged;
11720 if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
11722 if (insert_mode != UGLL_DONT_INSERT)
11723 insert_breakpoint_locations ();
11724 else
11726 /* Even though the caller told us to not insert new
11727 locations, we may still need to update conditions on the
11728 target's side of breakpoints that were already inserted
11729 if the target is evaluating breakpoint conditions. We
11730 only update conditions for locations that are marked
11731 "needs_update". */
11732 update_inserted_breakpoint_locations ();
11736 if (insert_mode != UGLL_DONT_INSERT)
11737 download_tracepoint_locations ();
11740 void
11741 breakpoint_retire_moribund (void)
11743 for (int ix = 0; ix < moribund_locations.size (); ++ix)
11745 struct bp_location *loc = moribund_locations[ix];
11746 if (--(loc->events_till_retirement) == 0)
11748 decref_bp_location (&loc);
11749 unordered_remove (moribund_locations, ix);
11750 --ix;
11755 static void
11756 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
11761 update_global_location_list (insert_mode);
11763 catch (const gdb_exception_error &e)
11768 /* Clear BKP from a BPS. */
11770 static void
11771 bpstat_remove_bp_location (bpstat *bps, struct breakpoint *bpt)
11773 bpstat *bs;
11775 for (bs = bps; bs; bs = bs->next)
11776 if (bs->breakpoint_at == bpt)
11778 bs->breakpoint_at = NULL;
11779 bs->old_val = NULL;
11780 /* bs->commands will be freed later. */
11784 /* Callback for iterate_over_threads. */
11785 static int
11786 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11788 struct breakpoint *bpt = (struct breakpoint *) data;
11790 bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11791 return 0;
11794 /* See breakpoint.h. */
11796 void
11797 code_breakpoint::say_where () const
11799 struct value_print_options opts;
11801 get_user_print_options (&opts);
11803 /* i18n: cagney/2005-02-11: Below needs to be merged into a
11804 single string. */
11805 if (!this->has_locations ())
11807 /* For pending locations, the output differs slightly based
11808 on extra_string. If this is non-NULL, it contains either
11809 a condition or dprintf arguments. */
11810 if (extra_string == NULL)
11812 gdb_printf (_(" (%s) pending."), locspec->to_string ());
11814 else if (type == bp_dprintf)
11816 gdb_printf (_(" (%s,%s) pending."),
11817 locspec->to_string (),
11818 extra_string.get ());
11820 else
11822 gdb_printf (_(" (%s %s) pending."),
11823 locspec->to_string (),
11824 extra_string.get ());
11827 else
11829 const bp_location &bl = this->first_loc ();
11830 if (opts.addressprint || bl.symtab == nullptr)
11831 gdb_printf (" at %ps",
11832 styled_string (address_style.style (),
11833 paddress (bl.gdbarch,
11834 bl.address)));
11835 if (bl.symtab != NULL)
11837 /* If there is a single location, we can print the location
11838 more nicely. */
11839 if (!this->has_multiple_locations ())
11841 const char *filename
11842 = symtab_to_filename_for_display (bl.symtab);
11843 gdb_printf (": file %ps, line %d.",
11844 styled_string (file_name_style.style (),
11845 filename),
11846 bl.line_number);
11848 else
11849 /* This is not ideal, but each location may have a
11850 different file name, and this at least reflects the
11851 real situation somewhat. */
11852 gdb_printf (": %s.", locspec->to_string ());
11855 if (this->has_multiple_locations ())
11857 int n = std::distance (m_locations.begin (), m_locations.end ());
11858 gdb_printf (" (%d locations)", n);
11863 /* See breakpoint.h. */
11865 bp_location_range breakpoint::locations () const
11867 return bp_location_range (m_locations.begin (), m_locations.end ());
11870 struct bp_location *
11871 breakpoint::allocate_location ()
11873 return new bp_location (this);
11876 /* See breakpoint.h. */
11878 void
11879 breakpoint::add_location (bp_location &loc)
11881 gdb_assert (loc.owner == this);
11882 gdb_assert (!loc.is_linked ());
11884 auto ub = std::upper_bound (m_locations.begin (), m_locations.end (),
11885 loc,
11886 [] (const bp_location &left,
11887 const bp_location &right)
11888 { return left.address < right.address; });
11889 m_locations.insert (ub, loc);
11892 /* See breakpoint.h. */
11894 void
11895 breakpoint::unadd_location (bp_location &loc)
11897 gdb_assert (loc.owner == this);
11898 gdb_assert (loc.is_linked ());
11900 m_locations.erase (m_locations.iterator_to (loc));
11903 #define internal_error_pure_virtual_called() \
11904 gdb_assert_not_reached ("pure virtual function called")
11907 breakpoint::insert_location (struct bp_location *bl)
11909 internal_error_pure_virtual_called ();
11913 breakpoint::remove_location (struct bp_location *bl,
11914 enum remove_bp_reason reason)
11916 internal_error_pure_virtual_called ();
11920 breakpoint::breakpoint_hit (const struct bp_location *bl,
11921 const address_space *aspace,
11922 CORE_ADDR bp_addr,
11923 const target_waitstatus &ws)
11925 internal_error_pure_virtual_called ();
11929 breakpoint::resources_needed (const struct bp_location *bl)
11931 internal_error_pure_virtual_called ();
11934 enum print_stop_action
11935 breakpoint::print_it (const bpstat *bs) const
11937 internal_error_pure_virtual_called ();
11940 void
11941 breakpoint::print_mention () const
11943 internal_error_pure_virtual_called ();
11946 void
11947 breakpoint::print_recreate (struct ui_file *fp) const
11949 internal_error_pure_virtual_called ();
11952 /* Default breakpoint_ops methods. */
11954 void
11955 code_breakpoint::re_set ()
11957 /* FIXME: is this still reachable? */
11958 if (breakpoint_location_spec_empty_p (this))
11960 /* Anything without a location can't be re-set. */
11961 delete_breakpoint (this);
11962 return;
11965 re_set_default ();
11969 code_breakpoint::insert_location (struct bp_location *bl)
11971 CORE_ADDR addr = bl->target_info.reqstd_address;
11973 bl->target_info.kind = breakpoint_kind (bl, &addr);
11974 bl->target_info.placed_address = addr;
11976 int result;
11977 if (bl->loc_type == bp_loc_hardware_breakpoint)
11978 result = target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
11979 else
11980 result = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
11982 if (result == 0 && bl->probe.prob != nullptr)
11984 /* The insertion was successful, now let's set the probe's semaphore
11985 if needed. */
11986 bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
11989 return result;
11993 code_breakpoint::remove_location (struct bp_location *bl,
11994 enum remove_bp_reason reason)
11996 if (bl->probe.prob != nullptr)
11998 /* Let's clear the semaphore before removing the location. */
11999 bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12002 if (bl->loc_type == bp_loc_hardware_breakpoint)
12003 return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12004 else
12005 return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12009 code_breakpoint::breakpoint_hit (const struct bp_location *bl,
12010 const address_space *aspace,
12011 CORE_ADDR bp_addr,
12012 const target_waitstatus &ws)
12014 if (ws.kind () != TARGET_WAITKIND_STOPPED
12015 || ws.sig () != GDB_SIGNAL_TRAP)
12016 return 0;
12018 if (!breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
12019 aspace, bp_addr))
12020 return 0;
12022 if (overlay_debugging /* unmapped overlay section */
12023 && section_is_overlay (bl->section)
12024 && !section_is_mapped (bl->section))
12025 return 0;
12027 return 1;
12031 dprintf_breakpoint::breakpoint_hit (const struct bp_location *bl,
12032 const address_space *aspace,
12033 CORE_ADDR bp_addr,
12034 const target_waitstatus &ws)
12036 if (dprintf_style == dprintf_style_agent
12037 && target_can_run_breakpoint_commands ())
12039 /* An agent-style dprintf never causes a stop. If we see a trap
12040 for this address it must be for a breakpoint that happens to
12041 be set at the same address. */
12042 return 0;
12045 return this->ordinary_breakpoint::breakpoint_hit (bl, aspace, bp_addr, ws);
12049 ordinary_breakpoint::resources_needed (const struct bp_location *bl)
12051 gdb_assert (type == bp_hardware_breakpoint);
12053 return 1;
12056 enum print_stop_action
12057 ordinary_breakpoint::print_it (const bpstat *bs) const
12059 const struct bp_location *bl;
12060 int bp_temp;
12061 struct ui_out *uiout = current_uiout;
12063 bl = bs->bp_location_at.get ();
12065 bp_temp = disposition == disp_del;
12066 if (bl->address != bl->requested_address)
12067 breakpoint_adjustment_warning (bl->requested_address,
12068 bl->address,
12069 number, true);
12070 annotate_breakpoint (number);
12071 maybe_print_thread_hit_breakpoint (uiout);
12073 if (uiout->is_mi_like_p ())
12075 uiout->field_string ("reason",
12076 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12077 uiout->field_string ("disp", bpdisp_text (disposition));
12080 if (bp_temp)
12081 uiout->text ("Temporary breakpoint ");
12082 else
12083 uiout->text ("Breakpoint ");
12084 print_num_locno (bs, uiout);
12085 uiout->text (", ");
12087 return PRINT_SRC_AND_LOC;
12090 void
12091 ordinary_breakpoint::print_mention () const
12093 if (current_uiout->is_mi_like_p ())
12094 return;
12096 switch (type)
12098 case bp_breakpoint:
12099 case bp_gnu_ifunc_resolver:
12100 if (disposition == disp_del)
12101 gdb_printf (_("Temporary breakpoint"));
12102 else
12103 gdb_printf (_("Breakpoint"));
12104 gdb_printf (_(" %d"), number);
12105 if (type == bp_gnu_ifunc_resolver)
12106 gdb_printf (_(" at gnu-indirect-function resolver"));
12107 break;
12108 case bp_hardware_breakpoint:
12109 gdb_printf (_("Hardware assisted breakpoint %d"), number);
12110 break;
12111 case bp_dprintf:
12112 gdb_printf (_("Dprintf %d"), number);
12113 break;
12116 say_where ();
12119 void
12120 ordinary_breakpoint::print_recreate (struct ui_file *fp) const
12122 if (type == bp_breakpoint && disposition == disp_del)
12123 gdb_printf (fp, "tbreak");
12124 else if (type == bp_breakpoint)
12125 gdb_printf (fp, "break");
12126 else if (type == bp_hardware_breakpoint
12127 && disposition == disp_del)
12128 gdb_printf (fp, "thbreak");
12129 else if (type == bp_hardware_breakpoint)
12130 gdb_printf (fp, "hbreak");
12131 else
12132 internal_error (_("unhandled breakpoint type %d"), (int) type);
12134 gdb_printf (fp, " %s", locspec->to_string ());
12136 /* Print out extra_string if this breakpoint is pending. It might
12137 contain, for example, conditions that were set by the user. */
12138 if (!this->has_locations () && extra_string != NULL)
12139 gdb_printf (fp, " %s", extra_string.get ());
12141 print_recreate_thread (fp);
12144 std::vector<symtab_and_line>
12145 code_breakpoint::decode_location_spec (location_spec *locspec,
12146 program_space *search_pspace)
12148 if (locspec->type () == PROBE_LOCATION_SPEC)
12149 return bkpt_probe_decode_location_spec (this, locspec, search_pspace);
12151 struct linespec_result canonical;
12153 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
12154 NULL, 0, &canonical, multiple_symbols_all,
12155 filter.get ());
12157 /* We should get 0 or 1 resulting SALs. */
12158 gdb_assert (canonical.lsals.size () < 2);
12160 if (!canonical.lsals.empty ())
12162 const linespec_sals &lsal = canonical.lsals[0];
12163 return std::move (lsal.sals);
12165 return {};
12168 /* Virtual table for internal breakpoints. */
12170 void
12171 internal_breakpoint::re_set ()
12173 switch (type)
12175 /* Delete overlay event and longjmp master breakpoints; they
12176 will be reset later by breakpoint_re_set. */
12177 case bp_overlay_event:
12178 case bp_longjmp_master:
12179 case bp_std_terminate_master:
12180 case bp_exception_master:
12181 delete_breakpoint (this);
12182 break;
12184 /* This breakpoint is special, it's set up when the inferior
12185 starts and we really don't want to touch it. */
12186 case bp_shlib_event:
12188 /* Like bp_shlib_event, this breakpoint type is special. Once
12189 it is set up, we do not want to touch it. */
12190 case bp_thread_event:
12191 break;
12195 void
12196 internal_breakpoint::check_status (bpstat *bs)
12198 if (type == bp_shlib_event)
12200 /* If requested, stop when the dynamic linker notifies GDB of
12201 events. This allows the user to get control and place
12202 breakpoints in initializer routines for dynamically loaded
12203 objects (among other things). */
12204 bs->stop = stop_on_solib_events != 0;
12205 bs->print = stop_on_solib_events != 0;
12207 else
12208 bs->stop = false;
12211 enum print_stop_action
12212 internal_breakpoint::print_it (const bpstat *bs) const
12214 switch (type)
12216 case bp_shlib_event:
12217 /* Did we stop because the user set the stop_on_solib_events
12218 variable? (If so, we report this as a generic, "Stopped due
12219 to shlib event" message.) */
12220 print_solib_event (false);
12221 break;
12223 case bp_thread_event:
12224 /* Not sure how we will get here.
12225 GDB should not stop for these breakpoints. */
12226 gdb_printf (_("Thread Event Breakpoint: gdb should not stop!\n"));
12227 break;
12229 case bp_overlay_event:
12230 /* By analogy with the thread event, GDB should not stop for these. */
12231 gdb_printf (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12232 break;
12234 case bp_longjmp_master:
12235 /* These should never be enabled. */
12236 gdb_printf (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12237 break;
12239 case bp_std_terminate_master:
12240 /* These should never be enabled. */
12241 gdb_printf (_("std::terminate Master Breakpoint: "
12242 "gdb should not stop!\n"));
12243 break;
12245 case bp_exception_master:
12246 /* These should never be enabled. */
12247 gdb_printf (_("Exception Master Breakpoint: "
12248 "gdb should not stop!\n"));
12249 break;
12252 return PRINT_NOTHING;
12255 void
12256 internal_breakpoint::print_mention () const
12258 /* Nothing to mention. These breakpoints are internal. */
12261 /* Virtual table for momentary breakpoints */
12263 void
12264 momentary_breakpoint::re_set ()
12266 /* Keep temporary breakpoints, which can be encountered when we step
12267 over a dlopen call and solib_add is resetting the breakpoints.
12268 Otherwise these should have been blown away via the cleanup chain
12269 or by breakpoint_init_inferior when we rerun the executable. */
12272 void
12273 momentary_breakpoint::check_status (bpstat *bs)
12275 /* Nothing. The point of these breakpoints is causing a stop. */
12278 enum print_stop_action
12279 momentary_breakpoint::print_it (const bpstat *bs) const
12281 return PRINT_UNKNOWN;
12284 void
12285 momentary_breakpoint::print_mention () const
12287 /* Nothing to mention. These breakpoints are internal. */
12290 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12292 It gets cleared already on the removal of the first one of such placed
12293 breakpoints. This is OK as they get all removed altogether. */
12295 longjmp_breakpoint::~longjmp_breakpoint ()
12297 thread_info *tp = find_thread_global_id (this->thread);
12299 if (tp != NULL)
12300 tp->initiating_frame = null_frame_id;
12303 static void
12304 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
12305 struct linespec_result *canonical)
12308 struct linespec_sals lsal;
12310 lsal.sals = parse_probes (locspec, NULL, canonical);
12311 lsal.canonical = xstrdup (canonical->locspec->to_string ());
12312 canonical->lsals.push_back (std::move (lsal));
12315 static std::vector<symtab_and_line>
12316 bkpt_probe_decode_location_spec (struct breakpoint *b,
12317 location_spec *locspec,
12318 program_space *search_pspace)
12320 std::vector<symtab_and_line> sals
12321 = parse_probes (locspec, search_pspace, NULL);
12322 if (sals.empty ())
12323 error (_("probe not found"));
12324 return sals;
12328 tracepoint::breakpoint_hit (const struct bp_location *bl,
12329 const address_space *aspace, CORE_ADDR bp_addr,
12330 const target_waitstatus &ws)
12332 /* By definition, the inferior does not report stops at
12333 tracepoints. */
12334 return 0;
12337 void
12338 tracepoint::print_one_detail (struct ui_out *uiout) const
12340 if (!static_trace_marker_id.empty ())
12342 gdb_assert (type == bp_static_tracepoint
12343 || type == bp_static_marker_tracepoint);
12345 uiout->message ("\tmarker id is %pF\n",
12346 string_field ("static-tracepoint-marker-string-id",
12347 static_trace_marker_id.c_str ()));
12351 void
12352 tracepoint::print_mention () const
12354 if (current_uiout->is_mi_like_p ())
12355 return;
12357 switch (type)
12359 case bp_tracepoint:
12360 gdb_printf (_("Tracepoint"));
12361 gdb_printf (_(" %d"), number);
12362 break;
12363 case bp_fast_tracepoint:
12364 gdb_printf (_("Fast tracepoint"));
12365 gdb_printf (_(" %d"), number);
12366 break;
12367 case bp_static_tracepoint:
12368 case bp_static_marker_tracepoint:
12369 gdb_printf (_("Static tracepoint"));
12370 gdb_printf (_(" %d"), number);
12371 break;
12372 default:
12373 internal_error (_("unhandled tracepoint type %d"), (int) type);
12376 say_where ();
12379 void
12380 tracepoint::print_recreate (struct ui_file *fp) const
12382 if (type == bp_fast_tracepoint)
12383 gdb_printf (fp, "ftrace");
12384 else if (type == bp_static_tracepoint
12385 || type == bp_static_marker_tracepoint)
12386 gdb_printf (fp, "strace");
12387 else if (type == bp_tracepoint)
12388 gdb_printf (fp, "trace");
12389 else
12390 internal_error (_("unhandled tracepoint type %d"), (int) type);
12392 gdb_printf (fp, " %s", locspec->to_string ());
12393 print_recreate_thread (fp);
12395 if (pass_count)
12396 gdb_printf (fp, " passcount %d\n", pass_count);
12399 /* Virtual table for tracepoints on static probes. */
12401 static void
12402 tracepoint_probe_create_sals_from_location_spec
12403 (location_spec *locspec,
12404 struct linespec_result *canonical)
12406 /* We use the same method for breakpoint on probes. */
12407 bkpt_probe_create_sals_from_location_spec (locspec, canonical);
12410 void
12411 dprintf_breakpoint::re_set ()
12413 re_set_default ();
12415 /* extra_string should never be non-NULL for dprintf. */
12416 gdb_assert (extra_string != NULL);
12418 /* 1 - connect to target 1, that can run breakpoint commands.
12419 2 - create a dprintf, which resolves fine.
12420 3 - disconnect from target 1
12421 4 - connect to target 2, that can NOT run breakpoint commands.
12423 After steps #3/#4, you'll want the dprintf command list to
12424 be updated, because target 1 and 2 may well return different
12425 answers for target_can_run_breakpoint_commands().
12426 Given absence of finer grained resetting, we get to do
12427 it all the time. */
12428 if (extra_string != NULL)
12429 update_dprintf_command_list (this);
12432 /* Implement the "print_recreate" method for dprintf. */
12434 void
12435 dprintf_breakpoint::print_recreate (struct ui_file *fp) const
12437 gdb_printf (fp, "dprintf %s,%s", locspec->to_string (), extra_string.get ());
12438 print_recreate_thread (fp);
12441 /* Implement the "after_condition_true" method for dprintf.
12443 dprintf's are implemented with regular commands in their command
12444 list, but we run the commands here instead of before presenting the
12445 stop to the user, as dprintf's don't actually cause a stop. This
12446 also makes it so that the commands of multiple dprintfs at the same
12447 address are all handled. */
12449 void
12450 dprintf_breakpoint::after_condition_true (struct bpstat *bs)
12452 /* dprintf's never cause a stop. This wasn't set in the
12453 check_status hook instead because that would make the dprintf's
12454 condition not be evaluated. */
12455 bs->stop = false;
12457 /* Run the command list here. Take ownership of it instead of
12458 copying. We never want these commands to run later in
12459 bpstat_do_actions, if a breakpoint that causes a stop happens to
12460 be set at same address as this dprintf, or even if running the
12461 commands here throws. */
12462 counted_command_line cmds = std::move (bs->commands);
12463 gdb_assert (cmds != nullptr);
12464 execute_control_commands (cmds.get (), 0);
12467 /* The breakpoint_ops structure to be used on static tracepoints with
12468 markers (`-m'). */
12470 static void
12471 strace_marker_create_sals_from_location_spec (location_spec *locspec,
12472 struct linespec_result *canonical)
12474 struct linespec_sals lsal;
12475 const char *arg_start, *arg;
12477 arg = arg_start = as_linespec_location_spec (locspec)->spec_string;
12478 lsal.sals = decode_static_tracepoint_spec (&arg);
12480 std::string str (arg_start, arg - arg_start);
12481 const char *ptr = str.c_str ();
12482 canonical->locspec
12483 = new_linespec_location_spec (&ptr, symbol_name_match_type::FULL);
12485 lsal.canonical = xstrdup (canonical->locspec->to_string ());
12486 canonical->lsals.push_back (std::move (lsal));
12489 static void
12490 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12491 struct linespec_result *canonical,
12492 gdb::unique_xmalloc_ptr<char> cond_string,
12493 gdb::unique_xmalloc_ptr<char> extra_string,
12494 enum bptype type_wanted,
12495 enum bpdisp disposition,
12496 int thread,
12497 int task, int inferior,
12498 int ignore_count,
12499 int from_tty, int enabled,
12500 int internal, unsigned flags)
12502 const linespec_sals &lsal = canonical->lsals[0];
12504 /* If the user is creating a static tracepoint by marker id
12505 (strace -m MARKER_ID), then store the sals index, so that
12506 breakpoint_re_set can try to match up which of the newly
12507 found markers corresponds to this one, and, don't try to
12508 expand multiple locations for each sal, given than SALS
12509 already should contain all sals for MARKER_ID. */
12511 for (size_t i = 0; i < lsal.sals.size (); i++)
12513 location_spec_up locspec = canonical->locspec->clone ();
12515 std::unique_ptr<tracepoint> tp
12516 (new tracepoint (gdbarch,
12517 type_wanted,
12518 lsal.sals[i],
12519 std::move (locspec),
12520 NULL,
12521 std::move (cond_string),
12522 std::move (extra_string),
12523 disposition,
12524 thread, task, inferior, ignore_count,
12525 from_tty, enabled, flags,
12526 canonical->special_display));
12528 /* Given that its possible to have multiple markers with
12529 the same string id, if the user is creating a static
12530 tracepoint by marker id ("strace -m MARKER_ID"), then
12531 store the sals index, so that breakpoint_re_set can
12532 try to match up which of the newly found markers
12533 corresponds to this one */
12534 tp->static_trace_marker_id_idx = i;
12536 install_breakpoint (internal, std::move (tp), 0);
12540 std::vector<symtab_and_line>
12541 static_marker_tracepoint::decode_location_spec (location_spec *locspec,
12542 program_space *search_pspace)
12544 const char *s = as_linespec_location_spec (locspec)->spec_string;
12546 std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
12547 if (sals.size () > static_trace_marker_id_idx)
12549 sals[0] = sals[static_trace_marker_id_idx];
12550 sals.resize (1);
12551 return sals;
12553 else
12554 error (_("marker %s not found"), static_trace_marker_id.c_str ());
12557 /* Static tracepoints with marker (`-m'). */
12558 static struct breakpoint_ops strace_marker_breakpoint_ops =
12560 strace_marker_create_sals_from_location_spec,
12561 strace_marker_create_breakpoints_sal,
12564 static bool
12565 strace_marker_p (struct breakpoint *b)
12567 return b->type == bp_static_marker_tracepoint;
12570 /* Notify interpreters and observers that breakpoint B was deleted. */
12572 static void
12573 notify_breakpoint_deleted (breakpoint *b)
12575 interps_notify_breakpoint_deleted (b);
12576 gdb::observers::breakpoint_deleted.notify (b);
12579 /* Delete a breakpoint and clean up all traces of it in the data
12580 structures. */
12582 void
12583 delete_breakpoint (struct breakpoint *bpt)
12585 gdb_assert (bpt != NULL);
12587 /* Has this bp already been deleted? This can happen because
12588 multiple lists can hold pointers to bp's. bpstat lists are
12589 especial culprits.
12591 One example of this happening is a watchpoint's scope bp. When
12592 the scope bp triggers, we notice that the watchpoint is out of
12593 scope, and delete it. We also delete its scope bp. But the
12594 scope bp is marked "auto-deleting", and is already on a bpstat.
12595 That bpstat is then checked for auto-deleting bp's, which are
12596 deleted.
12598 A real solution to this problem might involve reference counts in
12599 bp's, and/or giving them pointers back to their referencing
12600 bpstat's, and teaching delete_breakpoint to only free a bp's
12601 storage when no more references were extent. A cheaper bandaid
12602 was chosen. */
12603 if (bpt->type == bp_none)
12604 return;
12606 /* At least avoid this stale reference until the reference counting
12607 of breakpoints gets resolved. */
12608 if (bpt->related_breakpoint != bpt)
12610 struct breakpoint *related;
12611 struct watchpoint *w;
12613 if (bpt->type == bp_watchpoint_scope)
12614 w = gdb::checked_static_cast<watchpoint *> (bpt->related_breakpoint);
12615 else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12616 w = gdb::checked_static_cast<watchpoint *> (bpt);
12617 else
12618 w = NULL;
12619 if (w != NULL)
12620 watchpoint_del_at_next_stop (w);
12622 /* Unlink bpt from the bpt->related_breakpoint ring. */
12623 for (related = bpt; related->related_breakpoint != bpt;
12624 related = related->related_breakpoint);
12625 related->related_breakpoint = bpt->related_breakpoint;
12626 bpt->related_breakpoint = bpt;
12629 /* watch_command_1 creates a watchpoint but only sets its number if
12630 update_watchpoint succeeds in creating its bp_locations. If there's
12631 a problem in that process, we'll be asked to delete the half-created
12632 watchpoint. In that case, don't announce the deletion. */
12633 if (bpt->number)
12634 notify_breakpoint_deleted (bpt);
12636 breakpoint_chain.erase (breakpoint_chain.iterator_to (*bpt));
12638 /* Be sure no bpstat's are pointing at the breakpoint after it's
12639 been freed. */
12640 /* FIXME, how can we find all bpstat's? We just check stop_bpstat
12641 in all threads for now. Note that we cannot just remove bpstats
12642 pointing at bpt from the stop_bpstat list entirely, as breakpoint
12643 commands are associated with the bpstat; if we remove it here,
12644 then the later call to bpstat_do_actions (&stop_bpstat); in
12645 event-top.c won't do anything, and temporary breakpoints with
12646 commands won't work. */
12648 iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12650 /* Now that breakpoint is removed from breakpoint list, update the
12651 global location list. This will remove locations that used to
12652 belong to this breakpoint. Do this before freeing the breakpoint
12653 itself, since remove_breakpoint looks at location's owner. It
12654 might be better design to have location completely
12655 self-contained, but it's not the case now.
12657 Clear the location linked list first, otherwise, the intrusive_list
12658 destructor accesses the locations after they are freed. */
12659 bpt->clear_locations ();
12660 update_global_location_list (UGLL_DONT_INSERT);
12662 /* On the chance that someone will soon try again to delete this
12663 same bp, we mark it as deleted before freeing its storage. */
12664 bpt->type = bp_none;
12665 delete bpt;
12668 /* Iterator function to call a user-provided callback function once
12669 for each of B and its related breakpoints. */
12671 static void
12672 iterate_over_related_breakpoints (struct breakpoint *b,
12673 gdb::function_view<void (breakpoint *)> function)
12675 struct breakpoint *related;
12677 related = b;
12680 struct breakpoint *next;
12682 /* FUNCTION may delete RELATED. */
12683 next = related->related_breakpoint;
12685 if (next == related)
12687 /* RELATED is the last ring entry. */
12688 function (related);
12690 /* FUNCTION may have deleted it, so we'd never reach back to
12691 B. There's nothing left to do anyway, so just break
12692 out. */
12693 break;
12695 else
12696 function (related);
12698 related = next;
12700 while (related != b);
12703 static void
12704 delete_command (const char *arg, int from_tty)
12706 dont_repeat ();
12708 if (arg == 0)
12710 int breaks_to_delete = 0;
12712 /* Delete all breakpoints if no argument. Do not delete
12713 internal breakpoints, these have to be deleted with an
12714 explicit breakpoint number argument. */
12715 for (breakpoint &b : all_breakpoints ())
12716 if (user_breakpoint_p (&b))
12718 breaks_to_delete = 1;
12719 break;
12722 /* Ask user only if there are some breakpoints to delete. */
12723 if (!from_tty
12724 || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12725 for (breakpoint &b : all_breakpoints_safe ())
12726 if (user_breakpoint_p (&b))
12727 delete_breakpoint (&b);
12729 else
12730 map_breakpoint_numbers
12731 (arg, [&] (breakpoint *br)
12733 iterate_over_related_breakpoints (br, delete_breakpoint);
12737 /* Return true if all locations of B bound to PSPACE are pending. If
12738 PSPACE is NULL, all locations of all program spaces are
12739 considered. */
12741 static bool
12742 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
12744 for (bp_location &loc : b->locations ())
12745 if ((pspace == NULL
12746 || loc.pspace == pspace)
12747 && !loc.shlib_disabled
12748 && !loc.pspace->executing_startup)
12749 return false;
12750 return true;
12753 /* Subroutine of update_breakpoint_locations to simplify it.
12754 Return true if multiple fns in list LOCS have the same name.
12755 Null names are ignored. */
12757 static bool
12758 ambiguous_names_p (const bp_location_range &locs)
12760 htab_up htab (htab_create_alloc (13, htab_hash_string, htab_eq_string, NULL,
12761 xcalloc, xfree));
12763 for (const bp_location &l : locs)
12765 const char **slot;
12766 const char *name = l.function_name.get ();
12768 /* Allow for some names to be NULL, ignore them. */
12769 if (name == NULL)
12770 continue;
12772 slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
12773 INSERT);
12774 /* NOTE: We can assume slot != NULL here because xcalloc never
12775 returns NULL. */
12776 if (*slot != NULL)
12777 return true;
12778 *slot = name;
12781 return false;
12784 /* When symbols change, it probably means the sources changed as well,
12785 and it might mean the static tracepoint markers are no longer at
12786 the same address or line numbers they used to be at last we
12787 checked. Losing your static tracepoints whenever you rebuild is
12788 undesirable. This function tries to resync/rematch gdb static
12789 tracepoints with the markers on the target, for static tracepoints
12790 that have not been set by marker id. Static tracepoint that have
12791 been set by marker id are reset by marker id in breakpoint_re_set.
12792 The heuristic is:
12794 1) For a tracepoint set at a specific address, look for a marker at
12795 the old PC. If one is found there, assume to be the same marker.
12796 If the name / string id of the marker found is different from the
12797 previous known name, assume that means the user renamed the marker
12798 in the sources, and output a warning.
12800 2) For a tracepoint set at a given line number, look for a marker
12801 at the new address of the old line number. If one is found there,
12802 assume to be the same marker. If the name / string id of the
12803 marker found is different from the previous known name, assume that
12804 means the user renamed the marker in the sources, and output a
12805 warning.
12807 3) If a marker is no longer found at the same address or line, it
12808 may mean the marker no longer exists. But it may also just mean
12809 the code changed a bit. Maybe the user added a few lines of code
12810 that made the marker move up or down (in line number terms). Ask
12811 the target for info about the marker with the string id as we knew
12812 it. If found, update line number and address in the matching
12813 static tracepoint. This will get confused if there's more than one
12814 marker with the same ID (possible in UST, although unadvised
12815 precisely because it confuses tools). */
12817 static struct symtab_and_line
12818 update_static_tracepoint (tracepoint *tp, struct symtab_and_line sal)
12820 struct static_tracepoint_marker marker;
12821 CORE_ADDR pc;
12823 pc = sal.pc;
12824 if (sal.line)
12825 find_line_pc (sal.symtab, sal.line, &pc);
12827 if (target_static_tracepoint_marker_at (pc, &marker))
12829 if (tp->static_trace_marker_id != marker.str_id)
12830 warning (_("static tracepoint %d changed probed marker from %s to %s"),
12831 tp->number, tp->static_trace_marker_id.c_str (),
12832 marker.str_id.c_str ());
12834 tp->static_trace_marker_id = std::move (marker.str_id);
12836 return sal;
12839 /* Old marker wasn't found on target at lineno. Try looking it up
12840 by string ID. */
12841 if (!sal.explicit_pc
12842 && sal.line != 0
12843 && sal.symtab != NULL
12844 && !tp->static_trace_marker_id.empty ())
12846 std::vector<static_tracepoint_marker> markers
12847 = target_static_tracepoint_markers_by_strid
12848 (tp->static_trace_marker_id.c_str ());
12850 if (!markers.empty ())
12852 struct symbol *sym;
12853 struct static_tracepoint_marker *tpmarker;
12854 struct ui_out *uiout = current_uiout;
12856 tpmarker = &markers[0];
12858 tp->static_trace_marker_id = std::move (tpmarker->str_id);
12860 warning (_("marker for static tracepoint %d (%s) not "
12861 "found at previous line number"),
12862 tp->number, tp->static_trace_marker_id.c_str ());
12864 symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
12865 sym = find_pc_sect_function (tpmarker->address, NULL);
12866 uiout->text ("Now in ");
12867 if (sym)
12869 uiout->field_string ("func", sym->print_name (),
12870 function_name_style.style ());
12871 uiout->text (" at ");
12873 uiout->field_string ("file",
12874 symtab_to_filename_for_display (sal2.symtab),
12875 file_name_style.style ());
12876 uiout->text (":");
12878 if (uiout->is_mi_like_p ())
12880 const char *fullname = symtab_to_fullname (sal2.symtab);
12882 uiout->field_string ("fullname", fullname);
12885 uiout->field_signed ("line", sal2.line);
12886 uiout->text ("\n");
12888 tp->first_loc ().line_number = sal2.line;
12889 tp->first_loc ().symtab = sym != NULL ? sal2.symtab : NULL;
12891 std::unique_ptr<explicit_location_spec> els
12892 (new explicit_location_spec ());
12893 els->source_filename
12894 = xstrdup (symtab_to_filename_for_display (sal2.symtab));
12895 els->line_offset.offset = tp->first_loc ().line_number;
12896 els->line_offset.sign = LINE_OFFSET_NONE;
12898 tp->locspec = std::move (els);
12900 /* Might be nice to check if function changed, and warn if
12901 so. */
12904 return sal;
12907 /* Returns true iff location lists A and B are sufficiently same that
12908 we don't need to report breakpoint as changed. */
12910 static bool
12911 locations_are_equal (const bp_location_list &a, const bp_location_range &b)
12913 auto a_iter = a.begin ();
12914 auto b_iter = b.begin ();
12916 for (; a_iter != a.end () && b_iter != b.end (); ++a_iter, ++b_iter)
12918 if (a_iter->address != b_iter->address)
12919 return false;
12921 if (a_iter->shlib_disabled != b_iter->shlib_disabled)
12922 return false;
12924 if (a_iter->enabled != b_iter->enabled)
12925 return false;
12927 if (a_iter->disabled_by_cond != b_iter->disabled_by_cond)
12928 return false;
12931 return (a_iter == a.end ()) == (b_iter == b.end ());
12934 /* See breakpoint.h. */
12936 bp_location_list
12937 breakpoint::steal_locations (program_space *pspace)
12939 if (pspace == NULL)
12940 return std::move (m_locations);
12942 bp_location_list ret;
12944 for (auto it = m_locations.begin (); it != m_locations.end (); )
12946 if (it->pspace == pspace)
12948 bp_location &loc = *it;
12949 it = m_locations.erase (it);
12950 ret.push_back (loc);
12952 else
12953 ++it;
12956 return ret;
12959 /* Create new breakpoint locations for B (a hardware or software
12960 breakpoint) based on SALS and SALS_END. If SALS_END.NELTS is not
12961 zero, then B is a ranged breakpoint. Only recreates locations for
12962 FILTER_PSPACE. Locations of other program spaces are left
12963 untouched. */
12965 void
12966 update_breakpoint_locations (code_breakpoint *b,
12967 struct program_space *filter_pspace,
12968 gdb::array_view<const symtab_and_line> sals,
12969 gdb::array_view<const symtab_and_line> sals_end)
12971 if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
12973 /* Ranged breakpoints have only one start location and one end
12974 location. */
12975 b->enable_state = bp_disabled;
12976 gdb_printf (gdb_stderr,
12977 _("Could not reset ranged breakpoint %d: "
12978 "multiple locations found\n"),
12979 b->number);
12980 return;
12983 /* If there's no new locations, and all existing locations are
12984 pending, don't do anything. This optimizes the common case where
12985 all locations are in the same shared library, that was unloaded.
12986 We'd like to retain the location, so that when the library is
12987 loaded again, we don't loose the enabled/disabled status of the
12988 individual locations. */
12989 if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
12990 return;
12992 bp_location_list existing_locations = b->steal_locations (filter_pspace);
12994 for (const auto &sal : sals)
12996 struct bp_location *new_loc;
12998 switch_to_program_space_and_thread (sal.pspace);
13000 new_loc = b->add_location (sal);
13002 /* Reparse conditions, they might contain references to the
13003 old symtab. */
13004 if (b->cond_string != NULL)
13006 const char *s;
13008 s = b->cond_string.get ();
13011 new_loc->cond = parse_exp_1 (&s, sal.pc,
13012 block_for_pc (sal.pc),
13015 catch (const gdb_exception_error &e)
13017 new_loc->disabled_by_cond = true;
13021 if (!sals_end.empty ())
13023 CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13025 new_loc->length = end - sals[0].pc + 1;
13029 /* If possible, carry over 'disable' status from existing
13030 breakpoints. */
13032 /* If there are multiple breakpoints with the same function name,
13033 e.g. for inline functions, comparing function names won't work.
13034 Instead compare pc addresses; this is just a heuristic as things
13035 may have moved, but in practice it gives the correct answer
13036 often enough until a better solution is found. */
13037 int have_ambiguous_names = ambiguous_names_p (b->locations ());
13039 for (const bp_location &e : existing_locations)
13041 if ((!e.enabled || e.disabled_by_cond) && e.function_name)
13043 if (have_ambiguous_names)
13045 for (bp_location &l : b->locations ())
13047 /* Ignore software vs hardware location type at
13048 this point, because with "set breakpoint
13049 auto-hw", after a re-set, locations that were
13050 hardware can end up as software, or vice versa.
13051 As mentioned above, this is an heuristic and in
13052 practice should give the correct answer often
13053 enough. */
13054 if (breakpoint_locations_match (&e, &l, true))
13056 l.enabled = e.enabled;
13057 l.disabled_by_cond = e.disabled_by_cond;
13058 break;
13062 else
13064 for (bp_location &l : b->locations ())
13065 if (l.function_name
13066 && strcmp (e.function_name.get (),
13067 l.function_name.get ()) == 0)
13069 l.enabled = e.enabled;
13070 l.disabled_by_cond = e.disabled_by_cond;
13071 break;
13078 if (!locations_are_equal (existing_locations, b->locations ()))
13079 notify_breakpoint_modified (b);
13082 /* Find the SaL locations corresponding to the given LOCSPEC.
13083 On return, FOUND will be 1 if any SaL was found, zero otherwise. */
13085 std::vector<symtab_and_line>
13086 code_breakpoint::location_spec_to_sals (location_spec *locspec,
13087 struct program_space *search_pspace,
13088 int *found)
13090 struct gdb_exception exception;
13092 std::vector<symtab_and_line> sals;
13096 sals = decode_location_spec (locspec, search_pspace);
13098 catch (gdb_exception_error &e)
13100 int not_found_and_ok = false;
13102 /* For pending breakpoints, it's expected that parsing will
13103 fail until the right shared library is loaded. User has
13104 already told to create pending breakpoints and don't need
13105 extra messages. If breakpoint is in bp_shlib_disabled
13106 state, then user already saw the message about that
13107 breakpoint being disabled, and don't want to see more
13108 errors. */
13109 if (e.error == NOT_FOUND_ERROR
13110 && (condition_not_parsed
13111 || (this->has_locations ()
13112 && search_pspace != NULL
13113 && this->first_loc ().pspace != search_pspace)
13114 || (this->has_locations () && this->first_loc ().shlib_disabled)
13115 || (this->has_locations ()
13116 && this->first_loc ().pspace->executing_startup)
13117 || enable_state == bp_disabled))
13118 not_found_and_ok = true;
13120 if (!not_found_and_ok)
13122 /* We surely don't want to warn about the same breakpoint
13123 10 times. One solution, implemented here, is disable
13124 the breakpoint on error. Another solution would be to
13125 have separate 'warning emitted' flag. Since this
13126 happens only when a binary has changed, I don't know
13127 which approach is better. */
13128 enable_state = bp_disabled;
13129 throw;
13132 exception = std::move (e);
13135 if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13137 for (auto &sal : sals)
13138 resolve_sal_pc (&sal);
13139 if (condition_not_parsed && extra_string != NULL)
13141 gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
13142 int local_thread, local_task, local_inferior;
13144 find_condition_and_thread_for_sals (sals, extra_string.get (),
13145 &local_cond, &local_thread,
13146 &local_inferior,
13147 &local_task, &local_extra);
13148 gdb_assert (cond_string == nullptr);
13149 if (local_cond != nullptr)
13150 cond_string = std::move (local_cond);
13151 thread = local_thread;
13152 task = local_task;
13153 if (local_extra != nullptr)
13154 extra_string = std::move (local_extra);
13155 condition_not_parsed = 0;
13158 if (type == bp_static_tracepoint)
13160 tracepoint *t = gdb::checked_static_cast<tracepoint *> (this);
13161 sals[0] = update_static_tracepoint (t, sals[0]);
13164 *found = 1;
13166 else
13167 *found = 0;
13169 return sals;
13172 /* The default re_set method, for typical hardware or software
13173 breakpoints. Reevaluate the breakpoint and recreate its
13174 locations. */
13176 void
13177 code_breakpoint::re_set_default ()
13179 struct program_space *filter_pspace = current_program_space;
13180 std::vector<symtab_and_line> expanded, expanded_end;
13182 int found;
13183 std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
13184 filter_pspace,
13185 &found);
13186 if (found)
13187 expanded = std::move (sals);
13189 if (locspec_range_end != nullptr)
13191 std::vector<symtab_and_line> sals_end
13192 = location_spec_to_sals (locspec_range_end.get (),
13193 filter_pspace, &found);
13194 if (found)
13195 expanded_end = std::move (sals_end);
13198 update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
13201 /* Default method for creating SALs from an address string. It basically
13202 calls parse_breakpoint_sals. Return 1 for success, zero for failure. */
13204 static void
13205 create_sals_from_location_spec_default (location_spec *locspec,
13206 struct linespec_result *canonical)
13208 parse_breakpoint_sals (locspec, canonical);
13211 /* Reset a breakpoint. */
13213 static void
13214 breakpoint_re_set_one (breakpoint *b)
13216 input_radix = b->input_radix;
13217 set_language (b->language);
13219 b->re_set ();
13222 /* Re-set breakpoint locations for the current program space.
13223 Locations bound to other program spaces are left untouched. */
13225 void
13226 breakpoint_re_set (void)
13229 scoped_restore_current_language save_language;
13230 scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13231 scoped_restore_current_pspace_and_thread restore_pspace_thread;
13233 /* breakpoint_re_set_one sets the current_language to the language
13234 of the breakpoint it is resetting (see prepare_re_set_context)
13235 before re-evaluating the breakpoint's location. This change can
13236 unfortunately get undone by accident if the language_mode is set
13237 to auto, and we either switch frames, or more likely in this context,
13238 we select the current frame.
13240 We prevent this by temporarily turning the language_mode to
13241 language_mode_manual. We restore it once all breakpoints
13242 have been reset. */
13243 scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13244 language_mode = language_mode_manual;
13246 /* Note: we must not try to insert locations until after all
13247 breakpoints have been re-set. Otherwise, e.g., when re-setting
13248 breakpoint 1, we'd insert the locations of breakpoint 2, which
13249 hadn't been re-set yet, and thus may have stale locations. */
13251 for (breakpoint &b : all_breakpoints_safe ())
13255 breakpoint_re_set_one (&b);
13257 catch (const gdb_exception &ex)
13259 exception_fprintf (gdb_stderr, ex,
13260 "Error in re-setting breakpoint %d: ",
13261 b.number);
13265 jit_breakpoint_re_set ();
13268 create_overlay_event_breakpoint ();
13269 create_longjmp_master_breakpoint ();
13270 create_std_terminate_master_breakpoint ();
13271 create_exception_master_breakpoint ();
13273 /* Now we can insert. */
13274 update_global_location_list (UGLL_MAY_INSERT);
13277 /* Reset the thread number of this breakpoint:
13279 - If the breakpoint is for all threads, leave it as-is.
13280 - Else, reset it to the current thread for inferior_ptid. */
13281 void
13282 breakpoint_re_set_thread (struct breakpoint *b)
13284 if (b->thread != -1)
13286 b->thread = inferior_thread ()->global_num;
13288 /* We're being called after following a fork. The new fork is
13289 selected as current, and unless this was a vfork will have a
13290 different program space from the original thread. Reset that
13291 as well. */
13292 b->first_loc ().pspace = current_program_space;
13296 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13297 If from_tty is nonzero, it prints a message to that effect,
13298 which ends with a period (no newline). */
13300 void
13301 set_ignore_count (int bptnum, int count, int from_tty)
13303 if (count < 0)
13304 count = 0;
13306 for (breakpoint &b : all_breakpoints ())
13307 if (b.number == bptnum)
13309 if (is_tracepoint (&b))
13311 if (from_tty && count != 0)
13312 gdb_printf (_("Ignore count ignored for tracepoint %d."),
13313 bptnum);
13314 return;
13317 b.ignore_count = count;
13318 if (from_tty)
13320 if (count == 0)
13321 gdb_printf (_("Will stop next time "
13322 "breakpoint %d is reached."),
13323 bptnum);
13324 else if (count == 1)
13325 gdb_printf (_("Will ignore next crossing of breakpoint %d."),
13326 bptnum);
13327 else
13328 gdb_printf (_("Will ignore next %d "
13329 "crossings of breakpoint %d."),
13330 count, bptnum);
13332 notify_breakpoint_modified (&b);
13333 return;
13336 error (_("No breakpoint number %d."), bptnum);
13339 /* Command to set ignore-count of breakpoint N to COUNT. */
13341 static void
13342 ignore_command (const char *args, int from_tty)
13344 const char *p = args;
13345 int num;
13347 if (p == 0)
13348 error_no_arg (_("a breakpoint number"));
13350 num = get_number (&p);
13351 if (num == 0)
13352 error (_("bad breakpoint number: '%s'"), args);
13353 if (*p == 0)
13354 error (_("Second argument (specified ignore-count) is missing."));
13356 set_ignore_count (num,
13357 longest_to_int (value_as_long (parse_and_eval (p))),
13358 from_tty);
13359 if (from_tty)
13360 gdb_printf ("\n");
13364 /* Call FUNCTION on each of the breakpoints with numbers in the range
13365 defined by BP_NUM_RANGE (an inclusive range). */
13367 static void
13368 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13369 gdb::function_view<void (breakpoint *)> function)
13371 if (bp_num_range.first == 0)
13373 warning (_("bad breakpoint number at or near '%d'"),
13374 bp_num_range.first);
13376 else
13378 for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
13380 bool match = false;
13382 for (breakpoint &b : all_breakpoints_safe ())
13383 if (b.number == i)
13385 match = true;
13386 function (&b);
13387 break;
13389 if (!match)
13390 gdb_printf (_("No breakpoint number %d.\n"), i);
13395 /* Call FUNCTION on each of the breakpoints whose numbers are given in
13396 ARGS. */
13398 static void
13399 map_breakpoint_numbers (const char *args,
13400 gdb::function_view<void (breakpoint *)> function)
13402 if (args == NULL || *args == '\0')
13403 error_no_arg (_("one or more breakpoint numbers"));
13405 number_or_range_parser parser (args);
13407 while (!parser.finished ())
13409 int num = parser.get_number ();
13410 map_breakpoint_number_range (std::make_pair (num, num), function);
13414 /* Return the breakpoint location structure corresponding to the
13415 BP_NUM and LOC_NUM values. */
13417 static struct bp_location *
13418 find_location_by_number (int bp_num, int loc_num)
13420 breakpoint *b = get_breakpoint (bp_num);
13422 if (!b || b->number != bp_num)
13423 error (_("Bad breakpoint number '%d'"), bp_num);
13425 if (loc_num == 0)
13426 error (_("Bad breakpoint location number '%d'"), loc_num);
13428 int n = 0;
13429 for (bp_location &loc : b->locations ())
13430 if (++n == loc_num)
13431 return &loc;
13433 error (_("Bad breakpoint location number '%d'"), loc_num);
13436 /* Modes of operation for extract_bp_num. */
13437 enum class extract_bp_kind
13439 /* Extracting a breakpoint number. */
13442 /* Extracting a location number. */
13443 loc,
13446 /* Extract a breakpoint or location number (as determined by KIND)
13447 from the string starting at START. TRAILER is a character which
13448 can be found after the number. If you don't want a trailer, use
13449 '\0'. If END_OUT is not NULL, it is set to point after the parsed
13450 string. This always returns a positive integer. */
13452 static int
13453 extract_bp_num (extract_bp_kind kind, const char *start,
13454 int trailer, const char **end_out = NULL)
13456 const char *end = start;
13457 int num = get_number_trailer (&end, trailer);
13458 if (num < 0)
13459 error (kind == extract_bp_kind::bp
13460 ? _("Negative breakpoint number '%.*s'")
13461 : _("Negative breakpoint location number '%.*s'"),
13462 int (end - start), start);
13463 if (num == 0)
13464 error (kind == extract_bp_kind::bp
13465 ? _("Bad breakpoint number '%.*s'")
13466 : _("Bad breakpoint location number '%.*s'"),
13467 int (end - start), start);
13469 if (end_out != NULL)
13470 *end_out = end;
13471 return num;
13474 /* Extract a breakpoint or location range (as determined by KIND) in
13475 the form NUM1-NUM2 stored at &ARG[arg_offset]. Returns a std::pair
13476 representing the (inclusive) range. The returned pair's elements
13477 are always positive integers. */
13479 static std::pair<int, int>
13480 extract_bp_or_bp_range (extract_bp_kind kind,
13481 const std::string &arg,
13482 std::string::size_type arg_offset)
13484 std::pair<int, int> range;
13485 const char *bp_loc = &arg[arg_offset];
13486 std::string::size_type dash = arg.find ('-', arg_offset);
13487 if (dash != std::string::npos)
13489 /* bp_loc is a range (x-z). */
13490 if (arg.length () == dash + 1)
13491 error (kind == extract_bp_kind::bp
13492 ? _("Bad breakpoint number at or near: '%s'")
13493 : _("Bad breakpoint location number at or near: '%s'"),
13494 bp_loc);
13496 const char *end;
13497 const char *start_first = bp_loc;
13498 const char *start_second = &arg[dash + 1];
13499 range.first = extract_bp_num (kind, start_first, '-');
13500 range.second = extract_bp_num (kind, start_second, '\0', &end);
13502 if (range.first > range.second)
13503 error (kind == extract_bp_kind::bp
13504 ? _("Inverted breakpoint range at '%.*s'")
13505 : _("Inverted breakpoint location range at '%.*s'"),
13506 int (end - start_first), start_first);
13508 else
13510 /* bp_loc is a single value. */
13511 range.first = extract_bp_num (kind, bp_loc, '\0');
13512 range.second = range.first;
13514 return range;
13517 /* Extract the breakpoint/location range specified by ARG. Returns
13518 the breakpoint range in BP_NUM_RANGE, and the location range in
13519 BP_LOC_RANGE.
13521 ARG may be in any of the following forms:
13523 x where 'x' is a breakpoint number.
13524 x-y where 'x' and 'y' specify a breakpoint numbers range.
13525 x.y where 'x' is a breakpoint number and 'y' a location number.
13526 x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
13527 location number range.
13530 static void
13531 extract_bp_number_and_location (const std::string &arg,
13532 std::pair<int, int> &bp_num_range,
13533 std::pair<int, int> &bp_loc_range)
13535 std::string::size_type dot = arg.find ('.');
13537 if (dot != std::string::npos)
13539 /* Handle 'x.y' and 'x.y-z' cases. */
13541 if (arg.length () == dot + 1 || dot == 0)
13542 error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
13544 bp_num_range.first
13545 = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
13546 bp_num_range.second = bp_num_range.first;
13548 bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
13549 arg, dot + 1);
13551 else
13553 /* Handle x and x-y cases. */
13555 bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
13556 bp_loc_range.first = 0;
13557 bp_loc_range.second = 0;
13561 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM. ENABLE
13562 specifies whether to enable or disable. */
13564 static void
13565 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
13567 struct bp_location *loc = find_location_by_number (bp_num, loc_num);
13568 if (loc != NULL)
13570 if (loc->disabled_by_cond && enable)
13571 error (_("Breakpoint %d's condition is invalid at location %d, "
13572 "cannot enable."), bp_num, loc_num);
13574 if (loc->enabled != enable)
13576 loc->enabled = enable;
13577 mark_breakpoint_location_modified (loc);
13579 if (target_supports_enable_disable_tracepoint ()
13580 && current_trace_status ()->running && loc->owner
13581 && is_tracepoint (loc->owner))
13582 target_disable_tracepoint (loc);
13584 update_global_location_list (UGLL_DONT_INSERT);
13586 notify_breakpoint_modified (loc->owner);
13589 /* Calculates LOC_NUM for LOC by traversing the bp_location chain of LOC's
13590 owner. 1-based indexing. -1 signals NOT FOUND. */
13592 static int
13593 find_loc_num_by_location (const bp_location *loc)
13595 if (loc != nullptr && loc->owner != nullptr)
13597 /* Locations use 1-based indexing. */
13598 int loc_num = 1;
13599 for (bp_location &it : loc->owner->locations ())
13601 if (&it == loc)
13602 return loc_num;
13603 loc_num++;
13606 return -1;
13609 /* Enable or disable a breakpoint location LOC. ENABLE
13610 specifies whether to enable or disable. */
13612 void
13613 enable_disable_bp_location (bp_location *loc, bool enable)
13615 if (loc == nullptr)
13616 error (_("Breakpoint location is invalid."));
13618 if (loc->owner == nullptr)
13619 error (_("Breakpoint location does not have an owner breakpoint."));
13621 if (loc->disabled_by_cond && enable)
13623 int loc_num = find_loc_num_by_location (loc);
13624 if (loc_num == -1)
13625 error (_("Breakpoint location LOC_NUM could not be found."));
13626 else
13627 error (_("Breakpoint %d's condition is invalid at location %d, "
13628 "cannot enable."), loc->owner->number, loc_num);
13631 if (loc->enabled != enable)
13633 loc->enabled = enable;
13634 mark_breakpoint_location_modified (loc);
13637 if (target_supports_enable_disable_tracepoint ()
13638 && current_trace_status ()->running && loc->owner
13639 && is_tracepoint (loc->owner))
13640 target_disable_tracepoint (loc);
13642 update_global_location_list (UGLL_DONT_INSERT);
13643 notify_breakpoint_modified (loc->owner);
13646 /* Enable or disable a range of breakpoint locations. BP_NUM is the
13647 number of the breakpoint, and BP_LOC_RANGE specifies the
13648 (inclusive) range of location numbers of that breakpoint to
13649 enable/disable. ENABLE specifies whether to enable or disable the
13650 location. */
13652 static void
13653 enable_disable_breakpoint_location_range (int bp_num,
13654 std::pair<int, int> &bp_loc_range,
13655 bool enable)
13657 for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
13658 enable_disable_bp_num_loc (bp_num, i, enable);
13661 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13662 If from_tty is nonzero, it prints a message to that effect,
13663 which ends with a period (no newline). */
13665 void
13666 disable_breakpoint (struct breakpoint *bpt)
13668 /* Never disable a watchpoint scope breakpoint; we want to
13669 hit them when we leave scope so we can delete both the
13670 watchpoint and its scope breakpoint at that time. */
13671 if (bpt->type == bp_watchpoint_scope)
13672 return;
13674 bpt->enable_state = bp_disabled;
13676 /* Mark breakpoint locations modified. */
13677 mark_breakpoint_modified (bpt);
13679 if (target_supports_enable_disable_tracepoint ()
13680 && current_trace_status ()->running && is_tracepoint (bpt))
13682 for (bp_location &location : bpt->locations ())
13683 target_disable_tracepoint (&location);
13686 update_global_location_list (UGLL_DONT_INSERT);
13688 notify_breakpoint_modified (bpt);
13691 /* Enable or disable the breakpoint(s) or breakpoint location(s)
13692 specified in ARGS. ARGS may be in any of the formats handled by
13693 extract_bp_number_and_location. ENABLE specifies whether to enable
13694 or disable the breakpoints/locations. */
13696 static void
13697 enable_disable_command (const char *args, int from_tty, bool enable)
13699 if (args == 0)
13701 for (breakpoint &bpt : all_breakpoints ())
13702 if (user_breakpoint_p (&bpt))
13704 if (enable)
13705 enable_breakpoint (&bpt);
13706 else
13707 disable_breakpoint (&bpt);
13710 else
13712 std::string num = extract_arg (&args);
13714 while (!num.empty ())
13716 std::pair<int, int> bp_num_range, bp_loc_range;
13718 extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
13720 if (bp_loc_range.first == bp_loc_range.second
13721 && (bp_loc_range.first == 0
13722 || (bp_loc_range.first == 1
13723 && bp_num_range.first == bp_num_range.second
13724 && !has_multiple_locations (bp_num_range.first))))
13726 /* Handle breakpoint ids with formats 'x' or 'x-z'
13727 or 'y.1' where y has only one code location. */
13728 map_breakpoint_number_range (bp_num_range,
13729 enable
13730 ? enable_breakpoint
13731 : disable_breakpoint);
13733 else
13735 /* Handle breakpoint ids with formats 'x.y' or
13736 'x.y-z'. */
13737 enable_disable_breakpoint_location_range
13738 (bp_num_range.first, bp_loc_range, enable);
13740 num = extract_arg (&args);
13745 /* The disable command disables the specified breakpoints/locations
13746 (or all defined breakpoints) so they're no longer effective in
13747 stopping the inferior. ARGS may be in any of the forms defined in
13748 extract_bp_number_and_location. */
13750 static void
13751 disable_command (const char *args, int from_tty)
13753 enable_disable_command (args, from_tty, false);
13756 static void
13757 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13758 int count)
13760 int target_resources_ok;
13762 if (bpt->type == bp_hardware_breakpoint)
13764 int i;
13765 i = hw_breakpoint_used_count ();
13766 target_resources_ok =
13767 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
13768 i + 1, 0);
13769 if (target_resources_ok == 0)
13770 error (_("No hardware breakpoint support in the target."));
13771 else if (target_resources_ok < 0)
13772 error (_("Hardware breakpoints used exceeds limit."));
13775 if (is_watchpoint (bpt))
13777 /* Initialize it just to avoid a GCC false warning. */
13778 enum enable_state orig_enable_state = bp_disabled;
13782 watchpoint *w = gdb::checked_static_cast<watchpoint *> (bpt);
13784 orig_enable_state = bpt->enable_state;
13785 bpt->enable_state = bp_enabled;
13786 update_watchpoint (w, true /* reparse */);
13788 catch (const gdb_exception_error &e)
13790 bpt->enable_state = orig_enable_state;
13791 exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13792 bpt->number);
13793 return;
13797 bpt->enable_state = bp_enabled;
13799 /* Mark breakpoint locations modified. */
13800 mark_breakpoint_modified (bpt);
13802 if (target_supports_enable_disable_tracepoint ()
13803 && current_trace_status ()->running && is_tracepoint (bpt))
13805 for (bp_location &location : bpt->locations ())
13806 target_enable_tracepoint (&location);
13809 bpt->disposition = disposition;
13810 bpt->enable_count = count;
13811 update_global_location_list (UGLL_MAY_INSERT);
13813 notify_breakpoint_modified (bpt);
13817 void
13818 enable_breakpoint (struct breakpoint *bpt)
13820 enable_breakpoint_disp (bpt, bpt->disposition, 0);
13823 /* The enable command enables the specified breakpoints/locations (or
13824 all defined breakpoints) so they once again become (or continue to
13825 be) effective in stopping the inferior. ARGS may be in any of the
13826 forms defined in extract_bp_number_and_location. */
13828 static void
13829 enable_command (const char *args, int from_tty)
13831 enable_disable_command (args, from_tty, true);
13834 static void
13835 enable_once_command (const char *args, int from_tty)
13837 map_breakpoint_numbers
13838 (args, [&] (breakpoint *b)
13840 iterate_over_related_breakpoints
13841 (b, [&] (breakpoint *bpt)
13843 enable_breakpoint_disp (bpt, disp_disable, 1);
13848 static void
13849 enable_count_command (const char *args, int from_tty)
13851 int count;
13853 if (args == NULL)
13854 error_no_arg (_("hit count"));
13856 count = get_number (&args);
13858 map_breakpoint_numbers
13859 (args, [&] (breakpoint *b)
13861 iterate_over_related_breakpoints
13862 (b, [&] (breakpoint *bpt)
13864 enable_breakpoint_disp (bpt, disp_disable, count);
13869 static void
13870 enable_delete_command (const char *args, int from_tty)
13872 map_breakpoint_numbers
13873 (args, [&] (breakpoint *b)
13875 iterate_over_related_breakpoints
13876 (b, [&] (breakpoint *bpt)
13878 enable_breakpoint_disp (bpt, disp_del, 1);
13883 /* Invalidate last known value of any hardware watchpoint if
13884 the memory which that value represents has been written to by
13885 GDB itself. */
13887 static void
13888 invalidate_bp_value_on_memory_change (struct inferior *inferior,
13889 CORE_ADDR addr, ssize_t len,
13890 const bfd_byte *data)
13892 for (breakpoint &bp : all_breakpoints ())
13893 if (bp.enable_state == bp_enabled
13894 && bp.type == bp_hardware_watchpoint)
13896 watchpoint &wp = gdb::checked_static_cast<watchpoint &> (bp);
13898 if (wp.val_valid && wp.val != nullptr)
13900 for (bp_location &loc : bp.locations ())
13901 if (loc.loc_type == bp_loc_hardware_watchpoint
13902 && loc.address + loc.length > addr
13903 && addr + len > loc.address)
13905 wp.val = NULL;
13906 wp.val_valid = false;
13912 /* Create and insert a breakpoint for software single step. */
13914 void
13915 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13916 const address_space *aspace,
13917 CORE_ADDR next_pc)
13919 struct thread_info *tp = inferior_thread ();
13920 struct symtab_and_line sal;
13921 CORE_ADDR pc = next_pc;
13923 if (tp->control.single_step_breakpoints == NULL)
13925 std::unique_ptr<breakpoint> b
13926 (new momentary_breakpoint (gdbarch, bp_single_step,
13927 current_program_space,
13928 null_frame_id,
13929 tp->global_num));
13931 tp->control.single_step_breakpoints
13932 = add_to_breakpoint_chain (std::move (b));
13935 sal = find_pc_line (pc, 0);
13936 sal.pc = pc;
13937 sal.section = find_pc_overlay (pc);
13938 sal.explicit_pc = 1;
13940 auto *ss_bp
13941 = (gdb::checked_static_cast<momentary_breakpoint *>
13942 (tp->control.single_step_breakpoints));
13943 ss_bp->add_location (sal);
13945 update_global_location_list (UGLL_INSERT);
13948 /* Insert single step breakpoints according to the current state. */
13951 insert_single_step_breakpoints (struct gdbarch *gdbarch)
13953 regcache *regcache = get_thread_regcache (inferior_thread ());
13954 std::vector<CORE_ADDR> next_pcs;
13956 next_pcs = gdbarch_software_single_step (gdbarch, regcache);
13958 if (!next_pcs.empty ())
13960 frame_info_ptr frame = get_current_frame ();
13961 const address_space *aspace = get_frame_address_space (frame);
13963 for (CORE_ADDR pc : next_pcs)
13964 insert_single_step_breakpoint (gdbarch, aspace, pc);
13966 return 1;
13968 else
13969 return 0;
13972 /* See breakpoint.h. */
13975 breakpoint_has_location_inserted_here (struct breakpoint *bp,
13976 const address_space *aspace,
13977 CORE_ADDR pc)
13979 for (bp_location &loc : bp->locations ())
13980 if (loc.inserted
13981 && breakpoint_location_address_match (&loc, aspace, pc))
13982 return 1;
13984 return 0;
13987 /* Check whether a software single-step breakpoint is inserted at
13988 PC. */
13991 single_step_breakpoint_inserted_here_p (const address_space *aspace,
13992 CORE_ADDR pc)
13994 for (breakpoint &bpt : all_breakpoints ())
13996 if (bpt.type == bp_single_step
13997 && breakpoint_has_location_inserted_here (&bpt, aspace, pc))
13998 return 1;
14000 return 0;
14003 /* Tracepoint-specific operations. */
14005 /* Set tracepoint count to NUM. */
14006 static void
14007 set_tracepoint_count (int num)
14009 tracepoint_count = num;
14010 set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14013 static void
14014 trace_command (const char *arg, int from_tty)
14016 location_spec_up locspec = string_to_location_spec (&arg,
14017 current_language);
14018 const struct breakpoint_ops *ops = breakpoint_ops_for_location_spec
14019 (locspec.get (), true /* is_tracepoint */);
14021 create_breakpoint (get_current_arch (),
14022 locspec.get (),
14023 NULL, -1, -1, arg, false, 1 /* parse arg */,
14024 0 /* tempflag */,
14025 bp_tracepoint /* type_wanted */,
14026 0 /* Ignore count */,
14027 pending_break_support,
14028 ops,
14029 from_tty,
14030 1 /* enabled */,
14031 0 /* internal */, 0);
14034 static void
14035 ftrace_command (const char *arg, int from_tty)
14037 location_spec_up locspec = string_to_location_spec (&arg,
14038 current_language);
14039 create_breakpoint (get_current_arch (),
14040 locspec.get (),
14041 NULL, -1, -1, arg, false, 1 /* parse arg */,
14042 0 /* tempflag */,
14043 bp_fast_tracepoint /* type_wanted */,
14044 0 /* Ignore count */,
14045 pending_break_support,
14046 &code_breakpoint_ops,
14047 from_tty,
14048 1 /* enabled */,
14049 0 /* internal */, 0);
14052 /* strace command implementation. Creates a static tracepoint. */
14054 static void
14055 strace_command (const char *arg, int from_tty)
14057 const struct breakpoint_ops *ops;
14058 location_spec_up locspec;
14059 enum bptype type;
14061 /* Decide if we are dealing with a static tracepoint marker (`-m'),
14062 or with a normal static tracepoint. */
14063 if (arg && startswith (arg, "-m") && isspace (arg[2]))
14065 ops = &strace_marker_breakpoint_ops;
14066 locspec = new_linespec_location_spec (&arg,
14067 symbol_name_match_type::FULL);
14068 type = bp_static_marker_tracepoint;
14070 else
14072 ops = &code_breakpoint_ops;
14073 locspec = string_to_location_spec (&arg, current_language);
14074 type = bp_static_tracepoint;
14077 create_breakpoint (get_current_arch (),
14078 locspec.get (),
14079 NULL, -1, -1, arg, false, 1 /* parse arg */,
14080 0 /* tempflag */,
14081 type /* type_wanted */,
14082 0 /* Ignore count */,
14083 pending_break_support,
14084 ops,
14085 from_tty,
14086 1 /* enabled */,
14087 0 /* internal */, 0);
14090 /* Set up a fake reader function that gets command lines from a linked
14091 list that was acquired during tracepoint uploading. */
14093 static struct uploaded_tp *this_utp;
14094 static int next_cmd;
14096 static const char *
14097 read_uploaded_action (std::string &buffer)
14099 char *rslt = nullptr;
14101 if (next_cmd < this_utp->cmd_strings.size ())
14103 rslt = this_utp->cmd_strings[next_cmd].get ();
14104 next_cmd++;
14107 return rslt;
14110 /* Given information about a tracepoint as recorded on a target (which
14111 can be either a live system or a trace file), attempt to create an
14112 equivalent GDB tracepoint. This is not a reliable process, since
14113 the target does not necessarily have all the information used when
14114 the tracepoint was originally defined. */
14116 struct tracepoint *
14117 create_tracepoint_from_upload (struct uploaded_tp *utp)
14119 const char *addr_str;
14120 char small_buf[100];
14121 struct tracepoint *tp;
14123 if (utp->at_string)
14124 addr_str = utp->at_string.get ();
14125 else
14127 /* In the absence of a source location, fall back to raw
14128 address. Since there is no way to confirm that the address
14129 means the same thing as when the trace was started, warn the
14130 user. */
14131 warning (_("Uploaded tracepoint %d has no "
14132 "source location, using raw address"),
14133 utp->number);
14134 xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14135 addr_str = small_buf;
14138 /* There's not much we can do with a sequence of bytecodes. */
14139 if (utp->cond && !utp->cond_string)
14140 warning (_("Uploaded tracepoint %d condition "
14141 "has no source form, ignoring it"),
14142 utp->number);
14144 location_spec_up locspec = string_to_location_spec (&addr_str,
14145 current_language);
14146 if (!create_breakpoint (get_current_arch (),
14147 locspec.get (),
14148 utp->cond_string.get (), -1, -1, addr_str,
14149 false /* force_condition */,
14150 0 /* parse cond/thread */,
14151 0 /* tempflag */,
14152 utp->type /* type_wanted */,
14153 0 /* Ignore count */,
14154 pending_break_support,
14155 &code_breakpoint_ops,
14156 0 /* from_tty */,
14157 utp->enabled /* enabled */,
14158 0 /* internal */,
14159 CREATE_BREAKPOINT_FLAGS_INSERTED))
14160 return NULL;
14162 /* Get the tracepoint we just created. */
14163 tp = get_tracepoint (tracepoint_count);
14164 gdb_assert (tp != NULL);
14166 if (utp->pass > 0)
14168 xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14169 tp->number);
14171 trace_pass_command (small_buf, 0);
14174 /* If we have uploaded versions of the original commands, set up a
14175 special-purpose "reader" function and call the usual command line
14176 reader, then pass the result to the breakpoint command-setting
14177 function. */
14178 if (!utp->cmd_strings.empty ())
14180 counted_command_line cmd_list;
14182 this_utp = utp;
14183 next_cmd = 0;
14185 cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14187 breakpoint_set_commands (tp, std::move (cmd_list));
14189 else if (!utp->actions.empty ()
14190 || !utp->step_actions.empty ())
14191 warning (_("Uploaded tracepoint %d actions "
14192 "have no source form, ignoring them"),
14193 utp->number);
14195 /* Copy any status information that might be available. */
14196 tp->hit_count = utp->hit_count;
14197 tp->traceframe_usage = utp->traceframe_usage;
14199 return tp;
14202 /* Print information on tracepoint number TPNUM_EXP, or all if
14203 omitted. */
14205 static void
14206 info_tracepoints_command (const char *args, int from_tty)
14208 struct ui_out *uiout = current_uiout;
14209 int num_printed;
14211 num_printed = breakpoint_1 (args, false, is_tracepoint);
14213 if (num_printed == 0)
14215 if (args == NULL || *args == '\0')
14216 uiout->message ("No tracepoints.\n");
14217 else
14218 uiout->message ("No tracepoint matching '%s'.\n", args);
14221 default_collect_info ();
14224 /* The 'enable trace' command enables tracepoints.
14225 Not supported by all targets. */
14226 static void
14227 enable_trace_command (const char *args, int from_tty)
14229 enable_command (args, from_tty);
14232 /* The 'disable trace' command disables tracepoints.
14233 Not supported by all targets. */
14234 static void
14235 disable_trace_command (const char *args, int from_tty)
14237 disable_command (args, from_tty);
14240 /* Remove a tracepoint (or all if no argument). */
14241 static void
14242 delete_trace_command (const char *arg, int from_tty)
14244 dont_repeat ();
14246 if (arg == 0)
14248 int breaks_to_delete = 0;
14250 /* Delete all breakpoints if no argument.
14251 Do not delete internal or call-dummy breakpoints, these
14252 have to be deleted with an explicit breakpoint number
14253 argument. */
14254 for (breakpoint &tp : all_tracepoints ())
14255 if (is_tracepoint (&tp) && user_breakpoint_p (&tp))
14257 breaks_to_delete = 1;
14258 break;
14261 /* Ask user only if there are some breakpoints to delete. */
14262 if (!from_tty
14263 || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14265 for (breakpoint &b : all_breakpoints_safe ())
14266 if (is_tracepoint (&b) && user_breakpoint_p (&b))
14267 delete_breakpoint (&b);
14270 else
14271 map_breakpoint_numbers
14272 (arg, [&] (breakpoint *br)
14274 iterate_over_related_breakpoints (br, delete_breakpoint);
14278 /* Helper function for trace_pass_command. */
14280 static void
14281 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14283 tp->pass_count = count;
14284 notify_breakpoint_modified (tp);
14285 if (from_tty)
14286 gdb_printf (_("Setting tracepoint %d's passcount to %d\n"),
14287 tp->number, count);
14290 /* Set passcount for tracepoint.
14292 First command argument is passcount, second is tracepoint number.
14293 If tracepoint number omitted, apply to most recently defined.
14294 Also accepts special argument "all". */
14296 static void
14297 trace_pass_command (const char *args, int from_tty)
14299 ULONGEST count;
14301 if (args == 0 || *args == 0)
14302 error (_("passcount command requires an "
14303 "argument (count + optional TP num)"));
14305 count = strtoulst (args, &args, 10); /* Count comes first, then TP num. */
14307 args = skip_spaces (args);
14308 if (*args && strncasecmp (args, "all", 3) == 0)
14310 args += 3; /* Skip special argument "all". */
14311 if (*args)
14312 error (_("Junk at end of arguments."));
14314 for (breakpoint &b : all_tracepoints ())
14316 tracepoint &t1 = gdb::checked_static_cast<tracepoint &> (b);
14317 trace_pass_set_count (&t1, count, from_tty);
14320 else if (*args == '\0')
14322 tracepoint *t1 = get_tracepoint_by_number (&args, NULL);
14323 if (t1)
14324 trace_pass_set_count (t1, count, from_tty);
14326 else
14328 number_or_range_parser parser (args);
14329 while (!parser.finished ())
14331 tracepoint *t1 = get_tracepoint_by_number (&args, &parser);
14332 if (t1)
14333 trace_pass_set_count (t1, count, from_tty);
14338 struct tracepoint *
14339 get_tracepoint (int num)
14341 for (breakpoint &t : all_tracepoints ())
14342 if (t.number == num)
14343 return gdb::checked_static_cast<tracepoint *> (&t);
14345 return NULL;
14348 /* Find the tracepoint with the given target-side number (which may be
14349 different from the tracepoint number after disconnecting and
14350 reconnecting). */
14352 struct tracepoint *
14353 get_tracepoint_by_number_on_target (int num)
14355 for (breakpoint &b : all_tracepoints ())
14357 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
14359 if (t.number_on_target == num)
14360 return &t;
14363 return NULL;
14366 /* Utility: parse a tracepoint number and look it up in the list.
14367 If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14368 If the argument is missing, the most recent tracepoint
14369 (tracepoint_count) is returned. */
14371 struct tracepoint *
14372 get_tracepoint_by_number (const char **arg,
14373 number_or_range_parser *parser)
14375 int tpnum;
14376 const char *instring = arg == NULL ? NULL : *arg;
14378 if (parser != NULL)
14380 gdb_assert (!parser->finished ());
14381 tpnum = parser->get_number ();
14383 else if (arg == NULL || *arg == NULL || ! **arg)
14384 tpnum = tracepoint_count;
14385 else
14386 tpnum = get_number (arg);
14388 if (tpnum <= 0)
14390 if (instring && *instring)
14391 gdb_printf (_("bad tracepoint number at or near '%s'\n"),
14392 instring);
14393 else
14394 gdb_printf (_("No previous tracepoint\n"));
14395 return NULL;
14398 for (breakpoint &t : all_tracepoints ())
14399 if (t.number == tpnum)
14400 return gdb::checked_static_cast<tracepoint *> (&t);
14402 gdb_printf ("No tracepoint number %d.\n", tpnum);
14403 return NULL;
14406 void
14407 breakpoint::print_recreate_thread (struct ui_file *fp) const
14409 if (thread != -1)
14411 struct thread_info *thr = find_thread_global_id (thread);
14412 gdb_printf (fp, " thread %s", print_full_thread_id (thr));
14415 if (task != -1)
14416 gdb_printf (fp, " task %d", task);
14418 gdb_printf (fp, "\n");
14421 /* Save information on user settable breakpoints (watchpoints, etc) to
14422 a new script file named FILENAME. If FILTER is non-NULL, call it
14423 on each breakpoint and only include the ones for which it returns
14424 true. */
14426 static void
14427 save_breakpoints (const char *filename, int from_tty,
14428 bool (*filter) (const struct breakpoint *))
14430 bool any = false;
14431 int extra_trace_bits = 0;
14433 if (filename == 0 || *filename == 0)
14434 error (_("Argument required (file name in which to save)"));
14436 /* See if we have anything to save. */
14437 for (breakpoint &tp : all_breakpoints ())
14439 /* Skip internal and momentary breakpoints. */
14440 if (!user_breakpoint_p (&tp))
14441 continue;
14443 /* If we have a filter, only save the breakpoints it accepts. */
14444 if (filter && !filter (&tp))
14445 continue;
14447 any = true;
14449 if (is_tracepoint (&tp))
14451 extra_trace_bits = 1;
14453 /* We can stop searching. */
14454 break;
14458 if (!any)
14460 warning (_("Nothing to save."));
14461 return;
14464 gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
14466 stdio_file fp;
14468 if (!fp.open (expanded_filename.get (), "w"))
14469 error (_("Unable to open file '%s' for saving (%s)"),
14470 expanded_filename.get (), safe_strerror (errno));
14472 if (extra_trace_bits)
14473 save_trace_state_variables (&fp);
14475 for (breakpoint &tp : all_breakpoints ())
14477 /* Skip internal and momentary breakpoints. */
14478 if (!user_breakpoint_p (&tp))
14479 continue;
14481 /* If we have a filter, only save the breakpoints it accepts. */
14482 if (filter && !filter (&tp))
14483 continue;
14485 tp.print_recreate (&fp);
14487 /* Note, we can't rely on tp->number for anything, as we can't
14488 assume the recreated breakpoint numbers will match. Use $bpnum
14489 instead. */
14491 if (tp.cond_string)
14492 fp.printf (" condition $bpnum %s\n", tp.cond_string.get ());
14494 if (tp.ignore_count)
14495 fp.printf (" ignore $bpnum %d\n", tp.ignore_count);
14497 if (tp.type != bp_dprintf && tp.commands)
14499 fp.puts (" commands\n");
14501 ui_out_redirect_pop redir (current_uiout, &fp);
14502 print_command_lines (current_uiout, tp.commands.get (), 2);
14504 fp.puts (" end\n");
14507 if (tp.enable_state == bp_disabled)
14508 fp.puts ("disable $bpnum\n");
14510 /* If this is a multi-location breakpoint, check if the locations
14511 should be individually disabled. Watchpoint locations are
14512 special, and not user visible. */
14513 if (!is_watchpoint (&tp) && tp.has_multiple_locations ())
14515 int n = 1;
14517 for (bp_location &loc : tp.locations ())
14519 if (!loc.enabled)
14520 fp.printf ("disable $bpnum.%d\n", n);
14522 n++;
14527 if (extra_trace_bits && !default_collect.empty ())
14528 fp.printf ("set default-collect %s\n", default_collect.c_str ());
14530 if (from_tty)
14531 gdb_printf (_("Saved to file '%s'.\n"), expanded_filename.get ());
14534 /* The `save breakpoints' command. */
14536 static void
14537 save_breakpoints_command (const char *args, int from_tty)
14539 save_breakpoints (args, from_tty, NULL);
14542 /* The `save tracepoints' command. */
14544 static void
14545 save_tracepoints_command (const char *args, int from_tty)
14547 save_breakpoints (args, from_tty, is_tracepoint);
14551 /* This help string is used to consolidate all the help string for specifying
14552 locations used by several commands. */
14554 #define LOCATION_SPEC_HELP_STRING \
14555 "Linespecs are colon-separated lists of location parameters, such as\n\
14556 source filename, function name, label name, and line number.\n\
14557 Example: To specify the start of a label named \"the_top\" in the\n\
14558 function \"fact\" in the file \"factorial.c\", use\n\
14559 \"factorial.c:fact:the_top\".\n\
14561 Address locations begin with \"*\" and specify an exact address in the\n\
14562 program. Example: To specify the fourth byte past the start function\n\
14563 \"main\", use \"*main + 4\".\n\
14565 Explicit locations are similar to linespecs but use an option/argument\n\
14566 syntax to specify location parameters.\n\
14567 Example: To specify the start of the label named \"the_top\" in the\n\
14568 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
14569 -function fact -label the_top\".\n\
14571 By default, a specified function is matched against the program's\n\
14572 functions in all scopes. For C++, this means in all namespaces and\n\
14573 classes. For Ada, this means in all packages. E.g., in C++,\n\
14574 \"func()\" matches \"A::func()\", \"A::B::func()\", etc. The\n\
14575 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
14576 specified name as a complete fully-qualified name instead."
14578 /* This help string is used for the break, hbreak, tbreak and thbreak
14579 commands. It is defined as a macro to prevent duplication.
14580 COMMAND should be a string constant containing the name of the
14581 command. */
14583 #define BREAK_ARGS_HELP(command) \
14584 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
14585 \t[-force-condition] [if CONDITION]\n\
14586 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
14587 probe point. Accepted values are `-probe' (for a generic, automatically\n\
14588 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
14589 `-probe-dtrace' (for a DTrace probe).\n\
14590 LOCATION may be a linespec, address, or explicit location as described\n\
14591 below.\n\
14593 With no LOCATION, uses current execution address of the selected\n\
14594 stack frame. This is useful for breaking on return to a stack frame.\n\
14596 THREADNUM is the number from \"info threads\".\n\
14597 CONDITION is a boolean expression.\n\
14599 With the \"-force-condition\" flag, the condition is defined even when\n\
14600 it is invalid for all current locations.\n\
14601 \n" LOCATION_SPEC_HELP_STRING "\n\n\
14602 Multiple breakpoints at one place are permitted, and useful if their\n\
14603 conditions are different.\n\
14605 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14607 /* List of subcommands for "catch". */
14608 static struct cmd_list_element *catch_cmdlist;
14610 /* List of subcommands for "tcatch". */
14611 static struct cmd_list_element *tcatch_cmdlist;
14613 void
14614 add_catch_command (const char *name, const char *docstring,
14615 cmd_func_ftype *func,
14616 completer_ftype *completer,
14617 void *user_data_catch,
14618 void *user_data_tcatch)
14620 struct cmd_list_element *command;
14622 command = add_cmd (name, class_breakpoint, docstring,
14623 &catch_cmdlist);
14624 command->func = func;
14625 command->set_context (user_data_catch);
14626 set_cmd_completer (command, completer);
14628 command = add_cmd (name, class_breakpoint, docstring,
14629 &tcatch_cmdlist);
14630 command->func = func;
14631 command->set_context (user_data_tcatch);
14632 set_cmd_completer (command, completer);
14635 /* False if any of the breakpoint's locations could be a location where
14636 functions have been inlined, true otherwise. */
14638 static bool
14639 is_non_inline_function (struct breakpoint *b)
14641 /* The shared library event breakpoint is set on the address of a
14642 non-inline function. */
14643 return (b->type == bp_shlib_event);
14646 /* Nonzero if the specified PC cannot be a location where functions
14647 have been inlined. */
14650 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
14651 const target_waitstatus &ws)
14653 for (breakpoint &b : all_breakpoints ())
14655 if (!is_non_inline_function (&b))
14656 continue;
14658 for (bp_location &bl : b.locations ())
14660 if (!bl.shlib_disabled
14661 && bpstat_check_location (&bl, aspace, pc, ws))
14662 return 1;
14666 return 0;
14669 /* Remove any references to OBJFILE which is going to be freed. */
14671 void
14672 breakpoint_free_objfile (struct objfile *objfile)
14674 for (bp_location *loc : all_bp_locations ())
14675 if (loc->symtab != NULL && loc->symtab->compunit ()->objfile () == objfile)
14676 loc->symtab = NULL;
14679 /* Chain containing all defined "enable breakpoint" subcommands. */
14681 static struct cmd_list_element *enablebreaklist = NULL;
14683 /* See breakpoint.h. */
14685 cmd_list_element *commands_cmd_element = nullptr;
14687 void _initialize_breakpoint ();
14688 void
14689 _initialize_breakpoint ()
14691 struct cmd_list_element *c;
14693 gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
14694 "breakpoint");
14695 gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
14696 "breakpoint");
14697 gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
14698 "breakpoint");
14700 /* Don't bother to call set_breakpoint_count. $bpnum isn't useful
14701 before a breakpoint is set. */
14702 breakpoint_count = 0;
14704 tracepoint_count = 0;
14706 add_com ("ignore", class_breakpoint, ignore_command, _("\
14707 Set ignore-count of breakpoint number N to COUNT.\n\
14708 Usage is `ignore N COUNT'."));
14710 commands_cmd_element = add_com ("commands", class_breakpoint,
14711 commands_command, _("\
14712 Set commands to be executed when the given breakpoints are hit.\n\
14713 Give a space-separated breakpoint list as argument after \"commands\".\n\
14714 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
14715 (e.g. `5-7').\n\
14716 With no argument, the targeted breakpoint is the last one set.\n\
14717 The commands themselves follow starting on the next line.\n\
14718 Type a line containing \"end\" to indicate the end of them.\n\
14719 Give \"silent\" as the first line to make the breakpoint silent;\n\
14720 then no output is printed when it is hit, except what the commands print."));
14722 const auto cc_opts = make_condition_command_options_def_group (nullptr);
14723 static std::string condition_command_help
14724 = gdb::option::build_help (_("\
14725 Specify breakpoint number N to break only if COND is true.\n\
14726 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
14727 is an expression to be evaluated whenever breakpoint N is reached.\n\
14729 Options:\n\
14730 %OPTIONS%"), cc_opts);
14732 c = add_com ("condition", class_breakpoint, condition_command,
14733 condition_command_help.c_str ());
14734 set_cmd_completer_handle_brkchars (c, condition_completer);
14736 c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14737 Set a temporary breakpoint.\n\
14738 Like \"break\" except the breakpoint is only temporary,\n\
14739 so it will be deleted when hit. Equivalent to \"break\" followed\n\
14740 by using \"enable delete\" on the breakpoint number.\n\
14742 BREAK_ARGS_HELP ("tbreak")));
14743 set_cmd_completer (c, location_completer);
14745 c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
14746 Set a hardware assisted breakpoint.\n\
14747 Like \"break\" except the breakpoint requires hardware support,\n\
14748 some target hardware may not have this support.\n\
14750 BREAK_ARGS_HELP ("hbreak")));
14751 set_cmd_completer (c, location_completer);
14753 c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
14754 Set a temporary hardware assisted breakpoint.\n\
14755 Like \"hbreak\" except the breakpoint is only temporary,\n\
14756 so it will be deleted when hit.\n\
14758 BREAK_ARGS_HELP ("thbreak")));
14759 set_cmd_completer (c, location_completer);
14761 cmd_list_element *enable_cmd
14762 = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
14763 Enable all or some breakpoints.\n\
14764 Usage: enable [BREAKPOINTNUM]...\n\
14765 Give breakpoint numbers (separated by spaces) as arguments.\n\
14766 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14767 This is used to cancel the effect of the \"disable\" command.\n\
14768 With a subcommand you can enable temporarily."),
14769 &enablelist, 1, &cmdlist);
14771 add_com_alias ("en", enable_cmd, class_breakpoint, 1);
14773 add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
14774 Enable all or some breakpoints.\n\
14775 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
14776 Give breakpoint numbers (separated by spaces) as arguments.\n\
14777 This is used to cancel the effect of the \"disable\" command.\n\
14778 May be abbreviated to simply \"enable\"."),
14779 &enablebreaklist, 1, &enablelist);
14781 add_cmd ("once", no_class, enable_once_command, _("\
14782 Enable some breakpoints for one hit.\n\
14783 Usage: enable breakpoints once BREAKPOINTNUM...\n\
14784 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14785 &enablebreaklist);
14787 add_cmd ("delete", no_class, enable_delete_command, _("\
14788 Enable some breakpoints and delete when hit.\n\
14789 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
14790 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14791 &enablebreaklist);
14793 add_cmd ("count", no_class, enable_count_command, _("\
14794 Enable some breakpoints for COUNT hits.\n\
14795 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
14796 If a breakpoint is hit while enabled in this fashion,\n\
14797 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14798 &enablebreaklist);
14800 add_cmd ("delete", no_class, enable_delete_command, _("\
14801 Enable some breakpoints and delete when hit.\n\
14802 Usage: enable delete BREAKPOINTNUM...\n\
14803 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14804 &enablelist);
14806 add_cmd ("once", no_class, enable_once_command, _("\
14807 Enable some breakpoints for one hit.\n\
14808 Usage: enable once BREAKPOINTNUM...\n\
14809 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14810 &enablelist);
14812 add_cmd ("count", no_class, enable_count_command, _("\
14813 Enable some breakpoints for COUNT hits.\n\
14814 Usage: enable count COUNT BREAKPOINTNUM...\n\
14815 If a breakpoint is hit while enabled in this fashion,\n\
14816 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14817 &enablelist);
14819 cmd_list_element *disable_cmd
14820 = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
14821 Disable all or some breakpoints.\n\
14822 Usage: disable [BREAKPOINTNUM]...\n\
14823 Arguments are breakpoint numbers with spaces in between.\n\
14824 To disable all breakpoints, give no argument.\n\
14825 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
14826 &disablelist, 1, &cmdlist);
14827 add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
14828 add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
14830 add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
14831 Disable all or some breakpoints.\n\
14832 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
14833 Arguments are breakpoint numbers with spaces in between.\n\
14834 To disable all breakpoints, give no argument.\n\
14835 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
14836 This command may be abbreviated \"disable\"."),
14837 &disablelist);
14839 cmd_list_element *delete_cmd
14840 = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
14841 Delete all or some breakpoints.\n\
14842 Usage: delete [BREAKPOINTNUM]...\n\
14843 Arguments are breakpoint numbers with spaces in between.\n\
14844 To delete all breakpoints, give no argument.\n\
14846 Also a prefix command for deletion of other GDB objects."),
14847 &deletelist, 1, &cmdlist);
14848 add_com_alias ("d", delete_cmd, class_breakpoint, 1);
14849 add_com_alias ("del", delete_cmd, class_breakpoint, 1);
14851 add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
14852 Delete all or some breakpoints or auto-display expressions.\n\
14853 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
14854 Arguments are breakpoint numbers with spaces in between.\n\
14855 To delete all breakpoints, give no argument.\n\
14856 This command may be abbreviated \"delete\"."),
14857 &deletelist);
14859 cmd_list_element *clear_cmd
14860 = add_com ("clear", class_breakpoint, clear_command, _("\
14861 Clear breakpoint at specified location.\n\
14862 Argument may be a linespec, explicit, or address location as described below.\n\
14864 With no argument, clears all breakpoints in the line that the selected frame\n\
14865 is executing in.\n"
14866 "\n" LOCATION_SPEC_HELP_STRING "\n\n\
14867 See also the \"delete\" command which clears breakpoints by number."));
14868 add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
14870 cmd_list_element *break_cmd
14871 = add_com ("break", class_breakpoint, break_command, _("\
14872 Set breakpoint at specified location.\n"
14873 BREAK_ARGS_HELP ("break")));
14874 set_cmd_completer (break_cmd, location_completer);
14876 add_com_alias ("b", break_cmd, class_run, 1);
14877 add_com_alias ("br", break_cmd, class_run, 1);
14878 add_com_alias ("bre", break_cmd, class_run, 1);
14879 add_com_alias ("brea", break_cmd, class_run, 1);
14881 cmd_list_element *info_breakpoints_cmd
14882 = add_info ("breakpoints", info_breakpoints_command, _("\
14883 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14884 The \"Type\" column indicates one of:\n\
14885 \tbreakpoint - normal breakpoint\n\
14886 \twatchpoint - watchpoint\n\
14887 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14888 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14889 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14890 address and file/line number respectively.\n\
14892 Convenience variable \"$_\" and default examine address for \"x\"\n\
14893 are set to the address of the last breakpoint listed unless the command\n\
14894 is prefixed with \"server \".\n\n\
14895 Convenience variable \"$bpnum\" contains the number of the last\n\
14896 breakpoint set."));
14898 add_info_alias ("b", info_breakpoints_cmd, 1);
14900 add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14901 Status of all breakpoints, or breakpoint number NUMBER.\n\
14902 The \"Type\" column indicates one of:\n\
14903 \tbreakpoint - normal breakpoint\n\
14904 \twatchpoint - watchpoint\n\
14905 \tlongjmp - internal breakpoint used to step through longjmp()\n\
14906 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14907 \tuntil - internal breakpoint used by the \"until\" command\n\
14908 \tfinish - internal breakpoint used by the \"finish\" command\n\
14909 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14910 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14911 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14912 address and file/line number respectively.\n\
14914 Convenience variable \"$_\" and default examine address for \"x\"\n\
14915 are set to the address of the last breakpoint listed unless the command\n\
14916 is prefixed with \"server \".\n\n\
14917 Convenience variable \"$bpnum\" contains the number of the last\n\
14918 breakpoint set."),
14919 &maintenanceinfolist);
14921 add_basic_prefix_cmd ("catch", class_breakpoint, _("\
14922 Set catchpoints to catch events."),
14923 &catch_cmdlist,
14924 0/*allow-unknown*/, &cmdlist);
14926 add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
14927 Set temporary catchpoints to catch events."),
14928 &tcatch_cmdlist,
14929 0/*allow-unknown*/, &cmdlist);
14931 const auto opts = make_watch_options_def_group (nullptr);
14933 static const std::string watch_help = gdb::option::build_help (_("\
14934 Set a watchpoint for EXPRESSION.\n\
14935 Usage: watch [-location] EXPRESSION\n\
14937 Options:\n\
14938 %OPTIONS%\n\
14940 A watchpoint stops execution of your program whenever the value of\n\
14941 an expression changes."), opts);
14942 c = add_com ("watch", class_breakpoint, watch_command,
14943 watch_help.c_str ());
14944 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14946 static const std::string rwatch_help = gdb::option::build_help (_("\
14947 Set a read watchpoint for EXPRESSION.\n\
14948 Usage: rwatch [-location] EXPRESSION\n\
14950 Options:\n\
14951 %OPTIONS%\n\
14953 A read watchpoint stops execution of your program whenever the value of\n\
14954 an expression is read."), opts);
14955 c = add_com ("rwatch", class_breakpoint, rwatch_command,
14956 rwatch_help.c_str ());
14957 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14959 static const std::string awatch_help = gdb::option::build_help (_("\
14960 Set an access watchpoint for EXPRESSION.\n\
14961 Usage: awatch [-location] EXPRESSION\n\
14963 Options:\n\
14964 %OPTIONS%\n\
14966 An access watchpoint stops execution of your program whenever the value\n\
14967 of an expression is either read or written."), opts);
14968 c = add_com ("awatch", class_breakpoint, awatch_command,
14969 awatch_help.c_str ());
14970 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14972 add_info ("watchpoints", info_watchpoints_command, _("\
14973 Status of specified watchpoints (all watchpoints if no argument)."));
14975 /* XXX: cagney/2005-02-23: This should be a boolean, and should
14976 respond to changes - contrary to the description. */
14977 add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
14978 &can_use_hw_watchpoints, _("\
14979 Set debugger's willingness to use watchpoint hardware."), _("\
14980 Show debugger's willingness to use watchpoint hardware."), _("\
14981 If zero, gdb will not use hardware for new watchpoints, even if\n\
14982 such is available. (However, any hardware watchpoints that were\n\
14983 created before setting this to nonzero, will continue to use watchpoint\n\
14984 hardware.)"),
14985 NULL,
14986 show_can_use_hw_watchpoints,
14987 &setlist, &showlist);
14989 can_use_hw_watchpoints = 1;
14991 /* Tracepoint manipulation commands. */
14993 cmd_list_element *trace_cmd
14994 = add_com ("trace", class_breakpoint, trace_command, _("\
14995 Set a tracepoint at specified location.\n\
14997 BREAK_ARGS_HELP ("trace") "\n\
14998 Do \"help tracepoints\" for info on other tracepoint commands."));
14999 set_cmd_completer (trace_cmd, location_completer);
15001 add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
15002 add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
15003 add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
15004 add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
15006 c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15007 Set a fast tracepoint at specified location.\n\
15009 BREAK_ARGS_HELP ("ftrace") "\n\
15010 Do \"help tracepoints\" for info on other tracepoint commands."));
15011 set_cmd_completer (c, location_completer);
15013 c = add_com ("strace", class_breakpoint, strace_command, _("\
15014 Set a static tracepoint at location or marker.\n\
15016 strace [LOCATION] [if CONDITION]\n\
15017 LOCATION may be a linespec, explicit, or address location (described below) \n\
15018 or -m MARKER_ID.\n\n\
15019 If a marker id is specified, probe the marker with that name. With\n\
15020 no LOCATION, uses current execution address of the selected stack frame.\n\
15021 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15022 This collects arbitrary user data passed in the probe point call to the\n\
15023 tracing library. You can inspect it when analyzing the trace buffer,\n\
15024 by printing the $_sdata variable like any other convenience variable.\n\
15026 CONDITION is a boolean expression.\n\
15027 \n" LOCATION_SPEC_HELP_STRING "\n\n\
15028 Multiple tracepoints at one place are permitted, and useful if their\n\
15029 conditions are different.\n\
15031 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15032 Do \"help tracepoints\" for info on other tracepoint commands."));
15033 set_cmd_completer (c, location_completer);
15035 cmd_list_element *info_tracepoints_cmd
15036 = add_info ("tracepoints", info_tracepoints_command, _("\
15037 Status of specified tracepoints (all tracepoints if no argument).\n\
15038 Convenience variable \"$tpnum\" contains the number of the\n\
15039 last tracepoint set."));
15041 add_info_alias ("tp", info_tracepoints_cmd, 1);
15043 cmd_list_element *delete_tracepoints_cmd
15044 = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15045 Delete specified tracepoints.\n\
15046 Arguments are tracepoint numbers, separated by spaces.\n\
15047 No argument means delete all tracepoints."),
15048 &deletelist);
15049 add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
15051 c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15052 Disable specified tracepoints.\n\
15053 Arguments are tracepoint numbers, separated by spaces.\n\
15054 No argument means disable all tracepoints."),
15055 &disablelist);
15056 deprecate_cmd (c, "disable");
15058 c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15059 Enable specified tracepoints.\n\
15060 Arguments are tracepoint numbers, separated by spaces.\n\
15061 No argument means enable all tracepoints."),
15062 &enablelist);
15063 deprecate_cmd (c, "enable");
15065 add_com ("passcount", class_trace, trace_pass_command, _("\
15066 Set the passcount for a tracepoint.\n\
15067 The trace will end when the tracepoint has been passed 'count' times.\n\
15068 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15069 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15071 add_basic_prefix_cmd ("save", class_breakpoint,
15072 _("Save breakpoint definitions as a script."),
15073 &save_cmdlist,
15074 0/*allow-unknown*/, &cmdlist);
15076 c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15077 Save current breakpoint definitions as a script.\n\
15078 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15079 catchpoints, tracepoints). Use the 'source' command in another debug\n\
15080 session to restore them."),
15081 &save_cmdlist);
15082 set_cmd_completer (c, filename_completer);
15084 cmd_list_element *save_tracepoints_cmd
15085 = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15086 Save current tracepoint definitions as a script.\n\
15087 Use the 'source' command in another debug session to restore them."),
15088 &save_cmdlist);
15089 set_cmd_completer (save_tracepoints_cmd, filename_completer);
15091 c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
15092 deprecate_cmd (c, "save tracepoints");
15094 add_setshow_prefix_cmd ("breakpoint", class_maintenance,
15095 _("\
15096 Breakpoint specific settings.\n\
15097 Configure various breakpoint-specific variables such as\n\
15098 pending breakpoint behavior."),
15099 _("\
15100 Breakpoint specific settings.\n\
15101 Configure various breakpoint-specific variables such as\n\
15102 pending breakpoint behavior."),
15103 &breakpoint_set_cmdlist, &breakpoint_show_cmdlist,
15104 &setlist, &showlist);
15106 add_setshow_auto_boolean_cmd ("pending", no_class,
15107 &pending_break_support, _("\
15108 Set debugger's behavior regarding pending breakpoints."), _("\
15109 Show debugger's behavior regarding pending breakpoints."), _("\
15110 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15111 pending breakpoint. If off, an unrecognized breakpoint location results in\n\
15112 an error. If auto, an unrecognized breakpoint location results in a\n\
15113 user-query to see if a pending breakpoint should be created."),
15114 NULL,
15115 show_pending_break_support,
15116 &breakpoint_set_cmdlist,
15117 &breakpoint_show_cmdlist);
15119 pending_break_support = AUTO_BOOLEAN_AUTO;
15121 add_setshow_boolean_cmd ("auto-hw", no_class,
15122 &automatic_hardware_breakpoints, _("\
15123 Set automatic usage of hardware breakpoints."), _("\
15124 Show automatic usage of hardware breakpoints."), _("\
15125 If set, the debugger will automatically use hardware breakpoints for\n\
15126 breakpoints set with \"break\" but falling in read-only memory. If not set,\n\
15127 a warning will be emitted for such breakpoints."),
15128 NULL,
15129 show_automatic_hardware_breakpoints,
15130 &breakpoint_set_cmdlist,
15131 &breakpoint_show_cmdlist);
15133 add_setshow_boolean_cmd ("always-inserted", class_support,
15134 &always_inserted_mode, _("\
15135 Set mode for inserting breakpoints."), _("\
15136 Show mode for inserting breakpoints."), _("\
15137 When this mode is on, breakpoints are inserted immediately as soon as\n\
15138 they're created, kept inserted even when execution stops, and removed\n\
15139 only when the user deletes them. When this mode is off (the default),\n\
15140 breakpoints are inserted only when execution continues, and removed\n\
15141 when execution stops."),
15142 NULL,
15143 &show_always_inserted_mode,
15144 &breakpoint_set_cmdlist,
15145 &breakpoint_show_cmdlist);
15147 add_setshow_boolean_cmd ("breakpoint", class_maintenance,
15148 &debug_breakpoint, _("\
15149 Set breakpoint location debugging."), _("\
15150 Show breakpoint location debugging."), _("\
15151 When on, breakpoint location specific debugging is enabled."),
15152 NULL,
15153 show_debug_breakpoint,
15154 &setdebuglist, &showdebuglist);
15156 add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15157 condition_evaluation_enums,
15158 &condition_evaluation_mode_1, _("\
15159 Set mode of breakpoint condition evaluation."), _("\
15160 Show mode of breakpoint condition evaluation."), _("\
15161 When this is set to \"host\", breakpoint conditions will be\n\
15162 evaluated on the host's side by GDB. When it is set to \"target\",\n\
15163 breakpoint conditions will be downloaded to the target (if the target\n\
15164 supports such feature) and conditions will be evaluated on the target's side.\n\
15165 If this is set to \"auto\" (default), this will be automatically set to\n\
15166 \"target\" if it supports condition evaluation, otherwise it will\n\
15167 be set to \"host\"."),
15168 &set_condition_evaluation_mode,
15169 &show_condition_evaluation_mode,
15170 &breakpoint_set_cmdlist,
15171 &breakpoint_show_cmdlist);
15173 add_com ("break-range", class_breakpoint, break_range_command, _("\
15174 Set a breakpoint for an address range.\n\
15175 break-range START-LOCATION, END-LOCATION\n\
15176 where START-LOCATION and END-LOCATION can be one of the following:\n\
15177 LINENUM, for that line in the current file,\n\
15178 FILE:LINENUM, for that line in that file,\n\
15179 +OFFSET, for that number of lines after the current line\n\
15180 or the start of the range\n\
15181 FUNCTION, for the first line in that function,\n\
15182 FILE:FUNCTION, to distinguish among like-named static functions.\n\
15183 *ADDRESS, for the instruction at that address.\n\
15185 The breakpoint will stop execution of the inferior whenever it executes\n\
15186 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15187 range (including START-LOCATION and END-LOCATION)."));
15189 c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
15190 Set a dynamic printf at specified location.\n\
15191 dprintf location,format string,arg1,arg2,...\n\
15192 location may be a linespec, explicit, or address location.\n"
15193 "\n" LOCATION_SPEC_HELP_STRING));
15194 set_cmd_completer (c, location_completer);
15196 add_setshow_enum_cmd ("dprintf-style", class_support,
15197 dprintf_style_enums, &dprintf_style, _("\
15198 Set the style of usage for dynamic printf."), _("\
15199 Show the style of usage for dynamic printf."), _("\
15200 This setting chooses how GDB will do a dynamic printf.\n\
15201 If the value is \"gdb\", then the printing is done by GDB to its own\n\
15202 console, as with the \"printf\" command.\n\
15203 If the value is \"call\", the print is done by calling a function in your\n\
15204 program; by default printf(), but you can choose a different function or\n\
15205 output stream by setting dprintf-function and dprintf-channel."),
15206 update_dprintf_commands, NULL,
15207 &setlist, &showlist);
15209 add_setshow_string_cmd ("dprintf-function", class_support,
15210 &dprintf_function, _("\
15211 Set the function to use for dynamic printf."), _("\
15212 Show the function to use for dynamic printf."), NULL,
15213 update_dprintf_commands, NULL,
15214 &setlist, &showlist);
15216 add_setshow_string_cmd ("dprintf-channel", class_support,
15217 &dprintf_channel, _("\
15218 Set the channel to use for dynamic printf."), _("\
15219 Show the channel to use for dynamic printf."), NULL,
15220 update_dprintf_commands, NULL,
15221 &setlist, &showlist);
15223 add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
15224 &disconnected_dprintf, _("\
15225 Set whether dprintf continues after GDB disconnects."), _("\
15226 Show whether dprintf continues after GDB disconnects."), _("\
15227 Use this to let dprintf commands continue to hit and produce output\n\
15228 even if GDB disconnects or detaches from the target."),
15229 NULL,
15230 NULL,
15231 &setlist, &showlist);
15233 add_com ("agent-printf", class_vars, agent_printf_command, _("\
15234 Target agent only formatted printing, like the C \"printf\" function.\n\
15235 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
15236 This supports most C printf format specifications, like %s, %d, etc.\n\
15237 This is useful for formatted output in user-defined commands."));
15239 automatic_hardware_breakpoints = true;
15241 gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
15242 "breakpoint");
15243 gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
15244 "breakpoint");
15245 gdb::observers::inferior_removed.attach (remove_inferior_breakpoints,
15246 "breakpoint");