Automatic date update in version.in
[binutils-gdb.git] / gdb / breakpoint.c
blob74f53368464a20e4c0c8cf78ebca79d630ca0631
1 /* Everything about breakpoints, for GDB.
3 Copyright (C) 1986-2022 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 "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdbsupport/gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "stack.h"
63 #include "ax-gdb.h"
64 #include "dummy-frame.h"
65 #include "interps.h"
66 #include "gdbsupport/format.h"
67 #include "thread-fsm.h"
68 #include "tid-parse.h"
69 #include "cli/cli-style.h"
70 #include "cli/cli-decode.h"
72 /* readline include files */
73 #include "readline/tilde.h"
75 /* readline defines this. */
76 #undef savestring
78 #include "mi/mi-common.h"
79 #include "extension.h"
80 #include <algorithm>
81 #include "progspace-and-thread.h"
82 #include "gdbsupport/array-view.h"
83 #include "gdbsupport/gdb_optional.h"
85 /* Prototypes for local functions. */
87 static void map_breakpoint_numbers (const char *,
88 gdb::function_view<void (breakpoint *)>);
90 static void breakpoint_re_set_default (code_breakpoint *);
92 static void
93 create_sals_from_location_spec_default (location_spec *locspec,
94 linespec_result *canonical);
96 static void create_breakpoints_sal (struct gdbarch *,
97 struct linespec_result *,
98 gdb::unique_xmalloc_ptr<char>,
99 gdb::unique_xmalloc_ptr<char>,
100 enum bptype,
101 enum bpdisp, int, int,
102 int,
103 int, int, int, unsigned);
105 static std::vector<symtab_and_line> decode_location_spec_default
106 (struct breakpoint *b, struct location_spec *locspec,
107 struct program_space *search_pspace);
109 static int can_use_hardware_watchpoint
110 (const std::vector<value_ref_ptr> &vals);
112 static void mention (const breakpoint *);
114 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
116 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
118 static struct breakpoint *
119 momentary_breakpoint_from_master (struct breakpoint *orig,
120 enum bptype type,
121 int loc_enabled, int thread);
123 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
125 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
126 CORE_ADDR bpaddr,
127 enum bptype bptype);
129 static int watchpoint_locations_match (struct bp_location *loc1,
130 struct bp_location *loc2);
132 static int breakpoint_locations_match (struct bp_location *loc1,
133 struct bp_location *loc2,
134 bool sw_hw_bps_match = false);
136 static int breakpoint_location_address_match (struct bp_location *bl,
137 const struct address_space *aspace,
138 CORE_ADDR addr);
140 static int breakpoint_location_address_range_overlap (struct bp_location *,
141 const address_space *,
142 CORE_ADDR, int);
144 static int remove_breakpoint (struct bp_location *);
145 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
147 static enum print_stop_action print_bp_stop_message (bpstat *bs);
149 static int hw_breakpoint_used_count (void);
151 static int hw_watchpoint_use_count (struct breakpoint *);
153 static int hw_watchpoint_used_count_others (struct breakpoint *except,
154 enum bptype type,
155 int *other_type_used);
157 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
158 int count);
160 static void decref_bp_location (struct bp_location **loc);
162 static std::vector<symtab_and_line> bkpt_probe_decode_location_spec
163 (struct breakpoint *b,
164 location_spec *locspec,
165 struct program_space *search_pspace);
167 static bool bl_address_is_meaningful (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 static void update_global_location_list (enum ugll_insert_mode);
206 static void update_global_location_list_nothrow (enum ugll_insert_mode);
208 static void insert_breakpoint_locations (void);
210 static void trace_pass_command (const char *, int);
212 static void set_tracepoint_count (int num);
214 static bool is_masked_watchpoint (const struct breakpoint *b);
216 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
217 otherwise. */
219 static int strace_marker_p (struct breakpoint *b);
221 static void bkpt_probe_create_sals_from_location_spec
222 (location_spec *locspec,
223 struct linespec_result *canonical);
224 static void tracepoint_probe_create_sals_from_location_spec
225 (location_spec *locspec,
226 struct linespec_result *canonical);
228 const struct breakpoint_ops code_breakpoint_ops =
230 create_sals_from_location_spec_default,
231 create_breakpoints_sal,
234 /* Breakpoints set on probes. */
235 static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
237 bkpt_probe_create_sals_from_location_spec,
238 create_breakpoints_sal,
241 /* Tracepoints set on probes. */
242 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
244 tracepoint_probe_create_sals_from_location_spec,
245 create_breakpoints_sal,
248 /* Implementation of abstract dtors. These must exist to satisfy the
249 linker. */
251 breakpoint::~breakpoint ()
255 code_breakpoint::~code_breakpoint ()
259 catchpoint::~catchpoint ()
263 /* The structure to be used in regular breakpoints. */
264 struct ordinary_breakpoint : public code_breakpoint
266 using code_breakpoint::code_breakpoint;
268 int resources_needed (const struct bp_location *) override;
269 enum print_stop_action print_it (const bpstat *bs) const override;
270 void print_mention () const override;
271 void print_recreate (struct ui_file *fp) const override;
274 /* Internal breakpoints. These typically have a lifetime the same as
275 the program, and they end up installed on the breakpoint chain with
276 a negative breakpoint number. They're visible in "maint info
277 breakpoints", but not "info breakpoints". */
278 struct internal_breakpoint : public code_breakpoint
280 internal_breakpoint (struct gdbarch *gdbarch,
281 enum bptype type, CORE_ADDR address)
282 : code_breakpoint (gdbarch, type)
284 symtab_and_line sal;
285 sal.pc = address;
286 sal.section = find_pc_overlay (sal.pc);
287 sal.pspace = current_program_space;
288 add_location (sal);
290 pspace = current_program_space;
291 disposition = disp_donttouch;
294 void re_set () override;
295 void check_status (struct bpstat *bs) override;
296 enum print_stop_action print_it (const bpstat *bs) const override;
297 void print_mention () const override;
300 /* Momentary breakpoints. These typically have a lifetime of some run
301 control command only, are always thread-specific, and have 0 for
302 breakpoint number. I.e., there can be many momentary breakpoints
303 on the breakpoint chain and they all same the same number (zero).
304 They're visible in "maint info breakpoints", but not "info
305 breakpoints". */
306 struct momentary_breakpoint : public code_breakpoint
308 momentary_breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
309 program_space *pspace_,
310 const struct frame_id &frame_id_,
311 int thread_)
312 : code_breakpoint (gdbarch_, bptype)
314 /* If FRAME_ID is valid, it should be a real frame, not an inlined
315 or tail-called one. */
316 gdb_assert (!frame_id_artificial_p (frame_id));
318 /* Momentary breakpoints are always thread-specific. */
319 gdb_assert (thread_ > 0);
321 pspace = pspace_;
322 enable_state = bp_enabled;
323 disposition = disp_donttouch;
324 frame_id = frame_id_;
325 thread = thread_;
328 void re_set () override;
329 void check_status (struct bpstat *bs) override;
330 enum print_stop_action print_it (const bpstat *bs) const override;
331 void print_mention () const override;
334 /* DPrintf breakpoints. */
335 struct dprintf_breakpoint : public ordinary_breakpoint
337 using ordinary_breakpoint::ordinary_breakpoint;
339 void re_set () override;
340 int breakpoint_hit (const struct bp_location *bl,
341 const address_space *aspace,
342 CORE_ADDR bp_addr,
343 const target_waitstatus &ws) override;
344 void print_recreate (struct ui_file *fp) const override;
345 void after_condition_true (struct bpstat *bs) override;
348 /* Ranged breakpoints. */
349 struct ranged_breakpoint : public ordinary_breakpoint
351 explicit ranged_breakpoint (struct gdbarch *gdbarch,
352 const symtab_and_line &sal_start,
353 int length,
354 location_spec_up start_locspec,
355 location_spec_up end_locspec)
356 : ordinary_breakpoint (gdbarch, bp_hardware_breakpoint)
358 bp_location *bl = add_location (sal_start);
359 bl->length = length;
361 disposition = disp_donttouch;
363 locspec = std::move (start_locspec);
364 locspec_range_end = std::move (end_locspec);
367 int breakpoint_hit (const struct bp_location *bl,
368 const address_space *aspace,
369 CORE_ADDR bp_addr,
370 const target_waitstatus &ws) override;
371 int resources_needed (const struct bp_location *) override;
372 enum print_stop_action print_it (const bpstat *bs) const override;
373 bool print_one (bp_location **) const override;
374 void print_one_detail (struct ui_out *) const override;
375 void print_mention () const override;
376 void print_recreate (struct ui_file *fp) const override;
379 /* Static tracepoints with marker (`-m'). */
380 struct static_marker_tracepoint : public tracepoint
382 using tracepoint::tracepoint;
384 std::vector<symtab_and_line> decode_location_spec
385 (struct location_spec *locspec,
386 struct program_space *search_pspace) override;
389 /* The style in which to perform a dynamic printf. This is a user
390 option because different output options have different tradeoffs;
391 if GDB does the printing, there is better error handling if there
392 is a problem with any of the arguments, but using an inferior
393 function lets you have special-purpose printers and sending of
394 output to the same place as compiled-in print functions. */
396 static const char dprintf_style_gdb[] = "gdb";
397 static const char dprintf_style_call[] = "call";
398 static const char dprintf_style_agent[] = "agent";
399 static const char *const dprintf_style_enums[] = {
400 dprintf_style_gdb,
401 dprintf_style_call,
402 dprintf_style_agent,
403 NULL
405 static const char *dprintf_style = dprintf_style_gdb;
407 /* The function to use for dynamic printf if the preferred style is to
408 call into the inferior. The value is simply a string that is
409 copied into the command, so it can be anything that GDB can
410 evaluate to a callable address, not necessarily a function name. */
412 static std::string dprintf_function = "printf";
414 /* The channel to use for dynamic printf if the preferred style is to
415 call into the inferior; if a nonempty string, it will be passed to
416 the call as the first argument, with the format string as the
417 second. As with the dprintf function, this can be anything that
418 GDB knows how to evaluate, so in addition to common choices like
419 "stderr", this could be an app-specific expression like
420 "mystreams[curlogger]". */
422 static std::string dprintf_channel;
424 /* True if dprintf commands should continue to operate even if GDB
425 has disconnected. */
426 static bool disconnected_dprintf = true;
428 struct command_line *
429 breakpoint_commands (struct breakpoint *b)
431 return b->commands ? b->commands.get () : NULL;
434 /* Flag indicating that a command has proceeded the inferior past the
435 current breakpoint. */
437 static bool breakpoint_proceeded;
439 const char *
440 bpdisp_text (enum bpdisp disp)
442 /* NOTE: the following values are a part of MI protocol and
443 represent values of 'disp' field returned when inferior stops at
444 a breakpoint. */
445 static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
447 return bpdisps[(int) disp];
450 /* Prototypes for exported functions. */
451 /* If FALSE, gdb will not use hardware support for watchpoints, even
452 if such is available. */
453 static int can_use_hw_watchpoints;
455 static void
456 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
457 struct cmd_list_element *c,
458 const char *value)
460 gdb_printf (file,
461 _("Debugger's willingness to use "
462 "watchpoint hardware is %s.\n"),
463 value);
466 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
467 If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
468 for unrecognized breakpoint locations.
469 If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized. */
470 static enum auto_boolean pending_break_support;
471 static void
472 show_pending_break_support (struct ui_file *file, int from_tty,
473 struct cmd_list_element *c,
474 const char *value)
476 gdb_printf (file,
477 _("Debugger's behavior regarding "
478 "pending breakpoints is %s.\n"),
479 value);
482 /* If true, gdb will automatically use hardware breakpoints for breakpoints
483 set with "break" but falling in read-only memory.
484 If false, gdb will warn about such breakpoints, but won't automatically
485 use hardware breakpoints. */
486 static bool automatic_hardware_breakpoints;
487 static void
488 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
489 struct cmd_list_element *c,
490 const char *value)
492 gdb_printf (file,
493 _("Automatic usage of hardware breakpoints is %s.\n"),
494 value);
497 /* If on, GDB keeps breakpoints inserted even if the inferior is
498 stopped, and immediately inserts any new breakpoints as soon as
499 they're created. If off (default), GDB keeps breakpoints off of
500 the target as long as possible. That is, it delays inserting
501 breakpoints until the next resume, and removes them again when the
502 target fully stops. This is a bit safer in case GDB crashes while
503 processing user input. */
504 static bool always_inserted_mode = false;
506 static void
507 show_always_inserted_mode (struct ui_file *file, int from_tty,
508 struct cmd_list_element *c, const char *value)
510 gdb_printf (file, _("Always inserted breakpoint mode is %s.\n"),
511 value);
514 /* See breakpoint.h. */
517 breakpoints_should_be_inserted_now (void)
519 if (gdbarch_has_global_breakpoints (target_gdbarch ()))
521 /* If breakpoints are global, they should be inserted even if no
522 thread under gdb's control is running, or even if there are
523 no threads under GDB's control yet. */
524 return 1;
526 else
528 if (always_inserted_mode)
530 /* The user wants breakpoints inserted even if all threads
531 are stopped. */
532 return 1;
535 for (inferior *inf : all_inferiors ())
536 if (inf->has_execution ()
537 && threads_are_executing (inf->process_target ()))
538 return 1;
540 /* Don't remove breakpoints yet if, even though all threads are
541 stopped, we still have events to process. */
542 for (thread_info *tp : all_non_exited_threads ())
543 if (tp->resumed () && tp->has_pending_waitstatus ())
544 return 1;
546 return 0;
549 static const char condition_evaluation_both[] = "host or target";
551 /* Modes for breakpoint condition evaluation. */
552 static const char condition_evaluation_auto[] = "auto";
553 static const char condition_evaluation_host[] = "host";
554 static const char condition_evaluation_target[] = "target";
555 static const char *const condition_evaluation_enums[] = {
556 condition_evaluation_auto,
557 condition_evaluation_host,
558 condition_evaluation_target,
559 NULL
562 /* Global that holds the current mode for breakpoint condition evaluation. */
563 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
565 /* Global that we use to display information to the user (gets its value from
566 condition_evaluation_mode_1. */
567 static const char *condition_evaluation_mode = condition_evaluation_auto;
569 /* Translate a condition evaluation mode MODE into either "host"
570 or "target". This is used mostly to translate from "auto" to the
571 real setting that is being used. It returns the translated
572 evaluation mode. */
574 static const char *
575 translate_condition_evaluation_mode (const char *mode)
577 if (mode == condition_evaluation_auto)
579 if (target_supports_evaluation_of_breakpoint_conditions ())
580 return condition_evaluation_target;
581 else
582 return condition_evaluation_host;
584 else
585 return mode;
588 /* Discovers what condition_evaluation_auto translates to. */
590 static const char *
591 breakpoint_condition_evaluation_mode (void)
593 return translate_condition_evaluation_mode (condition_evaluation_mode);
596 /* Return true if GDB should evaluate breakpoint conditions or false
597 otherwise. */
599 static int
600 gdb_evaluates_breakpoint_condition_p (void)
602 const char *mode = breakpoint_condition_evaluation_mode ();
604 return (mode == condition_evaluation_host);
607 /* Are we executing breakpoint commands? */
608 static int executing_breakpoint_commands;
610 /* Are overlay event breakpoints enabled? */
611 static int overlay_events_enabled;
613 /* See description in breakpoint.h. */
614 bool target_exact_watchpoints = false;
616 /* Walk the following statement or block through all breakpoints.
617 ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
618 current breakpoint. */
620 #define ALL_BREAKPOINTS_SAFE(B,TMP) \
621 for (B = breakpoint_chain; \
622 B ? (TMP=B->next, 1): 0; \
623 B = TMP)
625 /* Chains of all breakpoints defined. */
627 static struct breakpoint *breakpoint_chain;
629 /* See breakpoint.h. */
631 breakpoint_range
632 all_breakpoints ()
634 return breakpoint_range (breakpoint_chain);
637 /* See breakpoint.h. */
639 breakpoint_safe_range
640 all_breakpoints_safe ()
642 return breakpoint_safe_range (all_breakpoints ());
645 /* See breakpoint.h. */
647 tracepoint_range
648 all_tracepoints ()
650 return tracepoint_range (breakpoint_chain);
653 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS. */
655 static std::vector<bp_location *> bp_locations;
657 /* See breakpoint.h. */
659 const std::vector<bp_location *> &
660 all_bp_locations ()
662 return bp_locations;
665 /* Range to iterate over breakpoint locations at a given address. */
667 struct bp_locations_at_addr_range
669 using iterator = std::vector<bp_location *>::iterator;
671 bp_locations_at_addr_range (CORE_ADDR addr)
673 struct compare
675 bool operator() (const bp_location *loc, CORE_ADDR addr_) const
676 { return loc->address < addr_; }
678 bool operator() (CORE_ADDR addr_, const bp_location *loc) const
679 { return addr_ < loc->address; }
682 auto it_pair = std::equal_range (bp_locations.begin (), bp_locations.end (),
683 addr, compare ());
685 m_begin = it_pair.first;
686 m_end = it_pair.second;
689 iterator begin () const
690 { return m_begin; }
692 iterator end () const
693 { return m_end; }
695 private:
696 iterator m_begin;
697 iterator m_end;
700 /* Return a range to iterate over all breakpoint locations exactly at address
701 ADDR.
703 If it's needed to iterate multiple times on the same range, it's possible
704 to save the range in a local variable and use it multiple times:
706 auto range = all_bp_locations_at_addr (addr);
708 for (bp_location *loc : range)
709 // use loc
711 for (bp_location *loc : range)
712 // use loc
714 This saves a bit of time, as it avoids re-doing the binary searches to find
715 the range's boundaries. Just remember not to change the bp_locations vector
716 in the mean time, as it could make the range's iterators stale. */
718 static bp_locations_at_addr_range
719 all_bp_locations_at_addr (CORE_ADDR addr)
721 return bp_locations_at_addr_range (addr);
724 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
725 ADDRESS for the current elements of BP_LOCATIONS which get a valid
726 result from bp_location_has_shadow. You can use it for roughly
727 limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
728 an address you need to read. */
730 static CORE_ADDR bp_locations_placed_address_before_address_max;
732 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
733 + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
734 BP_LOCATIONS which get a valid result from bp_location_has_shadow.
735 You can use it for roughly limiting the subrange of BP_LOCATIONS to
736 scan for shadow bytes for an address you need to read. */
738 static CORE_ADDR bp_locations_shadow_len_after_address_max;
740 /* The locations that no longer correspond to any breakpoint, unlinked
741 from the bp_locations array, but for which a hit may still be
742 reported by a target. */
743 static std::vector<bp_location *> moribund_locations;
745 /* Number of last breakpoint made. */
747 static int breakpoint_count;
749 /* The value of `breakpoint_count' before the last command that
750 created breakpoints. If the last (break-like) command created more
751 than one breakpoint, then the difference between BREAKPOINT_COUNT
752 and PREV_BREAKPOINT_COUNT is more than one. */
753 static int prev_breakpoint_count;
755 /* Number of last tracepoint made. */
757 static int tracepoint_count;
759 static struct cmd_list_element *breakpoint_set_cmdlist;
760 static struct cmd_list_element *breakpoint_show_cmdlist;
761 struct cmd_list_element *save_cmdlist;
763 /* Return whether a breakpoint is an active enabled breakpoint. */
764 static int
765 breakpoint_enabled (struct breakpoint *b)
767 return (b->enable_state == bp_enabled);
770 /* Set breakpoint count to NUM. */
772 static void
773 set_breakpoint_count (int num)
775 prev_breakpoint_count = breakpoint_count;
776 breakpoint_count = num;
777 set_internalvar_integer (lookup_internalvar ("bpnum"), num);
780 /* Used by `start_rbreak_breakpoints' below, to record the current
781 breakpoint count before "rbreak" creates any breakpoint. */
782 static int rbreak_start_breakpoint_count;
784 /* Called at the start an "rbreak" command to record the first
785 breakpoint made. */
787 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
789 rbreak_start_breakpoint_count = breakpoint_count;
792 /* Called at the end of an "rbreak" command to record the last
793 breakpoint made. */
795 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
797 prev_breakpoint_count = rbreak_start_breakpoint_count;
800 /* Used in run_command to zero the hit count when a new run starts. */
802 void
803 clear_breakpoint_hit_counts (void)
805 for (breakpoint *b : all_breakpoints ())
806 b->hit_count = 0;
810 /* Return the breakpoint with the specified number, or NULL
811 if the number does not refer to an existing breakpoint. */
813 struct breakpoint *
814 get_breakpoint (int num)
816 for (breakpoint *b : all_breakpoints ())
817 if (b->number == num)
818 return b;
820 return nullptr;
825 /* Mark locations as "conditions have changed" in case the target supports
826 evaluating conditions on its side. */
828 static void
829 mark_breakpoint_modified (struct breakpoint *b)
831 /* This is only meaningful if the target is
832 evaluating conditions and if the user has
833 opted for condition evaluation on the target's
834 side. */
835 if (gdb_evaluates_breakpoint_condition_p ()
836 || !target_supports_evaluation_of_breakpoint_conditions ())
837 return;
839 if (!is_breakpoint (b))
840 return;
842 for (bp_location *loc : b->locations ())
843 loc->condition_changed = condition_modified;
846 /* Mark location as "conditions have changed" in case the target supports
847 evaluating conditions on its side. */
849 static void
850 mark_breakpoint_location_modified (struct bp_location *loc)
852 /* This is only meaningful if the target is
853 evaluating conditions and if the user has
854 opted for condition evaluation on the target's
855 side. */
856 if (gdb_evaluates_breakpoint_condition_p ()
857 || !target_supports_evaluation_of_breakpoint_conditions ())
859 return;
861 if (!is_breakpoint (loc->owner))
862 return;
864 loc->condition_changed = condition_modified;
867 /* Sets the condition-evaluation mode using the static global
868 condition_evaluation_mode. */
870 static void
871 set_condition_evaluation_mode (const char *args, int from_tty,
872 struct cmd_list_element *c)
874 const char *old_mode, *new_mode;
876 if ((condition_evaluation_mode_1 == condition_evaluation_target)
877 && !target_supports_evaluation_of_breakpoint_conditions ())
879 condition_evaluation_mode_1 = condition_evaluation_mode;
880 warning (_("Target does not support breakpoint condition evaluation.\n"
881 "Using host evaluation mode instead."));
882 return;
885 new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
886 old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
888 /* Flip the switch. Flip it even if OLD_MODE == NEW_MODE as one of the
889 settings was "auto". */
890 condition_evaluation_mode = condition_evaluation_mode_1;
892 /* Only update the mode if the user picked a different one. */
893 if (new_mode != old_mode)
895 /* If the user switched to a different evaluation mode, we
896 need to synch the changes with the target as follows:
898 "host" -> "target": Send all (valid) conditions to the target.
899 "target" -> "host": Remove all the conditions from the target.
902 if (new_mode == condition_evaluation_target)
904 /* Mark everything modified and synch conditions with the
905 target. */
906 for (bp_location *loc : all_bp_locations ())
907 mark_breakpoint_location_modified (loc);
909 else
911 /* Manually mark non-duplicate locations to synch conditions
912 with the target. We do this to remove all the conditions the
913 target knows about. */
914 for (bp_location *loc : all_bp_locations ())
915 if (is_breakpoint (loc->owner) && loc->inserted)
916 loc->needs_update = 1;
919 /* Do the update. */
920 update_global_location_list (UGLL_MAY_INSERT);
923 return;
926 /* Shows the current mode of breakpoint condition evaluation. Explicitly shows
927 what "auto" is translating to. */
929 static void
930 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
931 struct cmd_list_element *c, const char *value)
933 if (condition_evaluation_mode == condition_evaluation_auto)
934 gdb_printf (file,
935 _("Breakpoint condition evaluation "
936 "mode is %s (currently %s).\n"),
937 value,
938 breakpoint_condition_evaluation_mode ());
939 else
940 gdb_printf (file, _("Breakpoint condition evaluation mode is %s.\n"),
941 value);
944 /* Parse COND_STRING in the context of LOC and set as the condition
945 expression of LOC. BP_NUM is the number of LOC's owner, LOC_NUM is
946 the number of LOC within its owner. In case of parsing error, mark
947 LOC as DISABLED_BY_COND. In case of success, unset DISABLED_BY_COND. */
949 static void
950 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
951 int bp_num, int loc_num)
953 bool has_junk = false;
956 expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
957 block_for_pc (loc->address), 0);
958 if (*cond_string != 0)
959 has_junk = true;
960 else
962 loc->cond = std::move (new_exp);
963 if (loc->disabled_by_cond && loc->enabled)
964 gdb_printf (_("Breakpoint %d's condition is now valid at "
965 "location %d, enabling.\n"),
966 bp_num, loc_num);
968 loc->disabled_by_cond = false;
971 catch (const gdb_exception_error &e)
973 if (loc->enabled)
975 /* Warn if a user-enabled location is now becoming disabled-by-cond.
976 BP_NUM is 0 if the breakpoint is being defined for the first
977 time using the "break ... if ..." command, and non-zero if
978 already defined. */
979 if (bp_num != 0)
980 warning (_("failed to validate condition at location %d.%d, "
981 "disabling:\n %s"), bp_num, loc_num, e.what ());
982 else
983 warning (_("failed to validate condition at location %d, "
984 "disabling:\n %s"), loc_num, e.what ());
987 loc->disabled_by_cond = true;
990 if (has_junk)
991 error (_("Garbage '%s' follows condition"), cond_string);
994 void
995 set_breakpoint_condition (struct breakpoint *b, const char *exp,
996 int from_tty, bool force)
998 if (*exp == 0)
1000 b->cond_string.reset ();
1002 if (is_watchpoint (b))
1003 static_cast<watchpoint *> (b)->cond_exp.reset ();
1004 else
1006 int loc_num = 1;
1007 for (bp_location *loc : b->locations ())
1009 loc->cond.reset ();
1010 if (loc->disabled_by_cond && loc->enabled)
1011 gdb_printf (_("Breakpoint %d's condition is now valid at "
1012 "location %d, enabling.\n"),
1013 b->number, loc_num);
1014 loc->disabled_by_cond = false;
1015 loc_num++;
1017 /* No need to free the condition agent expression
1018 bytecode (if we have one). We will handle this
1019 when we go through update_global_location_list. */
1023 if (from_tty)
1024 gdb_printf (_("Breakpoint %d now unconditional.\n"), b->number);
1026 else
1028 if (is_watchpoint (b))
1030 innermost_block_tracker tracker;
1031 const char *arg = exp;
1032 expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
1033 if (*arg != 0)
1034 error (_("Junk at end of expression"));
1035 watchpoint *w = static_cast<watchpoint *> (b);
1036 w->cond_exp = std::move (new_exp);
1037 w->cond_exp_valid_block = tracker.block ();
1039 else
1041 /* Parse and set condition expressions. We make two passes.
1042 In the first, we parse the condition string to see if it
1043 is valid in at least one location. If so, the condition
1044 would be accepted. So we go ahead and set the locations'
1045 conditions. In case no valid case is found, we throw
1046 the error and the condition string will be rejected.
1047 This two-pass approach is taken to avoid setting the
1048 state of locations in case of a reject. */
1049 for (bp_location *loc : b->locations ())
1053 const char *arg = exp;
1054 parse_exp_1 (&arg, loc->address,
1055 block_for_pc (loc->address), 0);
1056 if (*arg != 0)
1057 error (_("Junk at end of expression"));
1058 break;
1060 catch (const gdb_exception_error &e)
1062 /* Condition string is invalid. If this happens to
1063 be the last loc, abandon (if not forced) or continue
1064 (if forced). */
1065 if (loc->next == nullptr && !force)
1066 throw;
1070 /* If we reach here, the condition is valid at some locations. */
1071 int loc_num = 1;
1072 for (bp_location *loc : b->locations ())
1074 set_breakpoint_location_condition (exp, loc, b->number, loc_num);
1075 loc_num++;
1079 /* We know that the new condition parsed successfully. The
1080 condition string of the breakpoint can be safely updated. */
1081 b->cond_string = make_unique_xstrdup (exp);
1082 b->condition_not_parsed = 0;
1084 mark_breakpoint_modified (b);
1086 gdb::observers::breakpoint_modified.notify (b);
1089 /* See breakpoint.h. */
1091 void
1092 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
1093 bool force)
1095 for (breakpoint *b : all_breakpoints ())
1096 if (b->number == bpnum)
1098 /* Check if this breakpoint has a "stop" method implemented in an
1099 extension language. This method and conditions entered into GDB
1100 from the CLI are mutually exclusive. */
1101 const struct extension_language_defn *extlang
1102 = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1104 if (extlang != NULL)
1106 error (_("Only one stop condition allowed. There is currently"
1107 " a %s stop condition defined for this breakpoint."),
1108 ext_lang_capitalized_name (extlang));
1110 set_breakpoint_condition (b, exp, from_tty, force);
1112 if (is_breakpoint (b))
1113 update_global_location_list (UGLL_MAY_INSERT);
1115 return;
1118 error (_("No breakpoint number %d."), bpnum);
1121 /* The options for the "condition" command. */
1123 struct condition_command_opts
1125 /* For "-force". */
1126 bool force_condition = false;
1129 static const gdb::option::option_def condition_command_option_defs[] = {
1131 gdb::option::flag_option_def<condition_command_opts> {
1132 "force",
1133 [] (condition_command_opts *opts) { return &opts->force_condition; },
1134 N_("Set the condition even if it is invalid for all current locations."),
1139 /* Create an option_def_group for the "condition" options, with
1140 CC_OPTS as context. */
1142 static inline gdb::option::option_def_group
1143 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1145 return {{condition_command_option_defs}, cc_opts};
1148 /* Completion for the "condition" command. */
1150 static void
1151 condition_completer (struct cmd_list_element *cmd,
1152 completion_tracker &tracker,
1153 const char *text, const char * /*word*/)
1155 bool has_no_arguments = (*text == '\0');
1156 condition_command_opts cc_opts;
1157 const auto group = make_condition_command_options_def_group (&cc_opts);
1158 if (gdb::option::complete_options
1159 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1160 return;
1162 text = skip_spaces (text);
1163 const char *space = skip_to_space (text);
1164 if (*space == '\0')
1166 int len;
1168 if (text[0] == '$')
1170 tracker.advance_custom_word_point_by (1);
1171 /* We don't support completion of history indices. */
1172 if (!isdigit (text[1]))
1173 complete_internalvar (tracker, &text[1]);
1174 return;
1177 /* Suggest the "-force" flag if no arguments are given. If
1178 arguments were passed, they either already include the flag,
1179 or we are beyond the point of suggesting it because it's
1180 positionally the first argument. */
1181 if (has_no_arguments)
1182 gdb::option::complete_on_all_options (tracker, group);
1184 /* We're completing the breakpoint number. */
1185 len = strlen (text);
1187 for (breakpoint *b : all_breakpoints ())
1189 char number[50];
1191 xsnprintf (number, sizeof (number), "%d", b->number);
1193 if (strncmp (number, text, len) == 0)
1194 tracker.add_completion (make_unique_xstrdup (number));
1197 return;
1200 /* We're completing the expression part. Skip the breakpoint num. */
1201 const char *exp_start = skip_spaces (space);
1202 tracker.advance_custom_word_point_by (exp_start - text);
1203 text = exp_start;
1204 const char *word = advance_to_expression_complete_word_point (tracker, text);
1205 expression_completer (cmd, tracker, text, word);
1208 /* condition N EXP -- set break condition of breakpoint N to EXP. */
1210 static void
1211 condition_command (const char *arg, int from_tty)
1213 const char *p;
1214 int bnum;
1216 if (arg == 0)
1217 error_no_arg (_("breakpoint number"));
1219 p = arg;
1221 /* Check if the "-force" flag was passed. */
1222 condition_command_opts cc_opts;
1223 const auto group = make_condition_command_options_def_group (&cc_opts);
1224 gdb::option::process_options
1225 (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1227 bnum = get_number (&p);
1228 if (bnum == 0)
1229 error (_("Bad breakpoint argument: '%s'"), arg);
1231 set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1234 /* Check that COMMAND do not contain commands that are suitable
1235 only for tracepoints and not suitable for ordinary breakpoints.
1236 Throw if any such commands is found. */
1238 static void
1239 check_no_tracepoint_commands (struct command_line *commands)
1241 struct command_line *c;
1243 for (c = commands; c; c = c->next)
1245 if (c->control_type == while_stepping_control)
1246 error (_("The 'while-stepping' command can "
1247 "only be used for tracepoints"));
1249 check_no_tracepoint_commands (c->body_list_0.get ());
1250 check_no_tracepoint_commands (c->body_list_1.get ());
1252 /* Not that command parsing removes leading whitespace and comment
1253 lines and also empty lines. So, we only need to check for
1254 command directly. */
1255 if (strstr (c->line, "collect ") == c->line)
1256 error (_("The 'collect' command can only be used for tracepoints"));
1258 if (strstr (c->line, "teval ") == c->line)
1259 error (_("The 'teval' command can only be used for tracepoints"));
1263 struct longjmp_breakpoint : public momentary_breakpoint
1265 using momentary_breakpoint::momentary_breakpoint;
1267 ~longjmp_breakpoint () override;
1270 /* Encapsulate tests for different types of tracepoints. */
1272 static bool
1273 is_tracepoint_type (bptype type)
1275 return (type == bp_tracepoint
1276 || type == bp_fast_tracepoint
1277 || type == bp_static_tracepoint
1278 || type == bp_static_marker_tracepoint);
1281 /* See breakpoint.h. */
1283 bool
1284 is_tracepoint (const struct breakpoint *b)
1286 return is_tracepoint_type (b->type);
1289 /* Factory function to create an appropriate instance of breakpoint given
1290 TYPE. */
1292 template<typename... Arg>
1293 static std::unique_ptr<code_breakpoint>
1294 new_breakpoint_from_type (struct gdbarch *gdbarch, bptype type,
1295 Arg&&... args)
1297 code_breakpoint *b;
1299 switch (type)
1301 case bp_breakpoint:
1302 case bp_hardware_breakpoint:
1303 b = new ordinary_breakpoint (gdbarch, type,
1304 std::forward<Arg> (args)...);
1305 break;
1307 case bp_fast_tracepoint:
1308 case bp_static_tracepoint:
1309 case bp_tracepoint:
1310 b = new tracepoint (gdbarch, type,
1311 std::forward<Arg> (args)...);
1312 break;
1314 case bp_static_marker_tracepoint:
1315 b = new static_marker_tracepoint (gdbarch, type,
1316 std::forward<Arg> (args)...);
1317 break;
1319 case bp_dprintf:
1320 b = new dprintf_breakpoint (gdbarch, type,
1321 std::forward<Arg> (args)...);
1322 break;
1324 default:
1325 gdb_assert_not_reached ("invalid type");
1328 return std::unique_ptr<code_breakpoint> (b);
1331 /* A helper function that validates that COMMANDS are valid for a
1332 breakpoint. This function will throw an exception if a problem is
1333 found. */
1335 static void
1336 validate_commands_for_breakpoint (struct breakpoint *b,
1337 struct command_line *commands)
1339 if (is_tracepoint (b))
1341 struct tracepoint *t = (struct tracepoint *) b;
1342 struct command_line *c;
1343 struct command_line *while_stepping = 0;
1345 /* Reset the while-stepping step count. The previous commands
1346 might have included a while-stepping action, while the new
1347 ones might not. */
1348 t->step_count = 0;
1350 /* We need to verify that each top-level element of commands is
1351 valid for tracepoints, that there's at most one
1352 while-stepping element, and that the while-stepping's body
1353 has valid tracing commands excluding nested while-stepping.
1354 We also need to validate the tracepoint action line in the
1355 context of the tracepoint --- validate_actionline actually
1356 has side effects, like setting the tracepoint's
1357 while-stepping STEP_COUNT, in addition to checking if the
1358 collect/teval actions parse and make sense in the
1359 tracepoint's context. */
1360 for (c = commands; c; c = c->next)
1362 if (c->control_type == while_stepping_control)
1364 if (b->type == bp_fast_tracepoint)
1365 error (_("The 'while-stepping' command "
1366 "cannot be used for fast tracepoint"));
1367 else if (b->type == bp_static_tracepoint
1368 || b->type == bp_static_marker_tracepoint)
1369 error (_("The 'while-stepping' command "
1370 "cannot be used for static tracepoint"));
1372 if (while_stepping)
1373 error (_("The 'while-stepping' command "
1374 "can be used only once"));
1375 else
1376 while_stepping = c;
1379 validate_actionline (c->line, b);
1381 if (while_stepping)
1383 struct command_line *c2;
1385 gdb_assert (while_stepping->body_list_1 == nullptr);
1386 c2 = while_stepping->body_list_0.get ();
1387 for (; c2; c2 = c2->next)
1389 if (c2->control_type == while_stepping_control)
1390 error (_("The 'while-stepping' command cannot be nested"));
1394 else
1396 check_no_tracepoint_commands (commands);
1400 /* Return a vector of all the static tracepoints set at ADDR. The
1401 caller is responsible for releasing the vector. */
1403 std::vector<breakpoint *>
1404 static_tracepoints_here (CORE_ADDR addr)
1406 std::vector<breakpoint *> found;
1408 for (breakpoint *b : all_breakpoints ())
1409 if (b->type == bp_static_tracepoint
1410 || b->type == bp_static_marker_tracepoint)
1412 for (bp_location *loc : b->locations ())
1413 if (loc->address == addr)
1414 found.push_back (b);
1417 return found;
1420 /* Set the command list of B to COMMANDS. If breakpoint is tracepoint,
1421 validate that only allowed commands are included. */
1423 void
1424 breakpoint_set_commands (struct breakpoint *b,
1425 counted_command_line &&commands)
1427 validate_commands_for_breakpoint (b, commands.get ());
1429 b->commands = std::move (commands);
1430 gdb::observers::breakpoint_modified.notify (b);
1433 /* Set the internal `silent' flag on the breakpoint. Note that this
1434 is not the same as the "silent" that may appear in the breakpoint's
1435 commands. */
1437 void
1438 breakpoint_set_silent (struct breakpoint *b, int silent)
1440 int old_silent = b->silent;
1442 b->silent = silent;
1443 if (old_silent != silent)
1444 gdb::observers::breakpoint_modified.notify (b);
1447 /* Set the thread for this breakpoint. If THREAD is -1, make the
1448 breakpoint work for any thread. */
1450 void
1451 breakpoint_set_thread (struct breakpoint *b, int thread)
1453 int old_thread = b->thread;
1455 b->thread = thread;
1456 if (old_thread != thread)
1457 gdb::observers::breakpoint_modified.notify (b);
1460 /* Set the task for this breakpoint. If TASK is 0, make the
1461 breakpoint work for any task. */
1463 void
1464 breakpoint_set_task (struct breakpoint *b, int task)
1466 int old_task = b->task;
1468 b->task = task;
1469 if (old_task != task)
1470 gdb::observers::breakpoint_modified.notify (b);
1473 static void
1474 commands_command_1 (const char *arg, int from_tty,
1475 struct command_line *control)
1477 counted_command_line cmd;
1478 /* cmd_read will be true once we have read cmd. Note that cmd might still be
1479 NULL after the call to read_command_lines if the user provides an empty
1480 list of command by just typing "end". */
1481 bool cmd_read = false;
1483 std::string new_arg;
1485 if (arg == NULL || !*arg)
1487 /* Argument not explicitly given. Synthesize it. */
1488 if (breakpoint_count - prev_breakpoint_count > 1)
1489 new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1490 breakpoint_count);
1491 else if (breakpoint_count > 0)
1492 new_arg = string_printf ("%d", breakpoint_count);
1494 else
1496 /* Create a copy of ARG. This is needed because the "commands"
1497 command may be coming from a script. In that case, the read
1498 line buffer is going to be overwritten in the lambda of
1499 'map_breakpoint_numbers' below when reading the next line
1500 before we are are done parsing the breakpoint numbers. */
1501 new_arg = arg;
1503 arg = new_arg.c_str ();
1505 map_breakpoint_numbers
1506 (arg, [&] (breakpoint *b)
1508 if (!cmd_read)
1510 gdb_assert (cmd == NULL);
1511 if (control != NULL)
1512 cmd = control->body_list_0;
1513 else
1515 std::string str
1516 = string_printf (_("Type commands for breakpoint(s) "
1517 "%s, one per line."),
1518 arg);
1520 auto do_validate = [=] (const char *line)
1522 validate_actionline (line, b);
1524 gdb::function_view<void (const char *)> validator;
1525 if (is_tracepoint (b))
1526 validator = do_validate;
1528 cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1530 cmd_read = true;
1533 /* If a breakpoint was on the list more than once, we don't need to
1534 do anything. */
1535 if (b->commands != cmd)
1537 validate_commands_for_breakpoint (b, cmd.get ());
1538 b->commands = cmd;
1539 gdb::observers::breakpoint_modified.notify (b);
1544 static void
1545 commands_command (const char *arg, int from_tty)
1547 commands_command_1 (arg, from_tty, NULL);
1550 /* Like commands_command, but instead of reading the commands from
1551 input stream, takes them from an already parsed command structure.
1553 This is used by cli-script.c to DTRT with breakpoint commands
1554 that are part of if and while bodies. */
1555 enum command_control_type
1556 commands_from_control_command (const char *arg, struct command_line *cmd)
1558 commands_command_1 (arg, 0, cmd);
1559 return simple_control;
1562 /* Return non-zero if BL->TARGET_INFO contains valid information. */
1564 static int
1565 bp_location_has_shadow (struct bp_location *bl)
1567 if (bl->loc_type != bp_loc_software_breakpoint)
1568 return 0;
1569 if (!bl->inserted)
1570 return 0;
1571 if (bl->target_info.shadow_len == 0)
1572 /* BL isn't valid, or doesn't shadow memory. */
1573 return 0;
1574 return 1;
1577 /* Update BUF, which is LEN bytes read from the target address
1578 MEMADDR, by replacing a memory breakpoint with its shadowed
1579 contents.
1581 If READBUF is not NULL, this buffer must not overlap with the of
1582 the breakpoint location's shadow_contents buffer. Otherwise, a
1583 failed assertion internal error will be raised. */
1585 static void
1586 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1587 const gdb_byte *writebuf_org,
1588 ULONGEST memaddr, LONGEST len,
1589 struct bp_target_info *target_info,
1590 struct gdbarch *gdbarch)
1592 /* Now do full processing of the found relevant range of elements. */
1593 CORE_ADDR bp_addr = 0;
1594 int bp_size = 0;
1595 int bptoffset = 0;
1597 if (!breakpoint_address_match (target_info->placed_address_space, 0,
1598 current_program_space->aspace, 0))
1600 /* The breakpoint is inserted in a different address space. */
1601 return;
1604 /* Addresses and length of the part of the breakpoint that
1605 we need to copy. */
1606 bp_addr = target_info->placed_address;
1607 bp_size = target_info->shadow_len;
1609 if (bp_addr + bp_size <= memaddr)
1611 /* The breakpoint is entirely before the chunk of memory we are
1612 reading. */
1613 return;
1616 if (bp_addr >= memaddr + len)
1618 /* The breakpoint is entirely after the chunk of memory we are
1619 reading. */
1620 return;
1623 /* Offset within shadow_contents. */
1624 if (bp_addr < memaddr)
1626 /* Only copy the second part of the breakpoint. */
1627 bp_size -= memaddr - bp_addr;
1628 bptoffset = memaddr - bp_addr;
1629 bp_addr = memaddr;
1632 if (bp_addr + bp_size > memaddr + len)
1634 /* Only copy the first part of the breakpoint. */
1635 bp_size -= (bp_addr + bp_size) - (memaddr + len);
1638 if (readbuf != NULL)
1640 /* Verify that the readbuf buffer does not overlap with the
1641 shadow_contents buffer. */
1642 gdb_assert (target_info->shadow_contents >= readbuf + len
1643 || readbuf >= (target_info->shadow_contents
1644 + target_info->shadow_len));
1646 /* Update the read buffer with this inserted breakpoint's
1647 shadow. */
1648 memcpy (readbuf + bp_addr - memaddr,
1649 target_info->shadow_contents + bptoffset, bp_size);
1651 else
1653 const unsigned char *bp;
1654 CORE_ADDR addr = target_info->reqstd_address;
1655 int placed_size;
1657 /* Update the shadow with what we want to write to memory. */
1658 memcpy (target_info->shadow_contents + bptoffset,
1659 writebuf_org + bp_addr - memaddr, bp_size);
1661 /* Determine appropriate breakpoint contents and size for this
1662 address. */
1663 bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1665 /* Update the final write buffer with this inserted
1666 breakpoint's INSN. */
1667 memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1671 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1672 by replacing any memory breakpoints with their shadowed contents.
1674 If READBUF is not NULL, this buffer must not overlap with any of
1675 the breakpoint location's shadow_contents buffers. Otherwise,
1676 a failed assertion internal error will be raised.
1678 The range of shadowed area by each bp_location is:
1679 bl->address - bp_locations_placed_address_before_address_max
1680 up to bl->address + bp_locations_shadow_len_after_address_max
1681 The range we were requested to resolve shadows for is:
1682 memaddr ... memaddr + len
1683 Thus the safe cutoff boundaries for performance optimization are
1684 memaddr + len <= (bl->address
1685 - bp_locations_placed_address_before_address_max)
1686 and:
1687 bl->address + bp_locations_shadow_len_after_address_max <= memaddr */
1689 void
1690 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1691 const gdb_byte *writebuf_org,
1692 ULONGEST memaddr, LONGEST len)
1694 /* Left boundary, right boundary and median element of our binary
1695 search. */
1696 unsigned bc_l, bc_r, bc;
1698 /* Find BC_L which is a leftmost element which may affect BUF
1699 content. It is safe to report lower value but a failure to
1700 report higher one. */
1702 bc_l = 0;
1703 bc_r = bp_locations.size ();
1704 while (bc_l + 1 < bc_r)
1706 struct bp_location *bl;
1708 bc = (bc_l + bc_r) / 2;
1709 bl = bp_locations[bc];
1711 /* Check first BL->ADDRESS will not overflow due to the added
1712 constant. Then advance the left boundary only if we are sure
1713 the BC element can in no way affect the BUF content (MEMADDR
1714 to MEMADDR + LEN range).
1716 Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1717 offset so that we cannot miss a breakpoint with its shadow
1718 range tail still reaching MEMADDR. */
1720 if ((bl->address + bp_locations_shadow_len_after_address_max
1721 >= bl->address)
1722 && (bl->address + bp_locations_shadow_len_after_address_max
1723 <= memaddr))
1724 bc_l = bc;
1725 else
1726 bc_r = bc;
1729 /* Due to the binary search above, we need to make sure we pick the
1730 first location that's at BC_L's address. E.g., if there are
1731 multiple locations at the same address, BC_L may end up pointing
1732 at a duplicate location, and miss the "master"/"inserted"
1733 location. Say, given locations L1, L2 and L3 at addresses A and
1736 L1@A, L2@A, L3@B, ...
1738 BC_L could end up pointing at location L2, while the "master"
1739 location could be L1. Since the `loc->inserted' flag is only set
1740 on "master" locations, we'd forget to restore the shadow of L1
1741 and L2. */
1742 while (bc_l > 0
1743 && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1744 bc_l--;
1746 /* Now do full processing of the found relevant range of elements. */
1748 for (bc = bc_l; bc < bp_locations.size (); bc++)
1750 struct bp_location *bl = bp_locations[bc];
1752 /* bp_location array has BL->OWNER always non-NULL. */
1753 if (bl->owner->type == bp_none)
1754 warning (_("reading through apparently deleted breakpoint #%d?"),
1755 bl->owner->number);
1757 /* Performance optimization: any further element can no longer affect BUF
1758 content. */
1760 if (bl->address >= bp_locations_placed_address_before_address_max
1761 && (memaddr + len
1762 <= (bl->address
1763 - bp_locations_placed_address_before_address_max)))
1764 break;
1766 if (!bp_location_has_shadow (bl))
1767 continue;
1769 one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1770 memaddr, len, &bl->target_info, bl->gdbarch);
1774 /* See breakpoint.h. */
1776 bool
1777 is_breakpoint (const struct breakpoint *bpt)
1779 return (bpt->type == bp_breakpoint
1780 || bpt->type == bp_hardware_breakpoint
1781 || bpt->type == bp_dprintf);
1784 /* Return true if BPT is of any hardware watchpoint kind. */
1786 static bool
1787 is_hardware_watchpoint (const struct breakpoint *bpt)
1789 return (bpt->type == bp_hardware_watchpoint
1790 || bpt->type == bp_read_watchpoint
1791 || bpt->type == bp_access_watchpoint);
1794 /* See breakpoint.h. */
1796 bool
1797 is_watchpoint (const struct breakpoint *bpt)
1799 return (is_hardware_watchpoint (bpt)
1800 || bpt->type == bp_watchpoint);
1803 /* Returns true if the current thread and its running state are safe
1804 to evaluate or update watchpoint B. Watchpoints on local
1805 expressions need to be evaluated in the context of the thread that
1806 was current when the watchpoint was created, and, that thread needs
1807 to be stopped to be able to select the correct frame context.
1808 Watchpoints on global expressions can be evaluated on any thread,
1809 and in any state. It is presently left to the target allowing
1810 memory accesses when threads are running. */
1812 static int
1813 watchpoint_in_thread_scope (struct watchpoint *b)
1815 return (b->pspace == current_program_space
1816 && (b->watchpoint_thread == null_ptid
1817 || (inferior_ptid == b->watchpoint_thread
1818 && !inferior_thread ()->executing ())));
1821 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1822 associated bp_watchpoint_scope breakpoint. */
1824 static void
1825 watchpoint_del_at_next_stop (struct watchpoint *w)
1827 if (w->related_breakpoint != w)
1829 gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1830 gdb_assert (w->related_breakpoint->related_breakpoint == w);
1831 w->related_breakpoint->disposition = disp_del_at_next_stop;
1832 w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1833 w->related_breakpoint = w;
1835 w->disposition = disp_del_at_next_stop;
1838 /* Extract a bitfield value from value VAL using the bit parameters contained in
1839 watchpoint W. */
1841 static struct value *
1842 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1844 struct value *bit_val;
1846 if (val == NULL)
1847 return NULL;
1849 bit_val = allocate_value (value_type (val));
1851 unpack_value_bitfield (bit_val,
1852 w->val_bitpos,
1853 w->val_bitsize,
1854 value_contents_for_printing (val).data (),
1855 value_offset (val),
1856 val);
1858 return bit_val;
1861 /* Allocate a dummy location and add it to B. This is required
1862 because bpstat_stop_status requires a location to be able to report
1863 stops. */
1865 static void
1866 add_dummy_location (struct breakpoint *b,
1867 struct program_space *pspace)
1869 gdb_assert (b->loc == NULL);
1871 b->loc = new bp_location (b, bp_loc_other);
1872 b->loc->pspace = pspace;
1875 /* Assuming that B is a watchpoint:
1876 - Reparse watchpoint expression, if REPARSE is non-zero
1877 - Evaluate expression and store the result in B->val
1878 - Evaluate the condition if there is one, and store the result
1879 in b->loc->cond.
1880 - Update the list of values that must be watched in B->loc.
1882 If the watchpoint disposition is disp_del_at_next_stop, then do
1883 nothing. If this is local watchpoint that is out of scope, delete
1886 Even with `set breakpoint always-inserted on' the watchpoints are
1887 removed + inserted on each stop here. Normal breakpoints must
1888 never be removed because they might be missed by a running thread
1889 when debugging in non-stop mode. On the other hand, hardware
1890 watchpoints (is_hardware_watchpoint; processed here) are specific
1891 to each LWP since they are stored in each LWP's hardware debug
1892 registers. Therefore, such LWP must be stopped first in order to
1893 be able to modify its hardware watchpoints.
1895 Hardware watchpoints must be reset exactly once after being
1896 presented to the user. It cannot be done sooner, because it would
1897 reset the data used to present the watchpoint hit to the user. And
1898 it must not be done later because it could display the same single
1899 watchpoint hit during multiple GDB stops. Note that the latter is
1900 relevant only to the hardware watchpoint types bp_read_watchpoint
1901 and bp_access_watchpoint. False hit by bp_hardware_watchpoint is
1902 not user-visible - its hit is suppressed if the memory content has
1903 not changed.
1905 The following constraints influence the location where we can reset
1906 hardware watchpoints:
1908 * target_stopped_by_watchpoint and target_stopped_data_address are
1909 called several times when GDB stops.
1911 [linux]
1912 * Multiple hardware watchpoints can be hit at the same time,
1913 causing GDB to stop. GDB only presents one hardware watchpoint
1914 hit at a time as the reason for stopping, and all the other hits
1915 are presented later, one after the other, each time the user
1916 requests the execution to be resumed. Execution is not resumed
1917 for the threads still having pending hit event stored in
1918 LWP_INFO->STATUS. While the watchpoint is already removed from
1919 the inferior on the first stop the thread hit event is kept being
1920 reported from its cached value by linux_nat_stopped_data_address
1921 until the real thread resume happens after the watchpoint gets
1922 presented and thus its LWP_INFO->STATUS gets reset.
1924 Therefore the hardware watchpoint hit can get safely reset on the
1925 watchpoint removal from inferior. */
1927 static void
1928 update_watchpoint (struct watchpoint *b, int reparse)
1930 int within_current_scope;
1931 struct frame_id saved_frame_id;
1932 int frame_saved;
1934 /* If this is a local watchpoint, we only want to check if the
1935 watchpoint frame is in scope if the current thread is the thread
1936 that was used to create the watchpoint. */
1937 if (!watchpoint_in_thread_scope (b))
1938 return;
1940 if (b->disposition == disp_del_at_next_stop)
1941 return;
1943 frame_saved = 0;
1945 /* Determine if the watchpoint is within scope. */
1946 if (b->exp_valid_block == NULL)
1947 within_current_scope = 1;
1948 else
1950 struct frame_info *fi = get_current_frame ();
1951 struct gdbarch *frame_arch = get_frame_arch (fi);
1952 CORE_ADDR frame_pc = get_frame_pc (fi);
1954 /* If we're at a point where the stack has been destroyed
1955 (e.g. in a function epilogue), unwinding may not work
1956 properly. Do not attempt to recreate locations at this
1957 point. See similar comments in watchpoint_check. */
1958 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1959 return;
1961 /* Save the current frame's ID so we can restore it after
1962 evaluating the watchpoint expression on its own frame. */
1963 /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1964 took a frame parameter, so that we didn't have to change the
1965 selected frame. */
1966 frame_saved = 1;
1967 saved_frame_id = get_frame_id (get_selected_frame (NULL));
1969 fi = frame_find_by_id (b->watchpoint_frame);
1970 within_current_scope = (fi != NULL);
1971 if (within_current_scope)
1972 select_frame (fi);
1975 /* We don't free locations. They are stored in the bp_location array
1976 and update_global_location_list will eventually delete them and
1977 remove breakpoints if needed. */
1978 b->loc = NULL;
1980 if (within_current_scope && reparse)
1982 const char *s;
1984 b->exp.reset ();
1985 s = (b->exp_string_reparse
1986 ? b->exp_string_reparse.get ()
1987 : b->exp_string.get ());
1988 b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1989 /* If the meaning of expression itself changed, the old value is
1990 no longer relevant. We don't want to report a watchpoint hit
1991 to the user when the old value and the new value may actually
1992 be completely different objects. */
1993 b->val = NULL;
1994 b->val_valid = false;
1996 /* Note that unlike with breakpoints, the watchpoint's condition
1997 expression is stored in the breakpoint object, not in the
1998 locations (re)created below. */
1999 if (b->cond_string != NULL)
2001 b->cond_exp.reset ();
2003 s = b->cond_string.get ();
2004 b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
2008 /* If we failed to parse the expression, for example because
2009 it refers to a global variable in a not-yet-loaded shared library,
2010 don't try to insert watchpoint. We don't automatically delete
2011 such watchpoint, though, since failure to parse expression
2012 is different from out-of-scope watchpoint. */
2013 if (!target_has_execution ())
2015 /* Without execution, memory can't change. No use to try and
2016 set watchpoint locations. The watchpoint will be reset when
2017 the target gains execution, through breakpoint_re_set. */
2018 if (!can_use_hw_watchpoints)
2020 if (b->works_in_software_mode ())
2021 b->type = bp_watchpoint;
2022 else
2023 error (_("Can't set read/access watchpoint when "
2024 "hardware watchpoints are disabled."));
2027 else if (within_current_scope && b->exp)
2029 std::vector<value_ref_ptr> val_chain;
2030 struct value *v, *result;
2031 struct program_space *frame_pspace;
2033 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
2034 &val_chain, false);
2036 /* Avoid setting b->val if it's already set. The meaning of
2037 b->val is 'the last value' user saw, and we should update
2038 it only if we reported that last value to user. As it
2039 happens, the code that reports it updates b->val directly.
2040 We don't keep track of the memory value for masked
2041 watchpoints. */
2042 if (!b->val_valid && !is_masked_watchpoint (b))
2044 if (b->val_bitsize != 0)
2045 v = extract_bitfield_from_watchpoint_value (b, v);
2046 b->val = release_value (v);
2047 b->val_valid = true;
2050 frame_pspace = get_frame_program_space (get_selected_frame (NULL));
2052 /* Look at each value on the value chain. */
2053 gdb_assert (!val_chain.empty ());
2054 for (const value_ref_ptr &iter : val_chain)
2056 v = iter.get ();
2058 /* If it's a memory location, and GDB actually needed
2059 its contents to evaluate the expression, then we
2060 must watch it. If the first value returned is
2061 still lazy, that means an error occurred reading it;
2062 watch it anyway in case it becomes readable. */
2063 if (VALUE_LVAL (v) == lval_memory
2064 && (v == val_chain[0] || ! value_lazy (v)))
2066 struct type *vtype = check_typedef (value_type (v));
2068 /* We only watch structs and arrays if user asked
2069 for it explicitly, never if they just happen to
2070 appear in the middle of some value chain. */
2071 if (v == result
2072 || (vtype->code () != TYPE_CODE_STRUCT
2073 && vtype->code () != TYPE_CODE_ARRAY))
2075 CORE_ADDR addr;
2076 enum target_hw_bp_type type;
2077 struct bp_location *loc, **tmp;
2078 int bitpos = 0, bitsize = 0;
2080 if (value_bitsize (v) != 0)
2082 /* Extract the bit parameters out from the bitfield
2083 sub-expression. */
2084 bitpos = value_bitpos (v);
2085 bitsize = value_bitsize (v);
2087 else if (v == result && b->val_bitsize != 0)
2089 /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2090 lvalue whose bit parameters are saved in the fields
2091 VAL_BITPOS and VAL_BITSIZE. */
2092 bitpos = b->val_bitpos;
2093 bitsize = b->val_bitsize;
2096 addr = value_address (v);
2097 if (bitsize != 0)
2099 /* Skip the bytes that don't contain the bitfield. */
2100 addr += bitpos / 8;
2103 type = hw_write;
2104 if (b->type == bp_read_watchpoint)
2105 type = hw_read;
2106 else if (b->type == bp_access_watchpoint)
2107 type = hw_access;
2109 loc = b->allocate_location ();
2110 for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
2112 *tmp = loc;
2113 loc->gdbarch = value_type (v)->arch ();
2115 loc->pspace = frame_pspace;
2116 loc->address = address_significant (loc->gdbarch, addr);
2118 if (bitsize != 0)
2120 /* Just cover the bytes that make up the bitfield. */
2121 loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2123 else
2124 loc->length = TYPE_LENGTH (value_type (v));
2126 loc->watchpoint_type = type;
2131 /* Change the type of breakpoint between hardware assisted or
2132 an ordinary watchpoint depending on the hardware support
2133 and free hardware slots. REPARSE is set when the inferior
2134 is started. */
2135 if (reparse)
2137 int reg_cnt;
2138 enum bp_loc_type loc_type;
2140 reg_cnt = can_use_hardware_watchpoint (val_chain);
2142 if (reg_cnt)
2144 int i, target_resources_ok, other_type_used;
2145 enum bptype type;
2147 /* Use an exact watchpoint when there's only one memory region to be
2148 watched, and only one debug register is needed to watch it. */
2149 b->exact = target_exact_watchpoints && reg_cnt == 1;
2151 /* We need to determine how many resources are already
2152 used for all other hardware watchpoints plus this one
2153 to see if we still have enough resources to also fit
2154 this watchpoint in as well. */
2156 /* If this is a software watchpoint, we try to turn it
2157 to a hardware one -- count resources as if B was of
2158 hardware watchpoint type. */
2159 type = b->type;
2160 if (type == bp_watchpoint)
2161 type = bp_hardware_watchpoint;
2163 /* This watchpoint may or may not have been placed on
2164 the list yet at this point (it won't be in the list
2165 if we're trying to create it for the first time,
2166 through watch_command), so always account for it
2167 manually. */
2169 /* Count resources used by all watchpoints except B. */
2170 i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2172 /* Add in the resources needed for B. */
2173 i += hw_watchpoint_use_count (b);
2175 target_resources_ok
2176 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2177 if (target_resources_ok <= 0)
2179 bool sw_mode = b->works_in_software_mode ();
2181 if (target_resources_ok == 0 && !sw_mode)
2182 error (_("Target does not support this type of "
2183 "hardware watchpoint."));
2184 else if (target_resources_ok < 0 && !sw_mode)
2185 error (_("There are not enough available hardware "
2186 "resources for this watchpoint."));
2188 /* Downgrade to software watchpoint. */
2189 b->type = bp_watchpoint;
2191 else
2193 /* If this was a software watchpoint, we've just
2194 found we have enough resources to turn it to a
2195 hardware watchpoint. Otherwise, this is a
2196 nop. */
2197 b->type = type;
2200 else if (!b->works_in_software_mode ())
2202 if (!can_use_hw_watchpoints)
2203 error (_("Can't set read/access watchpoint when "
2204 "hardware watchpoints are disabled."));
2205 else
2206 error (_("Expression cannot be implemented with "
2207 "read/access watchpoint."));
2209 else
2210 b->type = bp_watchpoint;
2212 loc_type = (b->type == bp_watchpoint? bp_loc_software_watchpoint
2213 : bp_loc_hardware_watchpoint);
2214 for (bp_location *bl : b->locations ())
2215 bl->loc_type = loc_type;
2218 /* If a software watchpoint is not watching any memory, then the
2219 above left it without any location set up. But,
2220 bpstat_stop_status requires a location to be able to report
2221 stops, so make sure there's at least a dummy one. */
2222 if (b->type == bp_watchpoint && b->loc == NULL)
2223 add_dummy_location (b, frame_pspace);
2225 else if (!within_current_scope)
2227 gdb_printf (_("\
2228 Watchpoint %d deleted because the program has left the block\n\
2229 in which its expression is valid.\n"),
2230 b->number);
2231 watchpoint_del_at_next_stop (b);
2234 /* Restore the selected frame. */
2235 if (frame_saved)
2236 select_frame (frame_find_by_id (saved_frame_id));
2240 /* Returns 1 iff breakpoint location should be
2241 inserted in the inferior. We don't differentiate the type of BL's owner
2242 (breakpoint vs. tracepoint), although insert_location in tracepoint's
2243 breakpoint_ops is not defined, because in insert_bp_location,
2244 tracepoint's insert_location will not be called. */
2245 static int
2246 should_be_inserted (struct bp_location *bl)
2248 if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2249 return 0;
2251 if (bl->owner->disposition == disp_del_at_next_stop)
2252 return 0;
2254 if (!bl->enabled || bl->disabled_by_cond
2255 || bl->shlib_disabled || bl->duplicate)
2256 return 0;
2258 if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2259 return 0;
2261 /* This is set for example, when we're attached to the parent of a
2262 vfork, and have detached from the child. The child is running
2263 free, and we expect it to do an exec or exit, at which point the
2264 OS makes the parent schedulable again (and the target reports
2265 that the vfork is done). Until the child is done with the shared
2266 memory region, do not insert breakpoints in the parent, otherwise
2267 the child could still trip on the parent's breakpoints. Since
2268 the parent is blocked anyway, it won't miss any breakpoint. */
2269 if (bl->pspace->breakpoints_not_allowed)
2270 return 0;
2272 /* Don't insert a breakpoint if we're trying to step past its
2273 location, except if the breakpoint is a single-step breakpoint,
2274 and the breakpoint's thread is the thread which is stepping past
2275 a breakpoint. */
2276 if ((bl->loc_type == bp_loc_software_breakpoint
2277 || bl->loc_type == bp_loc_hardware_breakpoint)
2278 && stepping_past_instruction_at (bl->pspace->aspace,
2279 bl->address)
2280 /* The single-step breakpoint may be inserted at the location
2281 we're trying to step if the instruction branches to itself.
2282 However, the instruction won't be executed at all and it may
2283 break the semantics of the instruction, for example, the
2284 instruction is a conditional branch or updates some flags.
2285 We can't fix it unless GDB is able to emulate the instruction
2286 or switch to displaced stepping. */
2287 && !(bl->owner->type == bp_single_step
2288 && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2290 infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2291 paddress (bl->gdbarch, bl->address));
2292 return 0;
2295 /* Don't insert watchpoints if we're trying to step past the
2296 instruction that triggered one. */
2297 if ((bl->loc_type == bp_loc_hardware_watchpoint)
2298 && stepping_past_nonsteppable_watchpoint ())
2300 infrun_debug_printf ("stepping past non-steppable watchpoint. "
2301 "skipping watchpoint at %s:%d",
2302 paddress (bl->gdbarch, bl->address), bl->length);
2303 return 0;
2306 return 1;
2309 /* Same as should_be_inserted but does the check assuming
2310 that the location is not duplicated. */
2312 static int
2313 unduplicated_should_be_inserted (struct bp_location *bl)
2315 int result;
2316 const int save_duplicate = bl->duplicate;
2318 bl->duplicate = 0;
2319 result = should_be_inserted (bl);
2320 bl->duplicate = save_duplicate;
2321 return result;
2324 /* Parses a conditional described by an expression COND into an
2325 agent expression bytecode suitable for evaluation
2326 by the bytecode interpreter. Return NULL if there was
2327 any error during parsing. */
2329 static agent_expr_up
2330 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2332 if (cond == NULL)
2333 return NULL;
2335 agent_expr_up aexpr;
2337 /* We don't want to stop processing, so catch any errors
2338 that may show up. */
2341 aexpr = gen_eval_for_expr (scope, cond);
2344 catch (const gdb_exception_error &ex)
2346 /* If we got here, it means the condition could not be parsed to a valid
2347 bytecode expression and thus can't be evaluated on the target's side.
2348 It's no use iterating through the conditions. */
2351 /* We have a valid agent expression. */
2352 return aexpr;
2355 /* Based on location BL, create a list of breakpoint conditions to be
2356 passed on to the target. If we have duplicated locations with different
2357 conditions, we will add such conditions to the list. The idea is that the
2358 target will evaluate the list of conditions and will only notify GDB when
2359 one of them is true. */
2361 static void
2362 build_target_condition_list (struct bp_location *bl)
2364 int null_condition_or_parse_error = 0;
2365 int modified = bl->needs_update;
2367 /* Release conditions left over from a previous insert. */
2368 bl->target_info.conditions.clear ();
2370 /* This is only meaningful if the target is
2371 evaluating conditions and if the user has
2372 opted for condition evaluation on the target's
2373 side. */
2374 if (gdb_evaluates_breakpoint_condition_p ()
2375 || !target_supports_evaluation_of_breakpoint_conditions ())
2376 return;
2378 auto loc_range = all_bp_locations_at_addr (bl->address);
2380 /* Do a first pass to check for locations with no assigned
2381 conditions or conditions that fail to parse to a valid agent
2382 expression bytecode. If any of these happen, then it's no use to
2383 send conditions to the target since this location will always
2384 trigger and generate a response back to GDB. Note we consider
2385 all locations at the same address irrespective of type, i.e.,
2386 even if the locations aren't considered duplicates (e.g.,
2387 software breakpoint and hardware breakpoint at the same
2388 address). */
2389 for (bp_location *loc : loc_range)
2391 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2393 if (modified)
2395 /* Re-parse the conditions since something changed. In that
2396 case we already freed the condition bytecodes (see
2397 force_breakpoint_reinsertion). We just
2398 need to parse the condition to bytecodes again. */
2399 loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2400 loc->cond.get ());
2403 /* If we have a NULL bytecode expression, it means something
2404 went wrong or we have a null condition expression. */
2405 if (!loc->cond_bytecode)
2407 null_condition_or_parse_error = 1;
2408 break;
2413 /* If any of these happened, it means we will have to evaluate the conditions
2414 for the location's address on gdb's side. It is no use keeping bytecodes
2415 for all the other duplicate locations, thus we free all of them here.
2417 This is so we have a finer control over which locations' conditions are
2418 being evaluated by GDB or the remote stub. */
2419 if (null_condition_or_parse_error)
2421 for (bp_location *loc : loc_range)
2423 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2425 /* Only go as far as the first NULL bytecode is
2426 located. */
2427 if (!loc->cond_bytecode)
2428 return;
2430 loc->cond_bytecode.reset ();
2435 /* No NULL conditions or failed bytecode generation. Build a
2436 condition list for this location's address. If we have software
2437 and hardware locations at the same address, they aren't
2438 considered duplicates, but we still marge all the conditions
2439 anyway, as it's simpler, and doesn't really make a practical
2440 difference. */
2441 for (bp_location *loc : loc_range)
2442 if (loc->cond
2443 && is_breakpoint (loc->owner)
2444 && loc->pspace->num == bl->pspace->num
2445 && loc->owner->enable_state == bp_enabled
2446 && loc->enabled
2447 && !loc->disabled_by_cond)
2449 /* Add the condition to the vector. This will be used later
2450 to send the conditions to the target. */
2451 bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2454 return;
2457 /* Parses a command described by string CMD into an agent expression
2458 bytecode suitable for evaluation by the bytecode interpreter.
2459 Return NULL if there was any error during parsing. */
2461 static agent_expr_up
2462 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2464 const char *cmdrest;
2465 const char *format_start, *format_end;
2466 struct gdbarch *gdbarch = get_current_arch ();
2468 if (cmd == NULL)
2469 return NULL;
2471 cmdrest = cmd;
2473 if (*cmdrest == ',')
2474 ++cmdrest;
2475 cmdrest = skip_spaces (cmdrest);
2477 if (*cmdrest++ != '"')
2478 error (_("No format string following the location"));
2480 format_start = cmdrest;
2482 format_pieces fpieces (&cmdrest);
2484 format_end = cmdrest;
2486 if (*cmdrest++ != '"')
2487 error (_("Bad format string, non-terminated '\"'."));
2489 cmdrest = skip_spaces (cmdrest);
2491 if (!(*cmdrest == ',' || *cmdrest == '\0'))
2492 error (_("Invalid argument syntax"));
2494 if (*cmdrest == ',')
2495 cmdrest++;
2496 cmdrest = skip_spaces (cmdrest);
2498 /* For each argument, make an expression. */
2500 std::vector<struct expression *> argvec;
2501 while (*cmdrest != '\0')
2503 const char *cmd1;
2505 cmd1 = cmdrest;
2506 expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2507 argvec.push_back (expr.release ());
2508 cmdrest = cmd1;
2509 if (*cmdrest == ',')
2510 ++cmdrest;
2513 agent_expr_up aexpr;
2515 /* We don't want to stop processing, so catch any errors
2516 that may show up. */
2519 aexpr = gen_printf (scope, gdbarch, 0, 0,
2520 format_start, format_end - format_start,
2521 argvec.size (), argvec.data ());
2523 catch (const gdb_exception_error &ex)
2525 /* If we got here, it means the command could not be parsed to a valid
2526 bytecode expression and thus can't be evaluated on the target's side.
2527 It's no use iterating through the other commands. */
2530 /* We have a valid agent expression, return it. */
2531 return aexpr;
2534 /* Based on location BL, create a list of breakpoint commands to be
2535 passed on to the target. If we have duplicated locations with
2536 different commands, we will add any such to the list. */
2538 static void
2539 build_target_command_list (struct bp_location *bl)
2541 int null_command_or_parse_error = 0;
2542 int modified = bl->needs_update;
2544 /* Clear commands left over from a previous insert. */
2545 bl->target_info.tcommands.clear ();
2547 if (!target_can_run_breakpoint_commands ())
2548 return;
2550 /* For now, limit to agent-style dprintf breakpoints. */
2551 if (dprintf_style != dprintf_style_agent)
2552 return;
2554 auto loc_range = all_bp_locations_at_addr (bl->address);
2556 /* For now, if we have any location at the same address that isn't a
2557 dprintf, don't install the target-side commands, as that would
2558 make the breakpoint not be reported to the core, and we'd lose
2559 control. */
2560 for (bp_location *loc : loc_range)
2561 if (is_breakpoint (loc->owner)
2562 && loc->pspace->num == bl->pspace->num
2563 && loc->owner->type != bp_dprintf)
2564 return;
2566 /* Do a first pass to check for locations with no assigned
2567 conditions or conditions that fail to parse to a valid agent expression
2568 bytecode. If any of these happen, then it's no use to send conditions
2569 to the target since this location will always trigger and generate a
2570 response back to GDB. */
2571 for (bp_location *loc : loc_range)
2573 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2575 if (modified)
2577 /* Re-parse the commands since something changed. In that
2578 case we already freed the command bytecodes (see
2579 force_breakpoint_reinsertion). We just
2580 need to parse the command to bytecodes again. */
2581 loc->cmd_bytecode
2582 = parse_cmd_to_aexpr (bl->address,
2583 loc->owner->extra_string.get ());
2586 /* If we have a NULL bytecode expression, it means something
2587 went wrong or we have a null command expression. */
2588 if (!loc->cmd_bytecode)
2590 null_command_or_parse_error = 1;
2591 break;
2596 /* If anything failed, then we're not doing target-side commands,
2597 and so clean up. */
2598 if (null_command_or_parse_error)
2600 for (bp_location *loc : loc_range)
2601 if (is_breakpoint (loc->owner)
2602 && loc->pspace->num == bl->pspace->num)
2604 /* Only go as far as the first NULL bytecode is
2605 located. */
2606 if (loc->cmd_bytecode == NULL)
2607 return;
2609 loc->cmd_bytecode.reset ();
2613 /* No NULL commands or failed bytecode generation. Build a command
2614 list for all duplicate locations at this location's address.
2615 Note that here we must care for whether the breakpoint location
2616 types are considered duplicates, otherwise, say, if we have a
2617 software and hardware location at the same address, the target
2618 could end up running the commands twice. For the moment, we only
2619 support targets-side commands with dprintf, but it doesn't hurt
2620 to be pedantically correct in case that changes. */
2621 for (bp_location *loc : loc_range)
2622 if (breakpoint_locations_match (bl, loc)
2623 && loc->owner->extra_string
2624 && is_breakpoint (loc->owner)
2625 && loc->pspace->num == bl->pspace->num
2626 && loc->owner->enable_state == bp_enabled
2627 && loc->enabled
2628 && !loc->disabled_by_cond)
2630 /* Add the command to the vector. This will be used later
2631 to send the commands to the target. */
2632 bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2635 bl->target_info.persist = 0;
2636 /* Maybe flag this location as persistent. */
2637 if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2638 bl->target_info.persist = 1;
2641 /* Return the kind of breakpoint on address *ADDR. Get the kind
2642 of breakpoint according to ADDR except single-step breakpoint.
2643 Get the kind of single-step breakpoint according to the current
2644 registers state. */
2646 static int
2647 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2649 if (bl->owner->type == bp_single_step)
2651 struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2652 struct regcache *regcache;
2654 regcache = get_thread_regcache (thr);
2656 return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2657 regcache, addr);
2659 else
2660 return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2663 /* Insert a low-level "breakpoint" of some type. BL is the breakpoint
2664 location. Any error messages are printed to TMP_ERROR_STREAM; and
2665 DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2666 Returns 0 for success, 1 if the bp_location type is not supported or
2667 -1 for failure.
2669 NOTE drow/2003-09-09: This routine could be broken down to an
2670 object-style method for each breakpoint or catchpoint type. */
2671 static int
2672 insert_bp_location (struct bp_location *bl,
2673 struct ui_file *tmp_error_stream,
2674 int *disabled_breaks,
2675 int *hw_breakpoint_error,
2676 int *hw_bp_error_explained_already)
2678 gdb_exception bp_excpt;
2680 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2681 return 0;
2683 /* Note we don't initialize bl->target_info, as that wipes out
2684 the breakpoint location's shadow_contents if the breakpoint
2685 is still inserted at that location. This in turn breaks
2686 target_read_memory which depends on these buffers when
2687 a memory read is requested at the breakpoint location:
2688 Once the target_info has been wiped, we fail to see that
2689 we have a breakpoint inserted at that address and thus
2690 read the breakpoint instead of returning the data saved in
2691 the breakpoint location's shadow contents. */
2692 bl->target_info.reqstd_address = bl->address;
2693 bl->target_info.placed_address_space = bl->pspace->aspace;
2694 bl->target_info.length = bl->length;
2696 /* When working with target-side conditions, we must pass all the conditions
2697 for the same breakpoint address down to the target since GDB will not
2698 insert those locations. With a list of breakpoint conditions, the target
2699 can decide when to stop and notify GDB. */
2701 if (is_breakpoint (bl->owner))
2703 build_target_condition_list (bl);
2704 build_target_command_list (bl);
2705 /* Reset the modification marker. */
2706 bl->needs_update = 0;
2709 /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2710 set at a read-only address, then a breakpoint location will have
2711 been changed to hardware breakpoint before we get here. If it is
2712 "off" however, error out before actually trying to insert the
2713 breakpoint, with a nicer error message. */
2714 if (bl->loc_type == bp_loc_software_breakpoint
2715 && !automatic_hardware_breakpoints)
2717 mem_region *mr = lookup_mem_region (bl->address);
2719 if (mr != nullptr && mr->attrib.mode != MEM_RW)
2721 gdb_printf (tmp_error_stream,
2722 _("Cannot insert breakpoint %d.\n"
2723 "Cannot set software breakpoint "
2724 "at read-only address %s\n"),
2725 bl->owner->number,
2726 paddress (bl->gdbarch, bl->address));
2727 return 1;
2731 if (bl->loc_type == bp_loc_software_breakpoint
2732 || bl->loc_type == bp_loc_hardware_breakpoint)
2734 /* First check to see if we have to handle an overlay. */
2735 if (overlay_debugging == ovly_off
2736 || bl->section == NULL
2737 || !(section_is_overlay (bl->section)))
2739 /* No overlay handling: just set the breakpoint. */
2742 int val;
2744 val = bl->owner->insert_location (bl);
2745 if (val)
2746 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2748 catch (gdb_exception &e)
2750 bp_excpt = std::move (e);
2753 else
2755 /* This breakpoint is in an overlay section.
2756 Shall we set a breakpoint at the LMA? */
2757 if (!overlay_events_enabled)
2759 /* Yes -- overlay event support is not active,
2760 so we must try to set a breakpoint at the LMA.
2761 This will not work for a hardware breakpoint. */
2762 if (bl->loc_type == bp_loc_hardware_breakpoint)
2763 warning (_("hardware breakpoint %d not supported in overlay!"),
2764 bl->owner->number);
2765 else
2767 CORE_ADDR addr = overlay_unmapped_address (bl->address,
2768 bl->section);
2769 /* Set a software (trap) breakpoint at the LMA. */
2770 bl->overlay_target_info = bl->target_info;
2771 bl->overlay_target_info.reqstd_address = addr;
2773 /* No overlay handling: just set the breakpoint. */
2776 int val;
2778 bl->overlay_target_info.kind
2779 = breakpoint_kind (bl, &addr);
2780 bl->overlay_target_info.placed_address = addr;
2781 val = target_insert_breakpoint (bl->gdbarch,
2782 &bl->overlay_target_info);
2783 if (val)
2784 bp_excpt
2785 = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2787 catch (gdb_exception &e)
2789 bp_excpt = std::move (e);
2792 if (bp_excpt.reason != 0)
2793 gdb_printf (tmp_error_stream,
2794 "Overlay breakpoint %d "
2795 "failed: in ROM?\n",
2796 bl->owner->number);
2799 /* Shall we set a breakpoint at the VMA? */
2800 if (section_is_mapped (bl->section))
2802 /* Yes. This overlay section is mapped into memory. */
2805 int val;
2807 val = bl->owner->insert_location (bl);
2808 if (val)
2809 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2811 catch (gdb_exception &e)
2813 bp_excpt = std::move (e);
2816 else
2818 /* No. This breakpoint will not be inserted.
2819 No error, but do not mark the bp as 'inserted'. */
2820 return 0;
2824 if (bp_excpt.reason != 0)
2826 /* Can't set the breakpoint. */
2828 /* If the target has closed then it will have deleted any
2829 breakpoints inserted within the target inferior, as a result
2830 any further attempts to interact with the breakpoint objects
2831 is not possible. Just rethrow the error. */
2832 if (bp_excpt.error == TARGET_CLOSE_ERROR)
2833 throw bp_excpt;
2834 gdb_assert (bl->owner != nullptr);
2836 /* In some cases, we might not be able to insert a
2837 breakpoint in a shared library that has already been
2838 removed, but we have not yet processed the shlib unload
2839 event. Unfortunately, some targets that implement
2840 breakpoint insertion themselves can't tell why the
2841 breakpoint insertion failed (e.g., the remote target
2842 doesn't define error codes), so we must treat generic
2843 errors as memory errors. */
2844 if (bp_excpt.reason == RETURN_ERROR
2845 && (bp_excpt.error == GENERIC_ERROR
2846 || bp_excpt.error == MEMORY_ERROR)
2847 && bl->loc_type == bp_loc_software_breakpoint
2848 && (solib_name_from_address (bl->pspace, bl->address)
2849 || shared_objfile_contains_address_p (bl->pspace,
2850 bl->address)))
2852 /* See also: disable_breakpoints_in_shlibs. */
2853 bl->shlib_disabled = 1;
2854 gdb::observers::breakpoint_modified.notify (bl->owner);
2855 if (!*disabled_breaks)
2857 gdb_printf (tmp_error_stream,
2858 "Cannot insert breakpoint %d.\n",
2859 bl->owner->number);
2860 gdb_printf (tmp_error_stream,
2861 "Temporarily disabling shared "
2862 "library breakpoints:\n");
2864 *disabled_breaks = 1;
2865 gdb_printf (tmp_error_stream,
2866 "breakpoint #%d\n", bl->owner->number);
2867 return 0;
2869 else
2871 if (bl->loc_type == bp_loc_hardware_breakpoint)
2873 *hw_breakpoint_error = 1;
2874 *hw_bp_error_explained_already = bp_excpt.message != NULL;
2875 gdb_printf (tmp_error_stream,
2876 "Cannot insert hardware breakpoint %d%s",
2877 bl->owner->number,
2878 bp_excpt.message ? ":" : ".\n");
2879 if (bp_excpt.message != NULL)
2880 gdb_printf (tmp_error_stream, "%s.\n",
2881 bp_excpt.what ());
2883 else
2885 if (bp_excpt.message == NULL)
2887 std::string message
2888 = memory_error_message (TARGET_XFER_E_IO,
2889 bl->gdbarch, bl->address);
2891 gdb_printf (tmp_error_stream,
2892 "Cannot insert breakpoint %d.\n"
2893 "%s\n",
2894 bl->owner->number, message.c_str ());
2896 else
2898 gdb_printf (tmp_error_stream,
2899 "Cannot insert breakpoint %d: %s\n",
2900 bl->owner->number,
2901 bp_excpt.what ());
2904 return 1;
2908 else
2909 bl->inserted = 1;
2911 return 0;
2914 else if (bl->loc_type == bp_loc_hardware_watchpoint
2915 /* NOTE drow/2003-09-08: This state only exists for removing
2916 watchpoints. It's not clear that it's necessary... */
2917 && bl->owner->disposition != disp_del_at_next_stop)
2919 int val;
2921 val = bl->owner->insert_location (bl);
2923 /* If trying to set a read-watchpoint, and it turns out it's not
2924 supported, try emulating one with an access watchpoint. */
2925 if (val == 1 && bl->watchpoint_type == hw_read)
2927 /* But don't try to insert it, if there's already another
2928 hw_access location that would be considered a duplicate
2929 of this one. */
2930 for (bp_location *loc : all_bp_locations ())
2931 if (loc != bl
2932 && loc->watchpoint_type == hw_access
2933 && watchpoint_locations_match (bl, loc))
2935 bl->duplicate = 1;
2936 bl->inserted = 1;
2937 bl->target_info = loc->target_info;
2938 bl->watchpoint_type = hw_access;
2939 val = 0;
2940 break;
2943 if (val == 1)
2945 bl->watchpoint_type = hw_access;
2946 val = bl->owner->insert_location (bl);
2948 if (val)
2949 /* Back to the original value. */
2950 bl->watchpoint_type = hw_read;
2954 bl->inserted = (val == 0);
2957 else if (bl->owner->type == bp_catchpoint)
2959 int val;
2961 val = bl->owner->insert_location (bl);
2962 if (val)
2964 bl->owner->enable_state = bp_disabled;
2966 if (val == 1)
2967 warning (_("\
2968 Error inserting catchpoint %d: Your system does not support this type\n\
2969 of catchpoint."), bl->owner->number);
2970 else
2971 warning (_("Error inserting catchpoint %d."), bl->owner->number);
2974 bl->inserted = (val == 0);
2976 /* We've already printed an error message if there was a problem
2977 inserting this catchpoint, and we've disabled the catchpoint,
2978 so just return success. */
2979 return 0;
2982 return 0;
2985 /* This function is called when program space PSPACE is about to be
2986 deleted. It takes care of updating breakpoints to not reference
2987 PSPACE anymore. */
2989 void
2990 breakpoint_program_space_exit (struct program_space *pspace)
2992 /* Remove any breakpoint that was set through this program space. */
2993 for (breakpoint *b : all_breakpoints_safe ())
2994 if (b->pspace == pspace)
2995 delete_breakpoint (b);
2997 /* Breakpoints set through other program spaces could have locations
2998 bound to PSPACE as well. Remove those. */
2999 for (bp_location *loc : all_bp_locations ())
3001 struct bp_location *tmp;
3003 if (loc->pspace == pspace)
3005 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
3006 if (loc->owner->loc == loc)
3007 loc->owner->loc = loc->next;
3008 else
3009 for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
3010 if (tmp->next == loc)
3012 tmp->next = loc->next;
3013 break;
3018 /* Now update the global location list to permanently delete the
3019 removed locations above. */
3020 update_global_location_list (UGLL_DONT_INSERT);
3023 /* Make sure all breakpoints are inserted in inferior.
3024 Throws exception on any error.
3025 A breakpoint that is already inserted won't be inserted
3026 again, so calling this function twice is safe. */
3027 void
3028 insert_breakpoints (void)
3030 for (breakpoint *bpt : all_breakpoints ())
3031 if (is_hardware_watchpoint (bpt))
3033 struct watchpoint *w = (struct watchpoint *) bpt;
3035 update_watchpoint (w, 0 /* don't reparse. */);
3038 /* Updating watchpoints creates new locations, so update the global
3039 location list. Explicitly tell ugll to insert locations and
3040 ignore breakpoints_always_inserted_mode. Also,
3041 update_global_location_list tries to "upgrade" software
3042 breakpoints to hardware breakpoints to handle "set breakpoint
3043 auto-hw", so we need to call it even if we don't have new
3044 locations. */
3045 update_global_location_list (UGLL_INSERT);
3048 /* This is used when we need to synch breakpoint conditions between GDB and the
3049 target. It is the case with deleting and disabling of breakpoints when using
3050 always-inserted mode. */
3052 static void
3053 update_inserted_breakpoint_locations (void)
3055 int error_flag = 0;
3056 int val = 0;
3057 int disabled_breaks = 0;
3058 int hw_breakpoint_error = 0;
3059 int hw_bp_details_reported = 0;
3061 string_file tmp_error_stream;
3063 /* Explicitly mark the warning -- this will only be printed if
3064 there was an error. */
3065 tmp_error_stream.puts ("Warning:\n");
3067 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3069 for (bp_location *bl : all_bp_locations ())
3071 /* We only want to update software breakpoints and hardware
3072 breakpoints. */
3073 if (!is_breakpoint (bl->owner))
3074 continue;
3076 /* We only want to update locations that are already inserted
3077 and need updating. This is to avoid unwanted insertion during
3078 deletion of breakpoints. */
3079 if (!bl->inserted || !bl->needs_update)
3080 continue;
3082 switch_to_program_space_and_thread (bl->pspace);
3084 /* For targets that support global breakpoints, there's no need
3085 to select an inferior to insert breakpoint to. In fact, even
3086 if we aren't attached to any process yet, we should still
3087 insert breakpoints. */
3088 if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3089 && (inferior_ptid == null_ptid || !target_has_execution ()))
3090 continue;
3092 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3093 &hw_breakpoint_error, &hw_bp_details_reported);
3094 if (val)
3095 error_flag = val;
3098 if (error_flag)
3100 target_terminal::ours_for_output ();
3101 error_stream (tmp_error_stream);
3105 /* Used when starting or continuing the program. */
3107 static void
3108 insert_breakpoint_locations (void)
3110 int error_flag = 0;
3111 int val = 0;
3112 int disabled_breaks = 0;
3113 int hw_breakpoint_error = 0;
3114 int hw_bp_error_explained_already = 0;
3116 string_file tmp_error_stream;
3118 /* Explicitly mark the warning -- this will only be printed if
3119 there was an error. */
3120 tmp_error_stream.puts ("Warning:\n");
3122 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3124 for (bp_location *bl : all_bp_locations ())
3126 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3127 continue;
3129 /* There is no point inserting thread-specific breakpoints if
3130 the thread no longer exists. ALL_BP_LOCATIONS bp_location
3131 has BL->OWNER always non-NULL. */
3132 if (bl->owner->thread != -1
3133 && !valid_global_thread_id (bl->owner->thread))
3134 continue;
3136 switch_to_program_space_and_thread (bl->pspace);
3138 /* For targets that support global breakpoints, there's no need
3139 to select an inferior to insert breakpoint to. In fact, even
3140 if we aren't attached to any process yet, we should still
3141 insert breakpoints. */
3142 if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3143 && (inferior_ptid == null_ptid || !target_has_execution ()))
3144 continue;
3146 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3147 &hw_breakpoint_error, &hw_bp_error_explained_already);
3148 if (val)
3149 error_flag = val;
3152 /* If we failed to insert all locations of a watchpoint, remove
3153 them, as half-inserted watchpoint is of limited use. */
3154 for (breakpoint *bpt : all_breakpoints ())
3156 int some_failed = 0;
3158 if (!is_hardware_watchpoint (bpt))
3159 continue;
3161 if (!breakpoint_enabled (bpt))
3162 continue;
3164 if (bpt->disposition == disp_del_at_next_stop)
3165 continue;
3167 for (bp_location *loc : bpt->locations ())
3168 if (!loc->inserted && should_be_inserted (loc))
3170 some_failed = 1;
3171 break;
3174 if (some_failed)
3176 for (bp_location *loc : bpt->locations ())
3177 if (loc->inserted)
3178 remove_breakpoint (loc);
3180 hw_breakpoint_error = 1;
3181 tmp_error_stream.printf ("Could not insert "
3182 "hardware watchpoint %d.\n",
3183 bpt->number);
3184 error_flag = -1;
3188 if (error_flag)
3190 /* If a hardware breakpoint or watchpoint was inserted, add a
3191 message about possibly exhausted resources. */
3192 if (hw_breakpoint_error && !hw_bp_error_explained_already)
3194 tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3195 You may have requested too many hardware breakpoints/watchpoints.\n");
3197 target_terminal::ours_for_output ();
3198 error_stream (tmp_error_stream);
3202 /* Used when the program stops.
3203 Returns zero if successful, or non-zero if there was a problem
3204 removing a breakpoint location. */
3207 remove_breakpoints (void)
3209 int val = 0;
3211 for (bp_location *bl : all_bp_locations ())
3212 if (bl->inserted && !is_tracepoint (bl->owner))
3213 val |= remove_breakpoint (bl);
3215 return val;
3218 /* When a thread exits, remove breakpoints that are related to
3219 that thread. */
3221 static void
3222 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3224 for (breakpoint *b : all_breakpoints_safe ())
3226 if (b->thread == tp->global_num && user_breakpoint_p (b))
3228 b->disposition = disp_del_at_next_stop;
3230 gdb_printf (_("\
3231 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3232 b->number, print_thread_id (tp));
3234 /* Hide it from the user. */
3235 b->number = 0;
3240 /* See breakpoint.h. */
3242 void
3243 remove_breakpoints_inf (inferior *inf)
3245 int val;
3247 for (bp_location *bl : all_bp_locations ())
3249 if (bl->pspace != inf->pspace)
3250 continue;
3252 if (bl->inserted && !bl->target_info.persist)
3254 val = remove_breakpoint (bl);
3255 if (val != 0)
3256 return;
3261 static int internal_breakpoint_number = -1;
3263 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3264 If INTERNAL is non-zero, the breakpoint number will be populated
3265 from internal_breakpoint_number and that variable decremented.
3266 Otherwise the breakpoint number will be populated from
3267 breakpoint_count and that value incremented. Internal breakpoints
3268 do not set the internal var bpnum. */
3269 static void
3270 set_breakpoint_number (int internal, struct breakpoint *b)
3272 if (internal)
3273 b->number = internal_breakpoint_number--;
3274 else
3276 set_breakpoint_count (breakpoint_count + 1);
3277 b->number = breakpoint_count;
3281 static struct breakpoint *
3282 create_internal_breakpoint (struct gdbarch *gdbarch,
3283 CORE_ADDR address, enum bptype type)
3285 std::unique_ptr<internal_breakpoint> b
3286 (new internal_breakpoint (gdbarch, type, address));
3288 b->number = internal_breakpoint_number--;
3290 return add_to_breakpoint_chain (std::move (b));
3293 static const char *const longjmp_names[] =
3295 "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3297 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3299 /* Per-objfile data private to breakpoint.c. */
3300 struct breakpoint_objfile_data
3302 /* Minimal symbol for "_ovly_debug_event" (if any). */
3303 struct bound_minimal_symbol overlay_msym;
3305 /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any). */
3306 struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3308 /* True if we have looked for longjmp probes. */
3309 int longjmp_searched = 0;
3311 /* SystemTap probe points for longjmp (if any). These are non-owning
3312 references. */
3313 std::vector<probe *> longjmp_probes;
3315 /* Minimal symbol for "std::terminate()" (if any). */
3316 struct bound_minimal_symbol terminate_msym;
3318 /* Minimal symbol for "_Unwind_DebugHook" (if any). */
3319 struct bound_minimal_symbol exception_msym;
3321 /* True if we have looked for exception probes. */
3322 int exception_searched = 0;
3324 /* SystemTap probe points for unwinding (if any). These are non-owning
3325 references. */
3326 std::vector<probe *> exception_probes;
3329 static const struct objfile_key<breakpoint_objfile_data>
3330 breakpoint_objfile_key;
3332 /* Minimal symbol not found sentinel. */
3333 static struct minimal_symbol msym_not_found;
3335 /* Returns TRUE if MSYM point to the "not found" sentinel. */
3337 static int
3338 msym_not_found_p (const struct minimal_symbol *msym)
3340 return msym == &msym_not_found;
3343 /* Return per-objfile data needed by breakpoint.c.
3344 Allocate the data if necessary. */
3346 static struct breakpoint_objfile_data *
3347 get_breakpoint_objfile_data (struct objfile *objfile)
3349 struct breakpoint_objfile_data *bp_objfile_data;
3351 bp_objfile_data = breakpoint_objfile_key.get (objfile);
3352 if (bp_objfile_data == NULL)
3353 bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3354 return bp_objfile_data;
3357 static void
3358 create_overlay_event_breakpoint (void)
3360 const char *const func_name = "_ovly_debug_event";
3362 for (objfile *objfile : current_program_space->objfiles ())
3364 struct breakpoint *b;
3365 struct breakpoint_objfile_data *bp_objfile_data;
3366 CORE_ADDR addr;
3368 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3370 if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3371 continue;
3373 if (bp_objfile_data->overlay_msym.minsym == NULL)
3375 struct bound_minimal_symbol m;
3377 m = lookup_minimal_symbol_text (func_name, objfile);
3378 if (m.minsym == NULL)
3380 /* Avoid future lookups in this objfile. */
3381 bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3382 continue;
3384 bp_objfile_data->overlay_msym = m;
3387 addr = bp_objfile_data->overlay_msym.value_address ();
3388 b = create_internal_breakpoint (objfile->arch (), addr,
3389 bp_overlay_event);
3390 b->locspec = new_explicit_location_spec_function (func_name);
3392 if (overlay_debugging == ovly_auto)
3394 b->enable_state = bp_enabled;
3395 overlay_events_enabled = 1;
3397 else
3399 b->enable_state = bp_disabled;
3400 overlay_events_enabled = 0;
3405 /* Install a master longjmp breakpoint for OBJFILE using a probe. Return
3406 true if a breakpoint was installed. */
3408 static bool
3409 create_longjmp_master_breakpoint_probe (objfile *objfile)
3411 struct gdbarch *gdbarch = objfile->arch ();
3412 struct breakpoint_objfile_data *bp_objfile_data
3413 = get_breakpoint_objfile_data (objfile);
3415 if (!bp_objfile_data->longjmp_searched)
3417 std::vector<probe *> ret
3418 = find_probes_in_objfile (objfile, "libc", "longjmp");
3420 if (!ret.empty ())
3422 /* We are only interested in checking one element. */
3423 probe *p = ret[0];
3425 if (!p->can_evaluate_arguments ())
3427 /* We cannot use the probe interface here,
3428 because it does not know how to evaluate
3429 arguments. */
3430 ret.clear ();
3433 bp_objfile_data->longjmp_probes = ret;
3434 bp_objfile_data->longjmp_searched = 1;
3437 if (bp_objfile_data->longjmp_probes.empty ())
3438 return false;
3440 for (probe *p : bp_objfile_data->longjmp_probes)
3442 struct breakpoint *b;
3444 b = create_internal_breakpoint (gdbarch,
3445 p->get_relocated_address (objfile),
3446 bp_longjmp_master);
3447 b->locspec = new_probe_location_spec ("-probe-stap libc:longjmp");
3448 b->enable_state = bp_disabled;
3451 return true;
3454 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3455 Return true if at least one breakpoint was installed. */
3457 static bool
3458 create_longjmp_master_breakpoint_names (objfile *objfile)
3460 struct gdbarch *gdbarch = objfile->arch ();
3461 if (!gdbarch_get_longjmp_target_p (gdbarch))
3462 return false;
3464 struct breakpoint_objfile_data *bp_objfile_data
3465 = get_breakpoint_objfile_data (objfile);
3466 unsigned int installed_bp = 0;
3468 for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3470 struct breakpoint *b;
3471 const char *func_name;
3472 CORE_ADDR addr;
3474 if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3475 continue;
3477 func_name = longjmp_names[i];
3478 if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3480 struct bound_minimal_symbol m;
3482 m = lookup_minimal_symbol_text (func_name, objfile);
3483 if (m.minsym == NULL)
3485 /* Prevent future lookups in this objfile. */
3486 bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3487 continue;
3489 bp_objfile_data->longjmp_msym[i] = m;
3492 addr = bp_objfile_data->longjmp_msym[i].value_address ();
3493 b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master);
3494 b->locspec = new_explicit_location_spec_function (func_name);
3495 b->enable_state = bp_disabled;
3496 installed_bp++;
3499 return installed_bp > 0;
3502 /* Create a master longjmp breakpoint. */
3504 static void
3505 create_longjmp_master_breakpoint (void)
3507 scoped_restore_current_program_space restore_pspace;
3509 for (struct program_space *pspace : program_spaces)
3511 set_current_program_space (pspace);
3513 for (objfile *obj : current_program_space->objfiles ())
3515 /* Skip separate debug object, it's handled in the loop below. */
3516 if (obj->separate_debug_objfile_backlink != nullptr)
3517 continue;
3519 /* Try a probe kind breakpoint on main objfile. */
3520 if (create_longjmp_master_breakpoint_probe (obj))
3521 continue;
3523 /* Try longjmp_names kind breakpoints on main and separate_debug
3524 objfiles. */
3525 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3526 if (create_longjmp_master_breakpoint_names (debug_objfile))
3527 break;
3532 /* Create a master std::terminate breakpoint. */
3533 static void
3534 create_std_terminate_master_breakpoint (void)
3536 const char *const func_name = "std::terminate()";
3538 scoped_restore_current_program_space restore_pspace;
3540 for (struct program_space *pspace : program_spaces)
3542 CORE_ADDR addr;
3544 set_current_program_space (pspace);
3546 for (objfile *objfile : current_program_space->objfiles ())
3548 struct breakpoint *b;
3549 struct breakpoint_objfile_data *bp_objfile_data;
3551 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3553 if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3554 continue;
3556 if (bp_objfile_data->terminate_msym.minsym == NULL)
3558 struct bound_minimal_symbol m;
3560 m = lookup_minimal_symbol (func_name, NULL, objfile);
3561 if (m.minsym == NULL || (m.minsym->type () != mst_text
3562 && m.minsym->type () != mst_file_text))
3564 /* Prevent future lookups in this objfile. */
3565 bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3566 continue;
3568 bp_objfile_data->terminate_msym = m;
3571 addr = bp_objfile_data->terminate_msym.value_address ();
3572 b = create_internal_breakpoint (objfile->arch (), addr,
3573 bp_std_terminate_master);
3574 b->locspec = new_explicit_location_spec_function (func_name);
3575 b->enable_state = bp_disabled;
3580 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3581 probe. Return true if a breakpoint was installed. */
3583 static bool
3584 create_exception_master_breakpoint_probe (objfile *objfile)
3586 struct breakpoint *b;
3587 struct gdbarch *gdbarch;
3588 struct breakpoint_objfile_data *bp_objfile_data;
3590 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3592 /* We prefer the SystemTap probe point if it exists. */
3593 if (!bp_objfile_data->exception_searched)
3595 std::vector<probe *> ret
3596 = find_probes_in_objfile (objfile, "libgcc", "unwind");
3598 if (!ret.empty ())
3600 /* We are only interested in checking one element. */
3601 probe *p = ret[0];
3603 if (!p->can_evaluate_arguments ())
3605 /* We cannot use the probe interface here, because it does
3606 not know how to evaluate arguments. */
3607 ret.clear ();
3610 bp_objfile_data->exception_probes = ret;
3611 bp_objfile_data->exception_searched = 1;
3614 if (bp_objfile_data->exception_probes.empty ())
3615 return false;
3617 gdbarch = objfile->arch ();
3619 for (probe *p : bp_objfile_data->exception_probes)
3621 b = create_internal_breakpoint (gdbarch,
3622 p->get_relocated_address (objfile),
3623 bp_exception_master);
3624 b->locspec = new_probe_location_spec ("-probe-stap libgcc:unwind");
3625 b->enable_state = bp_disabled;
3628 return true;
3631 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3632 _Unwind_DebugHook. Return true if a breakpoint was installed. */
3634 static bool
3635 create_exception_master_breakpoint_hook (objfile *objfile)
3637 const char *const func_name = "_Unwind_DebugHook";
3638 struct breakpoint *b;
3639 struct gdbarch *gdbarch;
3640 struct breakpoint_objfile_data *bp_objfile_data;
3641 CORE_ADDR addr;
3643 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3645 if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3646 return false;
3648 gdbarch = objfile->arch ();
3650 if (bp_objfile_data->exception_msym.minsym == NULL)
3652 struct bound_minimal_symbol debug_hook;
3654 debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3655 if (debug_hook.minsym == NULL)
3657 bp_objfile_data->exception_msym.minsym = &msym_not_found;
3658 return false;
3661 bp_objfile_data->exception_msym = debug_hook;
3664 addr = bp_objfile_data->exception_msym.value_address ();
3665 addr = gdbarch_convert_from_func_ptr_addr
3666 (gdbarch, addr, current_inferior ()->top_target ());
3667 b = create_internal_breakpoint (gdbarch, addr, bp_exception_master);
3668 b->locspec = new_explicit_location_spec_function (func_name);
3669 b->enable_state = bp_disabled;
3671 return true;
3674 /* Install a master breakpoint on the unwinder's debug hook. */
3676 static void
3677 create_exception_master_breakpoint (void)
3679 for (objfile *obj : current_program_space->objfiles ())
3681 /* Skip separate debug object. */
3682 if (obj->separate_debug_objfile_backlink)
3683 continue;
3685 /* Try a probe kind breakpoint. */
3686 if (create_exception_master_breakpoint_probe (obj))
3687 continue;
3689 /* Iterate over main and separate debug objects and try an
3690 _Unwind_DebugHook kind breakpoint. */
3691 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3692 if (create_exception_master_breakpoint_hook (debug_objfile))
3693 break;
3697 /* Does B have a location spec? */
3699 static int
3700 breakpoint_location_spec_empty_p (const struct breakpoint *b)
3702 return (b->locspec != nullptr && b->locspec->empty_p ());
3705 void
3706 update_breakpoints_after_exec (void)
3708 /* We're about to delete breakpoints from GDB's lists. If the
3709 INSERTED flag is true, GDB will try to lift the breakpoints by
3710 writing the breakpoints' "shadow contents" back into memory. The
3711 "shadow contents" are NOT valid after an exec, so GDB should not
3712 do that. Instead, the target is responsible from marking
3713 breakpoints out as soon as it detects an exec. We don't do that
3714 here instead, because there may be other attempts to delete
3715 breakpoints after detecting an exec and before reaching here. */
3716 for (bp_location *bploc : all_bp_locations ())
3717 if (bploc->pspace == current_program_space)
3718 gdb_assert (!bploc->inserted);
3720 for (breakpoint *b : all_breakpoints_safe ())
3722 if (b->pspace != current_program_space)
3723 continue;
3725 /* Solib breakpoints must be explicitly reset after an exec(). */
3726 if (b->type == bp_shlib_event)
3728 delete_breakpoint (b);
3729 continue;
3732 /* JIT breakpoints must be explicitly reset after an exec(). */
3733 if (b->type == bp_jit_event)
3735 delete_breakpoint (b);
3736 continue;
3739 /* Thread event breakpoints must be set anew after an exec(),
3740 as must overlay event and longjmp master breakpoints. */
3741 if (b->type == bp_thread_event || b->type == bp_overlay_event
3742 || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3743 || b->type == bp_exception_master)
3745 delete_breakpoint (b);
3746 continue;
3749 /* Step-resume breakpoints are meaningless after an exec(). */
3750 if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3752 delete_breakpoint (b);
3753 continue;
3756 /* Just like single-step breakpoints. */
3757 if (b->type == bp_single_step)
3759 delete_breakpoint (b);
3760 continue;
3763 /* Longjmp and longjmp-resume breakpoints are also meaningless
3764 after an exec. */
3765 if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3766 || b->type == bp_longjmp_call_dummy
3767 || b->type == bp_exception || b->type == bp_exception_resume)
3769 delete_breakpoint (b);
3770 continue;
3773 if (b->type == bp_catchpoint)
3775 /* For now, none of the bp_catchpoint breakpoints need to
3776 do anything at this point. In the future, if some of
3777 the catchpoints need to something, we will need to add
3778 a new method, and call this method from here. */
3779 continue;
3782 /* bp_finish is a special case. The only way we ought to be able
3783 to see one of these when an exec() has happened, is if the user
3784 caught a vfork, and then said "finish". Ordinarily a finish just
3785 carries them to the call-site of the current callee, by setting
3786 a temporary bp there and resuming. But in this case, the finish
3787 will carry them entirely through the vfork & exec.
3789 We don't want to allow a bp_finish to remain inserted now. But
3790 we can't safely delete it, 'cause finish_command has a handle to
3791 the bp on a bpstat, and will later want to delete it. There's a
3792 chance (and I've seen it happen) that if we delete the bp_finish
3793 here, that its storage will get reused by the time finish_command
3794 gets 'round to deleting the "use to be a bp_finish" breakpoint.
3795 We really must allow finish_command to delete a bp_finish.
3797 In the absence of a general solution for the "how do we know
3798 it's safe to delete something others may have handles to?"
3799 problem, what we'll do here is just uninsert the bp_finish, and
3800 let finish_command delete it.
3802 (We know the bp_finish is "doomed" in the sense that it's
3803 momentary, and will be deleted as soon as finish_command sees
3804 the inferior stopped. So it doesn't matter that the bp's
3805 address is probably bogus in the new a.out, unlike e.g., the
3806 solib breakpoints.) */
3808 if (b->type == bp_finish)
3810 continue;
3813 /* Without a symbolic address, we have little hope of the
3814 pre-exec() address meaning the same thing in the post-exec()
3815 a.out. */
3816 if (breakpoint_location_spec_empty_p (b))
3818 delete_breakpoint (b);
3819 continue;
3825 detach_breakpoints (ptid_t ptid)
3827 int val = 0;
3828 scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3829 struct inferior *inf = current_inferior ();
3831 if (ptid.pid () == inferior_ptid.pid ())
3832 error (_("Cannot detach breakpoints of inferior_ptid"));
3834 /* Set inferior_ptid; remove_breakpoint_1 uses this global. */
3835 inferior_ptid = ptid;
3836 for (bp_location *bl : all_bp_locations ())
3838 if (bl->pspace != inf->pspace)
3839 continue;
3841 /* This function must physically remove breakpoints locations
3842 from the specified ptid, without modifying the breakpoint
3843 package's state. Locations of type bp_loc_other and
3844 bp_loc_software_watchpoint are only maintained at GDB side,
3845 so there is no need to remove them. Moreover, removing these
3846 would modify the breakpoint package's state. */
3847 if (bl->loc_type == bp_loc_other
3848 || bl->loc_type == bp_loc_software_watchpoint)
3849 continue;
3851 if (bl->inserted)
3852 val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3855 return val;
3858 /* Remove the breakpoint location BL from the current address space.
3859 Note that this is used to detach breakpoints from a child fork.
3860 When we get here, the child isn't in the inferior list, and neither
3861 do we have objects to represent its address space --- we should
3862 *not* look at bl->pspace->aspace here. */
3864 static int
3865 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3867 int val;
3869 /* BL is never in moribund_locations by our callers. */
3870 gdb_assert (bl->owner != NULL);
3872 /* The type of none suggests that owner is actually deleted.
3873 This should not ever happen. */
3874 gdb_assert (bl->owner->type != bp_none);
3876 if (bl->loc_type == bp_loc_software_breakpoint
3877 || bl->loc_type == bp_loc_hardware_breakpoint)
3879 /* "Normal" instruction breakpoint: either the standard
3880 trap-instruction bp (bp_breakpoint), or a
3881 bp_hardware_breakpoint. */
3883 /* First check to see if we have to handle an overlay. */
3884 if (overlay_debugging == ovly_off
3885 || bl->section == NULL
3886 || !(section_is_overlay (bl->section)))
3888 /* No overlay handling: just remove the breakpoint. */
3890 /* If we're trying to uninsert a memory breakpoint that we
3891 know is set in a dynamic object that is marked
3892 shlib_disabled, then either the dynamic object was
3893 removed with "remove-symbol-file" or with
3894 "nosharedlibrary". In the former case, we don't know
3895 whether another dynamic object might have loaded over the
3896 breakpoint's address -- the user might well let us know
3897 about it next with add-symbol-file (the whole point of
3898 add-symbol-file is letting the user manually maintain a
3899 list of dynamically loaded objects). If we have the
3900 breakpoint's shadow memory, that is, this is a software
3901 breakpoint managed by GDB, check whether the breakpoint
3902 is still inserted in memory, to avoid overwriting wrong
3903 code with stale saved shadow contents. Note that HW
3904 breakpoints don't have shadow memory, as they're
3905 implemented using a mechanism that is not dependent on
3906 being able to modify the target's memory, and as such
3907 they should always be removed. */
3908 if (bl->shlib_disabled
3909 && bl->target_info.shadow_len != 0
3910 && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3911 val = 0;
3912 else
3913 val = bl->owner->remove_location (bl, reason);
3915 else
3917 /* This breakpoint is in an overlay section.
3918 Did we set a breakpoint at the LMA? */
3919 if (!overlay_events_enabled)
3921 /* Yes -- overlay event support is not active, so we
3922 should have set a breakpoint at the LMA. Remove it.
3924 /* Ignore any failures: if the LMA is in ROM, we will
3925 have already warned when we failed to insert it. */
3926 if (bl->loc_type == bp_loc_hardware_breakpoint)
3927 target_remove_hw_breakpoint (bl->gdbarch,
3928 &bl->overlay_target_info);
3929 else
3930 target_remove_breakpoint (bl->gdbarch,
3931 &bl->overlay_target_info,
3932 reason);
3934 /* Did we set a breakpoint at the VMA?
3935 If so, we will have marked the breakpoint 'inserted'. */
3936 if (bl->inserted)
3938 /* Yes -- remove it. Previously we did not bother to
3939 remove the breakpoint if the section had been
3940 unmapped, but let's not rely on that being safe. We
3941 don't know what the overlay manager might do. */
3943 /* However, we should remove *software* breakpoints only
3944 if the section is still mapped, or else we overwrite
3945 wrong code with the saved shadow contents. */
3946 if (bl->loc_type == bp_loc_hardware_breakpoint
3947 || section_is_mapped (bl->section))
3948 val = bl->owner->remove_location (bl, reason);
3949 else
3950 val = 0;
3952 else
3954 /* No -- not inserted, so no need to remove. No error. */
3955 val = 0;
3959 /* In some cases, we might not be able to remove a breakpoint in
3960 a shared library that has already been removed, but we have
3961 not yet processed the shlib unload event. Similarly for an
3962 unloaded add-symbol-file object - the user might not yet have
3963 had the chance to remove-symbol-file it. shlib_disabled will
3964 be set if the library/object has already been removed, but
3965 the breakpoint hasn't been uninserted yet, e.g., after
3966 "nosharedlibrary" or "remove-symbol-file" with breakpoints
3967 always-inserted mode. */
3968 if (val
3969 && (bl->loc_type == bp_loc_software_breakpoint
3970 && (bl->shlib_disabled
3971 || solib_name_from_address (bl->pspace, bl->address)
3972 || shared_objfile_contains_address_p (bl->pspace,
3973 bl->address))))
3974 val = 0;
3976 if (val)
3977 return val;
3978 bl->inserted = (reason == DETACH_BREAKPOINT);
3980 else if (bl->loc_type == bp_loc_hardware_watchpoint)
3982 bl->inserted = (reason == DETACH_BREAKPOINT);
3983 bl->owner->remove_location (bl, reason);
3985 /* Failure to remove any of the hardware watchpoints comes here. */
3986 if (reason == REMOVE_BREAKPOINT && bl->inserted)
3987 warning (_("Could not remove hardware watchpoint %d."),
3988 bl->owner->number);
3990 else if (bl->owner->type == bp_catchpoint
3991 && breakpoint_enabled (bl->owner)
3992 && !bl->duplicate)
3994 val = bl->owner->remove_location (bl, reason);
3995 if (val)
3996 return val;
3998 bl->inserted = (reason == DETACH_BREAKPOINT);
4001 return 0;
4004 static int
4005 remove_breakpoint (struct bp_location *bl)
4007 /* BL is never in moribund_locations by our callers. */
4008 gdb_assert (bl->owner != NULL);
4010 /* The type of none suggests that owner is actually deleted.
4011 This should not ever happen. */
4012 gdb_assert (bl->owner->type != bp_none);
4014 scoped_restore_current_pspace_and_thread restore_pspace_thread;
4016 switch_to_program_space_and_thread (bl->pspace);
4018 return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4021 /* Clear the "inserted" flag in all breakpoints. */
4023 void
4024 mark_breakpoints_out (void)
4026 for (bp_location *bl : all_bp_locations ())
4027 if (bl->pspace == current_program_space)
4028 bl->inserted = 0;
4031 /* Clear the "inserted" flag in all breakpoints and delete any
4032 breakpoints which should go away between runs of the program.
4034 Plus other such housekeeping that has to be done for breakpoints
4035 between runs.
4037 Note: this function gets called at the end of a run (by
4038 generic_mourn_inferior) and when a run begins (by
4039 init_wait_for_inferior). */
4043 void
4044 breakpoint_init_inferior (enum inf_context context)
4046 struct program_space *pspace = current_program_space;
4048 /* If breakpoint locations are shared across processes, then there's
4049 nothing to do. */
4050 if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4051 return;
4053 mark_breakpoints_out ();
4055 for (breakpoint *b : all_breakpoints_safe ())
4057 if (b->loc && b->loc->pspace != pspace)
4058 continue;
4060 switch (b->type)
4062 case bp_call_dummy:
4063 case bp_longjmp_call_dummy:
4065 /* If the call dummy breakpoint is at the entry point it will
4066 cause problems when the inferior is rerun, so we better get
4067 rid of it. */
4069 case bp_watchpoint_scope:
4071 /* Also get rid of scope breakpoints. */
4073 case bp_shlib_event:
4075 /* Also remove solib event breakpoints. Their addresses may
4076 have changed since the last time we ran the program.
4077 Actually we may now be debugging against different target;
4078 and so the solib backend that installed this breakpoint may
4079 not be used in by the target. E.g.,
4081 (gdb) file prog-linux
4082 (gdb) run # native linux target
4084 (gdb) kill
4085 (gdb) file prog-win.exe
4086 (gdb) tar rem :9999 # remote Windows gdbserver.
4089 case bp_step_resume:
4091 /* Also remove step-resume breakpoints. */
4093 case bp_single_step:
4095 /* Also remove single-step breakpoints. */
4097 delete_breakpoint (b);
4098 break;
4100 case bp_watchpoint:
4101 case bp_hardware_watchpoint:
4102 case bp_read_watchpoint:
4103 case bp_access_watchpoint:
4105 struct watchpoint *w = (struct watchpoint *) b;
4107 /* Likewise for watchpoints on local expressions. */
4108 if (w->exp_valid_block != NULL)
4109 delete_breakpoint (b);
4110 else
4112 /* Get rid of existing locations, which are no longer
4113 valid. New ones will be created in
4114 update_watchpoint, when the inferior is restarted.
4115 The next update_global_location_list call will
4116 garbage collect them. */
4117 b->loc = NULL;
4119 if (context == inf_starting)
4121 /* Reset val field to force reread of starting value in
4122 insert_breakpoints. */
4123 w->val.reset (nullptr);
4124 w->val_valid = false;
4128 break;
4129 default:
4130 break;
4134 /* Get rid of the moribund locations. */
4135 for (bp_location *bl : moribund_locations)
4136 decref_bp_location (&bl);
4137 moribund_locations.clear ();
4140 /* These functions concern about actual breakpoints inserted in the
4141 target --- to e.g. check if we need to do decr_pc adjustment or if
4142 we need to hop over the bkpt --- so we check for address space
4143 match, not program space. */
4145 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4146 exists at PC. It returns ordinary_breakpoint_here if it's an
4147 ordinary breakpoint, or permanent_breakpoint_here if it's a
4148 permanent breakpoint.
4149 - When continuing from a location with an ordinary breakpoint, we
4150 actually single step once before calling insert_breakpoints.
4151 - When continuing from a location with a permanent breakpoint, we
4152 need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4153 the target, to advance the PC past the breakpoint. */
4155 enum breakpoint_here
4156 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4158 int any_breakpoint_here = 0;
4160 for (bp_location *bl : all_bp_locations ())
4162 if (bl->loc_type != bp_loc_software_breakpoint
4163 && bl->loc_type != bp_loc_hardware_breakpoint)
4164 continue;
4166 /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL. */
4167 if ((breakpoint_enabled (bl->owner)
4168 || bl->permanent)
4169 && breakpoint_location_address_match (bl, aspace, pc))
4171 if (overlay_debugging
4172 && section_is_overlay (bl->section)
4173 && !section_is_mapped (bl->section))
4174 continue; /* unmapped overlay -- can't be a match */
4175 else if (bl->permanent)
4176 return permanent_breakpoint_here;
4177 else
4178 any_breakpoint_here = 1;
4182 return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4185 /* See breakpoint.h. */
4188 breakpoint_in_range_p (const address_space *aspace,
4189 CORE_ADDR addr, ULONGEST len)
4191 for (bp_location *bl : all_bp_locations ())
4193 if (bl->loc_type != bp_loc_software_breakpoint
4194 && bl->loc_type != bp_loc_hardware_breakpoint)
4195 continue;
4197 if ((breakpoint_enabled (bl->owner)
4198 || bl->permanent)
4199 && breakpoint_location_address_range_overlap (bl, aspace,
4200 addr, len))
4202 if (overlay_debugging
4203 && section_is_overlay (bl->section)
4204 && !section_is_mapped (bl->section))
4206 /* Unmapped overlay -- can't be a match. */
4207 continue;
4210 return 1;
4214 return 0;
4217 /* Return true if there's a moribund breakpoint at PC. */
4220 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4222 for (bp_location *loc : moribund_locations)
4223 if (breakpoint_location_address_match (loc, aspace, pc))
4224 return 1;
4226 return 0;
4229 /* Returns non-zero iff BL is inserted at PC, in address space
4230 ASPACE. */
4232 static int
4233 bp_location_inserted_here_p (struct bp_location *bl,
4234 const address_space *aspace, CORE_ADDR pc)
4236 if (bl->inserted
4237 && breakpoint_address_match (bl->pspace->aspace, bl->address,
4238 aspace, pc))
4240 if (overlay_debugging
4241 && section_is_overlay (bl->section)
4242 && !section_is_mapped (bl->section))
4243 return 0; /* unmapped overlay -- can't be a match */
4244 else
4245 return 1;
4247 return 0;
4250 /* Returns non-zero iff there's a breakpoint inserted at PC. */
4253 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4255 for (bp_location *bl : all_bp_locations_at_addr (pc))
4257 if (bl->loc_type != bp_loc_software_breakpoint
4258 && bl->loc_type != bp_loc_hardware_breakpoint)
4259 continue;
4261 if (bp_location_inserted_here_p (bl, aspace, pc))
4262 return 1;
4264 return 0;
4267 /* This function returns non-zero iff there is a software breakpoint
4268 inserted at PC. */
4271 software_breakpoint_inserted_here_p (const address_space *aspace,
4272 CORE_ADDR pc)
4274 for (bp_location *bl : all_bp_locations_at_addr (pc))
4276 if (bl->loc_type != bp_loc_software_breakpoint)
4277 continue;
4279 if (bp_location_inserted_here_p (bl, aspace, pc))
4280 return 1;
4283 return 0;
4286 /* See breakpoint.h. */
4289 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4290 CORE_ADDR pc)
4292 for (bp_location *bl : all_bp_locations_at_addr (pc))
4294 if (bl->loc_type != bp_loc_hardware_breakpoint)
4295 continue;
4297 if (bp_location_inserted_here_p (bl, aspace, pc))
4298 return 1;
4301 return 0;
4305 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4306 CORE_ADDR addr, ULONGEST len)
4308 for (breakpoint *bpt : all_breakpoints ())
4310 if (bpt->type != bp_hardware_watchpoint
4311 && bpt->type != bp_access_watchpoint)
4312 continue;
4314 if (!breakpoint_enabled (bpt))
4315 continue;
4317 for (bp_location *loc : bpt->locations ())
4318 if (loc->pspace->aspace == aspace && loc->inserted)
4320 CORE_ADDR l, h;
4322 /* Check for intersection. */
4323 l = std::max<CORE_ADDR> (loc->address, addr);
4324 h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4325 if (l < h)
4326 return 1;
4329 return 0;
4332 /* See breakpoint.h. */
4334 bool
4335 is_catchpoint (struct breakpoint *b)
4337 return (b->type == bp_catchpoint);
4340 /* Clear a bpstat so that it says we are not at any breakpoint.
4341 Also free any storage that is part of a bpstat. */
4343 void
4344 bpstat_clear (bpstat **bsp)
4346 bpstat *p;
4347 bpstat *q;
4349 if (bsp == 0)
4350 return;
4351 p = *bsp;
4352 while (p != NULL)
4354 q = p->next;
4355 delete p;
4356 p = q;
4358 *bsp = NULL;
4361 bpstat::bpstat (const bpstat &other)
4362 : next (NULL),
4363 bp_location_at (other.bp_location_at),
4364 breakpoint_at (other.breakpoint_at),
4365 commands (other.commands),
4366 print (other.print),
4367 stop (other.stop),
4368 print_it (other.print_it)
4370 if (other.old_val != NULL)
4371 old_val = release_value (value_copy (other.old_val.get ()));
4374 /* Return a copy of a bpstat. Like "bs1 = bs2" but all storage that
4375 is part of the bpstat is copied as well. */
4377 bpstat *
4378 bpstat_copy (bpstat *bs)
4380 bpstat *p = nullptr;
4381 bpstat *tmp;
4382 bpstat *retval = nullptr;
4384 if (bs == NULL)
4385 return bs;
4387 for (; bs != NULL; bs = bs->next)
4389 tmp = new bpstat (*bs);
4391 if (p == NULL)
4392 /* This is the first thing in the chain. */
4393 retval = tmp;
4394 else
4395 p->next = tmp;
4396 p = tmp;
4398 p->next = NULL;
4399 return retval;
4402 /* Find the bpstat associated with this breakpoint. */
4404 bpstat *
4405 bpstat_find_breakpoint (bpstat *bsp, struct breakpoint *breakpoint)
4407 if (bsp == NULL)
4408 return NULL;
4410 for (; bsp != NULL; bsp = bsp->next)
4412 if (bsp->breakpoint_at == breakpoint)
4413 return bsp;
4415 return NULL;
4418 /* See breakpoint.h. */
4420 bool
4421 bpstat_explains_signal (bpstat *bsp, enum gdb_signal sig)
4423 for (; bsp != NULL; bsp = bsp->next)
4425 if (bsp->breakpoint_at == NULL)
4427 /* A moribund location can never explain a signal other than
4428 GDB_SIGNAL_TRAP. */
4429 if (sig == GDB_SIGNAL_TRAP)
4430 return true;
4432 else
4434 if (bsp->breakpoint_at->explains_signal (sig))
4435 return true;
4439 return false;
4442 /* Put in *NUM the breakpoint number of the first breakpoint we are
4443 stopped at. *BSP upon return is a bpstat which points to the
4444 remaining breakpoints stopped at (but which is not guaranteed to be
4445 good for anything but further calls to bpstat_num).
4447 Return 0 if passed a bpstat which does not indicate any breakpoints.
4448 Return -1 if stopped at a breakpoint that has been deleted since
4449 we set it.
4450 Return 1 otherwise. */
4453 bpstat_num (bpstat **bsp, int *num)
4455 struct breakpoint *b;
4457 if ((*bsp) == NULL)
4458 return 0; /* No more breakpoint values */
4460 /* We assume we'll never have several bpstats that correspond to a
4461 single breakpoint -- otherwise, this function might return the
4462 same number more than once and this will look ugly. */
4463 b = (*bsp)->breakpoint_at;
4464 *bsp = (*bsp)->next;
4465 if (b == NULL)
4466 return -1; /* breakpoint that's been deleted since */
4468 *num = b->number; /* We have its number */
4469 return 1;
4472 /* See breakpoint.h. */
4474 void
4475 bpstat_clear_actions (void)
4477 bpstat *bs;
4479 if (inferior_ptid == null_ptid)
4480 return;
4482 thread_info *tp = inferior_thread ();
4483 for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4485 bs->commands = NULL;
4486 bs->old_val.reset (nullptr);
4490 /* Called when a command is about to proceed the inferior. */
4492 static void
4493 breakpoint_about_to_proceed (void)
4495 if (inferior_ptid != null_ptid)
4497 struct thread_info *tp = inferior_thread ();
4499 /* Allow inferior function calls in breakpoint commands to not
4500 interrupt the command list. When the call finishes
4501 successfully, the inferior will be standing at the same
4502 breakpoint as if nothing happened. */
4503 if (tp->control.in_infcall)
4504 return;
4507 breakpoint_proceeded = 1;
4510 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4511 or its equivalent. */
4513 static int
4514 command_line_is_silent (struct command_line *cmd)
4516 return cmd && (strcmp ("silent", cmd->line) == 0);
4519 /* Execute all the commands associated with all the breakpoints at
4520 this location. Any of these commands could cause the process to
4521 proceed beyond this point, etc. We look out for such changes by
4522 checking the global "breakpoint_proceeded" after each command.
4524 Returns true if a breakpoint command resumed the inferior. In that
4525 case, it is the caller's responsibility to recall it again with the
4526 bpstat of the current thread. */
4528 static int
4529 bpstat_do_actions_1 (bpstat **bsp)
4531 bpstat *bs;
4532 int again = 0;
4534 /* Avoid endless recursion if a `source' command is contained
4535 in bs->commands. */
4536 if (executing_breakpoint_commands)
4537 return 0;
4539 scoped_restore save_executing
4540 = make_scoped_restore (&executing_breakpoint_commands, 1);
4542 scoped_restore preventer = prevent_dont_repeat ();
4544 /* This pointer will iterate over the list of bpstat's. */
4545 bs = *bsp;
4547 breakpoint_proceeded = 0;
4548 for (; bs != NULL; bs = bs->next)
4550 struct command_line *cmd = NULL;
4552 /* Take ownership of the BSP's command tree, if it has one.
4554 The command tree could legitimately contain commands like
4555 'step' and 'next', which call clear_proceed_status, which
4556 frees stop_bpstat's command tree. To make sure this doesn't
4557 free the tree we're executing out from under us, we need to
4558 take ownership of the tree ourselves. Since a given bpstat's
4559 commands are only executed once, we don't need to copy it; we
4560 can clear the pointer in the bpstat, and make sure we free
4561 the tree when we're done. */
4562 counted_command_line ccmd = bs->commands;
4563 bs->commands = NULL;
4564 if (ccmd != NULL)
4565 cmd = ccmd.get ();
4566 if (command_line_is_silent (cmd))
4568 /* The action has been already done by bpstat_stop_status. */
4569 cmd = cmd->next;
4572 while (cmd != NULL)
4574 execute_control_command (cmd);
4576 if (breakpoint_proceeded)
4577 break;
4578 else
4579 cmd = cmd->next;
4582 if (breakpoint_proceeded)
4584 if (current_ui->async)
4585 /* If we are in async mode, then the target might be still
4586 running, not stopped at any breakpoint, so nothing for
4587 us to do here -- just return to the event loop. */
4589 else
4590 /* In sync mode, when execute_control_command returns
4591 we're already standing on the next breakpoint.
4592 Breakpoint commands for that stop were not run, since
4593 execute_command does not run breakpoint commands --
4594 only command_line_handler does, but that one is not
4595 involved in execution of breakpoint commands. So, we
4596 can now execute breakpoint commands. It should be
4597 noted that making execute_command do bpstat actions is
4598 not an option -- in this case we'll have recursive
4599 invocation of bpstat for each breakpoint with a
4600 command, and can easily blow up GDB stack. Instead, we
4601 return true, which will trigger the caller to recall us
4602 with the new stop_bpstat. */
4603 again = 1;
4604 break;
4607 return again;
4610 /* Helper for bpstat_do_actions. Get the current thread, if there's
4611 one, is alive and has execution. Return NULL otherwise. */
4613 static thread_info *
4614 get_bpstat_thread ()
4616 if (inferior_ptid == null_ptid || !target_has_execution ())
4617 return NULL;
4619 thread_info *tp = inferior_thread ();
4620 if (tp->state == THREAD_EXITED || tp->executing ())
4621 return NULL;
4622 return tp;
4625 void
4626 bpstat_do_actions (void)
4628 auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4629 thread_info *tp;
4631 /* Do any commands attached to breakpoint we are stopped at. */
4632 while ((tp = get_bpstat_thread ()) != NULL)
4634 /* Since in sync mode, bpstat_do_actions may resume the
4635 inferior, and only return when it is stopped at the next
4636 breakpoint, we keep doing breakpoint actions until it returns
4637 false to indicate the inferior was not resumed. */
4638 if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4639 break;
4642 cleanup_if_error.release ();
4645 /* Print out the (old or new) value associated with a watchpoint. */
4647 static void
4648 watchpoint_value_print (struct value *val, struct ui_file *stream)
4650 if (val == NULL)
4651 fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4652 else
4654 struct value_print_options opts;
4655 get_user_print_options (&opts);
4656 value_print (val, stream, &opts);
4660 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4661 debugging multiple threads. */
4663 void
4664 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4666 if (uiout->is_mi_like_p ())
4667 return;
4669 uiout->text ("\n");
4671 if (show_thread_that_caused_stop ())
4673 struct thread_info *thr = inferior_thread ();
4675 uiout->text ("Thread ");
4676 uiout->field_string ("thread-id", print_thread_id (thr));
4678 const char *name = thread_name (thr);
4679 if (name != NULL)
4681 uiout->text (" \"");
4682 uiout->field_string ("name", name);
4683 uiout->text ("\"");
4686 uiout->text (" hit ");
4690 /* Generic routine for printing messages indicating why we
4691 stopped. The behavior of this function depends on the value
4692 'print_it' in the bpstat structure. Under some circumstances we
4693 may decide not to print anything here and delegate the task to
4694 normal_stop(). */
4696 static enum print_stop_action
4697 print_bp_stop_message (bpstat *bs)
4699 switch (bs->print_it)
4701 case print_it_noop:
4702 /* Nothing should be printed for this bpstat entry. */
4703 return PRINT_UNKNOWN;
4704 break;
4706 case print_it_done:
4707 /* We still want to print the frame, but we already printed the
4708 relevant messages. */
4709 return PRINT_SRC_AND_LOC;
4710 break;
4712 case print_it_normal:
4714 struct breakpoint *b = bs->breakpoint_at;
4716 /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4717 which has since been deleted. */
4718 if (b == NULL)
4719 return PRINT_UNKNOWN;
4721 /* Normal case. Call the breakpoint's print_it method. */
4722 return b->print_it (bs);
4724 break;
4726 default:
4727 internal_error (__FILE__, __LINE__,
4728 _("print_bp_stop_message: unrecognized enum value"));
4729 break;
4733 /* See breakpoint.h. */
4735 void
4736 print_solib_event (bool is_catchpoint)
4738 bool any_deleted = !current_program_space->deleted_solibs.empty ();
4739 bool any_added = !current_program_space->added_solibs.empty ();
4741 if (!is_catchpoint)
4743 if (any_added || any_deleted)
4744 current_uiout->text (_("Stopped due to shared library event:\n"));
4745 else
4746 current_uiout->text (_("Stopped due to shared library event (no "
4747 "libraries added or removed)\n"));
4750 if (current_uiout->is_mi_like_p ())
4751 current_uiout->field_string ("reason",
4752 async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4754 if (any_deleted)
4756 current_uiout->text (_(" Inferior unloaded "));
4757 ui_out_emit_list list_emitter (current_uiout, "removed");
4758 for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4760 const std::string &name = current_program_space->deleted_solibs[ix];
4762 if (ix > 0)
4763 current_uiout->text (" ");
4764 current_uiout->field_string ("library", name);
4765 current_uiout->text ("\n");
4769 if (any_added)
4771 current_uiout->text (_(" Inferior loaded "));
4772 ui_out_emit_list list_emitter (current_uiout, "added");
4773 bool first = true;
4774 for (so_list *iter : current_program_space->added_solibs)
4776 if (!first)
4777 current_uiout->text (" ");
4778 first = false;
4779 current_uiout->field_string ("library", iter->so_name);
4780 current_uiout->text ("\n");
4785 /* Print a message indicating what happened. This is called from
4786 normal_stop(). The input to this routine is the head of the bpstat
4787 list - a list of the eventpoints that caused this stop. KIND is
4788 the target_waitkind for the stopping event. This
4789 routine calls the generic print routine for printing a message
4790 about reasons for stopping. This will print (for example) the
4791 "Breakpoint n," part of the output. The return value of this
4792 routine is one of:
4794 PRINT_UNKNOWN: Means we printed nothing.
4795 PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4796 code to print the location. An example is
4797 "Breakpoint 1, " which should be followed by
4798 the location.
4799 PRINT_SRC_ONLY: Means we printed something, but there is no need
4800 to also print the location part of the message.
4801 An example is the catch/throw messages, which
4802 don't require a location appended to the end.
4803 PRINT_NOTHING: We have done some printing and we don't need any
4804 further info to be printed. */
4806 enum print_stop_action
4807 bpstat_print (bpstat *bs, int kind)
4809 enum print_stop_action val;
4811 /* Maybe another breakpoint in the chain caused us to stop.
4812 (Currently all watchpoints go on the bpstat whether hit or not.
4813 That probably could (should) be changed, provided care is taken
4814 with respect to bpstat_explains_signal). */
4815 for (; bs; bs = bs->next)
4817 val = print_bp_stop_message (bs);
4818 if (val == PRINT_SRC_ONLY
4819 || val == PRINT_SRC_AND_LOC
4820 || val == PRINT_NOTHING)
4821 return val;
4824 /* If we had hit a shared library event breakpoint,
4825 print_bp_stop_message would print out this message. If we hit an
4826 OS-level shared library event, do the same thing. */
4827 if (kind == TARGET_WAITKIND_LOADED)
4829 print_solib_event (false);
4830 return PRINT_NOTHING;
4833 /* We reached the end of the chain, or we got a null BS to start
4834 with and nothing was printed. */
4835 return PRINT_UNKNOWN;
4838 /* Evaluate the boolean expression EXP and return the result. */
4840 static bool
4841 breakpoint_cond_eval (expression *exp)
4843 struct value *mark = value_mark ();
4844 bool res = value_true (evaluate_expression (exp));
4846 value_free_to_mark (mark);
4847 return res;
4850 /* Allocate a new bpstat. Link it to the FIFO list by BS_LINK_POINTER. */
4852 bpstat::bpstat (struct bp_location *bl, bpstat ***bs_link_pointer)
4853 : next (NULL),
4854 bp_location_at (bp_location_ref_ptr::new_reference (bl)),
4855 breakpoint_at (bl->owner),
4856 commands (NULL),
4857 print (0),
4858 stop (0),
4859 print_it (print_it_normal)
4861 **bs_link_pointer = this;
4862 *bs_link_pointer = &next;
4865 bpstat::bpstat ()
4866 : next (NULL),
4867 breakpoint_at (NULL),
4868 commands (NULL),
4869 print (0),
4870 stop (0),
4871 print_it (print_it_normal)
4875 /* The target has stopped with waitstatus WS. Check if any hardware
4876 watchpoints have triggered, according to the target. */
4879 watchpoints_triggered (const target_waitstatus &ws)
4881 bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4882 CORE_ADDR addr;
4884 if (!stopped_by_watchpoint)
4886 /* We were not stopped by a watchpoint. Mark all watchpoints
4887 as not triggered. */
4888 for (breakpoint *b : all_breakpoints ())
4889 if (is_hardware_watchpoint (b))
4891 struct watchpoint *w = (struct watchpoint *) b;
4893 w->watchpoint_triggered = watch_triggered_no;
4896 return 0;
4899 if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
4901 /* We were stopped by a watchpoint, but we don't know where.
4902 Mark all watchpoints as unknown. */
4903 for (breakpoint *b : all_breakpoints ())
4904 if (is_hardware_watchpoint (b))
4906 struct watchpoint *w = (struct watchpoint *) b;
4908 w->watchpoint_triggered = watch_triggered_unknown;
4911 return 1;
4914 /* The target could report the data address. Mark watchpoints
4915 affected by this data address as triggered, and all others as not
4916 triggered. */
4918 for (breakpoint *b : all_breakpoints ())
4919 if (is_hardware_watchpoint (b))
4921 struct watchpoint *w = (struct watchpoint *) b;
4923 w->watchpoint_triggered = watch_triggered_no;
4924 for (bp_location *loc : b->locations ())
4926 if (is_masked_watchpoint (b))
4928 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4929 CORE_ADDR start = loc->address & w->hw_wp_mask;
4931 if (newaddr == start)
4933 w->watchpoint_triggered = watch_triggered_yes;
4934 break;
4937 /* Exact match not required. Within range is sufficient. */
4938 else if (target_watchpoint_addr_within_range
4939 (current_inferior ()->top_target (), addr, loc->address,
4940 loc->length))
4942 w->watchpoint_triggered = watch_triggered_yes;
4943 break;
4948 return 1;
4951 /* Possible return values for watchpoint_check. */
4952 enum wp_check_result
4954 /* The watchpoint has been deleted. */
4955 WP_DELETED = 1,
4957 /* The value has changed. */
4958 WP_VALUE_CHANGED = 2,
4960 /* The value has not changed. */
4961 WP_VALUE_NOT_CHANGED = 3,
4963 /* Ignore this watchpoint, no matter if the value changed or not. */
4964 WP_IGNORE = 4,
4967 #define BP_TEMPFLAG 1
4968 #define BP_HARDWAREFLAG 2
4970 /* Evaluate watchpoint condition expression and check if its value
4971 changed. */
4973 static wp_check_result
4974 watchpoint_check (bpstat *bs)
4976 struct watchpoint *b;
4977 struct frame_info *fr;
4978 int within_current_scope;
4980 /* BS is built from an existing struct breakpoint. */
4981 gdb_assert (bs->breakpoint_at != NULL);
4982 b = (struct watchpoint *) bs->breakpoint_at;
4984 /* If this is a local watchpoint, we only want to check if the
4985 watchpoint frame is in scope if the current thread is the thread
4986 that was used to create the watchpoint. */
4987 if (!watchpoint_in_thread_scope (b))
4988 return WP_IGNORE;
4990 if (b->exp_valid_block == NULL)
4991 within_current_scope = 1;
4992 else
4994 struct frame_info *frame = get_current_frame ();
4995 struct gdbarch *frame_arch = get_frame_arch (frame);
4996 CORE_ADDR frame_pc = get_frame_pc (frame);
4998 /* stack_frame_destroyed_p() returns a non-zero value if we're
4999 still in the function but the stack frame has already been
5000 invalidated. Since we can't rely on the values of local
5001 variables after the stack has been destroyed, we are treating
5002 the watchpoint in that state as `not changed' without further
5003 checking. Don't mark watchpoints as changed if the current
5004 frame is in an epilogue - even if they are in some other
5005 frame, our view of the stack is likely to be wrong and
5006 frame_find_by_id could error out. */
5007 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5008 return WP_IGNORE;
5010 fr = frame_find_by_id (b->watchpoint_frame);
5011 within_current_scope = (fr != NULL);
5013 /* If we've gotten confused in the unwinder, we might have
5014 returned a frame that can't describe this variable. */
5015 if (within_current_scope)
5017 struct symbol *function;
5019 function = get_frame_function (fr);
5020 if (function == NULL
5021 || !contained_in (b->exp_valid_block, function->value_block ()))
5022 within_current_scope = 0;
5025 if (within_current_scope)
5026 /* If we end up stopping, the current frame will get selected
5027 in normal_stop. So this call to select_frame won't affect
5028 the user. */
5029 select_frame (fr);
5032 if (within_current_scope)
5034 /* We use value_{,free_to_}mark because it could be a *long*
5035 time before we return to the command level and call
5036 free_all_values. We can't call free_all_values because we
5037 might be in the middle of evaluating a function call. */
5039 struct value *mark;
5040 struct value *new_val;
5042 if (is_masked_watchpoint (b))
5043 /* Since we don't know the exact trigger address (from
5044 stopped_data_address), just tell the user we've triggered
5045 a mask watchpoint. */
5046 return WP_VALUE_CHANGED;
5048 mark = value_mark ();
5049 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
5050 NULL, NULL, false);
5052 if (b->val_bitsize != 0)
5053 new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5055 /* We use value_equal_contents instead of value_equal because
5056 the latter coerces an array to a pointer, thus comparing just
5057 the address of the array instead of its contents. This is
5058 not what we want. */
5059 if ((b->val != NULL) != (new_val != NULL)
5060 || (b->val != NULL && !value_equal_contents (b->val.get (),
5061 new_val)))
5063 bs->old_val = b->val;
5064 b->val = release_value (new_val);
5065 b->val_valid = true;
5066 if (new_val != NULL)
5067 value_free_to_mark (mark);
5068 return WP_VALUE_CHANGED;
5070 else
5072 /* Nothing changed. */
5073 value_free_to_mark (mark);
5074 return WP_VALUE_NOT_CHANGED;
5077 else
5079 /* This seems like the only logical thing to do because
5080 if we temporarily ignored the watchpoint, then when
5081 we reenter the block in which it is valid it contains
5082 garbage (in the case of a function, it may have two
5083 garbage values, one before and one after the prologue).
5084 So we can't even detect the first assignment to it and
5085 watch after that (since the garbage may or may not equal
5086 the first value assigned). */
5087 /* We print all the stop information in
5088 breakpointprint_it, but in this case, by the time we
5089 call breakpoint->print_it this bp will be deleted
5090 already. So we have no choice but print the information
5091 here. */
5093 SWITCH_THRU_ALL_UIS ()
5095 struct ui_out *uiout = current_uiout;
5097 if (uiout->is_mi_like_p ())
5098 uiout->field_string
5099 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5100 uiout->message ("\nWatchpoint %pF deleted because the program has "
5101 "left the block in\n"
5102 "which its expression is valid.\n",
5103 signed_field ("wpnum", b->number));
5106 /* Make sure the watchpoint's commands aren't executed. */
5107 b->commands = NULL;
5108 watchpoint_del_at_next_stop (b);
5110 return WP_DELETED;
5114 /* Return true if it looks like target has stopped due to hitting
5115 breakpoint location BL. This function does not check if we should
5116 stop, only if BL explains the stop. */
5118 static int
5119 bpstat_check_location (const struct bp_location *bl,
5120 const address_space *aspace, CORE_ADDR bp_addr,
5121 const target_waitstatus &ws)
5123 struct breakpoint *b = bl->owner;
5125 /* BL is from an existing breakpoint. */
5126 gdb_assert (b != NULL);
5128 return b->breakpoint_hit (bl, aspace, bp_addr, ws);
5131 /* Determine if the watched values have actually changed, and we
5132 should stop. If not, set BS->stop to 0. */
5134 static void
5135 bpstat_check_watchpoint (bpstat *bs)
5137 const struct bp_location *bl;
5138 struct watchpoint *b;
5140 /* BS is built for existing struct breakpoint. */
5141 bl = bs->bp_location_at.get ();
5142 gdb_assert (bl != NULL);
5143 b = (struct watchpoint *) bs->breakpoint_at;
5144 gdb_assert (b != NULL);
5147 int must_check_value = 0;
5149 if (b->type == bp_watchpoint)
5150 /* For a software watchpoint, we must always check the
5151 watched value. */
5152 must_check_value = 1;
5153 else if (b->watchpoint_triggered == watch_triggered_yes)
5154 /* We have a hardware watchpoint (read, write, or access)
5155 and the target earlier reported an address watched by
5156 this watchpoint. */
5157 must_check_value = 1;
5158 else if (b->watchpoint_triggered == watch_triggered_unknown
5159 && b->type == bp_hardware_watchpoint)
5160 /* We were stopped by a hardware watchpoint, but the target could
5161 not report the data address. We must check the watchpoint's
5162 value. Access and read watchpoints are out of luck; without
5163 a data address, we can't figure it out. */
5164 must_check_value = 1;
5166 if (must_check_value)
5168 wp_check_result e;
5172 e = watchpoint_check (bs);
5174 catch (const gdb_exception &ex)
5176 exception_fprintf (gdb_stderr, ex,
5177 "Error evaluating expression "
5178 "for watchpoint %d\n",
5179 b->number);
5181 SWITCH_THRU_ALL_UIS ()
5183 gdb_printf (_("Watchpoint %d deleted.\n"),
5184 b->number);
5186 watchpoint_del_at_next_stop (b);
5187 e = WP_DELETED;
5190 switch (e)
5192 case WP_DELETED:
5193 /* We've already printed what needs to be printed. */
5194 bs->print_it = print_it_done;
5195 /* Stop. */
5196 break;
5197 case WP_IGNORE:
5198 bs->print_it = print_it_noop;
5199 bs->stop = 0;
5200 break;
5201 case WP_VALUE_CHANGED:
5202 if (b->type == bp_read_watchpoint)
5204 /* There are two cases to consider here:
5206 1. We're watching the triggered memory for reads.
5207 In that case, trust the target, and always report
5208 the watchpoint hit to the user. Even though
5209 reads don't cause value changes, the value may
5210 have changed since the last time it was read, and
5211 since we're not trapping writes, we will not see
5212 those, and as such we should ignore our notion of
5213 old value.
5215 2. We're watching the triggered memory for both
5216 reads and writes. There are two ways this may
5217 happen:
5219 2.1. This is a target that can't break on data
5220 reads only, but can break on accesses (reads or
5221 writes), such as e.g., x86. We detect this case
5222 at the time we try to insert read watchpoints.
5224 2.2. Otherwise, the target supports read
5225 watchpoints, but, the user set an access or write
5226 watchpoint watching the same memory as this read
5227 watchpoint.
5229 If we're watching memory writes as well as reads,
5230 ignore watchpoint hits when we find that the
5231 value hasn't changed, as reads don't cause
5232 changes. This still gives false positives when
5233 the program writes the same value to memory as
5234 what there was already in memory (we will confuse
5235 it for a read), but it's much better than
5236 nothing. */
5238 int other_write_watchpoint = 0;
5240 if (bl->watchpoint_type == hw_read)
5242 for (breakpoint *other_b : all_breakpoints ())
5243 if (other_b->type == bp_hardware_watchpoint
5244 || other_b->type == bp_access_watchpoint)
5246 struct watchpoint *other_w =
5247 (struct watchpoint *) other_b;
5249 if (other_w->watchpoint_triggered
5250 == watch_triggered_yes)
5252 other_write_watchpoint = 1;
5253 break;
5258 if (other_write_watchpoint
5259 || bl->watchpoint_type == hw_access)
5261 /* We're watching the same memory for writes,
5262 and the value changed since the last time we
5263 updated it, so this trap must be for a write.
5264 Ignore it. */
5265 bs->print_it = print_it_noop;
5266 bs->stop = 0;
5269 break;
5270 case WP_VALUE_NOT_CHANGED:
5271 if (b->type == bp_hardware_watchpoint
5272 || b->type == bp_watchpoint)
5274 /* Don't stop: write watchpoints shouldn't fire if
5275 the value hasn't changed. */
5276 bs->print_it = print_it_noop;
5277 bs->stop = 0;
5279 /* Stop. */
5280 break;
5281 default:
5282 /* Can't happen. */
5283 break;
5286 else /* must_check_value == 0 */
5288 /* This is a case where some watchpoint(s) triggered, but
5289 not at the address of this watchpoint, or else no
5290 watchpoint triggered after all. So don't print
5291 anything for this watchpoint. */
5292 bs->print_it = print_it_noop;
5293 bs->stop = 0;
5298 /* For breakpoints that are currently marked as telling gdb to stop,
5299 check conditions (condition proper, frame, thread and ignore count)
5300 of breakpoint referred to by BS. If we should not stop for this
5301 breakpoint, set BS->stop to 0. */
5303 static void
5304 bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
5306 const struct bp_location *bl;
5307 struct breakpoint *b;
5308 /* Assume stop. */
5309 bool condition_result = true;
5310 struct expression *cond;
5312 gdb_assert (bs->stop);
5314 /* BS is built for existing struct breakpoint. */
5315 bl = bs->bp_location_at.get ();
5316 gdb_assert (bl != NULL);
5317 b = bs->breakpoint_at;
5318 gdb_assert (b != NULL);
5320 /* Even if the target evaluated the condition on its end and notified GDB, we
5321 need to do so again since GDB does not know if we stopped due to a
5322 breakpoint or a single step breakpoint. */
5324 if (frame_id_p (b->frame_id)
5325 && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5327 bs->stop = 0;
5328 return;
5331 /* If this is a thread/task-specific breakpoint, don't waste cpu
5332 evaluating the condition if this isn't the specified
5333 thread/task. */
5334 if ((b->thread != -1 && b->thread != thread->global_num)
5335 || (b->task != 0 && b->task != ada_get_task_number (thread)))
5337 bs->stop = 0;
5338 return;
5341 /* Evaluate extension language breakpoints that have a "stop" method
5342 implemented. */
5343 bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5345 if (is_watchpoint (b))
5347 struct watchpoint *w = (struct watchpoint *) b;
5349 cond = w->cond_exp.get ();
5351 else
5352 cond = bl->cond.get ();
5354 if (cond && b->disposition != disp_del_at_next_stop)
5356 int within_current_scope = 1;
5357 struct watchpoint * w;
5359 /* We use value_mark and value_free_to_mark because it could
5360 be a long time before we return to the command level and
5361 call free_all_values. We can't call free_all_values
5362 because we might be in the middle of evaluating a
5363 function call. */
5364 struct value *mark = value_mark ();
5366 if (is_watchpoint (b))
5367 w = (struct watchpoint *) b;
5368 else
5369 w = NULL;
5371 /* Need to select the frame, with all that implies so that
5372 the conditions will have the right context. Because we
5373 use the frame, we will not see an inlined function's
5374 variables when we arrive at a breakpoint at the start
5375 of the inlined function; the current frame will be the
5376 call site. */
5377 if (w == NULL || w->cond_exp_valid_block == NULL)
5378 select_frame (get_current_frame ());
5379 else
5381 struct frame_info *frame;
5383 /* For local watchpoint expressions, which particular
5384 instance of a local is being watched matters, so we
5385 keep track of the frame to evaluate the expression
5386 in. To evaluate the condition however, it doesn't
5387 really matter which instantiation of the function
5388 where the condition makes sense triggers the
5389 watchpoint. This allows an expression like "watch
5390 global if q > 10" set in `func', catch writes to
5391 global on all threads that call `func', or catch
5392 writes on all recursive calls of `func' by a single
5393 thread. We simply always evaluate the condition in
5394 the innermost frame that's executing where it makes
5395 sense to evaluate the condition. It seems
5396 intuitive. */
5397 frame = block_innermost_frame (w->cond_exp_valid_block);
5398 if (frame != NULL)
5399 select_frame (frame);
5400 else
5401 within_current_scope = 0;
5403 if (within_current_scope)
5407 condition_result = breakpoint_cond_eval (cond);
5409 catch (const gdb_exception &ex)
5411 exception_fprintf (gdb_stderr, ex,
5412 "Error in testing breakpoint condition:\n");
5415 else
5417 warning (_("Watchpoint condition cannot be tested "
5418 "in the current scope"));
5419 /* If we failed to set the right context for this
5420 watchpoint, unconditionally report it. */
5422 /* FIXME-someday, should give breakpoint #. */
5423 value_free_to_mark (mark);
5426 if (cond && !condition_result)
5428 bs->stop = 0;
5430 else if (b->ignore_count > 0)
5432 b->ignore_count--;
5433 bs->stop = 0;
5434 /* Increase the hit count even though we don't stop. */
5435 ++(b->hit_count);
5436 gdb::observers::breakpoint_modified.notify (b);
5440 /* Returns true if we need to track moribund locations of LOC's type
5441 on the current target. */
5443 static int
5444 need_moribund_for_location_type (struct bp_location *loc)
5446 return ((loc->loc_type == bp_loc_software_breakpoint
5447 && !target_supports_stopped_by_sw_breakpoint ())
5448 || (loc->loc_type == bp_loc_hardware_breakpoint
5449 && !target_supports_stopped_by_hw_breakpoint ()));
5452 /* See breakpoint.h. */
5454 bpstat *
5455 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5456 const target_waitstatus &ws)
5458 bpstat *bs_head = nullptr, **bs_link = &bs_head;
5460 for (breakpoint *b : all_breakpoints ())
5462 if (!breakpoint_enabled (b))
5463 continue;
5465 for (bp_location *bl : b->locations ())
5467 /* For hardware watchpoints, we look only at the first
5468 location. The watchpoint_check function will work on the
5469 entire expression, not the individual locations. For
5470 read watchpoints, the watchpoints_triggered function has
5471 checked all locations already. */
5472 if (b->type == bp_hardware_watchpoint && bl != b->loc)
5473 break;
5475 if (!bl->enabled || bl->disabled_by_cond || bl->shlib_disabled)
5476 continue;
5478 if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5479 continue;
5481 /* Come here if it's a watchpoint, or if the break address
5482 matches. */
5484 bpstat *bs = new bpstat (bl, &bs_link); /* Alloc a bpstat to
5485 explain stop. */
5487 /* Assume we stop. Should we find a watchpoint that is not
5488 actually triggered, or if the condition of the breakpoint
5489 evaluates as false, we'll reset 'stop' to 0. */
5490 bs->stop = 1;
5491 bs->print = 1;
5493 /* If this is a scope breakpoint, mark the associated
5494 watchpoint as triggered so that we will handle the
5495 out-of-scope event. We'll get to the watchpoint next
5496 iteration. */
5497 if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5499 struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5501 w->watchpoint_triggered = watch_triggered_yes;
5506 /* Check if a moribund breakpoint explains the stop. */
5507 if (!target_supports_stopped_by_sw_breakpoint ()
5508 || !target_supports_stopped_by_hw_breakpoint ())
5510 for (bp_location *loc : moribund_locations)
5512 if (breakpoint_location_address_match (loc, aspace, bp_addr)
5513 && need_moribund_for_location_type (loc))
5515 bpstat *bs = new bpstat (loc, &bs_link);
5516 /* For hits of moribund locations, we should just proceed. */
5517 bs->stop = 0;
5518 bs->print = 0;
5519 bs->print_it = print_it_noop;
5524 return bs_head;
5527 /* See breakpoint.h. */
5529 bpstat *
5530 bpstat_stop_status (const address_space *aspace,
5531 CORE_ADDR bp_addr, thread_info *thread,
5532 const target_waitstatus &ws,
5533 bpstat *stop_chain)
5535 struct breakpoint *b = NULL;
5536 /* First item of allocated bpstat's. */
5537 bpstat *bs_head = stop_chain;
5538 bpstat *bs;
5539 int need_remove_insert;
5540 int removed_any;
5542 /* First, build the bpstat chain with locations that explain a
5543 target stop, while being careful to not set the target running,
5544 as that may invalidate locations (in particular watchpoint
5545 locations are recreated). Resuming will happen here with
5546 breakpoint conditions or watchpoint expressions that include
5547 inferior function calls. */
5548 if (bs_head == NULL)
5549 bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5551 /* A bit of special processing for shlib breakpoints. We need to
5552 process solib loading here, so that the lists of loaded and
5553 unloaded libraries are correct before we handle "catch load" and
5554 "catch unload". */
5555 for (bs = bs_head; bs != NULL; bs = bs->next)
5557 if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5559 handle_solib_event ();
5560 break;
5564 /* Now go through the locations that caused the target to stop, and
5565 check whether we're interested in reporting this stop to higher
5566 layers, or whether we should resume the target transparently. */
5568 removed_any = 0;
5570 for (bs = bs_head; bs != NULL; bs = bs->next)
5572 if (!bs->stop)
5573 continue;
5575 b = bs->breakpoint_at;
5576 b->check_status (bs);
5577 if (bs->stop)
5579 bpstat_check_breakpoint_conditions (bs, thread);
5581 if (bs->stop)
5583 ++(b->hit_count);
5585 /* We will stop here. */
5586 if (b->disposition == disp_disable)
5588 --(b->enable_count);
5589 if (b->enable_count <= 0)
5590 b->enable_state = bp_disabled;
5591 removed_any = 1;
5593 gdb::observers::breakpoint_modified.notify (b);
5594 if (b->silent)
5595 bs->print = 0;
5596 bs->commands = b->commands;
5597 if (command_line_is_silent (bs->commands
5598 ? bs->commands.get () : NULL))
5599 bs->print = 0;
5601 b->after_condition_true (bs);
5606 /* Print nothing for this entry if we don't stop or don't
5607 print. */
5608 if (!bs->stop || !bs->print)
5609 bs->print_it = print_it_noop;
5612 /* If we aren't stopping, the value of some hardware watchpoint may
5613 not have changed, but the intermediate memory locations we are
5614 watching may have. Don't bother if we're stopping; this will get
5615 done later. */
5616 need_remove_insert = 0;
5617 if (! bpstat_causes_stop (bs_head))
5618 for (bs = bs_head; bs != NULL; bs = bs->next)
5619 if (!bs->stop
5620 && bs->breakpoint_at
5621 && is_hardware_watchpoint (bs->breakpoint_at))
5623 struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5625 update_watchpoint (w, 0 /* don't reparse. */);
5626 need_remove_insert = 1;
5629 if (need_remove_insert)
5630 update_global_location_list (UGLL_MAY_INSERT);
5631 else if (removed_any)
5632 update_global_location_list (UGLL_DONT_INSERT);
5634 return bs_head;
5637 /* See breakpoint.h. */
5639 bpstat *
5640 bpstat_stop_status_nowatch (const address_space *aspace, CORE_ADDR bp_addr,
5641 thread_info *thread, const target_waitstatus &ws)
5643 gdb_assert (!target_stopped_by_watchpoint ());
5645 /* Clear all watchpoints' 'watchpoint_triggered' value from a
5646 previous stop to avoid confusing bpstat_stop_status. */
5647 watchpoints_triggered (ws);
5649 return bpstat_stop_status (aspace, bp_addr, thread, ws);
5652 static void
5653 handle_jit_event (CORE_ADDR address)
5655 struct gdbarch *gdbarch;
5657 infrun_debug_printf ("handling bp_jit_event");
5659 /* Switch terminal for any messages produced by
5660 breakpoint_re_set. */
5661 target_terminal::ours_for_output ();
5663 gdbarch = get_frame_arch (get_current_frame ());
5664 /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5665 thus it is expected that its objectfile can be found through
5666 minimal symbol lookup. If it doesn't work (and assert fails), it
5667 most likely means that `jit_breakpoint_re_set` was changes and this
5668 function needs to be updated too. */
5669 bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5670 gdb_assert (jit_bp_sym.objfile != nullptr);
5671 jit_event_handler (gdbarch, jit_bp_sym.objfile);
5673 target_terminal::inferior ();
5676 /* Prepare WHAT final decision for infrun. */
5678 /* Decide what infrun needs to do with this bpstat. */
5680 struct bpstat_what
5681 bpstat_what (bpstat *bs_head)
5683 struct bpstat_what retval;
5684 bpstat *bs;
5686 retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5687 retval.call_dummy = STOP_NONE;
5688 retval.is_longjmp = false;
5690 for (bs = bs_head; bs != NULL; bs = bs->next)
5692 /* Extract this BS's action. After processing each BS, we check
5693 if its action overrides all we've seem so far. */
5694 enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5695 enum bptype bptype;
5697 if (bs->breakpoint_at == NULL)
5699 /* I suspect this can happen if it was a momentary
5700 breakpoint which has since been deleted. */
5701 bptype = bp_none;
5703 else
5704 bptype = bs->breakpoint_at->type;
5706 switch (bptype)
5708 case bp_none:
5709 break;
5710 case bp_breakpoint:
5711 case bp_hardware_breakpoint:
5712 case bp_single_step:
5713 case bp_until:
5714 case bp_finish:
5715 case bp_shlib_event:
5716 if (bs->stop)
5718 if (bs->print)
5719 this_action = BPSTAT_WHAT_STOP_NOISY;
5720 else
5721 this_action = BPSTAT_WHAT_STOP_SILENT;
5723 else
5724 this_action = BPSTAT_WHAT_SINGLE;
5725 break;
5726 case bp_watchpoint:
5727 case bp_hardware_watchpoint:
5728 case bp_read_watchpoint:
5729 case bp_access_watchpoint:
5730 if (bs->stop)
5732 if (bs->print)
5733 this_action = BPSTAT_WHAT_STOP_NOISY;
5734 else
5735 this_action = BPSTAT_WHAT_STOP_SILENT;
5737 else
5739 /* There was a watchpoint, but we're not stopping.
5740 This requires no further action. */
5742 break;
5743 case bp_longjmp:
5744 case bp_longjmp_call_dummy:
5745 case bp_exception:
5746 if (bs->stop)
5748 this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5749 retval.is_longjmp = bptype != bp_exception;
5751 else
5752 this_action = BPSTAT_WHAT_SINGLE;
5753 break;
5754 case bp_longjmp_resume:
5755 case bp_exception_resume:
5756 if (bs->stop)
5758 this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5759 retval.is_longjmp = bptype == bp_longjmp_resume;
5761 else
5762 this_action = BPSTAT_WHAT_SINGLE;
5763 break;
5764 case bp_step_resume:
5765 if (bs->stop)
5766 this_action = BPSTAT_WHAT_STEP_RESUME;
5767 else
5769 /* It is for the wrong frame. */
5770 this_action = BPSTAT_WHAT_SINGLE;
5772 break;
5773 case bp_hp_step_resume:
5774 if (bs->stop)
5775 this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5776 else
5778 /* It is for the wrong frame. */
5779 this_action = BPSTAT_WHAT_SINGLE;
5781 break;
5782 case bp_watchpoint_scope:
5783 case bp_thread_event:
5784 case bp_overlay_event:
5785 case bp_longjmp_master:
5786 case bp_std_terminate_master:
5787 case bp_exception_master:
5788 this_action = BPSTAT_WHAT_SINGLE;
5789 break;
5790 case bp_catchpoint:
5791 if (bs->stop)
5793 if (bs->print)
5794 this_action = BPSTAT_WHAT_STOP_NOISY;
5795 else
5796 this_action = BPSTAT_WHAT_STOP_SILENT;
5798 else
5800 /* Some catchpoints are implemented with breakpoints.
5801 For those, we need to step over the breakpoint. */
5802 if (bs->bp_location_at->loc_type == bp_loc_software_breakpoint
5803 || bs->bp_location_at->loc_type == bp_loc_hardware_breakpoint)
5804 this_action = BPSTAT_WHAT_SINGLE;
5806 break;
5807 case bp_jit_event:
5808 this_action = BPSTAT_WHAT_SINGLE;
5809 break;
5810 case bp_call_dummy:
5811 /* Make sure the action is stop (silent or noisy),
5812 so infrun.c pops the dummy frame. */
5813 retval.call_dummy = STOP_STACK_DUMMY;
5814 this_action = BPSTAT_WHAT_STOP_SILENT;
5815 break;
5816 case bp_std_terminate:
5817 /* Make sure the action is stop (silent or noisy),
5818 so infrun.c pops the dummy frame. */
5819 retval.call_dummy = STOP_STD_TERMINATE;
5820 this_action = BPSTAT_WHAT_STOP_SILENT;
5821 break;
5822 case bp_tracepoint:
5823 case bp_fast_tracepoint:
5824 case bp_static_tracepoint:
5825 case bp_static_marker_tracepoint:
5826 /* Tracepoint hits should not be reported back to GDB, and
5827 if one got through somehow, it should have been filtered
5828 out already. */
5829 internal_error (__FILE__, __LINE__,
5830 _("bpstat_what: tracepoint encountered"));
5831 break;
5832 case bp_gnu_ifunc_resolver:
5833 /* Step over it (and insert bp_gnu_ifunc_resolver_return). */
5834 this_action = BPSTAT_WHAT_SINGLE;
5835 break;
5836 case bp_gnu_ifunc_resolver_return:
5837 /* The breakpoint will be removed, execution will restart from the
5838 PC of the former breakpoint. */
5839 this_action = BPSTAT_WHAT_KEEP_CHECKING;
5840 break;
5842 case bp_dprintf:
5843 if (bs->stop)
5844 this_action = BPSTAT_WHAT_STOP_SILENT;
5845 else
5846 this_action = BPSTAT_WHAT_SINGLE;
5847 break;
5849 default:
5850 internal_error (__FILE__, __LINE__,
5851 _("bpstat_what: unhandled bptype %d"), (int) bptype);
5854 retval.main_action = std::max (retval.main_action, this_action);
5857 return retval;
5860 void
5861 bpstat_run_callbacks (bpstat *bs_head)
5863 bpstat *bs;
5865 for (bs = bs_head; bs != NULL; bs = bs->next)
5867 struct breakpoint *b = bs->breakpoint_at;
5869 if (b == NULL)
5870 continue;
5871 switch (b->type)
5873 case bp_jit_event:
5874 handle_jit_event (bs->bp_location_at->address);
5875 break;
5876 case bp_gnu_ifunc_resolver:
5877 gnu_ifunc_resolver_stop ((code_breakpoint *) b);
5878 break;
5879 case bp_gnu_ifunc_resolver_return:
5880 gnu_ifunc_resolver_return_stop ((code_breakpoint *) b);
5881 break;
5886 /* See breakpoint.h. */
5888 bool
5889 bpstat_should_step ()
5891 for (breakpoint *b : all_breakpoints ())
5892 if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5893 return true;
5895 return false;
5898 /* See breakpoint.h. */
5900 bool
5901 bpstat_causes_stop (bpstat *bs)
5903 for (; bs != NULL; bs = bs->next)
5904 if (bs->stop)
5905 return true;
5907 return false;
5912 /* Compute a number of spaces suitable to indent the next line
5913 so it starts at the position corresponding to the table column
5914 named COL_NAME in the currently active table of UIOUT. */
5916 static int
5917 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5919 int i, total_width, width, align;
5920 const char *text;
5922 total_width = 0;
5923 for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5925 if (strcmp (text, col_name) == 0)
5926 return total_width;
5928 total_width += width + 1;
5931 return 0;
5934 /* Determine if the locations of this breakpoint will have their conditions
5935 evaluated by the target, host or a mix of both. Returns the following:
5937 "host": Host evals condition.
5938 "host or target": Host or Target evals condition.
5939 "target": Target evals condition.
5942 static const char *
5943 bp_condition_evaluator (const breakpoint *b)
5945 char host_evals = 0;
5946 char target_evals = 0;
5948 if (!b)
5949 return NULL;
5951 if (!is_breakpoint (b))
5952 return NULL;
5954 if (gdb_evaluates_breakpoint_condition_p ()
5955 || !target_supports_evaluation_of_breakpoint_conditions ())
5956 return condition_evaluation_host;
5958 for (bp_location *bl : b->locations ())
5960 if (bl->cond_bytecode)
5961 target_evals++;
5962 else
5963 host_evals++;
5966 if (host_evals && target_evals)
5967 return condition_evaluation_both;
5968 else if (target_evals)
5969 return condition_evaluation_target;
5970 else
5971 return condition_evaluation_host;
5974 /* Determine the breakpoint location's condition evaluator. This is
5975 similar to bp_condition_evaluator, but for locations. */
5977 static const char *
5978 bp_location_condition_evaluator (struct bp_location *bl)
5980 if (bl && !is_breakpoint (bl->owner))
5981 return NULL;
5983 if (gdb_evaluates_breakpoint_condition_p ()
5984 || !target_supports_evaluation_of_breakpoint_conditions ())
5985 return condition_evaluation_host;
5987 if (bl && bl->cond_bytecode)
5988 return condition_evaluation_target;
5989 else
5990 return condition_evaluation_host;
5993 /* Print the LOC location out of the list of B->LOC locations. */
5995 static void
5996 print_breakpoint_location (const breakpoint *b,
5997 struct bp_location *loc)
5999 struct ui_out *uiout = current_uiout;
6001 scoped_restore_current_program_space restore_pspace;
6003 if (loc != NULL && loc->shlib_disabled)
6004 loc = NULL;
6006 if (loc != NULL)
6007 set_current_program_space (loc->pspace);
6009 if (b->display_canonical)
6010 uiout->field_string ("what", b->locspec->to_string ());
6011 else if (loc && loc->symtab)
6013 const struct symbol *sym = loc->symbol;
6015 if (sym)
6017 uiout->text ("in ");
6018 uiout->field_string ("func", sym->print_name (),
6019 function_name_style.style ());
6020 uiout->text (" ");
6021 uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6022 uiout->text ("at ");
6024 uiout->field_string ("file",
6025 symtab_to_filename_for_display (loc->symtab),
6026 file_name_style.style ());
6027 uiout->text (":");
6029 if (uiout->is_mi_like_p ())
6030 uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6032 uiout->field_signed ("line", loc->line_number);
6034 else if (loc)
6036 string_file stb;
6038 print_address_symbolic (loc->gdbarch, loc->address, &stb,
6039 demangle, "");
6040 uiout->field_stream ("at", stb);
6042 else
6044 uiout->field_string ("pending", b->locspec->to_string ());
6045 /* If extra_string is available, it could be holding a condition
6046 or dprintf arguments. In either case, make sure it is printed,
6047 too, but only for non-MI streams. */
6048 if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6050 if (b->type == bp_dprintf)
6051 uiout->text (",");
6052 else
6053 uiout->text (" ");
6054 uiout->text (b->extra_string.get ());
6058 if (loc && is_breakpoint (b)
6059 && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6060 && bp_condition_evaluator (b) == condition_evaluation_both)
6062 uiout->text (" (");
6063 uiout->field_string ("evaluated-by",
6064 bp_location_condition_evaluator (loc));
6065 uiout->text (")");
6069 static const char *
6070 bptype_string (enum bptype type)
6072 struct ep_type_description
6074 enum bptype type;
6075 const char *description;
6077 static struct ep_type_description bptypes[] =
6079 {bp_none, "?deleted?"},
6080 {bp_breakpoint, "breakpoint"},
6081 {bp_hardware_breakpoint, "hw breakpoint"},
6082 {bp_single_step, "sw single-step"},
6083 {bp_until, "until"},
6084 {bp_finish, "finish"},
6085 {bp_watchpoint, "watchpoint"},
6086 {bp_hardware_watchpoint, "hw watchpoint"},
6087 {bp_read_watchpoint, "read watchpoint"},
6088 {bp_access_watchpoint, "acc watchpoint"},
6089 {bp_longjmp, "longjmp"},
6090 {bp_longjmp_resume, "longjmp resume"},
6091 {bp_longjmp_call_dummy, "longjmp for call dummy"},
6092 {bp_exception, "exception"},
6093 {bp_exception_resume, "exception resume"},
6094 {bp_step_resume, "step resume"},
6095 {bp_hp_step_resume, "high-priority step resume"},
6096 {bp_watchpoint_scope, "watchpoint scope"},
6097 {bp_call_dummy, "call dummy"},
6098 {bp_std_terminate, "std::terminate"},
6099 {bp_shlib_event, "shlib events"},
6100 {bp_thread_event, "thread events"},
6101 {bp_overlay_event, "overlay events"},
6102 {bp_longjmp_master, "longjmp master"},
6103 {bp_std_terminate_master, "std::terminate master"},
6104 {bp_exception_master, "exception master"},
6105 {bp_catchpoint, "catchpoint"},
6106 {bp_tracepoint, "tracepoint"},
6107 {bp_fast_tracepoint, "fast tracepoint"},
6108 {bp_static_tracepoint, "static tracepoint"},
6109 {bp_static_marker_tracepoint, "static marker tracepoint"},
6110 {bp_dprintf, "dprintf"},
6111 {bp_jit_event, "jit events"},
6112 {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6113 {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6116 if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6117 || ((int) type != bptypes[(int) type].type))
6118 internal_error (__FILE__, __LINE__,
6119 _("bptypes table does not describe type #%d."),
6120 (int) type);
6122 return bptypes[(int) type].description;
6125 /* For MI, output a field named 'thread-groups' with a list as the value.
6126 For CLI, prefix the list with the string 'inf'. */
6128 static void
6129 output_thread_groups (struct ui_out *uiout,
6130 const char *field_name,
6131 const std::vector<int> &inf_nums,
6132 int mi_only)
6134 int is_mi = uiout->is_mi_like_p ();
6136 /* For backward compatibility, don't display inferiors in CLI unless
6137 there are several. Always display them for MI. */
6138 if (!is_mi && mi_only)
6139 return;
6141 ui_out_emit_list list_emitter (uiout, field_name);
6143 for (size_t i = 0; i < inf_nums.size (); i++)
6145 if (is_mi)
6147 char mi_group[10];
6149 xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6150 uiout->field_string (NULL, mi_group);
6152 else
6154 if (i == 0)
6155 uiout->text (" inf ");
6156 else
6157 uiout->text (", ");
6159 uiout->text (plongest (inf_nums[i]));
6164 /* Print B to gdb_stdout. If RAW_LOC, print raw breakpoint locations
6165 instead of going via breakpoint_ops::print_one. This makes "maint
6166 info breakpoints" show the software breakpoint locations of
6167 catchpoints, which are considered internal implementation
6168 detail. Returns true if RAW_LOC is false and if the breakpoint's
6169 print_one method did something; false otherwise. */
6171 static bool
6172 print_one_breakpoint_location (struct breakpoint *b,
6173 struct bp_location *loc,
6174 int loc_number,
6175 struct bp_location **last_loc,
6176 int allflag, bool raw_loc)
6178 struct command_line *l;
6179 static char bpenables[] = "nynny";
6181 struct ui_out *uiout = current_uiout;
6182 int header_of_multiple = 0;
6183 int part_of_multiple = (loc != NULL);
6184 struct value_print_options opts;
6186 get_user_print_options (&opts);
6188 gdb_assert (!loc || loc_number != 0);
6189 /* See comment in print_one_breakpoint concerning treatment of
6190 breakpoints with single disabled location. */
6191 if (loc == NULL
6192 && (b->loc != NULL
6193 && (b->loc->next != NULL
6194 || !b->loc->enabled || b->loc->disabled_by_cond)))
6195 header_of_multiple = 1;
6196 if (loc == NULL)
6197 loc = b->loc;
6199 annotate_record ();
6201 /* 1 */
6202 annotate_field (0);
6203 if (part_of_multiple)
6204 uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6205 else
6206 uiout->field_signed ("number", b->number);
6208 /* 2 */
6209 annotate_field (1);
6210 if (part_of_multiple)
6211 uiout->field_skip ("type");
6212 else
6213 uiout->field_string ("type", bptype_string (b->type));
6215 /* 3 */
6216 annotate_field (2);
6217 if (part_of_multiple)
6218 uiout->field_skip ("disp");
6219 else
6220 uiout->field_string ("disp", bpdisp_text (b->disposition));
6222 /* 4 */
6223 annotate_field (3);
6224 if (part_of_multiple)
6226 /* For locations that are disabled because of an invalid
6227 condition, display "N*" on the CLI, where "*" refers to a
6228 footnote below the table. For MI, simply display a "N"
6229 without a footnote. On the CLI, for enabled locations whose
6230 breakpoint is disabled, display "y-". */
6231 auto get_enable_state = [uiout, loc] () -> const char *
6233 if (uiout->is_mi_like_p ())
6235 if (loc->disabled_by_cond)
6236 return "N";
6237 else if (!loc->enabled)
6238 return "n";
6239 else
6240 return "y";
6242 else
6244 if (loc->disabled_by_cond)
6245 return "N*";
6246 else if (!loc->enabled)
6247 return "n";
6248 else if (!breakpoint_enabled (loc->owner))
6249 return "y-";
6250 else
6251 return "y";
6254 uiout->field_string ("enabled", get_enable_state ());
6256 else
6257 uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6259 /* 5 and 6 */
6260 bool result = false;
6261 if (!raw_loc && b->print_one (last_loc))
6262 result = true;
6263 else
6265 if (is_watchpoint (b))
6267 struct watchpoint *w = (struct watchpoint *) b;
6269 /* Field 4, the address, is omitted (which makes the columns
6270 not line up too nicely with the headers, but the effect
6271 is relatively readable). */
6272 if (opts.addressprint)
6273 uiout->field_skip ("addr");
6274 annotate_field (5);
6275 uiout->field_string ("what", w->exp_string.get ());
6277 else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6278 || is_ada_exception_catchpoint (b))
6280 if (opts.addressprint)
6282 annotate_field (4);
6283 if (header_of_multiple)
6284 uiout->field_string ("addr", "<MULTIPLE>",
6285 metadata_style.style ());
6286 else if (b->loc == NULL || loc->shlib_disabled)
6287 uiout->field_string ("addr", "<PENDING>",
6288 metadata_style.style ());
6289 else
6290 uiout->field_core_addr ("addr",
6291 loc->gdbarch, loc->address);
6293 annotate_field (5);
6294 if (!header_of_multiple)
6295 print_breakpoint_location (b, loc);
6296 if (b->loc)
6297 *last_loc = b->loc;
6301 if (loc != NULL && !header_of_multiple)
6303 std::vector<int> inf_nums;
6304 int mi_only = 1;
6306 for (inferior *inf : all_inferiors ())
6308 if (inf->pspace == loc->pspace)
6309 inf_nums.push_back (inf->num);
6312 /* For backward compatibility, don't display inferiors in CLI unless
6313 there are several. Always display for MI. */
6314 if (allflag
6315 || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6316 && (program_spaces.size () > 1
6317 || number_of_inferiors () > 1)
6318 /* LOC is for existing B, it cannot be in
6319 moribund_locations and thus having NULL OWNER. */
6320 && loc->owner->type != bp_catchpoint))
6321 mi_only = 0;
6322 output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6325 if (!part_of_multiple)
6327 if (b->thread != -1)
6329 /* FIXME: This seems to be redundant and lost here; see the
6330 "stop only in" line a little further down. */
6331 uiout->text (" thread ");
6332 uiout->field_signed ("thread", b->thread);
6334 else if (b->task != 0)
6336 uiout->text (" task ");
6337 uiout->field_signed ("task", b->task);
6341 uiout->text ("\n");
6343 if (!part_of_multiple)
6344 b->print_one_detail (uiout);
6346 if (part_of_multiple && frame_id_p (b->frame_id))
6348 annotate_field (6);
6349 uiout->text ("\tstop only in stack frame at ");
6350 /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6351 the frame ID. */
6352 uiout->field_core_addr ("frame",
6353 b->gdbarch, b->frame_id.stack_addr);
6354 uiout->text ("\n");
6357 if (!part_of_multiple && b->cond_string)
6359 annotate_field (7);
6360 if (is_tracepoint (b))
6361 uiout->text ("\ttrace only if ");
6362 else
6363 uiout->text ("\tstop only if ");
6364 uiout->field_string ("cond", b->cond_string.get ());
6366 /* Print whether the target is doing the breakpoint's condition
6367 evaluation. If GDB is doing the evaluation, don't print anything. */
6368 if (is_breakpoint (b)
6369 && breakpoint_condition_evaluation_mode ()
6370 == condition_evaluation_target)
6372 uiout->message (" (%pF evals)",
6373 string_field ("evaluated-by",
6374 bp_condition_evaluator (b)));
6376 uiout->text ("\n");
6379 if (!part_of_multiple && b->thread != -1)
6381 /* FIXME should make an annotation for this. */
6382 uiout->text ("\tstop only in thread ");
6383 if (uiout->is_mi_like_p ())
6384 uiout->field_signed ("thread", b->thread);
6385 else
6387 struct thread_info *thr = find_thread_global_id (b->thread);
6389 uiout->field_string ("thread", print_thread_id (thr));
6391 uiout->text ("\n");
6394 if (!part_of_multiple)
6396 if (b->hit_count)
6398 /* FIXME should make an annotation for this. */
6399 if (is_catchpoint (b))
6400 uiout->text ("\tcatchpoint");
6401 else if (is_tracepoint (b))
6402 uiout->text ("\ttracepoint");
6403 else
6404 uiout->text ("\tbreakpoint");
6405 uiout->text (" already hit ");
6406 uiout->field_signed ("times", b->hit_count);
6407 if (b->hit_count == 1)
6408 uiout->text (" time\n");
6409 else
6410 uiout->text (" times\n");
6412 else
6414 /* Output the count also if it is zero, but only if this is mi. */
6415 if (uiout->is_mi_like_p ())
6416 uiout->field_signed ("times", b->hit_count);
6420 if (!part_of_multiple && b->ignore_count)
6422 annotate_field (8);
6423 uiout->message ("\tignore next %pF hits\n",
6424 signed_field ("ignore", b->ignore_count));
6427 /* Note that an enable count of 1 corresponds to "enable once"
6428 behavior, which is reported by the combination of enablement and
6429 disposition, so we don't need to mention it here. */
6430 if (!part_of_multiple && b->enable_count > 1)
6432 annotate_field (8);
6433 uiout->text ("\tdisable after ");
6434 /* Tweak the wording to clarify that ignore and enable counts
6435 are distinct, and have additive effect. */
6436 if (b->ignore_count)
6437 uiout->text ("additional ");
6438 else
6439 uiout->text ("next ");
6440 uiout->field_signed ("enable", b->enable_count);
6441 uiout->text (" hits\n");
6444 if (!part_of_multiple && is_tracepoint (b))
6446 struct tracepoint *tp = (struct tracepoint *) b;
6448 if (tp->traceframe_usage)
6450 uiout->text ("\ttrace buffer usage ");
6451 uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6452 uiout->text (" bytes\n");
6456 l = b->commands ? b->commands.get () : NULL;
6457 if (!part_of_multiple && l)
6459 annotate_field (9);
6460 ui_out_emit_tuple tuple_emitter (uiout, "script");
6461 print_command_lines (uiout, l, 4);
6464 if (is_tracepoint (b))
6466 struct tracepoint *t = (struct tracepoint *) b;
6468 if (!part_of_multiple && t->pass_count)
6470 annotate_field (10);
6471 uiout->text ("\tpass count ");
6472 uiout->field_signed ("pass", t->pass_count);
6473 uiout->text (" \n");
6476 /* Don't display it when tracepoint or tracepoint location is
6477 pending. */
6478 if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6480 annotate_field (11);
6482 if (uiout->is_mi_like_p ())
6483 uiout->field_string ("installed",
6484 loc->inserted ? "y" : "n");
6485 else
6487 if (loc->inserted)
6488 uiout->text ("\t");
6489 else
6490 uiout->text ("\tnot ");
6491 uiout->text ("installed on target\n");
6496 if (uiout->is_mi_like_p () && !part_of_multiple)
6498 if (is_watchpoint (b))
6500 struct watchpoint *w = (struct watchpoint *) b;
6502 uiout->field_string ("original-location", w->exp_string.get ());
6504 else if (b->locspec != nullptr)
6506 const char *str = b->locspec->to_string ();
6507 if (str != nullptr)
6508 uiout->field_string ("original-location", str);
6512 return result;
6515 /* See breakpoint.h. */
6517 bool fix_multi_location_breakpoint_output_globally = false;
6519 static void
6520 print_one_breakpoint (struct breakpoint *b,
6521 struct bp_location **last_loc,
6522 int allflag)
6524 struct ui_out *uiout = current_uiout;
6525 bool use_fixed_output
6526 = (uiout->test_flags (fix_multi_location_breakpoint_output)
6527 || fix_multi_location_breakpoint_output_globally);
6529 gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6530 bool printed = print_one_breakpoint_location (b, NULL, 0, last_loc,
6531 allflag, false);
6533 /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6534 are outside. */
6535 if (!use_fixed_output)
6536 bkpt_tuple_emitter.reset ();
6538 /* If this breakpoint has custom print function,
6539 it's already printed. Otherwise, print individual
6540 locations, if any. */
6541 if (!printed || allflag)
6543 /* If breakpoint has a single location that is disabled, we
6544 print it as if it had several locations, since otherwise it's
6545 hard to represent "breakpoint enabled, location disabled"
6546 situation.
6548 Note that while hardware watchpoints have several locations
6549 internally, that's not a property exposed to users.
6551 Likewise, while catchpoints may be implemented with
6552 breakpoints (e.g., catch throw), that's not a property
6553 exposed to users. We do however display the internal
6554 breakpoint locations with "maint info breakpoints". */
6555 if (!is_hardware_watchpoint (b)
6556 && (!is_catchpoint (b) || is_exception_catchpoint (b)
6557 || is_ada_exception_catchpoint (b))
6558 && (allflag
6559 || (b->loc && (b->loc->next
6560 || !b->loc->enabled
6561 || b->loc->disabled_by_cond))))
6563 gdb::optional<ui_out_emit_list> locations_list;
6565 /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6566 MI record. For later versions, place breakpoint locations in a
6567 list. */
6568 if (uiout->is_mi_like_p () && use_fixed_output)
6569 locations_list.emplace (uiout, "locations");
6571 int n = 1;
6572 for (bp_location *loc : b->locations ())
6574 ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6575 print_one_breakpoint_location (b, loc, n, last_loc,
6576 allflag, allflag);
6577 n++;
6583 static int
6584 breakpoint_address_bits (struct breakpoint *b)
6586 int print_address_bits = 0;
6588 for (bp_location *loc : b->locations ())
6590 if (!bl_address_is_meaningful (loc))
6591 continue;
6593 int addr_bit = gdbarch_addr_bit (loc->gdbarch);
6594 if (addr_bit > print_address_bits)
6595 print_address_bits = addr_bit;
6598 return print_address_bits;
6601 /* See breakpoint.h. */
6603 void
6604 print_breakpoint (breakpoint *b)
6606 struct bp_location *dummy_loc = NULL;
6607 print_one_breakpoint (b, &dummy_loc, 0);
6610 /* Return true if this breakpoint was set by the user, false if it is
6611 internal or momentary. */
6614 user_breakpoint_p (struct breakpoint *b)
6616 return b->number > 0;
6619 /* See breakpoint.h. */
6622 pending_breakpoint_p (struct breakpoint *b)
6624 return b->loc == NULL;
6627 /* Print information on breakpoints (including watchpoints and tracepoints).
6629 If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6630 understood by number_or_range_parser. Only breakpoints included in this
6631 list are then printed.
6633 If SHOW_INTERNAL is true, print internal breakpoints.
6635 If FILTER is non-NULL, call it on each breakpoint and only include the
6636 ones for which it returns true.
6638 Return the total number of breakpoints listed. */
6640 static int
6641 breakpoint_1 (const char *bp_num_list, bool show_internal,
6642 bool (*filter) (const struct breakpoint *))
6644 struct bp_location *last_loc = NULL;
6645 int nr_printable_breakpoints;
6646 struct value_print_options opts;
6647 int print_address_bits = 0;
6648 int print_type_col_width = 14;
6649 struct ui_out *uiout = current_uiout;
6650 bool has_disabled_by_cond_location = false;
6652 get_user_print_options (&opts);
6654 /* Compute the number of rows in the table, as well as the size
6655 required for address fields. */
6656 nr_printable_breakpoints = 0;
6657 for (breakpoint *b : all_breakpoints ())
6659 /* If we have a filter, only list the breakpoints it accepts. */
6660 if (filter && !filter (b))
6661 continue;
6663 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6664 accept. Skip the others. */
6665 if (bp_num_list != NULL && *bp_num_list != '\0')
6667 if (show_internal && parse_and_eval_long (bp_num_list) != b->number)
6668 continue;
6669 if (!show_internal && !number_is_in_list (bp_num_list, b->number))
6670 continue;
6673 if (show_internal || user_breakpoint_p (b))
6675 int addr_bit, type_len;
6677 addr_bit = breakpoint_address_bits (b);
6678 if (addr_bit > print_address_bits)
6679 print_address_bits = addr_bit;
6681 type_len = strlen (bptype_string (b->type));
6682 if (type_len > print_type_col_width)
6683 print_type_col_width = type_len;
6685 nr_printable_breakpoints++;
6690 ui_out_emit_table table_emitter (uiout,
6691 opts.addressprint ? 6 : 5,
6692 nr_printable_breakpoints,
6693 "BreakpointTable");
6695 if (nr_printable_breakpoints > 0)
6696 annotate_breakpoints_headers ();
6697 if (nr_printable_breakpoints > 0)
6698 annotate_field (0);
6699 uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6700 if (nr_printable_breakpoints > 0)
6701 annotate_field (1);
6702 uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6703 if (nr_printable_breakpoints > 0)
6704 annotate_field (2);
6705 uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6706 if (nr_printable_breakpoints > 0)
6707 annotate_field (3);
6708 uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6709 if (opts.addressprint)
6711 if (nr_printable_breakpoints > 0)
6712 annotate_field (4);
6713 if (print_address_bits <= 32)
6714 uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6715 else
6716 uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6718 if (nr_printable_breakpoints > 0)
6719 annotate_field (5);
6720 uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6721 uiout->table_body ();
6722 if (nr_printable_breakpoints > 0)
6723 annotate_breakpoints_table ();
6725 for (breakpoint *b : all_breakpoints ())
6727 QUIT;
6728 /* If we have a filter, only list the breakpoints it accepts. */
6729 if (filter && !filter (b))
6730 continue;
6732 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6733 accept. Skip the others. */
6735 if (bp_num_list != NULL && *bp_num_list != '\0')
6737 if (show_internal) /* maintenance info breakpoint */
6739 if (parse_and_eval_long (bp_num_list) != b->number)
6740 continue;
6742 else /* all others */
6744 if (!number_is_in_list (bp_num_list, b->number))
6745 continue;
6748 /* We only print out user settable breakpoints unless the
6749 show_internal is set. */
6750 if (show_internal || user_breakpoint_p (b))
6752 print_one_breakpoint (b, &last_loc, show_internal);
6753 for (bp_location *loc : b->locations ())
6754 if (loc->disabled_by_cond)
6755 has_disabled_by_cond_location = true;
6760 if (nr_printable_breakpoints == 0)
6762 /* If there's a filter, let the caller decide how to report
6763 empty list. */
6764 if (!filter)
6766 if (bp_num_list == NULL || *bp_num_list == '\0')
6767 uiout->message ("No breakpoints or watchpoints.\n");
6768 else
6769 uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6770 bp_num_list);
6773 else
6775 if (last_loc && !server_command)
6776 set_next_address (last_loc->gdbarch, last_loc->address);
6778 if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
6779 uiout->message (_("(*): Breakpoint condition is invalid at this "
6780 "location.\n"));
6783 /* FIXME? Should this be moved up so that it is only called when
6784 there have been breakpoints? */
6785 annotate_breakpoints_table_end ();
6787 return nr_printable_breakpoints;
6790 /* Display the value of default-collect in a way that is generally
6791 compatible with the breakpoint list. */
6793 static void
6794 default_collect_info (void)
6796 struct ui_out *uiout = current_uiout;
6798 /* If it has no value (which is frequently the case), say nothing; a
6799 message like "No default-collect." gets in user's face when it's
6800 not wanted. */
6801 if (default_collect.empty ())
6802 return;
6804 /* The following phrase lines up nicely with per-tracepoint collect
6805 actions. */
6806 uiout->text ("default collect ");
6807 uiout->field_string ("default-collect", default_collect);
6808 uiout->text (" \n");
6811 static void
6812 info_breakpoints_command (const char *args, int from_tty)
6814 breakpoint_1 (args, false, NULL);
6816 default_collect_info ();
6819 static void
6820 info_watchpoints_command (const char *args, int from_tty)
6822 int num_printed = breakpoint_1 (args, false, is_watchpoint);
6823 struct ui_out *uiout = current_uiout;
6825 if (num_printed == 0)
6827 if (args == NULL || *args == '\0')
6828 uiout->message ("No watchpoints.\n");
6829 else
6830 uiout->message ("No watchpoint matching '%s'.\n", args);
6834 static void
6835 maintenance_info_breakpoints (const char *args, int from_tty)
6837 breakpoint_1 (args, true, NULL);
6839 default_collect_info ();
6842 static int
6843 breakpoint_has_pc (struct breakpoint *b,
6844 struct program_space *pspace,
6845 CORE_ADDR pc, struct obj_section *section)
6847 for (bp_location *bl : b->locations ())
6849 if (bl->pspace == pspace
6850 && bl->address == pc
6851 && (!overlay_debugging || bl->section == section))
6852 return 1;
6854 return 0;
6857 /* See breakpoint.h. */
6859 void
6860 describe_other_breakpoints (struct gdbarch *gdbarch,
6861 struct program_space *pspace, CORE_ADDR pc,
6862 struct obj_section *section, int thread)
6864 int others = 0;
6866 for (breakpoint *b : all_breakpoints ())
6867 others += (user_breakpoint_p (b)
6868 && breakpoint_has_pc (b, pspace, pc, section));
6870 if (others > 0)
6872 if (others == 1)
6873 gdb_printf (_("Note: breakpoint "));
6874 else /* if (others == ???) */
6875 gdb_printf (_("Note: breakpoints "));
6876 for (breakpoint *b : all_breakpoints ())
6877 if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6879 others--;
6880 gdb_printf ("%d", b->number);
6881 if (b->thread == -1 && thread != -1)
6882 gdb_printf (" (all threads)");
6883 else if (b->thread != -1)
6884 gdb_printf (" (thread %d)", b->thread);
6885 gdb_printf ("%s%s ",
6886 ((b->enable_state == bp_disabled
6887 || b->enable_state == bp_call_disabled)
6888 ? " (disabled)"
6889 : ""),
6890 (others > 1) ? ","
6891 : ((others == 1) ? " and" : ""));
6893 current_uiout->message (_("also set at pc %ps.\n"),
6894 styled_string (address_style.style (),
6895 paddress (gdbarch, pc)));
6900 /* Return true iff it is meaningful to use the address member of LOC.
6901 For some breakpoint types, the locations' address members are
6902 irrelevant and it makes no sense to attempt to compare them to
6903 other addresses (or use them for any other purpose either).
6905 More specifically, software watchpoints and catchpoints that are
6906 not backed by breakpoints always have a zero valued location
6907 address and we don't want to mark breakpoints of any of these types
6908 to be a duplicate of an actual breakpoint location at address
6909 zero. */
6911 static bool
6912 bl_address_is_meaningful (bp_location *loc)
6914 return loc->loc_type != bp_loc_other;
6917 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6918 true if LOC1 and LOC2 represent the same watchpoint location. */
6920 static int
6921 watchpoint_locations_match (struct bp_location *loc1,
6922 struct bp_location *loc2)
6924 struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6925 struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6927 /* Both of them must exist. */
6928 gdb_assert (w1 != NULL);
6929 gdb_assert (w2 != NULL);
6931 /* If the target can evaluate the condition expression in hardware,
6932 then we we need to insert both watchpoints even if they are at
6933 the same place. Otherwise the watchpoint will only trigger when
6934 the condition of whichever watchpoint was inserted evaluates to
6935 true, not giving a chance for GDB to check the condition of the
6936 other watchpoint. */
6937 if ((w1->cond_exp
6938 && target_can_accel_watchpoint_condition (loc1->address,
6939 loc1->length,
6940 loc1->watchpoint_type,
6941 w1->cond_exp.get ()))
6942 || (w2->cond_exp
6943 && target_can_accel_watchpoint_condition (loc2->address,
6944 loc2->length,
6945 loc2->watchpoint_type,
6946 w2->cond_exp.get ())))
6947 return 0;
6949 /* Note that this checks the owner's type, not the location's. In
6950 case the target does not support read watchpoints, but does
6951 support access watchpoints, we'll have bp_read_watchpoint
6952 watchpoints with hw_access locations. Those should be considered
6953 duplicates of hw_read locations. The hw_read locations will
6954 become hw_access locations later. */
6955 return (loc1->owner->type == loc2->owner->type
6956 && loc1->pspace->aspace == loc2->pspace->aspace
6957 && loc1->address == loc2->address
6958 && loc1->length == loc2->length);
6961 /* See breakpoint.h. */
6964 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6965 const address_space *aspace2, CORE_ADDR addr2)
6967 return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6968 || aspace1 == aspace2)
6969 && addr1 == addr2);
6972 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6973 {ASPACE1,ADDR1,LEN1}. In most targets, this can only be true if ASPACE1
6974 matches ASPACE2. On targets that have global breakpoints, the address
6975 space doesn't really matter. */
6977 static int
6978 breakpoint_address_match_range (const address_space *aspace1,
6979 CORE_ADDR addr1,
6980 int len1, const address_space *aspace2,
6981 CORE_ADDR addr2)
6983 return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6984 || aspace1 == aspace2)
6985 && addr2 >= addr1 && addr2 < addr1 + len1);
6988 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL. BL may be
6989 a ranged breakpoint. In most targets, a match happens only if ASPACE
6990 matches the breakpoint's address space. On targets that have global
6991 breakpoints, the address space doesn't really matter. */
6993 static int
6994 breakpoint_location_address_match (struct bp_location *bl,
6995 const address_space *aspace,
6996 CORE_ADDR addr)
6998 return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6999 aspace, addr)
7000 || (bl->length
7001 && breakpoint_address_match_range (bl->pspace->aspace,
7002 bl->address, bl->length,
7003 aspace, addr)));
7006 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7007 breakpoint BL. BL may be a ranged breakpoint. In most targets, a
7008 match happens only if ASPACE matches the breakpoint's address
7009 space. On targets that have global breakpoints, the address space
7010 doesn't really matter. */
7012 static int
7013 breakpoint_location_address_range_overlap (struct bp_location *bl,
7014 const address_space *aspace,
7015 CORE_ADDR addr, int len)
7017 if (gdbarch_has_global_breakpoints (target_gdbarch ())
7018 || bl->pspace->aspace == aspace)
7020 int bl_len = bl->length != 0 ? bl->length : 1;
7022 if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7023 return 1;
7025 return 0;
7028 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7029 Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7030 true, otherwise returns false. */
7032 static int
7033 tracepoint_locations_match (struct bp_location *loc1,
7034 struct bp_location *loc2)
7036 if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7037 /* Since tracepoint locations are never duplicated with others', tracepoint
7038 locations at the same address of different tracepoints are regarded as
7039 different locations. */
7040 return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7041 else
7042 return 0;
7045 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7046 (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
7047 the same location. If SW_HW_BPS_MATCH is true, then software
7048 breakpoint locations and hardware breakpoint locations match,
7049 otherwise they don't. */
7051 static int
7052 breakpoint_locations_match (struct bp_location *loc1,
7053 struct bp_location *loc2,
7054 bool sw_hw_bps_match)
7056 int hw_point1, hw_point2;
7058 /* Both of them must not be in moribund_locations. */
7059 gdb_assert (loc1->owner != NULL);
7060 gdb_assert (loc2->owner != NULL);
7062 hw_point1 = is_hardware_watchpoint (loc1->owner);
7063 hw_point2 = is_hardware_watchpoint (loc2->owner);
7065 if (hw_point1 != hw_point2)
7066 return 0;
7067 else if (hw_point1)
7068 return watchpoint_locations_match (loc1, loc2);
7069 else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7070 return tracepoint_locations_match (loc1, loc2);
7071 else
7072 /* We compare bp_location.length in order to cover ranged
7073 breakpoints. Keep this in sync with
7074 bp_location_is_less_than. */
7075 return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7076 loc2->pspace->aspace, loc2->address)
7077 && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
7078 && loc1->length == loc2->length);
7081 static void
7082 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7083 int bnum, int have_bnum)
7085 /* The longest string possibly returned by hex_string_custom
7086 is 50 chars. These must be at least that big for safety. */
7087 char astr1[64];
7088 char astr2[64];
7090 strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7091 strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7092 if (have_bnum)
7093 warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7094 bnum, astr1, astr2);
7095 else
7096 warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7099 /* Adjust a breakpoint's address to account for architectural
7100 constraints on breakpoint placement. Return the adjusted address.
7101 Note: Very few targets require this kind of adjustment. For most
7102 targets, this function is simply the identity function. */
7104 static CORE_ADDR
7105 adjust_breakpoint_address (struct gdbarch *gdbarch,
7106 CORE_ADDR bpaddr, enum bptype bptype)
7108 if (bptype == bp_watchpoint
7109 || bptype == bp_hardware_watchpoint
7110 || bptype == bp_read_watchpoint
7111 || bptype == bp_access_watchpoint
7112 || bptype == bp_catchpoint)
7114 /* Watchpoints and the various bp_catch_* eventpoints should not
7115 have their addresses modified. */
7116 return bpaddr;
7118 else if (bptype == bp_single_step)
7120 /* Single-step breakpoints should not have their addresses
7121 modified. If there's any architectural constrain that
7122 applies to this address, then it should have already been
7123 taken into account when the breakpoint was created in the
7124 first place. If we didn't do this, stepping through e.g.,
7125 Thumb-2 IT blocks would break. */
7126 return bpaddr;
7128 else
7130 CORE_ADDR adjusted_bpaddr = bpaddr;
7132 if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7134 /* Some targets have architectural constraints on the placement
7135 of breakpoint instructions. Obtain the adjusted address. */
7136 adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7139 adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
7141 /* An adjusted breakpoint address can significantly alter
7142 a user's expectations. Print a warning if an adjustment
7143 is required. */
7144 if (adjusted_bpaddr != bpaddr)
7145 breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7147 return adjusted_bpaddr;
7151 static bp_loc_type
7152 bp_location_from_bp_type (bptype type)
7154 switch (type)
7156 case bp_breakpoint:
7157 case bp_single_step:
7158 case bp_until:
7159 case bp_finish:
7160 case bp_longjmp:
7161 case bp_longjmp_resume:
7162 case bp_longjmp_call_dummy:
7163 case bp_exception:
7164 case bp_exception_resume:
7165 case bp_step_resume:
7166 case bp_hp_step_resume:
7167 case bp_watchpoint_scope:
7168 case bp_call_dummy:
7169 case bp_std_terminate:
7170 case bp_shlib_event:
7171 case bp_thread_event:
7172 case bp_overlay_event:
7173 case bp_jit_event:
7174 case bp_longjmp_master:
7175 case bp_std_terminate_master:
7176 case bp_exception_master:
7177 case bp_gnu_ifunc_resolver:
7178 case bp_gnu_ifunc_resolver_return:
7179 case bp_dprintf:
7180 return bp_loc_software_breakpoint;
7181 case bp_hardware_breakpoint:
7182 return bp_loc_hardware_breakpoint;
7183 case bp_hardware_watchpoint:
7184 case bp_read_watchpoint:
7185 case bp_access_watchpoint:
7186 return bp_loc_hardware_watchpoint;
7187 case bp_watchpoint:
7188 return bp_loc_software_watchpoint;
7189 case bp_catchpoint:
7190 case bp_tracepoint:
7191 case bp_fast_tracepoint:
7192 case bp_static_tracepoint:
7193 case bp_static_marker_tracepoint:
7194 return bp_loc_other;
7195 default:
7196 internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7200 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7202 this->owner = owner;
7203 this->cond_bytecode = NULL;
7204 this->shlib_disabled = 0;
7205 this->enabled = 1;
7206 this->disabled_by_cond = false;
7208 this->loc_type = type;
7210 if (this->loc_type == bp_loc_software_breakpoint
7211 || this->loc_type == bp_loc_hardware_breakpoint)
7212 mark_breakpoint_location_modified (this);
7214 incref ();
7217 bp_location::bp_location (breakpoint *owner)
7218 : bp_location::bp_location (owner,
7219 bp_location_from_bp_type (owner->type))
7223 /* Decrement reference count. If the reference count reaches 0,
7224 destroy the bp_location. Sets *BLP to NULL. */
7226 static void
7227 decref_bp_location (struct bp_location **blp)
7229 bp_location_ref_policy::decref (*blp);
7230 *blp = NULL;
7233 /* Add breakpoint B at the end of the global breakpoint chain. */
7235 static breakpoint *
7236 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7238 struct breakpoint *b1;
7239 struct breakpoint *result = b.get ();
7241 /* Add this breakpoint to the end of the chain so that a list of
7242 breakpoints will come out in order of increasing numbers. */
7244 b1 = breakpoint_chain;
7245 if (b1 == 0)
7246 breakpoint_chain = b.release ();
7247 else
7249 while (b1->next)
7250 b1 = b1->next;
7251 b1->next = b.release ();
7254 return result;
7257 /* Initialize loc->function_name. */
7259 static void
7260 set_breakpoint_location_function (struct bp_location *loc)
7262 gdb_assert (loc->owner != NULL);
7264 if (loc->owner->type == bp_breakpoint
7265 || loc->owner->type == bp_hardware_breakpoint
7266 || is_tracepoint (loc->owner))
7268 const char *function_name;
7270 if (loc->msymbol != NULL
7271 && (loc->msymbol->type () == mst_text_gnu_ifunc
7272 || loc->msymbol->type () == mst_data_gnu_ifunc))
7274 struct breakpoint *b = loc->owner;
7276 function_name = loc->msymbol->linkage_name ();
7278 if (b->type == bp_breakpoint && b->loc == loc
7279 && loc->next == NULL && b->related_breakpoint == b)
7281 /* Create only the whole new breakpoint of this type but do not
7282 mess more complicated breakpoints with multiple locations. */
7283 b->type = bp_gnu_ifunc_resolver;
7284 /* Remember the resolver's address for use by the return
7285 breakpoint. */
7286 loc->related_address = loc->address;
7289 else
7290 find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7292 if (function_name)
7293 loc->function_name = make_unique_xstrdup (function_name);
7297 /* Attempt to determine architecture of location identified by SAL. */
7298 struct gdbarch *
7299 get_sal_arch (struct symtab_and_line sal)
7301 if (sal.section)
7302 return sal.section->objfile->arch ();
7303 if (sal.symtab)
7304 return sal.symtab->compunit ()->objfile ()->arch ();
7306 return NULL;
7309 /* Call this routine when stepping and nexting to enable a breakpoint
7310 if we do a longjmp() or 'throw' in TP. FRAME is the frame which
7311 initiated the operation. */
7313 void
7314 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7316 int thread = tp->global_num;
7318 /* To avoid having to rescan all objfile symbols at every step,
7319 we maintain a list of continually-inserted but always disabled
7320 longjmp "master" breakpoints. Here, we simply create momentary
7321 clones of those and enable them for the requested thread. */
7322 for (breakpoint *b : all_breakpoints_safe ())
7323 if (b->pspace == current_program_space
7324 && (b->type == bp_longjmp_master
7325 || b->type == bp_exception_master))
7327 enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7328 /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7329 after their removal. */
7330 momentary_breakpoint_from_master (b, type, 1, thread);
7333 tp->initiating_frame = frame;
7336 /* Delete all longjmp breakpoints from THREAD. */
7337 void
7338 delete_longjmp_breakpoint (int thread)
7340 for (breakpoint *b : all_breakpoints_safe ())
7341 if (b->type == bp_longjmp || b->type == bp_exception)
7343 if (b->thread == thread)
7344 delete_breakpoint (b);
7348 void
7349 delete_longjmp_breakpoint_at_next_stop (int thread)
7351 for (breakpoint *b : all_breakpoints_safe ())
7352 if (b->type == bp_longjmp || b->type == bp_exception)
7354 if (b->thread == thread)
7355 b->disposition = disp_del_at_next_stop;
7359 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7360 INFERIOR_PTID thread. Chain them all by RELATED_BREAKPOINT and return
7361 pointer to any of them. Return NULL if this system cannot place longjmp
7362 breakpoints. */
7364 struct breakpoint *
7365 set_longjmp_breakpoint_for_call_dummy (void)
7367 breakpoint *retval = nullptr;
7369 for (breakpoint *b : all_breakpoints ())
7370 if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7372 int thread = inferior_thread ()->global_num;
7373 breakpoint *new_b
7374 = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7375 1, thread);
7377 /* Link NEW_B into the chain of RETVAL breakpoints. */
7379 gdb_assert (new_b->related_breakpoint == new_b);
7380 if (retval == NULL)
7381 retval = new_b;
7382 new_b->related_breakpoint = retval;
7383 while (retval->related_breakpoint != new_b->related_breakpoint)
7384 retval = retval->related_breakpoint;
7385 retval->related_breakpoint = new_b;
7388 return retval;
7391 /* Verify all existing dummy frames and their associated breakpoints for
7392 TP. Remove those which can no longer be found in the current frame
7393 stack.
7395 If the unwind fails then there is not sufficient information to discard
7396 dummy frames. In this case, elide the clean up and the dummy frames will
7397 be cleaned up next time this function is called from a location where
7398 unwinding is possible. */
7400 void
7401 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7403 struct breakpoint *b, *b_tmp;
7405 ALL_BREAKPOINTS_SAFE (b, b_tmp)
7406 if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7408 struct breakpoint *dummy_b = b->related_breakpoint;
7410 /* Find the bp_call_dummy breakpoint in the list of breakpoints
7411 chained off b->related_breakpoint. */
7412 while (dummy_b != b && dummy_b->type != bp_call_dummy)
7413 dummy_b = dummy_b->related_breakpoint;
7415 /* If there was no bp_call_dummy breakpoint then there's nothing
7416 more to do. Or, if the dummy frame associated with the
7417 bp_call_dummy is still on the stack then we need to leave this
7418 bp_call_dummy in place. */
7419 if (dummy_b->type != bp_call_dummy
7420 || frame_find_by_id (dummy_b->frame_id) != NULL)
7421 continue;
7423 /* We didn't find the dummy frame on the stack, this could be
7424 because we have longjmp'd to a stack frame that is previous to
7425 the dummy frame, or it could be because the stack unwind is
7426 broken at some point between the longjmp frame and the dummy
7427 frame.
7429 Next we figure out why the stack unwind stopped. If it looks
7430 like the unwind is complete then we assume the dummy frame has
7431 been jumped over, however, if the unwind stopped for an
7432 unexpected reason then we assume the stack unwind is currently
7433 broken, and that we will (eventually) return to the dummy
7434 frame.
7436 It might be tempting to consider using frame_id_inner here, but
7437 that is not safe. There is no guarantee that the stack frames
7438 we are looking at here are even on the same stack as the
7439 original dummy frame, hence frame_id_inner can't be used. See
7440 the comments on frame_id_inner for more details. */
7441 bool unwind_finished_unexpectedly = false;
7442 for (struct frame_info *fi = get_current_frame (); fi != nullptr; )
7444 struct frame_info *prev = get_prev_frame (fi);
7445 if (prev == nullptr)
7447 /* FI is the last stack frame. Why did this frame not
7448 unwind further? */
7449 auto stop_reason = get_frame_unwind_stop_reason (fi);
7450 if (stop_reason != UNWIND_NO_REASON
7451 && stop_reason != UNWIND_OUTERMOST)
7452 unwind_finished_unexpectedly = true;
7454 fi = prev;
7456 if (unwind_finished_unexpectedly)
7457 continue;
7459 dummy_frame_discard (dummy_b->frame_id, tp);
7461 while (b->related_breakpoint != b)
7463 if (b_tmp == b->related_breakpoint)
7464 b_tmp = b->related_breakpoint->next;
7465 delete_breakpoint (b->related_breakpoint);
7467 delete_breakpoint (b);
7471 void
7472 enable_overlay_breakpoints (void)
7474 for (breakpoint *b : all_breakpoints ())
7475 if (b->type == bp_overlay_event)
7477 b->enable_state = bp_enabled;
7478 update_global_location_list (UGLL_MAY_INSERT);
7479 overlay_events_enabled = 1;
7483 void
7484 disable_overlay_breakpoints (void)
7486 for (breakpoint *b : all_breakpoints ())
7487 if (b->type == bp_overlay_event)
7489 b->enable_state = bp_disabled;
7490 update_global_location_list (UGLL_DONT_INSERT);
7491 overlay_events_enabled = 0;
7495 /* Set an active std::terminate breakpoint for each std::terminate
7496 master breakpoint. */
7497 void
7498 set_std_terminate_breakpoint (void)
7500 for (breakpoint *b : all_breakpoints_safe ())
7501 if (b->pspace == current_program_space
7502 && b->type == bp_std_terminate_master)
7504 momentary_breakpoint_from_master (b, bp_std_terminate, 1,
7505 inferior_thread ()->global_num);
7509 /* Delete all the std::terminate breakpoints. */
7510 void
7511 delete_std_terminate_breakpoint (void)
7513 for (breakpoint *b : all_breakpoints_safe ())
7514 if (b->type == bp_std_terminate)
7515 delete_breakpoint (b);
7518 struct breakpoint *
7519 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7521 struct breakpoint *b;
7523 b = create_internal_breakpoint (gdbarch, address, bp_thread_event);
7525 b->enable_state = bp_enabled;
7526 /* locspec has to be used or breakpoint_re_set will delete me. */
7527 b->locspec = new_address_location_spec (b->loc->address, NULL, 0);
7529 update_global_location_list_nothrow (UGLL_MAY_INSERT);
7531 return b;
7534 struct lang_and_radix
7536 enum language lang;
7537 int radix;
7540 /* Create a breakpoint for JIT code registration and unregistration. */
7542 struct breakpoint *
7543 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7545 return create_internal_breakpoint (gdbarch, address, bp_jit_event);
7548 /* Remove JIT code registration and unregistration breakpoint(s). */
7550 void
7551 remove_jit_event_breakpoints (void)
7553 for (breakpoint *b : all_breakpoints_safe ())
7554 if (b->type == bp_jit_event
7555 && b->loc->pspace == current_program_space)
7556 delete_breakpoint (b);
7559 void
7560 remove_solib_event_breakpoints (void)
7562 for (breakpoint *b : all_breakpoints_safe ())
7563 if (b->type == bp_shlib_event
7564 && b->loc->pspace == current_program_space)
7565 delete_breakpoint (b);
7568 /* See breakpoint.h. */
7570 void
7571 remove_solib_event_breakpoints_at_next_stop (void)
7573 for (breakpoint *b : all_breakpoints_safe ())
7574 if (b->type == bp_shlib_event
7575 && b->loc->pspace == current_program_space)
7576 b->disposition = disp_del_at_next_stop;
7579 /* Helper for create_solib_event_breakpoint /
7580 create_and_insert_solib_event_breakpoint. Allows specifying which
7581 INSERT_MODE to pass through to update_global_location_list. */
7583 static struct breakpoint *
7584 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7585 enum ugll_insert_mode insert_mode)
7587 struct breakpoint *b;
7589 b = create_internal_breakpoint (gdbarch, address, bp_shlib_event);
7590 update_global_location_list_nothrow (insert_mode);
7591 return b;
7594 struct breakpoint *
7595 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7597 return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7600 /* See breakpoint.h. */
7602 struct breakpoint *
7603 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7605 struct breakpoint *b;
7607 /* Explicitly tell update_global_location_list to insert
7608 locations. */
7609 b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7610 if (!b->loc->inserted)
7612 delete_breakpoint (b);
7613 return NULL;
7615 return b;
7618 /* Disable any breakpoints that are on code in shared libraries. Only
7619 apply to enabled breakpoints, disabled ones can just stay disabled. */
7621 void
7622 disable_breakpoints_in_shlibs (void)
7624 for (bp_location *loc : all_bp_locations ())
7626 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
7627 struct breakpoint *b = loc->owner;
7629 /* We apply the check to all breakpoints, including disabled for
7630 those with loc->duplicate set. This is so that when breakpoint
7631 becomes enabled, or the duplicate is removed, gdb will try to
7632 insert all breakpoints. If we don't set shlib_disabled here,
7633 we'll try to insert those breakpoints and fail. */
7634 if (((b->type == bp_breakpoint)
7635 || (b->type == bp_jit_event)
7636 || (b->type == bp_hardware_breakpoint)
7637 || (is_tracepoint (b)))
7638 && loc->pspace == current_program_space
7639 && !loc->shlib_disabled
7640 && solib_name_from_address (loc->pspace, loc->address)
7643 loc->shlib_disabled = 1;
7648 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7649 notification of unloaded_shlib. Only apply to enabled breakpoints,
7650 disabled ones can just stay disabled. */
7652 static void
7653 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7655 int disabled_shlib_breaks = 0;
7657 for (bp_location *loc : all_bp_locations ())
7659 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
7660 struct breakpoint *b = loc->owner;
7662 if (solib->pspace == loc->pspace
7663 && !loc->shlib_disabled
7664 && (((b->type == bp_breakpoint
7665 || b->type == bp_jit_event
7666 || b->type == bp_hardware_breakpoint)
7667 && (loc->loc_type == bp_loc_hardware_breakpoint
7668 || loc->loc_type == bp_loc_software_breakpoint))
7669 || is_tracepoint (b))
7670 && solib_contains_address_p (solib, loc->address))
7672 loc->shlib_disabled = 1;
7673 /* At this point, we cannot rely on remove_breakpoint
7674 succeeding so we must mark the breakpoint as not inserted
7675 to prevent future errors occurring in remove_breakpoints. */
7676 loc->inserted = 0;
7678 /* This may cause duplicate notifications for the same breakpoint. */
7679 gdb::observers::breakpoint_modified.notify (b);
7681 if (!disabled_shlib_breaks)
7683 target_terminal::ours_for_output ();
7684 warning (_("Temporarily disabling breakpoints "
7685 "for unloaded shared library \"%s\""),
7686 solib->so_name);
7688 disabled_shlib_breaks = 1;
7693 /* Disable any breakpoints and tracepoints in OBJFILE upon
7694 notification of free_objfile. Only apply to enabled breakpoints,
7695 disabled ones can just stay disabled. */
7697 static void
7698 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7700 if (objfile == NULL)
7701 return;
7703 /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7704 managed by the user with add-symbol-file/remove-symbol-file.
7705 Similarly to how breakpoints in shared libraries are handled in
7706 response to "nosharedlibrary", mark breakpoints in such modules
7707 shlib_disabled so they end up uninserted on the next global
7708 location list update. Shared libraries not loaded by the user
7709 aren't handled here -- they're already handled in
7710 disable_breakpoints_in_unloaded_shlib, called by solib.c's
7711 solib_unloaded observer. We skip objfiles that are not
7712 OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7713 main objfile). */
7714 if ((objfile->flags & OBJF_SHARED) == 0
7715 || (objfile->flags & OBJF_USERLOADED) == 0)
7716 return;
7718 for (breakpoint *b : all_breakpoints ())
7720 int bp_modified = 0;
7722 if (!is_breakpoint (b) && !is_tracepoint (b))
7723 continue;
7725 for (bp_location *loc : b->locations ())
7727 CORE_ADDR loc_addr = loc->address;
7729 if (loc->loc_type != bp_loc_hardware_breakpoint
7730 && loc->loc_type != bp_loc_software_breakpoint)
7731 continue;
7733 if (loc->shlib_disabled != 0)
7734 continue;
7736 if (objfile->pspace != loc->pspace)
7737 continue;
7739 if (loc->loc_type != bp_loc_hardware_breakpoint
7740 && loc->loc_type != bp_loc_software_breakpoint)
7741 continue;
7743 if (is_addr_in_objfile (loc_addr, objfile))
7745 loc->shlib_disabled = 1;
7746 /* At this point, we don't know whether the object was
7747 unmapped from the inferior or not, so leave the
7748 inserted flag alone. We'll handle failure to
7749 uninsert quietly, in case the object was indeed
7750 unmapped. */
7752 mark_breakpoint_location_modified (loc);
7754 bp_modified = 1;
7758 if (bp_modified)
7759 gdb::observers::breakpoint_modified.notify (b);
7763 /* See breakpoint.h. */
7765 breakpoint::breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
7766 bool temp, const char *cond_string_)
7767 : type (bptype),
7768 disposition (temp ? disp_del : disp_donttouch),
7769 gdbarch (gdbarch_),
7770 language (current_language->la_language),
7771 input_radix (::input_radix),
7772 cond_string (cond_string_ != nullptr
7773 ? make_unique_xstrdup (cond_string_)
7774 : nullptr),
7775 related_breakpoint (this)
7779 /* See breakpoint.h. */
7781 catchpoint::catchpoint (struct gdbarch *gdbarch, bool temp,
7782 const char *cond_string)
7783 : breakpoint (gdbarch, bp_catchpoint, temp, cond_string)
7785 add_dummy_location (this, current_program_space);
7787 pspace = current_program_space;
7790 void
7791 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
7793 breakpoint *b = add_to_breakpoint_chain (std::move (arg));
7794 set_breakpoint_number (internal, b);
7795 if (is_tracepoint (b))
7796 set_tracepoint_count (breakpoint_count);
7797 if (!internal)
7798 mention (b);
7799 gdb::observers::breakpoint_created.notify (b);
7801 if (update_gll)
7802 update_global_location_list (UGLL_MAY_INSERT);
7805 static int
7806 hw_breakpoint_used_count (void)
7808 int i = 0;
7810 for (breakpoint *b : all_breakpoints ())
7811 if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
7812 for (bp_location *bl : b->locations ())
7814 /* Special types of hardware breakpoints may use more than
7815 one register. */
7816 i += b->resources_needed (bl);
7819 return i;
7822 /* Returns the resources B would use if it were a hardware
7823 watchpoint. */
7825 static int
7826 hw_watchpoint_use_count (struct breakpoint *b)
7828 int i = 0;
7830 if (!breakpoint_enabled (b))
7831 return 0;
7833 for (bp_location *bl : b->locations ())
7835 /* Special types of hardware watchpoints may use more than
7836 one register. */
7837 i += b->resources_needed (bl);
7840 return i;
7843 /* Returns the sum the used resources of all hardware watchpoints of
7844 type TYPE in the breakpoints list. Also returns in OTHER_TYPE_USED
7845 the sum of the used resources of all hardware watchpoints of other
7846 types _not_ TYPE. */
7848 static int
7849 hw_watchpoint_used_count_others (struct breakpoint *except,
7850 enum bptype type, int *other_type_used)
7852 int i = 0;
7854 *other_type_used = 0;
7855 for (breakpoint *b : all_breakpoints ())
7857 if (b == except)
7858 continue;
7859 if (!breakpoint_enabled (b))
7860 continue;
7862 if (b->type == type)
7863 i += hw_watchpoint_use_count (b);
7864 else if (is_hardware_watchpoint (b))
7865 *other_type_used = 1;
7868 return i;
7871 void
7872 disable_watchpoints_before_interactive_call_start (void)
7874 for (breakpoint *b : all_breakpoints ())
7875 if (is_watchpoint (b) && breakpoint_enabled (b))
7877 b->enable_state = bp_call_disabled;
7878 update_global_location_list (UGLL_DONT_INSERT);
7882 void
7883 enable_watchpoints_after_interactive_call_stop (void)
7885 for (breakpoint *b : all_breakpoints ())
7886 if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
7888 b->enable_state = bp_enabled;
7889 update_global_location_list (UGLL_MAY_INSERT);
7893 void
7894 disable_breakpoints_before_startup (void)
7896 current_program_space->executing_startup = 1;
7897 update_global_location_list (UGLL_DONT_INSERT);
7900 void
7901 enable_breakpoints_after_startup (void)
7903 current_program_space->executing_startup = 0;
7904 breakpoint_re_set ();
7907 /* Allocate a new momentary breakpoint. */
7909 template<typename... Arg>
7910 static momentary_breakpoint *
7911 new_momentary_breakpoint (struct gdbarch *gdbarch, enum bptype type,
7912 Arg&&... args)
7914 if (type == bp_longjmp || type == bp_exception)
7915 return new longjmp_breakpoint (gdbarch, type,
7916 std::forward<Arg> (args)...);
7917 else
7918 return new momentary_breakpoint (gdbarch, type,
7919 std::forward<Arg> (args)...);
7922 /* Set a momentary breakpoint of type TYPE at address specified by
7923 SAL. If FRAME_ID is valid, the breakpoint is restricted to that
7924 frame. */
7926 breakpoint_up
7927 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
7928 struct frame_id frame_id, enum bptype type)
7930 /* If FRAME_ID is valid, it should be a real frame, not an inlined or
7931 tail-called one. */
7932 gdb_assert (!frame_id_artificial_p (frame_id));
7934 std::unique_ptr<momentary_breakpoint> b
7935 (new_momentary_breakpoint (gdbarch, type, sal.pspace, frame_id,
7936 inferior_thread ()->global_num));
7938 b->add_location (sal);
7940 breakpoint_up bp (add_to_breakpoint_chain (std::move (b)));
7942 update_global_location_list_nothrow (UGLL_MAY_INSERT);
7944 return bp;
7947 /* Make a momentary breakpoint based on the master breakpoint ORIG.
7948 The new breakpoint will have type TYPE, use OPS as its
7949 breakpoint_ops, and will set enabled to LOC_ENABLED. */
7951 static struct breakpoint *
7952 momentary_breakpoint_from_master (struct breakpoint *orig,
7953 enum bptype type,
7954 int loc_enabled,
7955 int thread)
7957 std::unique_ptr<breakpoint> copy
7958 (new_momentary_breakpoint (orig->gdbarch, type, orig->pspace,
7959 orig->frame_id, thread));
7960 copy->loc = copy->allocate_location ();
7961 set_breakpoint_location_function (copy->loc);
7963 copy->loc->gdbarch = orig->loc->gdbarch;
7964 copy->loc->requested_address = orig->loc->requested_address;
7965 copy->loc->address = orig->loc->address;
7966 copy->loc->section = orig->loc->section;
7967 copy->loc->pspace = orig->loc->pspace;
7968 copy->loc->probe = orig->loc->probe;
7969 copy->loc->line_number = orig->loc->line_number;
7970 copy->loc->symtab = orig->loc->symtab;
7971 copy->loc->enabled = loc_enabled;
7973 breakpoint *b = add_to_breakpoint_chain (std::move (copy));
7974 update_global_location_list_nothrow (UGLL_DONT_INSERT);
7975 return b;
7978 /* Make a deep copy of momentary breakpoint ORIG. Returns NULL if
7979 ORIG is NULL. */
7981 struct breakpoint *
7982 clone_momentary_breakpoint (struct breakpoint *orig)
7984 /* If there's nothing to clone, then return nothing. */
7985 if (orig == NULL)
7986 return NULL;
7988 return momentary_breakpoint_from_master (orig, orig->type, 0,
7989 orig->thread);
7992 breakpoint_up
7993 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
7994 enum bptype type)
7996 struct symtab_and_line sal;
7998 sal = find_pc_line (pc, 0);
7999 sal.pc = pc;
8000 sal.section = find_pc_overlay (pc);
8001 sal.explicit_pc = 1;
8003 return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8007 /* Tell the user we have just set a breakpoint B. */
8009 static void
8010 mention (const breakpoint *b)
8012 b->print_mention ();
8013 current_uiout->text ("\n");
8017 static bool bp_loc_is_permanent (struct bp_location *loc);
8019 /* Handle "set breakpoint auto-hw on".
8021 If the explicitly specified breakpoint type is not hardware
8022 breakpoint, check the memory map to see whether the breakpoint
8023 address is in read-only memory.
8025 - location type is not hardware breakpoint, memory is read-only.
8026 We change the type of the location to hardware breakpoint.
8028 - location type is hardware breakpoint, memory is read-write. This
8029 means we've previously made the location hardware one, but then the
8030 memory map changed, so we undo.
8033 static void
8034 handle_automatic_hardware_breakpoints (bp_location *bl)
8036 if (automatic_hardware_breakpoints
8037 && bl->owner->type != bp_hardware_breakpoint
8038 && (bl->loc_type == bp_loc_software_breakpoint
8039 || bl->loc_type == bp_loc_hardware_breakpoint))
8041 /* When breakpoints are removed, remove_breakpoints will use
8042 location types we've just set here, the only possible problem
8043 is that memory map has changed during running program, but
8044 it's not going to work anyway with current gdb. */
8045 mem_region *mr = lookup_mem_region (bl->address);
8047 if (mr != nullptr)
8049 enum bp_loc_type new_type;
8051 if (mr->attrib.mode != MEM_RW)
8052 new_type = bp_loc_hardware_breakpoint;
8053 else
8054 new_type = bp_loc_software_breakpoint;
8056 if (new_type != bl->loc_type)
8058 static bool said = false;
8060 bl->loc_type = new_type;
8061 if (!said)
8063 gdb_printf (_("Note: automatically using "
8064 "hardware breakpoints for "
8065 "read-only addresses.\n"));
8066 said = true;
8073 bp_location *
8074 code_breakpoint::add_location (const symtab_and_line &sal)
8076 struct bp_location *new_loc, **tmp;
8077 CORE_ADDR adjusted_address;
8078 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8080 if (loc_gdbarch == NULL)
8081 loc_gdbarch = gdbarch;
8083 /* Adjust the breakpoint's address prior to allocating a location.
8084 Once we call allocate_location(), that mostly uninitialized
8085 location will be placed on the location chain. Adjustment of the
8086 breakpoint may cause target_read_memory() to be called and we do
8087 not want its scan of the location chain to find a breakpoint and
8088 location that's only been partially initialized. */
8089 adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8090 sal.pc, type);
8092 /* Sort the locations by their ADDRESS. */
8093 new_loc = allocate_location ();
8094 for (tmp = &(loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8095 tmp = &((*tmp)->next))
8097 new_loc->next = *tmp;
8098 *tmp = new_loc;
8100 new_loc->requested_address = sal.pc;
8101 new_loc->address = adjusted_address;
8102 new_loc->pspace = sal.pspace;
8103 new_loc->probe.prob = sal.prob;
8104 new_loc->probe.objfile = sal.objfile;
8105 gdb_assert (new_loc->pspace != NULL);
8106 new_loc->section = sal.section;
8107 new_loc->gdbarch = loc_gdbarch;
8108 new_loc->line_number = sal.line;
8109 new_loc->symtab = sal.symtab;
8110 new_loc->symbol = sal.symbol;
8111 new_loc->msymbol = sal.msymbol;
8112 new_loc->objfile = sal.objfile;
8114 set_breakpoint_location_function (new_loc);
8116 /* While by definition, permanent breakpoints are already present in the
8117 code, we don't mark the location as inserted. Normally one would expect
8118 that GDB could rely on that breakpoint instruction to stop the program,
8119 thus removing the need to insert its own breakpoint, except that executing
8120 the breakpoint instruction can kill the target instead of reporting a
8121 SIGTRAP. E.g., on SPARC, when interrupts are disabled, executing the
8122 instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8123 with "Trap 0x02 while interrupts disabled, Error state". Letting the
8124 breakpoint be inserted normally results in QEMU knowing about the GDB
8125 breakpoint, and thus trap before the breakpoint instruction is executed.
8126 (If GDB later needs to continue execution past the permanent breakpoint,
8127 it manually increments the PC, thus avoiding executing the breakpoint
8128 instruction.) */
8129 if (bp_loc_is_permanent (new_loc))
8130 new_loc->permanent = 1;
8132 return new_loc;
8136 /* Return true if LOC is pointing to a permanent breakpoint,
8137 return false otherwise. */
8139 static bool
8140 bp_loc_is_permanent (struct bp_location *loc)
8142 gdb_assert (loc != NULL);
8144 /* If we have a non-breakpoint-backed catchpoint or a software
8145 watchpoint, just return 0. We should not attempt to read from
8146 the addresses the locations of these breakpoint types point to.
8147 gdbarch_program_breakpoint_here_p, below, will attempt to read
8148 memory. */
8149 if (!bl_address_is_meaningful (loc))
8150 return false;
8152 scoped_restore_current_pspace_and_thread restore_pspace_thread;
8153 switch_to_program_space_and_thread (loc->pspace);
8154 return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8157 /* Build a command list for the dprintf corresponding to the current
8158 settings of the dprintf style options. */
8160 static void
8161 update_dprintf_command_list (struct breakpoint *b)
8163 const char *dprintf_args = b->extra_string.get ();
8164 gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
8166 if (!dprintf_args)
8167 return;
8169 dprintf_args = skip_spaces (dprintf_args);
8171 /* Allow a comma, as it may have terminated a location, but don't
8172 insist on it. */
8173 if (*dprintf_args == ',')
8174 ++dprintf_args;
8175 dprintf_args = skip_spaces (dprintf_args);
8177 if (*dprintf_args != '"')
8178 error (_("Bad format string, missing '\"'."));
8180 if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8181 printf_line = xstrprintf ("printf %s", dprintf_args);
8182 else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8184 if (dprintf_function.empty ())
8185 error (_("No function supplied for dprintf call"));
8187 if (!dprintf_channel.empty ())
8188 printf_line = xstrprintf ("call (void) %s (%s,%s)",
8189 dprintf_function.c_str (),
8190 dprintf_channel.c_str (),
8191 dprintf_args);
8192 else
8193 printf_line = xstrprintf ("call (void) %s (%s)",
8194 dprintf_function.c_str (),
8195 dprintf_args);
8197 else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8199 if (target_can_run_breakpoint_commands ())
8200 printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8201 else
8203 warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8204 printf_line = xstrprintf ("printf %s", dprintf_args);
8207 else
8208 internal_error (__FILE__, __LINE__,
8209 _("Invalid dprintf style."));
8211 gdb_assert (printf_line != NULL);
8213 /* Manufacture a printf sequence. */
8214 struct command_line *printf_cmd_line
8215 = new struct command_line (simple_control, printf_line.release ());
8216 breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8217 command_lines_deleter ()));
8220 /* Update all dprintf commands, making their command lists reflect
8221 current style settings. */
8223 static void
8224 update_dprintf_commands (const char *args, int from_tty,
8225 struct cmd_list_element *c)
8227 for (breakpoint *b : all_breakpoints ())
8228 if (b->type == bp_dprintf)
8229 update_dprintf_command_list (b);
8232 code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
8233 enum bptype type_,
8234 gdb::array_view<const symtab_and_line> sals,
8235 location_spec_up &&locspec_,
8236 gdb::unique_xmalloc_ptr<char> filter_,
8237 gdb::unique_xmalloc_ptr<char> cond_string_,
8238 gdb::unique_xmalloc_ptr<char> extra_string_,
8239 enum bpdisp disposition_,
8240 int thread_, int task_, int ignore_count_,
8241 int from_tty,
8242 int enabled_, unsigned flags,
8243 int display_canonical_)
8244 : breakpoint (gdbarch_, type_)
8246 int i;
8248 if (type == bp_hardware_breakpoint)
8250 int target_resources_ok;
8252 i = hw_breakpoint_used_count ();
8253 target_resources_ok =
8254 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8255 i + 1, 0);
8256 if (target_resources_ok == 0)
8257 error (_("No hardware breakpoint support in the target."));
8258 else if (target_resources_ok < 0)
8259 error (_("Hardware breakpoints used exceeds limit."));
8262 gdb_assert (!sals.empty ());
8264 thread = thread_;
8265 task = task_;
8267 cond_string = std::move (cond_string_);
8268 extra_string = std::move (extra_string_);
8269 ignore_count = ignore_count_;
8270 enable_state = enabled_ ? bp_enabled : bp_disabled;
8271 disposition = disposition_;
8273 if (type == bp_static_tracepoint
8274 || type == bp_static_marker_tracepoint)
8276 auto *t = static_cast<struct tracepoint *> (this);
8277 struct static_tracepoint_marker marker;
8279 if (strace_marker_p (this))
8281 /* We already know the marker exists, otherwise, we wouldn't
8282 see a sal for it. */
8283 const char *p = &locspec_->to_string ()[3];
8284 const char *endp;
8286 p = skip_spaces (p);
8288 endp = skip_to_space (p);
8290 t->static_trace_marker_id.assign (p, endp - p);
8292 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8293 t->static_trace_marker_id.c_str ());
8295 else if (target_static_tracepoint_marker_at (sals[0].pc, &marker))
8297 t->static_trace_marker_id = std::move (marker.str_id);
8299 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8300 t->static_trace_marker_id.c_str ());
8302 else
8303 warning (_("Couldn't determine the static tracepoint marker to probe"));
8306 for (const auto &sal : sals)
8308 if (from_tty)
8310 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8311 if (loc_gdbarch == nullptr)
8312 loc_gdbarch = gdbarch;
8314 describe_other_breakpoints (loc_gdbarch,
8315 sal.pspace, sal.pc, sal.section, thread);
8318 bp_location *new_loc = add_location (sal);
8319 if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8320 new_loc->inserted = 1;
8322 /* Do not set breakpoint locations conditions yet. As locations
8323 are inserted, they get sorted based on their addresses. Let
8324 the list stabilize to have reliable location numbers. */
8326 /* Dynamic printf requires and uses additional arguments on the
8327 command line, otherwise it's an error. */
8328 if (type == bp_dprintf)
8330 if (extra_string != nullptr)
8331 update_dprintf_command_list (this);
8332 else
8333 error (_("Format string required"));
8335 else if (extra_string != nullptr)
8336 error (_("Garbage '%s' at end of command"), extra_string.get ());
8339 /* The order of the locations is now stable. Set the location
8340 condition using the location's number. */
8341 int loc_num = 1;
8342 for (bp_location *bl : locations ())
8344 if (cond_string != nullptr)
8345 set_breakpoint_location_condition (cond_string.get (), bl,
8346 number, loc_num);
8348 ++loc_num;
8351 display_canonical = display_canonical_;
8352 if (locspec_ != nullptr)
8353 locspec = std::move (locspec_);
8354 else
8355 locspec = new_address_location_spec (this->loc->address, NULL, 0);
8356 filter = std::move (filter_);
8359 static void
8360 create_breakpoint_sal (struct gdbarch *gdbarch,
8361 gdb::array_view<const symtab_and_line> sals,
8362 location_spec_up &&locspec,
8363 gdb::unique_xmalloc_ptr<char> filter,
8364 gdb::unique_xmalloc_ptr<char> cond_string,
8365 gdb::unique_xmalloc_ptr<char> extra_string,
8366 enum bptype type, enum bpdisp disposition,
8367 int thread, int task, int ignore_count,
8368 int from_tty,
8369 int enabled, int internal, unsigned flags,
8370 int display_canonical)
8372 std::unique_ptr<code_breakpoint> b
8373 = new_breakpoint_from_type (gdbarch,
8374 type,
8375 sals,
8376 std::move (locspec),
8377 std::move (filter),
8378 std::move (cond_string),
8379 std::move (extra_string),
8380 disposition,
8381 thread, task, ignore_count,
8382 from_tty,
8383 enabled, flags,
8384 display_canonical);
8386 install_breakpoint (internal, std::move (b), 0);
8389 /* Add SALS.nelts breakpoints to the breakpoint table. For each
8390 SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8391 value. COND_STRING, if not NULL, specified the condition to be
8392 used for all breakpoints. Essentially the only case where
8393 SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8394 function. In that case, it's still not possible to specify
8395 separate conditions for different overloaded functions, so
8396 we take just a single condition string.
8398 NOTE: If the function succeeds, the caller is expected to cleanup
8399 the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8400 array contents). If the function fails (error() is called), the
8401 caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8402 COND and SALS arrays and each of those arrays contents. */
8404 static void
8405 create_breakpoints_sal (struct gdbarch *gdbarch,
8406 struct linespec_result *canonical,
8407 gdb::unique_xmalloc_ptr<char> cond_string,
8408 gdb::unique_xmalloc_ptr<char> extra_string,
8409 enum bptype type, enum bpdisp disposition,
8410 int thread, int task, int ignore_count,
8411 int from_tty,
8412 int enabled, int internal, unsigned flags)
8414 if (canonical->pre_expanded)
8415 gdb_assert (canonical->lsals.size () == 1);
8417 for (const auto &lsal : canonical->lsals)
8419 /* Note that 'location' can be NULL in the case of a plain
8420 'break', without arguments. */
8421 location_spec_up locspec
8422 = (canonical->locspec != nullptr
8423 ? canonical->locspec->clone ()
8424 : nullptr);
8425 gdb::unique_xmalloc_ptr<char> filter_string
8426 (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8428 create_breakpoint_sal (gdbarch, lsal.sals,
8429 std::move (locspec),
8430 std::move (filter_string),
8431 std::move (cond_string),
8432 std::move (extra_string),
8433 type, disposition,
8434 thread, task, ignore_count,
8435 from_tty, enabled, internal, flags,
8436 canonical->special_display);
8440 /* Parse LOCSPEC which is assumed to be a SAL specification possibly
8441 followed by conditionals. On return, SALS contains an array of SAL
8442 addresses found. LOCSPEC points to the end of the SAL (for
8443 linespec locspecs).
8445 The array and the line spec strings are allocated on the heap, it is
8446 the caller's responsibility to free them. */
8448 static void
8449 parse_breakpoint_sals (location_spec *locspec,
8450 struct linespec_result *canonical)
8452 struct symtab_and_line cursal;
8454 if (locspec->type () == LINESPEC_LOCATION_SPEC)
8456 const char *spec = as_linespec_location_spec (locspec)->spec_string;
8458 if (spec == NULL)
8460 /* The last displayed codepoint, if it's valid, is our default
8461 breakpoint address. */
8462 if (last_displayed_sal_is_valid ())
8464 /* Set sal's pspace, pc, symtab, and line to the values
8465 corresponding to the last call to print_frame_info.
8466 Be sure to reinitialize LINE with NOTCURRENT == 0
8467 as the breakpoint line number is inappropriate otherwise.
8468 find_pc_line would adjust PC, re-set it back. */
8469 symtab_and_line sal = get_last_displayed_sal ();
8470 CORE_ADDR pc = sal.pc;
8472 sal = find_pc_line (pc, 0);
8474 /* "break" without arguments is equivalent to "break *PC"
8475 where PC is the last displayed codepoint's address. So
8476 make sure to set sal.explicit_pc to prevent GDB from
8477 trying to expand the list of sals to include all other
8478 instances with the same symtab and line. */
8479 sal.pc = pc;
8480 sal.explicit_pc = 1;
8482 struct linespec_sals lsal;
8483 lsal.sals = {sal};
8484 lsal.canonical = NULL;
8486 canonical->lsals.push_back (std::move (lsal));
8487 return;
8489 else
8490 error (_("No default breakpoint address now."));
8494 /* Force almost all breakpoints to be in terms of the
8495 current_source_symtab (which is decode_line_1's default).
8496 This should produce the results we want almost all of the
8497 time while leaving default_breakpoint_* alone.
8499 ObjC: However, don't match an Objective-C method name which
8500 may have a '+' or '-' succeeded by a '['. */
8501 cursal = get_current_source_symtab_and_line ();
8502 if (last_displayed_sal_is_valid ())
8504 const char *spec = NULL;
8506 if (locspec->type () == LINESPEC_LOCATION_SPEC)
8507 spec = as_linespec_location_spec (locspec)->spec_string;
8509 if (!cursal.symtab
8510 || (spec != NULL
8511 && strchr ("+-", spec[0]) != NULL
8512 && spec[1] != '['))
8514 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8515 get_last_displayed_symtab (),
8516 get_last_displayed_line (),
8517 canonical, NULL, NULL);
8518 return;
8522 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8523 cursal.symtab, cursal.line, canonical, NULL, NULL);
8527 /* Convert each SAL into a real PC. Verify that the PC can be
8528 inserted as a breakpoint. If it can't throw an error. */
8530 static void
8531 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
8533 for (auto &sal : sals)
8534 resolve_sal_pc (&sal);
8537 /* Fast tracepoints may have restrictions on valid locations. For
8538 instance, a fast tracepoint using a jump instead of a trap will
8539 likely have to overwrite more bytes than a trap would, and so can
8540 only be placed where the instruction is longer than the jump, or a
8541 multi-instruction sequence does not have a jump into the middle of
8542 it, etc. */
8544 static void
8545 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8546 gdb::array_view<const symtab_and_line> sals)
8548 for (const auto &sal : sals)
8550 struct gdbarch *sarch;
8552 sarch = get_sal_arch (sal);
8553 /* We fall back to GDBARCH if there is no architecture
8554 associated with SAL. */
8555 if (sarch == NULL)
8556 sarch = gdbarch;
8557 std::string msg;
8558 if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
8559 error (_("May not have a fast tracepoint at %s%s"),
8560 paddress (sarch, sal.pc), msg.c_str ());
8564 /* Given TOK, a string specification of condition and thread, as
8565 accepted by the 'break' command, extract the condition
8566 string and thread number and set *COND_STRING and *THREAD.
8567 PC identifies the context at which the condition should be parsed.
8568 If no condition is found, *COND_STRING is set to NULL.
8569 If no thread is found, *THREAD is set to -1. */
8571 static void
8572 find_condition_and_thread (const char *tok, CORE_ADDR pc,
8573 gdb::unique_xmalloc_ptr<char> *cond_string,
8574 int *thread, int *task,
8575 gdb::unique_xmalloc_ptr<char> *rest)
8577 cond_string->reset ();
8578 *thread = -1;
8579 *task = 0;
8580 rest->reset ();
8581 bool force = false;
8583 while (tok && *tok)
8585 const char *end_tok;
8586 int toklen;
8587 const char *cond_start = NULL;
8588 const char *cond_end = NULL;
8590 tok = skip_spaces (tok);
8592 if ((*tok == '"' || *tok == ',') && rest)
8594 rest->reset (savestring (tok, strlen (tok)));
8595 return;
8598 end_tok = skip_to_space (tok);
8600 toklen = end_tok - tok;
8602 if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8604 tok = cond_start = end_tok + 1;
8607 parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
8609 catch (const gdb_exception_error &)
8611 if (!force)
8612 throw;
8613 else
8614 tok = tok + strlen (tok);
8616 cond_end = tok;
8617 cond_string->reset (savestring (cond_start, cond_end - cond_start));
8619 else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
8621 tok = tok + toklen;
8622 force = true;
8624 else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8626 const char *tmptok;
8627 struct thread_info *thr;
8629 tok = end_tok + 1;
8630 thr = parse_thread_id (tok, &tmptok);
8631 if (tok == tmptok)
8632 error (_("Junk after thread keyword."));
8633 *thread = thr->global_num;
8634 tok = tmptok;
8636 else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8638 char *tmptok;
8640 tok = end_tok + 1;
8641 *task = strtol (tok, &tmptok, 0);
8642 if (tok == tmptok)
8643 error (_("Junk after task keyword."));
8644 if (!valid_task_id (*task))
8645 error (_("Unknown task %d."), *task);
8646 tok = tmptok;
8648 else if (rest)
8650 rest->reset (savestring (tok, strlen (tok)));
8651 return;
8653 else
8654 error (_("Junk at end of arguments."));
8658 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
8659 succeeds. The parsed values are written to COND_STRING, THREAD,
8660 TASK, and REST. See the comment of 'find_condition_and_thread'
8661 for the description of these parameters and INPUT. */
8663 static void
8664 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
8665 const char *input,
8666 gdb::unique_xmalloc_ptr<char> *cond_string,
8667 int *thread, int *task,
8668 gdb::unique_xmalloc_ptr<char> *rest)
8670 int num_failures = 0;
8671 for (auto &sal : sals)
8673 gdb::unique_xmalloc_ptr<char> cond;
8674 int thread_id = 0;
8675 int task_id = 0;
8676 gdb::unique_xmalloc_ptr<char> remaining;
8678 /* Here we want to parse 'arg' to separate condition from thread
8679 number. But because parsing happens in a context and the
8680 contexts of sals might be different, try each until there is
8681 success. Finding one successful parse is sufficient for our
8682 goal. When setting the breakpoint we'll re-parse the
8683 condition in the context of each sal. */
8686 find_condition_and_thread (input, sal.pc, &cond, &thread_id,
8687 &task_id, &remaining);
8688 *cond_string = std::move (cond);
8689 *thread = thread_id;
8690 *task = task_id;
8691 *rest = std::move (remaining);
8692 break;
8694 catch (const gdb_exception_error &e)
8696 num_failures++;
8697 /* If no sal remains, do not continue. */
8698 if (num_failures == sals.size ())
8699 throw;
8704 /* Decode a static tracepoint marker spec. */
8706 static std::vector<symtab_and_line>
8707 decode_static_tracepoint_spec (const char **arg_p)
8709 const char *p = &(*arg_p)[3];
8710 const char *endp;
8712 p = skip_spaces (p);
8714 endp = skip_to_space (p);
8716 std::string marker_str (p, endp - p);
8718 std::vector<static_tracepoint_marker> markers
8719 = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
8720 if (markers.empty ())
8721 error (_("No known static tracepoint marker named %s"),
8722 marker_str.c_str ());
8724 std::vector<symtab_and_line> sals;
8725 sals.reserve (markers.size ());
8727 for (const static_tracepoint_marker &marker : markers)
8729 symtab_and_line sal = find_pc_line (marker.address, 0);
8730 sal.pc = marker.address;
8731 sals.push_back (sal);
8734 *arg_p = endp;
8735 return sals;
8738 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
8739 according to IS_TRACEPOINT. */
8741 static const struct breakpoint_ops *
8742 breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
8743 bool is_tracepoint)
8745 if (is_tracepoint)
8747 if (locspec_type == PROBE_LOCATION_SPEC)
8748 return &tracepoint_probe_breakpoint_ops;
8749 else
8750 return &code_breakpoint_ops;
8752 else
8754 if (locspec_type == PROBE_LOCATION_SPEC)
8755 return &bkpt_probe_breakpoint_ops;
8756 else
8757 return &code_breakpoint_ops;
8761 /* See breakpoint.h. */
8763 const struct breakpoint_ops *
8764 breakpoint_ops_for_location_spec (const location_spec *locspec,
8765 bool is_tracepoint)
8767 if (locspec != nullptr)
8768 return (breakpoint_ops_for_location_spec_type
8769 (locspec->type (), is_tracepoint));
8770 return &code_breakpoint_ops;
8773 /* See breakpoint.h. */
8776 create_breakpoint (struct gdbarch *gdbarch,
8777 location_spec *locspec,
8778 const char *cond_string,
8779 int thread, const char *extra_string,
8780 bool force_condition, int parse_extra,
8781 int tempflag, enum bptype type_wanted,
8782 int ignore_count,
8783 enum auto_boolean pending_break_support,
8784 const struct breakpoint_ops *ops,
8785 int from_tty, int enabled, int internal,
8786 unsigned flags)
8788 struct linespec_result canonical;
8789 int pending = 0;
8790 int task = 0;
8791 int prev_bkpt_count = breakpoint_count;
8793 gdb_assert (ops != NULL);
8795 /* If extra_string isn't useful, set it to NULL. */
8796 if (extra_string != NULL && *extra_string == '\0')
8797 extra_string = NULL;
8801 ops->create_sals_from_location_spec (locspec, &canonical);
8803 catch (const gdb_exception_error &e)
8805 /* If caller is interested in rc value from parse, set
8806 value. */
8807 if (e.error == NOT_FOUND_ERROR)
8809 /* If pending breakpoint support is turned off, throw
8810 error. */
8812 if (pending_break_support == AUTO_BOOLEAN_FALSE)
8813 throw;
8815 exception_print (gdb_stderr, e);
8817 /* If pending breakpoint support is auto query and the user
8818 selects no, then simply return the error code. */
8819 if (pending_break_support == AUTO_BOOLEAN_AUTO
8820 && !nquery (_("Make %s pending on future shared library load? "),
8821 bptype_string (type_wanted)))
8822 return 0;
8824 /* At this point, either the user was queried about setting
8825 a pending breakpoint and selected yes, or pending
8826 breakpoint behavior is on and thus a pending breakpoint
8827 is defaulted on behalf of the user. */
8828 pending = 1;
8830 else
8831 throw;
8834 if (!pending && canonical.lsals.empty ())
8835 return 0;
8837 /* Resolve all line numbers to PC's and verify that the addresses
8838 are ok for the target. */
8839 if (!pending)
8841 for (auto &lsal : canonical.lsals)
8842 breakpoint_sals_to_pc (lsal.sals);
8845 /* Fast tracepoints may have additional restrictions on location. */
8846 if (!pending && type_wanted == bp_fast_tracepoint)
8848 for (const auto &lsal : canonical.lsals)
8849 check_fast_tracepoint_sals (gdbarch, lsal.sals);
8852 /* Verify that condition can be parsed, before setting any
8853 breakpoints. Allocate a separate condition expression for each
8854 breakpoint. */
8855 if (!pending)
8857 gdb::unique_xmalloc_ptr<char> cond_string_copy;
8858 gdb::unique_xmalloc_ptr<char> extra_string_copy;
8860 if (parse_extra)
8862 gdb::unique_xmalloc_ptr<char> rest;
8863 gdb::unique_xmalloc_ptr<char> cond;
8865 const linespec_sals &lsal = canonical.lsals[0];
8867 find_condition_and_thread_for_sals (lsal.sals, extra_string,
8868 &cond, &thread, &task, &rest);
8869 cond_string_copy = std::move (cond);
8870 extra_string_copy = std::move (rest);
8872 else
8874 if (type_wanted != bp_dprintf
8875 && extra_string != NULL && *extra_string != '\0')
8876 error (_("Garbage '%s' at end of location"), extra_string);
8878 /* Check the validity of the condition. We should error out
8879 if the condition is invalid at all of the locations and
8880 if it is not forced. In the PARSE_EXTRA case above, this
8881 check is done when parsing the EXTRA_STRING. */
8882 if (cond_string != nullptr && !force_condition)
8884 int num_failures = 0;
8885 const linespec_sals &lsal = canonical.lsals[0];
8886 for (const auto &sal : lsal.sals)
8888 const char *cond = cond_string;
8891 parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
8892 /* One success is sufficient to keep going. */
8893 break;
8895 catch (const gdb_exception_error &)
8897 num_failures++;
8898 /* If this is the last sal, error out. */
8899 if (num_failures == lsal.sals.size ())
8900 throw;
8905 /* Create a private copy of condition string. */
8906 if (cond_string)
8907 cond_string_copy.reset (xstrdup (cond_string));
8908 /* Create a private copy of any extra string. */
8909 if (extra_string)
8910 extra_string_copy.reset (xstrdup (extra_string));
8913 ops->create_breakpoints_sal (gdbarch, &canonical,
8914 std::move (cond_string_copy),
8915 std::move (extra_string_copy),
8916 type_wanted,
8917 tempflag ? disp_del : disp_donttouch,
8918 thread, task, ignore_count,
8919 from_tty, enabled, internal, flags);
8921 else
8923 std::unique_ptr <breakpoint> b = new_breakpoint_from_type (gdbarch,
8924 type_wanted);
8925 b->locspec = locspec->clone ();
8927 if (parse_extra)
8928 b->cond_string = NULL;
8929 else
8931 /* Create a private copy of condition string. */
8932 b->cond_string.reset (cond_string != NULL
8933 ? xstrdup (cond_string)
8934 : NULL);
8935 b->thread = thread;
8938 /* Create a private copy of any extra string. */
8939 b->extra_string.reset (extra_string != NULL
8940 ? xstrdup (extra_string)
8941 : NULL);
8942 b->ignore_count = ignore_count;
8943 b->disposition = tempflag ? disp_del : disp_donttouch;
8944 b->condition_not_parsed = 1;
8945 b->enable_state = enabled ? bp_enabled : bp_disabled;
8946 if ((type_wanted != bp_breakpoint
8947 && type_wanted != bp_hardware_breakpoint) || thread != -1)
8948 b->pspace = current_program_space;
8950 install_breakpoint (internal, std::move (b), 0);
8953 if (canonical.lsals.size () > 1)
8955 warning (_("Multiple breakpoints were set.\nUse the "
8956 "\"delete\" command to delete unwanted breakpoints."));
8957 prev_breakpoint_count = prev_bkpt_count;
8960 update_global_location_list (UGLL_MAY_INSERT);
8962 return 1;
8965 /* Set a breakpoint.
8966 ARG is a string describing breakpoint address,
8967 condition, and thread.
8968 FLAG specifies if a breakpoint is hardware on,
8969 and if breakpoint is temporary, using BP_HARDWARE_FLAG
8970 and BP_TEMPFLAG. */
8972 static void
8973 break_command_1 (const char *arg, int flag, int from_tty)
8975 int tempflag = flag & BP_TEMPFLAG;
8976 enum bptype type_wanted = (flag & BP_HARDWAREFLAG
8977 ? bp_hardware_breakpoint
8978 : bp_breakpoint);
8980 location_spec_up locspec = string_to_location_spec (&arg, current_language);
8981 const struct breakpoint_ops *ops
8982 = breakpoint_ops_for_location_spec (locspec.get (),
8983 false /* is_tracepoint */);
8985 create_breakpoint (get_current_arch (),
8986 locspec.get (),
8987 NULL, 0, arg, false, 1 /* parse arg */,
8988 tempflag, type_wanted,
8989 0 /* Ignore count */,
8990 pending_break_support,
8991 ops,
8992 from_tty,
8993 1 /* enabled */,
8994 0 /* internal */,
8998 /* Helper function for break_command_1 and disassemble_command. */
9000 void
9001 resolve_sal_pc (struct symtab_and_line *sal)
9003 CORE_ADDR pc;
9005 if (sal->pc == 0 && sal->symtab != NULL)
9007 if (!find_line_pc (sal->symtab, sal->line, &pc))
9008 error (_("No line %d in file \"%s\"."),
9009 sal->line, symtab_to_filename_for_display (sal->symtab));
9010 sal->pc = pc;
9012 /* If this SAL corresponds to a breakpoint inserted using a line
9013 number, then skip the function prologue if necessary. */
9014 if (sal->explicit_line)
9015 skip_prologue_sal (sal);
9018 if (sal->section == 0 && sal->symtab != NULL)
9020 const struct blockvector *bv;
9021 const struct block *b;
9022 struct symbol *sym;
9024 bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9025 sal->symtab->compunit ());
9026 if (bv != NULL)
9028 sym = block_linkage_function (b);
9029 if (sym != NULL)
9031 fixup_symbol_section (sym, sal->symtab->compunit ()->objfile ());
9032 sal->section
9033 = sym->obj_section (sal->symtab->compunit ()->objfile ());
9035 else
9037 /* It really is worthwhile to have the section, so we'll
9038 just have to look harder. This case can be executed
9039 if we have line numbers but no functions (as can
9040 happen in assembly source). */
9042 scoped_restore_current_pspace_and_thread restore_pspace_thread;
9043 switch_to_program_space_and_thread (sal->pspace);
9045 bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9046 if (msym.minsym)
9047 sal->section = msym.obj_section ();
9053 void
9054 break_command (const char *arg, int from_tty)
9056 break_command_1 (arg, 0, from_tty);
9059 void
9060 tbreak_command (const char *arg, int from_tty)
9062 break_command_1 (arg, BP_TEMPFLAG, from_tty);
9065 static void
9066 hbreak_command (const char *arg, int from_tty)
9068 break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9071 static void
9072 thbreak_command (const char *arg, int from_tty)
9074 break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9077 /* The dynamic printf command is mostly like a regular breakpoint, but
9078 with a prewired command list consisting of a single output command,
9079 built from extra arguments supplied on the dprintf command
9080 line. */
9082 static void
9083 dprintf_command (const char *arg, int from_tty)
9085 location_spec_up locspec = string_to_location_spec (&arg, current_language);
9087 /* If non-NULL, ARG should have been advanced past the location;
9088 the next character must be ','. */
9089 if (arg != NULL)
9091 if (arg[0] != ',' || arg[1] == '\0')
9092 error (_("Format string required"));
9093 else
9095 /* Skip the comma. */
9096 ++arg;
9100 create_breakpoint (get_current_arch (),
9101 locspec.get (),
9102 NULL, 0, arg, false, 1 /* parse arg */,
9103 0, bp_dprintf,
9104 0 /* Ignore count */,
9105 pending_break_support,
9106 &code_breakpoint_ops,
9107 from_tty,
9108 1 /* enabled */,
9109 0 /* internal */,
9113 static void
9114 agent_printf_command (const char *arg, int from_tty)
9116 error (_("May only run agent-printf on the target"));
9119 /* Implement the "breakpoint_hit" method for ranged breakpoints. */
9122 ranged_breakpoint::breakpoint_hit (const struct bp_location *bl,
9123 const address_space *aspace,
9124 CORE_ADDR bp_addr,
9125 const target_waitstatus &ws)
9127 if (ws.kind () != TARGET_WAITKIND_STOPPED
9128 || ws.sig () != GDB_SIGNAL_TRAP)
9129 return 0;
9131 return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9132 bl->length, aspace, bp_addr);
9135 /* Implement the "resources_needed" method for ranged breakpoints. */
9138 ranged_breakpoint::resources_needed (const struct bp_location *bl)
9140 return target_ranged_break_num_registers ();
9143 /* Implement the "print_it" method for ranged breakpoints. */
9145 enum print_stop_action
9146 ranged_breakpoint::print_it (const bpstat *bs) const
9148 struct bp_location *bl = loc;
9149 struct ui_out *uiout = current_uiout;
9151 gdb_assert (type == bp_hardware_breakpoint);
9153 /* Ranged breakpoints have only one location. */
9154 gdb_assert (bl && bl->next == NULL);
9156 annotate_breakpoint (number);
9158 maybe_print_thread_hit_breakpoint (uiout);
9160 if (disposition == disp_del)
9161 uiout->text ("Temporary ranged breakpoint ");
9162 else
9163 uiout->text ("Ranged breakpoint ");
9164 if (uiout->is_mi_like_p ())
9166 uiout->field_string ("reason",
9167 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9168 uiout->field_string ("disp", bpdisp_text (disposition));
9170 uiout->field_signed ("bkptno", number);
9171 uiout->text (", ");
9173 return PRINT_SRC_AND_LOC;
9176 /* Implement the "print_one" method for ranged breakpoints. */
9178 bool
9179 ranged_breakpoint::print_one (bp_location **last_loc) const
9181 struct bp_location *bl = loc;
9182 struct value_print_options opts;
9183 struct ui_out *uiout = current_uiout;
9185 /* Ranged breakpoints have only one location. */
9186 gdb_assert (bl && bl->next == NULL);
9188 get_user_print_options (&opts);
9190 if (opts.addressprint)
9191 /* We don't print the address range here, it will be printed later
9192 by print_one_detail_ranged_breakpoint. */
9193 uiout->field_skip ("addr");
9194 annotate_field (5);
9195 print_breakpoint_location (this, bl);
9196 *last_loc = bl;
9198 return true;
9201 /* Implement the "print_one_detail" method for ranged breakpoints. */
9203 void
9204 ranged_breakpoint::print_one_detail (struct ui_out *uiout) const
9206 CORE_ADDR address_start, address_end;
9207 struct bp_location *bl = loc;
9208 string_file stb;
9210 gdb_assert (bl);
9212 address_start = bl->address;
9213 address_end = address_start + bl->length - 1;
9215 uiout->text ("\taddress range: ");
9216 stb.printf ("[%s, %s]",
9217 print_core_address (bl->gdbarch, address_start),
9218 print_core_address (bl->gdbarch, address_end));
9219 uiout->field_stream ("addr", stb);
9220 uiout->text ("\n");
9223 /* Implement the "print_mention" method for ranged breakpoints. */
9225 void
9226 ranged_breakpoint::print_mention () const
9228 struct bp_location *bl = loc;
9229 struct ui_out *uiout = current_uiout;
9231 gdb_assert (bl);
9232 gdb_assert (type == bp_hardware_breakpoint);
9234 uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9235 number, paddress (bl->gdbarch, bl->address),
9236 paddress (bl->gdbarch, bl->address + bl->length - 1));
9239 /* Implement the "print_recreate" method for ranged breakpoints. */
9241 void
9242 ranged_breakpoint::print_recreate (struct ui_file *fp) const
9244 gdb_printf (fp, "break-range %s, %s",
9245 locspec->to_string (),
9246 locspec_range_end->to_string ());
9247 print_recreate_thread (fp);
9250 /* Find the address where the end of the breakpoint range should be
9251 placed, given the SAL of the end of the range. This is so that if
9252 the user provides a line number, the end of the range is set to the
9253 last instruction of the given line. */
9255 static CORE_ADDR
9256 find_breakpoint_range_end (struct symtab_and_line sal)
9258 CORE_ADDR end;
9260 /* If the user provided a PC value, use it. Otherwise,
9261 find the address of the end of the given location. */
9262 if (sal.explicit_pc)
9263 end = sal.pc;
9264 else
9266 int ret;
9267 CORE_ADDR start;
9269 ret = find_line_pc_range (sal, &start, &end);
9270 if (!ret)
9271 error (_("Could not find location of the end of the range."));
9273 /* find_line_pc_range returns the start of the next line. */
9274 end--;
9277 return end;
9280 /* Implement the "break-range" CLI command. */
9282 static void
9283 break_range_command (const char *arg, int from_tty)
9285 const char *arg_start;
9286 struct linespec_result canonical_start, canonical_end;
9287 int bp_count, can_use_bp, length;
9288 CORE_ADDR end;
9290 /* We don't support software ranged breakpoints. */
9291 if (target_ranged_break_num_registers () < 0)
9292 error (_("This target does not support hardware ranged breakpoints."));
9294 bp_count = hw_breakpoint_used_count ();
9295 bp_count += target_ranged_break_num_registers ();
9296 can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9297 bp_count, 0);
9298 if (can_use_bp < 0)
9299 error (_("Hardware breakpoints used exceeds limit."));
9301 arg = skip_spaces (arg);
9302 if (arg == NULL || arg[0] == '\0')
9303 error(_("No address range specified."));
9305 arg_start = arg;
9306 location_spec_up start_locspec
9307 = string_to_location_spec (&arg, current_language);
9308 parse_breakpoint_sals (start_locspec.get (), &canonical_start);
9310 if (arg[0] != ',')
9311 error (_("Too few arguments."));
9312 else if (canonical_start.lsals.empty ())
9313 error (_("Could not find location of the beginning of the range."));
9315 const linespec_sals &lsal_start = canonical_start.lsals[0];
9317 if (canonical_start.lsals.size () > 1
9318 || lsal_start.sals.size () != 1)
9319 error (_("Cannot create a ranged breakpoint with multiple locations."));
9321 const symtab_and_line &sal_start = lsal_start.sals[0];
9322 std::string addr_string_start (arg_start, arg - arg_start);
9324 arg++; /* Skip the comma. */
9325 arg = skip_spaces (arg);
9327 /* Parse the end location specification. */
9329 arg_start = arg;
9331 /* We call decode_line_full directly here instead of using
9332 parse_breakpoint_sals because we need to specify the start
9333 location spec's symtab and line as the default symtab and line
9334 for the end of the range. This makes it possible to have ranges
9335 like "foo.c:27, +14", where +14 means 14 lines from the start
9336 location spec. */
9337 location_spec_up end_locspec
9338 = string_to_location_spec (&arg, current_language);
9339 decode_line_full (end_locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9340 sal_start.symtab, sal_start.line,
9341 &canonical_end, NULL, NULL);
9343 if (canonical_end.lsals.empty ())
9344 error (_("Could not find location of the end of the range."));
9346 const linespec_sals &lsal_end = canonical_end.lsals[0];
9347 if (canonical_end.lsals.size () > 1
9348 || lsal_end.sals.size () != 1)
9349 error (_("Cannot create a ranged breakpoint with multiple locations."));
9351 const symtab_and_line &sal_end = lsal_end.sals[0];
9353 end = find_breakpoint_range_end (sal_end);
9354 if (sal_start.pc > end)
9355 error (_("Invalid address range, end precedes start."));
9357 length = end - sal_start.pc + 1;
9358 if (length < 0)
9359 /* Length overflowed. */
9360 error (_("Address range too large."));
9361 else if (length == 1)
9363 /* This range is simple enough to be handled by
9364 the `hbreak' command. */
9365 hbreak_command (&addr_string_start[0], 1);
9367 return;
9370 /* Now set up the breakpoint and install it. */
9372 std::unique_ptr<breakpoint> br
9373 (new ranged_breakpoint (get_current_arch (),
9374 sal_start, length,
9375 std::move (start_locspec),
9376 std::move (end_locspec)));
9378 install_breakpoint (false, std::move (br), true);
9381 /* Return non-zero if EXP is verified as constant. Returned zero
9382 means EXP is variable. Also the constant detection may fail for
9383 some constant expressions and in such case still falsely return
9384 zero. */
9386 static bool
9387 watchpoint_exp_is_const (const struct expression *exp)
9389 return exp->op->constant_p ();
9392 /* Implement the "re_set" method for watchpoints. */
9394 void
9395 watchpoint::re_set ()
9397 /* Watchpoint can be either on expression using entirely global
9398 variables, or it can be on local variables.
9400 Watchpoints of the first kind are never auto-deleted, and even
9401 persist across program restarts. Since they can use variables
9402 from shared libraries, we need to reparse expression as libraries
9403 are loaded and unloaded.
9405 Watchpoints on local variables can also change meaning as result
9406 of solib event. For example, if a watchpoint uses both a local
9407 and a global variables in expression, it's a local watchpoint,
9408 but unloading of a shared library will make the expression
9409 invalid. This is not a very common use case, but we still
9410 re-evaluate expression, to avoid surprises to the user.
9412 Note that for local watchpoints, we re-evaluate it only if
9413 watchpoints frame id is still valid. If it's not, it means the
9414 watchpoint is out of scope and will be deleted soon. In fact,
9415 I'm not sure we'll ever be called in this case.
9417 If a local watchpoint's frame id is still valid, then
9418 exp_valid_block is likewise valid, and we can safely use it.
9420 Don't do anything about disabled watchpoints, since they will be
9421 reevaluated again when enabled. */
9422 update_watchpoint (this, 1 /* reparse */);
9425 /* Implement the "insert" method for hardware watchpoints. */
9428 watchpoint::insert_location (struct bp_location *bl)
9430 int length = exact ? 1 : bl->length;
9432 return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9433 cond_exp.get ());
9436 /* Implement the "remove" method for hardware watchpoints. */
9439 watchpoint::remove_location (struct bp_location *bl,
9440 enum remove_bp_reason reason)
9442 int length = exact ? 1 : bl->length;
9444 return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9445 cond_exp.get ());
9449 watchpoint::breakpoint_hit (const struct bp_location *bl,
9450 const address_space *aspace, CORE_ADDR bp_addr,
9451 const target_waitstatus &ws)
9453 struct breakpoint *b = bl->owner;
9455 /* Continuable hardware watchpoints are treated as non-existent if the
9456 reason we stopped wasn't a hardware watchpoint (we didn't stop on
9457 some data address). Otherwise gdb won't stop on a break instruction
9458 in the code (not from a breakpoint) when a hardware watchpoint has
9459 been defined. Also skip watchpoints which we know did not trigger
9460 (did not match the data address). */
9461 if (is_hardware_watchpoint (b)
9462 && watchpoint_triggered == watch_triggered_no)
9463 return 0;
9465 return 1;
9468 void
9469 watchpoint::check_status (bpstat *bs)
9471 gdb_assert (is_watchpoint (bs->breakpoint_at));
9473 bpstat_check_watchpoint (bs);
9476 /* Implement the "resources_needed" method for hardware
9477 watchpoints. */
9480 watchpoint::resources_needed (const struct bp_location *bl)
9482 int length = exact? 1 : bl->length;
9484 return target_region_ok_for_hw_watchpoint (bl->address, length);
9487 /* Implement the "works_in_software_mode" method for hardware
9488 watchpoints. */
9490 bool
9491 watchpoint::works_in_software_mode () const
9493 /* Read and access watchpoints only work with hardware support. */
9494 return type == bp_watchpoint || type == bp_hardware_watchpoint;
9497 enum print_stop_action
9498 watchpoint::print_it (const bpstat *bs) const
9500 struct breakpoint *b;
9501 enum print_stop_action result;
9502 struct ui_out *uiout = current_uiout;
9504 gdb_assert (bs->bp_location_at != NULL);
9506 b = bs->breakpoint_at;
9508 annotate_watchpoint (b->number);
9509 maybe_print_thread_hit_breakpoint (uiout);
9511 string_file stb;
9513 gdb::optional<ui_out_emit_tuple> tuple_emitter;
9514 switch (b->type)
9516 case bp_watchpoint:
9517 case bp_hardware_watchpoint:
9518 if (uiout->is_mi_like_p ())
9519 uiout->field_string
9520 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9521 mention (b);
9522 tuple_emitter.emplace (uiout, "value");
9523 uiout->text ("\nOld value = ");
9524 watchpoint_value_print (bs->old_val.get (), &stb);
9525 uiout->field_stream ("old", stb);
9526 uiout->text ("\nNew value = ");
9527 watchpoint_value_print (val.get (), &stb);
9528 uiout->field_stream ("new", stb);
9529 uiout->text ("\n");
9530 /* More than one watchpoint may have been triggered. */
9531 result = PRINT_UNKNOWN;
9532 break;
9534 case bp_read_watchpoint:
9535 if (uiout->is_mi_like_p ())
9536 uiout->field_string
9537 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9538 mention (b);
9539 tuple_emitter.emplace (uiout, "value");
9540 uiout->text ("\nValue = ");
9541 watchpoint_value_print (val.get (), &stb);
9542 uiout->field_stream ("value", stb);
9543 uiout->text ("\n");
9544 result = PRINT_UNKNOWN;
9545 break;
9547 case bp_access_watchpoint:
9548 if (bs->old_val != NULL)
9550 if (uiout->is_mi_like_p ())
9551 uiout->field_string
9552 ("reason",
9553 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9554 mention (b);
9555 tuple_emitter.emplace (uiout, "value");
9556 uiout->text ("\nOld value = ");
9557 watchpoint_value_print (bs->old_val.get (), &stb);
9558 uiout->field_stream ("old", stb);
9559 uiout->text ("\nNew value = ");
9561 else
9563 mention (b);
9564 if (uiout->is_mi_like_p ())
9565 uiout->field_string
9566 ("reason",
9567 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9568 tuple_emitter.emplace (uiout, "value");
9569 uiout->text ("\nValue = ");
9571 watchpoint_value_print (val.get (), &stb);
9572 uiout->field_stream ("new", stb);
9573 uiout->text ("\n");
9574 result = PRINT_UNKNOWN;
9575 break;
9576 default:
9577 result = PRINT_UNKNOWN;
9580 return result;
9583 /* Implement the "print_mention" method for hardware watchpoints. */
9585 void
9586 watchpoint::print_mention () const
9588 struct ui_out *uiout = current_uiout;
9589 const char *tuple_name;
9591 switch (type)
9593 case bp_watchpoint:
9594 uiout->text ("Watchpoint ");
9595 tuple_name = "wpt";
9596 break;
9597 case bp_hardware_watchpoint:
9598 uiout->text ("Hardware watchpoint ");
9599 tuple_name = "wpt";
9600 break;
9601 case bp_read_watchpoint:
9602 uiout->text ("Hardware read watchpoint ");
9603 tuple_name = "hw-rwpt";
9604 break;
9605 case bp_access_watchpoint:
9606 uiout->text ("Hardware access (read/write) watchpoint ");
9607 tuple_name = "hw-awpt";
9608 break;
9609 default:
9610 internal_error (__FILE__, __LINE__,
9611 _("Invalid hardware watchpoint type."));
9614 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
9615 uiout->field_signed ("number", number);
9616 uiout->text (": ");
9617 uiout->field_string ("exp", exp_string.get ());
9620 /* Implement the "print_recreate" method for watchpoints. */
9622 void
9623 watchpoint::print_recreate (struct ui_file *fp) const
9625 switch (type)
9627 case bp_watchpoint:
9628 case bp_hardware_watchpoint:
9629 gdb_printf (fp, "watch");
9630 break;
9631 case bp_read_watchpoint:
9632 gdb_printf (fp, "rwatch");
9633 break;
9634 case bp_access_watchpoint:
9635 gdb_printf (fp, "awatch");
9636 break;
9637 default:
9638 internal_error (__FILE__, __LINE__,
9639 _("Invalid watchpoint type."));
9642 gdb_printf (fp, " %s", exp_string.get ());
9643 print_recreate_thread (fp);
9646 /* Implement the "explains_signal" method for watchpoints. */
9648 bool
9649 watchpoint::explains_signal (enum gdb_signal sig)
9651 /* A software watchpoint cannot cause a signal other than
9652 GDB_SIGNAL_TRAP. */
9653 if (type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
9654 return false;
9656 return true;
9659 struct masked_watchpoint : public watchpoint
9661 using watchpoint::watchpoint;
9663 int insert_location (struct bp_location *) override;
9664 int remove_location (struct bp_location *,
9665 enum remove_bp_reason reason) override;
9666 int resources_needed (const struct bp_location *) override;
9667 bool works_in_software_mode () const override;
9668 enum print_stop_action print_it (const bpstat *bs) const override;
9669 void print_one_detail (struct ui_out *) const override;
9670 void print_mention () const override;
9671 void print_recreate (struct ui_file *fp) const override;
9674 /* Implement the "insert" method for masked hardware watchpoints. */
9677 masked_watchpoint::insert_location (struct bp_location *bl)
9679 return target_insert_mask_watchpoint (bl->address, hw_wp_mask,
9680 bl->watchpoint_type);
9683 /* Implement the "remove" method for masked hardware watchpoints. */
9686 masked_watchpoint::remove_location (struct bp_location *bl,
9687 enum remove_bp_reason reason)
9689 return target_remove_mask_watchpoint (bl->address, hw_wp_mask,
9690 bl->watchpoint_type);
9693 /* Implement the "resources_needed" method for masked hardware
9694 watchpoints. */
9697 masked_watchpoint::resources_needed (const struct bp_location *bl)
9699 return target_masked_watch_num_registers (bl->address, hw_wp_mask);
9702 /* Implement the "works_in_software_mode" method for masked hardware
9703 watchpoints. */
9705 bool
9706 masked_watchpoint::works_in_software_mode () const
9708 return false;
9711 /* Implement the "print_it" method for masked hardware
9712 watchpoints. */
9714 enum print_stop_action
9715 masked_watchpoint::print_it (const bpstat *bs) const
9717 struct breakpoint *b = bs->breakpoint_at;
9718 struct ui_out *uiout = current_uiout;
9720 /* Masked watchpoints have only one location. */
9721 gdb_assert (b->loc && b->loc->next == NULL);
9723 annotate_watchpoint (b->number);
9724 maybe_print_thread_hit_breakpoint (uiout);
9726 switch (b->type)
9728 case bp_hardware_watchpoint:
9729 if (uiout->is_mi_like_p ())
9730 uiout->field_string
9731 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9732 break;
9734 case bp_read_watchpoint:
9735 if (uiout->is_mi_like_p ())
9736 uiout->field_string
9737 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9738 break;
9740 case bp_access_watchpoint:
9741 if (uiout->is_mi_like_p ())
9742 uiout->field_string
9743 ("reason",
9744 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9745 break;
9746 default:
9747 internal_error (__FILE__, __LINE__,
9748 _("Invalid hardware watchpoint type."));
9751 mention (b);
9752 uiout->text (_("\n\
9753 Check the underlying instruction at PC for the memory\n\
9754 address and value which triggered this watchpoint.\n"));
9755 uiout->text ("\n");
9757 /* More than one watchpoint may have been triggered. */
9758 return PRINT_UNKNOWN;
9761 /* Implement the "print_one_detail" method for masked hardware
9762 watchpoints. */
9764 void
9765 masked_watchpoint::print_one_detail (struct ui_out *uiout) const
9767 /* Masked watchpoints have only one location. */
9768 gdb_assert (loc && loc->next == NULL);
9770 uiout->text ("\tmask ");
9771 uiout->field_core_addr ("mask", loc->gdbarch, hw_wp_mask);
9772 uiout->text ("\n");
9775 /* Implement the "print_mention" method for masked hardware
9776 watchpoints. */
9778 void
9779 masked_watchpoint::print_mention () const
9781 struct ui_out *uiout = current_uiout;
9782 const char *tuple_name;
9784 switch (type)
9786 case bp_hardware_watchpoint:
9787 uiout->text ("Masked hardware watchpoint ");
9788 tuple_name = "wpt";
9789 break;
9790 case bp_read_watchpoint:
9791 uiout->text ("Masked hardware read watchpoint ");
9792 tuple_name = "hw-rwpt";
9793 break;
9794 case bp_access_watchpoint:
9795 uiout->text ("Masked hardware access (read/write) watchpoint ");
9796 tuple_name = "hw-awpt";
9797 break;
9798 default:
9799 internal_error (__FILE__, __LINE__,
9800 _("Invalid hardware watchpoint type."));
9803 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
9804 uiout->field_signed ("number", number);
9805 uiout->text (": ");
9806 uiout->field_string ("exp", exp_string.get ());
9809 /* Implement the "print_recreate" method for masked hardware
9810 watchpoints. */
9812 void
9813 masked_watchpoint::print_recreate (struct ui_file *fp) const
9815 switch (type)
9817 case bp_hardware_watchpoint:
9818 gdb_printf (fp, "watch");
9819 break;
9820 case bp_read_watchpoint:
9821 gdb_printf (fp, "rwatch");
9822 break;
9823 case bp_access_watchpoint:
9824 gdb_printf (fp, "awatch");
9825 break;
9826 default:
9827 internal_error (__FILE__, __LINE__,
9828 _("Invalid hardware watchpoint type."));
9831 gdb_printf (fp, " %s mask 0x%s", exp_string.get (),
9832 phex (hw_wp_mask, sizeof (CORE_ADDR)));
9833 print_recreate_thread (fp);
9836 /* Tell whether the given watchpoint is a masked hardware watchpoint. */
9838 static bool
9839 is_masked_watchpoint (const struct breakpoint *b)
9841 return dynamic_cast<const masked_watchpoint *> (b) != nullptr;
9844 /* accessflag: hw_write: watch write,
9845 hw_read: watch read,
9846 hw_access: watch access (read or write) */
9847 static void
9848 watch_command_1 (const char *arg, int accessflag, int from_tty,
9849 bool just_location, bool internal)
9851 struct breakpoint *scope_breakpoint = NULL;
9852 const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
9853 struct value *result;
9854 int saved_bitpos = 0, saved_bitsize = 0;
9855 const char *exp_start = NULL;
9856 const char *exp_end = NULL;
9857 const char *tok, *end_tok;
9858 int toklen = -1;
9859 const char *cond_start = NULL;
9860 const char *cond_end = NULL;
9861 enum bptype bp_type;
9862 int thread = -1;
9863 /* Flag to indicate whether we are going to use masks for
9864 the hardware watchpoint. */
9865 bool use_mask = false;
9866 CORE_ADDR mask = 0;
9867 int task = 0;
9869 /* Make sure that we actually have parameters to parse. */
9870 if (arg != NULL && arg[0] != '\0')
9872 const char *value_start;
9874 exp_end = arg + strlen (arg);
9876 /* Look for "parameter value" pairs at the end
9877 of the arguments string. */
9878 for (tok = exp_end - 1; tok > arg; tok--)
9880 /* Skip whitespace at the end of the argument list. */
9881 while (tok > arg && (*tok == ' ' || *tok == '\t'))
9882 tok--;
9884 /* Find the beginning of the last token.
9885 This is the value of the parameter. */
9886 while (tok > arg && (*tok != ' ' && *tok != '\t'))
9887 tok--;
9888 value_start = tok + 1;
9890 /* Skip whitespace. */
9891 while (tok > arg && (*tok == ' ' || *tok == '\t'))
9892 tok--;
9894 end_tok = tok;
9896 /* Find the beginning of the second to last token.
9897 This is the parameter itself. */
9898 while (tok > arg && (*tok != ' ' && *tok != '\t'))
9899 tok--;
9900 tok++;
9901 toklen = end_tok - tok + 1;
9903 if (toklen == 6 && startswith (tok, "thread"))
9905 struct thread_info *thr;
9906 /* At this point we've found a "thread" token, which means
9907 the user is trying to set a watchpoint that triggers
9908 only in a specific thread. */
9909 const char *endp;
9911 if (thread != -1)
9912 error(_("You can specify only one thread."));
9914 /* Extract the thread ID from the next token. */
9915 thr = parse_thread_id (value_start, &endp);
9917 /* Check if the user provided a valid thread ID. */
9918 if (*endp != ' ' && *endp != '\t' && *endp != '\0')
9919 invalid_thread_id_error (value_start);
9921 thread = thr->global_num;
9923 else if (toklen == 4 && startswith (tok, "task"))
9925 char *tmp;
9927 task = strtol (value_start, &tmp, 0);
9928 if (tmp == value_start)
9929 error (_("Junk after task keyword."));
9930 if (!valid_task_id (task))
9931 error (_("Unknown task %d."), task);
9933 else if (toklen == 4 && startswith (tok, "mask"))
9935 /* We've found a "mask" token, which means the user wants to
9936 create a hardware watchpoint that is going to have the mask
9937 facility. */
9938 struct value *mask_value, *mark;
9940 if (use_mask)
9941 error(_("You can specify only one mask."));
9943 use_mask = just_location = true;
9945 mark = value_mark ();
9946 mask_value = parse_to_comma_and_eval (&value_start);
9947 mask = value_as_address (mask_value);
9948 value_free_to_mark (mark);
9950 else
9951 /* We didn't recognize what we found. We should stop here. */
9952 break;
9954 /* Truncate the string and get rid of the "parameter value" pair before
9955 the arguments string is parsed by the parse_exp_1 function. */
9956 exp_end = tok;
9959 else
9960 exp_end = arg;
9962 /* Parse the rest of the arguments. From here on out, everything
9963 is in terms of a newly allocated string instead of the original
9964 ARG. */
9965 std::string expression (arg, exp_end - arg);
9966 exp_start = arg = expression.c_str ();
9967 innermost_block_tracker tracker;
9968 expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
9969 exp_end = arg;
9970 /* Remove trailing whitespace from the expression before saving it.
9971 This makes the eventual display of the expression string a bit
9972 prettier. */
9973 while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
9974 --exp_end;
9976 /* Checking if the expression is not constant. */
9977 if (watchpoint_exp_is_const (exp.get ()))
9979 int len;
9981 len = exp_end - exp_start;
9982 while (len > 0 && isspace (exp_start[len - 1]))
9983 len--;
9984 error (_("Cannot watch constant value `%.*s'."), len, exp_start);
9987 exp_valid_block = tracker.block ();
9988 struct value *mark = value_mark ();
9989 struct value *val_as_value = nullptr;
9990 fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
9991 just_location);
9993 if (val_as_value != NULL && just_location)
9995 saved_bitpos = value_bitpos (val_as_value);
9996 saved_bitsize = value_bitsize (val_as_value);
9999 value_ref_ptr val;
10000 if (just_location)
10002 int ret;
10004 exp_valid_block = NULL;
10005 val = release_value (value_addr (result));
10006 value_free_to_mark (mark);
10008 if (use_mask)
10010 ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10011 mask);
10012 if (ret == -1)
10013 error (_("This target does not support masked watchpoints."));
10014 else if (ret == -2)
10015 error (_("Invalid mask or memory region."));
10018 else if (val_as_value != NULL)
10019 val = release_value (val_as_value);
10021 tok = skip_spaces (arg);
10022 end_tok = skip_to_space (tok);
10024 toklen = end_tok - tok;
10025 if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10027 tok = cond_start = end_tok + 1;
10028 innermost_block_tracker if_tracker;
10029 parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10031 /* The watchpoint expression may not be local, but the condition
10032 may still be. E.g.: `watch global if local > 0'. */
10033 cond_exp_valid_block = if_tracker.block ();
10035 cond_end = tok;
10037 if (*tok)
10038 error (_("Junk at end of command."));
10040 frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10042 /* Save this because create_internal_breakpoint below invalidates
10043 'wp_frame'. */
10044 frame_id watchpoint_frame = get_frame_id (wp_frame);
10046 /* If the expression is "local", then set up a "watchpoint scope"
10047 breakpoint at the point where we've left the scope of the watchpoint
10048 expression. Create the scope breakpoint before the watchpoint, so
10049 that we will encounter it first in bpstat_stop_status. */
10050 if (exp_valid_block != NULL && wp_frame != NULL)
10052 frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10054 if (frame_id_p (caller_frame_id))
10056 gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10057 CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10059 scope_breakpoint
10060 = create_internal_breakpoint (caller_arch, caller_pc,
10061 bp_watchpoint_scope);
10063 /* create_internal_breakpoint could invalidate WP_FRAME. */
10064 wp_frame = NULL;
10066 scope_breakpoint->enable_state = bp_enabled;
10068 /* Automatically delete the breakpoint when it hits. */
10069 scope_breakpoint->disposition = disp_del;
10071 /* Only break in the proper frame (help with recursion). */
10072 scope_breakpoint->frame_id = caller_frame_id;
10074 /* Set the address at which we will stop. */
10075 scope_breakpoint->loc->gdbarch = caller_arch;
10076 scope_breakpoint->loc->requested_address = caller_pc;
10077 scope_breakpoint->loc->address
10078 = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10079 scope_breakpoint->loc->requested_address,
10080 scope_breakpoint->type);
10084 /* Now set up the breakpoint. We create all watchpoints as hardware
10085 watchpoints here even if hardware watchpoints are turned off, a call
10086 to update_watchpoint later in this function will cause the type to
10087 drop back to bp_watchpoint (software watchpoint) if required. */
10089 if (accessflag == hw_read)
10090 bp_type = bp_read_watchpoint;
10091 else if (accessflag == hw_access)
10092 bp_type = bp_access_watchpoint;
10093 else
10094 bp_type = bp_hardware_watchpoint;
10096 std::unique_ptr<watchpoint> w;
10097 if (use_mask)
10098 w.reset (new masked_watchpoint (nullptr, bp_type));
10099 else
10100 w.reset (new watchpoint (nullptr, bp_type));
10102 w->thread = thread;
10103 w->task = task;
10104 w->disposition = disp_donttouch;
10105 w->pspace = current_program_space;
10106 w->exp = std::move (exp);
10107 w->exp_valid_block = exp_valid_block;
10108 w->cond_exp_valid_block = cond_exp_valid_block;
10109 if (just_location)
10111 struct type *t = value_type (val.get ());
10112 CORE_ADDR addr = value_as_address (val.get ());
10114 w->exp_string_reparse
10115 = current_language->watch_location_expression (t, addr);
10117 w->exp_string = xstrprintf ("-location %.*s",
10118 (int) (exp_end - exp_start), exp_start);
10120 else
10121 w->exp_string.reset (savestring (exp_start, exp_end - exp_start));
10123 if (use_mask)
10125 w->hw_wp_mask = mask;
10127 else
10129 w->val = val;
10130 w->val_bitpos = saved_bitpos;
10131 w->val_bitsize = saved_bitsize;
10132 w->val_valid = true;
10135 if (cond_start)
10136 w->cond_string.reset (savestring (cond_start, cond_end - cond_start));
10137 else
10138 w->cond_string = 0;
10140 if (frame_id_p (watchpoint_frame))
10142 w->watchpoint_frame = watchpoint_frame;
10143 w->watchpoint_thread = inferior_ptid;
10145 else
10147 w->watchpoint_frame = null_frame_id;
10148 w->watchpoint_thread = null_ptid;
10151 if (scope_breakpoint != NULL)
10153 /* The scope breakpoint is related to the watchpoint. We will
10154 need to act on them together. */
10155 w->related_breakpoint = scope_breakpoint;
10156 scope_breakpoint->related_breakpoint = w.get ();
10159 if (!just_location)
10160 value_free_to_mark (mark);
10162 /* Finally update the new watchpoint. This creates the locations
10163 that should be inserted. */
10164 update_watchpoint (w.get (), 1);
10166 install_breakpoint (internal, std::move (w), 1);
10169 /* Return count of debug registers needed to watch the given expression.
10170 If the watchpoint cannot be handled in hardware return zero. */
10172 static int
10173 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10175 int found_memory_cnt = 0;
10177 /* Did the user specifically forbid us to use hardware watchpoints? */
10178 if (!can_use_hw_watchpoints)
10179 return 0;
10181 gdb_assert (!vals.empty ());
10182 struct value *head = vals[0].get ();
10184 /* Make sure that the value of the expression depends only upon
10185 memory contents, and values computed from them within GDB. If we
10186 find any register references or function calls, we can't use a
10187 hardware watchpoint.
10189 The idea here is that evaluating an expression generates a series
10190 of values, one holding the value of every subexpression. (The
10191 expression a*b+c has five subexpressions: a, b, a*b, c, and
10192 a*b+c.) GDB's values hold almost enough information to establish
10193 the criteria given above --- they identify memory lvalues,
10194 register lvalues, computed values, etcetera. So we can evaluate
10195 the expression, and then scan the chain of values that leaves
10196 behind to decide whether we can detect any possible change to the
10197 expression's final value using only hardware watchpoints.
10199 However, I don't think that the values returned by inferior
10200 function calls are special in any way. So this function may not
10201 notice that an expression involving an inferior function call
10202 can't be watched with hardware watchpoints. FIXME. */
10203 for (const value_ref_ptr &iter : vals)
10205 struct value *v = iter.get ();
10207 if (VALUE_LVAL (v) == lval_memory)
10209 if (v != head && value_lazy (v))
10210 /* A lazy memory lvalue in the chain is one that GDB never
10211 needed to fetch; we either just used its address (e.g.,
10212 `a' in `a.b') or we never needed it at all (e.g., `a'
10213 in `a,b'). This doesn't apply to HEAD; if that is
10214 lazy then it was not readable, but watch it anyway. */
10216 else
10218 /* Ahh, memory we actually used! Check if we can cover
10219 it with hardware watchpoints. */
10220 struct type *vtype = check_typedef (value_type (v));
10222 /* We only watch structs and arrays if user asked for it
10223 explicitly, never if they just happen to appear in a
10224 middle of some value chain. */
10225 if (v == head
10226 || (vtype->code () != TYPE_CODE_STRUCT
10227 && vtype->code () != TYPE_CODE_ARRAY))
10229 CORE_ADDR vaddr = value_address (v);
10230 int len;
10231 int num_regs;
10233 len = (target_exact_watchpoints
10234 && is_scalar_type_recursive (vtype))?
10235 1 : TYPE_LENGTH (value_type (v));
10237 num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10238 if (!num_regs)
10239 return 0;
10240 else
10241 found_memory_cnt += num_regs;
10245 else if (VALUE_LVAL (v) != not_lval
10246 && deprecated_value_modifiable (v) == 0)
10247 return 0; /* These are values from the history (e.g., $1). */
10248 else if (VALUE_LVAL (v) == lval_register)
10249 return 0; /* Cannot watch a register with a HW watchpoint. */
10252 /* The expression itself looks suitable for using a hardware
10253 watchpoint, but give the target machine a chance to reject it. */
10254 return found_memory_cnt;
10257 void
10258 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10260 watch_command_1 (arg, hw_write, from_tty, 0, internal);
10263 /* Options for the watch, awatch, and rwatch commands. */
10265 struct watch_options
10267 /* For -location. */
10268 bool location = false;
10271 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10273 Historically GDB always accepted both '-location' and '-l' flags for
10274 these commands (both flags being synonyms). When converting to the
10275 newer option scheme only '-location' is added here. That's fine (for
10276 backward compatibility) as any non-ambiguous prefix of a flag will be
10277 accepted, so '-l', '-loc', are now all accepted.
10279 What this means is that, if in the future, we add any new flag here
10280 that starts with '-l' then this will break backward compatibility, so
10281 please, don't do that! */
10283 static const gdb::option::option_def watch_option_defs[] = {
10284 gdb::option::flag_option_def<watch_options> {
10285 "location",
10286 [] (watch_options *opt) { return &opt->location; },
10287 N_("\
10288 This evaluates EXPRESSION and watches the memory to which is refers.\n\
10289 -l can be used as a short form of -location."),
10293 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
10294 commands. */
10296 static gdb::option::option_def_group
10297 make_watch_options_def_group (watch_options *opts)
10299 return {{watch_option_defs}, opts};
10302 /* A helper function that looks for the "-location" argument and then
10303 calls watch_command_1. */
10305 static void
10306 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10308 watch_options opts;
10309 auto grp = make_watch_options_def_group (&opts);
10310 gdb::option::process_options
10311 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
10312 if (arg != nullptr && *arg == '\0')
10313 arg = nullptr;
10315 watch_command_1 (arg, accessflag, from_tty, opts.location, false);
10318 /* Command completion for 'watch', 'awatch', and 'rwatch' commands. */
10319 static void
10320 watch_command_completer (struct cmd_list_element *ignore,
10321 completion_tracker &tracker,
10322 const char *text, const char * /*word*/)
10324 const auto group = make_watch_options_def_group (nullptr);
10325 if (gdb::option::complete_options
10326 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
10327 return;
10329 const char *word = advance_to_expression_complete_word_point (tracker, text);
10330 expression_completer (ignore, tracker, text, word);
10333 static void
10334 watch_command (const char *arg, int from_tty)
10336 watch_maybe_just_location (arg, hw_write, from_tty);
10339 void
10340 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
10342 watch_command_1 (arg, hw_read, from_tty, 0, internal);
10345 static void
10346 rwatch_command (const char *arg, int from_tty)
10348 watch_maybe_just_location (arg, hw_read, from_tty);
10351 void
10352 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
10354 watch_command_1 (arg, hw_access, from_tty, 0, internal);
10357 static void
10358 awatch_command (const char *arg, int from_tty)
10360 watch_maybe_just_location (arg, hw_access, from_tty);
10364 /* Data for the FSM that manages the until(location)/advance commands
10365 in infcmd.c. Here because it uses the mechanisms of
10366 breakpoints. */
10368 struct until_break_fsm : public thread_fsm
10370 /* The thread that was current when the command was executed. */
10371 int thread;
10373 /* The breakpoint set at the return address in the caller frame,
10374 plus breakpoints at all the destination locations. */
10375 std::vector<breakpoint_up> breakpoints;
10377 until_break_fsm (struct interp *cmd_interp, int thread,
10378 std::vector<breakpoint_up> &&breakpoints)
10379 : thread_fsm (cmd_interp),
10380 thread (thread),
10381 breakpoints (std::move (breakpoints))
10385 void clean_up (struct thread_info *thread) override;
10386 bool should_stop (struct thread_info *thread) override;
10387 enum async_reply_reason do_async_reply_reason () override;
10390 /* Implementation of the 'should_stop' FSM method for the
10391 until(location)/advance commands. */
10393 bool
10394 until_break_fsm::should_stop (struct thread_info *tp)
10396 for (const breakpoint_up &bp : breakpoints)
10397 if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10398 bp.get ()) != NULL)
10400 set_finished ();
10401 break;
10404 return true;
10407 /* Implementation of the 'clean_up' FSM method for the
10408 until(location)/advance commands. */
10410 void
10411 until_break_fsm::clean_up (struct thread_info *)
10413 /* Clean up our temporary breakpoints. */
10414 breakpoints.clear ();
10415 delete_longjmp_breakpoint (thread);
10418 /* Implementation of the 'async_reply_reason' FSM method for the
10419 until(location)/advance commands. */
10421 enum async_reply_reason
10422 until_break_fsm::do_async_reply_reason ()
10424 return EXEC_ASYNC_LOCATION_REACHED;
10427 void
10428 until_break_command (const char *arg, int from_tty, int anywhere)
10430 struct frame_info *frame;
10431 struct gdbarch *frame_gdbarch;
10432 struct frame_id stack_frame_id;
10433 struct frame_id caller_frame_id;
10434 int thread;
10435 struct thread_info *tp;
10437 clear_proceed_status (0);
10439 /* Set a breakpoint where the user wants it and at return from
10440 this function. */
10442 location_spec_up locspec = string_to_location_spec (&arg, current_language);
10444 std::vector<symtab_and_line> sals
10445 = (last_displayed_sal_is_valid ()
10446 ? decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10447 get_last_displayed_symtab (),
10448 get_last_displayed_line ())
10449 : decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE,
10450 NULL, NULL, 0));
10452 if (sals.empty ())
10453 error (_("Couldn't get information on specified line."));
10455 if (*arg)
10456 error (_("Junk at end of arguments."));
10458 tp = inferior_thread ();
10459 thread = tp->global_num;
10461 /* Note linespec handling above invalidates the frame chain.
10462 Installing a breakpoint also invalidates the frame chain (as it
10463 may need to switch threads), so do any frame handling before
10464 that. */
10466 frame = get_selected_frame (NULL);
10467 frame_gdbarch = get_frame_arch (frame);
10468 stack_frame_id = get_stack_frame_id (frame);
10469 caller_frame_id = frame_unwind_caller_id (frame);
10471 /* Keep within the current frame, or in frames called by the current
10472 one. */
10474 std::vector<breakpoint_up> breakpoints;
10476 gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
10478 if (frame_id_p (caller_frame_id))
10480 struct symtab_and_line sal2;
10481 struct gdbarch *caller_gdbarch;
10483 sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10484 sal2.pc = frame_unwind_caller_pc (frame);
10485 caller_gdbarch = frame_unwind_caller_arch (frame);
10487 breakpoint_up caller_breakpoint
10488 = set_momentary_breakpoint (caller_gdbarch, sal2,
10489 caller_frame_id, bp_until);
10490 breakpoints.emplace_back (std::move (caller_breakpoint));
10492 set_longjmp_breakpoint (tp, stack_frame_id);
10493 lj_deleter.emplace (thread);
10496 /* set_momentary_breakpoint could invalidate FRAME. */
10497 frame = NULL;
10499 /* If the user told us to continue until a specified location, we
10500 don't specify a frame at which we need to stop. Otherwise,
10501 specify the selected frame, because we want to stop only at the
10502 very same frame. */
10503 frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
10505 for (symtab_and_line &sal : sals)
10507 resolve_sal_pc (&sal);
10509 breakpoint_up location_breakpoint
10510 = set_momentary_breakpoint (frame_gdbarch, sal,
10511 stop_frame_id, bp_until);
10512 breakpoints.emplace_back (std::move (location_breakpoint));
10515 tp->set_thread_fsm
10516 (std::unique_ptr<thread_fsm>
10517 (new until_break_fsm (command_interp (), tp->global_num,
10518 std::move (breakpoints))));
10520 if (lj_deleter)
10521 lj_deleter->release ();
10523 proceed (-1, GDB_SIGNAL_DEFAULT);
10528 /* Compare two breakpoints and return a strcmp-like result. */
10530 static int
10531 compare_breakpoints (const breakpoint *a, const breakpoint *b)
10533 uintptr_t ua = (uintptr_t) a;
10534 uintptr_t ub = (uintptr_t) b;
10536 if (a->number < b->number)
10537 return -1;
10538 else if (a->number > b->number)
10539 return 1;
10541 /* Now sort by address, in case we see, e..g, two breakpoints with
10542 the number 0. */
10543 if (ua < ub)
10544 return -1;
10545 return ua > ub ? 1 : 0;
10548 /* Delete breakpoints by address or line. */
10550 static void
10551 clear_command (const char *arg, int from_tty)
10553 int default_match;
10555 std::vector<symtab_and_line> decoded_sals;
10556 symtab_and_line last_sal;
10557 gdb::array_view<symtab_and_line> sals;
10558 if (arg)
10560 decoded_sals
10561 = decode_line_with_current_source (arg,
10562 (DECODE_LINE_FUNFIRSTLINE
10563 | DECODE_LINE_LIST_MODE));
10564 default_match = 0;
10565 sals = decoded_sals;
10567 else
10569 /* Set sal's line, symtab, pc, and pspace to the values
10570 corresponding to the last call to print_frame_info. If the
10571 codepoint is not valid, this will set all the fields to 0. */
10572 last_sal = get_last_displayed_sal ();
10573 if (last_sal.symtab == 0)
10574 error (_("No source file specified."));
10576 default_match = 1;
10577 sals = last_sal;
10580 /* We don't call resolve_sal_pc here. That's not as bad as it
10581 seems, because all existing breakpoints typically have both
10582 file/line and pc set. So, if clear is given file/line, we can
10583 match this to existing breakpoint without obtaining pc at all.
10585 We only support clearing given the address explicitly
10586 present in breakpoint table. Say, we've set breakpoint
10587 at file:line. There were several PC values for that file:line,
10588 due to optimization, all in one block.
10590 We've picked one PC value. If "clear" is issued with another
10591 PC corresponding to the same file:line, the breakpoint won't
10592 be cleared. We probably can still clear the breakpoint, but
10593 since the other PC value is never presented to user, user
10594 can only find it by guessing, and it does not seem important
10595 to support that. */
10597 /* For each line spec given, delete bps which correspond to it. Do
10598 it in two passes, solely to preserve the current behavior that
10599 from_tty is forced true if we delete more than one
10600 breakpoint. */
10602 std::vector<struct breakpoint *> found;
10603 for (const auto &sal : sals)
10605 const char *sal_fullname;
10607 /* If exact pc given, clear bpts at that pc.
10608 If line given (pc == 0), clear all bpts on specified line.
10609 If defaulting, clear all bpts on default line
10610 or at default pc.
10612 defaulting sal.pc != 0 tests to do
10614 0 1 pc
10615 1 1 pc _and_ line
10616 0 0 line
10617 1 0 <can't happen> */
10619 sal_fullname = (sal.symtab == NULL
10620 ? NULL : symtab_to_fullname (sal.symtab));
10622 /* Find all matching breakpoints and add them to 'found'. */
10623 for (breakpoint *b : all_breakpoints ())
10625 int match = 0;
10626 /* Are we going to delete b? */
10627 if (b->type != bp_none && !is_watchpoint (b)
10628 && user_breakpoint_p (b))
10630 for (bp_location *loc : b->locations ())
10632 /* If the user specified file:line, don't allow a PC
10633 match. This matches historical gdb behavior. */
10634 int pc_match = (!sal.explicit_line
10635 && sal.pc
10636 && (loc->pspace == sal.pspace)
10637 && (loc->address == sal.pc)
10638 && (!section_is_overlay (loc->section)
10639 || loc->section == sal.section));
10640 int line_match = 0;
10642 if ((default_match || sal.explicit_line)
10643 && loc->symtab != NULL
10644 && sal_fullname != NULL
10645 && sal.pspace == loc->pspace
10646 && loc->line_number == sal.line
10647 && filename_cmp (symtab_to_fullname (loc->symtab),
10648 sal_fullname) == 0)
10649 line_match = 1;
10651 if (pc_match || line_match)
10653 match = 1;
10654 break;
10659 if (match)
10660 found.push_back (b);
10664 /* Now go thru the 'found' chain and delete them. */
10665 if (found.empty ())
10667 if (arg)
10668 error (_("No breakpoint at %s."), arg);
10669 else
10670 error (_("No breakpoint at this line."));
10673 /* Remove duplicates from the vec. */
10674 std::sort (found.begin (), found.end (),
10675 [] (const breakpoint *bp_a, const breakpoint *bp_b)
10677 return compare_breakpoints (bp_a, bp_b) < 0;
10679 found.erase (std::unique (found.begin (), found.end (),
10680 [] (const breakpoint *bp_a, const breakpoint *bp_b)
10682 return compare_breakpoints (bp_a, bp_b) == 0;
10684 found.end ());
10686 if (found.size () > 1)
10687 from_tty = 1; /* Always report if deleted more than one. */
10688 if (from_tty)
10690 if (found.size () == 1)
10691 gdb_printf (_("Deleted breakpoint "));
10692 else
10693 gdb_printf (_("Deleted breakpoints "));
10696 for (breakpoint *iter : found)
10698 if (from_tty)
10699 gdb_printf ("%d ", iter->number);
10700 delete_breakpoint (iter);
10702 if (from_tty)
10703 gdb_putc ('\n');
10706 /* Delete breakpoint in BS if they are `delete' breakpoints and
10707 all breakpoints that are marked for deletion, whether hit or not.
10708 This is called after any breakpoint is hit, or after errors. */
10710 void
10711 breakpoint_auto_delete (bpstat *bs)
10713 for (; bs; bs = bs->next)
10714 if (bs->breakpoint_at
10715 && bs->breakpoint_at->disposition == disp_del
10716 && bs->stop)
10717 delete_breakpoint (bs->breakpoint_at);
10719 for (breakpoint *b : all_breakpoints_safe ())
10720 if (b->disposition == disp_del_at_next_stop)
10721 delete_breakpoint (b);
10724 /* A comparison function for bp_location AP and BP being interfaced to
10725 std::sort. Sort elements primarily by their ADDRESS (no matter what
10726 bl_address_is_meaningful says), secondarily by ordering first
10727 permanent elements and terciarily just ensuring the array is sorted
10728 stable way despite std::sort being an unstable algorithm. */
10730 static int
10731 bp_location_is_less_than (const bp_location *a, const bp_location *b)
10733 if (a->address != b->address)
10734 return a->address < b->address;
10736 /* Sort locations at the same address by their pspace number, keeping
10737 locations of the same inferior (in a multi-inferior environment)
10738 grouped. */
10740 if (a->pspace->num != b->pspace->num)
10741 return a->pspace->num < b->pspace->num;
10743 /* Sort permanent breakpoints first. */
10744 if (a->permanent != b->permanent)
10745 return a->permanent > b->permanent;
10747 /* Sort by type in order to make duplicate determination easier.
10748 See update_global_location_list. This is kept in sync with
10749 breakpoint_locations_match. */
10750 if (a->loc_type < b->loc_type)
10751 return true;
10753 /* Likewise, for range-breakpoints, sort by length. */
10754 if (a->loc_type == bp_loc_hardware_breakpoint
10755 && b->loc_type == bp_loc_hardware_breakpoint
10756 && a->length < b->length)
10757 return true;
10759 /* Make the internal GDB representation stable across GDB runs
10760 where A and B memory inside GDB can differ. Breakpoint locations of
10761 the same type at the same address can be sorted in arbitrary order. */
10763 if (a->owner->number != b->owner->number)
10764 return a->owner->number < b->owner->number;
10766 return a < b;
10769 /* Set bp_locations_placed_address_before_address_max and
10770 bp_locations_shadow_len_after_address_max according to the current
10771 content of the bp_locations array. */
10773 static void
10774 bp_locations_target_extensions_update (void)
10776 bp_locations_placed_address_before_address_max = 0;
10777 bp_locations_shadow_len_after_address_max = 0;
10779 for (bp_location *bl : all_bp_locations ())
10781 CORE_ADDR start, end, addr;
10783 if (!bp_location_has_shadow (bl))
10784 continue;
10786 start = bl->target_info.placed_address;
10787 end = start + bl->target_info.shadow_len;
10789 gdb_assert (bl->address >= start);
10790 addr = bl->address - start;
10791 if (addr > bp_locations_placed_address_before_address_max)
10792 bp_locations_placed_address_before_address_max = addr;
10794 /* Zero SHADOW_LEN would not pass bp_location_has_shadow. */
10796 gdb_assert (bl->address < end);
10797 addr = end - bl->address;
10798 if (addr > bp_locations_shadow_len_after_address_max)
10799 bp_locations_shadow_len_after_address_max = addr;
10803 /* Download tracepoint locations if they haven't been. */
10805 static void
10806 download_tracepoint_locations (void)
10808 enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
10810 scoped_restore_current_pspace_and_thread restore_pspace_thread;
10812 for (breakpoint *b : all_tracepoints ())
10814 struct tracepoint *t;
10815 int bp_location_downloaded = 0;
10817 if ((b->type == bp_fast_tracepoint
10818 ? !may_insert_fast_tracepoints
10819 : !may_insert_tracepoints))
10820 continue;
10822 if (can_download_tracepoint == TRIBOOL_UNKNOWN)
10824 if (target_can_download_tracepoint ())
10825 can_download_tracepoint = TRIBOOL_TRUE;
10826 else
10827 can_download_tracepoint = TRIBOOL_FALSE;
10830 if (can_download_tracepoint == TRIBOOL_FALSE)
10831 break;
10833 for (bp_location *bl : b->locations ())
10835 /* In tracepoint, locations are _never_ duplicated, so
10836 should_be_inserted is equivalent to
10837 unduplicated_should_be_inserted. */
10838 if (!should_be_inserted (bl) || bl->inserted)
10839 continue;
10841 switch_to_program_space_and_thread (bl->pspace);
10843 target_download_tracepoint (bl);
10845 bl->inserted = 1;
10846 bp_location_downloaded = 1;
10848 t = (struct tracepoint *) b;
10849 t->number_on_target = b->number;
10850 if (bp_location_downloaded)
10851 gdb::observers::breakpoint_modified.notify (b);
10855 /* Swap the insertion/duplication state between two locations. */
10857 static void
10858 swap_insertion (struct bp_location *left, struct bp_location *right)
10860 const int left_inserted = left->inserted;
10861 const int left_duplicate = left->duplicate;
10862 const int left_needs_update = left->needs_update;
10863 const struct bp_target_info left_target_info = left->target_info;
10865 /* Locations of tracepoints can never be duplicated. */
10866 if (is_tracepoint (left->owner))
10867 gdb_assert (!left->duplicate);
10868 if (is_tracepoint (right->owner))
10869 gdb_assert (!right->duplicate);
10871 left->inserted = right->inserted;
10872 left->duplicate = right->duplicate;
10873 left->needs_update = right->needs_update;
10874 left->target_info = right->target_info;
10875 right->inserted = left_inserted;
10876 right->duplicate = left_duplicate;
10877 right->needs_update = left_needs_update;
10878 right->target_info = left_target_info;
10881 /* Force the re-insertion of the locations at ADDRESS. This is called
10882 once a new/deleted/modified duplicate location is found and we are evaluating
10883 conditions on the target's side. Such conditions need to be updated on
10884 the target. */
10886 static void
10887 force_breakpoint_reinsertion (struct bp_location *bl)
10889 CORE_ADDR address = 0;
10890 int pspace_num;
10892 address = bl->address;
10893 pspace_num = bl->pspace->num;
10895 /* This is only meaningful if the target is
10896 evaluating conditions and if the user has
10897 opted for condition evaluation on the target's
10898 side. */
10899 if (gdb_evaluates_breakpoint_condition_p ()
10900 || !target_supports_evaluation_of_breakpoint_conditions ())
10901 return;
10903 /* Flag all breakpoint locations with this address and
10904 the same program space as the location
10905 as "its condition has changed". We need to
10906 update the conditions on the target's side. */
10907 for (bp_location *loc : all_bp_locations_at_addr (address))
10909 if (!is_breakpoint (loc->owner)
10910 || pspace_num != loc->pspace->num)
10911 continue;
10913 /* Flag the location appropriately. We use a different state to
10914 let everyone know that we already updated the set of locations
10915 with addr bl->address and program space bl->pspace. This is so
10916 we don't have to keep calling these functions just to mark locations
10917 that have already been marked. */
10918 loc->condition_changed = condition_updated;
10920 /* Free the agent expression bytecode as well. We will compute
10921 it later on. */
10922 loc->cond_bytecode.reset ();
10926 /* Called whether new breakpoints are created, or existing breakpoints
10927 deleted, to update the global location list and recompute which
10928 locations are duplicate of which.
10930 The INSERT_MODE flag determines whether locations may not, may, or
10931 shall be inserted now. See 'enum ugll_insert_mode' for more
10932 info. */
10934 static void
10935 update_global_location_list (enum ugll_insert_mode insert_mode)
10937 /* Last breakpoint location address that was marked for update. */
10938 CORE_ADDR last_addr = 0;
10939 /* Last breakpoint location program space that was marked for update. */
10940 int last_pspace_num = -1;
10942 /* Used in the duplicates detection below. When iterating over all
10943 bp_locations, points to the first bp_location of a given address.
10944 Breakpoints and watchpoints of different types are never
10945 duplicates of each other. Keep one pointer for each type of
10946 breakpoint/watchpoint, so we only need to loop over all locations
10947 once. */
10948 struct bp_location *bp_loc_first; /* breakpoint */
10949 struct bp_location *wp_loc_first; /* hardware watchpoint */
10950 struct bp_location *awp_loc_first; /* access watchpoint */
10951 struct bp_location *rwp_loc_first; /* read watchpoint */
10953 /* Saved former bp_locations array which we compare against the newly
10954 built bp_locations from the current state of ALL_BREAKPOINTS. */
10955 std::vector<bp_location *> old_locations = std::move (bp_locations);
10956 bp_locations.clear ();
10958 for (breakpoint *b : all_breakpoints ())
10959 for (bp_location *loc : b->locations ())
10960 bp_locations.push_back (loc);
10962 /* See if we need to "upgrade" a software breakpoint to a hardware
10963 breakpoint. Do this before deciding whether locations are
10964 duplicates. Also do this before sorting because sorting order
10965 depends on location type. */
10966 for (bp_location *loc : bp_locations)
10967 if (!loc->inserted && should_be_inserted (loc))
10968 handle_automatic_hardware_breakpoints (loc);
10970 std::sort (bp_locations.begin (), bp_locations.end (),
10971 bp_location_is_less_than);
10973 bp_locations_target_extensions_update ();
10975 /* Identify bp_location instances that are no longer present in the
10976 new list, and therefore should be freed. Note that it's not
10977 necessary that those locations should be removed from inferior --
10978 if there's another location at the same address (previously
10979 marked as duplicate), we don't need to remove/insert the
10980 location.
10982 LOCP is kept in sync with OLD_LOCP, each pointing to the current
10983 and former bp_location array state respectively. */
10985 size_t loc_i = 0;
10986 for (bp_location *old_loc : old_locations)
10988 /* Tells if 'old_loc' is found among the new locations. If
10989 not, we have to free it. */
10990 int found_object = 0;
10991 /* Tells if the location should remain inserted in the target. */
10992 int keep_in_target = 0;
10993 int removed = 0;
10995 /* Skip LOCP entries which will definitely never be needed.
10996 Stop either at or being the one matching OLD_LOC. */
10997 while (loc_i < bp_locations.size ()
10998 && bp_locations[loc_i]->address < old_loc->address)
10999 loc_i++;
11001 for (size_t loc2_i = loc_i;
11002 (loc2_i < bp_locations.size ()
11003 && bp_locations[loc2_i]->address == old_loc->address);
11004 loc2_i++)
11006 /* Check if this is a new/duplicated location or a duplicated
11007 location that had its condition modified. If so, we want to send
11008 its condition to the target if evaluation of conditions is taking
11009 place there. */
11010 if (bp_locations[loc2_i]->condition_changed == condition_modified
11011 && (last_addr != old_loc->address
11012 || last_pspace_num != old_loc->pspace->num))
11014 force_breakpoint_reinsertion (bp_locations[loc2_i]);
11015 last_pspace_num = old_loc->pspace->num;
11018 if (bp_locations[loc2_i] == old_loc)
11019 found_object = 1;
11022 /* We have already handled this address, update it so that we don't
11023 have to go through updates again. */
11024 last_addr = old_loc->address;
11026 /* Target-side condition evaluation: Handle deleted locations. */
11027 if (!found_object)
11028 force_breakpoint_reinsertion (old_loc);
11030 /* If this location is no longer present, and inserted, look if
11031 there's maybe a new location at the same address. If so,
11032 mark that one inserted, and don't remove this one. This is
11033 needed so that we don't have a time window where a breakpoint
11034 at certain location is not inserted. */
11036 if (old_loc->inserted)
11038 /* If the location is inserted now, we might have to remove
11039 it. */
11041 if (found_object && should_be_inserted (old_loc))
11043 /* The location is still present in the location list,
11044 and still should be inserted. Don't do anything. */
11045 keep_in_target = 1;
11047 else
11049 /* This location still exists, but it won't be kept in the
11050 target since it may have been disabled. We proceed to
11051 remove its target-side condition. */
11053 /* The location is either no longer present, or got
11054 disabled. See if there's another location at the
11055 same address, in which case we don't need to remove
11056 this one from the target. */
11058 /* OLD_LOC comes from existing struct breakpoint. */
11059 if (bl_address_is_meaningful (old_loc))
11061 for (size_t loc2_i = loc_i;
11062 (loc2_i < bp_locations.size ()
11063 && bp_locations[loc2_i]->address == old_loc->address);
11064 loc2_i++)
11066 bp_location *loc2 = bp_locations[loc2_i];
11068 if (loc2 == old_loc)
11069 continue;
11071 if (breakpoint_locations_match (loc2, old_loc))
11073 /* Read watchpoint locations are switched to
11074 access watchpoints, if the former are not
11075 supported, but the latter are. */
11076 if (is_hardware_watchpoint (old_loc->owner))
11078 gdb_assert (is_hardware_watchpoint (loc2->owner));
11079 loc2->watchpoint_type = old_loc->watchpoint_type;
11082 /* loc2 is a duplicated location. We need to check
11083 if it should be inserted in case it will be
11084 unduplicated. */
11085 if (unduplicated_should_be_inserted (loc2))
11087 swap_insertion (old_loc, loc2);
11088 keep_in_target = 1;
11089 break;
11096 if (!keep_in_target)
11098 if (remove_breakpoint (old_loc))
11100 /* This is just about all we can do. We could keep
11101 this location on the global list, and try to
11102 remove it next time, but there's no particular
11103 reason why we will succeed next time.
11105 Note that at this point, old_loc->owner is still
11106 valid, as delete_breakpoint frees the breakpoint
11107 only after calling us. */
11108 gdb_printf (_("warning: Error removing "
11109 "breakpoint %d\n"),
11110 old_loc->owner->number);
11112 removed = 1;
11116 if (!found_object)
11118 if (removed && target_is_non_stop_p ()
11119 && need_moribund_for_location_type (old_loc))
11121 /* This location was removed from the target. In
11122 non-stop mode, a race condition is possible where
11123 we've removed a breakpoint, but stop events for that
11124 breakpoint are already queued and will arrive later.
11125 We apply an heuristic to be able to distinguish such
11126 SIGTRAPs from other random SIGTRAPs: we keep this
11127 breakpoint location for a bit, and will retire it
11128 after we see some number of events. The theory here
11129 is that reporting of events should, "on the average",
11130 be fair, so after a while we'll see events from all
11131 threads that have anything of interest, and no longer
11132 need to keep this breakpoint location around. We
11133 don't hold locations forever so to reduce chances of
11134 mistaking a non-breakpoint SIGTRAP for a breakpoint
11135 SIGTRAP.
11137 The heuristic failing can be disastrous on
11138 decr_pc_after_break targets.
11140 On decr_pc_after_break targets, like e.g., x86-linux,
11141 if we fail to recognize a late breakpoint SIGTRAP,
11142 because events_till_retirement has reached 0 too
11143 soon, we'll fail to do the PC adjustment, and report
11144 a random SIGTRAP to the user. When the user resumes
11145 the inferior, it will most likely immediately crash
11146 with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11147 corrupted, because of being resumed e.g., in the
11148 middle of a multi-byte instruction, or skipped a
11149 one-byte instruction. This was actually seen happen
11150 on native x86-linux, and should be less rare on
11151 targets that do not support new thread events, like
11152 remote, due to the heuristic depending on
11153 thread_count.
11155 Mistaking a random SIGTRAP for a breakpoint trap
11156 causes similar symptoms (PC adjustment applied when
11157 it shouldn't), but then again, playing with SIGTRAPs
11158 behind the debugger's back is asking for trouble.
11160 Since hardware watchpoint traps are always
11161 distinguishable from other traps, so we don't need to
11162 apply keep hardware watchpoint moribund locations
11163 around. We simply always ignore hardware watchpoint
11164 traps we can no longer explain. */
11166 process_stratum_target *proc_target = nullptr;
11167 for (inferior *inf : all_inferiors ())
11168 if (inf->pspace == old_loc->pspace)
11170 proc_target = inf->process_target ();
11171 break;
11173 if (proc_target != nullptr)
11174 old_loc->events_till_retirement
11175 = 3 * (thread_count (proc_target) + 1);
11176 else
11177 old_loc->events_till_retirement = 1;
11178 old_loc->owner = NULL;
11180 moribund_locations.push_back (old_loc);
11182 else
11184 old_loc->owner = NULL;
11185 decref_bp_location (&old_loc);
11190 /* Rescan breakpoints at the same address and section, marking the
11191 first one as "first" and any others as "duplicates". This is so
11192 that the bpt instruction is only inserted once. If we have a
11193 permanent breakpoint at the same place as BPT, make that one the
11194 official one, and the rest as duplicates. Permanent breakpoints
11195 are sorted first for the same address.
11197 Do the same for hardware watchpoints, but also considering the
11198 watchpoint's type (regular/access/read) and length. */
11200 bp_loc_first = NULL;
11201 wp_loc_first = NULL;
11202 awp_loc_first = NULL;
11203 rwp_loc_first = NULL;
11205 for (bp_location *loc : all_bp_locations ())
11207 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11208 non-NULL. */
11209 struct bp_location **loc_first_p;
11210 breakpoint *b = loc->owner;
11212 if (!unduplicated_should_be_inserted (loc)
11213 || !bl_address_is_meaningful (loc)
11214 /* Don't detect duplicate for tracepoint locations because they are
11215 never duplicated. See the comments in field `duplicate' of
11216 `struct bp_location'. */
11217 || is_tracepoint (b))
11219 /* Clear the condition modification flag. */
11220 loc->condition_changed = condition_unchanged;
11221 continue;
11224 if (b->type == bp_hardware_watchpoint)
11225 loc_first_p = &wp_loc_first;
11226 else if (b->type == bp_read_watchpoint)
11227 loc_first_p = &rwp_loc_first;
11228 else if (b->type == bp_access_watchpoint)
11229 loc_first_p = &awp_loc_first;
11230 else
11231 loc_first_p = &bp_loc_first;
11233 if (*loc_first_p == NULL
11234 || (overlay_debugging && loc->section != (*loc_first_p)->section)
11235 || !breakpoint_locations_match (loc, *loc_first_p))
11237 *loc_first_p = loc;
11238 loc->duplicate = 0;
11240 if (is_breakpoint (loc->owner) && loc->condition_changed)
11242 loc->needs_update = 1;
11243 /* Clear the condition modification flag. */
11244 loc->condition_changed = condition_unchanged;
11246 continue;
11250 /* This and the above ensure the invariant that the first location
11251 is not duplicated, and is the inserted one.
11252 All following are marked as duplicated, and are not inserted. */
11253 if (loc->inserted)
11254 swap_insertion (loc, *loc_first_p);
11255 loc->duplicate = 1;
11257 /* Clear the condition modification flag. */
11258 loc->condition_changed = condition_unchanged;
11261 if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
11263 if (insert_mode != UGLL_DONT_INSERT)
11264 insert_breakpoint_locations ();
11265 else
11267 /* Even though the caller told us to not insert new
11268 locations, we may still need to update conditions on the
11269 target's side of breakpoints that were already inserted
11270 if the target is evaluating breakpoint conditions. We
11271 only update conditions for locations that are marked
11272 "needs_update". */
11273 update_inserted_breakpoint_locations ();
11277 if (insert_mode != UGLL_DONT_INSERT)
11278 download_tracepoint_locations ();
11281 void
11282 breakpoint_retire_moribund (void)
11284 for (int ix = 0; ix < moribund_locations.size (); ++ix)
11286 struct bp_location *loc = moribund_locations[ix];
11287 if (--(loc->events_till_retirement) == 0)
11289 decref_bp_location (&loc);
11290 unordered_remove (moribund_locations, ix);
11291 --ix;
11296 static void
11297 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
11302 update_global_location_list (insert_mode);
11304 catch (const gdb_exception_error &e)
11309 /* Clear BKP from a BPS. */
11311 static void
11312 bpstat_remove_bp_location (bpstat *bps, struct breakpoint *bpt)
11314 bpstat *bs;
11316 for (bs = bps; bs; bs = bs->next)
11317 if (bs->breakpoint_at == bpt)
11319 bs->breakpoint_at = NULL;
11320 bs->old_val = NULL;
11321 /* bs->commands will be freed later. */
11325 /* Callback for iterate_over_threads. */
11326 static int
11327 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11329 struct breakpoint *bpt = (struct breakpoint *) data;
11331 bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11332 return 0;
11335 /* Helper for breakpoint and tracepoint breakpoint->mention
11336 callbacks. */
11338 static void
11339 say_where (const breakpoint *b)
11341 struct value_print_options opts;
11343 get_user_print_options (&opts);
11345 /* i18n: cagney/2005-02-11: Below needs to be merged into a
11346 single string. */
11347 if (b->loc == NULL)
11349 /* For pending locations, the output differs slightly based
11350 on b->extra_string. If this is non-NULL, it contains either
11351 a condition or dprintf arguments. */
11352 if (b->extra_string == NULL)
11354 gdb_printf (_(" (%s) pending."), b->locspec->to_string ());
11356 else if (b->type == bp_dprintf)
11358 gdb_printf (_(" (%s,%s) pending."),
11359 b->locspec->to_string (),
11360 b->extra_string.get ());
11362 else
11364 gdb_printf (_(" (%s %s) pending."),
11365 b->locspec->to_string (),
11366 b->extra_string.get ());
11369 else
11371 if (opts.addressprint || b->loc->symtab == NULL)
11372 gdb_printf (" at %ps",
11373 styled_string (address_style.style (),
11374 paddress (b->loc->gdbarch,
11375 b->loc->address)));
11376 if (b->loc->symtab != NULL)
11378 /* If there is a single location, we can print the location
11379 more nicely. */
11380 if (b->loc->next == NULL)
11382 const char *filename
11383 = symtab_to_filename_for_display (b->loc->symtab);
11384 gdb_printf (": file %ps, line %d.",
11385 styled_string (file_name_style.style (),
11386 filename),
11387 b->loc->line_number);
11389 else
11390 /* This is not ideal, but each location may have a
11391 different file name, and this at least reflects the
11392 real situation somewhat. */
11393 gdb_printf (": %s.", b->locspec->to_string ());
11396 if (b->loc->next)
11398 struct bp_location *loc = b->loc;
11399 int n = 0;
11400 for (; loc; loc = loc->next)
11401 ++n;
11402 gdb_printf (" (%d locations)", n);
11407 /* See breakpoint.h. */
11409 bp_location_range breakpoint::locations () const
11411 return bp_location_range (this->loc);
11414 struct bp_location *
11415 breakpoint::allocate_location ()
11417 return new bp_location (this);
11420 #define internal_error_pure_virtual_called() \
11421 gdb_assert_not_reached ("pure virtual function called")
11424 breakpoint::insert_location (struct bp_location *bl)
11426 internal_error_pure_virtual_called ();
11430 breakpoint::remove_location (struct bp_location *bl,
11431 enum remove_bp_reason reason)
11433 internal_error_pure_virtual_called ();
11437 breakpoint::breakpoint_hit (const struct bp_location *bl,
11438 const address_space *aspace,
11439 CORE_ADDR bp_addr,
11440 const target_waitstatus &ws)
11442 internal_error_pure_virtual_called ();
11446 breakpoint::resources_needed (const struct bp_location *bl)
11448 internal_error_pure_virtual_called ();
11451 enum print_stop_action
11452 breakpoint::print_it (const bpstat *bs) const
11454 internal_error_pure_virtual_called ();
11457 void
11458 breakpoint::print_mention () const
11460 internal_error_pure_virtual_called ();
11463 void
11464 breakpoint::print_recreate (struct ui_file *fp) const
11466 internal_error_pure_virtual_called ();
11469 std::vector<symtab_and_line>
11470 breakpoint::decode_location_spec (location_spec *locspec,
11471 program_space *search_pspace)
11473 internal_error_pure_virtual_called ();
11476 /* Default breakpoint_ops methods. */
11478 void
11479 code_breakpoint::re_set ()
11481 /* FIXME: is this still reachable? */
11482 if (breakpoint_location_spec_empty_p (this))
11484 /* Anything without a location can't be re-set. */
11485 delete_breakpoint (this);
11486 return;
11489 breakpoint_re_set_default (this);
11493 code_breakpoint::insert_location (struct bp_location *bl)
11495 CORE_ADDR addr = bl->target_info.reqstd_address;
11497 bl->target_info.kind = breakpoint_kind (bl, &addr);
11498 bl->target_info.placed_address = addr;
11500 int result;
11501 if (bl->loc_type == bp_loc_hardware_breakpoint)
11502 result = target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
11503 else
11504 result = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
11506 if (result == 0 && bl->probe.prob != nullptr)
11508 /* The insertion was successful, now let's set the probe's semaphore
11509 if needed. */
11510 bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
11513 return result;
11517 code_breakpoint::remove_location (struct bp_location *bl,
11518 enum remove_bp_reason reason)
11520 if (bl->probe.prob != nullptr)
11522 /* Let's clear the semaphore before removing the location. */
11523 bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
11526 if (bl->loc_type == bp_loc_hardware_breakpoint)
11527 return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
11528 else
11529 return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
11533 code_breakpoint::breakpoint_hit (const struct bp_location *bl,
11534 const address_space *aspace,
11535 CORE_ADDR bp_addr,
11536 const target_waitstatus &ws)
11538 if (ws.kind () != TARGET_WAITKIND_STOPPED
11539 || ws.sig () != GDB_SIGNAL_TRAP)
11540 return 0;
11542 if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
11543 aspace, bp_addr))
11544 return 0;
11546 if (overlay_debugging /* unmapped overlay section */
11547 && section_is_overlay (bl->section)
11548 && !section_is_mapped (bl->section))
11549 return 0;
11551 return 1;
11555 dprintf_breakpoint::breakpoint_hit (const struct bp_location *bl,
11556 const address_space *aspace,
11557 CORE_ADDR bp_addr,
11558 const target_waitstatus &ws)
11560 if (dprintf_style == dprintf_style_agent
11561 && target_can_run_breakpoint_commands ())
11563 /* An agent-style dprintf never causes a stop. If we see a trap
11564 for this address it must be for a breakpoint that happens to
11565 be set at the same address. */
11566 return 0;
11569 return this->ordinary_breakpoint::breakpoint_hit (bl, aspace, bp_addr, ws);
11573 ordinary_breakpoint::resources_needed (const struct bp_location *bl)
11575 gdb_assert (type == bp_hardware_breakpoint);
11577 return 1;
11580 enum print_stop_action
11581 ordinary_breakpoint::print_it (const bpstat *bs) const
11583 const struct bp_location *bl;
11584 int bp_temp;
11585 struct ui_out *uiout = current_uiout;
11587 bl = bs->bp_location_at.get ();
11589 bp_temp = disposition == disp_del;
11590 if (bl->address != bl->requested_address)
11591 breakpoint_adjustment_warning (bl->requested_address,
11592 bl->address,
11593 number, 1);
11594 annotate_breakpoint (number);
11595 maybe_print_thread_hit_breakpoint (uiout);
11597 if (uiout->is_mi_like_p ())
11599 uiout->field_string ("reason",
11600 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11601 uiout->field_string ("disp", bpdisp_text (disposition));
11603 if (bp_temp)
11604 uiout->message ("Temporary breakpoint %pF, ",
11605 signed_field ("bkptno", number));
11606 else
11607 uiout->message ("Breakpoint %pF, ",
11608 signed_field ("bkptno", number));
11610 return PRINT_SRC_AND_LOC;
11613 void
11614 ordinary_breakpoint::print_mention () const
11616 if (current_uiout->is_mi_like_p ())
11617 return;
11619 switch (type)
11621 case bp_breakpoint:
11622 case bp_gnu_ifunc_resolver:
11623 if (disposition == disp_del)
11624 gdb_printf (_("Temporary breakpoint"));
11625 else
11626 gdb_printf (_("Breakpoint"));
11627 gdb_printf (_(" %d"), number);
11628 if (type == bp_gnu_ifunc_resolver)
11629 gdb_printf (_(" at gnu-indirect-function resolver"));
11630 break;
11631 case bp_hardware_breakpoint:
11632 gdb_printf (_("Hardware assisted breakpoint %d"), number);
11633 break;
11634 case bp_dprintf:
11635 gdb_printf (_("Dprintf %d"), number);
11636 break;
11639 say_where (this);
11642 void
11643 ordinary_breakpoint::print_recreate (struct ui_file *fp) const
11645 if (type == bp_breakpoint && disposition == disp_del)
11646 gdb_printf (fp, "tbreak");
11647 else if (type == bp_breakpoint)
11648 gdb_printf (fp, "break");
11649 else if (type == bp_hardware_breakpoint
11650 && disposition == disp_del)
11651 gdb_printf (fp, "thbreak");
11652 else if (type == bp_hardware_breakpoint)
11653 gdb_printf (fp, "hbreak");
11654 else
11655 internal_error (__FILE__, __LINE__,
11656 _("unhandled breakpoint type %d"), (int) type);
11658 gdb_printf (fp, " %s", locspec->to_string ());
11660 /* Print out extra_string if this breakpoint is pending. It might
11661 contain, for example, conditions that were set by the user. */
11662 if (loc == NULL && extra_string != NULL)
11663 gdb_printf (fp, " %s", extra_string.get ());
11665 print_recreate_thread (fp);
11668 std::vector<symtab_and_line>
11669 code_breakpoint::decode_location_spec (location_spec *locspec,
11670 program_space *search_pspace)
11672 if (locspec->type () == PROBE_LOCATION_SPEC)
11673 return bkpt_probe_decode_location_spec (this, locspec, search_pspace);
11675 return decode_location_spec_default (this, locspec, search_pspace);
11678 /* Virtual table for internal breakpoints. */
11680 void
11681 internal_breakpoint::re_set ()
11683 switch (type)
11685 /* Delete overlay event and longjmp master breakpoints; they
11686 will be reset later by breakpoint_re_set. */
11687 case bp_overlay_event:
11688 case bp_longjmp_master:
11689 case bp_std_terminate_master:
11690 case bp_exception_master:
11691 delete_breakpoint (this);
11692 break;
11694 /* This breakpoint is special, it's set up when the inferior
11695 starts and we really don't want to touch it. */
11696 case bp_shlib_event:
11698 /* Like bp_shlib_event, this breakpoint type is special. Once
11699 it is set up, we do not want to touch it. */
11700 case bp_thread_event:
11701 break;
11705 void
11706 internal_breakpoint::check_status (bpstat *bs)
11708 if (type == bp_shlib_event)
11710 /* If requested, stop when the dynamic linker notifies GDB of
11711 events. This allows the user to get control and place
11712 breakpoints in initializer routines for dynamically loaded
11713 objects (among other things). */
11714 bs->stop = stop_on_solib_events;
11715 bs->print = stop_on_solib_events;
11717 else
11718 bs->stop = 0;
11721 enum print_stop_action
11722 internal_breakpoint::print_it (const bpstat *bs) const
11724 switch (type)
11726 case bp_shlib_event:
11727 /* Did we stop because the user set the stop_on_solib_events
11728 variable? (If so, we report this as a generic, "Stopped due
11729 to shlib event" message.) */
11730 print_solib_event (false);
11731 break;
11733 case bp_thread_event:
11734 /* Not sure how we will get here.
11735 GDB should not stop for these breakpoints. */
11736 gdb_printf (_("Thread Event Breakpoint: gdb should not stop!\n"));
11737 break;
11739 case bp_overlay_event:
11740 /* By analogy with the thread event, GDB should not stop for these. */
11741 gdb_printf (_("Overlay Event Breakpoint: gdb should not stop!\n"));
11742 break;
11744 case bp_longjmp_master:
11745 /* These should never be enabled. */
11746 gdb_printf (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
11747 break;
11749 case bp_std_terminate_master:
11750 /* These should never be enabled. */
11751 gdb_printf (_("std::terminate Master Breakpoint: "
11752 "gdb should not stop!\n"));
11753 break;
11755 case bp_exception_master:
11756 /* These should never be enabled. */
11757 gdb_printf (_("Exception Master Breakpoint: "
11758 "gdb should not stop!\n"));
11759 break;
11762 return PRINT_NOTHING;
11765 void
11766 internal_breakpoint::print_mention () const
11768 /* Nothing to mention. These breakpoints are internal. */
11771 /* Virtual table for momentary breakpoints */
11773 void
11774 momentary_breakpoint::re_set ()
11776 /* Keep temporary breakpoints, which can be encountered when we step
11777 over a dlopen call and solib_add is resetting the breakpoints.
11778 Otherwise these should have been blown away via the cleanup chain
11779 or by breakpoint_init_inferior when we rerun the executable. */
11782 void
11783 momentary_breakpoint::check_status (bpstat *bs)
11785 /* Nothing. The point of these breakpoints is causing a stop. */
11788 enum print_stop_action
11789 momentary_breakpoint::print_it (const bpstat *bs) const
11791 return PRINT_UNKNOWN;
11794 void
11795 momentary_breakpoint::print_mention () const
11797 /* Nothing to mention. These breakpoints are internal. */
11800 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
11802 It gets cleared already on the removal of the first one of such placed
11803 breakpoints. This is OK as they get all removed altogether. */
11805 longjmp_breakpoint::~longjmp_breakpoint ()
11807 thread_info *tp = find_thread_global_id (this->thread);
11809 if (tp != NULL)
11810 tp->initiating_frame = null_frame_id;
11813 static void
11814 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
11815 struct linespec_result *canonical)
11818 struct linespec_sals lsal;
11820 lsal.sals = parse_probes (locspec, NULL, canonical);
11821 lsal.canonical = xstrdup (canonical->locspec->to_string ());
11822 canonical->lsals.push_back (std::move (lsal));
11825 static std::vector<symtab_and_line>
11826 bkpt_probe_decode_location_spec (struct breakpoint *b,
11827 location_spec *locspec,
11828 program_space *search_pspace)
11830 std::vector<symtab_and_line> sals
11831 = parse_probes (locspec, search_pspace, NULL);
11832 if (sals.empty ())
11833 error (_("probe not found"));
11834 return sals;
11838 tracepoint::breakpoint_hit (const struct bp_location *bl,
11839 const address_space *aspace, CORE_ADDR bp_addr,
11840 const target_waitstatus &ws)
11842 /* By definition, the inferior does not report stops at
11843 tracepoints. */
11844 return 0;
11847 void
11848 tracepoint::print_one_detail (struct ui_out *uiout) const
11850 if (!static_trace_marker_id.empty ())
11852 gdb_assert (type == bp_static_tracepoint
11853 || type == bp_static_marker_tracepoint);
11855 uiout->message ("\tmarker id is %pF\n",
11856 string_field ("static-tracepoint-marker-string-id",
11857 static_trace_marker_id.c_str ()));
11861 void
11862 tracepoint::print_mention () const
11864 if (current_uiout->is_mi_like_p ())
11865 return;
11867 switch (type)
11869 case bp_tracepoint:
11870 gdb_printf (_("Tracepoint"));
11871 gdb_printf (_(" %d"), number);
11872 break;
11873 case bp_fast_tracepoint:
11874 gdb_printf (_("Fast tracepoint"));
11875 gdb_printf (_(" %d"), number);
11876 break;
11877 case bp_static_tracepoint:
11878 case bp_static_marker_tracepoint:
11879 gdb_printf (_("Static tracepoint"));
11880 gdb_printf (_(" %d"), number);
11881 break;
11882 default:
11883 internal_error (__FILE__, __LINE__,
11884 _("unhandled tracepoint type %d"), (int) type);
11887 say_where (this);
11890 void
11891 tracepoint::print_recreate (struct ui_file *fp) const
11893 if (type == bp_fast_tracepoint)
11894 gdb_printf (fp, "ftrace");
11895 else if (type == bp_static_tracepoint
11896 || type == bp_static_marker_tracepoint)
11897 gdb_printf (fp, "strace");
11898 else if (type == bp_tracepoint)
11899 gdb_printf (fp, "trace");
11900 else
11901 internal_error (__FILE__, __LINE__,
11902 _("unhandled tracepoint type %d"), (int) type);
11904 gdb_printf (fp, " %s", locspec->to_string ());
11905 print_recreate_thread (fp);
11907 if (pass_count)
11908 gdb_printf (fp, " passcount %d\n", pass_count);
11911 /* Virtual table for tracepoints on static probes. */
11913 static void
11914 tracepoint_probe_create_sals_from_location_spec
11915 (location_spec *locspec,
11916 struct linespec_result *canonical)
11918 /* We use the same method for breakpoint on probes. */
11919 bkpt_probe_create_sals_from_location_spec (locspec, canonical);
11922 void
11923 dprintf_breakpoint::re_set ()
11925 breakpoint_re_set_default (this);
11927 /* extra_string should never be non-NULL for dprintf. */
11928 gdb_assert (extra_string != NULL);
11930 /* 1 - connect to target 1, that can run breakpoint commands.
11931 2 - create a dprintf, which resolves fine.
11932 3 - disconnect from target 1
11933 4 - connect to target 2, that can NOT run breakpoint commands.
11935 After steps #3/#4, you'll want the dprintf command list to
11936 be updated, because target 1 and 2 may well return different
11937 answers for target_can_run_breakpoint_commands().
11938 Given absence of finer grained resetting, we get to do
11939 it all the time. */
11940 if (extra_string != NULL)
11941 update_dprintf_command_list (this);
11944 /* Implement the "print_recreate" method for dprintf. */
11946 void
11947 dprintf_breakpoint::print_recreate (struct ui_file *fp) const
11949 gdb_printf (fp, "dprintf %s,%s", locspec->to_string (), extra_string.get ());
11950 print_recreate_thread (fp);
11953 /* Implement the "after_condition_true" method for dprintf.
11955 dprintf's are implemented with regular commands in their command
11956 list, but we run the commands here instead of before presenting the
11957 stop to the user, as dprintf's don't actually cause a stop. This
11958 also makes it so that the commands of multiple dprintfs at the same
11959 address are all handled. */
11961 void
11962 dprintf_breakpoint::after_condition_true (struct bpstat *bs)
11964 /* dprintf's never cause a stop. This wasn't set in the
11965 check_status hook instead because that would make the dprintf's
11966 condition not be evaluated. */
11967 bs->stop = 0;
11969 /* Run the command list here. Take ownership of it instead of
11970 copying. We never want these commands to run later in
11971 bpstat_do_actions, if a breakpoint that causes a stop happens to
11972 be set at same address as this dprintf, or even if running the
11973 commands here throws. */
11974 counted_command_line cmds = std::move (bs->commands);
11975 gdb_assert (cmds != nullptr);
11976 execute_control_commands (cmds.get (), 0);
11979 /* The breakpoint_ops structure to be used on static tracepoints with
11980 markers (`-m'). */
11982 static void
11983 strace_marker_create_sals_from_location_spec (location_spec *locspec,
11984 struct linespec_result *canonical)
11986 struct linespec_sals lsal;
11987 const char *arg_start, *arg;
11989 arg = arg_start = as_linespec_location_spec (locspec)->spec_string;
11990 lsal.sals = decode_static_tracepoint_spec (&arg);
11992 std::string str (arg_start, arg - arg_start);
11993 const char *ptr = str.c_str ();
11994 canonical->locspec
11995 = new_linespec_location_spec (&ptr, symbol_name_match_type::FULL);
11997 lsal.canonical = xstrdup (canonical->locspec->to_string ());
11998 canonical->lsals.push_back (std::move (lsal));
12001 static void
12002 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12003 struct linespec_result *canonical,
12004 gdb::unique_xmalloc_ptr<char> cond_string,
12005 gdb::unique_xmalloc_ptr<char> extra_string,
12006 enum bptype type_wanted,
12007 enum bpdisp disposition,
12008 int thread,
12009 int task, int ignore_count,
12010 int from_tty, int enabled,
12011 int internal, unsigned flags)
12013 const linespec_sals &lsal = canonical->lsals[0];
12015 /* If the user is creating a static tracepoint by marker id
12016 (strace -m MARKER_ID), then store the sals index, so that
12017 breakpoint_re_set can try to match up which of the newly
12018 found markers corresponds to this one, and, don't try to
12019 expand multiple locations for each sal, given than SALS
12020 already should contain all sals for MARKER_ID. */
12022 for (size_t i = 0; i < lsal.sals.size (); i++)
12024 location_spec_up locspec = canonical->locspec->clone ();
12026 std::unique_ptr<tracepoint> tp
12027 (new tracepoint (gdbarch,
12028 type_wanted,
12029 lsal.sals[i],
12030 std::move (locspec),
12031 NULL,
12032 std::move (cond_string),
12033 std::move (extra_string),
12034 disposition,
12035 thread, task, ignore_count,
12036 from_tty, enabled, flags,
12037 canonical->special_display));
12039 /* Given that its possible to have multiple markers with
12040 the same string id, if the user is creating a static
12041 tracepoint by marker id ("strace -m MARKER_ID"), then
12042 store the sals index, so that breakpoint_re_set can
12043 try to match up which of the newly found markers
12044 corresponds to this one */
12045 tp->static_trace_marker_id_idx = i;
12047 install_breakpoint (internal, std::move (tp), 0);
12051 std::vector<symtab_and_line>
12052 static_marker_tracepoint::decode_location_spec (location_spec *locspec,
12053 program_space *search_pspace)
12055 const char *s = as_linespec_location_spec (locspec)->spec_string;
12057 std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
12058 if (sals.size () > static_trace_marker_id_idx)
12060 sals[0] = sals[static_trace_marker_id_idx];
12061 sals.resize (1);
12062 return sals;
12064 else
12065 error (_("marker %s not found"), static_trace_marker_id.c_str ());
12068 /* Static tracepoints with marker (`-m'). */
12069 static struct breakpoint_ops strace_marker_breakpoint_ops =
12071 strace_marker_create_sals_from_location_spec,
12072 strace_marker_create_breakpoints_sal,
12075 static int
12076 strace_marker_p (struct breakpoint *b)
12078 return b->type == bp_static_marker_tracepoint;
12081 /* Delete a breakpoint and clean up all traces of it in the data
12082 structures. */
12084 void
12085 delete_breakpoint (struct breakpoint *bpt)
12087 gdb_assert (bpt != NULL);
12089 /* Has this bp already been deleted? This can happen because
12090 multiple lists can hold pointers to bp's. bpstat lists are
12091 especial culprits.
12093 One example of this happening is a watchpoint's scope bp. When
12094 the scope bp triggers, we notice that the watchpoint is out of
12095 scope, and delete it. We also delete its scope bp. But the
12096 scope bp is marked "auto-deleting", and is already on a bpstat.
12097 That bpstat is then checked for auto-deleting bp's, which are
12098 deleted.
12100 A real solution to this problem might involve reference counts in
12101 bp's, and/or giving them pointers back to their referencing
12102 bpstat's, and teaching delete_breakpoint to only free a bp's
12103 storage when no more references were extent. A cheaper bandaid
12104 was chosen. */
12105 if (bpt->type == bp_none)
12106 return;
12108 /* At least avoid this stale reference until the reference counting
12109 of breakpoints gets resolved. */
12110 if (bpt->related_breakpoint != bpt)
12112 struct breakpoint *related;
12113 struct watchpoint *w;
12115 if (bpt->type == bp_watchpoint_scope)
12116 w = (struct watchpoint *) bpt->related_breakpoint;
12117 else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12118 w = (struct watchpoint *) bpt;
12119 else
12120 w = NULL;
12121 if (w != NULL)
12122 watchpoint_del_at_next_stop (w);
12124 /* Unlink bpt from the bpt->related_breakpoint ring. */
12125 for (related = bpt; related->related_breakpoint != bpt;
12126 related = related->related_breakpoint);
12127 related->related_breakpoint = bpt->related_breakpoint;
12128 bpt->related_breakpoint = bpt;
12131 /* watch_command_1 creates a watchpoint but only sets its number if
12132 update_watchpoint succeeds in creating its bp_locations. If there's
12133 a problem in that process, we'll be asked to delete the half-created
12134 watchpoint. In that case, don't announce the deletion. */
12135 if (bpt->number)
12136 gdb::observers::breakpoint_deleted.notify (bpt);
12138 if (breakpoint_chain == bpt)
12139 breakpoint_chain = bpt->next;
12141 for (breakpoint *b : all_breakpoints ())
12142 if (b->next == bpt)
12144 b->next = bpt->next;
12145 break;
12148 /* Be sure no bpstat's are pointing at the breakpoint after it's
12149 been freed. */
12150 /* FIXME, how can we find all bpstat's? We just check stop_bpstat
12151 in all threads for now. Note that we cannot just remove bpstats
12152 pointing at bpt from the stop_bpstat list entirely, as breakpoint
12153 commands are associated with the bpstat; if we remove it here,
12154 then the later call to bpstat_do_actions (&stop_bpstat); in
12155 event-top.c won't do anything, and temporary breakpoints with
12156 commands won't work. */
12158 iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12160 /* Now that breakpoint is removed from breakpoint list, update the
12161 global location list. This will remove locations that used to
12162 belong to this breakpoint. Do this before freeing the breakpoint
12163 itself, since remove_breakpoint looks at location's owner. It
12164 might be better design to have location completely
12165 self-contained, but it's not the case now. */
12166 update_global_location_list (UGLL_DONT_INSERT);
12168 /* On the chance that someone will soon try again to delete this
12169 same bp, we mark it as deleted before freeing its storage. */
12170 bpt->type = bp_none;
12171 delete bpt;
12174 /* Iterator function to call a user-provided callback function once
12175 for each of B and its related breakpoints. */
12177 static void
12178 iterate_over_related_breakpoints (struct breakpoint *b,
12179 gdb::function_view<void (breakpoint *)> function)
12181 struct breakpoint *related;
12183 related = b;
12186 struct breakpoint *next;
12188 /* FUNCTION may delete RELATED. */
12189 next = related->related_breakpoint;
12191 if (next == related)
12193 /* RELATED is the last ring entry. */
12194 function (related);
12196 /* FUNCTION may have deleted it, so we'd never reach back to
12197 B. There's nothing left to do anyway, so just break
12198 out. */
12199 break;
12201 else
12202 function (related);
12204 related = next;
12206 while (related != b);
12209 static void
12210 delete_command (const char *arg, int from_tty)
12212 dont_repeat ();
12214 if (arg == 0)
12216 int breaks_to_delete = 0;
12218 /* Delete all breakpoints if no argument. Do not delete
12219 internal breakpoints, these have to be deleted with an
12220 explicit breakpoint number argument. */
12221 for (breakpoint *b : all_breakpoints ())
12222 if (user_breakpoint_p (b))
12224 breaks_to_delete = 1;
12225 break;
12228 /* Ask user only if there are some breakpoints to delete. */
12229 if (!from_tty
12230 || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12231 for (breakpoint *b : all_breakpoints_safe ())
12232 if (user_breakpoint_p (b))
12233 delete_breakpoint (b);
12235 else
12236 map_breakpoint_numbers
12237 (arg, [&] (breakpoint *br)
12239 iterate_over_related_breakpoints (br, delete_breakpoint);
12243 /* Return true if all locations of B bound to PSPACE are pending. If
12244 PSPACE is NULL, all locations of all program spaces are
12245 considered. */
12247 static int
12248 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
12250 for (bp_location *loc : b->locations ())
12251 if ((pspace == NULL
12252 || loc->pspace == pspace)
12253 && !loc->shlib_disabled
12254 && !loc->pspace->executing_startup)
12255 return 0;
12256 return 1;
12259 /* Subroutine of update_breakpoint_locations to simplify it.
12260 Return non-zero if multiple fns in list LOC have the same name.
12261 Null names are ignored. */
12263 static int
12264 ambiguous_names_p (struct bp_location *loc)
12266 struct bp_location *l;
12267 htab_up htab (htab_create_alloc (13, htab_hash_string, htab_eq_string, NULL,
12268 xcalloc, xfree));
12270 for (l = loc; l != NULL; l = l->next)
12272 const char **slot;
12273 const char *name = l->function_name.get ();
12275 /* Allow for some names to be NULL, ignore them. */
12276 if (name == NULL)
12277 continue;
12279 slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
12280 INSERT);
12281 /* NOTE: We can assume slot != NULL here because xcalloc never
12282 returns NULL. */
12283 if (*slot != NULL)
12284 return 1;
12285 *slot = name;
12288 return 0;
12291 /* When symbols change, it probably means the sources changed as well,
12292 and it might mean the static tracepoint markers are no longer at
12293 the same address or line numbers they used to be at last we
12294 checked. Losing your static tracepoints whenever you rebuild is
12295 undesirable. This function tries to resync/rematch gdb static
12296 tracepoints with the markers on the target, for static tracepoints
12297 that have not been set by marker id. Static tracepoint that have
12298 been set by marker id are reset by marker id in breakpoint_re_set.
12299 The heuristic is:
12301 1) For a tracepoint set at a specific address, look for a marker at
12302 the old PC. If one is found there, assume to be the same marker.
12303 If the name / string id of the marker found is different from the
12304 previous known name, assume that means the user renamed the marker
12305 in the sources, and output a warning.
12307 2) For a tracepoint set at a given line number, look for a marker
12308 at the new address of the old line number. If one is found there,
12309 assume to be the same marker. If the name / string id of the
12310 marker found is different from the previous known name, assume that
12311 means the user renamed the marker in the sources, and output a
12312 warning.
12314 3) If a marker is no longer found at the same address or line, it
12315 may mean the marker no longer exists. But it may also just mean
12316 the code changed a bit. Maybe the user added a few lines of code
12317 that made the marker move up or down (in line number terms). Ask
12318 the target for info about the marker with the string id as we knew
12319 it. If found, update line number and address in the matching
12320 static tracepoint. This will get confused if there's more than one
12321 marker with the same ID (possible in UST, although unadvised
12322 precisely because it confuses tools). */
12324 static struct symtab_and_line
12325 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12327 struct tracepoint *tp = (struct tracepoint *) b;
12328 struct static_tracepoint_marker marker;
12329 CORE_ADDR pc;
12331 pc = sal.pc;
12332 if (sal.line)
12333 find_line_pc (sal.symtab, sal.line, &pc);
12335 if (target_static_tracepoint_marker_at (pc, &marker))
12337 if (tp->static_trace_marker_id != marker.str_id)
12338 warning (_("static tracepoint %d changed probed marker from %s to %s"),
12339 b->number, tp->static_trace_marker_id.c_str (),
12340 marker.str_id.c_str ());
12342 tp->static_trace_marker_id = std::move (marker.str_id);
12344 return sal;
12347 /* Old marker wasn't found on target at lineno. Try looking it up
12348 by string ID. */
12349 if (!sal.explicit_pc
12350 && sal.line != 0
12351 && sal.symtab != NULL
12352 && !tp->static_trace_marker_id.empty ())
12354 std::vector<static_tracepoint_marker> markers
12355 = target_static_tracepoint_markers_by_strid
12356 (tp->static_trace_marker_id.c_str ());
12358 if (!markers.empty ())
12360 struct symbol *sym;
12361 struct static_tracepoint_marker *tpmarker;
12362 struct ui_out *uiout = current_uiout;
12364 tpmarker = &markers[0];
12366 tp->static_trace_marker_id = std::move (tpmarker->str_id);
12368 warning (_("marker for static tracepoint %d (%s) not "
12369 "found at previous line number"),
12370 b->number, tp->static_trace_marker_id.c_str ());
12372 symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
12373 sym = find_pc_sect_function (tpmarker->address, NULL);
12374 uiout->text ("Now in ");
12375 if (sym)
12377 uiout->field_string ("func", sym->print_name (),
12378 function_name_style.style ());
12379 uiout->text (" at ");
12381 uiout->field_string ("file",
12382 symtab_to_filename_for_display (sal2.symtab),
12383 file_name_style.style ());
12384 uiout->text (":");
12386 if (uiout->is_mi_like_p ())
12388 const char *fullname = symtab_to_fullname (sal2.symtab);
12390 uiout->field_string ("fullname", fullname);
12393 uiout->field_signed ("line", sal2.line);
12394 uiout->text ("\n");
12396 b->loc->line_number = sal2.line;
12397 b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
12399 std::unique_ptr<explicit_location_spec> els
12400 (new explicit_location_spec ());
12401 els->source_filename
12402 = xstrdup (symtab_to_filename_for_display (sal2.symtab));
12403 els->line_offset.offset = b->loc->line_number;
12404 els->line_offset.sign = LINE_OFFSET_NONE;
12406 b->locspec = std::move (els);
12408 /* Might be nice to check if function changed, and warn if
12409 so. */
12412 return sal;
12415 /* Returns 1 iff locations A and B are sufficiently same that
12416 we don't need to report breakpoint as changed. */
12418 static int
12419 locations_are_equal (struct bp_location *a, struct bp_location *b)
12421 while (a && b)
12423 if (a->address != b->address)
12424 return 0;
12426 if (a->shlib_disabled != b->shlib_disabled)
12427 return 0;
12429 if (a->enabled != b->enabled)
12430 return 0;
12432 if (a->disabled_by_cond != b->disabled_by_cond)
12433 return 0;
12435 a = a->next;
12436 b = b->next;
12439 if ((a == NULL) != (b == NULL))
12440 return 0;
12442 return 1;
12445 /* Split all locations of B that are bound to PSPACE out of B's
12446 location list to a separate list and return that list's head. If
12447 PSPACE is NULL, hoist out all locations of B. */
12449 static struct bp_location *
12450 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
12452 struct bp_location head;
12453 struct bp_location *i = b->loc;
12454 struct bp_location **i_link = &b->loc;
12455 struct bp_location *hoisted = &head;
12457 if (pspace == NULL)
12459 i = b->loc;
12460 b->loc = NULL;
12461 return i;
12464 head.next = NULL;
12466 while (i != NULL)
12468 if (i->pspace == pspace)
12470 *i_link = i->next;
12471 i->next = NULL;
12472 hoisted->next = i;
12473 hoisted = i;
12475 else
12476 i_link = &i->next;
12477 i = *i_link;
12480 return head.next;
12483 /* Create new breakpoint locations for B (a hardware or software
12484 breakpoint) based on SALS and SALS_END. If SALS_END.NELTS is not
12485 zero, then B is a ranged breakpoint. Only recreates locations for
12486 FILTER_PSPACE. Locations of other program spaces are left
12487 untouched. */
12489 void
12490 update_breakpoint_locations (code_breakpoint *b,
12491 struct program_space *filter_pspace,
12492 gdb::array_view<const symtab_and_line> sals,
12493 gdb::array_view<const symtab_and_line> sals_end)
12495 struct bp_location *existing_locations;
12497 if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
12499 /* Ranged breakpoints have only one start location and one end
12500 location. */
12501 b->enable_state = bp_disabled;
12502 gdb_printf (gdb_stderr,
12503 _("Could not reset ranged breakpoint %d: "
12504 "multiple locations found\n"),
12505 b->number);
12506 return;
12509 /* If there's no new locations, and all existing locations are
12510 pending, don't do anything. This optimizes the common case where
12511 all locations are in the same shared library, that was unloaded.
12512 We'd like to retain the location, so that when the library is
12513 loaded again, we don't loose the enabled/disabled status of the
12514 individual locations. */
12515 if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
12516 return;
12518 existing_locations = hoist_existing_locations (b, filter_pspace);
12520 for (const auto &sal : sals)
12522 struct bp_location *new_loc;
12524 switch_to_program_space_and_thread (sal.pspace);
12526 new_loc = b->add_location (sal);
12528 /* Reparse conditions, they might contain references to the
12529 old symtab. */
12530 if (b->cond_string != NULL)
12532 const char *s;
12534 s = b->cond_string.get ();
12537 new_loc->cond = parse_exp_1 (&s, sal.pc,
12538 block_for_pc (sal.pc),
12541 catch (const gdb_exception_error &e)
12543 new_loc->disabled_by_cond = true;
12547 if (!sals_end.empty ())
12549 CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
12551 new_loc->length = end - sals[0].pc + 1;
12555 /* If possible, carry over 'disable' status from existing
12556 breakpoints. */
12558 struct bp_location *e = existing_locations;
12559 /* If there are multiple breakpoints with the same function name,
12560 e.g. for inline functions, comparing function names won't work.
12561 Instead compare pc addresses; this is just a heuristic as things
12562 may have moved, but in practice it gives the correct answer
12563 often enough until a better solution is found. */
12564 int have_ambiguous_names = ambiguous_names_p (b->loc);
12566 for (; e; e = e->next)
12568 if ((!e->enabled || e->disabled_by_cond) && e->function_name)
12570 if (have_ambiguous_names)
12572 for (bp_location *l : b->locations ())
12574 /* Ignore software vs hardware location type at
12575 this point, because with "set breakpoint
12576 auto-hw", after a re-set, locations that were
12577 hardware can end up as software, or vice versa.
12578 As mentioned above, this is an heuristic and in
12579 practice should give the correct answer often
12580 enough. */
12581 if (breakpoint_locations_match (e, l, true))
12583 l->enabled = e->enabled;
12584 l->disabled_by_cond = e->disabled_by_cond;
12585 break;
12589 else
12591 for (bp_location *l : b->locations ())
12592 if (l->function_name
12593 && strcmp (e->function_name.get (),
12594 l->function_name.get ()) == 0)
12596 l->enabled = e->enabled;
12597 l->disabled_by_cond = e->disabled_by_cond;
12598 break;
12605 if (!locations_are_equal (existing_locations, b->loc))
12606 gdb::observers::breakpoint_modified.notify (b);
12609 /* Find the SaL locations corresponding to the given LOCSPEC.
12610 On return, FOUND will be 1 if any SaL was found, zero otherwise. */
12612 static std::vector<symtab_and_line>
12613 location_spec_to_sals (struct breakpoint *b, location_spec *locspec,
12614 struct program_space *search_pspace, int *found)
12616 struct gdb_exception exception;
12618 std::vector<symtab_and_line> sals;
12622 sals = b->decode_location_spec (locspec, search_pspace);
12624 catch (gdb_exception_error &e)
12626 int not_found_and_ok = 0;
12628 /* For pending breakpoints, it's expected that parsing will
12629 fail until the right shared library is loaded. User has
12630 already told to create pending breakpoints and don't need
12631 extra messages. If breakpoint is in bp_shlib_disabled
12632 state, then user already saw the message about that
12633 breakpoint being disabled, and don't want to see more
12634 errors. */
12635 if (e.error == NOT_FOUND_ERROR
12636 && (b->condition_not_parsed
12637 || (b->loc != NULL
12638 && search_pspace != NULL
12639 && b->loc->pspace != search_pspace)
12640 || (b->loc && b->loc->shlib_disabled)
12641 || (b->loc && b->loc->pspace->executing_startup)
12642 || b->enable_state == bp_disabled))
12643 not_found_and_ok = 1;
12645 if (!not_found_and_ok)
12647 /* We surely don't want to warn about the same breakpoint
12648 10 times. One solution, implemented here, is disable
12649 the breakpoint on error. Another solution would be to
12650 have separate 'warning emitted' flag. Since this
12651 happens only when a binary has changed, I don't know
12652 which approach is better. */
12653 b->enable_state = bp_disabled;
12654 throw;
12657 exception = std::move (e);
12660 if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
12662 for (auto &sal : sals)
12663 resolve_sal_pc (&sal);
12664 if (b->condition_not_parsed && b->extra_string != NULL)
12666 gdb::unique_xmalloc_ptr<char> cond_string, extra_string;
12667 int thread, task;
12669 find_condition_and_thread_for_sals (sals, b->extra_string.get (),
12670 &cond_string, &thread,
12671 &task, &extra_string);
12672 gdb_assert (b->cond_string == NULL);
12673 if (cond_string)
12674 b->cond_string = std::move (cond_string);
12675 b->thread = thread;
12676 b->task = task;
12677 if (extra_string)
12678 b->extra_string = std::move (extra_string);
12679 b->condition_not_parsed = 0;
12682 if (b->type == bp_static_tracepoint)
12683 sals[0] = update_static_tracepoint (b, sals[0]);
12685 *found = 1;
12687 else
12688 *found = 0;
12690 return sals;
12693 /* The default re_set method, for typical hardware or software
12694 breakpoints. Reevaluate the breakpoint and recreate its
12695 locations. */
12697 static void
12698 breakpoint_re_set_default (code_breakpoint *b)
12700 struct program_space *filter_pspace = current_program_space;
12701 std::vector<symtab_and_line> expanded, expanded_end;
12703 int found;
12704 std::vector<symtab_and_line> sals
12705 = location_spec_to_sals (b, b->locspec.get (), filter_pspace, &found);
12706 if (found)
12707 expanded = std::move (sals);
12709 if (b->locspec_range_end != nullptr)
12711 std::vector<symtab_and_line> sals_end
12712 = location_spec_to_sals (b, b->locspec_range_end.get (),
12713 filter_pspace, &found);
12714 if (found)
12715 expanded_end = std::move (sals_end);
12718 update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
12721 /* Default method for creating SALs from an address string. It basically
12722 calls parse_breakpoint_sals. Return 1 for success, zero for failure. */
12724 static void
12725 create_sals_from_location_spec_default (location_spec *locspec,
12726 struct linespec_result *canonical)
12728 parse_breakpoint_sals (locspec, canonical);
12731 /* Decode the line represented by S by calling decode_line_full. This is the
12732 default function for the `decode_location' method of breakpoint_ops. */
12734 static std::vector<symtab_and_line>
12735 decode_location_spec_default (struct breakpoint *b,
12736 location_spec *locspec,
12737 program_space *search_pspace)
12739 struct linespec_result canonical;
12741 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
12742 NULL, 0, &canonical, multiple_symbols_all,
12743 b->filter.get ());
12745 /* We should get 0 or 1 resulting SALs. */
12746 gdb_assert (canonical.lsals.size () < 2);
12748 if (!canonical.lsals.empty ())
12750 const linespec_sals &lsal = canonical.lsals[0];
12751 return std::move (lsal.sals);
12753 return {};
12756 /* Reset a breakpoint. */
12758 static void
12759 breakpoint_re_set_one (breakpoint *b)
12761 input_radix = b->input_radix;
12762 set_language (b->language);
12764 b->re_set ();
12767 /* Re-set breakpoint locations for the current program space.
12768 Locations bound to other program spaces are left untouched. */
12770 void
12771 breakpoint_re_set (void)
12774 scoped_restore_current_language save_language;
12775 scoped_restore save_input_radix = make_scoped_restore (&input_radix);
12776 scoped_restore_current_pspace_and_thread restore_pspace_thread;
12778 /* breakpoint_re_set_one sets the current_language to the language
12779 of the breakpoint it is resetting (see prepare_re_set_context)
12780 before re-evaluating the breakpoint's location. This change can
12781 unfortunately get undone by accident if the language_mode is set
12782 to auto, and we either switch frames, or more likely in this context,
12783 we select the current frame.
12785 We prevent this by temporarily turning the language_mode to
12786 language_mode_manual. We restore it once all breakpoints
12787 have been reset. */
12788 scoped_restore save_language_mode = make_scoped_restore (&language_mode);
12789 language_mode = language_mode_manual;
12791 /* Note: we must not try to insert locations until after all
12792 breakpoints have been re-set. Otherwise, e.g., when re-setting
12793 breakpoint 1, we'd insert the locations of breakpoint 2, which
12794 hadn't been re-set yet, and thus may have stale locations. */
12796 for (breakpoint *b : all_breakpoints_safe ())
12800 breakpoint_re_set_one (b);
12802 catch (const gdb_exception &ex)
12804 exception_fprintf (gdb_stderr, ex,
12805 "Error in re-setting breakpoint %d: ",
12806 b->number);
12810 jit_breakpoint_re_set ();
12813 create_overlay_event_breakpoint ();
12814 create_longjmp_master_breakpoint ();
12815 create_std_terminate_master_breakpoint ();
12816 create_exception_master_breakpoint ();
12818 /* Now we can insert. */
12819 update_global_location_list (UGLL_MAY_INSERT);
12822 /* Reset the thread number of this breakpoint:
12824 - If the breakpoint is for all threads, leave it as-is.
12825 - Else, reset it to the current thread for inferior_ptid. */
12826 void
12827 breakpoint_re_set_thread (struct breakpoint *b)
12829 if (b->thread != -1)
12831 b->thread = inferior_thread ()->global_num;
12833 /* We're being called after following a fork. The new fork is
12834 selected as current, and unless this was a vfork will have a
12835 different program space from the original thread. Reset that
12836 as well. */
12837 b->loc->pspace = current_program_space;
12841 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12842 If from_tty is nonzero, it prints a message to that effect,
12843 which ends with a period (no newline). */
12845 void
12846 set_ignore_count (int bptnum, int count, int from_tty)
12848 if (count < 0)
12849 count = 0;
12851 for (breakpoint *b : all_breakpoints ())
12852 if (b->number == bptnum)
12854 if (is_tracepoint (b))
12856 if (from_tty && count != 0)
12857 gdb_printf (_("Ignore count ignored for tracepoint %d."),
12858 bptnum);
12859 return;
12862 b->ignore_count = count;
12863 if (from_tty)
12865 if (count == 0)
12866 gdb_printf (_("Will stop next time "
12867 "breakpoint %d is reached."),
12868 bptnum);
12869 else if (count == 1)
12870 gdb_printf (_("Will ignore next crossing of breakpoint %d."),
12871 bptnum);
12872 else
12873 gdb_printf (_("Will ignore next %d "
12874 "crossings of breakpoint %d."),
12875 count, bptnum);
12877 gdb::observers::breakpoint_modified.notify (b);
12878 return;
12881 error (_("No breakpoint number %d."), bptnum);
12884 /* Command to set ignore-count of breakpoint N to COUNT. */
12886 static void
12887 ignore_command (const char *args, int from_tty)
12889 const char *p = args;
12890 int num;
12892 if (p == 0)
12893 error_no_arg (_("a breakpoint number"));
12895 num = get_number (&p);
12896 if (num == 0)
12897 error (_("bad breakpoint number: '%s'"), args);
12898 if (*p == 0)
12899 error (_("Second argument (specified ignore-count) is missing."));
12901 set_ignore_count (num,
12902 longest_to_int (value_as_long (parse_and_eval (p))),
12903 from_tty);
12904 if (from_tty)
12905 gdb_printf ("\n");
12909 /* Call FUNCTION on each of the breakpoints with numbers in the range
12910 defined by BP_NUM_RANGE (an inclusive range). */
12912 static void
12913 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
12914 gdb::function_view<void (breakpoint *)> function)
12916 if (bp_num_range.first == 0)
12918 warning (_("bad breakpoint number at or near '%d'"),
12919 bp_num_range.first);
12921 else
12923 for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
12925 bool match = false;
12927 for (breakpoint *b : all_breakpoints_safe ())
12928 if (b->number == i)
12930 match = true;
12931 function (b);
12932 break;
12934 if (!match)
12935 gdb_printf (_("No breakpoint number %d.\n"), i);
12940 /* Call FUNCTION on each of the breakpoints whose numbers are given in
12941 ARGS. */
12943 static void
12944 map_breakpoint_numbers (const char *args,
12945 gdb::function_view<void (breakpoint *)> function)
12947 if (args == NULL || *args == '\0')
12948 error_no_arg (_("one or more breakpoint numbers"));
12950 number_or_range_parser parser (args);
12952 while (!parser.finished ())
12954 int num = parser.get_number ();
12955 map_breakpoint_number_range (std::make_pair (num, num), function);
12959 /* Return the breakpoint location structure corresponding to the
12960 BP_NUM and LOC_NUM values. */
12962 static struct bp_location *
12963 find_location_by_number (int bp_num, int loc_num)
12965 breakpoint *b = get_breakpoint (bp_num);
12967 if (!b || b->number != bp_num)
12968 error (_("Bad breakpoint number '%d'"), bp_num);
12970 if (loc_num == 0)
12971 error (_("Bad breakpoint location number '%d'"), loc_num);
12973 int n = 0;
12974 for (bp_location *loc : b->locations ())
12975 if (++n == loc_num)
12976 return loc;
12978 error (_("Bad breakpoint location number '%d'"), loc_num);
12981 /* Modes of operation for extract_bp_num. */
12982 enum class extract_bp_kind
12984 /* Extracting a breakpoint number. */
12987 /* Extracting a location number. */
12988 loc,
12991 /* Extract a breakpoint or location number (as determined by KIND)
12992 from the string starting at START. TRAILER is a character which
12993 can be found after the number. If you don't want a trailer, use
12994 '\0'. If END_OUT is not NULL, it is set to point after the parsed
12995 string. This always returns a positive integer. */
12997 static int
12998 extract_bp_num (extract_bp_kind kind, const char *start,
12999 int trailer, const char **end_out = NULL)
13001 const char *end = start;
13002 int num = get_number_trailer (&end, trailer);
13003 if (num < 0)
13004 error (kind == extract_bp_kind::bp
13005 ? _("Negative breakpoint number '%.*s'")
13006 : _("Negative breakpoint location number '%.*s'"),
13007 int (end - start), start);
13008 if (num == 0)
13009 error (kind == extract_bp_kind::bp
13010 ? _("Bad breakpoint number '%.*s'")
13011 : _("Bad breakpoint location number '%.*s'"),
13012 int (end - start), start);
13014 if (end_out != NULL)
13015 *end_out = end;
13016 return num;
13019 /* Extract a breakpoint or location range (as determined by KIND) in
13020 the form NUM1-NUM2 stored at &ARG[arg_offset]. Returns a std::pair
13021 representing the (inclusive) range. The returned pair's elements
13022 are always positive integers. */
13024 static std::pair<int, int>
13025 extract_bp_or_bp_range (extract_bp_kind kind,
13026 const std::string &arg,
13027 std::string::size_type arg_offset)
13029 std::pair<int, int> range;
13030 const char *bp_loc = &arg[arg_offset];
13031 std::string::size_type dash = arg.find ('-', arg_offset);
13032 if (dash != std::string::npos)
13034 /* bp_loc is a range (x-z). */
13035 if (arg.length () == dash + 1)
13036 error (kind == extract_bp_kind::bp
13037 ? _("Bad breakpoint number at or near: '%s'")
13038 : _("Bad breakpoint location number at or near: '%s'"),
13039 bp_loc);
13041 const char *end;
13042 const char *start_first = bp_loc;
13043 const char *start_second = &arg[dash + 1];
13044 range.first = extract_bp_num (kind, start_first, '-');
13045 range.second = extract_bp_num (kind, start_second, '\0', &end);
13047 if (range.first > range.second)
13048 error (kind == extract_bp_kind::bp
13049 ? _("Inverted breakpoint range at '%.*s'")
13050 : _("Inverted breakpoint location range at '%.*s'"),
13051 int (end - start_first), start_first);
13053 else
13055 /* bp_loc is a single value. */
13056 range.first = extract_bp_num (kind, bp_loc, '\0');
13057 range.second = range.first;
13059 return range;
13062 /* Extract the breakpoint/location range specified by ARG. Returns
13063 the breakpoint range in BP_NUM_RANGE, and the location range in
13064 BP_LOC_RANGE.
13066 ARG may be in any of the following forms:
13068 x where 'x' is a breakpoint number.
13069 x-y where 'x' and 'y' specify a breakpoint numbers range.
13070 x.y where 'x' is a breakpoint number and 'y' a location number.
13071 x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
13072 location number range.
13075 static void
13076 extract_bp_number_and_location (const std::string &arg,
13077 std::pair<int, int> &bp_num_range,
13078 std::pair<int, int> &bp_loc_range)
13080 std::string::size_type dot = arg.find ('.');
13082 if (dot != std::string::npos)
13084 /* Handle 'x.y' and 'x.y-z' cases. */
13086 if (arg.length () == dot + 1 || dot == 0)
13087 error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
13089 bp_num_range.first
13090 = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
13091 bp_num_range.second = bp_num_range.first;
13093 bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
13094 arg, dot + 1);
13096 else
13098 /* Handle x and x-y cases. */
13100 bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
13101 bp_loc_range.first = 0;
13102 bp_loc_range.second = 0;
13106 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM. ENABLE
13107 specifies whether to enable or disable. */
13109 static void
13110 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
13112 struct bp_location *loc = find_location_by_number (bp_num, loc_num);
13113 if (loc != NULL)
13115 if (loc->disabled_by_cond && enable)
13116 error (_("Breakpoint %d's condition is invalid at location %d, "
13117 "cannot enable."), bp_num, loc_num);
13119 if (loc->enabled != enable)
13121 loc->enabled = enable;
13122 mark_breakpoint_location_modified (loc);
13124 if (target_supports_enable_disable_tracepoint ()
13125 && current_trace_status ()->running && loc->owner
13126 && is_tracepoint (loc->owner))
13127 target_disable_tracepoint (loc);
13129 update_global_location_list (UGLL_DONT_INSERT);
13131 gdb::observers::breakpoint_modified.notify (loc->owner);
13134 /* Enable or disable a range of breakpoint locations. BP_NUM is the
13135 number of the breakpoint, and BP_LOC_RANGE specifies the
13136 (inclusive) range of location numbers of that breakpoint to
13137 enable/disable. ENABLE specifies whether to enable or disable the
13138 location. */
13140 static void
13141 enable_disable_breakpoint_location_range (int bp_num,
13142 std::pair<int, int> &bp_loc_range,
13143 bool enable)
13145 for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
13146 enable_disable_bp_num_loc (bp_num, i, enable);
13149 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13150 If from_tty is nonzero, it prints a message to that effect,
13151 which ends with a period (no newline). */
13153 void
13154 disable_breakpoint (struct breakpoint *bpt)
13156 /* Never disable a watchpoint scope breakpoint; we want to
13157 hit them when we leave scope so we can delete both the
13158 watchpoint and its scope breakpoint at that time. */
13159 if (bpt->type == bp_watchpoint_scope)
13160 return;
13162 bpt->enable_state = bp_disabled;
13164 /* Mark breakpoint locations modified. */
13165 mark_breakpoint_modified (bpt);
13167 if (target_supports_enable_disable_tracepoint ()
13168 && current_trace_status ()->running && is_tracepoint (bpt))
13170 for (bp_location *location : bpt->locations ())
13171 target_disable_tracepoint (location);
13174 update_global_location_list (UGLL_DONT_INSERT);
13176 gdb::observers::breakpoint_modified.notify (bpt);
13179 /* Enable or disable the breakpoint(s) or breakpoint location(s)
13180 specified in ARGS. ARGS may be in any of the formats handled by
13181 extract_bp_number_and_location. ENABLE specifies whether to enable
13182 or disable the breakpoints/locations. */
13184 static void
13185 enable_disable_command (const char *args, int from_tty, bool enable)
13187 if (args == 0)
13189 for (breakpoint *bpt : all_breakpoints ())
13190 if (user_breakpoint_p (bpt))
13192 if (enable)
13193 enable_breakpoint (bpt);
13194 else
13195 disable_breakpoint (bpt);
13198 else
13200 std::string num = extract_arg (&args);
13202 while (!num.empty ())
13204 std::pair<int, int> bp_num_range, bp_loc_range;
13206 extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
13208 if (bp_loc_range.first == bp_loc_range.second
13209 && bp_loc_range.first == 0)
13211 /* Handle breakpoint ids with formats 'x' or 'x-z'. */
13212 map_breakpoint_number_range (bp_num_range,
13213 enable
13214 ? enable_breakpoint
13215 : disable_breakpoint);
13217 else
13219 /* Handle breakpoint ids with formats 'x.y' or
13220 'x.y-z'. */
13221 enable_disable_breakpoint_location_range
13222 (bp_num_range.first, bp_loc_range, enable);
13224 num = extract_arg (&args);
13229 /* The disable command disables the specified breakpoints/locations
13230 (or all defined breakpoints) so they're no longer effective in
13231 stopping the inferior. ARGS may be in any of the forms defined in
13232 extract_bp_number_and_location. */
13234 static void
13235 disable_command (const char *args, int from_tty)
13237 enable_disable_command (args, from_tty, false);
13240 static void
13241 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13242 int count)
13244 int target_resources_ok;
13246 if (bpt->type == bp_hardware_breakpoint)
13248 int i;
13249 i = hw_breakpoint_used_count ();
13250 target_resources_ok =
13251 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
13252 i + 1, 0);
13253 if (target_resources_ok == 0)
13254 error (_("No hardware breakpoint support in the target."));
13255 else if (target_resources_ok < 0)
13256 error (_("Hardware breakpoints used exceeds limit."));
13259 if (is_watchpoint (bpt))
13261 /* Initialize it just to avoid a GCC false warning. */
13262 enum enable_state orig_enable_state = bp_disabled;
13266 struct watchpoint *w = (struct watchpoint *) bpt;
13268 orig_enable_state = bpt->enable_state;
13269 bpt->enable_state = bp_enabled;
13270 update_watchpoint (w, 1 /* reparse */);
13272 catch (const gdb_exception &e)
13274 bpt->enable_state = orig_enable_state;
13275 exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13276 bpt->number);
13277 return;
13281 bpt->enable_state = bp_enabled;
13283 /* Mark breakpoint locations modified. */
13284 mark_breakpoint_modified (bpt);
13286 if (target_supports_enable_disable_tracepoint ()
13287 && current_trace_status ()->running && is_tracepoint (bpt))
13289 for (bp_location *location : bpt->locations ())
13290 target_enable_tracepoint (location);
13293 bpt->disposition = disposition;
13294 bpt->enable_count = count;
13295 update_global_location_list (UGLL_MAY_INSERT);
13297 gdb::observers::breakpoint_modified.notify (bpt);
13301 void
13302 enable_breakpoint (struct breakpoint *bpt)
13304 enable_breakpoint_disp (bpt, bpt->disposition, 0);
13307 /* The enable command enables the specified breakpoints/locations (or
13308 all defined breakpoints) so they once again become (or continue to
13309 be) effective in stopping the inferior. ARGS may be in any of the
13310 forms defined in extract_bp_number_and_location. */
13312 static void
13313 enable_command (const char *args, int from_tty)
13315 enable_disable_command (args, from_tty, true);
13318 static void
13319 enable_once_command (const char *args, int from_tty)
13321 map_breakpoint_numbers
13322 (args, [&] (breakpoint *b)
13324 iterate_over_related_breakpoints
13325 (b, [&] (breakpoint *bpt)
13327 enable_breakpoint_disp (bpt, disp_disable, 1);
13332 static void
13333 enable_count_command (const char *args, int from_tty)
13335 int count;
13337 if (args == NULL)
13338 error_no_arg (_("hit count"));
13340 count = get_number (&args);
13342 map_breakpoint_numbers
13343 (args, [&] (breakpoint *b)
13345 iterate_over_related_breakpoints
13346 (b, [&] (breakpoint *bpt)
13348 enable_breakpoint_disp (bpt, disp_disable, count);
13353 static void
13354 enable_delete_command (const char *args, int from_tty)
13356 map_breakpoint_numbers
13357 (args, [&] (breakpoint *b)
13359 iterate_over_related_breakpoints
13360 (b, [&] (breakpoint *bpt)
13362 enable_breakpoint_disp (bpt, disp_del, 1);
13367 /* Invalidate last known value of any hardware watchpoint if
13368 the memory which that value represents has been written to by
13369 GDB itself. */
13371 static void
13372 invalidate_bp_value_on_memory_change (struct inferior *inferior,
13373 CORE_ADDR addr, ssize_t len,
13374 const bfd_byte *data)
13376 for (breakpoint *bp : all_breakpoints ())
13377 if (bp->enable_state == bp_enabled
13378 && bp->type == bp_hardware_watchpoint)
13380 struct watchpoint *wp = (struct watchpoint *) bp;
13382 if (wp->val_valid && wp->val != nullptr)
13384 for (bp_location *loc : bp->locations ())
13385 if (loc->loc_type == bp_loc_hardware_watchpoint
13386 && loc->address + loc->length > addr
13387 && addr + len > loc->address)
13389 wp->val = NULL;
13390 wp->val_valid = false;
13396 /* Create and insert a breakpoint for software single step. */
13398 void
13399 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13400 const address_space *aspace,
13401 CORE_ADDR next_pc)
13403 struct thread_info *tp = inferior_thread ();
13404 struct symtab_and_line sal;
13405 CORE_ADDR pc = next_pc;
13407 if (tp->control.single_step_breakpoints == NULL)
13409 std::unique_ptr<breakpoint> b
13410 (new momentary_breakpoint (gdbarch, bp_single_step,
13411 current_program_space,
13412 null_frame_id,
13413 tp->global_num));
13415 tp->control.single_step_breakpoints
13416 = add_to_breakpoint_chain (std::move (b));
13419 sal = find_pc_line (pc, 0);
13420 sal.pc = pc;
13421 sal.section = find_pc_overlay (pc);
13422 sal.explicit_pc = 1;
13424 auto *ss_bp
13425 = static_cast<momentary_breakpoint *> (tp->control.single_step_breakpoints);
13426 ss_bp->add_location (sal);
13428 update_global_location_list (UGLL_INSERT);
13431 /* Insert single step breakpoints according to the current state. */
13434 insert_single_step_breakpoints (struct gdbarch *gdbarch)
13436 struct regcache *regcache = get_current_regcache ();
13437 std::vector<CORE_ADDR> next_pcs;
13439 next_pcs = gdbarch_software_single_step (gdbarch, regcache);
13441 if (!next_pcs.empty ())
13443 struct frame_info *frame = get_current_frame ();
13444 const address_space *aspace = get_frame_address_space (frame);
13446 for (CORE_ADDR pc : next_pcs)
13447 insert_single_step_breakpoint (gdbarch, aspace, pc);
13449 return 1;
13451 else
13452 return 0;
13455 /* See breakpoint.h. */
13458 breakpoint_has_location_inserted_here (struct breakpoint *bp,
13459 const address_space *aspace,
13460 CORE_ADDR pc)
13462 for (bp_location *loc : bp->locations ())
13463 if (loc->inserted
13464 && breakpoint_location_address_match (loc, aspace, pc))
13465 return 1;
13467 return 0;
13470 /* Check whether a software single-step breakpoint is inserted at
13471 PC. */
13474 single_step_breakpoint_inserted_here_p (const address_space *aspace,
13475 CORE_ADDR pc)
13477 for (breakpoint *bpt : all_breakpoints ())
13479 if (bpt->type == bp_single_step
13480 && breakpoint_has_location_inserted_here (bpt, aspace, pc))
13481 return 1;
13483 return 0;
13486 /* Tracepoint-specific operations. */
13488 /* Set tracepoint count to NUM. */
13489 static void
13490 set_tracepoint_count (int num)
13492 tracepoint_count = num;
13493 set_internalvar_integer (lookup_internalvar ("tpnum"), num);
13496 static void
13497 trace_command (const char *arg, int from_tty)
13499 location_spec_up locspec = string_to_location_spec (&arg,
13500 current_language);
13501 const struct breakpoint_ops *ops = breakpoint_ops_for_location_spec
13502 (locspec.get (), true /* is_tracepoint */);
13504 create_breakpoint (get_current_arch (),
13505 locspec.get (),
13506 NULL, 0, arg, false, 1 /* parse arg */,
13507 0 /* tempflag */,
13508 bp_tracepoint /* type_wanted */,
13509 0 /* Ignore count */,
13510 pending_break_support,
13511 ops,
13512 from_tty,
13513 1 /* enabled */,
13514 0 /* internal */, 0);
13517 static void
13518 ftrace_command (const char *arg, int from_tty)
13520 location_spec_up locspec = string_to_location_spec (&arg,
13521 current_language);
13522 create_breakpoint (get_current_arch (),
13523 locspec.get (),
13524 NULL, 0, arg, false, 1 /* parse arg */,
13525 0 /* tempflag */,
13526 bp_fast_tracepoint /* type_wanted */,
13527 0 /* Ignore count */,
13528 pending_break_support,
13529 &code_breakpoint_ops,
13530 from_tty,
13531 1 /* enabled */,
13532 0 /* internal */, 0);
13535 /* strace command implementation. Creates a static tracepoint. */
13537 static void
13538 strace_command (const char *arg, int from_tty)
13540 const struct breakpoint_ops *ops;
13541 location_spec_up locspec;
13542 enum bptype type;
13544 /* Decide if we are dealing with a static tracepoint marker (`-m'),
13545 or with a normal static tracepoint. */
13546 if (arg && startswith (arg, "-m") && isspace (arg[2]))
13548 ops = &strace_marker_breakpoint_ops;
13549 locspec = new_linespec_location_spec (&arg,
13550 symbol_name_match_type::FULL);
13551 type = bp_static_marker_tracepoint;
13553 else
13555 ops = &code_breakpoint_ops;
13556 locspec = string_to_location_spec (&arg, current_language);
13557 type = bp_static_tracepoint;
13560 create_breakpoint (get_current_arch (),
13561 locspec.get (),
13562 NULL, 0, arg, false, 1 /* parse arg */,
13563 0 /* tempflag */,
13564 type /* type_wanted */,
13565 0 /* Ignore count */,
13566 pending_break_support,
13567 ops,
13568 from_tty,
13569 1 /* enabled */,
13570 0 /* internal */, 0);
13573 /* Set up a fake reader function that gets command lines from a linked
13574 list that was acquired during tracepoint uploading. */
13576 static struct uploaded_tp *this_utp;
13577 static int next_cmd;
13579 static char *
13580 read_uploaded_action (void)
13582 char *rslt = nullptr;
13584 if (next_cmd < this_utp->cmd_strings.size ())
13586 rslt = this_utp->cmd_strings[next_cmd].get ();
13587 next_cmd++;
13590 return rslt;
13593 /* Given information about a tracepoint as recorded on a target (which
13594 can be either a live system or a trace file), attempt to create an
13595 equivalent GDB tracepoint. This is not a reliable process, since
13596 the target does not necessarily have all the information used when
13597 the tracepoint was originally defined. */
13599 struct tracepoint *
13600 create_tracepoint_from_upload (struct uploaded_tp *utp)
13602 const char *addr_str;
13603 char small_buf[100];
13604 struct tracepoint *tp;
13606 if (utp->at_string)
13607 addr_str = utp->at_string.get ();
13608 else
13610 /* In the absence of a source location, fall back to raw
13611 address. Since there is no way to confirm that the address
13612 means the same thing as when the trace was started, warn the
13613 user. */
13614 warning (_("Uploaded tracepoint %d has no "
13615 "source location, using raw address"),
13616 utp->number);
13617 xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
13618 addr_str = small_buf;
13621 /* There's not much we can do with a sequence of bytecodes. */
13622 if (utp->cond && !utp->cond_string)
13623 warning (_("Uploaded tracepoint %d condition "
13624 "has no source form, ignoring it"),
13625 utp->number);
13627 location_spec_up locspec = string_to_location_spec (&addr_str,
13628 current_language);
13629 if (!create_breakpoint (get_current_arch (),
13630 locspec.get (),
13631 utp->cond_string.get (), -1, addr_str,
13632 false /* force_condition */,
13633 0 /* parse cond/thread */,
13634 0 /* tempflag */,
13635 utp->type /* type_wanted */,
13636 0 /* Ignore count */,
13637 pending_break_support,
13638 &code_breakpoint_ops,
13639 0 /* from_tty */,
13640 utp->enabled /* enabled */,
13641 0 /* internal */,
13642 CREATE_BREAKPOINT_FLAGS_INSERTED))
13643 return NULL;
13645 /* Get the tracepoint we just created. */
13646 tp = get_tracepoint (tracepoint_count);
13647 gdb_assert (tp != NULL);
13649 if (utp->pass > 0)
13651 xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
13652 tp->number);
13654 trace_pass_command (small_buf, 0);
13657 /* If we have uploaded versions of the original commands, set up a
13658 special-purpose "reader" function and call the usual command line
13659 reader, then pass the result to the breakpoint command-setting
13660 function. */
13661 if (!utp->cmd_strings.empty ())
13663 counted_command_line cmd_list;
13665 this_utp = utp;
13666 next_cmd = 0;
13668 cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
13670 breakpoint_set_commands (tp, std::move (cmd_list));
13672 else if (!utp->actions.empty ()
13673 || !utp->step_actions.empty ())
13674 warning (_("Uploaded tracepoint %d actions "
13675 "have no source form, ignoring them"),
13676 utp->number);
13678 /* Copy any status information that might be available. */
13679 tp->hit_count = utp->hit_count;
13680 tp->traceframe_usage = utp->traceframe_usage;
13682 return tp;
13685 /* Print information on tracepoint number TPNUM_EXP, or all if
13686 omitted. */
13688 static void
13689 info_tracepoints_command (const char *args, int from_tty)
13691 struct ui_out *uiout = current_uiout;
13692 int num_printed;
13694 num_printed = breakpoint_1 (args, false, is_tracepoint);
13696 if (num_printed == 0)
13698 if (args == NULL || *args == '\0')
13699 uiout->message ("No tracepoints.\n");
13700 else
13701 uiout->message ("No tracepoint matching '%s'.\n", args);
13704 default_collect_info ();
13707 /* The 'enable trace' command enables tracepoints.
13708 Not supported by all targets. */
13709 static void
13710 enable_trace_command (const char *args, int from_tty)
13712 enable_command (args, from_tty);
13715 /* The 'disable trace' command disables tracepoints.
13716 Not supported by all targets. */
13717 static void
13718 disable_trace_command (const char *args, int from_tty)
13720 disable_command (args, from_tty);
13723 /* Remove a tracepoint (or all if no argument). */
13724 static void
13725 delete_trace_command (const char *arg, int from_tty)
13727 dont_repeat ();
13729 if (arg == 0)
13731 int breaks_to_delete = 0;
13733 /* Delete all breakpoints if no argument.
13734 Do not delete internal or call-dummy breakpoints, these
13735 have to be deleted with an explicit breakpoint number
13736 argument. */
13737 for (breakpoint *tp : all_tracepoints ())
13738 if (is_tracepoint (tp) && user_breakpoint_p (tp))
13740 breaks_to_delete = 1;
13741 break;
13744 /* Ask user only if there are some breakpoints to delete. */
13745 if (!from_tty
13746 || (breaks_to_delete && query (_("Delete all tracepoints? "))))
13748 for (breakpoint *b : all_breakpoints_safe ())
13749 if (is_tracepoint (b) && user_breakpoint_p (b))
13750 delete_breakpoint (b);
13753 else
13754 map_breakpoint_numbers
13755 (arg, [&] (breakpoint *br)
13757 iterate_over_related_breakpoints (br, delete_breakpoint);
13761 /* Helper function for trace_pass_command. */
13763 static void
13764 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
13766 tp->pass_count = count;
13767 gdb::observers::breakpoint_modified.notify (tp);
13768 if (from_tty)
13769 gdb_printf (_("Setting tracepoint %d's passcount to %d\n"),
13770 tp->number, count);
13773 /* Set passcount for tracepoint.
13775 First command argument is passcount, second is tracepoint number.
13776 If tracepoint number omitted, apply to most recently defined.
13777 Also accepts special argument "all". */
13779 static void
13780 trace_pass_command (const char *args, int from_tty)
13782 struct tracepoint *t1;
13783 ULONGEST count;
13785 if (args == 0 || *args == 0)
13786 error (_("passcount command requires an "
13787 "argument (count + optional TP num)"));
13789 count = strtoulst (args, &args, 10); /* Count comes first, then TP num. */
13791 args = skip_spaces (args);
13792 if (*args && strncasecmp (args, "all", 3) == 0)
13794 args += 3; /* Skip special argument "all". */
13795 if (*args)
13796 error (_("Junk at end of arguments."));
13798 for (breakpoint *b : all_tracepoints ())
13800 t1 = (struct tracepoint *) b;
13801 trace_pass_set_count (t1, count, from_tty);
13804 else if (*args == '\0')
13806 t1 = get_tracepoint_by_number (&args, NULL);
13807 if (t1)
13808 trace_pass_set_count (t1, count, from_tty);
13810 else
13812 number_or_range_parser parser (args);
13813 while (!parser.finished ())
13815 t1 = get_tracepoint_by_number (&args, &parser);
13816 if (t1)
13817 trace_pass_set_count (t1, count, from_tty);
13822 struct tracepoint *
13823 get_tracepoint (int num)
13825 for (breakpoint *t : all_tracepoints ())
13826 if (t->number == num)
13827 return (struct tracepoint *) t;
13829 return NULL;
13832 /* Find the tracepoint with the given target-side number (which may be
13833 different from the tracepoint number after disconnecting and
13834 reconnecting). */
13836 struct tracepoint *
13837 get_tracepoint_by_number_on_target (int num)
13839 for (breakpoint *b : all_tracepoints ())
13841 struct tracepoint *t = (struct tracepoint *) b;
13843 if (t->number_on_target == num)
13844 return t;
13847 return NULL;
13850 /* Utility: parse a tracepoint number and look it up in the list.
13851 If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
13852 If the argument is missing, the most recent tracepoint
13853 (tracepoint_count) is returned. */
13855 struct tracepoint *
13856 get_tracepoint_by_number (const char **arg,
13857 number_or_range_parser *parser)
13859 int tpnum;
13860 const char *instring = arg == NULL ? NULL : *arg;
13862 if (parser != NULL)
13864 gdb_assert (!parser->finished ());
13865 tpnum = parser->get_number ();
13867 else if (arg == NULL || *arg == NULL || ! **arg)
13868 tpnum = tracepoint_count;
13869 else
13870 tpnum = get_number (arg);
13872 if (tpnum <= 0)
13874 if (instring && *instring)
13875 gdb_printf (_("bad tracepoint number at or near '%s'\n"),
13876 instring);
13877 else
13878 gdb_printf (_("No previous tracepoint\n"));
13879 return NULL;
13882 for (breakpoint *t : all_tracepoints ())
13883 if (t->number == tpnum)
13884 return (struct tracepoint *) t;
13886 gdb_printf ("No tracepoint number %d.\n", tpnum);
13887 return NULL;
13890 void
13891 breakpoint::print_recreate_thread (struct ui_file *fp) const
13893 if (thread != -1)
13894 gdb_printf (fp, " thread %d", thread);
13896 if (task != 0)
13897 gdb_printf (fp, " task %d", task);
13899 gdb_printf (fp, "\n");
13902 /* Save information on user settable breakpoints (watchpoints, etc) to
13903 a new script file named FILENAME. If FILTER is non-NULL, call it
13904 on each breakpoint and only include the ones for which it returns
13905 true. */
13907 static void
13908 save_breakpoints (const char *filename, int from_tty,
13909 bool (*filter) (const struct breakpoint *))
13911 int any = 0;
13912 int extra_trace_bits = 0;
13914 if (filename == 0 || *filename == 0)
13915 error (_("Argument required (file name in which to save)"));
13917 /* See if we have anything to save. */
13918 for (breakpoint *tp : all_breakpoints ())
13920 /* Skip internal and momentary breakpoints. */
13921 if (!user_breakpoint_p (tp))
13922 continue;
13924 /* If we have a filter, only save the breakpoints it accepts. */
13925 if (filter && !filter (tp))
13926 continue;
13928 any = 1;
13930 if (is_tracepoint (tp))
13932 extra_trace_bits = 1;
13934 /* We can stop searching. */
13935 break;
13939 if (!any)
13941 warning (_("Nothing to save."));
13942 return;
13945 gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
13947 stdio_file fp;
13949 if (!fp.open (expanded_filename.get (), "w"))
13950 error (_("Unable to open file '%s' for saving (%s)"),
13951 expanded_filename.get (), safe_strerror (errno));
13953 if (extra_trace_bits)
13954 save_trace_state_variables (&fp);
13956 for (breakpoint *tp : all_breakpoints ())
13958 /* Skip internal and momentary breakpoints. */
13959 if (!user_breakpoint_p (tp))
13960 continue;
13962 /* If we have a filter, only save the breakpoints it accepts. */
13963 if (filter && !filter (tp))
13964 continue;
13966 tp->print_recreate (&fp);
13968 /* Note, we can't rely on tp->number for anything, as we can't
13969 assume the recreated breakpoint numbers will match. Use $bpnum
13970 instead. */
13972 if (tp->cond_string)
13973 fp.printf (" condition $bpnum %s\n", tp->cond_string.get ());
13975 if (tp->ignore_count)
13976 fp.printf (" ignore $bpnum %d\n", tp->ignore_count);
13978 if (tp->type != bp_dprintf && tp->commands)
13980 fp.puts (" commands\n");
13982 current_uiout->redirect (&fp);
13985 print_command_lines (current_uiout, tp->commands.get (), 2);
13987 catch (const gdb_exception &ex)
13989 current_uiout->redirect (NULL);
13990 throw;
13993 current_uiout->redirect (NULL);
13994 fp.puts (" end\n");
13997 if (tp->enable_state == bp_disabled)
13998 fp.puts ("disable $bpnum\n");
14000 /* If this is a multi-location breakpoint, check if the locations
14001 should be individually disabled. Watchpoint locations are
14002 special, and not user visible. */
14003 if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14005 int n = 1;
14007 for (bp_location *loc : tp->locations ())
14009 if (!loc->enabled)
14010 fp.printf ("disable $bpnum.%d\n", n);
14012 n++;
14017 if (extra_trace_bits && !default_collect.empty ())
14018 fp.printf ("set default-collect %s\n", default_collect.c_str ());
14020 if (from_tty)
14021 gdb_printf (_("Saved to file '%s'.\n"), expanded_filename.get ());
14024 /* The `save breakpoints' command. */
14026 static void
14027 save_breakpoints_command (const char *args, int from_tty)
14029 save_breakpoints (args, from_tty, NULL);
14032 /* The `save tracepoints' command. */
14034 static void
14035 save_tracepoints_command (const char *args, int from_tty)
14037 save_breakpoints (args, from_tty, is_tracepoint);
14041 /* This help string is used to consolidate all the help string for specifying
14042 locations used by several commands. */
14044 #define LOCATION_SPEC_HELP_STRING \
14045 "Linespecs are colon-separated lists of location parameters, such as\n\
14046 source filename, function name, label name, and line number.\n\
14047 Example: To specify the start of a label named \"the_top\" in the\n\
14048 function \"fact\" in the file \"factorial.c\", use\n\
14049 \"factorial.c:fact:the_top\".\n\
14051 Address locations begin with \"*\" and specify an exact address in the\n\
14052 program. Example: To specify the fourth byte past the start function\n\
14053 \"main\", use \"*main + 4\".\n\
14055 Explicit locations are similar to linespecs but use an option/argument\n\
14056 syntax to specify location parameters.\n\
14057 Example: To specify the start of the label named \"the_top\" in the\n\
14058 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
14059 -function fact -label the_top\".\n\
14061 By default, a specified function is matched against the program's\n\
14062 functions in all scopes. For C++, this means in all namespaces and\n\
14063 classes. For Ada, this means in all packages. E.g., in C++,\n\
14064 \"func()\" matches \"A::func()\", \"A::B::func()\", etc. The\n\
14065 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
14066 specified name as a complete fully-qualified name instead."
14068 /* This help string is used for the break, hbreak, tbreak and thbreak
14069 commands. It is defined as a macro to prevent duplication.
14070 COMMAND should be a string constant containing the name of the
14071 command. */
14073 #define BREAK_ARGS_HELP(command) \
14074 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
14075 \t[-force-condition] [if CONDITION]\n\
14076 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
14077 probe point. Accepted values are `-probe' (for a generic, automatically\n\
14078 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
14079 `-probe-dtrace' (for a DTrace probe).\n\
14080 LOCATION may be a linespec, address, or explicit location as described\n\
14081 below.\n\
14083 With no LOCATION, uses current execution address of the selected\n\
14084 stack frame. This is useful for breaking on return to a stack frame.\n\
14086 THREADNUM is the number from \"info threads\".\n\
14087 CONDITION is a boolean expression.\n\
14089 With the \"-force-condition\" flag, the condition is defined even when\n\
14090 it is invalid for all current locations.\n\
14091 \n" LOCATION_SPEC_HELP_STRING "\n\n\
14092 Multiple breakpoints at one place are permitted, and useful if their\n\
14093 conditions are different.\n\
14095 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14097 /* List of subcommands for "catch". */
14098 static struct cmd_list_element *catch_cmdlist;
14100 /* List of subcommands for "tcatch". */
14101 static struct cmd_list_element *tcatch_cmdlist;
14103 void
14104 add_catch_command (const char *name, const char *docstring,
14105 cmd_func_ftype *func,
14106 completer_ftype *completer,
14107 void *user_data_catch,
14108 void *user_data_tcatch)
14110 struct cmd_list_element *command;
14112 command = add_cmd (name, class_breakpoint, docstring,
14113 &catch_cmdlist);
14114 command->func = func;
14115 command->set_context (user_data_catch);
14116 set_cmd_completer (command, completer);
14118 command = add_cmd (name, class_breakpoint, docstring,
14119 &tcatch_cmdlist);
14120 command->func = func;
14121 command->set_context (user_data_tcatch);
14122 set_cmd_completer (command, completer);
14125 /* Zero if any of the breakpoint's locations could be a location where
14126 functions have been inlined, nonzero otherwise. */
14128 static int
14129 is_non_inline_function (struct breakpoint *b)
14131 /* The shared library event breakpoint is set on the address of a
14132 non-inline function. */
14133 if (b->type == bp_shlib_event)
14134 return 1;
14136 return 0;
14139 /* Nonzero if the specified PC cannot be a location where functions
14140 have been inlined. */
14143 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
14144 const target_waitstatus &ws)
14146 for (breakpoint *b : all_breakpoints ())
14148 if (!is_non_inline_function (b))
14149 continue;
14151 for (bp_location *bl : b->locations ())
14153 if (!bl->shlib_disabled
14154 && bpstat_check_location (bl, aspace, pc, ws))
14155 return 1;
14159 return 0;
14162 /* Remove any references to OBJFILE which is going to be freed. */
14164 void
14165 breakpoint_free_objfile (struct objfile *objfile)
14167 for (bp_location *loc : all_bp_locations ())
14168 if (loc->symtab != NULL && loc->symtab->compunit ()->objfile () == objfile)
14169 loc->symtab = NULL;
14172 /* Chain containing all defined "enable breakpoint" subcommands. */
14174 static struct cmd_list_element *enablebreaklist = NULL;
14176 /* See breakpoint.h. */
14178 cmd_list_element *commands_cmd_element = nullptr;
14180 void _initialize_breakpoint ();
14181 void
14182 _initialize_breakpoint ()
14184 struct cmd_list_element *c;
14186 gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
14187 "breakpoint");
14188 gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
14189 "breakpoint");
14190 gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
14191 "breakpoint");
14193 breakpoint_chain = 0;
14194 /* Don't bother to call set_breakpoint_count. $bpnum isn't useful
14195 before a breakpoint is set. */
14196 breakpoint_count = 0;
14198 tracepoint_count = 0;
14200 add_com ("ignore", class_breakpoint, ignore_command, _("\
14201 Set ignore-count of breakpoint number N to COUNT.\n\
14202 Usage is `ignore N COUNT'."));
14204 commands_cmd_element = add_com ("commands", class_breakpoint,
14205 commands_command, _("\
14206 Set commands to be executed when the given breakpoints are hit.\n\
14207 Give a space-separated breakpoint list as argument after \"commands\".\n\
14208 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
14209 (e.g. `5-7').\n\
14210 With no argument, the targeted breakpoint is the last one set.\n\
14211 The commands themselves follow starting on the next line.\n\
14212 Type a line containing \"end\" to indicate the end of them.\n\
14213 Give \"silent\" as the first line to make the breakpoint silent;\n\
14214 then no output is printed when it is hit, except what the commands print."));
14216 const auto cc_opts = make_condition_command_options_def_group (nullptr);
14217 static std::string condition_command_help
14218 = gdb::option::build_help (_("\
14219 Specify breakpoint number N to break only if COND is true.\n\
14220 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
14221 is an expression to be evaluated whenever breakpoint N is reached.\n\
14223 Options:\n\
14224 %OPTIONS%"), cc_opts);
14226 c = add_com ("condition", class_breakpoint, condition_command,
14227 condition_command_help.c_str ());
14228 set_cmd_completer_handle_brkchars (c, condition_completer);
14230 c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14231 Set a temporary breakpoint.\n\
14232 Like \"break\" except the breakpoint is only temporary,\n\
14233 so it will be deleted when hit. Equivalent to \"break\" followed\n\
14234 by using \"enable delete\" on the breakpoint number.\n\
14236 BREAK_ARGS_HELP ("tbreak")));
14237 set_cmd_completer (c, location_completer);
14239 c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
14240 Set a hardware assisted breakpoint.\n\
14241 Like \"break\" except the breakpoint requires hardware support,\n\
14242 some target hardware may not have this support.\n\
14244 BREAK_ARGS_HELP ("hbreak")));
14245 set_cmd_completer (c, location_completer);
14247 c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
14248 Set a temporary hardware assisted breakpoint.\n\
14249 Like \"hbreak\" except the breakpoint is only temporary,\n\
14250 so it will be deleted when hit.\n\
14252 BREAK_ARGS_HELP ("thbreak")));
14253 set_cmd_completer (c, location_completer);
14255 cmd_list_element *enable_cmd
14256 = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
14257 Enable all or some breakpoints.\n\
14258 Usage: enable [BREAKPOINTNUM]...\n\
14259 Give breakpoint numbers (separated by spaces) as arguments.\n\
14260 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14261 This is used to cancel the effect of the \"disable\" command.\n\
14262 With a subcommand you can enable temporarily."),
14263 &enablelist, 1, &cmdlist);
14265 add_com_alias ("en", enable_cmd, class_breakpoint, 1);
14267 add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
14268 Enable all or some breakpoints.\n\
14269 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
14270 Give breakpoint numbers (separated by spaces) as arguments.\n\
14271 This is used to cancel the effect of the \"disable\" command.\n\
14272 May be abbreviated to simply \"enable\"."),
14273 &enablebreaklist, 1, &enablelist);
14275 add_cmd ("once", no_class, enable_once_command, _("\
14276 Enable some breakpoints for one hit.\n\
14277 Usage: enable breakpoints once BREAKPOINTNUM...\n\
14278 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14279 &enablebreaklist);
14281 add_cmd ("delete", no_class, enable_delete_command, _("\
14282 Enable some breakpoints and delete when hit.\n\
14283 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
14284 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14285 &enablebreaklist);
14287 add_cmd ("count", no_class, enable_count_command, _("\
14288 Enable some breakpoints for COUNT hits.\n\
14289 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
14290 If a breakpoint is hit while enabled in this fashion,\n\
14291 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14292 &enablebreaklist);
14294 add_cmd ("delete", no_class, enable_delete_command, _("\
14295 Enable some breakpoints and delete when hit.\n\
14296 Usage: enable delete BREAKPOINTNUM...\n\
14297 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14298 &enablelist);
14300 add_cmd ("once", no_class, enable_once_command, _("\
14301 Enable some breakpoints for one hit.\n\
14302 Usage: enable once BREAKPOINTNUM...\n\
14303 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14304 &enablelist);
14306 add_cmd ("count", no_class, enable_count_command, _("\
14307 Enable some breakpoints for COUNT hits.\n\
14308 Usage: enable count COUNT BREAKPOINTNUM...\n\
14309 If a breakpoint is hit while enabled in this fashion,\n\
14310 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14311 &enablelist);
14313 cmd_list_element *disable_cmd
14314 = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
14315 Disable all or some breakpoints.\n\
14316 Usage: disable [BREAKPOINTNUM]...\n\
14317 Arguments are breakpoint numbers with spaces in between.\n\
14318 To disable all breakpoints, give no argument.\n\
14319 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
14320 &disablelist, 1, &cmdlist);
14321 add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
14322 add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
14324 add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
14325 Disable all or some breakpoints.\n\
14326 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
14327 Arguments are breakpoint numbers with spaces in between.\n\
14328 To disable all breakpoints, give no argument.\n\
14329 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
14330 This command may be abbreviated \"disable\"."),
14331 &disablelist);
14333 cmd_list_element *delete_cmd
14334 = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
14335 Delete all or some breakpoints.\n\
14336 Usage: delete [BREAKPOINTNUM]...\n\
14337 Arguments are breakpoint numbers with spaces in between.\n\
14338 To delete all breakpoints, give no argument.\n\
14340 Also a prefix command for deletion of other GDB objects."),
14341 &deletelist, 1, &cmdlist);
14342 add_com_alias ("d", delete_cmd, class_breakpoint, 1);
14343 add_com_alias ("del", delete_cmd, class_breakpoint, 1);
14345 add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
14346 Delete all or some breakpoints or auto-display expressions.\n\
14347 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
14348 Arguments are breakpoint numbers with spaces in between.\n\
14349 To delete all breakpoints, give no argument.\n\
14350 This command may be abbreviated \"delete\"."),
14351 &deletelist);
14353 cmd_list_element *clear_cmd
14354 = add_com ("clear", class_breakpoint, clear_command, _("\
14355 Clear breakpoint at specified location.\n\
14356 Argument may be a linespec, explicit, or address location as described below.\n\
14358 With no argument, clears all breakpoints in the line that the selected frame\n\
14359 is executing in.\n"
14360 "\n" LOCATION_SPEC_HELP_STRING "\n\n\
14361 See also the \"delete\" command which clears breakpoints by number."));
14362 add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
14364 cmd_list_element *break_cmd
14365 = add_com ("break", class_breakpoint, break_command, _("\
14366 Set breakpoint at specified location.\n"
14367 BREAK_ARGS_HELP ("break")));
14368 set_cmd_completer (break_cmd, location_completer);
14370 add_com_alias ("b", break_cmd, class_run, 1);
14371 add_com_alias ("br", break_cmd, class_run, 1);
14372 add_com_alias ("bre", break_cmd, class_run, 1);
14373 add_com_alias ("brea", break_cmd, class_run, 1);
14375 cmd_list_element *info_breakpoints_cmd
14376 = add_info ("breakpoints", info_breakpoints_command, _("\
14377 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14378 The \"Type\" column indicates one of:\n\
14379 \tbreakpoint - normal breakpoint\n\
14380 \twatchpoint - watchpoint\n\
14381 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14382 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14383 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14384 address and file/line number respectively.\n\
14386 Convenience variable \"$_\" and default examine address for \"x\"\n\
14387 are set to the address of the last breakpoint listed unless the command\n\
14388 is prefixed with \"server \".\n\n\
14389 Convenience variable \"$bpnum\" contains the number of the last\n\
14390 breakpoint set."));
14392 add_info_alias ("b", info_breakpoints_cmd, 1);
14394 add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14395 Status of all breakpoints, or breakpoint number NUMBER.\n\
14396 The \"Type\" column indicates one of:\n\
14397 \tbreakpoint - normal breakpoint\n\
14398 \twatchpoint - watchpoint\n\
14399 \tlongjmp - internal breakpoint used to step through longjmp()\n\
14400 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14401 \tuntil - internal breakpoint used by the \"until\" command\n\
14402 \tfinish - internal breakpoint used by the \"finish\" command\n\
14403 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14404 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14405 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14406 address and file/line number respectively.\n\
14408 Convenience variable \"$_\" and default examine address for \"x\"\n\
14409 are set to the address of the last breakpoint listed unless the command\n\
14410 is prefixed with \"server \".\n\n\
14411 Convenience variable \"$bpnum\" contains the number of the last\n\
14412 breakpoint set."),
14413 &maintenanceinfolist);
14415 add_basic_prefix_cmd ("catch", class_breakpoint, _("\
14416 Set catchpoints to catch events."),
14417 &catch_cmdlist,
14418 0/*allow-unknown*/, &cmdlist);
14420 add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
14421 Set temporary catchpoints to catch events."),
14422 &tcatch_cmdlist,
14423 0/*allow-unknown*/, &cmdlist);
14425 const auto opts = make_watch_options_def_group (nullptr);
14427 static const std::string watch_help = gdb::option::build_help (_("\
14428 Set a watchpoint for EXPRESSION.\n\
14429 Usage: watch [-location] EXPRESSION\n\
14431 Options:\n\
14432 %OPTIONS%\n\
14434 A watchpoint stops execution of your program whenever the value of\n\
14435 an expression changes."), opts);
14436 c = add_com ("watch", class_breakpoint, watch_command,
14437 watch_help.c_str ());
14438 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14440 static const std::string rwatch_help = gdb::option::build_help (_("\
14441 Set a read watchpoint for EXPRESSION.\n\
14442 Usage: rwatch [-location] EXPRESSION\n\
14444 Options:\n\
14445 %OPTIONS%\n\
14447 A read watchpoint stops execution of your program whenever the value of\n\
14448 an expression is read."), opts);
14449 c = add_com ("rwatch", class_breakpoint, rwatch_command,
14450 rwatch_help.c_str ());
14451 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14453 static const std::string awatch_help = gdb::option::build_help (_("\
14454 Set an access watchpoint for EXPRESSION.\n\
14455 Usage: awatch [-location] EXPRESSION\n\
14457 Options:\n\
14458 %OPTIONS%\n\
14460 An access watchpoint stops execution of your program whenever the value\n\
14461 of an expression is either read or written."), opts);
14462 c = add_com ("awatch", class_breakpoint, awatch_command,
14463 awatch_help.c_str ());
14464 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14466 add_info ("watchpoints", info_watchpoints_command, _("\
14467 Status of specified watchpoints (all watchpoints if no argument)."));
14469 /* XXX: cagney/2005-02-23: This should be a boolean, and should
14470 respond to changes - contrary to the description. */
14471 add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
14472 &can_use_hw_watchpoints, _("\
14473 Set debugger's willingness to use watchpoint hardware."), _("\
14474 Show debugger's willingness to use watchpoint hardware."), _("\
14475 If zero, gdb will not use hardware for new watchpoints, even if\n\
14476 such is available. (However, any hardware watchpoints that were\n\
14477 created before setting this to nonzero, will continue to use watchpoint\n\
14478 hardware.)"),
14479 NULL,
14480 show_can_use_hw_watchpoints,
14481 &setlist, &showlist);
14483 can_use_hw_watchpoints = 1;
14485 /* Tracepoint manipulation commands. */
14487 cmd_list_element *trace_cmd
14488 = add_com ("trace", class_breakpoint, trace_command, _("\
14489 Set a tracepoint at specified location.\n\
14491 BREAK_ARGS_HELP ("trace") "\n\
14492 Do \"help tracepoints\" for info on other tracepoint commands."));
14493 set_cmd_completer (trace_cmd, location_completer);
14495 add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
14496 add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
14497 add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
14498 add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
14500 c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
14501 Set a fast tracepoint at specified location.\n\
14503 BREAK_ARGS_HELP ("ftrace") "\n\
14504 Do \"help tracepoints\" for info on other tracepoint commands."));
14505 set_cmd_completer (c, location_completer);
14507 c = add_com ("strace", class_breakpoint, strace_command, _("\
14508 Set a static tracepoint at location or marker.\n\
14510 strace [LOCATION] [if CONDITION]\n\
14511 LOCATION may be a linespec, explicit, or address location (described below) \n\
14512 or -m MARKER_ID.\n\n\
14513 If a marker id is specified, probe the marker with that name. With\n\
14514 no LOCATION, uses current execution address of the selected stack frame.\n\
14515 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
14516 This collects arbitrary user data passed in the probe point call to the\n\
14517 tracing library. You can inspect it when analyzing the trace buffer,\n\
14518 by printing the $_sdata variable like any other convenience variable.\n\
14520 CONDITION is a boolean expression.\n\
14521 \n" LOCATION_SPEC_HELP_STRING "\n\n\
14522 Multiple tracepoints at one place are permitted, and useful if their\n\
14523 conditions are different.\n\
14525 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
14526 Do \"help tracepoints\" for info on other tracepoint commands."));
14527 set_cmd_completer (c, location_completer);
14529 cmd_list_element *info_tracepoints_cmd
14530 = add_info ("tracepoints", info_tracepoints_command, _("\
14531 Status of specified tracepoints (all tracepoints if no argument).\n\
14532 Convenience variable \"$tpnum\" contains the number of the\n\
14533 last tracepoint set."));
14535 add_info_alias ("tp", info_tracepoints_cmd, 1);
14537 cmd_list_element *delete_tracepoints_cmd
14538 = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
14539 Delete specified tracepoints.\n\
14540 Arguments are tracepoint numbers, separated by spaces.\n\
14541 No argument means delete all tracepoints."),
14542 &deletelist);
14543 add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
14545 c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
14546 Disable specified tracepoints.\n\
14547 Arguments are tracepoint numbers, separated by spaces.\n\
14548 No argument means disable all tracepoints."),
14549 &disablelist);
14550 deprecate_cmd (c, "disable");
14552 c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
14553 Enable specified tracepoints.\n\
14554 Arguments are tracepoint numbers, separated by spaces.\n\
14555 No argument means enable all tracepoints."),
14556 &enablelist);
14557 deprecate_cmd (c, "enable");
14559 add_com ("passcount", class_trace, trace_pass_command, _("\
14560 Set the passcount for a tracepoint.\n\
14561 The trace will end when the tracepoint has been passed 'count' times.\n\
14562 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
14563 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
14565 add_basic_prefix_cmd ("save", class_breakpoint,
14566 _("Save breakpoint definitions as a script."),
14567 &save_cmdlist,
14568 0/*allow-unknown*/, &cmdlist);
14570 c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
14571 Save current breakpoint definitions as a script.\n\
14572 This includes all types of breakpoints (breakpoints, watchpoints,\n\
14573 catchpoints, tracepoints). Use the 'source' command in another debug\n\
14574 session to restore them."),
14575 &save_cmdlist);
14576 set_cmd_completer (c, filename_completer);
14578 cmd_list_element *save_tracepoints_cmd
14579 = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
14580 Save current tracepoint definitions as a script.\n\
14581 Use the 'source' command in another debug session to restore them."),
14582 &save_cmdlist);
14583 set_cmd_completer (save_tracepoints_cmd, filename_completer);
14585 c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
14586 deprecate_cmd (c, "save tracepoints");
14588 add_setshow_prefix_cmd ("breakpoint", class_maintenance,
14589 _("\
14590 Breakpoint specific settings.\n\
14591 Configure various breakpoint-specific variables such as\n\
14592 pending breakpoint behavior."),
14593 _("\
14594 Breakpoint specific settings.\n\
14595 Configure various breakpoint-specific variables such as\n\
14596 pending breakpoint behavior."),
14597 &breakpoint_set_cmdlist, &breakpoint_show_cmdlist,
14598 &setlist, &showlist);
14600 add_setshow_auto_boolean_cmd ("pending", no_class,
14601 &pending_break_support, _("\
14602 Set debugger's behavior regarding pending breakpoints."), _("\
14603 Show debugger's behavior regarding pending breakpoints."), _("\
14604 If on, an unrecognized breakpoint location will cause gdb to create a\n\
14605 pending breakpoint. If off, an unrecognized breakpoint location results in\n\
14606 an error. If auto, an unrecognized breakpoint location results in a\n\
14607 user-query to see if a pending breakpoint should be created."),
14608 NULL,
14609 show_pending_break_support,
14610 &breakpoint_set_cmdlist,
14611 &breakpoint_show_cmdlist);
14613 pending_break_support = AUTO_BOOLEAN_AUTO;
14615 add_setshow_boolean_cmd ("auto-hw", no_class,
14616 &automatic_hardware_breakpoints, _("\
14617 Set automatic usage of hardware breakpoints."), _("\
14618 Show automatic usage of hardware breakpoints."), _("\
14619 If set, the debugger will automatically use hardware breakpoints for\n\
14620 breakpoints set with \"break\" but falling in read-only memory. If not set,\n\
14621 a warning will be emitted for such breakpoints."),
14622 NULL,
14623 show_automatic_hardware_breakpoints,
14624 &breakpoint_set_cmdlist,
14625 &breakpoint_show_cmdlist);
14627 add_setshow_boolean_cmd ("always-inserted", class_support,
14628 &always_inserted_mode, _("\
14629 Set mode for inserting breakpoints."), _("\
14630 Show mode for inserting breakpoints."), _("\
14631 When this mode is on, breakpoints are inserted immediately as soon as\n\
14632 they're created, kept inserted even when execution stops, and removed\n\
14633 only when the user deletes them. When this mode is off (the default),\n\
14634 breakpoints are inserted only when execution continues, and removed\n\
14635 when execution stops."),
14636 NULL,
14637 &show_always_inserted_mode,
14638 &breakpoint_set_cmdlist,
14639 &breakpoint_show_cmdlist);
14641 add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
14642 condition_evaluation_enums,
14643 &condition_evaluation_mode_1, _("\
14644 Set mode of breakpoint condition evaluation."), _("\
14645 Show mode of breakpoint condition evaluation."), _("\
14646 When this is set to \"host\", breakpoint conditions will be\n\
14647 evaluated on the host's side by GDB. When it is set to \"target\",\n\
14648 breakpoint conditions will be downloaded to the target (if the target\n\
14649 supports such feature) and conditions will be evaluated on the target's side.\n\
14650 If this is set to \"auto\" (default), this will be automatically set to\n\
14651 \"target\" if it supports condition evaluation, otherwise it will\n\
14652 be set to \"host\"."),
14653 &set_condition_evaluation_mode,
14654 &show_condition_evaluation_mode,
14655 &breakpoint_set_cmdlist,
14656 &breakpoint_show_cmdlist);
14658 add_com ("break-range", class_breakpoint, break_range_command, _("\
14659 Set a breakpoint for an address range.\n\
14660 break-range START-LOCATION, END-LOCATION\n\
14661 where START-LOCATION and END-LOCATION can be one of the following:\n\
14662 LINENUM, for that line in the current file,\n\
14663 FILE:LINENUM, for that line in that file,\n\
14664 +OFFSET, for that number of lines after the current line\n\
14665 or the start of the range\n\
14666 FUNCTION, for the first line in that function,\n\
14667 FILE:FUNCTION, to distinguish among like-named static functions.\n\
14668 *ADDRESS, for the instruction at that address.\n\
14670 The breakpoint will stop execution of the inferior whenever it executes\n\
14671 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
14672 range (including START-LOCATION and END-LOCATION)."));
14674 c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
14675 Set a dynamic printf at specified location.\n\
14676 dprintf location,format string,arg1,arg2,...\n\
14677 location may be a linespec, explicit, or address location.\n"
14678 "\n" LOCATION_SPEC_HELP_STRING));
14679 set_cmd_completer (c, location_completer);
14681 add_setshow_enum_cmd ("dprintf-style", class_support,
14682 dprintf_style_enums, &dprintf_style, _("\
14683 Set the style of usage for dynamic printf."), _("\
14684 Show the style of usage for dynamic printf."), _("\
14685 This setting chooses how GDB will do a dynamic printf.\n\
14686 If the value is \"gdb\", then the printing is done by GDB to its own\n\
14687 console, as with the \"printf\" command.\n\
14688 If the value is \"call\", the print is done by calling a function in your\n\
14689 program; by default printf(), but you can choose a different function or\n\
14690 output stream by setting dprintf-function and dprintf-channel."),
14691 update_dprintf_commands, NULL,
14692 &setlist, &showlist);
14694 add_setshow_string_cmd ("dprintf-function", class_support,
14695 &dprintf_function, _("\
14696 Set the function to use for dynamic printf."), _("\
14697 Show the function to use for dynamic printf."), NULL,
14698 update_dprintf_commands, NULL,
14699 &setlist, &showlist);
14701 add_setshow_string_cmd ("dprintf-channel", class_support,
14702 &dprintf_channel, _("\
14703 Set the channel to use for dynamic printf."), _("\
14704 Show the channel to use for dynamic printf."), NULL,
14705 update_dprintf_commands, NULL,
14706 &setlist, &showlist);
14708 add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
14709 &disconnected_dprintf, _("\
14710 Set whether dprintf continues after GDB disconnects."), _("\
14711 Show whether dprintf continues after GDB disconnects."), _("\
14712 Use this to let dprintf commands continue to hit and produce output\n\
14713 even if GDB disconnects or detaches from the target."),
14714 NULL,
14715 NULL,
14716 &setlist, &showlist);
14718 add_com ("agent-printf", class_vars, agent_printf_command, _("\
14719 Target agent only formatted printing, like the C \"printf\" function.\n\
14720 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
14721 This supports most C printf format specifications, like %s, %d, etc.\n\
14722 This is useful for formatted output in user-defined commands."));
14724 automatic_hardware_breakpoints = true;
14726 gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
14727 "breakpoint");
14728 gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
14729 "breakpoint");