]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/breakpoint.c
d704ad1e3e2001c2fedab92ec7d46756ad1db7c6
[thirdparty/binutils-gdb.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3 Copyright (C) 1986-2025 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "arch-utils.h"
21 #include <ctype.h>
22 #include "event-top.h"
23 #include "exceptions.h"
24 #include "gdbsupport/gdb_vecs.h"
25 #include "gdbsupport/unordered_set.h"
26 #include "symtab.h"
27 #include "frame.h"
28 #include "breakpoint.h"
29 #include "tracepoint.h"
30 #include "gdbtypes.h"
31 #include "expression.h"
32 #include "gdbcore.h"
33 #include "cli/cli-cmds.h"
34 #include "value.h"
35 #include "command.h"
36 #include "inferior.h"
37 #include "infrun.h"
38 #include "gdbthread.h"
39 #include "target.h"
40 #include "language.h"
41 #include "gdb-demangle.h"
42 #include "filenames.h"
43 #include "annotate.h"
44 #include "symfile.h"
45 #include "objfiles.h"
46 #include "source.h"
47 #include "linespec.h"
48 #include "completer.h"
49 #include "ui-out.h"
50 #include "cli/cli-script.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "observable.h"
54 #include "memattr.h"
55 #include "ada-lang.h"
56 #include "top.h"
57 #include "ui.h"
58 #include "valprint.h"
59 #include "jit.h"
60 #include "parser-defs.h"
61 #include "probe.h"
62 #include "cli/cli-utils.h"
63 #include "stack.h"
64 #include "ax-gdb.h"
65 #include "dummy-frame.h"
66 #include "interps.h"
67 #include "gdbsupport/format.h"
68 #include "thread-fsm.h"
69 #include "tid-parse.h"
70 #include "cli/cli-style.h"
71 #include "cli/cli-decode.h"
72 #include "break-cond-parse.h"
73
74 /* readline include files */
75 #include "readline/tilde.h"
76
77 /* readline defines this. */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82 #include <algorithm>
83 #include "progspace-and-thread.h"
84 #include "gdbsupport/array-view.h"
85 #include <optional>
86 #include "gdbsupport/common-utils.h"
87
88 /* Prototypes for local functions. */
89
90 static void map_breakpoint_numbers (const char *,
91 gdb::function_view<void (breakpoint *)>);
92
93 static void parse_breakpoint_sals (location_spec *locspec,
94 linespec_result *canonical,
95 program_space *search_pspace);
96
97 static void breakpoint_re_set_one (breakpoint *b,
98 program_space *filter_pspace);
99
100 static void create_breakpoints_sal (struct gdbarch *,
101 struct linespec_result *,
102 gdb::unique_xmalloc_ptr<char>,
103 gdb::unique_xmalloc_ptr<char>,
104 enum bptype,
105 enum bpdisp, int, int, int,
106 int,
107 int, int, int, unsigned);
108
109 static int can_use_hardware_watchpoint
110 (const std::vector<value_ref_ptr> &vals);
111
112 static void mention (const breakpoint *);
113
114 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
115
116 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
117
118 static struct breakpoint *
119 momentary_breakpoint_from_master (struct breakpoint *orig,
120 enum bptype type,
121 int loc_enabled, int thread);
122
123 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, bool);
124
125 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
126 CORE_ADDR bpaddr,
127 enum bptype bptype,
128 struct program_space *pspace);
129
130 static bool watchpoint_locations_match (const struct bp_location *loc1,
131 const struct bp_location *loc2);
132
133 static bool breakpoint_locations_match (const struct bp_location *loc1,
134 const struct bp_location *loc2,
135 bool sw_hw_bps_match = false);
136
137 static bool breakpoint_location_address_match (struct bp_location *bl,
138 const struct address_space *aspace,
139 CORE_ADDR addr);
140
141 static bool breakpoint_location_address_range_overlap (struct bp_location *,
142 const address_space *,
143 CORE_ADDR, int);
144
145 static int remove_breakpoint (struct bp_location *);
146 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
147
148 static enum print_stop_action print_bp_stop_message (bpstat *bs);
149
150 static int hw_breakpoint_used_count (void);
151
152 static int hw_watchpoint_use_count (struct breakpoint *);
153
154 static int hw_watchpoint_used_count_others (struct breakpoint *except,
155 enum bptype type,
156 int *other_type_used);
157
158 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
159 int count);
160
161 static void decref_bp_location (struct bp_location **loc);
162
163 static std::vector<symtab_and_line> bkpt_probe_decode_location_spec
164 (struct breakpoint *b,
165 location_spec *locspec,
166 struct program_space *search_pspace);
167
168 static bool bl_address_is_meaningful (const bp_location *loc);
169
170 static int find_loc_num_by_location (const bp_location *loc);
171
172 /* update_global_location_list's modes of operation wrt to whether to
173 insert locations now. */
174 enum ugll_insert_mode
175 {
176 /* Don't insert any breakpoint locations into the inferior, only
177 remove already-inserted locations that no longer should be
178 inserted. Functions that delete a breakpoint or breakpoints
179 should specify this mode, so that deleting a breakpoint doesn't
180 have the side effect of inserting the locations of other
181 breakpoints that are marked not-inserted, but should_be_inserted
182 returns true on them.
183
184 This behavior is useful is situations close to tear-down -- e.g.,
185 after an exec, while the target still has execution, but
186 breakpoint shadows of the previous executable image should *NOT*
187 be restored to the new image; or before detaching, where the
188 target still has execution and wants to delete breakpoints from
189 GDB's lists, and all breakpoints had already been removed from
190 the inferior. */
191 UGLL_DONT_INSERT,
192
193 /* May insert breakpoints iff breakpoints_should_be_inserted_now
194 claims breakpoints should be inserted now. */
195 UGLL_MAY_INSERT,
196
197 /* Insert locations now, irrespective of
198 breakpoints_should_be_inserted_now. E.g., say all threads are
199 stopped right now, and the user did "continue". We need to
200 insert breakpoints _before_ resuming the target, but
201 UGLL_MAY_INSERT wouldn't insert them, because
202 breakpoints_should_be_inserted_now returns false at that point,
203 as no thread is running yet. */
204 UGLL_INSERT
205 };
206
207 /* Return a textual version of INSERT_MODE. */
208
209 static const char *
210 ugll_insert_mode_text (ugll_insert_mode insert_mode)
211 {
212 /* Make sure the compiler warns if a new ugll_insert_mode enumerator is added
213 but not handled here. */
214 DIAGNOSTIC_PUSH
215 DIAGNOSTIC_ERROR_SWITCH
216 switch (insert_mode)
217 {
218 case UGLL_DONT_INSERT:
219 return "UGLL_DONT_INSERT";
220 case UGLL_MAY_INSERT:
221 return "UGLL_MAY_INSERT";
222 case UGLL_INSERT:
223 return "UGLL_INSERT";
224 }
225 DIAGNOSTIC_POP
226
227 gdb_assert_not_reached ("must handle all enum values");
228 }
229
230 /* Return a textual version of REASON. */
231
232 static const char *
233 remove_bp_reason_str (remove_bp_reason reason)
234 {
235 /* Make sure the compiler warns if a new remove_bp_reason enumerator is added
236 but not handled here. */
237 DIAGNOSTIC_PUSH
238 DIAGNOSTIC_ERROR_SWITCH
239 switch (reason)
240 {
241 case REMOVE_BREAKPOINT:
242 return "regular remove";
243 case DETACH_BREAKPOINT:
244 return "detach";
245 }
246 DIAGNOSTIC_POP
247
248 gdb_assert_not_reached ("must handle all enum values");
249 }
250
251 /* Return a textual version of breakpoint location BL describing number,
252 location and address. */
253
254 static std::string
255 breakpoint_location_address_str (const bp_location *bl)
256 {
257 std::string str = string_printf ("Breakpoint %d (%s) ",
258 bl->owner->number,
259 host_address_to_string (bl));
260
261 if (bl_address_is_meaningful (bl))
262 {
263 gdb_assert (bl->gdbarch != nullptr);
264 str += string_printf ("at address %s",
265 paddress (bl->gdbarch, bl->address));
266
267 std::string loc_string = bl->to_string ();
268 if (!loc_string.empty ())
269 str += string_printf (" %s", loc_string.c_str ());
270 }
271 else
272 str += "with dummy location";
273
274 return str;
275 }
276
277 static void update_global_location_list (enum ugll_insert_mode);
278
279 static void update_global_location_list_nothrow (enum ugll_insert_mode);
280
281 static void insert_breakpoint_locations (void);
282
283 static void trace_pass_command (const char *, int);
284
285 static void set_tracepoint_count (int num);
286
287 static bool is_masked_watchpoint (const struct breakpoint *b);
288
289 /* Return true if B refers to a static tracepoint set by marker ("-m"),
290 zero otherwise. */
291
292 static bool strace_marker_p (struct breakpoint *b);
293
294 static void bkpt_probe_create_sals_from_location_spec
295 (location_spec *locspec,
296 struct linespec_result *canonical,
297 struct program_space *search_pspace);
298
299 const struct breakpoint_ops code_breakpoint_ops =
300 {
301 parse_breakpoint_sals,
302 create_breakpoints_sal,
303 };
304
305 /* Breakpoints set on probes. */
306 static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
307 {
308 bkpt_probe_create_sals_from_location_spec,
309 create_breakpoints_sal,
310 };
311
312 /* Tracepoints set on probes. We use the same methods as for breakpoints
313 on probes. */
314 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
315 {
316 bkpt_probe_create_sals_from_location_spec,
317 create_breakpoints_sal,
318 };
319
320 /* Implementation of abstract dtors. These must exist to satisfy the
321 linker. */
322
323 breakpoint::~breakpoint ()
324 {
325 }
326
327 code_breakpoint::~code_breakpoint ()
328 {
329 }
330
331 catchpoint::~catchpoint ()
332 {
333 }
334
335 /* The structure to be used in regular breakpoints. */
336 struct ordinary_breakpoint : public code_breakpoint
337 {
338 using code_breakpoint::code_breakpoint;
339
340 int resources_needed (const struct bp_location *) override;
341 enum print_stop_action print_it (const bpstat *bs) const override;
342 void print_mention () const override;
343 void print_recreate (struct ui_file *fp) const override;
344 };
345
346 /* Internal breakpoints. These typically have a lifetime the same as
347 the program, and they end up installed on the breakpoint chain with
348 a negative breakpoint number. They're visible in "maint info
349 breakpoints", but not "info breakpoints". */
350 struct internal_breakpoint : public code_breakpoint
351 {
352 internal_breakpoint (struct gdbarch *gdbarch,
353 enum bptype type, CORE_ADDR address)
354 : code_breakpoint (gdbarch, type)
355 {
356 symtab_and_line sal;
357 sal.pc = address;
358 sal.section = find_pc_overlay (sal.pc);
359 sal.pspace = current_program_space;
360 add_location (sal);
361
362 pspace = current_program_space;
363 disposition = disp_donttouch;
364 }
365
366 void re_set (program_space *pspace) override;
367 void check_status (struct bpstat *bs) override;
368 enum print_stop_action print_it (const bpstat *bs) const override;
369 void print_mention () const override;
370 };
371
372 /* Momentary breakpoints. These typically have a lifetime of some run
373 control command only, are always thread-specific, and have 0 for
374 breakpoint number. I.e., there can be many momentary breakpoints
375 on the breakpoint chain and they all same the same number (zero).
376 They're visible in "maint info breakpoints", but not "info
377 breakpoints". */
378 struct momentary_breakpoint : public code_breakpoint
379 {
380 momentary_breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
381 program_space *pspace_,
382 const struct frame_id &frame_id_,
383 int thread_)
384 : code_breakpoint (gdbarch_, bptype)
385 {
386 /* If FRAME_ID is valid, it should be a real frame, not an inlined
387 or tail-called one. */
388 gdb_assert (!frame_id_artificial_p (frame_id));
389
390 /* Momentary breakpoints are always thread-specific. */
391 gdb_assert (thread_ > 0);
392
393 pspace = pspace_;
394 enable_state = bp_enabled;
395 disposition = disp_donttouch;
396 frame_id = frame_id_;
397 thread = thread_;
398
399 /* The inferior should have been set by the parent constructor. */
400 gdb_assert (inferior == -1);
401 }
402
403 void re_set (program_space *pspace) override;
404 void check_status (struct bpstat *bs) override;
405 enum print_stop_action print_it (const bpstat *bs) const override;
406 void print_mention () const override;
407 };
408
409 /* DPrintf breakpoints. */
410 struct dprintf_breakpoint : public ordinary_breakpoint
411 {
412 using ordinary_breakpoint::ordinary_breakpoint;
413
414 void re_set (program_space *pspace) override;
415 int breakpoint_hit (const struct bp_location *bl,
416 const address_space *aspace,
417 CORE_ADDR bp_addr,
418 const target_waitstatus &ws) override;
419 void print_recreate (struct ui_file *fp) const override;
420 void after_condition_true (struct bpstat *bs) override;
421 };
422
423 /* Ranged breakpoints. */
424 struct ranged_breakpoint : public ordinary_breakpoint
425 {
426 explicit ranged_breakpoint (struct gdbarch *gdbarch,
427 const symtab_and_line &sal_start,
428 int length,
429 location_spec_up start_locspec,
430 location_spec_up end_locspec)
431 : ordinary_breakpoint (gdbarch, bp_hardware_breakpoint)
432 {
433 bp_location *bl = add_location (sal_start);
434 bl->length = length;
435
436 disposition = disp_donttouch;
437
438 locspec = std::move (start_locspec);
439 locspec_range_end = std::move (end_locspec);
440 }
441
442 int breakpoint_hit (const struct bp_location *bl,
443 const address_space *aspace,
444 CORE_ADDR bp_addr,
445 const target_waitstatus &ws) override;
446 int resources_needed (const struct bp_location *) override;
447 enum print_stop_action print_it (const bpstat *bs) const override;
448 bool print_one (const bp_location **) const override;
449 void print_one_detail (struct ui_out *) const override;
450 void print_mention () const override;
451 void print_recreate (struct ui_file *fp) const override;
452 };
453
454 /* Static tracepoints with marker (`-m'). */
455 struct static_marker_tracepoint : public tracepoint
456 {
457 using tracepoint::tracepoint;
458
459 std::vector<symtab_and_line> decode_location_spec
460 (struct location_spec *locspec,
461 struct program_space *search_pspace) override;
462 };
463
464 /* The style in which to perform a dynamic printf. This is a user
465 option because different output options have different tradeoffs;
466 if GDB does the printing, there is better error handling if there
467 is a problem with any of the arguments, but using an inferior
468 function lets you have special-purpose printers and sending of
469 output to the same place as compiled-in print functions. */
470
471 static const char dprintf_style_gdb[] = "gdb";
472 static const char dprintf_style_call[] = "call";
473 static const char dprintf_style_agent[] = "agent";
474 static const char *const dprintf_style_enums[] = {
475 dprintf_style_gdb,
476 dprintf_style_call,
477 dprintf_style_agent,
478 NULL
479 };
480 static const char *dprintf_style = dprintf_style_gdb;
481
482 /* The function to use for dynamic printf if the preferred style is to
483 call into the inferior. The value is simply a string that is
484 copied into the command, so it can be anything that GDB can
485 evaluate to a callable address, not necessarily a function name. */
486
487 static std::string dprintf_function = "printf";
488
489 /* The channel to use for dynamic printf if the preferred style is to
490 call into the inferior; if a nonempty string, it will be passed to
491 the call as the first argument, with the format string as the
492 second. As with the dprintf function, this can be anything that
493 GDB knows how to evaluate, so in addition to common choices like
494 "stderr", this could be an app-specific expression like
495 "mystreams[curlogger]". */
496
497 static std::string dprintf_channel;
498
499 /* True if dprintf commands should continue to operate even if GDB
500 has disconnected. */
501 static bool disconnected_dprintf = true;
502
503 struct command_line *
504 breakpoint_commands (struct breakpoint *b)
505 {
506 return b->commands ? b->commands.get () : NULL;
507 }
508
509 /* Flag indicating that a command has proceeded the inferior past the
510 current breakpoint. */
511
512 static bool breakpoint_proceeded;
513
514 const char *
515 bpdisp_text (enum bpdisp disp)
516 {
517 /* NOTE: the following values are a part of MI protocol and
518 represent values of 'disp' field returned when inferior stops at
519 a breakpoint. */
520 static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
521
522 return bpdisps[(int) disp];
523 }
524
525 /* Prototypes for exported functions. */
526 /* If FALSE, gdb will not use hardware support for watchpoints, even
527 if such is available. */
528 static int can_use_hw_watchpoints;
529
530 static void
531 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
532 struct cmd_list_element *c,
533 const char *value)
534 {
535 gdb_printf (file,
536 _("Debugger's willingness to use "
537 "watchpoint hardware is %s.\n"),
538 value);
539 }
540
541 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
542 If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
543 for unrecognized breakpoint locations.
544 If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized. */
545 static enum auto_boolean pending_break_support;
546 static void
547 show_pending_break_support (struct ui_file *file, int from_tty,
548 struct cmd_list_element *c,
549 const char *value)
550 {
551 gdb_printf (file,
552 _("Debugger's behavior regarding "
553 "pending breakpoints is %s.\n"),
554 value);
555 }
556
557 /* If true, gdb will automatically use hardware breakpoints for breakpoints
558 set with "break" but falling in read-only memory.
559 If false, gdb will warn about such breakpoints, but won't automatically
560 use hardware breakpoints. */
561 static bool automatic_hardware_breakpoints;
562 static void
563 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
564 struct cmd_list_element *c,
565 const char *value)
566 {
567 gdb_printf (file,
568 _("Automatic usage of hardware breakpoints is %s.\n"),
569 value);
570 }
571
572 /* If on, GDB keeps breakpoints inserted even if the inferior is
573 stopped, and immediately inserts any new breakpoints as soon as
574 they're created. If off (default), GDB keeps breakpoints off of
575 the target as long as possible. That is, it delays inserting
576 breakpoints until the next resume, and removes them again when the
577 target fully stops. This is a bit safer in case GDB crashes while
578 processing user input. */
579 static bool always_inserted_mode = false;
580
581 static void
582 show_always_inserted_mode (struct ui_file *file, int from_tty,
583 struct cmd_list_element *c, const char *value)
584 {
585 gdb_printf (file, _("Always inserted breakpoint mode is %s.\n"),
586 value);
587 }
588
589 /* See breakpoint.h. */
590 bool debug_breakpoint = false;
591
592 /* "show debug breakpoint" implementation. */
593 static void
594 show_debug_breakpoint (struct ui_file *file, int from_tty,
595 struct cmd_list_element *c, const char *value)
596 {
597 gdb_printf (file, _("Breakpoint location debugging is %s.\n"), value);
598 }
599
600 /* See breakpoint.h. */
601
602 int
603 breakpoints_should_be_inserted_now (void)
604 {
605 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
606 {
607 /* If breakpoints are global, they should be inserted even if no
608 thread under gdb's control is running, or even if there are
609 no threads under GDB's control yet. */
610 return 1;
611 }
612 else
613 {
614 if (always_inserted_mode)
615 {
616 /* The user wants breakpoints inserted even if all threads
617 are stopped. */
618 return 1;
619 }
620
621 for (inferior *inf : all_inferiors ())
622 if (inf->has_execution ()
623 && threads_are_executing (inf->process_target ()))
624 return 1;
625
626 /* Don't remove breakpoints yet if, even though all threads are
627 stopped, we still have events to process. */
628 for (thread_info *tp : all_non_exited_threads ())
629 if (tp->resumed () && tp->has_pending_waitstatus ())
630 return 1;
631 }
632 return 0;
633 }
634
635 static const char condition_evaluation_both[] = "host or target";
636
637 /* Modes for breakpoint condition evaluation. */
638 static const char condition_evaluation_auto[] = "auto";
639 static const char condition_evaluation_host[] = "host";
640 static const char condition_evaluation_target[] = "target";
641 static const char *const condition_evaluation_enums[] = {
642 condition_evaluation_auto,
643 condition_evaluation_host,
644 condition_evaluation_target,
645 NULL
646 };
647
648 /* Global that holds the current mode for breakpoint condition evaluation. */
649 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
650
651 /* Global that we use to display information to the user (gets its value from
652 condition_evaluation_mode_1. */
653 static const char *condition_evaluation_mode = condition_evaluation_auto;
654
655 /* Translate a condition evaluation mode MODE into either "host"
656 or "target". This is used mostly to translate from "auto" to the
657 real setting that is being used. It returns the translated
658 evaluation mode. */
659
660 static const char *
661 translate_condition_evaluation_mode (const char *mode)
662 {
663 if (mode == condition_evaluation_auto)
664 {
665 if (target_supports_evaluation_of_breakpoint_conditions ())
666 return condition_evaluation_target;
667 else
668 return condition_evaluation_host;
669 }
670 else
671 return mode;
672 }
673
674 /* Discovers what condition_evaluation_auto translates to. */
675
676 static const char *
677 breakpoint_condition_evaluation_mode (void)
678 {
679 return translate_condition_evaluation_mode (condition_evaluation_mode);
680 }
681
682 /* Return true if GDB should evaluate breakpoint conditions or false
683 otherwise. */
684
685 static bool
686 gdb_evaluates_breakpoint_condition_p (void)
687 {
688 const char *mode = breakpoint_condition_evaluation_mode ();
689
690 return (mode == condition_evaluation_host);
691 }
692
693 /* Are we executing breakpoint commands? */
694 static int executing_breakpoint_commands;
695
696 /* Are overlay event breakpoints enabled? */
697 static int overlay_events_enabled;
698
699 /* See description in breakpoint.h. */
700 bool target_exact_watchpoints = false;
701
702 /* Chains of all breakpoints defined. */
703
704 static intrusive_list<breakpoint> breakpoint_chain;
705
706 /* See breakpoint.h. */
707
708 breakpoint_range
709 all_breakpoints ()
710 {
711 return breakpoint_range (breakpoint_chain.begin (), breakpoint_chain.end ());
712 }
713
714 /* See breakpoint.h. */
715
716 breakpoint_safe_range
717 all_breakpoints_safe ()
718 {
719 return breakpoint_safe_range (all_breakpoints ());
720 }
721
722 /* See breakpoint.h. */
723
724 tracepoint_range
725 all_tracepoints ()
726 {
727 return tracepoint_range (tracepoint_iterator (breakpoint_chain.begin ()),
728 tracepoint_iterator (breakpoint_chain.end ()));
729 }
730
731 /* Array is sorted by bp_location_ptr_is_less_than - primarily by the
732 ADDRESS. */
733
734 static std::vector<bp_location *> bp_locations;
735
736 /* See breakpoint.h. */
737
738 const std::vector<bp_location *> &
739 all_bp_locations ()
740 {
741 return bp_locations;
742 }
743
744 /* Range to iterate over breakpoint locations at a given address. */
745
746 struct bp_locations_at_addr_range
747 {
748 using iterator = std::vector<bp_location *>::iterator;
749
750 bp_locations_at_addr_range (CORE_ADDR addr)
751 {
752 struct compare
753 {
754 bool operator() (const bp_location *loc, CORE_ADDR addr_) const
755 { return loc->address < addr_; }
756
757 bool operator() (CORE_ADDR addr_, const bp_location *loc) const
758 { return addr_ < loc->address; }
759 };
760
761 auto it_pair = std::equal_range (bp_locations.begin (), bp_locations.end (),
762 addr, compare ());
763
764 m_begin = it_pair.first;
765 m_end = it_pair.second;
766 }
767
768 iterator begin () const
769 { return m_begin; }
770
771 iterator end () const
772 { return m_end; }
773
774 private:
775 iterator m_begin;
776 iterator m_end;
777 };
778
779 /* Return a range to iterate over all breakpoint locations exactly at address
780 ADDR.
781
782 If it's needed to iterate multiple times on the same range, it's possible
783 to save the range in a local variable and use it multiple times:
784
785 auto range = all_bp_locations_at_addr (addr);
786
787 for (bp_location *loc : range)
788 // use loc
789
790 for (bp_location *loc : range)
791 // use loc
792
793 This saves a bit of time, as it avoids re-doing the binary searches to find
794 the range's boundaries. Just remember not to change the bp_locations vector
795 in the mean time, as it could make the range's iterators stale. */
796
797 static bp_locations_at_addr_range
798 all_bp_locations_at_addr (CORE_ADDR addr)
799 {
800 return bp_locations_at_addr_range (addr);
801 }
802
803 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
804 ADDRESS for the current elements of BP_LOCATIONS which get a valid
805 result from bp_location_has_shadow. You can use it for roughly
806 limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
807 an address you need to read. */
808
809 static CORE_ADDR bp_locations_placed_address_before_address_max;
810
811 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
812 + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
813 BP_LOCATIONS which get a valid result from bp_location_has_shadow.
814 You can use it for roughly limiting the subrange of BP_LOCATIONS to
815 scan for shadow bytes for an address you need to read. */
816
817 static CORE_ADDR bp_locations_shadow_len_after_address_max;
818
819 /* The locations that no longer correspond to any breakpoint, unlinked
820 from the bp_locations array, but for which a hit may still be
821 reported by a target. */
822 static std::vector<bp_location *> moribund_locations;
823
824 /* Number of last breakpoint made. */
825
826 static int breakpoint_count;
827
828 /* The value of `breakpoint_count' before the last command that
829 created breakpoints. If the last (break-like) command created more
830 than one breakpoint, then the difference between BREAKPOINT_COUNT
831 and PREV_BREAKPOINT_COUNT is more than one. */
832 static int prev_breakpoint_count;
833
834 /* Number of last tracepoint made. */
835
836 static int tracepoint_count;
837
838 static struct cmd_list_element *breakpoint_set_cmdlist;
839 static struct cmd_list_element *breakpoint_show_cmdlist;
840 struct cmd_list_element *save_cmdlist;
841
842 /* Return whether a breakpoint is an active enabled breakpoint. */
843 static bool
844 breakpoint_enabled (struct breakpoint *b)
845 {
846 return (b->enable_state == bp_enabled);
847 }
848
849 /* Set breakpoint count to NUM. */
850
851 static void
852 set_breakpoint_count (int num)
853 {
854 prev_breakpoint_count = breakpoint_count;
855 breakpoint_count = num;
856 set_internalvar_integer (lookup_internalvar ("bpnum"), num);
857 }
858
859 /* Used by `start_rbreak_breakpoints' below, to record the current
860 breakpoint count before "rbreak" creates any breakpoint. */
861 static int rbreak_start_breakpoint_count;
862
863 /* Called at the start an "rbreak" command to record the first
864 breakpoint made. */
865
866 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
867 {
868 rbreak_start_breakpoint_count = breakpoint_count;
869 }
870
871 /* Called at the end of an "rbreak" command to record the last
872 breakpoint made. */
873
874 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
875 {
876 prev_breakpoint_count = rbreak_start_breakpoint_count;
877 }
878
879 /* See breakpoint.h. */
880
881 int
882 scoped_rbreak_breakpoints::first_breakpoint () const
883 {
884 return rbreak_start_breakpoint_count + 1;
885 }
886
887 /* See breakpoint.h. */
888
889 int
890 scoped_rbreak_breakpoints::last_breakpoint () const
891 {
892 return (rbreak_start_breakpoint_count == breakpoint_count
893 ? -1
894 : breakpoint_count);
895 }
896
897 /* Used in run_command to zero the hit count when a new run starts. */
898
899 void
900 clear_breakpoint_hit_counts (void)
901 {
902 for (breakpoint &b : all_breakpoints ())
903 b.hit_count = 0;
904 }
905
906 \f
907 /* Return the breakpoint with the specified number, or NULL
908 if the number does not refer to an existing breakpoint. */
909
910 struct breakpoint *
911 get_breakpoint (int num)
912 {
913 for (breakpoint &b : all_breakpoints ())
914 if (b.number == num)
915 return &b;
916
917 return nullptr;
918 }
919
920 /* Return TRUE if NUM refer to an existing breakpoint that has
921 multiple code locations. */
922
923 static bool
924 has_multiple_locations (int num)
925 {
926 for (breakpoint &b : all_breakpoints ())
927 if (b.number == num)
928 return b.has_multiple_locations ();
929
930 return false;
931 }
932
933 \f
934
935 /* Mark locations as "conditions have changed" in case the target supports
936 evaluating conditions on its side. */
937
938 static void
939 mark_breakpoint_modified (struct breakpoint *b)
940 {
941 /* This is only meaningful if the target is
942 evaluating conditions and if the user has
943 opted for condition evaluation on the target's
944 side. */
945 if (gdb_evaluates_breakpoint_condition_p ()
946 || !target_supports_evaluation_of_breakpoint_conditions ())
947 return;
948
949 if (!is_breakpoint (b))
950 return;
951
952 for (bp_location &loc : b->locations ())
953 loc.condition_changed = condition_modified;
954 }
955
956 /* Mark location as "conditions have changed" in case the target supports
957 evaluating conditions on its side. */
958
959 static void
960 mark_breakpoint_location_modified (struct bp_location *loc)
961 {
962 /* This is only meaningful if the target is
963 evaluating conditions and if the user has
964 opted for condition evaluation on the target's
965 side. */
966 if (gdb_evaluates_breakpoint_condition_p ()
967 || !target_supports_evaluation_of_breakpoint_conditions ())
968
969 return;
970
971 if (!is_breakpoint (loc->owner))
972 return;
973
974 loc->condition_changed = condition_modified;
975 }
976
977 /* Sets the condition-evaluation mode using the static global
978 condition_evaluation_mode. */
979
980 static void
981 set_condition_evaluation_mode (const char *args, int from_tty,
982 struct cmd_list_element *c)
983 {
984 const char *old_mode, *new_mode;
985
986 if ((condition_evaluation_mode_1 == condition_evaluation_target)
987 && !target_supports_evaluation_of_breakpoint_conditions ())
988 {
989 condition_evaluation_mode_1 = condition_evaluation_mode;
990 warning (_("Target does not support breakpoint condition evaluation.\n"
991 "Using host evaluation mode instead."));
992 return;
993 }
994
995 new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
996 old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
997
998 /* Flip the switch. Flip it even if OLD_MODE == NEW_MODE as one of the
999 settings was "auto". */
1000 condition_evaluation_mode = condition_evaluation_mode_1;
1001
1002 /* Only update the mode if the user picked a different one. */
1003 if (new_mode != old_mode)
1004 {
1005 /* If the user switched to a different evaluation mode, we
1006 need to synch the changes with the target as follows:
1007
1008 "host" -> "target": Send all (valid) conditions to the target.
1009 "target" -> "host": Remove all the conditions from the target.
1010 */
1011
1012 if (new_mode == condition_evaluation_target)
1013 {
1014 /* Mark everything modified and synch conditions with the
1015 target. */
1016 for (bp_location *loc : all_bp_locations ())
1017 mark_breakpoint_location_modified (loc);
1018 }
1019 else
1020 {
1021 /* Manually mark non-duplicate locations to synch conditions
1022 with the target. We do this to remove all the conditions the
1023 target knows about. */
1024 for (bp_location *loc : all_bp_locations ())
1025 if (is_breakpoint (loc->owner) && loc->inserted)
1026 loc->needs_update = 1;
1027 }
1028
1029 /* Do the update. */
1030 update_global_location_list (UGLL_MAY_INSERT);
1031 }
1032
1033 return;
1034 }
1035
1036 /* Shows the current mode of breakpoint condition evaluation. Explicitly shows
1037 what "auto" is translating to. */
1038
1039 static void
1040 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
1041 struct cmd_list_element *c, const char *value)
1042 {
1043 if (condition_evaluation_mode == condition_evaluation_auto)
1044 gdb_printf (file,
1045 _("Breakpoint condition evaluation "
1046 "mode is %s (currently %s).\n"),
1047 value,
1048 breakpoint_condition_evaluation_mode ());
1049 else
1050 gdb_printf (file, _("Breakpoint condition evaluation mode is %s.\n"),
1051 value);
1052 }
1053
1054 /* Parse COND_STRING in the context of LOC and set as the condition
1055 expression of LOC. BP_NUM is the number of LOC's owner, LOC_NUM is
1056 the number of LOC within its owner. In case of parsing error, mark
1057 LOC as DISABLED_BY_COND. In case of success, unset DISABLED_BY_COND. */
1058
1059 static void
1060 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
1061 int bp_num, int loc_num)
1062 {
1063 bool has_junk = false;
1064 try
1065 {
1066 expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
1067 block_for_pc (loc->address), 0);
1068 if (*cond_string != 0)
1069 has_junk = true;
1070 else
1071 {
1072 loc->cond = std::move (new_exp);
1073 if (loc->disabled_by_cond && loc->enabled)
1074 gdb_printf (_("Breakpoint %d's condition is now valid at "
1075 "location %d, enabling.\n"),
1076 bp_num, loc_num);
1077
1078 loc->disabled_by_cond = false;
1079 }
1080 }
1081 catch (const gdb_exception_error &e)
1082 {
1083 if (loc->enabled)
1084 {
1085 /* Warn if a user-enabled location is now becoming disabled-by-cond.
1086 BP_NUM is 0 if the breakpoint is being defined for the first
1087 time using the "break ... if ..." command, and non-zero if
1088 already defined. */
1089 if (bp_num != 0)
1090 warning (_("failed to validate condition at location %d.%d, "
1091 "disabling:\n %s"), bp_num, loc_num, e.what ());
1092 else
1093 warning (_("failed to validate condition at location %d, "
1094 "disabling:\n %s"), loc_num, e.what ());
1095 }
1096
1097 loc->disabled_by_cond = true;
1098 }
1099
1100 if (has_junk)
1101 error (_("Garbage '%s' follows condition"), cond_string);
1102 }
1103
1104 /* See breakpoint.h. */
1105
1106 void
1107 notify_breakpoint_modified (breakpoint *b)
1108 {
1109 interps_notify_breakpoint_modified (b);
1110 gdb::observers::breakpoint_modified.notify (b);
1111 }
1112
1113 void
1114 set_breakpoint_condition (struct breakpoint *b, const char *exp,
1115 int from_tty, bool force)
1116 {
1117 if (*exp == 0)
1118 {
1119 b->cond_string.reset ();
1120
1121 if (is_watchpoint (b))
1122 gdb::checked_static_cast<watchpoint *> (b)->cond_exp.reset ();
1123 else
1124 {
1125 int loc_num = 1;
1126 for (bp_location &loc : b->locations ())
1127 {
1128 loc.cond.reset ();
1129 if (loc.disabled_by_cond && loc.enabled)
1130 gdb_printf (_("Breakpoint %d's condition is now valid at "
1131 "location %d, enabling.\n"),
1132 b->number, loc_num);
1133 loc.disabled_by_cond = false;
1134 loc_num++;
1135
1136 /* No need to free the condition agent expression
1137 bytecode (if we have one). We will handle this
1138 when we go through update_global_location_list. */
1139 }
1140 }
1141
1142 if (from_tty)
1143 gdb_printf (_("Breakpoint %d now unconditional.\n"), b->number);
1144 }
1145 else
1146 {
1147 if (is_watchpoint (b))
1148 {
1149 innermost_block_tracker tracker;
1150 const char *arg = exp;
1151 expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
1152 if (*arg != 0)
1153 error (_("Junk at end of expression"));
1154 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
1155 w->cond_exp = std::move (new_exp);
1156 w->cond_exp_valid_block = tracker.block ();
1157 }
1158 else
1159 {
1160 /* Parse and set condition expressions. We make two passes.
1161 In the first, we parse the condition string to see if it
1162 is valid in at least one location. If so, the condition
1163 would be accepted. So we go ahead and set the locations'
1164 conditions. In case no valid case is found, we throw
1165 the error and the condition string will be rejected.
1166 This two-pass approach is taken to avoid setting the
1167 state of locations in case of a reject. */
1168 for (const bp_location &loc : b->locations ())
1169 {
1170 try
1171 {
1172 const char *arg = exp;
1173 parse_exp_1 (&arg, loc.address,
1174 block_for_pc (loc.address), 0);
1175 if (*arg != 0)
1176 error (_("Junk at end of expression"));
1177 break;
1178 }
1179 catch (const gdb_exception_error &e)
1180 {
1181 /* Condition string is invalid. If this happens to
1182 be the last loc, abandon (if not forced) or continue
1183 (if forced). */
1184 if (&loc == &b->last_loc () && !force)
1185 throw;
1186 }
1187 }
1188
1189 /* If we reach here, the condition is valid at some locations. */
1190 int loc_num = 1;
1191 for (bp_location &loc : b->locations ())
1192 {
1193 set_breakpoint_location_condition (exp, &loc, b->number, loc_num);
1194 loc_num++;
1195 }
1196 }
1197
1198 /* We know that the new condition parsed successfully. The
1199 condition string of the breakpoint can be safely updated. */
1200 b->cond_string = make_unique_xstrdup (exp);
1201 b->condition_not_parsed = 0;
1202 }
1203 mark_breakpoint_modified (b);
1204
1205 notify_breakpoint_modified (b);
1206 }
1207
1208 /* See breakpoint.h. */
1209
1210 void
1211 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
1212 bool force)
1213 {
1214 for (breakpoint &b : all_breakpoints ())
1215 if (b.number == bpnum)
1216 {
1217 /* Check if this breakpoint has a "stop" method implemented in an
1218 extension language. This method and conditions entered into GDB
1219 from the CLI are mutually exclusive. */
1220 const struct extension_language_defn *extlang
1221 = get_breakpoint_cond_ext_lang (&b, EXT_LANG_NONE);
1222
1223 if (extlang != NULL)
1224 {
1225 error (_("Only one stop condition allowed. There is currently"
1226 " a %s stop condition defined for this breakpoint."),
1227 ext_lang_capitalized_name (extlang));
1228 }
1229 set_breakpoint_condition (&b, exp, from_tty, force);
1230
1231 if (is_breakpoint (&b))
1232 update_global_location_list (UGLL_MAY_INSERT);
1233
1234 return;
1235 }
1236
1237 error (_("No breakpoint number %d."), bpnum);
1238 }
1239
1240 /* The options for the "condition" command. */
1241
1242 struct condition_command_opts
1243 {
1244 /* For "-force". */
1245 bool force_condition = false;
1246 };
1247
1248 static const gdb::option::option_def condition_command_option_defs[] = {
1249
1250 gdb::option::flag_option_def<condition_command_opts> {
1251 "force",
1252 [] (condition_command_opts *opts) { return &opts->force_condition; },
1253 N_("Set the condition even if it is invalid for all current locations."),
1254 },
1255
1256 };
1257
1258 /* Create an option_def_group for the "condition" options, with
1259 CC_OPTS as context. */
1260
1261 static inline gdb::option::option_def_group
1262 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1263 {
1264 return {{condition_command_option_defs}, cc_opts};
1265 }
1266
1267 /* Completion for the "condition" command. */
1268
1269 static void
1270 condition_completer (struct cmd_list_element *cmd,
1271 completion_tracker &tracker,
1272 const char *text, const char * /*word*/)
1273 {
1274 bool has_no_arguments = (*text == '\0');
1275 condition_command_opts cc_opts;
1276 const auto group = make_condition_command_options_def_group (&cc_opts);
1277 if (gdb::option::complete_options
1278 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1279 return;
1280
1281 text = skip_spaces (text);
1282 const char *space = skip_to_space (text);
1283 if (*space == '\0')
1284 {
1285 int len;
1286
1287 if (text[0] == '$')
1288 {
1289 tracker.advance_custom_word_point_by (1);
1290 /* We don't support completion of history indices. */
1291 if (!isdigit (text[1]))
1292 complete_internalvar (tracker, &text[1]);
1293 return;
1294 }
1295
1296 /* Suggest the "-force" flag if no arguments are given. If
1297 arguments were passed, they either already include the flag,
1298 or we are beyond the point of suggesting it because it's
1299 positionally the first argument. */
1300 if (has_no_arguments)
1301 gdb::option::complete_on_all_options (tracker, group);
1302
1303 /* We're completing the breakpoint number. */
1304 len = strlen (text);
1305
1306 for (breakpoint &b : all_breakpoints ())
1307 {
1308 char number[50];
1309
1310 xsnprintf (number, sizeof (number), "%d", b.number);
1311
1312 if (strncmp (number, text, len) == 0)
1313 tracker.add_completion (make_unique_xstrdup (number));
1314 }
1315
1316 return;
1317 }
1318
1319 /* We're completing the expression part. Skip the breakpoint num. */
1320 const char *exp_start = skip_spaces (space);
1321 tracker.advance_custom_word_point_by (exp_start - text);
1322 text = exp_start;
1323 const char *word = advance_to_expression_complete_word_point (tracker, text);
1324 expression_completer (cmd, tracker, text, word);
1325 }
1326
1327 /* condition N EXP -- set break condition of breakpoint N to EXP. */
1328
1329 static void
1330 condition_command (const char *arg, int from_tty)
1331 {
1332 const char *p;
1333 int bnum;
1334
1335 if (arg == 0)
1336 error_no_arg (_("breakpoint number"));
1337
1338 p = arg;
1339
1340 /* Check if the "-force" flag was passed. */
1341 condition_command_opts cc_opts;
1342 const auto group = make_condition_command_options_def_group (&cc_opts);
1343 gdb::option::process_options
1344 (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1345
1346 bnum = get_number (&p);
1347 if (bnum == 0)
1348 error (_("Bad breakpoint argument: '%s'"), arg);
1349
1350 set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1351 }
1352
1353 /* Check that COMMAND do not contain commands that are suitable
1354 only for tracepoints and not suitable for ordinary breakpoints.
1355 Throw if any such commands is found. */
1356
1357 static void
1358 check_no_tracepoint_commands (struct command_line *commands)
1359 {
1360 struct command_line *c;
1361
1362 for (c = commands; c; c = c->next)
1363 {
1364 if (c->control_type == while_stepping_control)
1365 error (_("The 'while-stepping' command can "
1366 "only be used for tracepoints"));
1367
1368 check_no_tracepoint_commands (c->body_list_0.get ());
1369 check_no_tracepoint_commands (c->body_list_1.get ());
1370
1371 /* Not that command parsing removes leading whitespace and comment
1372 lines and also empty lines. So, we only need to check for
1373 command directly. */
1374 if (strstr (c->line, "collect ") == c->line)
1375 error (_("The 'collect' command can only be used for tracepoints"));
1376
1377 if (strstr (c->line, "teval ") == c->line)
1378 error (_("The 'teval' command can only be used for tracepoints"));
1379 }
1380 }
1381
1382 struct longjmp_breakpoint : public momentary_breakpoint
1383 {
1384 using momentary_breakpoint::momentary_breakpoint;
1385
1386 ~longjmp_breakpoint () override;
1387 };
1388
1389 /* Encapsulate tests for different types of tracepoints. */
1390
1391 static bool
1392 is_tracepoint_type (bptype type)
1393 {
1394 return (type == bp_tracepoint
1395 || type == bp_fast_tracepoint
1396 || type == bp_static_tracepoint
1397 || type == bp_static_marker_tracepoint);
1398 }
1399
1400 /* See breakpoint.h. */
1401
1402 bool
1403 is_tracepoint (const struct breakpoint *b)
1404 {
1405 return is_tracepoint_type (b->type);
1406 }
1407
1408 /* Factory function to create an appropriate instance of breakpoint given
1409 TYPE. */
1410
1411 template<typename... Arg>
1412 static std::unique_ptr<code_breakpoint>
1413 new_breakpoint_from_type (struct gdbarch *gdbarch, bptype type,
1414 Arg&&... args)
1415 {
1416 code_breakpoint *b;
1417
1418 switch (type)
1419 {
1420 case bp_breakpoint:
1421 case bp_hardware_breakpoint:
1422 b = new ordinary_breakpoint (gdbarch, type,
1423 std::forward<Arg> (args)...);
1424 break;
1425
1426 case bp_fast_tracepoint:
1427 case bp_static_tracepoint:
1428 case bp_tracepoint:
1429 b = new tracepoint (gdbarch, type,
1430 std::forward<Arg> (args)...);
1431 break;
1432
1433 case bp_static_marker_tracepoint:
1434 b = new static_marker_tracepoint (gdbarch, type,
1435 std::forward<Arg> (args)...);
1436 break;
1437
1438 case bp_dprintf:
1439 b = new dprintf_breakpoint (gdbarch, type,
1440 std::forward<Arg> (args)...);
1441 break;
1442
1443 default:
1444 gdb_assert_not_reached ("invalid type");
1445 }
1446
1447 return std::unique_ptr<code_breakpoint> (b);
1448 }
1449
1450 /* A helper function that validates that COMMANDS are valid for a
1451 breakpoint. This function will throw an exception if a problem is
1452 found. */
1453
1454 static void
1455 validate_commands_for_breakpoint (struct breakpoint *b,
1456 struct command_line *commands)
1457 {
1458 if (is_tracepoint (b))
1459 {
1460 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
1461 struct command_line *c;
1462 struct command_line *while_stepping = 0;
1463
1464 /* Reset the while-stepping step count. The previous commands
1465 might have included a while-stepping action, while the new
1466 ones might not. */
1467 t->step_count = 0;
1468
1469 /* We need to verify that each top-level element of commands is
1470 valid for tracepoints, that there's at most one
1471 while-stepping element, and that the while-stepping's body
1472 has valid tracing commands excluding nested while-stepping.
1473 We also need to validate the tracepoint action line in the
1474 context of the tracepoint --- validate_actionline actually
1475 has side effects, like setting the tracepoint's
1476 while-stepping STEP_COUNT, in addition to checking if the
1477 collect/teval actions parse and make sense in the
1478 tracepoint's context. */
1479 for (c = commands; c; c = c->next)
1480 {
1481 if (c->control_type == while_stepping_control)
1482 {
1483 if (b->type == bp_fast_tracepoint)
1484 error (_("The 'while-stepping' command "
1485 "cannot be used for fast tracepoint"));
1486 else if (b->type == bp_static_tracepoint
1487 || b->type == bp_static_marker_tracepoint)
1488 error (_("The 'while-stepping' command "
1489 "cannot be used for static tracepoint"));
1490
1491 if (while_stepping)
1492 error (_("The 'while-stepping' command "
1493 "can be used only once"));
1494 else
1495 while_stepping = c;
1496 }
1497
1498 validate_actionline (c->line, t);
1499 }
1500 if (while_stepping)
1501 {
1502 struct command_line *c2;
1503
1504 gdb_assert (while_stepping->body_list_1 == nullptr);
1505 c2 = while_stepping->body_list_0.get ();
1506 for (; c2; c2 = c2->next)
1507 {
1508 if (c2->control_type == while_stepping_control)
1509 error (_("The 'while-stepping' command cannot be nested"));
1510 }
1511 }
1512 }
1513 else
1514 {
1515 check_no_tracepoint_commands (commands);
1516 }
1517 }
1518
1519 /* Return a vector of all the static tracepoints set at ADDR. The
1520 caller is responsible for releasing the vector. */
1521
1522 std::vector<breakpoint *>
1523 static_tracepoints_here (CORE_ADDR addr)
1524 {
1525 std::vector<breakpoint *> found;
1526
1527 for (breakpoint &b : all_breakpoints ())
1528 if (b.type == bp_static_tracepoint
1529 || b.type == bp_static_marker_tracepoint)
1530 {
1531 for (bp_location &loc : b.locations ())
1532 if (loc.address == addr)
1533 found.push_back (&b);
1534 }
1535
1536 return found;
1537 }
1538
1539 /* Set the command list of B to COMMANDS. If breakpoint is tracepoint,
1540 validate that only allowed commands are included. */
1541
1542 void
1543 breakpoint_set_commands (struct breakpoint *b,
1544 counted_command_line &&commands)
1545 {
1546 /* If the commands have not changed then there's no need to update
1547 anything, and no need to emit a breakpoint modified event. */
1548 if (commands_equal (b->commands.get (), commands.get ()))
1549 return;
1550
1551 validate_commands_for_breakpoint (b, commands.get ());
1552
1553 b->commands = std::move (commands);
1554 notify_breakpoint_modified (b);
1555 }
1556
1557 /* Set the internal `silent' flag on the breakpoint. Note that this
1558 is not the same as the "silent" that may appear in the breakpoint's
1559 commands. */
1560
1561 void
1562 breakpoint_set_silent (struct breakpoint *b, int silent)
1563 {
1564 int old_silent = b->silent;
1565
1566 b->silent = silent;
1567 if (old_silent != silent)
1568 notify_breakpoint_modified (b);
1569 }
1570
1571 /* See breakpoint.h. */
1572
1573 void
1574 breakpoint_set_thread (struct breakpoint *b, int thread)
1575 {
1576 /* THREAD should be -1, meaning no thread restriction, or it should be a
1577 valid global thread-id, which are greater than zero. */
1578 gdb_assert (thread == -1 || thread > 0);
1579
1580 /* It is not valid to set a thread restriction for a breakpoint that
1581 already has task or inferior restriction. */
1582 gdb_assert (thread == -1 || (b->task == -1 && b->inferior == -1));
1583
1584 int old_thread = b->thread;
1585 b->thread = thread;
1586 if (old_thread != thread)
1587 {
1588 /* If THREAD is in a different program_space than OLD_THREAD, or the
1589 breakpoint has switched to or from being thread-specific, then we
1590 need to re-set the locations of this breakpoint. First, figure
1591 out the program_space for the old and new threads, use a value of
1592 nullptr to indicate the breakpoint is in all program spaces. */
1593 program_space *old_pspace = nullptr;
1594 if (old_thread != -1)
1595 {
1596 struct thread_info *thr = find_thread_global_id (old_thread);
1597 gdb_assert (thr != nullptr);
1598 old_pspace = thr->inf->pspace;
1599 }
1600
1601 program_space *new_pspace = nullptr;
1602 if (thread != -1)
1603 {
1604 struct thread_info *thr = find_thread_global_id (thread);
1605 gdb_assert (thr != nullptr);
1606 new_pspace = thr->inf->pspace;
1607 }
1608
1609 /* If the program space has changed for this breakpoint, then
1610 re-evaluate it's locations. */
1611 if (old_pspace != new_pspace)
1612 {
1613 /* The breakpoint is now associated with a completely different
1614 program space. Discard all of the current locations and then
1615 re-set the breakpoint in the new program space, this will
1616 create the new locations. */
1617 b->clear_locations ();
1618 breakpoint_re_set_one (b, new_pspace);
1619 }
1620
1621 /* If the program space didn't change, or the breakpoint didn't
1622 acquire any new locations after the clear_locations call, then we
1623 need to notify of the breakpoint modification now. */
1624 if (old_pspace == new_pspace || !b->has_locations ())
1625 notify_breakpoint_modified (b);
1626 }
1627 }
1628
1629 /* See breakpoint.h. */
1630
1631 void
1632 breakpoint_set_inferior (struct breakpoint *b, int inferior)
1633 {
1634 /* INFERIOR should be -1, meaning no inferior restriction, or it should
1635 be a valid inferior number, which are greater than zero. */
1636 gdb_assert (inferior == -1 || inferior > 0);
1637
1638 /* It is not valid to set an inferior restriction for a breakpoint that
1639 already has a task or thread restriction. */
1640 gdb_assert (inferior == -1 || (b->task == -1 && b->thread == -1));
1641
1642 int old_inferior = b->inferior;
1643 b->inferior = inferior;
1644 if (old_inferior != inferior)
1645 {
1646 /* If INFERIOR is in a different program_space than OLD_INFERIOR, or
1647 the breakpoint has switch to or from inferior-specific, then we
1648 need to re-set the locations of this breakpoint. First, figure
1649 out the program_space for the old and new inferiors, use a value
1650 of nullptr to indicate the breakpoint is in all program
1651 spaces. */
1652 program_space *old_pspace = nullptr;
1653 if (old_inferior != -1)
1654 {
1655 struct inferior *inf = find_inferior_id (old_inferior);
1656 gdb_assert (inf != nullptr);
1657 old_pspace = inf->pspace;
1658 }
1659
1660 program_space *new_pspace = nullptr;
1661 if (inferior != -1)
1662 {
1663 struct inferior *inf = find_inferior_id (inferior);
1664 gdb_assert (inf != nullptr);
1665 new_pspace = inf->pspace;
1666 }
1667
1668 if (old_pspace != new_pspace)
1669 {
1670 /* The breakpoint is now associated with a completely different
1671 program space. Discard all of the current locations and then
1672 re-set the breakpoint in the new program space, this will
1673 create the new locations. */
1674 b->clear_locations ();
1675 breakpoint_re_set_one (b, new_pspace);
1676 }
1677
1678 /* If the program space didn't change, or the breakpoint didn't
1679 acquire any new locations after the clear_locations call, then we
1680 need to notify of the breakpoint modification now. */
1681 if (old_pspace == new_pspace || !b->has_locations ())
1682 notify_breakpoint_modified (b);
1683 }
1684 }
1685
1686 /* See breakpoint.h. */
1687
1688 void
1689 breakpoint_set_task (struct breakpoint *b, int task)
1690 {
1691 /* TASK should be -1, meaning no task restriction, or it should be a
1692 valid task-id, which are greater than zero. */
1693 gdb_assert (task == -1 || task > 0);
1694
1695 /* It is not valid to set a task restriction for a breakpoint that
1696 already has a thread or inferior restriction. */
1697 gdb_assert (task == -1 || (b->thread == -1 && b->inferior == -1));
1698
1699 int old_task = b->task;
1700 b->task = task;
1701 if (old_task != task)
1702 notify_breakpoint_modified (b);
1703 }
1704
1705 static void
1706 commands_command_1 (const char *arg, int from_tty,
1707 struct command_line *control)
1708 {
1709 counted_command_line cmd;
1710 /* cmd_read will be true once we have read cmd. Note that cmd might still be
1711 NULL after the call to read_command_lines if the user provides an empty
1712 list of command by just typing "end". */
1713 bool cmd_read = false;
1714
1715 std::string new_arg;
1716
1717 if (arg == NULL || !*arg)
1718 {
1719 /* Argument not explicitly given. Synthesize it. */
1720 if (breakpoint_count - prev_breakpoint_count > 1)
1721 new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1722 breakpoint_count);
1723 else if (breakpoint_count > 0)
1724 new_arg = string_printf ("%d", breakpoint_count);
1725 }
1726 else
1727 {
1728 /* Create a copy of ARG. This is needed because the "commands"
1729 command may be coming from a script. In that case, the read
1730 line buffer is going to be overwritten in the lambda of
1731 'map_breakpoint_numbers' below when reading the next line
1732 before we are are done parsing the breakpoint numbers. */
1733 new_arg = arg;
1734 }
1735 arg = new_arg.c_str ();
1736
1737 map_breakpoint_numbers
1738 (arg, [&] (breakpoint *b)
1739 {
1740 if (!cmd_read)
1741 {
1742 gdb_assert (cmd == NULL);
1743 if (control != NULL)
1744 cmd = control->body_list_0;
1745 else
1746 {
1747 std::string str
1748 = string_printf (_("Type commands for breakpoint(s) "
1749 "%s, one per line."),
1750 arg);
1751
1752 auto do_validate = [=] (const char *line)
1753 {
1754 tracepoint *t
1755 = gdb::checked_static_cast<tracepoint *> (b);
1756 validate_actionline (line, t);
1757 };
1758 gdb::function_view<void (const char *)> validator;
1759 if (is_tracepoint (b))
1760 validator = do_validate;
1761
1762 cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1763 }
1764 cmd_read = true;
1765 }
1766
1767 /* If a breakpoint was on the list more than once, we don't need to
1768 do anything. */
1769 if (b->commands != cmd)
1770 {
1771 validate_commands_for_breakpoint (b, cmd.get ());
1772 b->commands = cmd;
1773 notify_breakpoint_modified (b);
1774 }
1775 });
1776 }
1777
1778 static void
1779 commands_command (const char *arg, int from_tty)
1780 {
1781 commands_command_1 (arg, from_tty, NULL);
1782 }
1783
1784 /* Like commands_command, but instead of reading the commands from
1785 input stream, takes them from an already parsed command structure.
1786
1787 This is used by cli-script.c to DTRT with breakpoint commands
1788 that are part of if and while bodies. */
1789 enum command_control_type
1790 commands_from_control_command (const char *arg, struct command_line *cmd)
1791 {
1792 commands_command_1 (arg, 0, cmd);
1793 return simple_control;
1794 }
1795
1796 /* Return true if BL->TARGET_INFO contains valid information. */
1797
1798 static bool
1799 bp_location_has_shadow (struct bp_location *bl)
1800 {
1801 if (bl->loc_type != bp_loc_software_breakpoint)
1802 return false;
1803 if (!bl->inserted)
1804 return false;
1805 if (bl->target_info.shadow_len == 0)
1806 /* BL isn't valid, or doesn't shadow memory. */
1807 return false;
1808 return true;
1809 }
1810
1811 /* Update BUF, which is LEN bytes read from the target address
1812 MEMADDR, by replacing a memory breakpoint with its shadowed
1813 contents.
1814
1815 If READBUF is not NULL, this buffer must not overlap with the of
1816 the breakpoint location's shadow_contents buffer. Otherwise, a
1817 failed assertion internal error will be raised. */
1818
1819 static void
1820 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1821 const gdb_byte *writebuf_org,
1822 ULONGEST memaddr, LONGEST len,
1823 struct bp_target_info *target_info,
1824 struct gdbarch *gdbarch)
1825 {
1826 /* Now do full processing of the found relevant range of elements. */
1827 CORE_ADDR bp_addr = 0;
1828 int bp_size = 0;
1829 int bptoffset = 0;
1830
1831 if (!breakpoint_address_match (target_info->placed_address_space, 0,
1832 current_program_space->aspace.get (), 0))
1833 {
1834 /* The breakpoint is inserted in a different address space. */
1835 return;
1836 }
1837
1838 /* Addresses and length of the part of the breakpoint that
1839 we need to copy. */
1840 bp_addr = target_info->placed_address;
1841 bp_size = target_info->shadow_len;
1842
1843 if (bp_addr + bp_size <= memaddr)
1844 {
1845 /* The breakpoint is entirely before the chunk of memory we are
1846 reading. */
1847 return;
1848 }
1849
1850 if (bp_addr >= memaddr + len)
1851 {
1852 /* The breakpoint is entirely after the chunk of memory we are
1853 reading. */
1854 return;
1855 }
1856
1857 /* Offset within shadow_contents. */
1858 if (bp_addr < memaddr)
1859 {
1860 /* Only copy the second part of the breakpoint. */
1861 bp_size -= memaddr - bp_addr;
1862 bptoffset = memaddr - bp_addr;
1863 bp_addr = memaddr;
1864 }
1865
1866 if (bp_addr + bp_size > memaddr + len)
1867 {
1868 /* Only copy the first part of the breakpoint. */
1869 bp_size -= (bp_addr + bp_size) - (memaddr + len);
1870 }
1871
1872 if (readbuf != NULL)
1873 {
1874 /* Verify that the readbuf buffer does not overlap with the
1875 shadow_contents buffer. */
1876 gdb_assert (target_info->shadow_contents >= readbuf + len
1877 || readbuf >= (target_info->shadow_contents
1878 + target_info->shadow_len));
1879
1880 /* Update the read buffer with this inserted breakpoint's
1881 shadow. */
1882 memcpy (readbuf + bp_addr - memaddr,
1883 target_info->shadow_contents + bptoffset, bp_size);
1884 }
1885 else
1886 {
1887 const unsigned char *bp;
1888 CORE_ADDR addr = target_info->reqstd_address;
1889 int placed_size;
1890
1891 /* Update the shadow with what we want to write to memory. */
1892 memcpy (target_info->shadow_contents + bptoffset,
1893 writebuf_org + bp_addr - memaddr, bp_size);
1894
1895 /* Determine appropriate breakpoint contents and size for this
1896 address. */
1897 bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1898
1899 /* Update the final write buffer with this inserted
1900 breakpoint's INSN. */
1901 memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1902 }
1903 }
1904
1905 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1906 by replacing any memory breakpoints with their shadowed contents.
1907
1908 If READBUF is not NULL, this buffer must not overlap with any of
1909 the breakpoint location's shadow_contents buffers. Otherwise,
1910 a failed assertion internal error will be raised.
1911
1912 The range of shadowed area by each bp_location is:
1913 bl->address - bp_locations_placed_address_before_address_max
1914 up to bl->address + bp_locations_shadow_len_after_address_max
1915 The range we were requested to resolve shadows for is:
1916 memaddr ... memaddr + len
1917 Thus the safe cutoff boundaries for performance optimization are
1918 memaddr + len <= (bl->address
1919 - bp_locations_placed_address_before_address_max)
1920 and:
1921 bl->address + bp_locations_shadow_len_after_address_max <= memaddr */
1922
1923 void
1924 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1925 const gdb_byte *writebuf_org,
1926 ULONGEST memaddr, LONGEST len)
1927 {
1928 /* Left boundary, right boundary and median element of our binary
1929 search. */
1930 unsigned bc_l, bc_r, bc;
1931
1932 /* Find BC_L which is a leftmost element which may affect BUF
1933 content. It is safe to report lower value but a failure to
1934 report higher one. */
1935
1936 bc_l = 0;
1937 bc_r = bp_locations.size ();
1938 while (bc_l + 1 < bc_r)
1939 {
1940 struct bp_location *bl;
1941
1942 bc = (bc_l + bc_r) / 2;
1943 bl = bp_locations[bc];
1944
1945 /* Check first BL->ADDRESS will not overflow due to the added
1946 constant. Then advance the left boundary only if we are sure
1947 the BC element can in no way affect the BUF content (MEMADDR
1948 to MEMADDR + LEN range).
1949
1950 Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1951 offset so that we cannot miss a breakpoint with its shadow
1952 range tail still reaching MEMADDR. */
1953
1954 if ((bl->address + bp_locations_shadow_len_after_address_max
1955 >= bl->address)
1956 && (bl->address + bp_locations_shadow_len_after_address_max
1957 <= memaddr))
1958 bc_l = bc;
1959 else
1960 bc_r = bc;
1961 }
1962
1963 /* Due to the binary search above, we need to make sure we pick the
1964 first location that's at BC_L's address. E.g., if there are
1965 multiple locations at the same address, BC_L may end up pointing
1966 at a duplicate location, and miss the "master"/"inserted"
1967 location. Say, given locations L1, L2 and L3 at addresses A and
1968 B:
1969
1970 L1@A, L2@A, L3@B, ...
1971
1972 BC_L could end up pointing at location L2, while the "master"
1973 location could be L1. Since the `loc->inserted' flag is only set
1974 on "master" locations, we'd forget to restore the shadow of L1
1975 and L2. */
1976 while (bc_l > 0
1977 && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1978 bc_l--;
1979
1980 /* Now do full processing of the found relevant range of elements. */
1981
1982 for (bc = bc_l; bc < bp_locations.size (); bc++)
1983 {
1984 struct bp_location *bl = bp_locations[bc];
1985
1986 /* bp_location array has BL->OWNER always non-NULL. */
1987 if (bl->owner->type == bp_none)
1988 warning (_("reading through apparently deleted breakpoint #%d?"),
1989 bl->owner->number);
1990
1991 /* Performance optimization: any further element can no longer affect BUF
1992 content. */
1993
1994 if (bl->address >= bp_locations_placed_address_before_address_max
1995 && (memaddr + len
1996 <= (bl->address
1997 - bp_locations_placed_address_before_address_max)))
1998 break;
1999
2000 if (!bp_location_has_shadow (bl))
2001 continue;
2002
2003 one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
2004 memaddr, len, &bl->target_info, bl->gdbarch);
2005 }
2006 }
2007
2008 /* See breakpoint.h. */
2009
2010 bool
2011 is_breakpoint (const struct breakpoint *bpt)
2012 {
2013 return (bpt->type == bp_breakpoint
2014 || bpt->type == bp_hardware_breakpoint
2015 || bpt->type == bp_dprintf);
2016 }
2017
2018 /* Return true if BPT is of any hardware watchpoint kind. */
2019
2020 static bool
2021 is_hardware_watchpoint (const struct breakpoint *bpt)
2022 {
2023 return (bpt->type == bp_hardware_watchpoint
2024 || bpt->type == bp_read_watchpoint
2025 || bpt->type == bp_access_watchpoint);
2026 }
2027
2028 /* See breakpoint.h. */
2029
2030 bool
2031 is_watchpoint (const struct breakpoint *bpt)
2032 {
2033 return (is_hardware_watchpoint (bpt)
2034 || bpt->type == bp_watchpoint);
2035 }
2036
2037 /* Returns true if the current thread and its running state are safe
2038 to evaluate or update watchpoint B. Watchpoints on local
2039 expressions need to be evaluated in the context of the thread that
2040 was current when the watchpoint was created, and, that thread needs
2041 to be stopped to be able to select the correct frame context.
2042 Watchpoints on global expressions can be evaluated on any thread,
2043 and in any state. It is presently left to the target allowing
2044 memory accesses when threads are running. */
2045
2046 static bool
2047 watchpoint_in_thread_scope (struct watchpoint *b)
2048 {
2049 return (b->pspace == current_program_space
2050 && (b->watchpoint_thread == null_ptid
2051 || (inferior_ptid == b->watchpoint_thread
2052 && !inferior_thread ()->executing ())));
2053 }
2054
2055 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
2056 associated bp_watchpoint_scope breakpoint. */
2057
2058 static void
2059 watchpoint_del_at_next_stop (struct watchpoint *w)
2060 {
2061 if (w->related_breakpoint != w)
2062 {
2063 gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
2064 gdb_assert (w->related_breakpoint->related_breakpoint == w);
2065 w->related_breakpoint->disposition = disp_del_at_next_stop;
2066 w->related_breakpoint->related_breakpoint = w->related_breakpoint;
2067 w->related_breakpoint = w;
2068 }
2069 w->disposition = disp_del_at_next_stop;
2070 disable_breakpoint (w);
2071 }
2072
2073 /* Extract a bitfield value from value VAL using the bit parameters contained in
2074 watchpoint W. */
2075
2076 static struct value *
2077 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
2078 {
2079 struct value *bit_val;
2080
2081 if (val == NULL)
2082 return NULL;
2083
2084 bit_val = value::allocate (val->type ());
2085
2086 val->unpack_bitfield (bit_val,
2087 w->val_bitpos,
2088 w->val_bitsize,
2089 val->contents_for_printing ().data (),
2090 val->offset ());
2091
2092 return bit_val;
2093 }
2094
2095 /* Allocate a dummy location and add it to B. This is required
2096 because bpstat_stop_status requires a location to be able to report
2097 stops. */
2098
2099 static void
2100 add_dummy_location (struct breakpoint *b,
2101 struct program_space *pspace)
2102 {
2103 gdb_assert (!b->has_locations ());
2104
2105 bp_location *loc = new bp_location (b, bp_loc_other);
2106 loc->pspace = pspace;
2107 b->add_location (*loc);
2108 }
2109
2110 /* Assuming that B is a watchpoint:
2111 - Reparse watchpoint expression, if REPARSE is true
2112 - Evaluate expression and store the result in B->val
2113 - Evaluate the condition if there is one, and store the result
2114 in b->loc->cond.
2115 - Update the list of values that must be watched in B->loc.
2116
2117 If the watchpoint disposition is disp_del_at_next_stop, then do
2118 nothing. If this is local watchpoint that is out of scope, delete
2119 it.
2120
2121 Even with `set breakpoint always-inserted on' the watchpoints are
2122 removed + inserted on each stop here. Normal breakpoints must
2123 never be removed because they might be missed by a running thread
2124 when debugging in non-stop mode. On the other hand, hardware
2125 watchpoints (is_hardware_watchpoint; processed here) are specific
2126 to each LWP since they are stored in each LWP's hardware debug
2127 registers. Therefore, such LWP must be stopped first in order to
2128 be able to modify its hardware watchpoints.
2129
2130 Hardware watchpoints must be reset exactly once after being
2131 presented to the user. It cannot be done sooner, because it would
2132 reset the data used to present the watchpoint hit to the user. And
2133 it must not be done later because it could display the same single
2134 watchpoint hit during multiple GDB stops. Note that the latter is
2135 relevant only to the hardware watchpoint types bp_read_watchpoint
2136 and bp_access_watchpoint. False hit by bp_hardware_watchpoint is
2137 not user-visible - its hit is suppressed if the memory content has
2138 not changed.
2139
2140 The following constraints influence the location where we can reset
2141 hardware watchpoints:
2142
2143 * target_stopped_by_watchpoint and target_stopped_data_address are
2144 called several times when GDB stops.
2145
2146 [linux]
2147 * Multiple hardware watchpoints can be hit at the same time,
2148 causing GDB to stop. GDB only presents one hardware watchpoint
2149 hit at a time as the reason for stopping, and all the other hits
2150 are presented later, one after the other, each time the user
2151 requests the execution to be resumed. Execution is not resumed
2152 for the threads still having pending hit event stored in
2153 LWP_INFO->STATUS. While the watchpoint is already removed from
2154 the inferior on the first stop the thread hit event is kept being
2155 reported from its cached value by linux_nat_stopped_data_address
2156 until the real thread resume happens after the watchpoint gets
2157 presented and thus its LWP_INFO->STATUS gets reset.
2158
2159 Therefore the hardware watchpoint hit can get safely reset on the
2160 watchpoint removal from inferior. */
2161
2162 static void
2163 update_watchpoint (struct watchpoint *b, bool reparse)
2164 {
2165 bool within_current_scope;
2166
2167 /* If this is a local watchpoint, we only want to check if the
2168 watchpoint frame is in scope if the current thread is the thread
2169 that was used to create the watchpoint. */
2170 if (!watchpoint_in_thread_scope (b))
2171 return;
2172
2173 if (b->disposition == disp_del_at_next_stop)
2174 return;
2175
2176 std::optional<scoped_restore_selected_frame> restore_frame;
2177
2178 /* Determine if the watchpoint is within scope. */
2179 if (b->exp_valid_block == NULL)
2180 within_current_scope = true;
2181 else
2182 {
2183 frame_info_ptr fi = get_current_frame ();
2184 struct gdbarch *frame_arch = get_frame_arch (fi);
2185 CORE_ADDR frame_pc = get_frame_pc (fi);
2186
2187 /* If we're at a point where the stack has been destroyed
2188 (e.g. in a function epilogue), unwinding may not work
2189 properly. Do not attempt to recreate locations at this
2190 point. See similar comments in watchpoint_check. */
2191 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
2192 return;
2193
2194 /* Save the current frame's ID so we can restore it after
2195 evaluating the watchpoint expression on its own frame. */
2196 /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
2197 took a frame parameter, so that we didn't have to change the
2198 selected frame. */
2199 restore_frame.emplace ();
2200
2201 fi = frame_find_by_id (b->watchpoint_frame);
2202 within_current_scope = (fi != NULL);
2203 if (within_current_scope)
2204 select_frame (fi);
2205 }
2206
2207 /* We don't free locations. They are stored in the bp_location array
2208 and update_global_location_list will eventually delete them and
2209 remove breakpoints if needed. */
2210 b->clear_locations ();
2211
2212 if (within_current_scope && reparse)
2213 {
2214 const char *s;
2215
2216 b->exp.reset ();
2217 s = (b->exp_string_reparse
2218 ? b->exp_string_reparse.get ()
2219 : b->exp_string.get ());
2220 b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
2221 /* If the meaning of expression itself changed, the old value is
2222 no longer relevant. We don't want to report a watchpoint hit
2223 to the user when the old value and the new value may actually
2224 be completely different objects. */
2225 b->val = NULL;
2226 b->val_valid = false;
2227
2228 /* Note that unlike with breakpoints, the watchpoint's condition
2229 expression is stored in the breakpoint object, not in the
2230 locations (re)created below. */
2231 if (b->cond_string != NULL)
2232 {
2233 b->cond_exp.reset ();
2234
2235 s = b->cond_string.get ();
2236 b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
2237 }
2238 }
2239
2240 /* If we failed to parse the expression, for example because
2241 it refers to a global variable in a not-yet-loaded shared library,
2242 don't try to insert watchpoint. We don't automatically delete
2243 such watchpoint, though, since failure to parse expression
2244 is different from out-of-scope watchpoint. */
2245 if (!target_has_execution ())
2246 {
2247 /* Without execution, memory can't change. No use to try and
2248 set watchpoint locations. The watchpoint will be reset when
2249 the target gains execution, through breakpoint_re_set. */
2250 if (!can_use_hw_watchpoints)
2251 {
2252 if (b->works_in_software_mode ())
2253 b->type = bp_watchpoint;
2254 else
2255 error (_("Can't set read/access watchpoint when "
2256 "hardware watchpoints are disabled."));
2257 }
2258 }
2259 else if (within_current_scope && b->exp)
2260 {
2261 std::vector<value_ref_ptr> val_chain;
2262 struct value *v, *result;
2263 struct program_space *wp_pspace;
2264
2265 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
2266 &val_chain, false);
2267
2268 /* Avoid setting b->val if it's already set. The meaning of
2269 b->val is 'the last value' user saw, and we should update
2270 it only if we reported that last value to user. As it
2271 happens, the code that reports it updates b->val directly.
2272 We don't keep track of the memory value for masked
2273 watchpoints. */
2274 if (!b->val_valid && !is_masked_watchpoint (b))
2275 {
2276 if (b->val_bitsize != 0)
2277 v = extract_bitfield_from_watchpoint_value (b, v);
2278 b->val = release_value (v);
2279 b->val_valid = true;
2280 }
2281
2282 if (b->exp_valid_block == nullptr)
2283 wp_pspace = current_program_space;
2284 else
2285 wp_pspace = get_frame_program_space (get_selected_frame (NULL));
2286
2287 /* Look at each value on the value chain. */
2288 gdb_assert (!val_chain.empty ());
2289 for (const value_ref_ptr &iter : val_chain)
2290 {
2291 v = iter.get ();
2292
2293 /* If it's a memory location, and GDB actually needed
2294 its contents to evaluate the expression, then we
2295 must watch it. If the first value returned is
2296 still lazy, that means an error occurred reading it;
2297 watch it anyway in case it becomes readable. */
2298 if (v->lval () == lval_memory
2299 && (v == val_chain[0] || ! v->lazy ()))
2300 {
2301 struct type *vtype = check_typedef (v->type ());
2302
2303 /* We only watch structs and arrays if user asked
2304 for it explicitly, never if they just happen to
2305 appear in the middle of some value chain. */
2306 if (v == result
2307 || (vtype->code () != TYPE_CODE_STRUCT
2308 && vtype->code () != TYPE_CODE_ARRAY))
2309 {
2310 CORE_ADDR addr;
2311 enum target_hw_bp_type type;
2312 int bitpos = 0, bitsize = 0;
2313
2314 if (v->bitsize () != 0)
2315 {
2316 /* Extract the bit parameters out from the bitfield
2317 sub-expression. */
2318 bitpos = v->bitpos ();
2319 bitsize = v->bitsize ();
2320 }
2321 else if (v == result && b->val_bitsize != 0)
2322 {
2323 /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2324 lvalue whose bit parameters are saved in the fields
2325 VAL_BITPOS and VAL_BITSIZE. */
2326 bitpos = b->val_bitpos;
2327 bitsize = b->val_bitsize;
2328 }
2329
2330 addr = v->address ();
2331 if (bitsize != 0)
2332 {
2333 /* Skip the bytes that don't contain the bitfield. */
2334 addr += bitpos / 8;
2335 }
2336
2337 type = hw_write;
2338 if (b->type == bp_read_watchpoint)
2339 type = hw_read;
2340 else if (b->type == bp_access_watchpoint)
2341 type = hw_access;
2342
2343 bp_location *loc = b->allocate_location ();
2344 loc->gdbarch = v->type ()->arch ();
2345 loc->pspace = wp_pspace;
2346 loc->address
2347 = gdbarch_remove_non_address_bits_watchpoint (loc->gdbarch,
2348 addr);
2349 b->add_location (*loc);
2350
2351 if (bitsize != 0)
2352 {
2353 /* Just cover the bytes that make up the bitfield. */
2354 loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2355 }
2356 else
2357 loc->length = v->type ()->length ();
2358
2359 loc->watchpoint_type = type;
2360 }
2361 }
2362 }
2363
2364 /* Helper function to bundle possibly emitting a warning along with
2365 changing the type of B to bp_watchpoint. */
2366 auto change_type_to_bp_watchpoint = [] (breakpoint *bp)
2367 {
2368 /* Only warn for breakpoints that have been assigned a +ve number,
2369 anything else is either an internal watchpoint (which we don't
2370 currently create) or has not yet been finalized, in which case
2371 this change of type will be occurring before the user is told
2372 the type of this watchpoint. */
2373 if (bp->type == bp_hardware_watchpoint && bp->number > 0)
2374 warning (_("watchpoint %d downgraded to software watchpoint"),
2375 bp->number);
2376 bp->type = bp_watchpoint;
2377 };
2378
2379 /* Change the type of breakpoint between hardware assisted or
2380 an ordinary watchpoint depending on the hardware support and
2381 free hardware slots. Recheck the number of free hardware slots
2382 as the value chain may have changed. */
2383 {
2384 int reg_cnt;
2385 enum bp_loc_type loc_type;
2386
2387 reg_cnt = can_use_hardware_watchpoint (val_chain);
2388
2389 if (reg_cnt)
2390 {
2391 int i, target_resources_ok, other_type_used;
2392 enum bptype type;
2393
2394 /* Use an exact watchpoint when there's only one memory region to be
2395 watched, and only one debug register is needed to watch it. */
2396 b->exact = target_exact_watchpoints && reg_cnt == 1;
2397
2398 /* We need to determine how many resources are already
2399 used for all other hardware watchpoints plus this one
2400 to see if we still have enough resources to also fit
2401 this watchpoint in as well. */
2402
2403 /* If this is a software watchpoint, we try to turn it
2404 to a hardware one -- count resources as if B was of
2405 hardware watchpoint type. */
2406 type = b->type;
2407 if (type == bp_watchpoint)
2408 type = bp_hardware_watchpoint;
2409
2410 /* This watchpoint may or may not have been placed on
2411 the list yet at this point (it won't be in the list
2412 if we're trying to create it for the first time,
2413 through watch_command), so always account for it
2414 manually. */
2415
2416 /* Count resources used by all watchpoints except B. */
2417 i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2418
2419 /* Add in the resources needed for B. */
2420 i += hw_watchpoint_use_count (b);
2421
2422 target_resources_ok
2423 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2424 if (target_resources_ok <= 0)
2425 {
2426 bool sw_mode = b->works_in_software_mode ();
2427
2428 if (target_resources_ok == 0 && !sw_mode)
2429 error (_("Target does not support this type of "
2430 "hardware watchpoint."));
2431 else if (target_resources_ok < 0 && !sw_mode)
2432 error (_("There are not enough available hardware "
2433 "resources for this watchpoint."));
2434
2435 /* Downgrade to software watchpoint. */
2436 change_type_to_bp_watchpoint (b);
2437 }
2438 else
2439 {
2440 /* If this was a software watchpoint, we've just
2441 found we have enough resources to turn it to a
2442 hardware watchpoint. Otherwise, this is a
2443 nop. */
2444 b->type = type;
2445 }
2446 }
2447 else if (!b->works_in_software_mode ())
2448 {
2449 if (!can_use_hw_watchpoints)
2450 error (_("Can't set read/access watchpoint when "
2451 "hardware watchpoints are disabled."));
2452 else
2453 error (_("Expression cannot be implemented with "
2454 "read/access watchpoint."));
2455 }
2456 else
2457 change_type_to_bp_watchpoint (b);
2458
2459 loc_type = (b->type == bp_watchpoint? bp_loc_software_watchpoint
2460 : bp_loc_hardware_watchpoint);
2461
2462 for (bp_location &bl : b->locations ())
2463 bl.loc_type = loc_type;
2464 }
2465
2466 /* If a software watchpoint is not watching any memory, then the
2467 above left it without any location set up. But,
2468 bpstat_stop_status requires a location to be able to report
2469 stops, so make sure there's at least a dummy one. */
2470 if (b->type == bp_watchpoint && !b->has_locations ())
2471 add_dummy_location (b, wp_pspace);
2472 }
2473 else if (!within_current_scope)
2474 {
2475 gdb_printf (_("\
2476 Watchpoint %d deleted because the program has left the block\n\
2477 in which its expression is valid.\n"),
2478 b->number);
2479 watchpoint_del_at_next_stop (b);
2480 }
2481 }
2482
2483 /* Returns true iff breakpoint location should be
2484 inserted in the inferior. We don't differentiate the type of BL's owner
2485 (breakpoint vs. tracepoint), although insert_location in tracepoint's
2486 breakpoint_ops is not defined, because in insert_bp_location,
2487 tracepoint's insert_location will not be called. */
2488
2489 static bool
2490 should_be_inserted (struct bp_location *bl)
2491 {
2492 if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2493 return false;
2494
2495 if (bl->owner->disposition == disp_del_at_next_stop)
2496 return false;
2497
2498 if (!bl->enabled || bl->disabled_by_cond
2499 || bl->shlib_disabled || bl->duplicate)
2500 return false;
2501
2502 if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2503 return false;
2504
2505 /* This is set for example, when we're attached to the parent of a
2506 vfork, and have detached from the child. The child is running
2507 free, and we expect it to do an exec or exit, at which point the
2508 OS makes the parent schedulable again (and the target reports
2509 that the vfork is done). Until the child is done with the shared
2510 memory region, do not insert breakpoints in the parent, otherwise
2511 the child could still trip on the parent's breakpoints. Since
2512 the parent is blocked anyway, it won't miss any breakpoint. */
2513 if (bl->pspace->breakpoints_not_allowed)
2514 return false;
2515
2516 /* Don't insert a breakpoint if we're trying to step past its
2517 location, except if the breakpoint is a single-step breakpoint,
2518 and the breakpoint's thread is the thread which is stepping past
2519 a breakpoint. */
2520 if ((bl->loc_type == bp_loc_software_breakpoint
2521 || bl->loc_type == bp_loc_hardware_breakpoint)
2522 && stepping_past_instruction_at (bl->pspace->aspace.get (),
2523 bl->address)
2524 /* The single-step breakpoint may be inserted at the location
2525 we're trying to step if the instruction branches to itself.
2526 However, the instruction won't be executed at all and it may
2527 break the semantics of the instruction, for example, the
2528 instruction is a conditional branch or updates some flags.
2529 We can't fix it unless GDB is able to emulate the instruction
2530 or switch to displaced stepping. */
2531 && !(bl->owner->type == bp_single_step
2532 && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2533 {
2534 infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2535 paddress (bl->gdbarch, bl->address));
2536 return false;
2537 }
2538
2539 /* Don't insert watchpoints if we're trying to step past the
2540 instruction that triggered one. */
2541 if ((bl->loc_type == bp_loc_hardware_watchpoint)
2542 && stepping_past_nonsteppable_watchpoint ())
2543 {
2544 infrun_debug_printf ("stepping past non-steppable watchpoint. "
2545 "skipping watchpoint at %s:%d",
2546 paddress (bl->gdbarch, bl->address), bl->length);
2547 return false;
2548 }
2549
2550 return true;
2551 }
2552
2553 /* Same as should_be_inserted but does the check assuming
2554 that the location is not duplicated. */
2555
2556 static bool
2557 unduplicated_should_be_inserted (struct bp_location *bl)
2558 {
2559 scoped_restore restore_bl_duplicate
2560 = make_scoped_restore (&bl->duplicate, 0);
2561
2562 return should_be_inserted (bl);
2563 }
2564
2565 /* Parses a conditional described by an expression COND into an
2566 agent expression bytecode suitable for evaluation
2567 by the bytecode interpreter. Return NULL if there was
2568 any error during parsing. */
2569
2570 static agent_expr_up
2571 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2572 {
2573 if (cond == NULL)
2574 return NULL;
2575
2576 agent_expr_up aexpr;
2577
2578 /* We don't want to stop processing, so catch any errors
2579 that may show up. */
2580 try
2581 {
2582 aexpr = gen_eval_for_expr (scope, cond);
2583 }
2584
2585 catch (const gdb_exception_error &ex)
2586 {
2587 /* If we got here, it means the condition could not be parsed to a valid
2588 bytecode expression and thus can't be evaluated on the target's side.
2589 It's no use iterating through the conditions. */
2590 }
2591
2592 /* We have a valid agent expression. */
2593 return aexpr;
2594 }
2595
2596 /* Based on location BL, create a list of breakpoint conditions to be
2597 passed on to the target. If we have duplicated locations with different
2598 conditions, we will add such conditions to the list. The idea is that the
2599 target will evaluate the list of conditions and will only notify GDB when
2600 one of them is true. */
2601
2602 static void
2603 build_target_condition_list (struct bp_location *bl)
2604 {
2605 bool null_condition_or_parse_error = false;
2606 int modified = bl->needs_update;
2607
2608 /* Release conditions left over from a previous insert. */
2609 bl->target_info.conditions.clear ();
2610
2611 /* This is only meaningful if the target is
2612 evaluating conditions and if the user has
2613 opted for condition evaluation on the target's
2614 side. */
2615 if (gdb_evaluates_breakpoint_condition_p ()
2616 || !target_supports_evaluation_of_breakpoint_conditions ())
2617 return;
2618
2619 auto loc_range = all_bp_locations_at_addr (bl->address);
2620
2621 /* Do a first pass to check for locations with no assigned
2622 conditions or conditions that fail to parse to a valid agent
2623 expression bytecode. If any of these happen, then it's no use to
2624 send conditions to the target since this location will always
2625 trigger and generate a response back to GDB. Note we consider
2626 all locations at the same address irrespective of type, i.e.,
2627 even if the locations aren't considered duplicates (e.g.,
2628 software breakpoint and hardware breakpoint at the same
2629 address). */
2630 for (bp_location *loc : loc_range)
2631 {
2632 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2633 {
2634 if (modified)
2635 {
2636 /* Re-parse the conditions since something changed. In that
2637 case we already freed the condition bytecodes (see
2638 force_breakpoint_reinsertion). We just
2639 need to parse the condition to bytecodes again. */
2640 loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2641 loc->cond.get ());
2642 }
2643
2644 /* If we have a NULL bytecode expression, it means something
2645 went wrong or we have a null condition expression. */
2646 if (!loc->cond_bytecode)
2647 {
2648 null_condition_or_parse_error = true;
2649 break;
2650 }
2651 }
2652 }
2653
2654 /* If any of these happened, it means we will have to evaluate the conditions
2655 for the location's address on gdb's side. It is no use keeping bytecodes
2656 for all the other duplicate locations, thus we free all of them here.
2657
2658 This is so we have a finer control over which locations' conditions are
2659 being evaluated by GDB or the remote stub. */
2660 if (null_condition_or_parse_error)
2661 {
2662 for (bp_location *loc : loc_range)
2663 {
2664 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2665 {
2666 /* Only go as far as the first NULL bytecode is
2667 located. */
2668 if (!loc->cond_bytecode)
2669 return;
2670
2671 loc->cond_bytecode.reset ();
2672 }
2673 }
2674 }
2675
2676 /* No NULL conditions or failed bytecode generation. Build a
2677 condition list for this location's address. If we have software
2678 and hardware locations at the same address, they aren't
2679 considered duplicates, but we still merge all the conditions
2680 anyway, as it's simpler, and doesn't really make a practical
2681 difference. */
2682 for (bp_location *loc : loc_range)
2683 if (loc->cond
2684 && is_breakpoint (loc->owner)
2685 && loc->pspace->num == bl->pspace->num
2686 && loc->owner->enable_state == bp_enabled
2687 && loc->enabled
2688 && !loc->disabled_by_cond)
2689 {
2690 /* Add the condition to the vector. This will be used later
2691 to send the conditions to the target. */
2692 bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2693 }
2694
2695 return;
2696 }
2697
2698 /* Parses a command described by string CMD into an agent expression
2699 bytecode suitable for evaluation by the bytecode interpreter.
2700 Return NULL if there was any error during parsing. */
2701
2702 static agent_expr_up
2703 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2704 {
2705 const char *cmdrest;
2706 const char *format_start, *format_end;
2707 struct gdbarch *gdbarch = get_current_arch ();
2708
2709 if (cmd == NULL)
2710 return NULL;
2711
2712 cmdrest = cmd;
2713
2714 if (*cmdrest == ',')
2715 ++cmdrest;
2716 cmdrest = skip_spaces (cmdrest);
2717
2718 if (*cmdrest++ != '"')
2719 error (_("No format string following the location"));
2720
2721 format_start = cmdrest;
2722
2723 format_pieces fpieces (&cmdrest);
2724
2725 format_end = cmdrest;
2726
2727 if (*cmdrest++ != '"')
2728 error (_("Bad format string, non-terminated '\"'."));
2729
2730 cmdrest = skip_spaces (cmdrest);
2731
2732 if (!(*cmdrest == ',' || *cmdrest == '\0'))
2733 error (_("Invalid argument syntax"));
2734
2735 if (*cmdrest == ',')
2736 cmdrest++;
2737 cmdrest = skip_spaces (cmdrest);
2738
2739 /* For each argument, make an expression. */
2740
2741 std::vector<struct expression *> argvec;
2742 while (*cmdrest != '\0')
2743 {
2744 const char *cmd1;
2745
2746 cmd1 = cmdrest;
2747 expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope),
2748 PARSER_COMMA_TERMINATES);
2749 argvec.push_back (expr.release ());
2750 cmdrest = cmd1;
2751 if (*cmdrest == ',')
2752 ++cmdrest;
2753 }
2754
2755 agent_expr_up aexpr;
2756
2757 /* We don't want to stop processing, so catch any errors
2758 that may show up. */
2759 try
2760 {
2761 aexpr = gen_printf (scope, gdbarch, 0, 0,
2762 format_start, format_end - format_start,
2763 argvec.size (), argvec.data ());
2764 }
2765 catch (const gdb_exception_error &ex)
2766 {
2767 /* If we got here, it means the command could not be parsed to a valid
2768 bytecode expression and thus can't be evaluated on the target's side.
2769 It's no use iterating through the other commands. */
2770 }
2771
2772 /* We have a valid agent expression, return it. */
2773 return aexpr;
2774 }
2775
2776 /* Based on location BL, create a list of breakpoint commands to be
2777 passed on to the target. If we have duplicated locations with
2778 different commands, we will add any such to the list. */
2779
2780 static void
2781 build_target_command_list (struct bp_location *bl)
2782 {
2783 bool null_command_or_parse_error = false;
2784 int modified = bl->needs_update;
2785
2786 /* Clear commands left over from a previous insert. */
2787 bl->target_info.tcommands.clear ();
2788
2789 if (!target_can_run_breakpoint_commands ())
2790 return;
2791
2792 /* For now, limit to agent-style dprintf breakpoints. */
2793 if (dprintf_style != dprintf_style_agent)
2794 return;
2795
2796 auto loc_range = all_bp_locations_at_addr (bl->address);
2797
2798 /* For now, if we have any location at the same address that isn't a
2799 dprintf, don't install the target-side commands, as that would
2800 make the breakpoint not be reported to the core, and we'd lose
2801 control. */
2802 for (bp_location *loc : loc_range)
2803 if (is_breakpoint (loc->owner)
2804 && loc->pspace->num == bl->pspace->num
2805 && loc->owner->type != bp_dprintf)
2806 return;
2807
2808 /* Do a first pass to check for locations with no assigned
2809 conditions or conditions that fail to parse to a valid agent expression
2810 bytecode. If any of these happen, then it's no use to send conditions
2811 to the target since this location will always trigger and generate a
2812 response back to GDB. */
2813 for (bp_location *loc : loc_range)
2814 {
2815 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2816 {
2817 if (modified)
2818 {
2819 /* Re-parse the commands since something changed. In that
2820 case we already freed the command bytecodes (see
2821 force_breakpoint_reinsertion). We just
2822 need to parse the command to bytecodes again. */
2823 loc->cmd_bytecode
2824 = parse_cmd_to_aexpr (bl->address,
2825 loc->owner->extra_string.get ());
2826 }
2827
2828 /* If we have a NULL bytecode expression, it means something
2829 went wrong or we have a null command expression. */
2830 if (!loc->cmd_bytecode)
2831 {
2832 null_command_or_parse_error = true;
2833 break;
2834 }
2835 }
2836 }
2837
2838 /* If anything failed, then we're not doing target-side commands,
2839 and so clean up. */
2840 if (null_command_or_parse_error)
2841 {
2842 for (bp_location *loc : loc_range)
2843 if (is_breakpoint (loc->owner)
2844 && loc->pspace->num == bl->pspace->num)
2845 {
2846 /* Only go as far as the first NULL bytecode is
2847 located. */
2848 if (loc->cmd_bytecode == NULL)
2849 return;
2850
2851 loc->cmd_bytecode.reset ();
2852 }
2853 }
2854
2855 /* No NULL commands or failed bytecode generation. Build a command
2856 list for all duplicate locations at this location's address.
2857 Note that here we must care for whether the breakpoint location
2858 types are considered duplicates, otherwise, say, if we have a
2859 software and hardware location at the same address, the target
2860 could end up running the commands twice. For the moment, we only
2861 support targets-side commands with dprintf, but it doesn't hurt
2862 to be pedantically correct in case that changes. */
2863 for (bp_location *loc : loc_range)
2864 if (breakpoint_locations_match (bl, loc)
2865 && loc->owner->extra_string
2866 && is_breakpoint (loc->owner)
2867 && loc->pspace->num == bl->pspace->num
2868 && loc->owner->enable_state == bp_enabled
2869 && loc->enabled
2870 && !loc->disabled_by_cond)
2871 {
2872 /* Add the command to the vector. This will be used later
2873 to send the commands to the target. */
2874 bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2875 }
2876
2877 bl->target_info.persist = 0;
2878 /* Maybe flag this location as persistent. */
2879 if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2880 bl->target_info.persist = 1;
2881 }
2882
2883 /* Return the kind of breakpoint on address *ADDR. Get the kind
2884 of breakpoint according to ADDR except single-step breakpoint.
2885 Get the kind of single-step breakpoint according to the current
2886 registers state. */
2887
2888 static int
2889 breakpoint_kind (const struct bp_location *bl, CORE_ADDR *addr)
2890 {
2891 if (bl->owner->type == bp_single_step)
2892 {
2893 struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2894 struct regcache *regcache;
2895
2896 regcache = get_thread_regcache (thr);
2897
2898 return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2899 regcache, addr);
2900 }
2901 else
2902 return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2903 }
2904
2905 /* Rethrow the currently handled exception, if it's a TARGET_CLOSE_ERROR.
2906 E is either the currently handled exception, or a copy, or a sliced copy,
2907 so we can't rethrow that one, but we can use it to inspect the properties
2908 of the currently handled exception. */
2909
2910 static void
2911 rethrow_on_target_close_error (const gdb_exception &e)
2912 {
2913 if (e.reason == 0)
2914 return;
2915 /* Can't set the breakpoint. */
2916
2917 if (e.error != TARGET_CLOSE_ERROR)
2918 return;
2919
2920 /* If the target has closed then it will have deleted any breakpoints
2921 inserted within the target inferior, as a result any further attempts
2922 to interact with the breakpoint objects is not possible. Just rethrow
2923 the error. Don't use e to rethrow, to prevent object slicing of the
2924 exception. */
2925 throw;
2926 }
2927
2928 /* Insert a low-level "breakpoint" of some type. BL is the breakpoint
2929 location. Any error messages are printed to TMP_ERROR_STREAM; and
2930 DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2931 Returns 0 for success, 1 if the bp_location type is not supported or
2932 -1 for failure.
2933
2934 NOTE drow/2003-09-09: This routine could be broken down to an
2935 object-style method for each breakpoint or catchpoint type. */
2936 static int
2937 insert_bp_location (struct bp_location *bl,
2938 struct ui_file *tmp_error_stream,
2939 int *disabled_breaks,
2940 int *hw_breakpoint_error,
2941 int *hw_bp_error_explained_already)
2942 {
2943 gdb_exception bp_excpt;
2944
2945 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2946 return 0;
2947
2948 breakpoint_debug_printf ("%s", breakpoint_location_address_str (bl).c_str ());
2949
2950 /* Note we don't initialize bl->target_info, as that wipes out
2951 the breakpoint location's shadow_contents if the breakpoint
2952 is still inserted at that location. This in turn breaks
2953 target_read_memory which depends on these buffers when
2954 a memory read is requested at the breakpoint location:
2955 Once the target_info has been wiped, we fail to see that
2956 we have a breakpoint inserted at that address and thus
2957 read the breakpoint instead of returning the data saved in
2958 the breakpoint location's shadow contents. */
2959 bl->target_info.reqstd_address = bl->address;
2960 bl->target_info.placed_address_space = bl->pspace->aspace.get ();
2961 bl->target_info.length = bl->length;
2962
2963 /* When working with target-side conditions, we must pass all the conditions
2964 for the same breakpoint address down to the target since GDB will not
2965 insert those locations. With a list of breakpoint conditions, the target
2966 can decide when to stop and notify GDB. */
2967
2968 if (is_breakpoint (bl->owner))
2969 {
2970 build_target_condition_list (bl);
2971 build_target_command_list (bl);
2972 /* Reset the modification marker. */
2973 bl->needs_update = 0;
2974 }
2975
2976 /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2977 set at a read-only address, then a breakpoint location will have
2978 been changed to hardware breakpoint before we get here. If it is
2979 "off" however, error out before actually trying to insert the
2980 breakpoint, with a nicer error message. */
2981 if (bl->loc_type == bp_loc_software_breakpoint
2982 && !automatic_hardware_breakpoints)
2983 {
2984 mem_region *mr = lookup_mem_region (bl->address);
2985
2986 if (mr != nullptr && mr->attrib.mode != MEM_RW)
2987 {
2988 gdb_printf (tmp_error_stream,
2989 _("Cannot insert breakpoint %d.\n"
2990 "Cannot set software breakpoint "
2991 "at read-only address %s\n"),
2992 bl->owner->number,
2993 paddress (bl->gdbarch, bl->address));
2994 return 1;
2995 }
2996 }
2997
2998 if (bl->loc_type == bp_loc_software_breakpoint
2999 || bl->loc_type == bp_loc_hardware_breakpoint)
3000 {
3001 /* First check to see if we have to handle an overlay. */
3002 if (overlay_debugging == ovly_off
3003 || bl->section == NULL
3004 || !(section_is_overlay (bl->section)))
3005 {
3006 /* No overlay handling: just set the breakpoint. */
3007 try
3008 {
3009 int val;
3010
3011 val = bl->owner->insert_location (bl);
3012 if (val)
3013 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
3014 }
3015 catch (gdb_exception &e)
3016 {
3017 rethrow_on_target_close_error (e);
3018 bp_excpt = std::move (e);
3019 }
3020 }
3021 else
3022 {
3023 /* This breakpoint is in an overlay section.
3024 Shall we set a breakpoint at the LMA? */
3025 if (!overlay_events_enabled)
3026 {
3027 /* Yes -- overlay event support is not active,
3028 so we must try to set a breakpoint at the LMA.
3029 This will not work for a hardware breakpoint. */
3030 if (bl->loc_type == bp_loc_hardware_breakpoint)
3031 warning (_("hardware breakpoint %d not supported in overlay!"),
3032 bl->owner->number);
3033 else
3034 {
3035 CORE_ADDR addr = overlay_unmapped_address (bl->address,
3036 bl->section);
3037 /* Set a software (trap) breakpoint at the LMA. */
3038 bl->overlay_target_info = bl->target_info;
3039 bl->overlay_target_info.reqstd_address = addr;
3040
3041 /* No overlay handling: just set the breakpoint. */
3042 try
3043 {
3044 int val;
3045
3046 bl->overlay_target_info.kind
3047 = breakpoint_kind (bl, &addr);
3048 bl->overlay_target_info.placed_address = addr;
3049 val = target_insert_breakpoint (bl->gdbarch,
3050 &bl->overlay_target_info);
3051 if (val)
3052 bp_excpt
3053 = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
3054 }
3055 catch (gdb_exception &e)
3056 {
3057 rethrow_on_target_close_error (e);
3058 bp_excpt = std::move (e);
3059 }
3060
3061 if (bp_excpt.reason != 0)
3062 gdb_printf (tmp_error_stream,
3063 "Overlay breakpoint %d "
3064 "failed: in ROM?\n",
3065 bl->owner->number);
3066 }
3067 }
3068 /* Shall we set a breakpoint at the VMA? */
3069 if (section_is_mapped (bl->section))
3070 {
3071 /* Yes. This overlay section is mapped into memory. */
3072 try
3073 {
3074 int val;
3075
3076 val = bl->owner->insert_location (bl);
3077 if (val)
3078 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
3079 }
3080 catch (gdb_exception_error &e)
3081 {
3082 rethrow_on_target_close_error (e);
3083 bp_excpt = std::move (e);
3084 }
3085 }
3086 else
3087 {
3088 /* No. This breakpoint will not be inserted.
3089 No error, but do not mark the bp as 'inserted'. */
3090 return 0;
3091 }
3092 }
3093
3094 if (bp_excpt.reason != 0)
3095 {
3096 /* Can't set the breakpoint. */
3097 gdb_assert (bl->owner != nullptr);
3098
3099 /* In some cases, we might not be able to insert a
3100 breakpoint in a shared library that has already been
3101 removed, but we have not yet processed the shlib unload
3102 event. Unfortunately, some targets that implement
3103 breakpoint insertion themselves can't tell why the
3104 breakpoint insertion failed (e.g., the remote target
3105 doesn't define error codes), so we must treat generic
3106 errors as memory errors. */
3107 if (bp_excpt.reason == RETURN_ERROR
3108 && (bp_excpt.error == GENERIC_ERROR
3109 || bp_excpt.error == MEMORY_ERROR)
3110 && bl->loc_type == bp_loc_software_breakpoint
3111 && (solib_name_from_address (bl->pspace, bl->address)
3112 || shared_objfile_contains_address_p (bl->pspace,
3113 bl->address)))
3114 {
3115 bl->shlib_disabled = 1;
3116 notify_breakpoint_modified (bl->owner);
3117 if (!*disabled_breaks)
3118 {
3119 gdb_printf (tmp_error_stream,
3120 "Cannot insert breakpoint %d.\n",
3121 bl->owner->number);
3122 gdb_printf (tmp_error_stream,
3123 "Temporarily disabling shared "
3124 "library breakpoints:\n");
3125 }
3126 *disabled_breaks = 1;
3127 gdb_printf (tmp_error_stream,
3128 "breakpoint #%d\n", bl->owner->number);
3129 return 0;
3130 }
3131 else
3132 {
3133 if (bl->loc_type == bp_loc_hardware_breakpoint)
3134 {
3135 *hw_breakpoint_error = 1;
3136 *hw_bp_error_explained_already = bp_excpt.message != NULL;
3137 gdb_printf (tmp_error_stream,
3138 "Cannot insert hardware breakpoint %d%s",
3139 bl->owner->number,
3140 bp_excpt.message ? ":" : ".\n");
3141 if (bp_excpt.message != NULL)
3142 gdb_printf (tmp_error_stream, "%s.\n",
3143 bp_excpt.what ());
3144 }
3145 else
3146 {
3147 if (bp_excpt.message == NULL)
3148 {
3149 std::string message
3150 = memory_error_message (TARGET_XFER_E_IO,
3151 bl->gdbarch, bl->address);
3152
3153 gdb_printf (tmp_error_stream,
3154 "Cannot insert breakpoint %d.\n"
3155 "%s\n",
3156 bl->owner->number, message.c_str ());
3157 }
3158 else
3159 {
3160 gdb_printf (tmp_error_stream,
3161 "Cannot insert breakpoint %d: %s\n",
3162 bl->owner->number,
3163 bp_excpt.what ());
3164 }
3165 }
3166 return 1;
3167
3168 }
3169 }
3170 else
3171 bl->inserted = 1;
3172
3173 return 0;
3174 }
3175
3176 else if (bl->loc_type == bp_loc_hardware_watchpoint
3177 && bl->owner->disposition != disp_del_at_next_stop)
3178 {
3179 int val;
3180
3181 val = bl->owner->insert_location (bl);
3182
3183 /* If trying to set a read-watchpoint, and it turns out it's not
3184 supported, try emulating one with an access watchpoint. */
3185 if (val == 1 && bl->watchpoint_type == hw_read)
3186 {
3187 /* But don't try to insert it, if there's already another
3188 hw_access location that would be considered a duplicate
3189 of this one. */
3190 for (bp_location *loc : all_bp_locations ())
3191 if (loc != bl
3192 && loc->watchpoint_type == hw_access
3193 && watchpoint_locations_match (bl, loc))
3194 {
3195 bl->duplicate = 1;
3196 bl->inserted = 1;
3197 bl->target_info = loc->target_info;
3198 bl->watchpoint_type = hw_access;
3199 val = 0;
3200 break;
3201 }
3202
3203 if (val == 1)
3204 {
3205 bl->watchpoint_type = hw_access;
3206 val = bl->owner->insert_location (bl);
3207
3208 if (val)
3209 /* Back to the original value. */
3210 bl->watchpoint_type = hw_read;
3211 }
3212 }
3213
3214 bl->inserted = (val == 0);
3215 }
3216
3217 else if (bl->owner->type == bp_catchpoint)
3218 {
3219 int val;
3220
3221 val = bl->owner->insert_location (bl);
3222 if (val)
3223 {
3224 bl->owner->enable_state = bp_disabled;
3225
3226 if (val == 1)
3227 warning (_("\
3228 Error inserting catchpoint %d: Your system does not support this type\n\
3229 of catchpoint."), bl->owner->number);
3230 else
3231 warning (_("Error inserting catchpoint %d."), bl->owner->number);
3232 }
3233
3234 bl->inserted = (val == 0);
3235
3236 /* We've already printed an error message if there was a problem
3237 inserting this catchpoint, and we've disabled the catchpoint,
3238 so just return success. */
3239 return 0;
3240 }
3241
3242 return 0;
3243 }
3244
3245 /* This function is called when program space PSPACE is about to be
3246 deleted. It takes care of updating breakpoints to not reference
3247 PSPACE anymore. */
3248
3249 void
3250 breakpoint_program_space_exit (struct program_space *pspace)
3251 {
3252 /* Remove any breakpoint that was set through this program space. */
3253 for (breakpoint &b : all_breakpoints_safe ())
3254 if (b.pspace == pspace)
3255 delete_breakpoint (&b);
3256
3257 /* Breakpoints set through other program spaces could have locations
3258 bound to PSPACE as well. Remove those. */
3259 for (bp_location *loc : all_bp_locations ())
3260 if (loc->pspace == pspace)
3261 {
3262 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
3263 loc->owner->unadd_location (*loc);
3264 }
3265
3266 /* Now update the global location list to permanently delete the
3267 removed locations above. */
3268 update_global_location_list (UGLL_DONT_INSERT);
3269 }
3270
3271 /* Make sure all breakpoints are inserted in inferior.
3272 Throws exception on any error.
3273 A breakpoint that is already inserted won't be inserted
3274 again, so calling this function twice is safe. */
3275 void
3276 insert_breakpoints (void)
3277 {
3278 for (breakpoint &bpt : all_breakpoints ())
3279 if (is_hardware_watchpoint (&bpt))
3280 {
3281 watchpoint &w = gdb::checked_static_cast<watchpoint &> (bpt);
3282
3283 update_watchpoint (&w, false /* don't reparse. */);
3284 }
3285
3286 /* Updating watchpoints creates new locations, so update the global
3287 location list. Explicitly tell ugll to insert locations and
3288 ignore breakpoints_always_inserted_mode. Also,
3289 update_global_location_list tries to "upgrade" software
3290 breakpoints to hardware breakpoints to handle "set breakpoint
3291 auto-hw", so we need to call it even if we don't have new
3292 locations. */
3293 update_global_location_list (UGLL_INSERT);
3294 }
3295
3296 /* This is used when we need to synch breakpoint conditions between GDB and the
3297 target. It is the case with deleting and disabling of breakpoints when using
3298 always-inserted mode. */
3299
3300 static void
3301 update_inserted_breakpoint_locations (void)
3302 {
3303 int error_flag = 0;
3304 int val = 0;
3305 int disabled_breaks = 0;
3306 int hw_breakpoint_error = 0;
3307 int hw_bp_details_reported = 0;
3308
3309 string_file tmp_error_stream;
3310
3311 /* Explicitly mark the warning -- this will only be printed if
3312 there was an error. */
3313 tmp_error_stream.puts ("Warning:\n");
3314
3315 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3316
3317 for (bp_location *bl : all_bp_locations ())
3318 {
3319 /* We only want to update software breakpoints and hardware
3320 breakpoints. */
3321 if (!is_breakpoint (bl->owner))
3322 continue;
3323
3324 /* We only want to update locations that are already inserted
3325 and need updating. This is to avoid unwanted insertion during
3326 deletion of breakpoints. */
3327 if (!bl->inserted || !bl->needs_update)
3328 continue;
3329
3330 switch_to_program_space_and_thread (bl->pspace);
3331
3332 /* For targets that support global breakpoints, there's no need
3333 to select an inferior to insert breakpoint to. In fact, even
3334 if we aren't attached to any process yet, we should still
3335 insert breakpoints. */
3336 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
3337 && (inferior_ptid == null_ptid || !target_has_execution ()))
3338 continue;
3339
3340 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3341 &hw_breakpoint_error, &hw_bp_details_reported);
3342 if (val)
3343 error_flag = val;
3344 }
3345
3346 if (error_flag)
3347 {
3348 target_terminal::ours_for_output ();
3349 error (("%s"), tmp_error_stream.c_str ());
3350 }
3351 }
3352
3353 /* Used when starting or continuing the program. */
3354
3355 static void
3356 insert_breakpoint_locations (void)
3357 {
3358 int error_flag = 0;
3359 int val = 0;
3360 int disabled_breaks = 0;
3361 int hw_breakpoint_error = 0;
3362 int hw_bp_error_explained_already = 0;
3363
3364 string_file tmp_error_stream;
3365
3366 /* Explicitly mark the warning -- this will only be printed if
3367 there was an error. */
3368 tmp_error_stream.puts ("Warning:\n");
3369
3370 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3371
3372 for (bp_location *bl : all_bp_locations ())
3373 {
3374 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3375 continue;
3376
3377 /* There is no point inserting thread-specific breakpoints if
3378 the thread no longer exists. ALL_BP_LOCATIONS bp_location
3379 has BL->OWNER always non-NULL. */
3380 if (bl->owner->thread != -1
3381 && !valid_global_thread_id (bl->owner->thread))
3382 continue;
3383
3384 /* Or inferior specific breakpoints if the inferior no longer
3385 exists. */
3386 if (bl->owner->inferior != -1
3387 && !valid_global_inferior_id (bl->owner->inferior))
3388 continue;
3389
3390 switch_to_program_space_and_thread (bl->pspace);
3391
3392 /* For targets that support global breakpoints, there's no need
3393 to select an inferior to insert breakpoint to. In fact, even
3394 if we aren't attached to any process yet, we should still
3395 insert breakpoints. */
3396 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
3397 && (inferior_ptid == null_ptid || !target_has_execution ()))
3398 continue;
3399
3400 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3401 &hw_breakpoint_error, &hw_bp_error_explained_already);
3402 if (val)
3403 error_flag = val;
3404 }
3405
3406 /* If we failed to insert all locations of a watchpoint, remove
3407 them, as half-inserted watchpoint is of limited use. */
3408 for (breakpoint &bpt : all_breakpoints ())
3409 {
3410 bool some_failed = false;
3411
3412 if (!is_hardware_watchpoint (&bpt))
3413 continue;
3414
3415 if (!breakpoint_enabled (&bpt))
3416 continue;
3417
3418 if (bpt.disposition == disp_del_at_next_stop)
3419 continue;
3420
3421 for (bp_location &loc : bpt.locations ())
3422 if (!loc.inserted && should_be_inserted (&loc))
3423 {
3424 some_failed = true;
3425 break;
3426 }
3427
3428 if (some_failed)
3429 {
3430 for (bp_location &loc : bpt.locations ())
3431 if (loc.inserted)
3432 remove_breakpoint (&loc);
3433
3434 hw_breakpoint_error = 1;
3435 tmp_error_stream.printf ("Could not insert "
3436 "hardware watchpoint %d.\n",
3437 bpt.number);
3438 error_flag = -1;
3439 }
3440 }
3441
3442 if (error_flag)
3443 {
3444 /* If a hardware breakpoint or watchpoint was inserted, add a
3445 message about possibly exhausted resources. */
3446 if (hw_breakpoint_error && !hw_bp_error_explained_already)
3447 {
3448 tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3449 You may have requested too many hardware breakpoints/watchpoints.\n");
3450 }
3451 target_terminal::ours_for_output ();
3452 error (("%s"), tmp_error_stream.c_str ());
3453 }
3454 }
3455
3456 /* Used when the program stops.
3457 Returns zero if successful, or non-zero if there was a problem
3458 removing a breakpoint location. */
3459
3460 int
3461 remove_breakpoints (void)
3462 {
3463 int val = 0;
3464
3465 for (bp_location *bl : all_bp_locations ())
3466 if (bl->inserted && !is_tracepoint (bl->owner))
3467 val |= remove_breakpoint (bl);
3468
3469 return val;
3470 }
3471
3472 /* When a thread exits, remove breakpoints that are related to
3473 that thread. */
3474
3475 static void
3476 remove_threaded_breakpoints (thread_info *tp,
3477 std::optional<ULONGEST> /* exit_code */,
3478 int /* silent */)
3479 {
3480 for (breakpoint &b : all_breakpoints_safe ())
3481 {
3482 if (b.thread == tp->global_num && user_breakpoint_p (&b))
3483 {
3484 gdb_printf (_("\
3485 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3486 b.number, print_thread_id (tp));
3487 delete_breakpoint (&b);
3488 }
3489 }
3490 }
3491
3492 /* Called when inferior INF has been removed from GDB. Remove associated
3493 per-inferior breakpoints. */
3494
3495 static void
3496 remove_inferior_breakpoints (struct inferior *inf)
3497 {
3498 for (breakpoint &b : all_breakpoints_safe ())
3499 {
3500 if (b.inferior == inf->num && user_breakpoint_p (&b))
3501 {
3502 /* Tell the user the breakpoint has been deleted. But only for
3503 breakpoints that would not normally have been deleted at the
3504 next stop anyway. */
3505 if (b.disposition != disp_del
3506 && b.disposition != disp_del_at_next_stop)
3507 gdb_printf (_("\
3508 Inferior-specific breakpoint %d deleted - inferior %d has been removed.\n"),
3509 b.number, inf->num);
3510 delete_breakpoint (&b);
3511 }
3512 }
3513 }
3514
3515 /* See breakpoint.h. */
3516
3517 void
3518 remove_breakpoints_inf (inferior *inf)
3519 {
3520 int val;
3521
3522 breakpoint_debug_printf ("inf->num = %d", inf->num);
3523
3524 for (bp_location *bl : all_bp_locations ())
3525 {
3526 if (bl->pspace != inf->pspace)
3527 continue;
3528
3529 if (bl->inserted && !bl->target_info.persist)
3530 {
3531 val = remove_breakpoint (bl);
3532 if (val != 0)
3533 return;
3534 }
3535 }
3536 }
3537
3538 static int internal_breakpoint_number = -1;
3539
3540 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3541 If INTERNAL is non-zero, the breakpoint number will be populated
3542 from internal_breakpoint_number and that variable decremented.
3543 Otherwise the breakpoint number will be populated from
3544 breakpoint_count and that value incremented. Internal breakpoints
3545 do not set the internal var bpnum. */
3546 static void
3547 set_breakpoint_number (int internal, struct breakpoint *b)
3548 {
3549 if (internal)
3550 b->number = internal_breakpoint_number--;
3551 else
3552 {
3553 set_breakpoint_count (breakpoint_count + 1);
3554 b->number = breakpoint_count;
3555 }
3556 }
3557
3558 /* Create a TYPE breakpoint on ADDRESS from an object file with GDBARCH. */
3559
3560 static struct breakpoint *
3561 create_internal_breakpoint (struct gdbarch *gdbarch,
3562 CORE_ADDR address, enum bptype type)
3563 {
3564 std::unique_ptr<internal_breakpoint> b
3565 (new internal_breakpoint (gdbarch, type, address));
3566
3567 b->number = internal_breakpoint_number--;
3568
3569 return add_to_breakpoint_chain (std::move (b));
3570 }
3571
3572 /* Create a TYPE breakpoint on minimal symbol MSYM from an object file with
3573 GDBARCH. */
3574
3575 static struct breakpoint *
3576 create_internal_breakpoint (struct gdbarch *gdbarch,
3577 bound_minimal_symbol &msym, enum bptype type)
3578 {
3579 CORE_ADDR address;
3580
3581 address = msym.value_address ();
3582
3583 address = gdbarch_convert_from_func_ptr_addr
3584 (gdbarch, address, current_inferior ()->top_target ());
3585
3586 /* Note that we're not using gdbarch_addr_bits_remove here, because that's
3587 related to addresses in $pc. We're getting the address from the
3588 minimal symbol table. */
3589
3590 /* Is gdbarch_deprecated_function_start_offset needed here? Or is that dealt
3591 with elsewhere? Needs testing on vax. */
3592
3593 if (gdbarch_skip_entrypoint_p (gdbarch))
3594 address = gdbarch_skip_entrypoint (gdbarch, address);
3595
3596 return create_internal_breakpoint (gdbarch, address, type);
3597 }
3598
3599 static const char *const longjmp_names[] =
3600 {
3601 "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3602 };
3603 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3604
3605 /* Per-objfile data private to breakpoint.c. */
3606 struct breakpoint_objfile_data
3607 {
3608 /* Minimal symbol for "_ovly_debug_event" (if any). */
3609 bound_minimal_symbol overlay_msym;
3610
3611 /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any). */
3612 bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3613
3614 /* True if we have looked for longjmp probes. */
3615 int longjmp_searched = 0;
3616
3617 /* SystemTap probe points for longjmp (if any). These are non-owning
3618 references. */
3619 std::vector<probe *> longjmp_probes;
3620
3621 /* Minimal symbol for "std::terminate()" (if any). */
3622 bound_minimal_symbol terminate_msym;
3623
3624 /* Minimal symbol for "_Unwind_DebugHook" (if any). */
3625 bound_minimal_symbol exception_msym;
3626
3627 /* True if we have looked for exception probes. */
3628 int exception_searched = 0;
3629
3630 /* SystemTap probe points for unwinding (if any). These are non-owning
3631 references. */
3632 std::vector<probe *> exception_probes;
3633 };
3634
3635 static const registry<objfile>::key<breakpoint_objfile_data>
3636 breakpoint_objfile_key;
3637
3638 /* Minimal symbol not found sentinel. */
3639 static struct minimal_symbol msym_not_found;
3640
3641 /* Returns TRUE if MSYM point to the "not found" sentinel. */
3642
3643 static bool
3644 msym_not_found_p (const struct minimal_symbol *msym)
3645 {
3646 return msym == &msym_not_found;
3647 }
3648
3649 /* Return per-objfile data needed by breakpoint.c.
3650 Allocate the data if necessary. */
3651
3652 static struct breakpoint_objfile_data *
3653 get_breakpoint_objfile_data (struct objfile *objfile)
3654 {
3655 struct breakpoint_objfile_data *bp_objfile_data;
3656
3657 bp_objfile_data = breakpoint_objfile_key.get (objfile);
3658 if (bp_objfile_data == NULL)
3659 bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3660 return bp_objfile_data;
3661 }
3662
3663 static void
3664 create_overlay_event_breakpoint (void)
3665 {
3666 const char *const func_name = "_ovly_debug_event";
3667
3668 for (objfile *objfile : current_program_space->objfiles ())
3669 {
3670 struct breakpoint *b;
3671 struct breakpoint_objfile_data *bp_objfile_data;
3672 CORE_ADDR addr;
3673
3674 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3675
3676 if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3677 continue;
3678
3679 if (bp_objfile_data->overlay_msym.minsym == NULL)
3680 {
3681 bound_minimal_symbol m
3682 = lookup_minimal_symbol_text (current_program_space, func_name,
3683 objfile);
3684 if (m.minsym == NULL)
3685 {
3686 /* Avoid future lookups in this objfile. */
3687 bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3688 continue;
3689 }
3690 bp_objfile_data->overlay_msym = m;
3691 }
3692
3693 addr = bp_objfile_data->overlay_msym.value_address ();
3694 b = create_internal_breakpoint (objfile->arch (), addr,
3695 bp_overlay_event);
3696 b->locspec = new_explicit_location_spec_function (func_name);
3697
3698 if (overlay_debugging == ovly_auto)
3699 {
3700 b->enable_state = bp_enabled;
3701 overlay_events_enabled = 1;
3702 }
3703 else
3704 {
3705 b->enable_state = bp_disabled;
3706 overlay_events_enabled = 0;
3707 }
3708 }
3709 }
3710
3711 /* Install a master longjmp breakpoint for OBJFILE using a probe. Return
3712 true if a breakpoint was installed. */
3713
3714 static bool
3715 create_longjmp_master_breakpoint_probe (objfile *objfile)
3716 {
3717 struct gdbarch *gdbarch = objfile->arch ();
3718 struct breakpoint_objfile_data *bp_objfile_data
3719 = get_breakpoint_objfile_data (objfile);
3720
3721 if (!bp_objfile_data->longjmp_searched)
3722 {
3723 std::vector<probe *> ret
3724 = find_probes_in_objfile (objfile, "libc", "longjmp");
3725
3726 if (!ret.empty ())
3727 {
3728 /* We are only interested in checking one element. */
3729 probe *p = ret[0];
3730
3731 if (!p->can_evaluate_arguments ())
3732 {
3733 /* We cannot use the probe interface here,
3734 because it does not know how to evaluate
3735 arguments. */
3736 ret.clear ();
3737 }
3738 }
3739 bp_objfile_data->longjmp_probes = ret;
3740 bp_objfile_data->longjmp_searched = 1;
3741 }
3742
3743 if (bp_objfile_data->longjmp_probes.empty ())
3744 return false;
3745
3746 for (probe *p : bp_objfile_data->longjmp_probes)
3747 {
3748 struct breakpoint *b;
3749
3750 b = create_internal_breakpoint (gdbarch,
3751 p->get_relocated_address (objfile),
3752 bp_longjmp_master);
3753 b->locspec = new_probe_location_spec ("-probe-stap libc:longjmp");
3754 b->enable_state = bp_disabled;
3755 }
3756
3757 return true;
3758 }
3759
3760 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3761 Return true if at least one breakpoint was installed. */
3762
3763 static bool
3764 create_longjmp_master_breakpoint_names (objfile *objfile)
3765 {
3766 struct gdbarch *gdbarch = objfile->arch ();
3767 if (!gdbarch_get_longjmp_target_p (gdbarch))
3768 return false;
3769
3770 struct breakpoint_objfile_data *bp_objfile_data
3771 = get_breakpoint_objfile_data (objfile);
3772 unsigned int installed_bp = 0;
3773
3774 for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3775 {
3776 struct breakpoint *b;
3777 const char *func_name;
3778 CORE_ADDR addr;
3779
3780 if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3781 continue;
3782
3783 func_name = longjmp_names[i];
3784 if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3785 {
3786 bound_minimal_symbol m
3787 = lookup_minimal_symbol_text (objfile->pspace (), func_name,
3788 objfile);
3789 if (m.minsym == NULL)
3790 {
3791 /* Prevent future lookups in this objfile. */
3792 bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3793 continue;
3794 }
3795 bp_objfile_data->longjmp_msym[i] = m;
3796 }
3797
3798 addr = bp_objfile_data->longjmp_msym[i].value_address ();
3799 b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master);
3800 b->locspec = new_explicit_location_spec_function (func_name);
3801 b->enable_state = bp_disabled;
3802 installed_bp++;
3803 }
3804
3805 return installed_bp > 0;
3806 }
3807
3808 /* Create a master longjmp breakpoint. */
3809
3810 static void
3811 create_longjmp_master_breakpoint (void)
3812 {
3813 scoped_restore_current_program_space restore_pspace;
3814
3815 for (struct program_space *pspace : program_spaces)
3816 {
3817 set_current_program_space (pspace);
3818
3819 for (objfile *obj : pspace->objfiles ())
3820 {
3821 /* Skip separate debug object, it's handled in the loop below. */
3822 if (obj->separate_debug_objfile_backlink != nullptr)
3823 continue;
3824
3825 /* Try a probe kind breakpoint on main objfile. */
3826 if (create_longjmp_master_breakpoint_probe (obj))
3827 continue;
3828
3829 /* Try longjmp_names kind breakpoints on main and separate_debug
3830 objfiles. */
3831 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3832 if (create_longjmp_master_breakpoint_names (debug_objfile))
3833 break;
3834 }
3835 }
3836 }
3837
3838 /* Create a master std::terminate breakpoint. */
3839 static void
3840 create_std_terminate_master_breakpoint (void)
3841 {
3842 const char *const func_name = "std::terminate()";
3843
3844 scoped_restore_current_program_space restore_pspace;
3845 scoped_restore_current_language save_language (language_cplus);
3846
3847 for (struct program_space *pspace : program_spaces)
3848 {
3849 set_current_program_space (pspace);
3850
3851 for (objfile *objfile : pspace->objfiles ())
3852 {
3853 struct breakpoint *b;
3854 struct breakpoint_objfile_data *bp_objfile_data;
3855
3856 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3857
3858 if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3859 continue;
3860
3861 if (bp_objfile_data->terminate_msym.minsym == NULL)
3862 {
3863 bound_minimal_symbol m
3864 = lookup_minimal_symbol (current_program_space, func_name,
3865 objfile);
3866 if (m.minsym == NULL || (m.minsym->type () != mst_text
3867 && m.minsym->type () != mst_file_text))
3868 {
3869 /* Prevent future lookups in this objfile. */
3870 bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3871 continue;
3872 }
3873 bp_objfile_data->terminate_msym = m;
3874 }
3875
3876 b = create_internal_breakpoint (objfile->arch (),
3877 bp_objfile_data->terminate_msym,
3878 bp_std_terminate_master);
3879 b->locspec = new_explicit_location_spec_function (func_name);
3880 b->enable_state = bp_disabled;
3881 }
3882 }
3883 }
3884
3885 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3886 probe. Return true if a breakpoint was installed. */
3887
3888 static bool
3889 create_exception_master_breakpoint_probe (objfile *objfile)
3890 {
3891 struct breakpoint *b;
3892 struct gdbarch *gdbarch;
3893 struct breakpoint_objfile_data *bp_objfile_data;
3894
3895 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3896
3897 /* We prefer the SystemTap probe point if it exists. */
3898 if (!bp_objfile_data->exception_searched)
3899 {
3900 std::vector<probe *> ret
3901 = find_probes_in_objfile (objfile, "libgcc", "unwind");
3902
3903 if (!ret.empty ())
3904 {
3905 /* We are only interested in checking one element. */
3906 probe *p = ret[0];
3907
3908 if (!p->can_evaluate_arguments ())
3909 {
3910 /* We cannot use the probe interface here, because it does
3911 not know how to evaluate arguments. */
3912 ret.clear ();
3913 }
3914 }
3915 bp_objfile_data->exception_probes = ret;
3916 bp_objfile_data->exception_searched = 1;
3917 }
3918
3919 if (bp_objfile_data->exception_probes.empty ())
3920 return false;
3921
3922 gdbarch = objfile->arch ();
3923
3924 for (probe *p : bp_objfile_data->exception_probes)
3925 {
3926 b = create_internal_breakpoint (gdbarch,
3927 p->get_relocated_address (objfile),
3928 bp_exception_master);
3929 b->locspec = new_probe_location_spec ("-probe-stap libgcc:unwind");
3930 b->enable_state = bp_disabled;
3931 }
3932
3933 return true;
3934 }
3935
3936 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3937 _Unwind_DebugHook. Return true if a breakpoint was installed. */
3938
3939 static bool
3940 create_exception_master_breakpoint_hook (objfile *objfile)
3941 {
3942 const char *const func_name = "_Unwind_DebugHook";
3943 struct breakpoint *b;
3944 struct gdbarch *gdbarch;
3945 struct breakpoint_objfile_data *bp_objfile_data;
3946
3947 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3948
3949 if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3950 return false;
3951
3952 gdbarch = objfile->arch ();
3953
3954 if (bp_objfile_data->exception_msym.minsym == NULL)
3955 {
3956 bound_minimal_symbol debug_hook
3957 = lookup_minimal_symbol_text (objfile->pspace (), func_name, objfile);
3958 if (debug_hook.minsym == NULL)
3959 {
3960 bp_objfile_data->exception_msym.minsym = &msym_not_found;
3961 return false;
3962 }
3963
3964 bp_objfile_data->exception_msym = debug_hook;
3965 }
3966
3967 b = create_internal_breakpoint (gdbarch, bp_objfile_data->exception_msym,
3968 bp_exception_master);
3969 b->locspec = new_explicit_location_spec_function (func_name);
3970 b->enable_state = bp_disabled;
3971
3972 return true;
3973 }
3974
3975 /* Install a master breakpoint on the unwinder's debug hook. */
3976
3977 static void
3978 create_exception_master_breakpoint (void)
3979 {
3980 for (objfile *obj : current_program_space->objfiles ())
3981 {
3982 /* Skip separate debug object. */
3983 if (obj->separate_debug_objfile_backlink)
3984 continue;
3985
3986 /* Try a probe kind breakpoint. */
3987 if (create_exception_master_breakpoint_probe (obj))
3988 continue;
3989
3990 /* Iterate over main and separate debug objects and try an
3991 _Unwind_DebugHook kind breakpoint. */
3992 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3993 if (create_exception_master_breakpoint_hook (debug_objfile))
3994 break;
3995 }
3996 }
3997
3998 /* Does B have a location spec? */
3999
4000 static bool
4001 breakpoint_location_spec_empty_p (const struct breakpoint *b)
4002 {
4003 return (b->locspec != nullptr && b->locspec->empty_p ());
4004 }
4005
4006 void
4007 update_breakpoints_after_exec (void)
4008 {
4009 /* We're about to delete breakpoints from GDB's lists. If the
4010 INSERTED flag is true, GDB will try to lift the breakpoints by
4011 writing the breakpoints' "shadow contents" back into memory. The
4012 "shadow contents" are NOT valid after an exec, so GDB should not
4013 do that. Instead, the target is responsible from marking
4014 breakpoints out as soon as it detects an exec. We don't do that
4015 here instead, because there may be other attempts to delete
4016 breakpoints after detecting an exec and before reaching here. */
4017 for (bp_location *bploc : all_bp_locations ())
4018 if (bploc->pspace == current_program_space)
4019 gdb_assert (!bploc->inserted);
4020
4021 for (breakpoint &b : all_breakpoints_safe ())
4022 {
4023 if (b.pspace != current_program_space)
4024 continue;
4025
4026 /* Solib breakpoints must be explicitly reset after an exec(). */
4027 if (b.type == bp_shlib_event)
4028 {
4029 delete_breakpoint (&b);
4030 continue;
4031 }
4032
4033 /* JIT breakpoints must be explicitly reset after an exec(). */
4034 if (b.type == bp_jit_event)
4035 {
4036 delete_breakpoint (&b);
4037 continue;
4038 }
4039
4040 /* Thread event breakpoints must be set anew after an exec(),
4041 as must overlay event and longjmp master breakpoints. */
4042 if (b.type == bp_thread_event || b.type == bp_overlay_event
4043 || b.type == bp_longjmp_master || b.type == bp_std_terminate_master
4044 || b.type == bp_exception_master)
4045 {
4046 delete_breakpoint (&b);
4047 continue;
4048 }
4049
4050 /* Step-resume breakpoints are meaningless after an exec(). */
4051 if (b.type == bp_step_resume || b.type == bp_hp_step_resume)
4052 {
4053 delete_breakpoint (&b);
4054 continue;
4055 }
4056
4057 /* Just like single-step breakpoints. */
4058 if (b.type == bp_single_step)
4059 {
4060 delete_breakpoint (&b);
4061 continue;
4062 }
4063
4064 /* Longjmp and longjmp-resume breakpoints are also meaningless
4065 after an exec. */
4066 if (b.type == bp_longjmp || b.type == bp_longjmp_resume
4067 || b.type == bp_longjmp_call_dummy
4068 || b.type == bp_exception || b.type == bp_exception_resume)
4069 {
4070 delete_breakpoint (&b);
4071 continue;
4072 }
4073
4074 if (b.type == bp_catchpoint)
4075 {
4076 /* For now, none of the bp_catchpoint breakpoints need to
4077 do anything at this point. In the future, if some of
4078 the catchpoints need to something, we will need to add
4079 a new method, and call this method from here. */
4080 continue;
4081 }
4082
4083 /* bp_finish is a special case. The only way we ought to be able
4084 to see one of these when an exec() has happened, is if the user
4085 caught a vfork, and then said "finish". Ordinarily a finish just
4086 carries them to the call-site of the current callee, by setting
4087 a temporary bp there and resuming. But in this case, the finish
4088 will carry them entirely through the vfork & exec.
4089
4090 We don't want to allow a bp_finish to remain inserted now. But
4091 we can't safely delete it, 'cause finish_command has a handle to
4092 the bp on a bpstat, and will later want to delete it. There's a
4093 chance (and I've seen it happen) that if we delete the bp_finish
4094 here, that its storage will get reused by the time finish_command
4095 gets 'round to deleting the "use to be a bp_finish" breakpoint.
4096 We really must allow finish_command to delete a bp_finish.
4097
4098 In the absence of a general solution for the "how do we know
4099 it's safe to delete something others may have handles to?"
4100 problem, what we'll do here is just uninsert the bp_finish, and
4101 let finish_command delete it.
4102
4103 (We know the bp_finish is "doomed" in the sense that it's
4104 momentary, and will be deleted as soon as finish_command sees
4105 the inferior stopped. So it doesn't matter that the bp's
4106 address is probably bogus in the new a.out, unlike e.g., the
4107 solib breakpoints.) */
4108
4109 if (b.type == bp_finish)
4110 {
4111 continue;
4112 }
4113
4114 /* Without a symbolic address, we have little hope of the
4115 pre-exec() address meaning the same thing in the post-exec()
4116 a.out. */
4117 if (breakpoint_location_spec_empty_p (&b))
4118 {
4119 delete_breakpoint (&b);
4120 continue;
4121 }
4122 }
4123 }
4124
4125 int
4126 detach_breakpoints (ptid_t ptid)
4127 {
4128 int val = 0;
4129 scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
4130 struct inferior *inf = current_inferior ();
4131
4132 if (ptid.pid () == inferior_ptid.pid ())
4133 error (_("Cannot detach breakpoints of inferior_ptid"));
4134
4135 /* Set inferior_ptid; remove_breakpoint_1 uses this global. */
4136 inferior_ptid = ptid;
4137 for (bp_location *bl : all_bp_locations ())
4138 {
4139 if (bl->pspace != inf->pspace)
4140 continue;
4141
4142 /* This function must physically remove breakpoints locations
4143 from the specified ptid, without modifying the breakpoint
4144 package's state. Locations of type bp_loc_other and
4145 bp_loc_software_watchpoint are only maintained at GDB side,
4146 so there is no need to remove them. Moreover, removing these
4147 would modify the breakpoint package's state. */
4148 if (bl->loc_type == bp_loc_other
4149 || bl->loc_type == bp_loc_software_watchpoint)
4150 continue;
4151
4152 if (bl->inserted)
4153 val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
4154 }
4155
4156 return val;
4157 }
4158
4159 /* Remove the breakpoint location BL from the current address space.
4160 Note that this is used to detach breakpoints from a child fork.
4161 When we get here, the child isn't in the inferior list, and neither
4162 do we have objects to represent its address space --- we should
4163 *not* look at bl->pspace->aspace here. */
4164
4165 static int
4166 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
4167 {
4168 breakpoint_debug_printf ("%s due to %s",
4169 breakpoint_location_address_str (bl).c_str (),
4170 remove_bp_reason_str (reason));
4171
4172 int val;
4173
4174 /* BL is never in moribund_locations by our callers. */
4175 gdb_assert (bl->owner != NULL);
4176
4177 /* The type of none suggests that owner is actually deleted.
4178 This should not ever happen. */
4179 gdb_assert (bl->owner->type != bp_none);
4180
4181 if (bl->loc_type == bp_loc_software_breakpoint
4182 || bl->loc_type == bp_loc_hardware_breakpoint)
4183 {
4184 /* "Normal" instruction breakpoint: either the standard
4185 trap-instruction bp (bp_breakpoint), or a
4186 bp_hardware_breakpoint. */
4187
4188 /* First check to see if we have to handle an overlay. */
4189 if (overlay_debugging == ovly_off
4190 || bl->section == NULL
4191 || !(section_is_overlay (bl->section)))
4192 {
4193 /* No overlay handling: just remove the breakpoint. */
4194
4195 /* If we're trying to uninsert a memory breakpoint that we
4196 know is set in a dynamic object that is marked
4197 shlib_disabled, then either the dynamic object was
4198 removed with "remove-symbol-file" or with
4199 "nosharedlibrary". In the former case, we don't know
4200 whether another dynamic object might have loaded over the
4201 breakpoint's address -- the user might well let us know
4202 about it next with add-symbol-file (the whole point of
4203 add-symbol-file is letting the user manually maintain a
4204 list of dynamically loaded objects). If we have the
4205 breakpoint's shadow memory, that is, this is a software
4206 breakpoint managed by GDB, check whether the breakpoint
4207 is still inserted in memory, to avoid overwriting wrong
4208 code with stale saved shadow contents. Note that HW
4209 breakpoints don't have shadow memory, as they're
4210 implemented using a mechanism that is not dependent on
4211 being able to modify the target's memory, and as such
4212 they should always be removed. */
4213 if (bl->shlib_disabled
4214 && bl->target_info.shadow_len != 0
4215 && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
4216 val = 0;
4217 else
4218 val = bl->owner->remove_location (bl, reason);
4219 }
4220 else
4221 {
4222 /* This breakpoint is in an overlay section.
4223 Did we set a breakpoint at the LMA? */
4224 if (!overlay_events_enabled)
4225 {
4226 /* Yes -- overlay event support is not active, so we
4227 should have set a breakpoint at the LMA. Remove it.
4228 */
4229 /* Ignore any failures: if the LMA is in ROM, we will
4230 have already warned when we failed to insert it. */
4231 if (bl->loc_type == bp_loc_hardware_breakpoint)
4232 target_remove_hw_breakpoint (bl->gdbarch,
4233 &bl->overlay_target_info);
4234 else
4235 target_remove_breakpoint (bl->gdbarch,
4236 &bl->overlay_target_info,
4237 reason);
4238 }
4239 /* Did we set a breakpoint at the VMA?
4240 If so, we will have marked the breakpoint 'inserted'. */
4241 if (bl->inserted)
4242 {
4243 /* Yes -- remove it. Previously we did not bother to
4244 remove the breakpoint if the section had been
4245 unmapped, but let's not rely on that being safe. We
4246 don't know what the overlay manager might do. */
4247
4248 /* However, we should remove *software* breakpoints only
4249 if the section is still mapped, or else we overwrite
4250 wrong code with the saved shadow contents. */
4251 if (bl->loc_type == bp_loc_hardware_breakpoint
4252 || section_is_mapped (bl->section))
4253 val = bl->owner->remove_location (bl, reason);
4254 else
4255 val = 0;
4256 }
4257 else
4258 {
4259 /* No -- not inserted, so no need to remove. No error. */
4260 val = 0;
4261 }
4262 }
4263
4264 /* In some cases, we might not be able to remove a breakpoint in
4265 a shared library that has already been removed, but we have
4266 not yet processed the shlib unload event. Similarly for an
4267 unloaded add-symbol-file object - the user might not yet have
4268 had the chance to remove-symbol-file it. shlib_disabled will
4269 be set if the library/object has already been removed, but
4270 the breakpoint hasn't been uninserted yet, e.g., after
4271 "nosharedlibrary" or "remove-symbol-file" with breakpoints
4272 always-inserted mode. */
4273 if (val
4274 && (bl->loc_type == bp_loc_software_breakpoint
4275 && (bl->shlib_disabled
4276 || solib_name_from_address (bl->pspace, bl->address)
4277 || shared_objfile_contains_address_p (bl->pspace,
4278 bl->address))))
4279 val = 0;
4280
4281 if (val)
4282 return val;
4283 bl->inserted = (reason == DETACH_BREAKPOINT);
4284 }
4285 else if (bl->loc_type == bp_loc_hardware_watchpoint)
4286 {
4287 bl->inserted = (reason == DETACH_BREAKPOINT);
4288 bl->owner->remove_location (bl, reason);
4289
4290 /* Failure to remove any of the hardware watchpoints comes here. */
4291 if (reason == REMOVE_BREAKPOINT && bl->inserted)
4292 warning (_("Could not remove hardware watchpoint %d."),
4293 bl->owner->number);
4294 }
4295 else if (bl->owner->type == bp_catchpoint
4296 && breakpoint_enabled (bl->owner)
4297 && !bl->duplicate)
4298 {
4299 val = bl->owner->remove_location (bl, reason);
4300 if (val)
4301 return val;
4302
4303 bl->inserted = (reason == DETACH_BREAKPOINT);
4304 }
4305
4306 return 0;
4307 }
4308
4309 static int
4310 remove_breakpoint (struct bp_location *bl)
4311 {
4312 /* BL is never in moribund_locations by our callers. */
4313 gdb_assert (bl->owner != NULL);
4314
4315 /* The type of none suggests that owner is actually deleted.
4316 This should not ever happen. */
4317 gdb_assert (bl->owner->type != bp_none);
4318
4319 scoped_restore_current_pspace_and_thread restore_pspace_thread;
4320
4321 switch_to_program_space_and_thread (bl->pspace);
4322
4323 return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4324 }
4325
4326 /* See breakpoint.h. */
4327
4328 void
4329 mark_breakpoints_out (program_space *pspace)
4330 {
4331 for (bp_location *bl : all_bp_locations ())
4332 if (bl->pspace == pspace)
4333 bl->inserted = 0;
4334 }
4335
4336 /* See breakpoint.h. */
4337
4338 void
4339 breakpoint_init_inferior (inferior *inf, inf_context context)
4340 {
4341 /* If breakpoint locations are shared across processes, then there's
4342 nothing to do. */
4343 if (gdbarch_has_global_breakpoints (inf->arch ()))
4344 return;
4345
4346 mark_breakpoints_out (inf->pspace);
4347
4348 for (breakpoint &b : all_breakpoints_safe ())
4349 {
4350 if (b.has_locations () && b.first_loc ().pspace != inf->pspace)
4351 continue;
4352
4353 switch (b.type)
4354 {
4355 case bp_call_dummy:
4356 case bp_longjmp_call_dummy:
4357
4358 /* If the call dummy breakpoint is at the entry point it will
4359 cause problems when the inferior is rerun, so we better get
4360 rid of it. */
4361
4362 case bp_watchpoint_scope:
4363
4364 /* Also get rid of scope breakpoints. */
4365
4366 case bp_shlib_event:
4367
4368 /* Also remove solib event breakpoints. Their addresses may
4369 have changed since the last time we ran the program.
4370 Actually we may now be debugging against different target;
4371 and so the solib backend that installed this breakpoint may
4372 not be used in by the target. E.g.,
4373
4374 (gdb) file prog-linux
4375 (gdb) run # native linux target
4376 ...
4377 (gdb) kill
4378 (gdb) file prog-win.exe
4379 (gdb) tar rem :9999 # remote Windows gdbserver.
4380 */
4381
4382 case bp_step_resume:
4383
4384 /* Also remove step-resume breakpoints. */
4385
4386 case bp_single_step:
4387
4388 /* Also remove single-step breakpoints. */
4389
4390 delete_breakpoint (&b);
4391 break;
4392
4393 case bp_watchpoint:
4394 case bp_hardware_watchpoint:
4395 case bp_read_watchpoint:
4396 case bp_access_watchpoint:
4397 {
4398 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
4399
4400 /* Likewise for watchpoints on local expressions. */
4401 if (w.exp_valid_block != NULL)
4402 delete_breakpoint (&b);
4403 else
4404 {
4405 /* Get rid of existing locations, which are no longer
4406 valid. New ones will be created in
4407 update_watchpoint, when the inferior is restarted.
4408 The next update_global_location_list call will
4409 garbage collect them. */
4410 b.clear_locations ();
4411
4412 if (context == inf_starting)
4413 {
4414 /* Reset val field to force reread of starting value in
4415 insert_breakpoints. */
4416 w.val.reset (nullptr);
4417 w.val_valid = false;
4418 }
4419 }
4420 }
4421 break;
4422 default:
4423 break;
4424 }
4425 }
4426
4427 /* Get rid of the moribund locations. */
4428 for (bp_location *bl : moribund_locations)
4429 decref_bp_location (&bl);
4430 moribund_locations.clear ();
4431 }
4432
4433 /* These functions concern about actual breakpoints inserted in the
4434 target --- to e.g. check if we need to do decr_pc adjustment or if
4435 we need to hop over the bkpt --- so we check for address space
4436 match, not program space. */
4437
4438 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4439 exists at PC. It returns ordinary_breakpoint_here if it's an
4440 ordinary breakpoint, or permanent_breakpoint_here if it's a
4441 permanent breakpoint.
4442 - When continuing from a location with an ordinary breakpoint, we
4443 actually single step once before calling insert_breakpoints.
4444 - When continuing from a location with a permanent breakpoint, we
4445 need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4446 the target, to advance the PC past the breakpoint. */
4447
4448 enum breakpoint_here
4449 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4450 {
4451 bool any_breakpoint_here = false;
4452
4453 for (bp_location *bl : all_bp_locations ())
4454 {
4455 if (bl->loc_type != bp_loc_software_breakpoint
4456 && bl->loc_type != bp_loc_hardware_breakpoint)
4457 continue;
4458
4459 /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL. */
4460 if ((breakpoint_enabled (bl->owner)
4461 || bl->permanent)
4462 && breakpoint_location_address_match (bl, aspace, pc))
4463 {
4464 if (overlay_debugging
4465 && section_is_overlay (bl->section)
4466 && !section_is_mapped (bl->section))
4467 continue; /* unmapped overlay -- can't be a match */
4468 else if (bl->permanent)
4469 return permanent_breakpoint_here;
4470 else
4471 any_breakpoint_here = true;
4472 }
4473 }
4474
4475 return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4476 }
4477
4478 /* See breakpoint.h. */
4479
4480 int
4481 breakpoint_in_range_p (const address_space *aspace,
4482 CORE_ADDR addr, ULONGEST len)
4483 {
4484 for (bp_location *bl : all_bp_locations ())
4485 {
4486 if (bl->loc_type != bp_loc_software_breakpoint
4487 && bl->loc_type != bp_loc_hardware_breakpoint)
4488 continue;
4489
4490 if ((breakpoint_enabled (bl->owner)
4491 || bl->permanent)
4492 && breakpoint_location_address_range_overlap (bl, aspace,
4493 addr, len))
4494 {
4495 if (overlay_debugging
4496 && section_is_overlay (bl->section)
4497 && !section_is_mapped (bl->section))
4498 {
4499 /* Unmapped overlay -- can't be a match. */
4500 continue;
4501 }
4502
4503 return 1;
4504 }
4505 }
4506
4507 return 0;
4508 }
4509
4510 /* Return true if there's a moribund breakpoint at PC. */
4511
4512 int
4513 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4514 {
4515 for (bp_location *loc : moribund_locations)
4516 if (breakpoint_location_address_match (loc, aspace, pc))
4517 return 1;
4518
4519 return 0;
4520 }
4521
4522 /* Returns true iff BL is inserted at PC, in address space ASPACE. */
4523
4524 static bool
4525 bp_location_inserted_here_p (const struct bp_location *bl,
4526 const address_space *aspace, CORE_ADDR pc)
4527 {
4528 if (bl->inserted
4529 && breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
4530 aspace, pc))
4531 {
4532 /* An unmapped overlay can't be a match. */
4533 return !(overlay_debugging
4534 && section_is_overlay (bl->section)
4535 && !section_is_mapped (bl->section));
4536 }
4537 return false;
4538 }
4539
4540 /* Returns non-zero iff there's a breakpoint inserted at PC. */
4541
4542 int
4543 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4544 {
4545 for (bp_location *bl : all_bp_locations_at_addr (pc))
4546 {
4547 if (bl->loc_type != bp_loc_software_breakpoint
4548 && bl->loc_type != bp_loc_hardware_breakpoint)
4549 continue;
4550
4551 if (bp_location_inserted_here_p (bl, aspace, pc))
4552 return 1;
4553 }
4554 return 0;
4555 }
4556
4557 /* This function returns non-zero iff there is a software breakpoint
4558 inserted at PC. */
4559
4560 int
4561 software_breakpoint_inserted_here_p (const address_space *aspace,
4562 CORE_ADDR pc)
4563 {
4564 for (bp_location *bl : all_bp_locations_at_addr (pc))
4565 {
4566 if (bl->loc_type != bp_loc_software_breakpoint)
4567 continue;
4568
4569 if (bp_location_inserted_here_p (bl, aspace, pc))
4570 return 1;
4571 }
4572
4573 return 0;
4574 }
4575
4576 /* See breakpoint.h. */
4577
4578 int
4579 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4580 CORE_ADDR pc)
4581 {
4582 for (bp_location *bl : all_bp_locations_at_addr (pc))
4583 {
4584 if (bl->loc_type != bp_loc_hardware_breakpoint)
4585 continue;
4586
4587 if (bp_location_inserted_here_p (bl, aspace, pc))
4588 return 1;
4589 }
4590
4591 return 0;
4592 }
4593
4594 int
4595 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4596 CORE_ADDR addr, ULONGEST len)
4597 {
4598 for (breakpoint &bpt : all_breakpoints ())
4599 {
4600 if (bpt.type != bp_hardware_watchpoint
4601 && bpt.type != bp_access_watchpoint)
4602 continue;
4603
4604 if (!breakpoint_enabled (&bpt))
4605 continue;
4606
4607 for (bp_location &loc : bpt.locations ())
4608 if (loc.pspace->aspace.get () == aspace && loc.inserted)
4609 {
4610 CORE_ADDR l, h;
4611
4612 /* Check for intersection. */
4613 l = std::max<CORE_ADDR> (loc.address, addr);
4614 h = std::min<CORE_ADDR> (loc.address + loc.length, addr + len);
4615 if (l < h)
4616 return 1;
4617 }
4618 }
4619 return 0;
4620 }
4621
4622 /* See breakpoint.h. */
4623
4624 bool
4625 is_catchpoint (struct breakpoint *b)
4626 {
4627 return (b->type == bp_catchpoint);
4628 }
4629
4630 /* Clear a bpstat so that it says we are not at any breakpoint.
4631 Also free any storage that is part of a bpstat. */
4632
4633 void
4634 bpstat_clear (bpstat **bsp)
4635 {
4636 bpstat *p;
4637 bpstat *q;
4638
4639 if (bsp == 0)
4640 return;
4641 p = *bsp;
4642 while (p != NULL)
4643 {
4644 q = p->next;
4645 delete p;
4646 p = q;
4647 }
4648 *bsp = NULL;
4649 }
4650
4651 bpstat::bpstat (const bpstat &other)
4652 : next (NULL),
4653 bp_location_at (other.bp_location_at),
4654 breakpoint_at (other.breakpoint_at),
4655 commands (other.commands),
4656 print (other.print),
4657 stop (other.stop),
4658 print_it (other.print_it)
4659 {
4660 if (other.old_val != NULL)
4661 old_val = release_value (other.old_val->copy ());
4662 }
4663
4664 /* Return a copy of a bpstat. Like "bs1 = bs2" but all storage that
4665 is part of the bpstat is copied as well. */
4666
4667 bpstat *
4668 bpstat_copy (bpstat *bs)
4669 {
4670 bpstat *p = nullptr;
4671 bpstat *tmp;
4672 bpstat *retval = nullptr;
4673
4674 if (bs == NULL)
4675 return bs;
4676
4677 for (; bs != NULL; bs = bs->next)
4678 {
4679 tmp = new bpstat (*bs);
4680
4681 if (p == NULL)
4682 /* This is the first thing in the chain. */
4683 retval = tmp;
4684 else
4685 p->next = tmp;
4686 p = tmp;
4687 }
4688 p->next = NULL;
4689 return retval;
4690 }
4691
4692 /* Find the bpstat associated with this breakpoint. */
4693
4694 bpstat *
4695 bpstat_find_breakpoint (bpstat *bsp, struct breakpoint *breakpoint)
4696 {
4697 if (bsp == NULL)
4698 return NULL;
4699
4700 for (; bsp != NULL; bsp = bsp->next)
4701 {
4702 if (bsp->breakpoint_at == breakpoint)
4703 return bsp;
4704 }
4705 return NULL;
4706 }
4707
4708 /* See breakpoint.h. */
4709
4710 bool
4711 bpstat_explains_signal (bpstat *bsp, enum gdb_signal sig)
4712 {
4713 for (; bsp != NULL; bsp = bsp->next)
4714 {
4715 if (bsp->breakpoint_at == NULL)
4716 {
4717 /* A moribund location can never explain a signal other than
4718 GDB_SIGNAL_TRAP. */
4719 if (sig == GDB_SIGNAL_TRAP)
4720 return true;
4721 }
4722 else
4723 {
4724 if (bsp->breakpoint_at->explains_signal (sig))
4725 return true;
4726 }
4727 }
4728
4729 return false;
4730 }
4731
4732 /* See breakpoint.h. */
4733
4734 int
4735 bpstat_num (bpstat **bsp, int *num)
4736 {
4737 struct breakpoint *b;
4738
4739 if ((*bsp) == NULL)
4740 return 0; /* No more breakpoint values */
4741
4742 /* We assume we'll never have several bpstats that correspond to a
4743 single breakpoint -- otherwise, this function might return the
4744 same number more than once and this will look ugly. */
4745 b = (*bsp)->breakpoint_at;
4746 *bsp = (*bsp)->next;
4747 if (b == NULL)
4748 return -1; /* breakpoint that's been deleted since */
4749
4750 *num = b->number; /* We have its number */
4751 return 1;
4752 }
4753
4754 /* See breakpoint.h */
4755
4756 int
4757 bpstat_locno (const bpstat *bs)
4758 {
4759 const struct breakpoint *b = bs->breakpoint_at;
4760 const struct bp_location *bl = bs->bp_location_at.get ();
4761
4762 if (b != nullptr && b->has_multiple_locations ())
4763 {
4764 int locno = 1;
4765
4766 for (bp_location &loc : b->locations ())
4767 {
4768 if (bl == &loc)
4769 return locno;
4770
4771 ++locno;
4772 }
4773
4774 warning (_("location number not found for breakpoint %d address %s."),
4775 b->number, paddress (bl->gdbarch, bl->address));
4776 }
4777
4778 return 0;
4779 }
4780
4781 /* See breakpoint.h. */
4782
4783 void
4784 print_num_locno (const bpstat *bs, struct ui_out *uiout)
4785 {
4786 struct breakpoint *b = bs->breakpoint_at;
4787
4788 if (b == nullptr)
4789 uiout->text (_("deleted breakpoint"));
4790 else
4791 {
4792 uiout->field_signed ("bkptno", b->number);
4793
4794 int locno = bpstat_locno (bs);
4795 if (locno != 0)
4796 uiout->message (".%pF", signed_field ("locno", locno));
4797 }
4798 }
4799
4800 /* See breakpoint.h. */
4801
4802 void
4803 bpstat_clear_actions (void)
4804 {
4805 bpstat *bs;
4806
4807 if (inferior_ptid == null_ptid)
4808 return;
4809
4810 thread_info *tp = inferior_thread ();
4811 for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4812 {
4813 bs->commands = NULL;
4814 bs->old_val.reset (nullptr);
4815 }
4816 }
4817
4818 /* Called when a command is about to proceed the inferior. */
4819
4820 static void
4821 breakpoint_about_to_proceed (void)
4822 {
4823 if (inferior_ptid != null_ptid)
4824 {
4825 struct thread_info *tp = inferior_thread ();
4826
4827 /* Allow inferior function calls in breakpoint commands to not
4828 interrupt the command list. When the call finishes
4829 successfully, the inferior will be standing at the same
4830 breakpoint as if nothing happened. */
4831 if (tp->control.in_infcall)
4832 return;
4833 }
4834
4835 breakpoint_proceeded = 1;
4836 }
4837
4838 /* Return true iff CMD as the first line of a command sequence is `silent'
4839 or its equivalent. */
4840
4841 static bool
4842 command_line_is_silent (struct command_line *cmd)
4843 {
4844 return cmd && (strcmp ("silent", cmd->line) == 0);
4845 }
4846
4847 /* Sets the $_hit_bpnum and $_hit_locno to bpnum and locno.
4848 A locno 0 is changed to 1 to e.g. let the user do
4849 (gdb) disable $_hit_bpnum.$_hit_locno
4850 for a single location breakpoint. */
4851
4852 static void
4853 set_hit_convenience_vars (int bpnum, int locno)
4854 {
4855 set_internalvar_integer (lookup_internalvar ("_hit_bpnum"), bpnum);
4856 set_internalvar_integer (lookup_internalvar ("_hit_locno"),
4857 (locno > 0 ? locno : 1));
4858 }
4859
4860 /* Execute all the commands associated with all the breakpoints at
4861 this location. Any of these commands could cause the process to
4862 proceed beyond this point, etc. We look out for such changes by
4863 checking the global "breakpoint_proceeded" after each command.
4864
4865 Returns true if a breakpoint command resumed the inferior. In that
4866 case, it is the caller's responsibility to recall it again with the
4867 bpstat of the current thread. */
4868
4869 static bool
4870 bpstat_do_actions_1 (bpstat **bsp)
4871 {
4872 bpstat *bs;
4873 bool again = false;
4874
4875 /* Avoid endless recursion if a `source' command is contained
4876 in bs->commands. */
4877 if (executing_breakpoint_commands)
4878 return false;
4879
4880 scoped_restore save_executing
4881 = make_scoped_restore (&executing_breakpoint_commands, 1);
4882
4883 scoped_restore preventer = prevent_dont_repeat ();
4884
4885 /* This pointer will iterate over the list of bpstat's. */
4886 bs = *bsp;
4887
4888 /* The $_hit_* convenience variables are set before running the
4889 commands of BS. In case we have several bs, after the loop,
4890 we set again the variables to the first printed bpnum and locno.
4891 For multiple breakpoints, this ensures the variables are set to the
4892 breakpoint printed for the user. */
4893 int printed_hit_bpnum = -1;
4894 int printed_hit_locno = -1;
4895
4896 breakpoint_proceeded = 0;
4897 for (; bs != NULL; bs = bs->next)
4898 {
4899 struct command_line *cmd = NULL;
4900
4901 /* Set the _hit_* convenience variables before running BS's commands. */
4902 {
4903 const struct breakpoint *b = bs->breakpoint_at;
4904 if (b != nullptr)
4905 {
4906 int locno = bpstat_locno (bs);
4907
4908 set_hit_convenience_vars (b->number, locno);
4909 if (printed_hit_locno == -1 && bs->print)
4910 {
4911 printed_hit_bpnum = b->number;
4912 printed_hit_locno = locno;
4913 }
4914 }
4915 }
4916
4917 /* Take ownership of the BSP's command tree, if it has one.
4918
4919 The command tree could legitimately contain commands like
4920 'step' and 'next', which call clear_proceed_status, which
4921 frees the bpstat BS and its command tree. To make sure this doesn't
4922 free the tree we're executing out from under us, we need to
4923 take ownership of the tree ourselves. Since a given bpstat's
4924 commands are only executed once, we don't need to copy it; we
4925 can clear the pointer in the bpstat, and make sure we free
4926 the tree when we're done. */
4927 counted_command_line ccmd = bs->commands;
4928 bs->commands = NULL;
4929 if (ccmd != NULL)
4930 cmd = ccmd.get ();
4931 if (command_line_is_silent (cmd))
4932 {
4933 /* The action has been already done by bpstat_stop_status. */
4934 cmd = cmd->next;
4935 }
4936
4937 while (cmd != NULL)
4938 {
4939 execute_control_command (cmd);
4940 /* After execute_control_command, if breakpoint_proceeded is true,
4941 BS has been freed and cannot be accessed anymore. */
4942
4943 if (breakpoint_proceeded)
4944 break;
4945 else
4946 cmd = cmd->next;
4947 }
4948
4949 if (breakpoint_proceeded)
4950 {
4951 if (current_ui->async)
4952 /* If we are in async mode, then the target might be still
4953 running, not stopped at any breakpoint, so nothing for
4954 us to do here -- just return to the event loop. */
4955 ;
4956 else
4957 /* In sync mode, when execute_control_command returns
4958 we're already standing on the next breakpoint.
4959 Breakpoint commands for that stop were not run, since
4960 execute_command does not run breakpoint commands --
4961 only command_line_handler does, but that one is not
4962 involved in execution of breakpoint commands. So, we
4963 can now execute breakpoint commands. It should be
4964 noted that making execute_command do bpstat actions is
4965 not an option -- in this case we'll have recursive
4966 invocation of bpstat for each breakpoint with a
4967 command, and can easily blow up GDB stack. Instead, we
4968 return true, which will trigger the caller to recall us
4969 with the new stop_bpstat. */
4970 again = true;
4971 break;
4972 }
4973 }
4974
4975 /* Now that we have executed the commands of all bs, set the _hit_*
4976 convenience variables to the printed values. */
4977 if (printed_hit_locno != -1)
4978 set_hit_convenience_vars (printed_hit_bpnum, printed_hit_locno);
4979
4980 return again;
4981 }
4982
4983 /* Helper for bpstat_do_actions. Get the current thread, if there's
4984 one, is alive and has execution. Return NULL otherwise. */
4985
4986 static thread_info *
4987 get_bpstat_thread ()
4988 {
4989 if (inferior_ptid == null_ptid || !target_has_execution ())
4990 return NULL;
4991
4992 thread_info *tp = inferior_thread ();
4993 if (tp->state == THREAD_EXITED || tp->executing ())
4994 return NULL;
4995 return tp;
4996 }
4997
4998 void
4999 bpstat_do_actions (void)
5000 {
5001 auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
5002 thread_info *tp;
5003
5004 /* Do any commands attached to breakpoint we are stopped at. */
5005 while ((tp = get_bpstat_thread ()) != NULL)
5006 {
5007 /* Since in sync mode, bpstat_do_actions may resume the
5008 inferior, and only return when it is stopped at the next
5009 breakpoint, we keep doing breakpoint actions until it returns
5010 false to indicate the inferior was not resumed. */
5011 if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
5012 break;
5013 }
5014
5015 cleanup_if_error.release ();
5016 }
5017
5018 /* Print out the (old or new) value associated with a watchpoint. */
5019
5020 static void
5021 watchpoint_value_print (struct value *val, struct ui_file *stream)
5022 {
5023 if (val == NULL)
5024 fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
5025 else
5026 {
5027 struct value_print_options opts;
5028 get_user_print_options (&opts);
5029 value_print (val, stream, &opts);
5030 }
5031 }
5032
5033 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
5034 debugging multiple threads. */
5035
5036 void
5037 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
5038 {
5039 if (uiout->is_mi_like_p ())
5040 return;
5041
5042 uiout->text ("\n");
5043
5044 if (show_thread_that_caused_stop ())
5045 {
5046 struct thread_info *thr = inferior_thread ();
5047
5048 uiout->text ("Thread ");
5049 uiout->field_string ("thread-id", print_thread_id (thr));
5050
5051 const char *name = thread_name (thr);
5052 if (name != NULL)
5053 {
5054 uiout->text (" \"");
5055 uiout->field_string ("name", name);
5056 uiout->text ("\"");
5057 }
5058
5059 uiout->text (" hit ");
5060 }
5061 }
5062
5063 /* Generic routine for printing messages indicating why we
5064 stopped. The behavior of this function depends on the value
5065 'print_it' in the bpstat structure. Under some circumstances we
5066 may decide not to print anything here and delegate the task to
5067 normal_stop(). */
5068
5069 static enum print_stop_action
5070 print_bp_stop_message (bpstat *bs)
5071 {
5072 switch (bs->print_it)
5073 {
5074 case print_it_noop:
5075 /* Nothing should be printed for this bpstat entry. */
5076 return PRINT_UNKNOWN;
5077
5078 case print_it_done:
5079 /* We still want to print the frame, but we already printed the
5080 relevant messages. */
5081 return PRINT_SRC_AND_LOC;
5082
5083 case print_it_normal:
5084 {
5085 struct breakpoint *b = bs->breakpoint_at;
5086
5087 /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
5088 which has since been deleted. */
5089 if (b == NULL)
5090 return PRINT_UNKNOWN;
5091
5092 /* Normal case. Call the breakpoint's print_it method. */
5093 return b->print_it (bs);
5094 }
5095
5096 default:
5097 internal_error (_("print_bp_stop_message: unrecognized enum value"));
5098 }
5099 }
5100
5101 /* See breakpoint.h. */
5102
5103 void
5104 print_solib_event (bool is_catchpoint)
5105 {
5106 bool any_deleted = !current_program_space->deleted_solibs.empty ();
5107 bool any_added = !current_program_space->added_solibs.empty ();
5108
5109 if (!is_catchpoint)
5110 {
5111 if (any_added || any_deleted)
5112 current_uiout->text (_("Stopped due to shared library event:\n"));
5113 else
5114 current_uiout->text (_("Stopped due to shared library event (no "
5115 "libraries added or removed)\n"));
5116 }
5117
5118 if (current_uiout->is_mi_like_p ())
5119 current_uiout->field_string ("reason",
5120 async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
5121
5122 if (any_deleted)
5123 {
5124 current_uiout->text (_(" Inferior unloaded "));
5125 ui_out_emit_list list_emitter (current_uiout, "removed");
5126 for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
5127 {
5128 const std::string &name = current_program_space->deleted_solibs[ix];
5129
5130 if (ix > 0)
5131 current_uiout->text (" ");
5132 current_uiout->field_string ("library", name);
5133 current_uiout->text ("\n");
5134 }
5135 }
5136
5137 if (any_added)
5138 {
5139 current_uiout->text (_(" Inferior loaded "));
5140 ui_out_emit_list list_emitter (current_uiout, "added");
5141 bool first = true;
5142 for (solib *iter : current_program_space->added_solibs)
5143 {
5144 if (!first)
5145 current_uiout->text (" ");
5146 first = false;
5147 current_uiout->field_string ("library", iter->name);
5148 current_uiout->text ("\n");
5149 }
5150 }
5151 }
5152
5153 /* Print a message indicating what happened. This is called from
5154 normal_stop(). The input to this routine is the head of the bpstat
5155 list - a list of the eventpoints that caused this stop. KIND is
5156 the target_waitkind for the stopping event. This
5157 routine calls the generic print routine for printing a message
5158 about reasons for stopping. This will print (for example) the
5159 "Breakpoint n," part of the output. The return value of this
5160 routine is one of:
5161
5162 PRINT_UNKNOWN: Means we printed nothing.
5163 PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
5164 code to print the location. An example is
5165 "Breakpoint 1, " which should be followed by
5166 the location.
5167 PRINT_SRC_ONLY: Means we printed something, but there is no need
5168 to also print the location part of the message.
5169 An example is the catch/throw messages, which
5170 don't require a location appended to the end.
5171 PRINT_NOTHING: We have done some printing and we don't need any
5172 further info to be printed. */
5173
5174 enum print_stop_action
5175 bpstat_print (bpstat *bs, target_waitkind kind)
5176 {
5177 enum print_stop_action val;
5178
5179 /* Maybe another breakpoint in the chain caused us to stop.
5180 (Currently all watchpoints go on the bpstat whether hit or not.
5181 That probably could (should) be changed, provided care is taken
5182 with respect to bpstat_explains_signal). */
5183 for (; bs; bs = bs->next)
5184 {
5185 val = print_bp_stop_message (bs);
5186 if (val == PRINT_SRC_ONLY
5187 || val == PRINT_SRC_AND_LOC
5188 || val == PRINT_NOTHING)
5189 return val;
5190 }
5191
5192 /* If we had hit a shared library event breakpoint,
5193 print_bp_stop_message would print out this message. If we hit an
5194 OS-level shared library event, do the same thing. */
5195 if (kind == TARGET_WAITKIND_LOADED)
5196 {
5197 print_solib_event (false);
5198 return PRINT_NOTHING;
5199 }
5200
5201 /* We reached the end of the chain, or we got a null BS to start
5202 with and nothing was printed. */
5203 return PRINT_UNKNOWN;
5204 }
5205
5206 /* Evaluate the boolean expression EXP and return the result. */
5207
5208 static bool
5209 breakpoint_cond_eval (expression *exp)
5210 {
5211 scoped_value_mark mark;
5212 return value_true (exp->evaluate ());
5213 }
5214
5215 /* Allocate a new bpstat. Link it to the FIFO list by BS_LINK_POINTER. */
5216
5217 bpstat::bpstat (struct bp_location *bl, bpstat ***bs_link_pointer)
5218 : next (NULL),
5219 bp_location_at (bp_location_ref_ptr::new_reference (bl)),
5220 breakpoint_at (bl->owner),
5221 commands (NULL),
5222 print (0),
5223 stop (0),
5224 print_it (print_it_normal)
5225 {
5226 **bs_link_pointer = this;
5227 *bs_link_pointer = &next;
5228 }
5229
5230 bpstat::bpstat ()
5231 : next (NULL),
5232 breakpoint_at (NULL),
5233 commands (NULL),
5234 print (0),
5235 stop (0),
5236 print_it (print_it_normal)
5237 {
5238 }
5239 \f
5240 /* The target has stopped with waitstatus WS. Check if any hardware
5241 watchpoints have triggered, according to the target. */
5242
5243 int
5244 watchpoints_triggered (const target_waitstatus &ws)
5245 {
5246 bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
5247 CORE_ADDR addr;
5248
5249 if (!stopped_by_watchpoint)
5250 {
5251 /* We were not stopped by a watchpoint. Mark all watchpoints
5252 as not triggered. */
5253 for (breakpoint &b : all_breakpoints ())
5254 if (is_hardware_watchpoint (&b))
5255 {
5256 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5257
5258 w.watchpoint_triggered = watch_triggered_no;
5259 }
5260
5261 return 0;
5262 }
5263
5264 if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
5265 {
5266 /* We were stopped by a watchpoint, but we don't know where.
5267 Mark all watchpoints as unknown. */
5268 for (breakpoint &b : all_breakpoints ())
5269 if (is_hardware_watchpoint (&b))
5270 {
5271 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5272
5273 w.watchpoint_triggered = watch_triggered_unknown;
5274 }
5275
5276 return 1;
5277 }
5278
5279 /* The target could report the data address. Mark watchpoints
5280 affected by this data address as triggered, and all others as not
5281 triggered. */
5282
5283 for (breakpoint &b : all_breakpoints ())
5284 if (is_hardware_watchpoint (&b))
5285 {
5286 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5287
5288 w.watchpoint_triggered = watch_triggered_no;
5289 for (bp_location &loc : b.locations ())
5290 {
5291 if (is_masked_watchpoint (&b))
5292 {
5293 CORE_ADDR newaddr = addr & w.hw_wp_mask;
5294 CORE_ADDR start = loc.address & w.hw_wp_mask;
5295
5296 if (newaddr == start)
5297 {
5298 w.watchpoint_triggered = watch_triggered_yes;
5299 break;
5300 }
5301 }
5302 /* Exact match not required. Within range is sufficient. */
5303 else if (target_watchpoint_addr_within_range
5304 (current_inferior ()->top_target (), addr, loc.address,
5305 loc.length))
5306 {
5307 w.watchpoint_triggered = watch_triggered_yes;
5308 break;
5309 }
5310 }
5311 }
5312
5313 return 1;
5314 }
5315
5316 /* Possible return values for watchpoint_check. */
5317 enum wp_check_result
5318 {
5319 /* The watchpoint has been deleted. */
5320 WP_DELETED = 1,
5321
5322 /* The value has changed. */
5323 WP_VALUE_CHANGED = 2,
5324
5325 /* The value has not changed. */
5326 WP_VALUE_NOT_CHANGED = 3,
5327
5328 /* Ignore this watchpoint, no matter if the value changed or not. */
5329 WP_IGNORE = 4,
5330 };
5331
5332 #define BP_TEMPFLAG 1
5333 #define BP_HARDWAREFLAG 2
5334
5335 /* Evaluate watchpoint condition expression and check if its value
5336 changed. */
5337
5338 static wp_check_result
5339 watchpoint_check (bpstat *bs)
5340 {
5341 frame_info_ptr fr;
5342 bool within_current_scope;
5343
5344 /* BS is built from an existing struct breakpoint. */
5345 gdb_assert (bs->breakpoint_at != NULL);
5346 watchpoint *b = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5347
5348 /* If this is a local watchpoint, we only want to check if the
5349 watchpoint frame is in scope if the current thread is the thread
5350 that was used to create the watchpoint. */
5351 if (!watchpoint_in_thread_scope (b))
5352 return WP_IGNORE;
5353
5354 if (b->exp_valid_block == NULL)
5355 within_current_scope = true;
5356 else
5357 {
5358 frame_info_ptr frame = get_current_frame ();
5359 struct gdbarch *frame_arch = get_frame_arch (frame);
5360 CORE_ADDR frame_pc = get_frame_pc (frame);
5361
5362 /* stack_frame_destroyed_p() returns a non-zero value if we're
5363 still in the function but the stack frame has already been
5364 invalidated. Since we can't rely on the values of local
5365 variables after the stack has been destroyed, we are treating
5366 the watchpoint in that state as `not changed' without further
5367 checking. Don't mark watchpoints as changed if the current
5368 frame is in an epilogue - even if they are in some other
5369 frame, our view of the stack is likely to be wrong and
5370 frame_find_by_id could error out. */
5371 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5372 return WP_IGNORE;
5373
5374 fr = frame_find_by_id (b->watchpoint_frame);
5375 within_current_scope = (fr != NULL);
5376
5377 /* If we've gotten confused in the unwinder, we might have
5378 returned a frame that can't describe this variable. */
5379 if (within_current_scope)
5380 {
5381 struct symbol *function;
5382
5383 function = get_frame_function (fr);
5384 if (function == NULL
5385 || !function->value_block ()->contains (b->exp_valid_block))
5386 within_current_scope = false;
5387 }
5388
5389 if (within_current_scope)
5390 /* If we end up stopping, the current frame will get selected
5391 in normal_stop. So this call to select_frame won't affect
5392 the user. */
5393 select_frame (fr);
5394 }
5395
5396 if (within_current_scope)
5397 {
5398 /* We use value_{,free_to_}mark because it could be a *long*
5399 time before we return to the command level and call
5400 free_all_values. We can't call free_all_values because we
5401 might be in the middle of evaluating a function call. */
5402
5403 struct value *mark;
5404 struct value *new_val;
5405
5406 if (is_masked_watchpoint (b))
5407 /* Since we don't know the exact trigger address (from
5408 stopped_data_address), just tell the user we've triggered
5409 a mask watchpoint. */
5410 return WP_VALUE_CHANGED;
5411
5412 mark = value_mark ();
5413 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
5414 NULL, NULL, false);
5415
5416 if (b->val_bitsize != 0)
5417 new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5418
5419 /* We use value_equal_contents instead of value_equal because
5420 the latter coerces an array to a pointer, thus comparing just
5421 the address of the array instead of its contents. This is
5422 not what we want. */
5423 if ((b->val != NULL) != (new_val != NULL)
5424 || (b->val != NULL && !value_equal_contents (b->val.get (),
5425 new_val)))
5426 {
5427 bs->old_val = b->val;
5428 b->val = release_value (new_val);
5429 b->val_valid = true;
5430 if (new_val != NULL)
5431 value_free_to_mark (mark);
5432 return WP_VALUE_CHANGED;
5433 }
5434 else
5435 {
5436 /* Nothing changed. */
5437 value_free_to_mark (mark);
5438 return WP_VALUE_NOT_CHANGED;
5439 }
5440 }
5441 else
5442 {
5443 /* This seems like the only logical thing to do because
5444 if we temporarily ignored the watchpoint, then when
5445 we reenter the block in which it is valid it contains
5446 garbage (in the case of a function, it may have two
5447 garbage values, one before and one after the prologue).
5448 So we can't even detect the first assignment to it and
5449 watch after that (since the garbage may or may not equal
5450 the first value assigned). */
5451 /* We print all the stop information in
5452 breakpointprint_it, but in this case, by the time we
5453 call breakpoint->print_it this bp will be deleted
5454 already. So we have no choice but print the information
5455 here. */
5456
5457 SWITCH_THRU_ALL_UIS ()
5458 {
5459 struct ui_out *uiout = current_uiout;
5460
5461 if (uiout->is_mi_like_p ())
5462 uiout->field_string
5463 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5464 uiout->message ("\nWatchpoint %pF deleted because the program has "
5465 "left the block in\n"
5466 "which its expression is valid.\n",
5467 signed_field ("wpnum", b->number));
5468 }
5469
5470 /* Make sure the watchpoint's commands aren't executed. */
5471 b->commands = NULL;
5472 watchpoint_del_at_next_stop (b);
5473
5474 return WP_DELETED;
5475 }
5476 }
5477
5478 /* Return true if it looks like target has stopped due to hitting
5479 breakpoint location BL. This function does not check if we should
5480 stop, only if BL explains the stop. */
5481
5482 static bool
5483 bpstat_check_location (const struct bp_location *bl,
5484 const address_space *aspace, CORE_ADDR bp_addr,
5485 const target_waitstatus &ws)
5486 {
5487 struct breakpoint *b = bl->owner;
5488
5489 /* BL is from an existing breakpoint. */
5490 gdb_assert (b != NULL);
5491
5492 return b->breakpoint_hit (bl, aspace, bp_addr, ws);
5493 }
5494
5495 /* Determine if the watched values have actually changed, and we
5496 should stop. If not, set BS->stop to false. */
5497
5498 static void
5499 bpstat_check_watchpoint (bpstat *bs)
5500 {
5501 const struct bp_location *bl;
5502
5503 /* BS is built for existing struct breakpoint. */
5504 bl = bs->bp_location_at.get ();
5505 gdb_assert (bl != NULL);
5506 watchpoint *b = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5507
5508 bool must_check_value = false;
5509
5510 if (b->type == bp_watchpoint)
5511 /* For a software watchpoint, we must always check the
5512 watched value. */
5513 must_check_value = true;
5514 else if (b->watchpoint_triggered == watch_triggered_yes)
5515 /* We have a hardware watchpoint (read, write, or access)
5516 and the target earlier reported an address watched by
5517 this watchpoint. */
5518 must_check_value = true;
5519 else if (b->watchpoint_triggered == watch_triggered_unknown
5520 && b->type == bp_hardware_watchpoint)
5521 /* We were stopped by a hardware watchpoint, but the target could
5522 not report the data address. We must check the watchpoint's
5523 value. Access and read watchpoints are out of luck; without
5524 a data address, we can't figure it out. */
5525 must_check_value = true;
5526
5527 if (must_check_value)
5528 {
5529 wp_check_result e;
5530
5531 try
5532 {
5533 e = watchpoint_check (bs);
5534 }
5535 catch (const gdb_exception_error &ex)
5536 {
5537 exception_fprintf (gdb_stderr, ex,
5538 "Error evaluating expression "
5539 "for watchpoint %d\n",
5540 b->number);
5541
5542 SWITCH_THRU_ALL_UIS ()
5543 {
5544 gdb_printf (_("Watchpoint %d deleted.\n"),
5545 b->number);
5546 }
5547 watchpoint_del_at_next_stop (b);
5548 e = WP_DELETED;
5549 }
5550
5551 switch (e)
5552 {
5553 case WP_DELETED:
5554 /* We've already printed what needs to be printed. */
5555 bs->print_it = print_it_done;
5556 /* Stop. */
5557 break;
5558 case WP_IGNORE:
5559 bs->print_it = print_it_noop;
5560 bs->stop = false;
5561 break;
5562 case WP_VALUE_CHANGED:
5563 if (b->type == bp_read_watchpoint)
5564 {
5565 /* There are two cases to consider here:
5566
5567 1. We're watching the triggered memory for reads.
5568 In that case, trust the target, and always report
5569 the watchpoint hit to the user. Even though
5570 reads don't cause value changes, the value may
5571 have changed since the last time it was read, and
5572 since we're not trapping writes, we will not see
5573 those, and as such we should ignore our notion of
5574 old value.
5575
5576 2. We're watching the triggered memory for both
5577 reads and writes. There are two ways this may
5578 happen:
5579
5580 2.1. This is a target that can't break on data
5581 reads only, but can break on accesses (reads or
5582 writes), such as e.g., x86. We detect this case
5583 at the time we try to insert read watchpoints.
5584
5585 2.2. Otherwise, the target supports read
5586 watchpoints, but, the user set an access or write
5587 watchpoint watching the same memory as this read
5588 watchpoint.
5589
5590 If we're watching memory writes as well as reads,
5591 ignore watchpoint hits when we find that the
5592 value hasn't changed, as reads don't cause
5593 changes. This still gives false positives when
5594 the program writes the same value to memory as
5595 what there was already in memory (we will confuse
5596 it for a read), but it's much better than
5597 nothing. */
5598
5599 int other_write_watchpoint = 0;
5600
5601 if (bl->watchpoint_type == hw_read)
5602 {
5603 for (breakpoint &other_b : all_breakpoints ())
5604 if (other_b.type == bp_hardware_watchpoint
5605 || other_b.type == bp_access_watchpoint)
5606 {
5607 watchpoint &other_w =
5608 gdb::checked_static_cast<watchpoint &> (other_b);
5609
5610 if (other_w.watchpoint_triggered
5611 == watch_triggered_yes)
5612 {
5613 other_write_watchpoint = 1;
5614 break;
5615 }
5616 }
5617 }
5618
5619 if (other_write_watchpoint
5620 || bl->watchpoint_type == hw_access)
5621 {
5622 /* We're watching the same memory for writes,
5623 and the value changed since the last time we
5624 updated it, so this trap must be for a write.
5625 Ignore it. */
5626 bs->print_it = print_it_noop;
5627 bs->stop = false;
5628 }
5629 }
5630 break;
5631 case WP_VALUE_NOT_CHANGED:
5632 if (b->type == bp_hardware_watchpoint
5633 || b->type == bp_watchpoint)
5634 {
5635 /* Don't stop: write watchpoints shouldn't fire if
5636 the value hasn't changed. */
5637 bs->print_it = print_it_noop;
5638 bs->stop = false;
5639 }
5640 /* Stop. */
5641 break;
5642 default:
5643 /* Can't happen. */
5644 break;
5645 }
5646 }
5647 else /* !must_check_value */
5648 {
5649 /* This is a case where some watchpoint(s) triggered, but
5650 not at the address of this watchpoint, or else no
5651 watchpoint triggered after all. So don't print
5652 anything for this watchpoint. */
5653 bs->print_it = print_it_noop;
5654 bs->stop = false;
5655 }
5656 }
5657
5658 /* For breakpoints that are currently marked as telling gdb to stop,
5659 check conditions (condition proper, frame, thread and ignore count)
5660 of breakpoint referred to by BS. If we should not stop for this
5661 breakpoint, set BS->stop to 0. */
5662
5663 static void
5664 bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
5665 {
5666 INFRUN_SCOPED_DEBUG_ENTER_EXIT;
5667
5668 const struct bp_location *bl;
5669 struct breakpoint *b;
5670 /* Assume stop. */
5671 bool condition_result = true;
5672 struct expression *cond;
5673
5674 gdb_assert (bs->stop);
5675
5676 /* BS is built for existing struct breakpoint. */
5677 bl = bs->bp_location_at.get ();
5678 gdb_assert (bl != NULL);
5679 b = bs->breakpoint_at;
5680 gdb_assert (b != NULL);
5681
5682 infrun_debug_printf ("thread = %s, breakpoint %d.%d",
5683 thread->ptid.to_string ().c_str (),
5684 b->number, find_loc_num_by_location (bl));
5685
5686 /* Even if the target evaluated the condition on its end and notified GDB, we
5687 need to do so again since GDB does not know if we stopped due to a
5688 breakpoint or a single step breakpoint. */
5689
5690 if (frame_id_p (b->frame_id)
5691 && b->frame_id != get_stack_frame_id (get_current_frame ()))
5692 {
5693 infrun_debug_printf ("incorrect frame %s not %s, not stopping",
5694 get_stack_frame_id (get_current_frame ()).to_string ().c_str (),
5695 b->frame_id.to_string ().c_str ());
5696 bs->stop = false;
5697 return;
5698 }
5699
5700 /* If this is a thread/task-specific breakpoint, don't waste cpu
5701 evaluating the condition if this isn't the specified
5702 thread/task. */
5703 if ((b->thread != -1 && b->thread != thread->global_num)
5704 || (b->inferior != -1 && b->inferior != thread->inf->num)
5705 || (b->task != -1 && b->task != ada_get_task_number (thread)))
5706 {
5707 infrun_debug_printf ("incorrect thread or task, not stopping");
5708 bs->stop = false;
5709 return;
5710 }
5711
5712 /* Evaluate extension language breakpoints that have a "stop" method
5713 implemented. */
5714 bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5715
5716 if (is_watchpoint (b))
5717 {
5718 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
5719
5720 cond = w->cond_exp.get ();
5721 }
5722 else
5723 cond = bl->cond.get ();
5724
5725 if (cond != nullptr && b->disposition != disp_del_at_next_stop)
5726 {
5727 bool within_current_scope = true;
5728
5729 /* We use scoped_value_mark because it could be a long time
5730 before we return to the command level and call
5731 free_all_values. We can't call free_all_values because we
5732 might be in the middle of evaluating a function call. */
5733 scoped_value_mark mark;
5734
5735 watchpoint *w = nullptr;
5736 if (is_watchpoint (b))
5737 w = gdb::checked_static_cast<watchpoint *> (b);
5738
5739 /* Need to select the frame, with all that implies so that
5740 the conditions will have the right context. Because we
5741 use the frame, we will not see an inlined function's
5742 variables when we arrive at a breakpoint at the start
5743 of the inlined function; the current frame will be the
5744 call site. */
5745 if (w == NULL || w->cond_exp_valid_block == NULL)
5746 select_frame (get_current_frame ());
5747 else
5748 {
5749 frame_info_ptr frame;
5750
5751 /* For local watchpoint expressions, which particular
5752 instance of a local is being watched matters, so we
5753 keep track of the frame to evaluate the expression
5754 in. To evaluate the condition however, it doesn't
5755 really matter which instantiation of the function
5756 where the condition makes sense triggers the
5757 watchpoint. This allows an expression like "watch
5758 global if q > 10" set in `func', catch writes to
5759 global on all threads that call `func', or catch
5760 writes on all recursive calls of `func' by a single
5761 thread. We simply always evaluate the condition in
5762 the innermost frame that's executing where it makes
5763 sense to evaluate the condition. It seems
5764 intuitive. */
5765 frame = block_innermost_frame (w->cond_exp_valid_block);
5766 if (frame != NULL)
5767 select_frame (frame);
5768 else
5769 within_current_scope = false;
5770 }
5771 if (within_current_scope)
5772 {
5773 try
5774 {
5775 scoped_restore reset_in_cond_eval
5776 = make_scoped_restore (&thread->control.in_cond_eval, true);
5777 condition_result = breakpoint_cond_eval (cond);
5778 }
5779 catch (const gdb_exception_error &ex)
5780 {
5781 int locno = bpstat_locno (bs);
5782 if (locno != 0)
5783 exception_fprintf
5784 (gdb_stderr, ex,
5785 "Error in testing condition for breakpoint %d.%d:\n",
5786 b->number, locno);
5787 else
5788 exception_fprintf
5789 (gdb_stderr, ex,
5790 "Error in testing condition for breakpoint %d:\n",
5791 b->number);
5792 }
5793 }
5794 else
5795 {
5796 warning (_("Watchpoint condition cannot be tested "
5797 "in the current scope"));
5798 /* If we failed to set the right context for this
5799 watchpoint, unconditionally report it. */
5800 }
5801 /* FIXME-someday, should give breakpoint #. */
5802 }
5803
5804 if (cond != nullptr && !condition_result)
5805 {
5806 infrun_debug_printf ("condition_result = false, not stopping");
5807 bs->stop = false;
5808 return;
5809 }
5810 else if (b->ignore_count > 0)
5811 {
5812 infrun_debug_printf ("ignore count %d, not stopping",
5813 b->ignore_count);
5814 b->ignore_count--;
5815 bs->stop = false;
5816 /* Increase the hit count even though we don't stop. */
5817 ++(b->hit_count);
5818 notify_breakpoint_modified (b);
5819 return;
5820 }
5821
5822 if (bs->stop)
5823 infrun_debug_printf ("stopping at this breakpoint");
5824 else
5825 infrun_debug_printf ("not stopping at this breakpoint");
5826 }
5827
5828 /* Returns true if we need to track moribund locations of LOC's type
5829 on the current target. */
5830
5831 static bool
5832 need_moribund_for_location_type (const struct bp_location *loc)
5833 {
5834 return ((loc->loc_type == bp_loc_software_breakpoint
5835 && !target_supports_stopped_by_sw_breakpoint ())
5836 || (loc->loc_type == bp_loc_hardware_breakpoint
5837 && !target_supports_stopped_by_hw_breakpoint ()));
5838 }
5839
5840 /* See breakpoint.h. */
5841
5842 bpstat *
5843 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5844 const target_waitstatus &ws)
5845 {
5846 bpstat *bs_head = nullptr, **bs_link = &bs_head;
5847
5848 for (breakpoint &b : all_breakpoints ())
5849 {
5850 if (!breakpoint_enabled (&b))
5851 continue;
5852
5853 for (bp_location &bl : b.locations ())
5854 {
5855 /* For hardware watchpoints, we look only at the first
5856 location. The watchpoint_check function will work on the
5857 entire expression, not the individual locations. For
5858 read watchpoints, the watchpoints_triggered function has
5859 checked all locations already. */
5860 if (b.type == bp_hardware_watchpoint && &bl != &b.first_loc ())
5861 break;
5862
5863 if (!bl.enabled || bl.disabled_by_cond || bl.shlib_disabled)
5864 continue;
5865
5866 if (!bpstat_check_location (&bl, aspace, bp_addr, ws))
5867 continue;
5868
5869 /* Come here if it's a watchpoint, or if the break address
5870 matches. */
5871
5872 bpstat *bs = new bpstat (&bl, &bs_link); /* Alloc a bpstat to
5873 explain stop. */
5874
5875 /* Assume we stop. Should we find a watchpoint that is not
5876 actually triggered, or if the condition of the breakpoint
5877 evaluates as false, we'll reset 'stop' to 0. */
5878 bs->stop = true;
5879 bs->print = true;
5880
5881 /* If this is a scope breakpoint, mark the associated
5882 watchpoint as triggered so that we will handle the
5883 out-of-scope event. We'll get to the watchpoint next
5884 iteration. */
5885 if (b.type == bp_watchpoint_scope && b.related_breakpoint != &b)
5886 {
5887 watchpoint *w
5888 = gdb::checked_static_cast<watchpoint *> (b.related_breakpoint);
5889
5890 w->watchpoint_triggered = watch_triggered_yes;
5891 }
5892 }
5893 }
5894
5895 /* Check if a moribund breakpoint explains the stop. */
5896 if (!target_supports_stopped_by_sw_breakpoint ()
5897 || !target_supports_stopped_by_hw_breakpoint ())
5898 {
5899 for (bp_location *loc : moribund_locations)
5900 {
5901 if (breakpoint_location_address_match (loc, aspace, bp_addr)
5902 && need_moribund_for_location_type (loc))
5903 {
5904 bpstat *bs = new bpstat (loc, &bs_link);
5905 /* For hits of moribund locations, we should just proceed. */
5906 bs->stop = false;
5907 bs->print = false;
5908 bs->print_it = print_it_noop;
5909 }
5910 }
5911 }
5912
5913 return bs_head;
5914 }
5915
5916 /* See breakpoint.h. */
5917
5918 bpstat *
5919 bpstat_stop_status (const address_space *aspace,
5920 CORE_ADDR bp_addr, thread_info *thread,
5921 const target_waitstatus &ws,
5922 bpstat *stop_chain)
5923 {
5924 struct breakpoint *b = NULL;
5925 /* First item of allocated bpstat's. */
5926 bpstat *bs_head = stop_chain;
5927 bpstat *bs;
5928 int need_remove_insert;
5929 int removed_any;
5930
5931 /* First, build the bpstat chain with locations that explain a
5932 target stop, while being careful to not set the target running,
5933 as that may invalidate locations (in particular watchpoint
5934 locations are recreated). Resuming will happen here with
5935 breakpoint conditions or watchpoint expressions that include
5936 inferior function calls. */
5937 if (bs_head == NULL)
5938 bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5939
5940 /* A bit of special processing for shlib breakpoints. We need to
5941 process solib loading here, so that the lists of loaded and
5942 unloaded libraries are correct before we handle "catch load" and
5943 "catch unload". */
5944 for (bs = bs_head; bs != NULL; bs = bs->next)
5945 {
5946 if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5947 {
5948 handle_solib_event ();
5949 break;
5950 }
5951 }
5952
5953 /* Now go through the locations that caused the target to stop, and
5954 check whether we're interested in reporting this stop to higher
5955 layers, or whether we should resume the target transparently. */
5956
5957 removed_any = 0;
5958
5959 for (bs = bs_head; bs != NULL; bs = bs->next)
5960 {
5961 if (!bs->stop)
5962 continue;
5963
5964 b = bs->breakpoint_at;
5965 b->check_status (bs);
5966 if (bs->stop)
5967 {
5968 bpstat_check_breakpoint_conditions (bs, thread);
5969
5970 if (bs->stop)
5971 {
5972 ++(b->hit_count);
5973
5974 /* We will stop here. */
5975 if (b->disposition == disp_disable)
5976 {
5977 --(b->enable_count);
5978 if (b->enable_count <= 0)
5979 b->enable_state = bp_disabled;
5980 removed_any = 1;
5981 }
5982 notify_breakpoint_modified (b);
5983 if (b->silent)
5984 bs->print = false;
5985 bs->commands = b->commands;
5986 if (command_line_is_silent (bs->commands
5987 ? bs->commands.get () : NULL))
5988 bs->print = false;
5989
5990 b->after_condition_true (bs);
5991 }
5992
5993 }
5994
5995 /* Print nothing for this entry if we don't stop or don't
5996 print. */
5997 if (!bs->stop || !bs->print)
5998 bs->print_it = print_it_noop;
5999 }
6000
6001 /* If we aren't stopping, the value of some hardware watchpoint may
6002 not have changed, but the intermediate memory locations we are
6003 watching may have. Don't bother if we're stopping; this will get
6004 done later. */
6005 need_remove_insert = 0;
6006 if (! bpstat_causes_stop (bs_head))
6007 for (bs = bs_head; bs != NULL; bs = bs->next)
6008 if (!bs->stop
6009 && bs->breakpoint_at
6010 && is_hardware_watchpoint (bs->breakpoint_at))
6011 {
6012 watchpoint *w
6013 = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
6014
6015 update_watchpoint (w, false /* don't reparse. */);
6016 need_remove_insert = 1;
6017 }
6018
6019 if (need_remove_insert)
6020 update_global_location_list (UGLL_MAY_INSERT);
6021 else if (removed_any)
6022 update_global_location_list (UGLL_DONT_INSERT);
6023
6024 return bs_head;
6025 }
6026
6027 /* See breakpoint.h. */
6028
6029 bpstat *
6030 bpstat_stop_status_nowatch (const address_space *aspace, CORE_ADDR bp_addr,
6031 thread_info *thread, const target_waitstatus &ws)
6032 {
6033 gdb_assert (!target_stopped_by_watchpoint ());
6034
6035 /* Clear all watchpoints' 'watchpoint_triggered' value from a
6036 previous stop to avoid confusing bpstat_stop_status. */
6037 watchpoints_triggered (ws);
6038
6039 return bpstat_stop_status (aspace, bp_addr, thread, ws);
6040 }
6041
6042 static void
6043 handle_jit_event (CORE_ADDR address)
6044 {
6045 struct gdbarch *gdbarch;
6046
6047 infrun_debug_printf ("handling bp_jit_event");
6048
6049 /* Switch terminal for any messages produced by
6050 breakpoint_re_set. */
6051 target_terminal::ours_for_output ();
6052
6053 gdbarch = get_frame_arch (get_current_frame ());
6054 /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
6055 thus it is expected that its objectfile can be found through
6056 minimal symbol lookup. If it doesn't work (and assert fails), it
6057 most likely means that `jit_breakpoint_re_set` was changes and this
6058 function needs to be updated too. */
6059 bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
6060 gdb_assert (jit_bp_sym.objfile != nullptr);
6061 objfile *objfile = jit_bp_sym.objfile;
6062 if (objfile->separate_debug_objfile_backlink)
6063 objfile = objfile->separate_debug_objfile_backlink;
6064 jit_event_handler (gdbarch, objfile);
6065
6066 target_terminal::inferior ();
6067 }
6068
6069 /* Prepare WHAT final decision for infrun. */
6070
6071 /* Decide what infrun needs to do with this bpstat. */
6072
6073 struct bpstat_what
6074 bpstat_what (bpstat *bs_head)
6075 {
6076 struct bpstat_what retval;
6077 bpstat *bs;
6078
6079 retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
6080 retval.call_dummy = STOP_NONE;
6081 retval.is_longjmp = false;
6082
6083 for (bs = bs_head; bs != NULL; bs = bs->next)
6084 {
6085 /* Extract this BS's action. After processing each BS, we check
6086 if its action overrides all we've seem so far. */
6087 enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
6088 enum bptype bptype;
6089
6090 if (bs->breakpoint_at == NULL)
6091 {
6092 /* I suspect this can happen if it was a momentary
6093 breakpoint which has since been deleted. */
6094 bptype = bp_none;
6095 }
6096 else
6097 bptype = bs->breakpoint_at->type;
6098
6099 switch (bptype)
6100 {
6101 case bp_none:
6102 break;
6103 case bp_breakpoint:
6104 case bp_hardware_breakpoint:
6105 case bp_single_step:
6106 case bp_until:
6107 case bp_finish:
6108 case bp_shlib_event:
6109 if (bs->stop)
6110 {
6111 if (bs->print)
6112 this_action = BPSTAT_WHAT_STOP_NOISY;
6113 else
6114 this_action = BPSTAT_WHAT_STOP_SILENT;
6115 }
6116 else
6117 this_action = BPSTAT_WHAT_SINGLE;
6118 break;
6119 case bp_watchpoint:
6120 case bp_hardware_watchpoint:
6121 case bp_read_watchpoint:
6122 case bp_access_watchpoint:
6123 if (bs->stop)
6124 {
6125 if (bs->print)
6126 this_action = BPSTAT_WHAT_STOP_NOISY;
6127 else
6128 this_action = BPSTAT_WHAT_STOP_SILENT;
6129 }
6130 else
6131 {
6132 /* There was a watchpoint, but we're not stopping.
6133 This requires no further action. */
6134 }
6135 break;
6136 case bp_longjmp:
6137 case bp_longjmp_call_dummy:
6138 case bp_exception:
6139 if (bs->stop)
6140 {
6141 this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
6142 retval.is_longjmp = bptype != bp_exception;
6143 }
6144 else
6145 this_action = BPSTAT_WHAT_SINGLE;
6146 break;
6147 case bp_longjmp_resume:
6148 case bp_exception_resume:
6149 if (bs->stop)
6150 {
6151 this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
6152 retval.is_longjmp = bptype == bp_longjmp_resume;
6153 }
6154 else
6155 this_action = BPSTAT_WHAT_SINGLE;
6156 break;
6157 case bp_step_resume:
6158 if (bs->stop)
6159 this_action = BPSTAT_WHAT_STEP_RESUME;
6160 else
6161 {
6162 /* It is for the wrong frame. */
6163 this_action = BPSTAT_WHAT_SINGLE;
6164 }
6165 break;
6166 case bp_hp_step_resume:
6167 if (bs->stop)
6168 this_action = BPSTAT_WHAT_HP_STEP_RESUME;
6169 else
6170 {
6171 /* It is for the wrong frame. */
6172 this_action = BPSTAT_WHAT_SINGLE;
6173 }
6174 break;
6175 case bp_watchpoint_scope:
6176 case bp_thread_event:
6177 case bp_overlay_event:
6178 case bp_longjmp_master:
6179 case bp_std_terminate_master:
6180 case bp_exception_master:
6181 this_action = BPSTAT_WHAT_SINGLE;
6182 break;
6183 case bp_catchpoint:
6184 if (bs->stop)
6185 {
6186 if (bs->print)
6187 this_action = BPSTAT_WHAT_STOP_NOISY;
6188 else
6189 this_action = BPSTAT_WHAT_STOP_SILENT;
6190 }
6191 else
6192 {
6193 /* Some catchpoints are implemented with breakpoints.
6194 For those, we need to step over the breakpoint. */
6195 if (bs->bp_location_at->loc_type == bp_loc_software_breakpoint
6196 || bs->bp_location_at->loc_type == bp_loc_hardware_breakpoint)
6197 this_action = BPSTAT_WHAT_SINGLE;
6198 }
6199 break;
6200 case bp_jit_event:
6201 this_action = BPSTAT_WHAT_SINGLE;
6202 break;
6203 case bp_call_dummy:
6204 /* Make sure the action is stop (silent or noisy),
6205 so infrun.c pops the dummy frame. */
6206 retval.call_dummy = STOP_STACK_DUMMY;
6207 this_action = BPSTAT_WHAT_STOP_SILENT;
6208 break;
6209 case bp_std_terminate:
6210 /* Make sure the action is stop (silent or noisy),
6211 so infrun.c pops the dummy frame. */
6212 retval.call_dummy = STOP_STD_TERMINATE;
6213 this_action = BPSTAT_WHAT_STOP_SILENT;
6214 break;
6215 case bp_tracepoint:
6216 case bp_fast_tracepoint:
6217 case bp_static_tracepoint:
6218 case bp_static_marker_tracepoint:
6219 /* Tracepoint hits should not be reported back to GDB, and
6220 if one got through somehow, it should have been filtered
6221 out already. */
6222 internal_error (_("bpstat_what: tracepoint encountered"));
6223 break;
6224 case bp_gnu_ifunc_resolver:
6225 /* Step over it (and insert bp_gnu_ifunc_resolver_return). */
6226 this_action = BPSTAT_WHAT_SINGLE;
6227 break;
6228 case bp_gnu_ifunc_resolver_return:
6229 /* The breakpoint will be removed, execution will restart from the
6230 PC of the former breakpoint. */
6231 this_action = BPSTAT_WHAT_KEEP_CHECKING;
6232 break;
6233
6234 case bp_dprintf:
6235 if (bs->stop)
6236 this_action = BPSTAT_WHAT_STOP_SILENT;
6237 else
6238 this_action = BPSTAT_WHAT_SINGLE;
6239 break;
6240
6241 default:
6242 internal_error (_("bpstat_what: unhandled bptype %d"), (int) bptype);
6243 }
6244
6245 retval.main_action = std::max (retval.main_action, this_action);
6246 }
6247
6248 return retval;
6249 }
6250
6251 void
6252 bpstat_run_callbacks (bpstat *bs_head)
6253 {
6254 bpstat *bs;
6255
6256 for (bs = bs_head; bs != NULL; bs = bs->next)
6257 {
6258 struct breakpoint *b = bs->breakpoint_at;
6259
6260 if (b == NULL)
6261 continue;
6262 switch (b->type)
6263 {
6264 case bp_jit_event:
6265 handle_jit_event (bs->bp_location_at->address);
6266 break;
6267 case bp_gnu_ifunc_resolver:
6268 gnu_ifunc_resolver_stop
6269 (gdb::checked_static_cast<code_breakpoint *> (b));
6270 break;
6271 case bp_gnu_ifunc_resolver_return:
6272 gnu_ifunc_resolver_return_stop
6273 (gdb::checked_static_cast<code_breakpoint *> (b));
6274 break;
6275 }
6276 }
6277 }
6278
6279 /* See breakpoint.h. */
6280
6281 bool
6282 bpstat_should_step ()
6283 {
6284 for (breakpoint &b : all_breakpoints ())
6285 if (breakpoint_enabled (&b)
6286 && b.type == bp_watchpoint
6287 && b.has_locations ())
6288 return true;
6289
6290 return false;
6291 }
6292
6293 /* See breakpoint.h. */
6294
6295 bool
6296 bpstat_causes_stop (bpstat *bs)
6297 {
6298 for (; bs != NULL; bs = bs->next)
6299 if (bs->stop)
6300 return true;
6301
6302 return false;
6303 }
6304
6305 \f
6306
6307 /* Compute a number of spaces suitable to indent the next line
6308 so it starts at the position corresponding to the table column
6309 named COL_NAME in the currently active table of UIOUT. */
6310
6311 static int
6312 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6313 {
6314 int i, total_width, width, align;
6315 const char *text;
6316
6317 total_width = 0;
6318 for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
6319 {
6320 if (strcmp (text, col_name) == 0)
6321 return total_width;
6322
6323 total_width += width + 1;
6324 }
6325
6326 return 0;
6327 }
6328
6329 /* Determine if the locations of this breakpoint will have their conditions
6330 evaluated by the target, host or a mix of both. Returns the following:
6331
6332 "host": Host evals condition.
6333 "host or target": Host or Target evals condition.
6334 "target": Target evals condition.
6335 */
6336
6337 static const char *
6338 bp_condition_evaluator (const breakpoint *b)
6339 {
6340 char host_evals = 0;
6341 char target_evals = 0;
6342
6343 if (!b)
6344 return NULL;
6345
6346 if (!is_breakpoint (b))
6347 return NULL;
6348
6349 if (gdb_evaluates_breakpoint_condition_p ()
6350 || !target_supports_evaluation_of_breakpoint_conditions ())
6351 return condition_evaluation_host;
6352
6353 for (bp_location &bl : b->locations ())
6354 {
6355 if (bl.cond_bytecode)
6356 target_evals++;
6357 else
6358 host_evals++;
6359 }
6360
6361 if (host_evals && target_evals)
6362 return condition_evaluation_both;
6363 else if (target_evals)
6364 return condition_evaluation_target;
6365 else
6366 return condition_evaluation_host;
6367 }
6368
6369 /* Determine the breakpoint location's condition evaluator. This is
6370 similar to bp_condition_evaluator, but for locations. */
6371
6372 static const char *
6373 bp_location_condition_evaluator (const struct bp_location *bl)
6374 {
6375 if (bl && !is_breakpoint (bl->owner))
6376 return NULL;
6377
6378 if (gdb_evaluates_breakpoint_condition_p ()
6379 || !target_supports_evaluation_of_breakpoint_conditions ())
6380 return condition_evaluation_host;
6381
6382 if (bl && bl->cond_bytecode)
6383 return condition_evaluation_target;
6384 else
6385 return condition_evaluation_host;
6386 }
6387
6388 /* Print the LOC location out of the list of B->LOC locations. */
6389
6390 static void
6391 print_breakpoint_location (const breakpoint *b, const bp_location *loc)
6392 {
6393 struct ui_out *uiout = current_uiout;
6394
6395 scoped_restore_current_program_space restore_pspace;
6396
6397 if (loc != NULL && loc->shlib_disabled)
6398 loc = NULL;
6399
6400 if (loc != NULL)
6401 set_current_program_space (loc->pspace);
6402
6403 if (b->display_canonical)
6404 uiout->field_string ("what", b->locspec->to_string ());
6405 else if (loc && loc->symtab)
6406 {
6407 const struct symbol *sym = loc->symbol;
6408
6409 if (sym)
6410 {
6411 uiout->text ("in ");
6412 uiout->field_string ("func", sym->print_name (),
6413 function_name_style.style ());
6414 uiout->text (" ");
6415 uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6416 uiout->text ("at ");
6417 }
6418 uiout->field_string ("file",
6419 symtab_to_filename_for_display (loc->symtab),
6420 file_name_style.style ());
6421 uiout->text (":");
6422
6423 if (uiout->is_mi_like_p ())
6424 uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6425
6426 uiout->field_signed ("line", loc->line_number,
6427 line_number_style.style ());
6428 }
6429 else if (loc)
6430 {
6431 string_file stb;
6432
6433 print_address_symbolic (loc->gdbarch, loc->address, &stb,
6434 demangle, "");
6435 uiout->field_stream ("at", stb);
6436 }
6437 else
6438 {
6439 /* Internal breakpoints don't have a locspec string, but can become
6440 pending if the shared library the breakpoint is in is unloaded.
6441 For most internal breakpoint types though, after unloading the
6442 shared library, the breakpoint will be deleted and never recreated
6443 (see internal_breakpoint::re_set). But for two internal
6444 breakpoint types bp_shlib_event and bp_thread_event this is not
6445 true. Usually we don't expect the libraries that contain these
6446 breakpoints to ever be unloaded, but a buggy inferior might do
6447 such a thing, in which case GDB should be prepared to handle this
6448 case.
6449
6450 If these two breakpoint types become pending then there will be no
6451 locspec string. */
6452 gdb_assert (b->locspec != nullptr
6453 || (!user_breakpoint_p (b)
6454 && (b->type == bp_shlib_event
6455 || b->type == bp_thread_event)));
6456 const char *locspec_str
6457 = (b->locspec != nullptr ? b->locspec->to_string () : "");
6458 uiout->field_string ("pending", locspec_str);
6459 }
6460
6461 if (loc && is_breakpoint (b)
6462 && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6463 && bp_condition_evaluator (b) == condition_evaluation_both)
6464 {
6465 uiout->text (" (");
6466 uiout->field_string ("evaluated-by",
6467 bp_location_condition_evaluator (loc));
6468 uiout->text (")");
6469 }
6470 }
6471
6472 static const char *
6473 bptype_string (enum bptype type)
6474 {
6475 struct ep_type_description
6476 {
6477 enum bptype type;
6478 const char *description;
6479 };
6480 static struct ep_type_description bptypes[] =
6481 {
6482 {bp_none, "?deleted?"},
6483 {bp_breakpoint, "breakpoint"},
6484 {bp_hardware_breakpoint, "hw breakpoint"},
6485 {bp_single_step, "sw single-step"},
6486 {bp_until, "until"},
6487 {bp_finish, "finish"},
6488 {bp_watchpoint, "watchpoint"},
6489 {bp_hardware_watchpoint, "hw watchpoint"},
6490 {bp_read_watchpoint, "read watchpoint"},
6491 {bp_access_watchpoint, "acc watchpoint"},
6492 {bp_longjmp, "longjmp"},
6493 {bp_longjmp_resume, "longjmp resume"},
6494 {bp_longjmp_call_dummy, "longjmp for call dummy"},
6495 {bp_exception, "exception"},
6496 {bp_exception_resume, "exception resume"},
6497 {bp_step_resume, "step resume"},
6498 {bp_hp_step_resume, "high-priority step resume"},
6499 {bp_watchpoint_scope, "watchpoint scope"},
6500 {bp_call_dummy, "call dummy"},
6501 {bp_std_terminate, "std::terminate"},
6502 {bp_shlib_event, "shlib events"},
6503 {bp_thread_event, "thread events"},
6504 {bp_overlay_event, "overlay events"},
6505 {bp_longjmp_master, "longjmp master"},
6506 {bp_std_terminate_master, "std::terminate master"},
6507 {bp_exception_master, "exception master"},
6508 {bp_catchpoint, "catchpoint"},
6509 {bp_tracepoint, "tracepoint"},
6510 {bp_fast_tracepoint, "fast tracepoint"},
6511 {bp_static_tracepoint, "static tracepoint"},
6512 {bp_static_marker_tracepoint, "static marker tracepoint"},
6513 {bp_dprintf, "dprintf"},
6514 {bp_jit_event, "jit events"},
6515 {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6516 {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6517 };
6518
6519 if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6520 || ((int) type != bptypes[(int) type].type))
6521 internal_error (_("bptypes table does not describe type #%d."),
6522 (int) type);
6523
6524 return bptypes[(int) type].description;
6525 }
6526
6527 /* For MI, output a field named 'thread-groups' with a list as the value.
6528 For CLI, prefix the list with the string 'inf'. */
6529
6530 static void
6531 output_thread_groups (struct ui_out *uiout,
6532 const char *field_name,
6533 const std::vector<int> &inf_nums,
6534 int mi_only)
6535 {
6536 int is_mi = uiout->is_mi_like_p ();
6537
6538 /* For backward compatibility, don't display inferiors in CLI unless
6539 there are several. Always display them for MI. */
6540 if (!is_mi && mi_only)
6541 return;
6542
6543 ui_out_emit_list list_emitter (uiout, field_name);
6544
6545 for (size_t i = 0; i < inf_nums.size (); i++)
6546 {
6547 if (is_mi)
6548 {
6549 char mi_group[10];
6550
6551 xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6552 uiout->field_string (NULL, mi_group);
6553 }
6554 else
6555 {
6556 if (i == 0)
6557 uiout->text (" inf ");
6558 else
6559 uiout->text (", ");
6560
6561 uiout->text (plongest (inf_nums[i]));
6562 }
6563 }
6564 }
6565
6566 /* See breakpoint.h. */
6567
6568 bool fix_breakpoint_script_output_globally = false;
6569
6570 /* Print B to gdb_stdout. If RAW_LOC, print raw breakpoint locations
6571 instead of going via breakpoint_ops::print_one. This makes "maint
6572 info breakpoints" show the software breakpoint locations of
6573 catchpoints, which are considered internal implementation
6574 detail. Returns true if RAW_LOC is false and if the breakpoint's
6575 print_one method did something; false otherwise. */
6576
6577 static bool
6578 print_one_breakpoint_location (struct breakpoint *b,
6579 struct bp_location *loc,
6580 int loc_number,
6581 const bp_location **last_loc,
6582 int allflag, bool raw_loc)
6583 {
6584 struct command_line *l;
6585 static char bpenables[] = "nynny";
6586
6587 struct ui_out *uiout = current_uiout;
6588 bool header_of_multiple = false;
6589 bool part_of_multiple = (loc != NULL);
6590 struct value_print_options opts;
6591
6592 get_user_print_options (&opts);
6593
6594 gdb_assert (!loc || loc_number != 0);
6595 /* See comment in print_one_breakpoint concerning treatment of
6596 breakpoints with single disabled location. */
6597 if (loc == NULL
6598 && (b->has_locations ()
6599 && (b->has_multiple_locations ()
6600 || !b->first_loc ().enabled || b->first_loc ().disabled_by_cond)))
6601 header_of_multiple = true;
6602
6603 if (loc == NULL && b->has_locations ())
6604 loc = &b->first_loc ();
6605
6606 annotate_record ();
6607
6608 /* 1 */
6609 annotate_field (0);
6610 if (part_of_multiple)
6611 uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6612 else
6613 uiout->field_signed ("number", b->number);
6614
6615 /* 2 */
6616 annotate_field (1);
6617 if (part_of_multiple)
6618 uiout->field_skip ("type");
6619 else
6620 uiout->field_string ("type", bptype_string (b->type));
6621
6622 /* 3 */
6623 annotate_field (2);
6624 if (part_of_multiple)
6625 uiout->field_skip ("disp");
6626 else
6627 uiout->field_string ("disp", bpdisp_text (b->disposition));
6628
6629 /* 4 */
6630 annotate_field (3);
6631 if (part_of_multiple)
6632 {
6633 /* For locations that are disabled because of an invalid
6634 condition, display "N*" on the CLI, where "*" refers to a
6635 footnote below the table. For MI, simply display a "N"
6636 without a footnote. On the CLI, for enabled locations whose
6637 breakpoint is disabled, display "y-". */
6638 auto get_enable_state = [uiout, loc] () -> const char *
6639 {
6640 if (uiout->is_mi_like_p ())
6641 {
6642 if (loc->disabled_by_cond)
6643 return "N";
6644 else if (!loc->enabled)
6645 return "n";
6646 else
6647 return "y";
6648 }
6649 else
6650 {
6651 if (loc->disabled_by_cond)
6652 return "N*";
6653 else if (!loc->enabled)
6654 return "n";
6655 else if (!breakpoint_enabled (loc->owner))
6656 return "y-";
6657 else
6658 return "y";
6659 }
6660 };
6661 uiout->field_string ("enabled", get_enable_state ());
6662 }
6663 else
6664 uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6665
6666 /* 5 and 6 */
6667 bool result = false;
6668 if (!raw_loc && b->print_one (last_loc))
6669 result = true;
6670 else
6671 {
6672 if (is_watchpoint (b))
6673 {
6674 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
6675
6676 /* Field 4, the address, is omitted (which makes the columns
6677 not line up too nicely with the headers, but the effect
6678 is relatively readable). */
6679 if (opts.addressprint)
6680 uiout->field_skip ("addr");
6681 annotate_field (5);
6682 uiout->field_string ("what", w->exp_string.get ());
6683 }
6684 else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6685 || is_ada_exception_catchpoint (b))
6686 {
6687 if (opts.addressprint)
6688 {
6689 annotate_field (4);
6690 if (header_of_multiple)
6691 uiout->field_string ("addr", "<MULTIPLE>",
6692 metadata_style.style ());
6693 else if (!b->has_locations () || loc->shlib_disabled)
6694 uiout->field_string ("addr", "<PENDING>",
6695 metadata_style.style ());
6696 else
6697 uiout->field_core_addr ("addr",
6698 loc->gdbarch, loc->address);
6699 }
6700 annotate_field (5);
6701 if (!header_of_multiple)
6702 print_breakpoint_location (b, loc);
6703 if (b->has_locations ())
6704 *last_loc = &b->first_loc ();
6705 }
6706 }
6707
6708 if (loc != nullptr && !header_of_multiple && !loc->shlib_disabled)
6709 {
6710 std::vector<int> inf_nums;
6711 int mi_only = 1;
6712
6713 for (inferior *inf : all_inferiors ())
6714 {
6715 if (inf->pspace == loc->pspace)
6716 inf_nums.push_back (inf->num);
6717 }
6718
6719 /* For backward compatibility, don't display inferiors in CLI unless
6720 there are several. Always display for MI. */
6721 if (allflag
6722 || (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
6723 && (program_spaces.size () > 1
6724 || number_of_inferiors () > 1)
6725 /* LOC is for existing B, it cannot be in
6726 moribund_locations and thus having NULL OWNER. */
6727 && loc->owner->type != bp_catchpoint))
6728 mi_only = 0;
6729 output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6730 }
6731
6732 /* In the MI output, each location of a thread or task specific
6733 breakpoint includes the relevant thread or task ID. This is done for
6734 backwards compatibility reasons.
6735
6736 For the CLI output, the thread/task information is printed on a
6737 separate line, see the 'stop only in thread' and 'stop only in task'
6738 output below. */
6739 if (part_of_multiple && uiout->is_mi_like_p ())
6740 {
6741 if (b->thread != -1)
6742 uiout->field_signed ("thread", b->thread);
6743 else if (b->task != -1)
6744 uiout->field_signed ("task", b->task);
6745 else if (b->inferior != -1)
6746 uiout->field_signed ("inferior", b->inferior);
6747 }
6748
6749 uiout->text ("\n");
6750
6751 if (!part_of_multiple)
6752 b->print_one_detail (uiout);
6753
6754 if (part_of_multiple && frame_id_p (b->frame_id))
6755 {
6756 annotate_field (6);
6757 uiout->text ("\tstop only in stack frame at ");
6758 /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6759 the frame ID. */
6760 uiout->field_core_addr ("frame",
6761 b->gdbarch, b->frame_id.stack_addr);
6762 uiout->text ("\n");
6763 }
6764
6765 if (!part_of_multiple && b->cond_string)
6766 {
6767 annotate_field (7);
6768 if (is_tracepoint (b))
6769 uiout->text ("\ttrace only if ");
6770 else
6771 uiout->text ("\tstop only if ");
6772 uiout->field_string ("cond", b->cond_string.get ());
6773
6774 /* Print whether the target is doing the breakpoint's condition
6775 evaluation. If GDB is doing the evaluation, don't print anything. */
6776 if (is_breakpoint (b)
6777 && breakpoint_condition_evaluation_mode ()
6778 == condition_evaluation_target)
6779 {
6780 uiout->message (" (%pF evals)",
6781 string_field ("evaluated-by",
6782 bp_condition_evaluator (b)));
6783 }
6784 uiout->text ("\n");
6785 }
6786
6787 if (!part_of_multiple && b->thread != -1)
6788 {
6789 /* FIXME should make an annotation for this. */
6790 uiout->text ("\tstop only in thread ");
6791 if (uiout->is_mi_like_p ())
6792 uiout->field_signed ("thread", b->thread);
6793 else
6794 {
6795 struct thread_info *thr = find_thread_global_id (b->thread);
6796
6797 uiout->field_string ("thread", print_thread_id (thr));
6798 }
6799 uiout->text ("\n");
6800 }
6801
6802 if (!part_of_multiple && b->task != -1)
6803 {
6804 uiout->text ("\tstop only in task ");
6805 uiout->field_signed ("task", b->task);
6806 uiout->text ("\n");
6807 }
6808
6809 if (!part_of_multiple && b->inferior != -1)
6810 {
6811 uiout->text ("\tstop only in inferior ");
6812 uiout->field_signed ("inferior", b->inferior);
6813 uiout->text ("\n");
6814 }
6815
6816 if (!part_of_multiple)
6817 {
6818 if (b->hit_count)
6819 {
6820 /* FIXME should make an annotation for this. */
6821 if (is_catchpoint (b))
6822 uiout->text ("\tcatchpoint");
6823 else if (is_tracepoint (b))
6824 uiout->text ("\ttracepoint");
6825 else
6826 uiout->text ("\tbreakpoint");
6827 uiout->text (" already hit ");
6828 uiout->field_signed ("times", b->hit_count);
6829 if (b->hit_count == 1)
6830 uiout->text (" time\n");
6831 else
6832 uiout->text (" times\n");
6833 }
6834 else
6835 {
6836 /* Output the count also if it is zero, but only if this is mi. */
6837 if (uiout->is_mi_like_p ())
6838 uiout->field_signed ("times", b->hit_count);
6839 }
6840 }
6841
6842 if (!part_of_multiple && b->ignore_count)
6843 {
6844 annotate_field (8);
6845 uiout->message ("\tignore next %pF hits\n",
6846 signed_field ("ignore", b->ignore_count));
6847 }
6848
6849 /* Note that an enable count of 1 corresponds to "enable once"
6850 behavior, which is reported by the combination of enablement and
6851 disposition, so we don't need to mention it here. */
6852 if (!part_of_multiple && b->enable_count > 1)
6853 {
6854 annotate_field (8);
6855 uiout->text ("\tdisable after ");
6856 /* Tweak the wording to clarify that ignore and enable counts
6857 are distinct, and have additive effect. */
6858 if (b->ignore_count)
6859 uiout->text ("additional ");
6860 else
6861 uiout->text ("next ");
6862 uiout->field_signed ("enable", b->enable_count);
6863 uiout->text (" hits\n");
6864 }
6865
6866 if (!part_of_multiple && is_tracepoint (b))
6867 {
6868 tracepoint *tp = gdb::checked_static_cast<tracepoint *> (b);
6869
6870 if (tp->traceframe_usage)
6871 {
6872 uiout->text ("\ttrace buffer usage ");
6873 uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6874 uiout->text (" bytes\n");
6875 }
6876 }
6877
6878 l = b->commands ? b->commands.get () : NULL;
6879 if (!part_of_multiple && l)
6880 {
6881 annotate_field (9);
6882
6883 bool use_fixed_output =
6884 (uiout->test_flags (fix_breakpoint_script_output)
6885 || fix_breakpoint_script_output_globally);
6886
6887 std::optional<ui_out_emit_tuple> tuple_emitter;
6888 std::optional<ui_out_emit_list> list_emitter;
6889
6890 if (use_fixed_output)
6891 list_emitter.emplace (uiout, "script");
6892 else
6893 tuple_emitter.emplace (uiout, "script");
6894
6895 print_command_lines (uiout, l, 4);
6896 }
6897
6898 if (is_tracepoint (b))
6899 {
6900 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
6901
6902 if (!part_of_multiple && t->pass_count)
6903 {
6904 annotate_field (10);
6905 uiout->text ("\tpass count ");
6906 uiout->field_signed ("pass", t->pass_count);
6907 uiout->text (" \n");
6908 }
6909
6910 /* Don't display it when tracepoint or tracepoint location is
6911 pending. */
6912 if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6913 {
6914 annotate_field (11);
6915
6916 if (uiout->is_mi_like_p ())
6917 uiout->field_string ("installed",
6918 loc->inserted ? "y" : "n");
6919 else
6920 {
6921 if (loc->inserted)
6922 uiout->text ("\t");
6923 else
6924 uiout->text ("\tnot ");
6925 uiout->text ("installed on target\n");
6926 }
6927 }
6928 }
6929
6930 if (uiout->is_mi_like_p () && !part_of_multiple)
6931 {
6932 if (is_watchpoint (b))
6933 {
6934 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
6935
6936 uiout->field_string ("original-location", w->exp_string.get ());
6937 }
6938 else if (b->locspec != nullptr)
6939 {
6940 const char *str = b->locspec->to_string ();
6941 if (str != nullptr)
6942 uiout->field_string ("original-location", str);
6943 }
6944 }
6945
6946 return result;
6947 }
6948
6949 /* See breakpoint.h. */
6950
6951 bool fix_multi_location_breakpoint_output_globally = false;
6952
6953 static void
6954 print_one_breakpoint (breakpoint *b, const bp_location **last_loc, int allflag)
6955 {
6956 struct ui_out *uiout = current_uiout;
6957 bool use_fixed_output
6958 = (uiout->test_flags (fix_multi_location_breakpoint_output)
6959 || fix_multi_location_breakpoint_output_globally);
6960
6961 std::optional<ui_out_emit_tuple> bkpt_tuple_emitter (std::in_place, uiout,
6962 "bkpt");
6963 bool printed = print_one_breakpoint_location (b, NULL, 0, last_loc,
6964 allflag, false);
6965
6966 /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6967 are outside. */
6968 if (!use_fixed_output)
6969 bkpt_tuple_emitter.reset ();
6970
6971 /* If this breakpoint has custom print function,
6972 it's already printed. Otherwise, print individual
6973 locations, if any. */
6974 if (!printed || allflag)
6975 {
6976 /* If breakpoint has a single location that is disabled, we
6977 print it as if it had several locations, since otherwise it's
6978 hard to represent "breakpoint enabled, location disabled"
6979 situation.
6980
6981 Note that while hardware watchpoints have several locations
6982 internally, that's not a property exposed to users.
6983
6984 Likewise, while catchpoints may be implemented with
6985 breakpoints (e.g., catch throw), that's not a property
6986 exposed to users. We do however display the internal
6987 breakpoint locations with "maint info breakpoints". */
6988 if (!is_hardware_watchpoint (b)
6989 && (!is_catchpoint (b) || is_exception_catchpoint (b)
6990 || is_ada_exception_catchpoint (b))
6991 && (allflag
6992 || (b->has_locations ()
6993 && (b->has_multiple_locations ()
6994 || !b->first_loc ().enabled
6995 || b->first_loc ().disabled_by_cond))))
6996 {
6997 std::optional<ui_out_emit_list> locations_list;
6998
6999 /* For MI version <= 2, keep the behavior where GDB outputs an invalid
7000 MI record. For later versions, place breakpoint locations in a
7001 list. */
7002 if (uiout->is_mi_like_p () && use_fixed_output)
7003 locations_list.emplace (uiout, "locations");
7004
7005 int n = 1;
7006 for (bp_location &loc : b->locations ())
7007 {
7008 ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
7009 print_one_breakpoint_location (b, &loc, n, last_loc,
7010 allflag, allflag);
7011 n++;
7012 }
7013 }
7014 }
7015 }
7016
7017 static int
7018 breakpoint_address_bits (struct breakpoint *b)
7019 {
7020 int print_address_bits = 0;
7021
7022 for (bp_location &loc : b->locations ())
7023 {
7024 if (!bl_address_is_meaningful (&loc))
7025 continue;
7026
7027 int addr_bit = gdbarch_addr_bit (loc.gdbarch);
7028 if (addr_bit > print_address_bits)
7029 print_address_bits = addr_bit;
7030 }
7031
7032 return print_address_bits;
7033 }
7034
7035 /* See breakpoint.h. */
7036
7037 void
7038 print_breakpoint (breakpoint *b)
7039 {
7040 const bp_location *dummy_loc = nullptr;
7041 print_one_breakpoint (b, &dummy_loc, 0);
7042 }
7043
7044 /* Return true if this breakpoint was set by the user, false if it is
7045 internal or momentary. */
7046
7047 int
7048 user_breakpoint_p (const breakpoint *b)
7049 {
7050 return b->number > 0;
7051 }
7052
7053 /* See breakpoint.h. */
7054
7055 int
7056 pending_breakpoint_p (const breakpoint *b)
7057 {
7058 return !b->has_locations ();
7059 }
7060
7061 /* Print information on breakpoints (including watchpoints and tracepoints).
7062
7063 If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
7064 understood by number_or_range_parser. Only breakpoints included in this
7065 list are then printed.
7066
7067 If SHOW_INTERNAL is true, print internal breakpoints.
7068
7069 If FILTER is non-NULL, call it on each breakpoint and only include the
7070 ones for which it returns true.
7071
7072 Return the total number of breakpoints listed. */
7073
7074 static int
7075 breakpoint_1 (const char *bp_num_list, bool show_internal,
7076 bool (*filter) (const struct breakpoint *))
7077 {
7078 const bp_location *last_loc = nullptr;
7079 int nr_printable_breakpoints;
7080 struct value_print_options opts;
7081 int print_address_bits = 0;
7082 int print_type_col_width = 14;
7083 struct ui_out *uiout = current_uiout;
7084 bool has_disabled_by_cond_location = false;
7085
7086 get_user_print_options (&opts);
7087
7088 /* Compute the number of rows in the table, as well as the size
7089 required for address fields. */
7090 nr_printable_breakpoints = 0;
7091 for (breakpoint &b : all_breakpoints ())
7092 {
7093 /* If we have a filter, only list the breakpoints it accepts. */
7094 if (filter && !filter (&b))
7095 continue;
7096
7097 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
7098 accept. Skip the others. */
7099 if (bp_num_list != NULL && *bp_num_list != '\0')
7100 {
7101 if (show_internal && parse_and_eval_long (bp_num_list) != b.number)
7102 continue;
7103 if (!show_internal && !number_is_in_list (bp_num_list, b.number))
7104 continue;
7105 }
7106
7107 if (show_internal || user_breakpoint_p (&b))
7108 {
7109 int addr_bit, type_len;
7110
7111 addr_bit = breakpoint_address_bits (&b);
7112 if (addr_bit > print_address_bits)
7113 print_address_bits = addr_bit;
7114
7115 type_len = strlen (bptype_string (b.type));
7116 if (type_len > print_type_col_width)
7117 print_type_col_width = type_len;
7118
7119 nr_printable_breakpoints++;
7120 }
7121 }
7122
7123 {
7124 ui_out_emit_table table_emitter (uiout,
7125 opts.addressprint ? 6 : 5,
7126 nr_printable_breakpoints,
7127 "BreakpointTable");
7128
7129 if (nr_printable_breakpoints > 0)
7130 annotate_breakpoints_headers ();
7131 if (nr_printable_breakpoints > 0)
7132 annotate_field (0);
7133 uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
7134 if (nr_printable_breakpoints > 0)
7135 annotate_field (1);
7136 uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
7137 if (nr_printable_breakpoints > 0)
7138 annotate_field (2);
7139 uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
7140 if (nr_printable_breakpoints > 0)
7141 annotate_field (3);
7142 uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
7143 if (opts.addressprint)
7144 {
7145 if (nr_printable_breakpoints > 0)
7146 annotate_field (4);
7147 if (print_address_bits <= 32)
7148 uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
7149 else
7150 uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
7151 }
7152 if (nr_printable_breakpoints > 0)
7153 annotate_field (5);
7154 uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
7155 uiout->table_body ();
7156 if (nr_printable_breakpoints > 0)
7157 annotate_breakpoints_table ();
7158
7159 for (breakpoint &b : all_breakpoints ())
7160 {
7161 QUIT;
7162 /* If we have a filter, only list the breakpoints it accepts. */
7163 if (filter && !filter (&b))
7164 continue;
7165
7166 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
7167 accept. Skip the others. */
7168
7169 if (bp_num_list != NULL && *bp_num_list != '\0')
7170 {
7171 if (show_internal) /* maintenance info breakpoint */
7172 {
7173 if (parse_and_eval_long (bp_num_list) != b.number)
7174 continue;
7175 }
7176 else /* all others */
7177 {
7178 if (!number_is_in_list (bp_num_list, b.number))
7179 continue;
7180 }
7181 }
7182 /* We only print out user settable breakpoints unless the
7183 show_internal is set. */
7184 if (show_internal || user_breakpoint_p (&b))
7185 {
7186 print_one_breakpoint (&b, &last_loc, show_internal);
7187 for (bp_location &loc : b.locations ())
7188 if (loc.disabled_by_cond)
7189 has_disabled_by_cond_location = true;
7190 }
7191 }
7192 }
7193
7194 if (nr_printable_breakpoints == 0)
7195 {
7196 /* If there's a filter, let the caller decide how to report
7197 empty list. */
7198 if (!filter)
7199 {
7200 if (bp_num_list == NULL || *bp_num_list == '\0')
7201 uiout->message ("No breakpoints, watchpoints, tracepoints, "
7202 "or catchpoints.\n");
7203 else
7204 uiout->message ("No breakpoint, watchpoint, tracepoint, "
7205 "or catchpoint matching '%s'.\n", bp_num_list);
7206 }
7207 }
7208 else
7209 {
7210 if (last_loc && !server_command)
7211 set_next_address (last_loc->gdbarch, last_loc->address);
7212
7213 if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
7214 uiout->message (_("(*): Breakpoint condition is invalid at this "
7215 "location.\n"));
7216 }
7217
7218 /* FIXME? Should this be moved up so that it is only called when
7219 there have been breakpoints? */
7220 annotate_breakpoints_table_end ();
7221
7222 return nr_printable_breakpoints;
7223 }
7224
7225 /* Display the value of default-collect in a way that is generally
7226 compatible with the breakpoint list. */
7227
7228 static void
7229 default_collect_info (void)
7230 {
7231 struct ui_out *uiout = current_uiout;
7232
7233 /* If it has no value (which is frequently the case), say nothing; a
7234 message like "No default-collect." gets in user's face when it's
7235 not wanted. */
7236 if (default_collect.empty ())
7237 return;
7238
7239 /* The following phrase lines up nicely with per-tracepoint collect
7240 actions. */
7241 uiout->text ("default collect ");
7242 uiout->field_string ("default-collect", default_collect);
7243 uiout->text (" \n");
7244 }
7245
7246 static void
7247 info_breakpoints_command (const char *args, int from_tty)
7248 {
7249 breakpoint_1 (args, false, NULL);
7250
7251 default_collect_info ();
7252 }
7253
7254 static void
7255 info_watchpoints_command (const char *args, int from_tty)
7256 {
7257 int num_printed = breakpoint_1 (args, false, is_watchpoint);
7258 struct ui_out *uiout = current_uiout;
7259
7260 if (num_printed == 0)
7261 {
7262 if (args == NULL || *args == '\0')
7263 uiout->message ("No watchpoints.\n");
7264 else
7265 uiout->message ("No watchpoint matching '%s'.\n", args);
7266 }
7267 }
7268
7269 static void
7270 maintenance_info_breakpoints (const char *args, int from_tty)
7271 {
7272 breakpoint_1 (args, true, NULL);
7273
7274 default_collect_info ();
7275 }
7276
7277 static bool
7278 breakpoint_has_pc (struct breakpoint *b,
7279 struct program_space *pspace,
7280 CORE_ADDR pc, struct obj_section *section)
7281 {
7282 for (bp_location &bl : b->locations ())
7283 {
7284 if (bl.pspace == pspace
7285 && bl.address == pc
7286 && (!overlay_debugging || bl.section == section))
7287 return true;
7288 }
7289 return false;
7290 }
7291
7292 /* See breakpoint.h. */
7293
7294 void
7295 describe_other_breakpoints (struct gdbarch *gdbarch,
7296 struct program_space *pspace, CORE_ADDR pc,
7297 struct obj_section *section, int thread)
7298 {
7299 int others = 0;
7300
7301 for (breakpoint &b : all_breakpoints ())
7302 others += (user_breakpoint_p (&b)
7303 && breakpoint_has_pc (&b, pspace, pc, section));
7304
7305 if (others > 0)
7306 {
7307 if (others == 1)
7308 gdb_printf (_("Note: breakpoint "));
7309 else /* if (others == ???) */
7310 gdb_printf (_("Note: breakpoints "));
7311 for (breakpoint &b : all_breakpoints ())
7312 if (user_breakpoint_p (&b)
7313 && breakpoint_has_pc (&b, pspace, pc, section))
7314 {
7315 others--;
7316 gdb_printf ("%d", b.number);
7317 if (b.thread == -1 && thread != -1)
7318 gdb_printf (" (all threads)");
7319 else if (b.thread != -1)
7320 {
7321 struct thread_info *thr = find_thread_global_id (b.thread);
7322 gdb_printf (" (thread %s)", print_thread_id (thr));
7323 }
7324 else if (b.task != -1)
7325 gdb_printf (" (task %d)", b.task);
7326 gdb_printf ("%s%s ",
7327 ((b.enable_state == bp_disabled
7328 || b.enable_state == bp_call_disabled)
7329 ? " (disabled)"
7330 : ""),
7331 (others > 1) ? ","
7332 : ((others == 1) ? " and" : ""));
7333 }
7334 current_uiout->message (_("also set at pc %ps.\n"),
7335 styled_string (address_style.style (),
7336 paddress (gdbarch, pc)));
7337 }
7338 }
7339 \f
7340
7341 /* Return true iff it is meaningful to use the address member of LOC.
7342 For some breakpoint types, the locations' address members are
7343 irrelevant and it makes no sense to attempt to compare them to
7344 other addresses (or use them for any other purpose either).
7345
7346 More specifically, software watchpoints and catchpoints that are
7347 not backed by breakpoints always have a zero valued location
7348 address and we don't want to mark breakpoints of any of these types
7349 to be a duplicate of an actual breakpoint location at address
7350 zero. */
7351
7352 static bool
7353 bl_address_is_meaningful (const bp_location *loc)
7354 {
7355 return loc->loc_type != bp_loc_other;
7356 }
7357
7358 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7359 true if LOC1 and LOC2 represent the same watchpoint location. */
7360
7361 static bool
7362 watchpoint_locations_match (const struct bp_location *loc1,
7363 const struct bp_location *loc2)
7364 {
7365 watchpoint *w1 = gdb::checked_static_cast<watchpoint *> (loc1->owner);
7366 watchpoint *w2 = gdb::checked_static_cast<watchpoint *> (loc2->owner);
7367
7368 /* Both of them must exist. */
7369 gdb_assert (w1 != NULL);
7370 gdb_assert (w2 != NULL);
7371
7372 /* If the target can evaluate the condition expression in hardware,
7373 then we we need to insert both watchpoints even if they are at
7374 the same place. Otherwise the watchpoint will only trigger when
7375 the condition of whichever watchpoint was inserted evaluates to
7376 true, not giving a chance for GDB to check the condition of the
7377 other watchpoint. */
7378 if ((w1->cond_exp
7379 && target_can_accel_watchpoint_condition (loc1->address,
7380 loc1->length,
7381 loc1->watchpoint_type,
7382 w1->cond_exp.get ()))
7383 || (w2->cond_exp
7384 && target_can_accel_watchpoint_condition (loc2->address,
7385 loc2->length,
7386 loc2->watchpoint_type,
7387 w2->cond_exp.get ())))
7388 return false;
7389
7390 /* Note that this checks the owner's type, not the location's. In
7391 case the target does not support read watchpoints, but does
7392 support access watchpoints, we'll have bp_read_watchpoint
7393 watchpoints with hw_access locations. Those should be considered
7394 duplicates of hw_read locations. The hw_read locations will
7395 become hw_access locations later. */
7396 return (loc1->owner->type == loc2->owner->type
7397 && loc1->pspace->aspace == loc2->pspace->aspace
7398 && loc1->address == loc2->address
7399 && loc1->length == loc2->length);
7400 }
7401
7402 /* See breakpoint.h. */
7403
7404 int
7405 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
7406 const address_space *aspace2, CORE_ADDR addr2)
7407 {
7408 return ((gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7409 || aspace1 == aspace2)
7410 && addr1 == addr2);
7411 }
7412
7413 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7414 {ASPACE1,ADDR1,LEN1}. In most targets, this can only be true if ASPACE1
7415 matches ASPACE2. On targets that have global breakpoints, the address
7416 space doesn't really matter. */
7417
7418 static bool
7419 breakpoint_address_match_range (const address_space *aspace1,
7420 CORE_ADDR addr1,
7421 int len1, const address_space *aspace2,
7422 CORE_ADDR addr2)
7423 {
7424 return ((gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7425 || aspace1 == aspace2)
7426 && addr2 >= addr1 && addr2 < addr1 + len1);
7427 }
7428
7429 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL. BL may be
7430 a ranged breakpoint. In most targets, a match happens only if ASPACE
7431 matches the breakpoint's address space. On targets that have global
7432 breakpoints, the address space doesn't really matter. */
7433
7434 static bool
7435 breakpoint_location_address_match (struct bp_location *bl,
7436 const address_space *aspace,
7437 CORE_ADDR addr)
7438 {
7439 return (breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
7440 aspace, addr)
7441 || (bl->length
7442 && breakpoint_address_match_range (bl->pspace->aspace.get (),
7443 bl->address, bl->length,
7444 aspace, addr)));
7445 }
7446
7447 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7448 breakpoint BL. BL may be a ranged breakpoint. In most targets, a
7449 match happens only if ASPACE matches the breakpoint's address
7450 space. On targets that have global breakpoints, the address space
7451 doesn't really matter. */
7452
7453 static bool
7454 breakpoint_location_address_range_overlap (struct bp_location *bl,
7455 const address_space *aspace,
7456 CORE_ADDR addr, int len)
7457 {
7458 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7459 || bl->pspace->aspace.get () == aspace)
7460 {
7461 int bl_len = bl->length != 0 ? bl->length : 1;
7462
7463 if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7464 return 1;
7465 }
7466 return 0;
7467 }
7468
7469 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7470 Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7471 true, otherwise returns false. */
7472
7473 static bool
7474 tracepoint_locations_match (const struct bp_location *loc1,
7475 const struct bp_location *loc2)
7476 {
7477 if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7478 /* Since tracepoint locations are never duplicated with others', tracepoint
7479 locations at the same address of different tracepoints are regarded as
7480 different locations. */
7481 return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7482 else
7483 return false;
7484 }
7485
7486 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7487 (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
7488 the same location. If SW_HW_BPS_MATCH is true, then software
7489 breakpoint locations and hardware breakpoint locations match,
7490 otherwise they don't. */
7491
7492 static bool
7493 breakpoint_locations_match (const struct bp_location *loc1,
7494 const struct bp_location *loc2,
7495 bool sw_hw_bps_match)
7496 {
7497 int hw_point1, hw_point2;
7498
7499 /* Both of them must not be in moribund_locations. */
7500 gdb_assert (loc1->owner != NULL);
7501 gdb_assert (loc2->owner != NULL);
7502
7503 hw_point1 = is_hardware_watchpoint (loc1->owner);
7504 hw_point2 = is_hardware_watchpoint (loc2->owner);
7505
7506 if (hw_point1 != hw_point2)
7507 return false;
7508 else if (hw_point1)
7509 return watchpoint_locations_match (loc1, loc2);
7510 else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7511 return tracepoint_locations_match (loc1, loc2);
7512 else
7513 /* We compare bp_location.length in order to cover ranged
7514 breakpoints. Keep this in sync with
7515 bp_location_ptr_is_less_than. */
7516 return (breakpoint_address_match (loc1->pspace->aspace.get (),
7517 loc1->address,
7518 loc2->pspace->aspace.get (),
7519 loc2->address)
7520 && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
7521 && loc1->length == loc2->length);
7522 }
7523
7524 static void
7525 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7526 int bnum, bool have_bnum)
7527 {
7528 /* The longest string possibly returned by hex_string_custom
7529 is 50 chars. These must be at least that big for safety. */
7530 char astr1[64];
7531 char astr2[64];
7532
7533 strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7534 strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7535 if (have_bnum)
7536 warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7537 bnum, astr1, astr2);
7538 else
7539 warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7540 }
7541
7542 /* Adjust a breakpoint's address to account for architectural
7543 constraints on breakpoint placement. Return the adjusted address.
7544 Note: Very few targets require this kind of adjustment. For most
7545 targets, this function is simply the identity function. */
7546
7547 static CORE_ADDR
7548 adjust_breakpoint_address (struct gdbarch *gdbarch,
7549 CORE_ADDR bpaddr, enum bptype bptype,
7550 struct program_space *pspace)
7551 {
7552 gdb_assert (pspace != nullptr);
7553
7554 if (bptype == bp_watchpoint
7555 || bptype == bp_hardware_watchpoint
7556 || bptype == bp_read_watchpoint
7557 || bptype == bp_access_watchpoint
7558 || bptype == bp_catchpoint)
7559 {
7560 /* Watchpoints and the various bp_catch_* eventpoints should not
7561 have their addresses modified. */
7562 return bpaddr;
7563 }
7564 else if (bptype == bp_single_step)
7565 {
7566 /* Single-step breakpoints should not have their addresses
7567 modified. If there's any architectural constrain that
7568 applies to this address, then it should have already been
7569 taken into account when the breakpoint was created in the
7570 first place. If we didn't do this, stepping through e.g.,
7571 Thumb-2 IT blocks would break. */
7572 return bpaddr;
7573 }
7574 else
7575 {
7576 CORE_ADDR adjusted_bpaddr = bpaddr;
7577
7578 /* Some targets have architectural constraints on the placement
7579 of breakpoint instructions. Obtain the adjusted address. */
7580 if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7581 {
7582 /* Targets that implement this adjustment function will likely
7583 inspect either the symbol table, target memory at BPADDR, or
7584 even state registers, so ensure a suitable thread (and its
7585 associated program space) are currently selected. */
7586 scoped_restore_current_pspace_and_thread restore_pspace_thread;
7587 switch_to_program_space_and_thread (pspace);
7588 adjusted_bpaddr
7589 = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7590 }
7591
7592 adjusted_bpaddr
7593 = gdbarch_remove_non_address_bits_breakpoint (gdbarch, adjusted_bpaddr);
7594
7595 /* An adjusted breakpoint address can significantly alter
7596 a user's expectations. Print a warning if an adjustment
7597 is required. */
7598 if (adjusted_bpaddr != bpaddr)
7599 breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, false);
7600
7601 return adjusted_bpaddr;
7602 }
7603 }
7604
7605 static bp_loc_type
7606 bp_location_from_bp_type (bptype type)
7607 {
7608 switch (type)
7609 {
7610 case bp_breakpoint:
7611 case bp_single_step:
7612 case bp_until:
7613 case bp_finish:
7614 case bp_longjmp:
7615 case bp_longjmp_resume:
7616 case bp_longjmp_call_dummy:
7617 case bp_exception:
7618 case bp_exception_resume:
7619 case bp_step_resume:
7620 case bp_hp_step_resume:
7621 case bp_watchpoint_scope:
7622 case bp_call_dummy:
7623 case bp_std_terminate:
7624 case bp_shlib_event:
7625 case bp_thread_event:
7626 case bp_overlay_event:
7627 case bp_jit_event:
7628 case bp_longjmp_master:
7629 case bp_std_terminate_master:
7630 case bp_exception_master:
7631 case bp_gnu_ifunc_resolver:
7632 case bp_gnu_ifunc_resolver_return:
7633 case bp_dprintf:
7634 return bp_loc_software_breakpoint;
7635
7636 case bp_hardware_breakpoint:
7637 return bp_loc_hardware_breakpoint;
7638
7639 case bp_hardware_watchpoint:
7640 case bp_read_watchpoint:
7641 case bp_access_watchpoint:
7642 return bp_loc_hardware_watchpoint;
7643
7644 case bp_watchpoint:
7645 return bp_loc_software_watchpoint;
7646
7647 case bp_tracepoint:
7648 case bp_fast_tracepoint:
7649 case bp_static_tracepoint:
7650 case bp_static_marker_tracepoint:
7651 return bp_loc_tracepoint;
7652
7653 case bp_catchpoint:
7654 return bp_loc_other;
7655
7656 default:
7657 internal_error (_("unknown breakpoint type"));
7658 }
7659 }
7660
7661 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7662 {
7663 this->owner = owner;
7664 this->cond_bytecode = NULL;
7665 this->shlib_disabled = 0;
7666 this->enabled = 1;
7667 this->disabled_by_cond = false;
7668
7669 this->loc_type = type;
7670
7671 if (this->loc_type == bp_loc_software_breakpoint
7672 || this->loc_type == bp_loc_hardware_breakpoint)
7673 mark_breakpoint_location_modified (this);
7674
7675 incref ();
7676 }
7677
7678 bp_location::bp_location (breakpoint *owner)
7679 : bp_location::bp_location (owner,
7680 bp_location_from_bp_type (owner->type))
7681 {
7682 }
7683
7684 /* See breakpoint.h. */
7685
7686 std::string
7687 bp_location::to_string () const
7688 {
7689 string_file stb;
7690 ui_out_redirect_pop redir (current_uiout, &stb);
7691 print_breakpoint_location (this->owner, this);
7692 return stb.release ();
7693 }
7694
7695 /* Decrement reference count. If the reference count reaches 0,
7696 destroy the bp_location. Sets *BLP to NULL. */
7697
7698 static void
7699 decref_bp_location (struct bp_location **blp)
7700 {
7701 bp_location_ref_policy::decref (*blp);
7702 *blp = NULL;
7703 }
7704
7705 /* Add breakpoint B at the end of the global breakpoint chain. */
7706
7707 static breakpoint *
7708 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7709 {
7710 /* Add this breakpoint to the end of the chain so that a list of
7711 breakpoints will come out in order of increasing numbers. */
7712
7713 breakpoint_chain.push_back (*b.release ());
7714
7715 return &breakpoint_chain.back ();
7716 }
7717
7718 /* Initialize loc->function_name. */
7719
7720 static void
7721 set_breakpoint_location_function (struct bp_location *loc)
7722 {
7723 gdb_assert (loc->owner != NULL);
7724
7725 if (loc->owner->type == bp_breakpoint
7726 || loc->owner->type == bp_hardware_breakpoint
7727 || is_tracepoint (loc->owner))
7728 {
7729 const char *function_name;
7730
7731 if (loc->msymbol != NULL
7732 && (loc->msymbol->type () == mst_text_gnu_ifunc
7733 || loc->msymbol->type () == mst_data_gnu_ifunc))
7734 {
7735 struct breakpoint *b = loc->owner;
7736
7737 function_name = loc->msymbol->linkage_name ();
7738
7739 if (b->type == bp_breakpoint
7740 && b->has_single_location ()
7741 && b->related_breakpoint == b)
7742 {
7743 /* Create only the whole new breakpoint of this type but do not
7744 mess more complicated breakpoints with multiple locations. */
7745 b->type = bp_gnu_ifunc_resolver;
7746 /* Remember the resolver's address for use by the return
7747 breakpoint. */
7748 loc->related_address = loc->address;
7749 }
7750 }
7751 else
7752 find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7753
7754 if (function_name)
7755 loc->function_name = make_unique_xstrdup (function_name);
7756 }
7757 }
7758
7759 /* Attempt to determine architecture of location identified by SAL. */
7760 struct gdbarch *
7761 get_sal_arch (struct symtab_and_line sal)
7762 {
7763 if (sal.section)
7764 return sal.section->objfile->arch ();
7765 if (sal.symtab)
7766 return sal.symtab->compunit ()->objfile ()->arch ();
7767
7768 return NULL;
7769 }
7770
7771 /* Call this routine when stepping and nexting to enable a breakpoint
7772 if we do a longjmp() or 'throw' in TP. FRAME is the frame which
7773 initiated the operation. */
7774
7775 void
7776 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7777 {
7778 int thread = tp->global_num;
7779
7780 /* To avoid having to rescan all objfile symbols at every step,
7781 we maintain a list of continually-inserted but always disabled
7782 longjmp "master" breakpoints. Here, we simply create momentary
7783 clones of those and enable them for the requested thread. */
7784 for (breakpoint &b : all_breakpoints_safe ())
7785 if (b.pspace == current_program_space
7786 && (b.type == bp_longjmp_master
7787 || b.type == bp_exception_master))
7788 {
7789 bptype type = b.type == bp_longjmp_master ? bp_longjmp : bp_exception;
7790 /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7791 after their removal. */
7792 momentary_breakpoint_from_master (&b, type, 1, thread);
7793 }
7794
7795 tp->initiating_frame = frame;
7796 }
7797
7798 /* Delete all longjmp breakpoints from THREAD. */
7799 void
7800 delete_longjmp_breakpoint (int thread)
7801 {
7802 for (breakpoint &b : all_breakpoints_safe ())
7803 if (b.type == bp_longjmp || b.type == bp_exception)
7804 {
7805 if (b.thread == thread)
7806 {
7807 gdb_assert (b.inferior == -1);
7808 delete_breakpoint (&b);
7809 }
7810 }
7811 }
7812
7813 void
7814 delete_longjmp_breakpoint_at_next_stop (int thread)
7815 {
7816 for (breakpoint &b : all_breakpoints_safe ())
7817 if (b.type == bp_longjmp || b.type == bp_exception)
7818 {
7819 if (b.thread == thread)
7820 {
7821 gdb_assert (b.inferior == -1);
7822 b.disposition = disp_del_at_next_stop;
7823 }
7824 }
7825 }
7826
7827 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7828 INFERIOR_PTID thread. Chain them all by RELATED_BREAKPOINT and return
7829 pointer to any of them. Return NULL if this system cannot place longjmp
7830 breakpoints. */
7831
7832 struct breakpoint *
7833 set_longjmp_breakpoint_for_call_dummy (void)
7834 {
7835 breakpoint *retval = nullptr;
7836
7837 for (breakpoint &b : all_breakpoints ())
7838 if (b.pspace == current_program_space && b.type == bp_longjmp_master)
7839 {
7840 int thread = inferior_thread ()->global_num;
7841 breakpoint *new_b
7842 = momentary_breakpoint_from_master (&b, bp_longjmp_call_dummy,
7843 1, thread);
7844
7845 /* Link NEW_B into the chain of RETVAL breakpoints. */
7846
7847 gdb_assert (new_b->related_breakpoint == new_b);
7848 if (retval == NULL)
7849 retval = new_b;
7850 new_b->related_breakpoint = retval;
7851 while (retval->related_breakpoint != new_b->related_breakpoint)
7852 retval = retval->related_breakpoint;
7853 retval->related_breakpoint = new_b;
7854 }
7855
7856 return retval;
7857 }
7858
7859 /* Verify all existing dummy frames and their associated breakpoints for
7860 TP. Remove those which can no longer be found in the current frame
7861 stack.
7862
7863 If the unwind fails then there is not sufficient information to discard
7864 dummy frames. In this case, elide the clean up and the dummy frames will
7865 be cleaned up next time this function is called from a location where
7866 unwinding is possible. */
7867
7868 void
7869 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7870 {
7871 /* We would need to delete breakpoints other than the current one while
7872 iterating, so all_breakpoints_safe is not sufficient to make that safe.
7873 Save all breakpoints to delete in that set and delete them at the end. */
7874 gdb::unordered_set<breakpoint *> to_delete;
7875
7876 for (struct breakpoint &b : all_breakpoints ())
7877 {
7878 if (b.type == bp_longjmp_call_dummy && b.thread == tp->global_num)
7879 {
7880 gdb_assert (b.inferior == -1);
7881 struct breakpoint *dummy_b = b.related_breakpoint;
7882
7883 /* Find the bp_call_dummy breakpoint in the list of breakpoints
7884 chained off b->related_breakpoint. */
7885 while (dummy_b != &b && dummy_b->type != bp_call_dummy)
7886 dummy_b = dummy_b->related_breakpoint;
7887
7888 /* If there was no bp_call_dummy breakpoint then there's nothing
7889 more to do. Or, if the dummy frame associated with the
7890 bp_call_dummy is still on the stack then we need to leave this
7891 bp_call_dummy in place. */
7892 if (dummy_b->type != bp_call_dummy
7893 || frame_find_by_id (dummy_b->frame_id) != NULL)
7894 continue;
7895
7896 /* We didn't find the dummy frame on the stack, this could be
7897 because we have longjmp'd to a stack frame that is previous to
7898 the dummy frame, or it could be because the stack unwind is
7899 broken at some point between the longjmp frame and the dummy
7900 frame.
7901
7902 Next we figure out why the stack unwind stopped. If it looks
7903 like the unwind is complete then we assume the dummy frame has
7904 been jumped over, however, if the unwind stopped for an
7905 unexpected reason then we assume the stack unwind is currently
7906 broken, and that we will (eventually) return to the dummy
7907 frame.
7908
7909 It might be tempting to consider using frame_id_inner here, but
7910 that is not safe. There is no guarantee that the stack frames
7911 we are looking at here are even on the same stack as the
7912 original dummy frame, hence frame_id_inner can't be used. See
7913 the comments on frame_id_inner for more details. */
7914 bool unwind_finished_unexpectedly = false;
7915 for (frame_info_ptr fi = get_current_frame (); fi != nullptr; )
7916 {
7917 frame_info_ptr prev = get_prev_frame (fi);
7918 if (prev == nullptr)
7919 {
7920 /* FI is the last stack frame. Why did this frame not
7921 unwind further? */
7922 auto stop_reason = get_frame_unwind_stop_reason (fi);
7923 if (stop_reason != UNWIND_NO_REASON
7924 && stop_reason != UNWIND_OUTERMOST)
7925 unwind_finished_unexpectedly = true;
7926 }
7927 fi = prev;
7928 }
7929 if (unwind_finished_unexpectedly)
7930 continue;
7931
7932 dummy_frame_discard (dummy_b->frame_id, tp);
7933
7934 for (breakpoint *related_breakpoint = b.related_breakpoint;
7935 related_breakpoint != &b;
7936 related_breakpoint = related_breakpoint->related_breakpoint)
7937 to_delete.insert (b.related_breakpoint);
7938
7939 to_delete.insert (&b);
7940 }
7941 }
7942
7943 for (breakpoint *b : to_delete)
7944 delete_breakpoint (b);
7945 }
7946
7947 void
7948 enable_overlay_breakpoints (void)
7949 {
7950 for (breakpoint &b : all_breakpoints ())
7951 if (b.type == bp_overlay_event)
7952 {
7953 b.enable_state = bp_enabled;
7954 update_global_location_list (UGLL_MAY_INSERT);
7955 overlay_events_enabled = 1;
7956 }
7957 }
7958
7959 void
7960 disable_overlay_breakpoints (void)
7961 {
7962 for (breakpoint &b : all_breakpoints ())
7963 if (b.type == bp_overlay_event)
7964 {
7965 b.enable_state = bp_disabled;
7966 update_global_location_list (UGLL_DONT_INSERT);
7967 overlay_events_enabled = 0;
7968 }
7969 }
7970
7971 /* Set an active std::terminate breakpoint for each std::terminate
7972 master breakpoint. */
7973 void
7974 set_std_terminate_breakpoint (void)
7975 {
7976 for (breakpoint &b : all_breakpoints_safe ())
7977 if (b.pspace == current_program_space
7978 && b.type == bp_std_terminate_master)
7979 {
7980 momentary_breakpoint_from_master (&b, bp_std_terminate, 1,
7981 inferior_thread ()->global_num);
7982 }
7983 }
7984
7985 /* Delete all the std::terminate breakpoints. */
7986 void
7987 delete_std_terminate_breakpoint (void)
7988 {
7989 for (breakpoint &b : all_breakpoints_safe ())
7990 if (b.type == bp_std_terminate)
7991 delete_breakpoint (&b);
7992 }
7993
7994 struct breakpoint *
7995 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7996 {
7997 struct breakpoint *b;
7998
7999 b = create_internal_breakpoint (gdbarch, address, bp_thread_event);
8000
8001 b->enable_state = bp_enabled;
8002 /* locspec has to be used or breakpoint_re_set will delete me. */
8003 b->locspec = new_address_location_spec (b->first_loc ().address, NULL, 0);
8004
8005 update_global_location_list_nothrow (UGLL_MAY_INSERT);
8006
8007 return b;
8008 }
8009
8010 struct lang_and_radix
8011 {
8012 enum language lang;
8013 int radix;
8014 };
8015
8016 /* Create a breakpoint for JIT code registration and unregistration. */
8017
8018 struct breakpoint *
8019 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
8020 {
8021 return create_internal_breakpoint (gdbarch, address, bp_jit_event);
8022 }
8023
8024 /* Remove JIT code registration and unregistration breakpoint(s). */
8025
8026 void
8027 remove_jit_event_breakpoints (void)
8028 {
8029 for (breakpoint &b : all_breakpoints_safe ())
8030 if (b.type == bp_jit_event
8031 && b.first_loc ().pspace == current_program_space)
8032 delete_breakpoint (&b);
8033 }
8034
8035 void
8036 remove_solib_event_breakpoints (void)
8037 {
8038 for (breakpoint &b : all_breakpoints_safe ())
8039 if (b.type == bp_shlib_event
8040 && b.first_loc ().pspace == current_program_space)
8041 delete_breakpoint (&b);
8042 }
8043
8044 /* See breakpoint.h. */
8045
8046 void
8047 remove_solib_event_breakpoints_at_next_stop (void)
8048 {
8049 for (breakpoint &b : all_breakpoints_safe ())
8050 if (b.type == bp_shlib_event
8051 && b.first_loc ().pspace == current_program_space)
8052 b.disposition = disp_del_at_next_stop;
8053 }
8054
8055 /* Helper for create_solib_event_breakpoint /
8056 create_and_insert_solib_event_breakpoint. Allows specifying which
8057 INSERT_MODE to pass through to update_global_location_list. */
8058
8059 static struct breakpoint *
8060 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
8061 enum ugll_insert_mode insert_mode)
8062 {
8063 struct breakpoint *b;
8064
8065 b = create_internal_breakpoint (gdbarch, address, bp_shlib_event);
8066 update_global_location_list_nothrow (insert_mode);
8067 return b;
8068 }
8069
8070 struct breakpoint *
8071 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
8072 {
8073 return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
8074 }
8075
8076 /* See breakpoint.h. */
8077
8078 struct breakpoint *
8079 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
8080 {
8081 struct breakpoint *b;
8082
8083 /* Explicitly tell update_global_location_list to insert
8084 locations. */
8085 b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
8086 if (!b->first_loc ().inserted)
8087 {
8088 delete_breakpoint (b);
8089 return NULL;
8090 }
8091 return b;
8092 }
8093
8094 /* Disable any breakpoints and tracepoints that are in SOLIB upon
8095 notification of unloaded_shlib. Only apply to enabled breakpoints,
8096 disabled ones can just stay disabled.
8097
8098 When STILL_IN_USE is true, SOLIB hasn't really been unmapped from
8099 the inferior. In this case, don't disable anything.
8100
8101 When SILENT is false notify the user if any breakpoints are disabled,
8102 otherwise, still disable the breakpoints, but don't tell the user. */
8103
8104 static void
8105 disable_breakpoints_in_unloaded_shlib (program_space *pspace, const solib &solib,
8106 bool still_in_use, bool silent)
8107 {
8108 if (still_in_use)
8109 return;
8110
8111 bool disabled_shlib_breaks = false;
8112
8113 for (breakpoint &b : all_breakpoints ())
8114 {
8115 bool bp_modified = false;
8116
8117 for (bp_location &loc : b.locations ())
8118 {
8119 if (pspace != loc.pspace || loc.shlib_disabled)
8120 continue;
8121
8122 if (loc.loc_type != bp_loc_hardware_breakpoint
8123 && loc.loc_type != bp_loc_software_breakpoint
8124 && !is_tracepoint (&b))
8125 continue;
8126
8127 if (!solib_contains_address_p (solib, loc.address))
8128 continue;
8129
8130 loc.shlib_disabled = 1;
8131
8132 /* At this point, we don't know whether the shared library
8133 was unmapped from the inferior or not, so leave the
8134 inserted flag alone. We'll handle failure to uninsert
8135 quietly, in case the library was indeed unmapped.
8136
8137 The test gdb.base/nostdlib.exp when run on AArch64
8138 GNU/Linux using glibc will cause the dynamic linker to be
8139 unloaded from the inferior, but the linker will never be
8140 unmapped. Additionally, at the time the dynamic linker
8141 is unloaded the inferior will be stopped within the
8142 dynamic linker.
8143
8144 If we clear the inserted flag here then GDB will fail to
8145 remove the internal breakpoints from the dynamic linker
8146 leading to unexpected SIGTRAPs. */
8147
8148 bp_modified = true;
8149
8150 if (!disabled_shlib_breaks && !silent && user_breakpoint_p (&b))
8151 {
8152 target_terminal::ours_for_output ();
8153 warning (_("Temporarily disabling breakpoints "
8154 "for unloaded shared library \"%s\""),
8155 solib.name.c_str ());
8156 disabled_shlib_breaks = true;
8157 }
8158 }
8159
8160 if (bp_modified)
8161 notify_breakpoint_modified (&b);
8162 }
8163 }
8164
8165 /* Disable any breakpoints and tracepoints in OBJFILE upon
8166 notification of free_objfile. Only apply to enabled breakpoints,
8167 disabled ones can just stay disabled. */
8168
8169 static void
8170 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
8171 {
8172 /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
8173 managed by the user with add-symbol-file/remove-symbol-file.
8174 Similarly to how breakpoints in shared libraries are handled in
8175 response to "nosharedlibrary", mark breakpoints in such modules
8176 shlib_disabled so they end up uninserted on the next global
8177 location list update. Shared libraries not loaded by the user
8178 aren't handled here -- they're already handled in
8179 disable_breakpoints_in_unloaded_shlib, called by solib.c's
8180 solib_unloaded observer. We skip objfiles that are not
8181 OBJF_SHARED as those aren't considered dynamic objects (e.g. the
8182 main objfile). */
8183 if ((objfile->flags & OBJF_SHARED) == 0
8184 || (objfile->flags & OBJF_USERLOADED) == 0)
8185 return;
8186
8187 for (breakpoint &b : all_breakpoints ())
8188 {
8189 bool bp_modified = false;
8190
8191 if (!is_breakpoint (&b) && !is_tracepoint (&b))
8192 continue;
8193
8194 for (bp_location &loc : b.locations ())
8195 {
8196 CORE_ADDR loc_addr = loc.address;
8197
8198 if (loc.loc_type != bp_loc_hardware_breakpoint
8199 && loc.loc_type != bp_loc_software_breakpoint)
8200 continue;
8201
8202 if (loc.shlib_disabled != 0)
8203 continue;
8204
8205 if (objfile->pspace () != loc.pspace)
8206 continue;
8207
8208 if (is_addr_in_objfile (loc_addr, objfile))
8209 {
8210 loc.shlib_disabled = 1;
8211 /* At this point, we don't know whether the object was
8212 unmapped from the inferior or not, so leave the
8213 inserted flag alone. We'll handle failure to
8214 uninsert quietly, in case the object was indeed
8215 unmapped. */
8216
8217 mark_breakpoint_location_modified (&loc);
8218
8219 bp_modified = true;
8220 }
8221 }
8222
8223 if (bp_modified)
8224 notify_breakpoint_modified (&b);
8225 }
8226 }
8227
8228 /* See breakpoint.h. */
8229
8230 breakpoint::breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
8231 bool temp, const char *cond_string_)
8232 : type (bptype),
8233 disposition (temp ? disp_del : disp_donttouch),
8234 gdbarch (gdbarch_),
8235 language (current_language->la_language),
8236 input_radix (::input_radix),
8237 cond_string (cond_string_ != nullptr
8238 ? make_unique_xstrdup (cond_string_)
8239 : nullptr),
8240 related_breakpoint (this)
8241 {
8242 }
8243
8244 /* See breakpoint.h. */
8245
8246 catchpoint::catchpoint (struct gdbarch *gdbarch, bool temp,
8247 const char *cond_string)
8248 : breakpoint (gdbarch, bp_catchpoint, temp, cond_string)
8249 {
8250 add_dummy_location (this, current_program_space);
8251
8252 pspace = current_program_space;
8253 }
8254
8255 /* See breakpoint.h. */
8256
8257 void
8258 catchpoint::re_set (program_space *filter_pspace)
8259 {
8260 /* All catchpoints are associated with a specific program_space. */
8261 gdb_assert (pspace != nullptr);
8262
8263 /* If only a single program space changed, and it's not the program space
8264 for which this catchpoint applies, then there's nothing to do. */
8265 if (filter_pspace != nullptr && filter_pspace != pspace)
8266 return;
8267
8268 /* Catchpoints have a single dummy location. */
8269 gdb_assert (locations ().size () == 1);
8270 bp_location &bl = m_locations.front ();
8271
8272 if (cond_string == nullptr)
8273 {
8274 /* It shouldn't be possible to have a parsed condition expression
8275 cached on this location if the catchpoint doesn't have a condition
8276 string set. */
8277 gdb_assert (bl.cond == nullptr);
8278
8279 /* Nothing to re-compute, and the catchpoint cannot change. */
8280 return;
8281 }
8282
8283 bool previous_disabled_by_cond = bl.disabled_by_cond;
8284
8285 /* Start by marking the location disabled and discarding the previously
8286 computed condition expression. Now if we get an exception, even if
8287 it's a quit exception, we'll leave the location disabled and there
8288 will be no (possibly invalid) expression cached. */
8289 bl.disabled_by_cond = true;
8290 bl.cond = nullptr;
8291
8292 const char *s = cond_string.get ();
8293 try
8294 {
8295 switch_to_program_space_and_thread (pspace);
8296
8297 bl.cond = parse_exp_1 (&s, bl.address, block_for_pc (bl.address),
8298 nullptr);
8299 bl.disabled_by_cond = false;
8300 }
8301 catch (const gdb_exception_error &e)
8302 {
8303 /* Any exception thrown must be from either the parse_exp_1 or
8304 earlier in the try block. As such the following two asserts
8305 should be true. */
8306 gdb_assert (bl.disabled_by_cond);
8307 gdb_assert (bl.cond == nullptr);
8308 }
8309
8310 if (previous_disabled_by_cond != bl.disabled_by_cond)
8311 notify_breakpoint_modified (this);
8312 }
8313
8314 /* Notify interpreters and observers that breakpoint B was created. */
8315
8316 static void
8317 notify_breakpoint_created (breakpoint *b)
8318 {
8319 interps_notify_breakpoint_created (b);
8320 gdb::observers::breakpoint_created.notify (b);
8321 }
8322
8323 breakpoint *
8324 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8325 {
8326 breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8327 set_breakpoint_number (internal, b);
8328 if (is_tracepoint (b))
8329 set_tracepoint_count (breakpoint_count);
8330 if (!internal)
8331 mention (b);
8332
8333 notify_breakpoint_created (b);
8334
8335 if (update_gll)
8336 update_global_location_list (UGLL_MAY_INSERT);
8337
8338 return b;
8339 }
8340
8341 static int
8342 hw_breakpoint_used_count (void)
8343 {
8344 int i = 0;
8345
8346 for (breakpoint &b : all_breakpoints ())
8347 if (b.type == bp_hardware_breakpoint && breakpoint_enabled (&b))
8348 for (bp_location &bl : b.locations ())
8349 {
8350 /* Special types of hardware breakpoints may use more than
8351 one register. */
8352 i += b.resources_needed (&bl);
8353 }
8354
8355 return i;
8356 }
8357
8358 /* Returns the resources B would use if it were a hardware
8359 watchpoint. */
8360
8361 static int
8362 hw_watchpoint_use_count (struct breakpoint *b)
8363 {
8364 int i = 0;
8365
8366 if (!breakpoint_enabled (b))
8367 return 0;
8368
8369 for (bp_location &bl : b->locations ())
8370 {
8371 /* Special types of hardware watchpoints may use more than
8372 one register. */
8373 i += b->resources_needed (&bl);
8374 }
8375
8376 return i;
8377 }
8378
8379 /* Returns the sum the used resources of all hardware watchpoints of
8380 type TYPE in the breakpoints list. Also returns in OTHER_TYPE_USED
8381 the sum of the used resources of all hardware watchpoints of other
8382 types _not_ TYPE. */
8383
8384 static int
8385 hw_watchpoint_used_count_others (struct breakpoint *except,
8386 enum bptype type, int *other_type_used)
8387 {
8388 int i = 0;
8389
8390 *other_type_used = 0;
8391 for (breakpoint &b : all_breakpoints ())
8392 {
8393 if (&b == except)
8394 continue;
8395 if (!breakpoint_enabled (&b))
8396 continue;
8397
8398 if (b.type == type)
8399 i += hw_watchpoint_use_count (&b);
8400 else if (is_hardware_watchpoint (&b))
8401 *other_type_used = 1;
8402 }
8403
8404 return i;
8405 }
8406
8407 void
8408 disable_watchpoints_before_interactive_call_start (void)
8409 {
8410 for (breakpoint &b : all_breakpoints ())
8411 if (is_watchpoint (&b) && breakpoint_enabled (&b))
8412 {
8413 b.enable_state = bp_call_disabled;
8414 update_global_location_list (UGLL_DONT_INSERT);
8415 }
8416 }
8417
8418 void
8419 enable_watchpoints_after_interactive_call_stop (void)
8420 {
8421 for (breakpoint &b : all_breakpoints ())
8422 if (is_watchpoint (&b) && b.enable_state == bp_call_disabled)
8423 {
8424 b.enable_state = bp_enabled;
8425 update_global_location_list (UGLL_MAY_INSERT);
8426 }
8427 }
8428
8429 void
8430 disable_breakpoints_before_startup (void)
8431 {
8432 current_program_space->executing_startup = 1;
8433 update_global_location_list (UGLL_DONT_INSERT);
8434 }
8435
8436 void
8437 enable_breakpoints_after_startup (void)
8438 {
8439 current_program_space->executing_startup = 0;
8440 breakpoint_re_set ();
8441 }
8442
8443 /* Allocate a new momentary breakpoint. */
8444
8445 template<typename... Arg>
8446 static momentary_breakpoint *
8447 new_momentary_breakpoint (struct gdbarch *gdbarch, enum bptype type,
8448 Arg&&... args)
8449 {
8450 if (type == bp_longjmp || type == bp_exception)
8451 return new longjmp_breakpoint (gdbarch, type,
8452 std::forward<Arg> (args)...);
8453 else
8454 return new momentary_breakpoint (gdbarch, type,
8455 std::forward<Arg> (args)...);
8456 }
8457
8458 /* Set a momentary breakpoint of type TYPE at address specified by
8459 SAL. If FRAME_ID is valid, the breakpoint is restricted to that
8460 frame. */
8461
8462 breakpoint_up
8463 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8464 struct frame_id frame_id, enum bptype type)
8465 {
8466 /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8467 tail-called one. */
8468 gdb_assert (!frame_id_artificial_p (frame_id));
8469
8470 std::unique_ptr<momentary_breakpoint> b
8471 (new_momentary_breakpoint (gdbarch, type, sal.pspace, frame_id,
8472 inferior_thread ()->global_num));
8473
8474 b->add_location (sal);
8475
8476 breakpoint_up bp (add_to_breakpoint_chain (std::move (b)));
8477
8478 update_global_location_list_nothrow (UGLL_MAY_INSERT);
8479
8480 return bp;
8481 }
8482
8483 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8484 The new breakpoint will have type TYPE, use OPS as its
8485 breakpoint_ops, and will set enabled to LOC_ENABLED. */
8486
8487 static struct breakpoint *
8488 momentary_breakpoint_from_master (struct breakpoint *orig,
8489 enum bptype type,
8490 int loc_enabled,
8491 int thread)
8492 {
8493 std::unique_ptr<breakpoint> copy
8494 (new_momentary_breakpoint (orig->gdbarch, type, orig->pspace,
8495 orig->frame_id, thread));
8496 const bp_location &orig_loc = orig->first_loc ();
8497 bp_location *copy_loc = copy->allocate_location ();
8498 copy->add_location (*copy_loc);
8499 set_breakpoint_location_function (copy_loc);
8500
8501 copy_loc->gdbarch = orig_loc.gdbarch;
8502 copy_loc->requested_address = orig_loc.requested_address;
8503 copy_loc->address = orig_loc.address;
8504 copy_loc->section = orig_loc.section;
8505 copy_loc->pspace = orig_loc.pspace;
8506 copy_loc->probe = orig_loc.probe;
8507 copy_loc->line_number = orig_loc.line_number;
8508 copy_loc->symtab = orig_loc.symtab;
8509 copy_loc->enabled = loc_enabled;
8510
8511 breakpoint *b = add_to_breakpoint_chain (std::move (copy));
8512 update_global_location_list_nothrow (UGLL_DONT_INSERT);
8513 return b;
8514 }
8515
8516 /* Make a deep copy of momentary breakpoint ORIG. Returns NULL if
8517 ORIG is NULL. */
8518
8519 struct breakpoint *
8520 clone_momentary_breakpoint (struct breakpoint *orig)
8521 {
8522 /* If there's nothing to clone, then return nothing. */
8523 if (orig == NULL)
8524 return NULL;
8525
8526 return momentary_breakpoint_from_master (orig, orig->type, 0,
8527 orig->thread);
8528 }
8529
8530 breakpoint_up
8531 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8532 enum bptype type)
8533 {
8534 struct symtab_and_line sal;
8535
8536 sal = find_pc_line (pc, 0);
8537 sal.pc = pc;
8538 sal.section = find_pc_overlay (pc);
8539 sal.explicit_pc = 1;
8540
8541 return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8542 }
8543 \f
8544
8545 /* Tell the user we have just set a breakpoint B. */
8546
8547 static void
8548 mention (const breakpoint *b)
8549 {
8550 b->print_mention ();
8551 current_uiout->text ("\n");
8552 }
8553 \f
8554
8555 static bool bp_loc_is_permanent (struct bp_location *loc);
8556
8557 /* Handle "set breakpoint auto-hw on".
8558
8559 If the explicitly specified breakpoint type is not hardware
8560 breakpoint, check the memory map to see whether the breakpoint
8561 address is in read-only memory.
8562
8563 - location type is not hardware breakpoint, memory is read-only.
8564 We change the type of the location to hardware breakpoint.
8565
8566 - location type is hardware breakpoint, memory is read-write. This
8567 means we've previously made the location hardware one, but then the
8568 memory map changed, so we undo.
8569 */
8570
8571 static void
8572 handle_automatic_hardware_breakpoints (bp_location *bl)
8573 {
8574 if (automatic_hardware_breakpoints
8575 && bl->owner->type != bp_hardware_breakpoint
8576 && (bl->loc_type == bp_loc_software_breakpoint
8577 || bl->loc_type == bp_loc_hardware_breakpoint))
8578 {
8579 /* When breakpoints are removed, remove_breakpoints will use
8580 location types we've just set here, the only possible problem
8581 is that memory map has changed during running program, but
8582 it's not going to work anyway with current gdb. */
8583 mem_region *mr = lookup_mem_region (bl->address);
8584
8585 if (mr != nullptr)
8586 {
8587 enum bp_loc_type new_type;
8588
8589 if (mr->attrib.mode != MEM_RW)
8590 new_type = bp_loc_hardware_breakpoint;
8591 else
8592 new_type = bp_loc_software_breakpoint;
8593
8594 if (new_type != bl->loc_type)
8595 {
8596 static bool said = false;
8597
8598 bl->loc_type = new_type;
8599 if (!said)
8600 {
8601 gdb_printf (_("Note: automatically using "
8602 "hardware breakpoints for "
8603 "read-only addresses.\n"));
8604 said = true;
8605 }
8606 }
8607 }
8608 }
8609 }
8610
8611 bp_location *
8612 code_breakpoint::add_location (const symtab_and_line &sal)
8613 {
8614 CORE_ADDR adjusted_address;
8615 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8616
8617 if (loc_gdbarch == NULL)
8618 loc_gdbarch = gdbarch;
8619
8620 /* Adjust the breakpoint's address prior to allocating a location.
8621 Once we call allocate_location(), that mostly uninitialized
8622 location will be placed on the location chain. Adjustment of the
8623 breakpoint may cause target_read_memory() to be called and we do
8624 not want its scan of the location chain to find a breakpoint and
8625 location that's only been partially initialized. */
8626 adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8627 sal.pc, type,
8628 sal.pspace);
8629
8630 /* Sort the locations by their ADDRESS. */
8631 bp_location *new_loc = this->allocate_location ();
8632
8633 new_loc->requested_address = sal.pc;
8634 new_loc->address = adjusted_address;
8635 new_loc->pspace = sal.pspace;
8636 new_loc->probe.prob = sal.prob;
8637 new_loc->probe.objfile = sal.objfile;
8638 gdb_assert (new_loc->pspace != NULL);
8639 new_loc->section = sal.section;
8640 new_loc->gdbarch = loc_gdbarch;
8641 new_loc->line_number = sal.line;
8642 new_loc->symtab = sal.symtab;
8643 new_loc->symbol = sal.symbol;
8644 new_loc->msymbol = sal.msymbol;
8645
8646 breakpoint::add_location (*new_loc);
8647
8648 set_breakpoint_location_function (new_loc);
8649
8650 /* While by definition, permanent breakpoints are already present in the
8651 code, we don't mark the location as inserted. Normally one would expect
8652 that GDB could rely on that breakpoint instruction to stop the program,
8653 thus removing the need to insert its own breakpoint, except that executing
8654 the breakpoint instruction can kill the target instead of reporting a
8655 SIGTRAP. E.g., on SPARC, when interrupts are disabled, executing the
8656 instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8657 with "Trap 0x02 while interrupts disabled, Error state". Letting the
8658 breakpoint be inserted normally results in QEMU knowing about the GDB
8659 breakpoint, and thus trap before the breakpoint instruction is executed.
8660 (If GDB later needs to continue execution past the permanent breakpoint,
8661 it manually increments the PC, thus avoiding executing the breakpoint
8662 instruction.) */
8663 if (bp_loc_is_permanent (new_loc))
8664 new_loc->permanent = 1;
8665
8666 return new_loc;
8667 }
8668 \f
8669
8670 /* Return true if LOC is pointing to a permanent breakpoint,
8671 return false otherwise. */
8672
8673 static bool
8674 bp_loc_is_permanent (struct bp_location *loc)
8675 {
8676 gdb_assert (loc != NULL);
8677
8678 /* If we have a non-breakpoint-backed catchpoint or a software
8679 watchpoint, just return 0. We should not attempt to read from
8680 the addresses the locations of these breakpoint types point to.
8681 gdbarch_program_breakpoint_here_p, below, will attempt to read
8682 memory. */
8683 if (!bl_address_is_meaningful (loc))
8684 return false;
8685
8686 scoped_restore_current_pspace_and_thread restore_pspace_thread;
8687 switch_to_program_space_and_thread (loc->pspace);
8688 return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8689 }
8690
8691 /* Build a command list for the dprintf corresponding to the current
8692 settings of the dprintf style options. */
8693
8694 static void
8695 update_dprintf_command_list (struct breakpoint *b)
8696 {
8697 gdb_assert (b->type == bp_dprintf);
8698 gdb_assert (b->extra_string != nullptr);
8699
8700 const char *dprintf_args = b->extra_string.get ();
8701 gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
8702
8703 /* Trying to create a dprintf breakpoint without a format and args
8704 string should be detected at creation time. */
8705 gdb_assert (dprintf_args != nullptr);
8706
8707 dprintf_args = skip_spaces (dprintf_args);
8708
8709 /* Allow a comma, as it may have terminated a location, but don't
8710 insist on it. */
8711 if (*dprintf_args == ',')
8712 ++dprintf_args;
8713 dprintf_args = skip_spaces (dprintf_args);
8714
8715 if (*dprintf_args != '"')
8716 error (_("Bad format string, missing '\"'."));
8717
8718 if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8719 printf_line = xstrprintf ("printf %s", dprintf_args);
8720 else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8721 {
8722 if (dprintf_function.empty ())
8723 error (_("No function supplied for dprintf call"));
8724
8725 if (!dprintf_channel.empty ())
8726 printf_line = xstrprintf ("call (void) %s (%s,%s)",
8727 dprintf_function.c_str (),
8728 dprintf_channel.c_str (),
8729 dprintf_args);
8730 else
8731 printf_line = xstrprintf ("call (void) %s (%s)",
8732 dprintf_function.c_str (),
8733 dprintf_args);
8734 }
8735 else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8736 {
8737 if (target_can_run_breakpoint_commands ())
8738 printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8739 else
8740 {
8741 warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8742 printf_line = xstrprintf ("printf %s", dprintf_args);
8743 }
8744 }
8745 else
8746 internal_error (_("Invalid dprintf style."));
8747
8748 gdb_assert (printf_line != NULL);
8749
8750 /* Manufacture a printf sequence. */
8751 struct command_line *printf_cmd_line
8752 = new struct command_line (simple_control, printf_line.release ());
8753 breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8754 command_lines_deleter ()));
8755 }
8756
8757 /* Update all dprintf commands, making their command lists reflect
8758 current style settings. */
8759
8760 static void
8761 update_dprintf_commands (const char *args, int from_tty,
8762 struct cmd_list_element *c)
8763 {
8764 for (breakpoint &b : all_breakpoints ())
8765 if (b.type == bp_dprintf)
8766 update_dprintf_command_list (&b);
8767 }
8768
8769 code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
8770 enum bptype type_,
8771 gdb::array_view<const symtab_and_line> sals,
8772 location_spec_up &&locspec_,
8773 gdb::unique_xmalloc_ptr<char> filter_,
8774 gdb::unique_xmalloc_ptr<char> cond_string_,
8775 gdb::unique_xmalloc_ptr<char> extra_string_,
8776 enum bpdisp disposition_,
8777 int thread_, int task_, int inferior_,
8778 int ignore_count_,
8779 int from_tty,
8780 int enabled_, unsigned flags,
8781 int display_canonical_)
8782 : breakpoint (gdbarch_, type_)
8783 {
8784 int i;
8785
8786 if (type == bp_hardware_breakpoint)
8787 {
8788 int target_resources_ok;
8789
8790 i = hw_breakpoint_used_count ();
8791 target_resources_ok =
8792 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8793 i + 1, 0);
8794 if (target_resources_ok == 0)
8795 error (_("No hardware breakpoint support in the target."));
8796 else if (target_resources_ok < 0)
8797 error (_("Hardware breakpoints used exceeds limit."));
8798 }
8799
8800 gdb_assert (!sals.empty ());
8801
8802 /* At most one of thread, task, or inferior can be set on any breakpoint. */
8803 gdb_assert (((thread == -1 ? 0 : 1)
8804 + (task == -1 ? 0 : 1)
8805 + (inferior == -1 ? 0 : 1)) <= 1);
8806
8807 thread = thread_;
8808 task = task_;
8809 inferior = inferior_;
8810
8811 cond_string = std::move (cond_string_);
8812 extra_string = std::move (extra_string_);
8813 ignore_count = ignore_count_;
8814 enable_state = enabled_ ? bp_enabled : bp_disabled;
8815 disposition = disposition_;
8816
8817 if (type == bp_static_tracepoint
8818 || type == bp_static_marker_tracepoint)
8819 {
8820 auto *t = gdb::checked_static_cast<tracepoint *> (this);
8821 struct static_tracepoint_marker marker;
8822
8823 if (strace_marker_p (this))
8824 {
8825 /* We already know the marker exists, otherwise, we wouldn't
8826 see a sal for it. */
8827 const char *p = &locspec_->to_string ()[3];
8828 const char *endp;
8829
8830 p = skip_spaces (p);
8831
8832 endp = skip_to_space (p);
8833
8834 t->static_trace_marker_id.assign (p, endp - p);
8835
8836 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8837 t->static_trace_marker_id.c_str ());
8838 }
8839 else if (target_static_tracepoint_marker_at (sals[0].pc, &marker))
8840 {
8841 t->static_trace_marker_id = std::move (marker.str_id);
8842
8843 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8844 t->static_trace_marker_id.c_str ());
8845 }
8846 else
8847 warning (_("Couldn't determine the static tracepoint marker to probe"));
8848 }
8849
8850 for (const auto &sal : sals)
8851 {
8852 if (from_tty)
8853 {
8854 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8855 if (loc_gdbarch == nullptr)
8856 loc_gdbarch = gdbarch;
8857
8858 describe_other_breakpoints (loc_gdbarch,
8859 sal.pspace, sal.pc, sal.section, thread);
8860 }
8861
8862 bp_location *new_loc = add_location (sal);
8863 if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8864 new_loc->inserted = 1;
8865
8866 /* Do not set breakpoint locations conditions yet. As locations
8867 are inserted, they get sorted based on their addresses. Let
8868 the list stabilize to have reliable location numbers. */
8869 }
8870
8871 /* Dynamic printf requires and uses additional arguments on the
8872 command line, otherwise it's an error. */
8873 if (type == bp_dprintf)
8874 update_dprintf_command_list (this);
8875 else
8876 gdb_assert (extra_string == nullptr);
8877
8878 /* The order of the locations is now stable. Set the location
8879 condition using the location's number. */
8880 int loc_num = 1;
8881 for (bp_location &bl : locations ())
8882 {
8883 if (cond_string != nullptr)
8884 set_breakpoint_location_condition (cond_string.get (), &bl,
8885 number, loc_num);
8886
8887 ++loc_num;
8888 }
8889
8890 display_canonical = display_canonical_;
8891 if (locspec_ != nullptr)
8892 locspec = std::move (locspec_);
8893 else
8894 locspec = new_address_location_spec (this->first_loc ().address, NULL, 0);
8895 filter = std::move (filter_);
8896 }
8897
8898 static void
8899 create_breakpoint_sal (struct gdbarch *gdbarch,
8900 gdb::array_view<const symtab_and_line> sals,
8901 location_spec_up &&locspec,
8902 gdb::unique_xmalloc_ptr<char> filter,
8903 gdb::unique_xmalloc_ptr<char> cond_string,
8904 gdb::unique_xmalloc_ptr<char> extra_string,
8905 enum bptype type, enum bpdisp disposition,
8906 int thread, int task, int inferior, int ignore_count,
8907 int from_tty,
8908 int enabled, int internal, unsigned flags,
8909 int display_canonical)
8910 {
8911 std::unique_ptr<code_breakpoint> b
8912 = new_breakpoint_from_type (gdbarch,
8913 type,
8914 sals,
8915 std::move (locspec),
8916 std::move (filter),
8917 std::move (cond_string),
8918 std::move (extra_string),
8919 disposition,
8920 thread, task, inferior, ignore_count,
8921 from_tty,
8922 enabled, flags,
8923 display_canonical);
8924
8925 install_breakpoint (internal, std::move (b), 0);
8926 }
8927
8928 /* Add SALS.nelts breakpoints to the breakpoint table. For each
8929 SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8930 value. COND_STRING, if not NULL, specified the condition to be
8931 used for all breakpoints. Essentially the only case where
8932 SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8933 function. In that case, it's still not possible to specify
8934 separate conditions for different overloaded functions, so
8935 we take just a single condition string.
8936
8937 NOTE: If the function succeeds, the caller is expected to cleanup
8938 the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8939 array contents). If the function fails (error() is called), the
8940 caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8941 COND and SALS arrays and each of those arrays contents. */
8942
8943 static void
8944 create_breakpoints_sal (struct gdbarch *gdbarch,
8945 struct linespec_result *canonical,
8946 gdb::unique_xmalloc_ptr<char> cond_string,
8947 gdb::unique_xmalloc_ptr<char> extra_string,
8948 enum bptype type, enum bpdisp disposition,
8949 int thread, int task, int inferior,
8950 int ignore_count,
8951 int from_tty,
8952 int enabled, int internal, unsigned flags)
8953 {
8954 if (canonical->pre_expanded)
8955 gdb_assert (canonical->lsals.size () == 1);
8956
8957 for (const auto &lsal : canonical->lsals)
8958 {
8959 /* Note that 'location' can be NULL in the case of a plain
8960 'break', without arguments. */
8961 location_spec_up locspec
8962 = (canonical->locspec != nullptr
8963 ? canonical->locspec->clone ()
8964 : nullptr);
8965 gdb::unique_xmalloc_ptr<char> filter_string
8966 (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8967
8968 create_breakpoint_sal (gdbarch, lsal.sals,
8969 std::move (locspec),
8970 std::move (filter_string),
8971 std::move (cond_string),
8972 std::move (extra_string),
8973 type, disposition,
8974 thread, task, inferior, ignore_count,
8975 from_tty, enabled, internal, flags,
8976 canonical->special_display);
8977 }
8978 }
8979
8980 /* Parse LOCSPEC which is assumed to be a SAL specification possibly
8981 followed by conditionals. On return, SALS contains an array of SAL
8982 addresses found. LOCSPEC points to the end of the SAL (for
8983 linespec locspecs).
8984
8985 The array and the line spec strings are allocated on the heap, it is
8986 the caller's responsibility to free them. */
8987
8988 static void
8989 parse_breakpoint_sals (location_spec *locspec,
8990 struct linespec_result *canonical,
8991 struct program_space *search_pspace)
8992 {
8993 if (locspec->type () == LINESPEC_LOCATION_SPEC)
8994 {
8995 const char *spec
8996 = as_linespec_location_spec (locspec)->spec_string.get ();
8997
8998 if (spec == NULL)
8999 {
9000 /* The last displayed codepoint, if it's valid, is our default
9001 breakpoint address. */
9002 if (last_displayed_sal_is_valid ())
9003 {
9004 /* Set sal's pspace, pc, symtab, and line to the values
9005 corresponding to the last call to print_frame_info.
9006 Be sure to reinitialize LINE with NOTCURRENT == 0
9007 as the breakpoint line number is inappropriate otherwise.
9008 find_pc_line would adjust PC, re-set it back. */
9009 symtab_and_line sal = get_last_displayed_sal ();
9010 CORE_ADDR pc = sal.pc;
9011
9012 sal = find_pc_line (pc, 0);
9013
9014 /* "break" without arguments is equivalent to "break *PC"
9015 where PC is the last displayed codepoint's address. So
9016 make sure to set sal.explicit_pc to prevent GDB from
9017 trying to expand the list of sals to include all other
9018 instances with the same symtab and line. */
9019 sal.pc = pc;
9020 sal.explicit_pc = 1;
9021
9022 struct linespec_sals lsal;
9023 lsal.sals = {sal};
9024 lsal.canonical = NULL;
9025
9026 canonical->lsals.push_back (std::move (lsal));
9027 return;
9028 }
9029 else
9030 error (_("No default breakpoint address now."));
9031 }
9032 }
9033
9034 /* Force almost all breakpoints to be in terms of the
9035 current_source_symtab (which is decode_line_1's default).
9036 This should produce the results we want almost all of the
9037 time while leaving default_breakpoint_* alone.
9038
9039 ObjC: However, don't match an Objective-C method name which
9040 may have a '+' or '-' succeeded by a '['. */
9041 symtab_and_line cursal
9042 = get_current_source_symtab_and_line (current_program_space);
9043 if (last_displayed_sal_is_valid ())
9044 {
9045 const char *spec = NULL;
9046
9047 if (locspec->type () == LINESPEC_LOCATION_SPEC)
9048 spec = as_linespec_location_spec (locspec)->spec_string.get ();
9049
9050 if (!cursal.symtab
9051 || (spec != NULL
9052 && strchr ("+-", spec[0]) != NULL
9053 && spec[1] != '['))
9054 {
9055 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
9056 get_last_displayed_symtab (),
9057 get_last_displayed_line (),
9058 canonical, NULL, NULL);
9059 return;
9060 }
9061 }
9062
9063 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
9064 cursal.symtab, cursal.line, canonical, NULL, NULL);
9065 }
9066
9067
9068 /* Convert each SAL into a real PC. Verify that the PC can be
9069 inserted as a breakpoint. If it can't throw an error. */
9070
9071 static void
9072 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9073 {
9074 for (auto &sal : sals)
9075 resolve_sal_pc (&sal);
9076 }
9077
9078 /* Fast tracepoints may have restrictions on valid locations. For
9079 instance, a fast tracepoint using a jump instead of a trap will
9080 likely have to overwrite more bytes than a trap would, and so can
9081 only be placed where the instruction is longer than the jump, or a
9082 multi-instruction sequence does not have a jump into the middle of
9083 it, etc. */
9084
9085 static void
9086 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9087 gdb::array_view<const symtab_and_line> sals)
9088 {
9089 for (const auto &sal : sals)
9090 {
9091 struct gdbarch *sarch;
9092
9093 sarch = get_sal_arch (sal);
9094 /* We fall back to GDBARCH if there is no architecture
9095 associated with SAL. */
9096 if (sarch == NULL)
9097 sarch = gdbarch;
9098 std::string msg;
9099 if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9100 error (_("May not have a fast tracepoint at %s%s"),
9101 paddress (sarch, sal.pc), msg.c_str ());
9102 }
9103 }
9104
9105 /* Decode a static tracepoint marker spec. */
9106
9107 static std::vector<symtab_and_line>
9108 decode_static_tracepoint_spec (const char **arg_p)
9109 {
9110 const char *p = &(*arg_p)[3];
9111 const char *endp;
9112
9113 p = skip_spaces (p);
9114
9115 endp = skip_to_space (p);
9116
9117 std::string marker_str (p, endp - p);
9118
9119 std::vector<static_tracepoint_marker> markers
9120 = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9121 if (markers.empty ())
9122 error (_("No known static tracepoint marker named %s"),
9123 marker_str.c_str ());
9124
9125 std::vector<symtab_and_line> sals;
9126 sals.reserve (markers.size ());
9127
9128 for (const static_tracepoint_marker &marker : markers)
9129 {
9130 symtab_and_line sal = find_pc_line (marker.address, 0);
9131 sal.pc = marker.address;
9132 sals.push_back (sal);
9133 }
9134
9135 *arg_p = endp;
9136 return sals;
9137 }
9138
9139 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
9140 according to IS_TRACEPOINT. */
9141
9142 static const struct breakpoint_ops *
9143 breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
9144 bool is_tracepoint)
9145 {
9146 if (is_tracepoint)
9147 {
9148 if (locspec_type == PROBE_LOCATION_SPEC)
9149 return &tracepoint_probe_breakpoint_ops;
9150 else
9151 return &code_breakpoint_ops;
9152 }
9153 else
9154 {
9155 if (locspec_type == PROBE_LOCATION_SPEC)
9156 return &bkpt_probe_breakpoint_ops;
9157 else
9158 return &code_breakpoint_ops;
9159 }
9160 }
9161
9162 /* Return the program space to use as a filter when searching for locations
9163 of a breakpoint specific to THREAD or INFERIOR. If THREAD and INFERIOR
9164 are both -1, meaning all threads/inferiors, then this function returns
9165 nullptr, indicating no program space filtering should be performed.
9166 Otherwise, this function returns the program space for the inferior that
9167 contains THREAD (when THREAD is not -1), or the program space for
9168 INFERIOR (when INFERIOR is not -1). */
9169
9170 static struct program_space *
9171 find_program_space_for_breakpoint (int thread, int inferior)
9172 {
9173 if (thread != -1)
9174 {
9175 gdb_assert (inferior == -1);
9176
9177 struct thread_info *thr = find_thread_global_id (thread);
9178 gdb_assert (thr != nullptr);
9179 gdb_assert (thr->inf != nullptr);
9180 return thr->inf->pspace;
9181 }
9182 else if (inferior != -1)
9183 {
9184 gdb_assert (thread == -1);
9185
9186 struct inferior *inf = find_inferior_id (inferior);
9187 gdb_assert (inf != nullptr);
9188
9189 return inf->pspace;
9190 }
9191
9192 return nullptr;
9193 }
9194
9195 /* See breakpoint.h. */
9196
9197 const struct breakpoint_ops *
9198 breakpoint_ops_for_location_spec (const location_spec *locspec,
9199 bool is_tracepoint)
9200 {
9201 if (locspec != nullptr)
9202 return (breakpoint_ops_for_location_spec_type
9203 (locspec->type (), is_tracepoint));
9204 return &code_breakpoint_ops;
9205 }
9206
9207 /* See breakpoint.h. */
9208
9209 int
9210 create_breakpoint (struct gdbarch *gdbarch,
9211 location_spec *locspec,
9212 const char *cond_string,
9213 int thread, int inferior,
9214 const char *extra_string,
9215 bool force_condition, int parse_extra,
9216 int tempflag, enum bptype type_wanted,
9217 int ignore_count,
9218 enum auto_boolean pending_break_support,
9219 const struct breakpoint_ops *ops,
9220 int from_tty, int enabled, int internal,
9221 unsigned flags)
9222 {
9223 struct linespec_result canonical;
9224 bool pending = false;
9225 int task = -1;
9226 int prev_bkpt_count = breakpoint_count;
9227
9228 gdb_assert (thread == -1 || thread > 0);
9229 gdb_assert (inferior == -1 || inferior > 0);
9230 gdb_assert (thread == -1 || inferior == -1);
9231
9232 /* If PARSE_EXTRA is true then the thread and inferior details will be
9233 parsed from the EXTRA_STRING, the THREAD and INFERIOR arguments
9234 should be -1. */
9235 gdb_assert (!parse_extra || thread == -1);
9236 gdb_assert (!parse_extra || inferior == -1);
9237
9238 gdb_assert (ops != NULL);
9239
9240 /* If extra_string isn't useful, set it to NULL. */
9241 if (extra_string != NULL && *extra_string == '\0')
9242 extra_string = NULL;
9243
9244 /* A bp_dprintf must always have an accompanying EXTRA_STRING containing
9245 the dprintf format and arguments -- PARSE_EXTRA should always be false
9246 in this case.
9247
9248 For all other breakpoint types, EXTRA_STRING should be nullptr unless
9249 PARSE_EXTRA is true. */
9250 gdb_assert ((type_wanted == bp_dprintf)
9251 ? (extra_string != nullptr && !parse_extra)
9252 : (extra_string == nullptr || parse_extra));
9253
9254 /* Will hold either copies of the similarly named function argument, or
9255 will hold a modified version of the function argument, depending on
9256 the value of PARSE_EXTRA. */
9257 gdb::unique_xmalloc_ptr<char> cond_string_copy;
9258 gdb::unique_xmalloc_ptr<char> extra_string_copy;
9259
9260 if (parse_extra)
9261 {
9262 /* Parse EXTRA_STRING splitting the parts out. */
9263 create_breakpoint_parse_arg_string (extra_string, &cond_string_copy,
9264 &thread, &inferior, &task,
9265 &extra_string_copy,
9266 &force_condition);
9267
9268 /* We could check that EXTRA_STRING_COPY is empty at this point -- it
9269 should be, as we only get here for things that are not bp_dprintf,
9270 however, we prefer to give the location spec parser a chance to
9271 run first, this means the user will get errors about invalid
9272 location spec instead of an error about garbage at the end of the
9273 command line.
9274
9275 We still do the EXTRA_STRING_COPY is empty check, just later in
9276 this function. */
9277
9278 gdb_assert (thread == -1 || thread > 0);
9279 gdb_assert (task == -1 || task > 0);
9280 gdb_assert (inferior == -1 || inferior > 0);
9281 }
9282 else
9283 {
9284 if (cond_string != nullptr)
9285 cond_string_copy.reset (xstrdup (cond_string));
9286 if (extra_string != nullptr)
9287 extra_string_copy.reset (xstrdup (extra_string));
9288 }
9289
9290 /* Clear these. Updated values are now held in the *_copy locals. */
9291 cond_string = nullptr;
9292 extra_string = nullptr;
9293
9294 try
9295 {
9296 struct program_space *search_pspace
9297 = find_program_space_for_breakpoint (thread, inferior);
9298 ops->create_sals_from_location_spec (locspec, &canonical,
9299 search_pspace);
9300 }
9301 catch (const gdb_exception_error &e)
9302 {
9303 /* If caller is interested in rc value from parse, set
9304 value. */
9305 if (e.error == NOT_FOUND_ERROR)
9306 {
9307 /* If pending breakpoint support is turned off, throw
9308 error. */
9309
9310 if (pending_break_support == AUTO_BOOLEAN_FALSE)
9311 throw;
9312
9313 exception_print (gdb_stderr, e);
9314
9315 /* If pending breakpoint support is auto query and the user
9316 selects no, then simply return the error code. */
9317 if (pending_break_support == AUTO_BOOLEAN_AUTO
9318 && !nquery (_("Make %s pending on future shared library load? "),
9319 bptype_string (type_wanted)))
9320 return 0;
9321
9322 /* At this point, either the user was queried about setting
9323 a pending breakpoint and selected yes, or pending
9324 breakpoint behavior is on and thus a pending breakpoint
9325 is defaulted on behalf of the user. */
9326 pending = true;
9327 }
9328 else
9329 throw;
9330 }
9331
9332 /* Only bp_dprintf breakpoints should have anything in EXTRA_STRING_COPY
9333 by this point. For all other breakpoints this indicates an error. We
9334 could place this check earlier in the function, but we prefer to see
9335 errors from the location spec parser before we see this error message. */
9336 if (type_wanted != bp_dprintf && extra_string_copy.get () != nullptr)
9337 error (_("Garbage '%s' at end of command"), extra_string_copy.get ());
9338
9339 if (!pending && canonical.lsals.empty ())
9340 return 0;
9341
9342 /* Resolve all line numbers to PC's and verify that the addresses
9343 are ok for the target. */
9344 if (!pending)
9345 {
9346 for (auto &lsal : canonical.lsals)
9347 breakpoint_sals_to_pc (lsal.sals);
9348 }
9349
9350 /* Fast tracepoints may have additional restrictions on location. */
9351 if (!pending && type_wanted == bp_fast_tracepoint)
9352 {
9353 for (const auto &lsal : canonical.lsals)
9354 check_fast_tracepoint_sals (gdbarch, lsal.sals);
9355 }
9356
9357 /* Verify that condition can be parsed, before setting any
9358 breakpoints. Allocate a separate condition expression for each
9359 breakpoint. */
9360 if (!pending)
9361 {
9362 /* Check the validity of the condition. We should error out if the
9363 condition is invalid at all of the locations and if it is not
9364 forced. In the PARSE_EXTRA case above, this check is done when
9365 parsing the EXTRA_STRING. */
9366 if (cond_string_copy.get () != nullptr && !force_condition)
9367 {
9368 int num_failures = 0;
9369 const linespec_sals &lsal = canonical.lsals[0];
9370 for (const auto &sal : lsal.sals)
9371 {
9372 const char *cond = cond_string_copy.get ();
9373 try
9374 {
9375 parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
9376 /* One success is sufficient to keep going. */
9377 break;
9378 }
9379 catch (const gdb_exception_error &)
9380 {
9381 num_failures++;
9382 /* If this is the last sal, error out. */
9383 if (num_failures == lsal.sals.size ())
9384 throw;
9385 }
9386 }
9387 }
9388
9389 ops->create_breakpoints_sal (gdbarch, &canonical,
9390 std::move (cond_string_copy),
9391 std::move (extra_string_copy),
9392 type_wanted,
9393 tempflag ? disp_del : disp_donttouch,
9394 thread, task, inferior, ignore_count,
9395 from_tty, enabled, internal, flags);
9396 }
9397 else
9398 {
9399 std::unique_ptr <breakpoint> b = new_breakpoint_from_type (gdbarch,
9400 type_wanted);
9401 b->locspec = locspec->clone ();
9402
9403 /* Create a private copy of the condition string. */
9404 b->cond_string = std::move (cond_string_copy);
9405
9406 b->thread = thread;
9407 b->task = task;
9408 b->inferior = inferior;
9409
9410 /* Create a private copy of any extra string. */
9411 b->extra_string = std::move (extra_string_copy);
9412
9413 b->ignore_count = ignore_count;
9414 b->disposition = tempflag ? disp_del : disp_donttouch;
9415 b->condition_not_parsed = 1;
9416 b->enable_state = enabled ? bp_enabled : bp_disabled;
9417
9418 if (b->type == bp_dprintf)
9419 update_dprintf_command_list (b.get ());
9420
9421 install_breakpoint (internal, std::move (b), 0);
9422 }
9423
9424 if (canonical.lsals.size () > 1)
9425 {
9426 warning (_("Multiple breakpoints were set.\nUse the "
9427 "\"%ps\" command to delete unwanted breakpoints."),
9428 styled_string (command_style.style (), "delete"));
9429 prev_breakpoint_count = prev_bkpt_count;
9430 }
9431
9432 update_global_location_list (UGLL_MAY_INSERT);
9433
9434 return 1;
9435 }
9436
9437 /* Set a breakpoint.
9438 ARG is a string describing breakpoint address,
9439 condition, and thread.
9440 FLAG specifies if a breakpoint is hardware on,
9441 and if breakpoint is temporary, using BP_HARDWARE_FLAG
9442 and BP_TEMPFLAG. */
9443
9444 static void
9445 break_command_1 (const char *arg, int flag, int from_tty)
9446 {
9447 int tempflag = flag & BP_TEMPFLAG;
9448 enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9449 ? bp_hardware_breakpoint
9450 : bp_breakpoint);
9451
9452 location_spec_up locspec = string_to_location_spec (&arg, current_language);
9453 const struct breakpoint_ops *ops
9454 = breakpoint_ops_for_location_spec (locspec.get (),
9455 false /* is_tracepoint */);
9456
9457 create_breakpoint (get_current_arch (),
9458 locspec.get (),
9459 NULL,
9460 -1 /* thread */, -1 /* inferior */,
9461 arg, false, 1 /* parse arg */,
9462 tempflag, type_wanted,
9463 0 /* Ignore count */,
9464 pending_break_support,
9465 ops,
9466 from_tty,
9467 1 /* enabled */,
9468 0 /* internal */,
9469 0);
9470 }
9471
9472 /* Helper function for break_command_1 and disassemble_command. */
9473
9474 void
9475 resolve_sal_pc (struct symtab_and_line *sal)
9476 {
9477 CORE_ADDR pc;
9478
9479 if (sal->pc == 0 && sal->symtab != NULL)
9480 {
9481 if (!find_line_pc (sal->symtab, sal->line, &pc))
9482 error (_("No line %d in file \"%s\"."),
9483 sal->line, symtab_to_filename_for_display (sal->symtab));
9484 sal->pc = pc;
9485
9486 /* If this SAL corresponds to a breakpoint inserted using a line
9487 number, then skip the function prologue if necessary. */
9488 if (sal->explicit_line)
9489 skip_prologue_sal (sal);
9490 }
9491
9492 if (sal->section == 0 && sal->symtab != NULL)
9493 {
9494 const struct blockvector *bv;
9495 const struct block *b;
9496 struct symbol *sym;
9497
9498 bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9499 sal->symtab->compunit ());
9500 if (bv != NULL)
9501 {
9502 sym = b->linkage_function ();
9503 if (sym != NULL)
9504 sal->section
9505 = sym->obj_section (sal->symtab->compunit ()->objfile ());
9506 else
9507 {
9508 /* It really is worthwhile to have the section, so we'll
9509 just have to look harder. This case can be executed
9510 if we have line numbers but no functions (as can
9511 happen in assembly source). */
9512
9513 scoped_restore_current_pspace_and_thread restore_pspace_thread;
9514 switch_to_program_space_and_thread (sal->pspace);
9515
9516 bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9517 if (msym.minsym)
9518 sal->section = msym.obj_section ();
9519 }
9520 }
9521 }
9522 }
9523
9524 void
9525 break_command (const char *arg, int from_tty)
9526 {
9527 break_command_1 (arg, 0, from_tty);
9528 }
9529
9530 void
9531 tbreak_command (const char *arg, int from_tty)
9532 {
9533 break_command_1 (arg, BP_TEMPFLAG, from_tty);
9534 }
9535
9536 static void
9537 hbreak_command (const char *arg, int from_tty)
9538 {
9539 break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9540 }
9541
9542 static void
9543 thbreak_command (const char *arg, int from_tty)
9544 {
9545 break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9546 }
9547
9548 /* The dynamic printf command is mostly like a regular breakpoint, but
9549 with a prewired command list consisting of a single output command,
9550 built from extra arguments supplied on the dprintf command
9551 line. */
9552
9553 static void
9554 dprintf_command (const char *arg, int from_tty)
9555 {
9556 location_spec_up locspec = string_to_location_spec (&arg, current_language);
9557
9558 /* If non-NULL, ARG should have been advanced past the location;
9559 the next character must be ','. */
9560 if (arg == nullptr || arg[0] != ',' || arg[1] == '\0')
9561 error (_("Format string required"));
9562 else
9563 {
9564 /* Skip the comma. */
9565 ++arg;
9566 }
9567
9568 create_breakpoint (get_current_arch (),
9569 locspec.get (),
9570 NULL, -1, -1,
9571 arg, false, 0 /* parse arg */,
9572 0, bp_dprintf,
9573 0 /* Ignore count */,
9574 pending_break_support,
9575 &code_breakpoint_ops,
9576 from_tty,
9577 1 /* enabled */,
9578 0 /* internal */,
9579 0);
9580 }
9581
9582 static void
9583 agent_printf_command (const char *arg, int from_tty)
9584 {
9585 error (_("May only run agent-printf on the target"));
9586 }
9587
9588 /* Implement the "breakpoint_hit" method for ranged breakpoints. */
9589
9590 int
9591 ranged_breakpoint::breakpoint_hit (const struct bp_location *bl,
9592 const address_space *aspace,
9593 CORE_ADDR bp_addr,
9594 const target_waitstatus &ws)
9595 {
9596 if (ws.kind () != TARGET_WAITKIND_STOPPED
9597 || ws.sig () != GDB_SIGNAL_TRAP)
9598 return 0;
9599
9600 return breakpoint_address_match_range (bl->pspace->aspace.get (),
9601 bl->address, bl->length, aspace,
9602 bp_addr);
9603 }
9604
9605 /* Implement the "resources_needed" method for ranged breakpoints. */
9606
9607 int
9608 ranged_breakpoint::resources_needed (const struct bp_location *bl)
9609 {
9610 return target_ranged_break_num_registers ();
9611 }
9612
9613 /* Implement the "print_it" method for ranged breakpoints. */
9614
9615 enum print_stop_action
9616 ranged_breakpoint::print_it (const bpstat *bs) const
9617 {
9618 struct ui_out *uiout = current_uiout;
9619
9620 gdb_assert (type == bp_hardware_breakpoint);
9621
9622 /* Ranged breakpoints have only one location. */
9623 gdb_assert (this->has_single_location ());
9624
9625 annotate_breakpoint (number);
9626
9627 maybe_print_thread_hit_breakpoint (uiout);
9628
9629 if (disposition == disp_del)
9630 uiout->text ("Temporary ranged breakpoint ");
9631 else
9632 uiout->text ("Ranged breakpoint ");
9633 if (uiout->is_mi_like_p ())
9634 {
9635 uiout->field_string ("reason",
9636 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9637 uiout->field_string ("disp", bpdisp_text (disposition));
9638 }
9639 print_num_locno (bs, uiout);
9640 uiout->text (", ");
9641
9642 return PRINT_SRC_AND_LOC;
9643 }
9644
9645 /* Implement the "print_one" method for ranged breakpoints. */
9646
9647 bool
9648 ranged_breakpoint::print_one (const bp_location **last_loc) const
9649 {
9650 struct value_print_options opts;
9651 struct ui_out *uiout = current_uiout;
9652
9653 /* Ranged breakpoints have only one location. */
9654 gdb_assert (this->has_single_location ());
9655
9656 get_user_print_options (&opts);
9657
9658 if (opts.addressprint)
9659 /* We don't print the address range here, it will be printed later
9660 by ranged_breakpoint::print_one_detail. */
9661 uiout->field_skip ("addr");
9662 annotate_field (5);
9663 print_breakpoint_location (this, &this->first_loc ());
9664 *last_loc = &this->first_loc ();
9665
9666 return true;
9667 }
9668
9669 /* Implement the "print_one_detail" method for ranged breakpoints. */
9670
9671 void
9672 ranged_breakpoint::print_one_detail (struct ui_out *uiout) const
9673 {
9674 CORE_ADDR address_start, address_end;
9675 const bp_location &bl = this->first_loc ();
9676 string_file stb;
9677
9678 address_start = bl.address;
9679 address_end = address_start + bl.length - 1;
9680
9681 uiout->text ("\taddress range: ");
9682 stb.printf ("[%s, %s]",
9683 print_core_address (bl.gdbarch, address_start),
9684 print_core_address (bl.gdbarch, address_end));
9685 uiout->field_stream ("addr", stb);
9686 uiout->text ("\n");
9687 }
9688
9689 /* Implement the "print_mention" method for ranged breakpoints. */
9690
9691 void
9692 ranged_breakpoint::print_mention () const
9693 {
9694 const bp_location &bl = this->first_loc ();
9695 struct ui_out *uiout = current_uiout;
9696
9697 gdb_assert (type == bp_hardware_breakpoint);
9698
9699 uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9700 number, paddress (bl.gdbarch, bl.address),
9701 paddress (bl.gdbarch, bl.address + bl.length - 1));
9702 }
9703
9704 /* Implement the "print_recreate" method for ranged breakpoints. */
9705
9706 void
9707 ranged_breakpoint::print_recreate (struct ui_file *fp) const
9708 {
9709 gdb_printf (fp, "break-range %s, %s",
9710 locspec->to_string (),
9711 locspec_range_end->to_string ());
9712 print_recreate_thread (fp);
9713 }
9714
9715 /* Find the address where the end of the breakpoint range should be
9716 placed, given the SAL of the end of the range. This is so that if
9717 the user provides a line number, the end of the range is set to the
9718 last instruction of the given line. */
9719
9720 static CORE_ADDR
9721 find_breakpoint_range_end (struct symtab_and_line sal)
9722 {
9723 CORE_ADDR end;
9724
9725 /* If the user provided a PC value, use it. Otherwise,
9726 find the address of the end of the given location. */
9727 if (sal.explicit_pc)
9728 end = sal.pc;
9729 else
9730 {
9731 int ret;
9732 CORE_ADDR start;
9733
9734 ret = find_line_pc_range (sal, &start, &end);
9735 if (!ret)
9736 error (_("Could not find location of the end of the range."));
9737
9738 /* find_line_pc_range returns the start of the next line. */
9739 end--;
9740 }
9741
9742 return end;
9743 }
9744
9745 /* Implement the "break-range" CLI command. */
9746
9747 static void
9748 break_range_command (const char *arg, int from_tty)
9749 {
9750 const char *arg_start;
9751 struct linespec_result canonical_start, canonical_end;
9752 int bp_count, can_use_bp, length;
9753 CORE_ADDR end;
9754
9755 /* We don't support software ranged breakpoints. */
9756 if (target_ranged_break_num_registers () < 0)
9757 error (_("This target does not support hardware ranged breakpoints."));
9758
9759 bp_count = hw_breakpoint_used_count ();
9760 bp_count += target_ranged_break_num_registers ();
9761 can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9762 bp_count, 0);
9763 if (can_use_bp < 0)
9764 error (_("Hardware breakpoints used exceeds limit."));
9765
9766 arg = skip_spaces (arg);
9767 if (arg == NULL || arg[0] == '\0')
9768 error(_("No address range specified."));
9769
9770 arg_start = arg;
9771 location_spec_up start_locspec
9772 = string_to_location_spec (&arg, current_language);
9773 parse_breakpoint_sals (start_locspec.get (), &canonical_start, nullptr);
9774
9775 if (arg[0] != ',')
9776 error (_("Too few arguments."));
9777 else if (canonical_start.lsals.empty ())
9778 error (_("Could not find location of the beginning of the range."));
9779
9780 const linespec_sals &lsal_start = canonical_start.lsals[0];
9781
9782 if (canonical_start.lsals.size () > 1
9783 || lsal_start.sals.size () != 1)
9784 error (_("Cannot create a ranged breakpoint with multiple locations."));
9785
9786 const symtab_and_line &sal_start = lsal_start.sals[0];
9787 std::string addr_string_start (arg_start, arg - arg_start);
9788
9789 arg++; /* Skip the comma. */
9790 arg = skip_spaces (arg);
9791
9792 /* Parse the end location specification. */
9793
9794 arg_start = arg;
9795
9796 /* We call decode_line_full directly here instead of using
9797 parse_breakpoint_sals because we need to specify the start
9798 location spec's symtab and line as the default symtab and line
9799 for the end of the range. This makes it possible to have ranges
9800 like "foo.c:27, +14", where +14 means 14 lines from the start
9801 location spec. */
9802 location_spec_up end_locspec
9803 = string_to_location_spec (&arg, current_language);
9804 decode_line_full (end_locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9805 sal_start.symtab, sal_start.line,
9806 &canonical_end, NULL, NULL);
9807
9808 if (canonical_end.lsals.empty ())
9809 error (_("Could not find location of the end of the range."));
9810
9811 const linespec_sals &lsal_end = canonical_end.lsals[0];
9812 if (canonical_end.lsals.size () > 1
9813 || lsal_end.sals.size () != 1)
9814 error (_("Cannot create a ranged breakpoint with multiple locations."));
9815
9816 const symtab_and_line &sal_end = lsal_end.sals[0];
9817
9818 end = find_breakpoint_range_end (sal_end);
9819 if (sal_start.pc > end)
9820 error (_("Invalid address range, end precedes start."));
9821
9822 length = end - sal_start.pc + 1;
9823 if (length < 0)
9824 /* Length overflowed. */
9825 error (_("Address range too large."));
9826 else if (length == 1)
9827 {
9828 /* This range is simple enough to be handled by
9829 the `hbreak' command. */
9830 hbreak_command (&addr_string_start[0], 1);
9831
9832 return;
9833 }
9834
9835 /* Now set up the breakpoint and install it. */
9836
9837 std::unique_ptr<breakpoint> br
9838 (new ranged_breakpoint (get_current_arch (),
9839 sal_start, length,
9840 std::move (start_locspec),
9841 std::move (end_locspec)));
9842
9843 install_breakpoint (false, std::move (br), true);
9844 }
9845
9846 /* See breakpoint.h. */
9847
9848 watchpoint::~watchpoint ()
9849 {
9850 /* Make sure to unlink the destroyed watchpoint from the related
9851 breakpoint ring. */
9852
9853 breakpoint *bpt = this;
9854 while (bpt->related_breakpoint != this)
9855 bpt = bpt->related_breakpoint;
9856
9857 bpt->related_breakpoint = this->related_breakpoint;
9858 }
9859
9860 /* Return non-zero if EXP is verified as constant. Returned zero
9861 means EXP is variable. Also the constant detection may fail for
9862 some constant expressions and in such case still falsely return
9863 zero. */
9864
9865 static bool
9866 watchpoint_exp_is_const (const struct expression *exp)
9867 {
9868 return exp->op->constant_p ();
9869 }
9870
9871 /* Implement the "re_set" method for watchpoints. */
9872
9873 void
9874 watchpoint::re_set (struct program_space *pspace)
9875 {
9876 /* Watchpoint can be either on expression using entirely global
9877 variables, or it can be on local variables.
9878
9879 Watchpoints of the first kind are never auto-deleted, and even
9880 persist across program restarts. Since they can use variables
9881 from shared libraries, we need to reparse expression as libraries
9882 are loaded and unloaded.
9883
9884 Watchpoints on local variables can also change meaning as result
9885 of solib event. For example, if a watchpoint uses both a local
9886 and a global variables in expression, it's a local watchpoint,
9887 but unloading of a shared library will make the expression
9888 invalid. This is not a very common use case, but we still
9889 re-evaluate expression, to avoid surprises to the user.
9890
9891 Note that for local watchpoints, we re-evaluate it only if
9892 watchpoints frame id is still valid. If it's not, it means the
9893 watchpoint is out of scope and will be deleted soon. In fact,
9894 I'm not sure we'll ever be called in this case.
9895
9896 If a local watchpoint's frame id is still valid, then
9897 exp_valid_block is likewise valid, and we can safely use it.
9898
9899 Don't do anything about disabled watchpoints, since they will be
9900 reevaluated again when enabled. */
9901 update_watchpoint (this, true /* reparse */);
9902 }
9903
9904 /* Implement the "insert" method for hardware watchpoints. */
9905
9906 int
9907 watchpoint::insert_location (struct bp_location *bl)
9908 {
9909 int length = exact ? 1 : bl->length;
9910
9911 return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9912 cond_exp.get ());
9913 }
9914
9915 /* Implement the "remove" method for hardware watchpoints. */
9916
9917 int
9918 watchpoint::remove_location (struct bp_location *bl,
9919 enum remove_bp_reason reason)
9920 {
9921 int length = exact ? 1 : bl->length;
9922
9923 return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9924 cond_exp.get ());
9925 }
9926
9927 int
9928 watchpoint::breakpoint_hit (const struct bp_location *bl,
9929 const address_space *aspace, CORE_ADDR bp_addr,
9930 const target_waitstatus &ws)
9931 {
9932 struct breakpoint *b = bl->owner;
9933
9934 /* Continuable hardware watchpoints are treated as non-existent if the
9935 reason we stopped wasn't a hardware watchpoint (we didn't stop on
9936 some data address). Otherwise gdb won't stop on a break instruction
9937 in the code (not from a breakpoint) when a hardware watchpoint has
9938 been defined. Also skip watchpoints which we know did not trigger
9939 (did not match the data address). */
9940 if (is_hardware_watchpoint (b)
9941 && watchpoint_triggered == watch_triggered_no)
9942 return 0;
9943
9944 return 1;
9945 }
9946
9947 void
9948 watchpoint::check_status (bpstat *bs)
9949 {
9950 bpstat_check_watchpoint (bs);
9951 }
9952
9953 /* Implement the "resources_needed" method for hardware
9954 watchpoints. */
9955
9956 int
9957 watchpoint::resources_needed (const struct bp_location *bl)
9958 {
9959 int length = exact? 1 : bl->length;
9960
9961 return target_region_ok_for_hw_watchpoint (bl->address, length);
9962 }
9963
9964 /* Implement the "works_in_software_mode" method for hardware
9965 watchpoints. */
9966
9967 bool
9968 watchpoint::works_in_software_mode () const
9969 {
9970 /* Read and access watchpoints only work with hardware support. */
9971 return type == bp_watchpoint || type == bp_hardware_watchpoint;
9972 }
9973
9974 enum print_stop_action
9975 watchpoint::print_it (const bpstat *bs) const
9976 {
9977 enum print_stop_action result;
9978 struct ui_out *uiout = current_uiout;
9979
9980 gdb_assert (bs->bp_location_at != NULL);
9981
9982 annotate_watchpoint (this->number);
9983 maybe_print_thread_hit_breakpoint (uiout);
9984
9985 string_file stb;
9986
9987 std::optional<ui_out_emit_tuple> tuple_emitter;
9988 switch (this->type)
9989 {
9990 case bp_watchpoint:
9991 case bp_hardware_watchpoint:
9992 if (uiout->is_mi_like_p ())
9993 uiout->field_string
9994 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9995 mention (this);
9996 tuple_emitter.emplace (uiout, "value");
9997 uiout->text ("\nOld value = ");
9998 watchpoint_value_print (bs->old_val.get (), &stb);
9999 uiout->field_stream ("old", stb);
10000 uiout->text ("\nNew value = ");
10001 watchpoint_value_print (val.get (), &stb);
10002 uiout->field_stream ("new", stb);
10003 uiout->text ("\n");
10004 /* More than one watchpoint may have been triggered. */
10005 result = PRINT_UNKNOWN;
10006 break;
10007
10008 case bp_read_watchpoint:
10009 if (uiout->is_mi_like_p ())
10010 uiout->field_string
10011 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10012 mention (this);
10013 tuple_emitter.emplace (uiout, "value");
10014 uiout->text ("\nValue = ");
10015 watchpoint_value_print (val.get (), &stb);
10016 uiout->field_stream ("value", stb);
10017 uiout->text ("\n");
10018 result = PRINT_UNKNOWN;
10019 break;
10020
10021 case bp_access_watchpoint:
10022 if (bs->old_val != NULL)
10023 {
10024 if (uiout->is_mi_like_p ())
10025 uiout->field_string
10026 ("reason",
10027 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10028 mention (this);
10029 tuple_emitter.emplace (uiout, "value");
10030 uiout->text ("\nOld value = ");
10031 watchpoint_value_print (bs->old_val.get (), &stb);
10032 uiout->field_stream ("old", stb);
10033 uiout->text ("\nNew value = ");
10034 }
10035 else
10036 {
10037 mention (this);
10038 if (uiout->is_mi_like_p ())
10039 uiout->field_string
10040 ("reason",
10041 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10042 tuple_emitter.emplace (uiout, "value");
10043 uiout->text ("\nValue = ");
10044 }
10045 watchpoint_value_print (val.get (), &stb);
10046 uiout->field_stream ("new", stb);
10047 uiout->text ("\n");
10048 result = PRINT_UNKNOWN;
10049 break;
10050 default:
10051 result = PRINT_UNKNOWN;
10052 }
10053
10054 return result;
10055 }
10056
10057 /* Implement the "print_mention" method for hardware watchpoints. */
10058
10059 void
10060 watchpoint::print_mention () const
10061 {
10062 struct ui_out *uiout = current_uiout;
10063 const char *tuple_name;
10064
10065 switch (type)
10066 {
10067 case bp_watchpoint:
10068 uiout->text ("Watchpoint ");
10069 tuple_name = "wpt";
10070 break;
10071 case bp_hardware_watchpoint:
10072 uiout->text ("Hardware watchpoint ");
10073 tuple_name = "wpt";
10074 break;
10075 case bp_read_watchpoint:
10076 uiout->text ("Hardware read watchpoint ");
10077 tuple_name = "hw-rwpt";
10078 break;
10079 case bp_access_watchpoint:
10080 uiout->text ("Hardware access (read/write) watchpoint ");
10081 tuple_name = "hw-awpt";
10082 break;
10083 default:
10084 internal_error (_("Invalid hardware watchpoint type."));
10085 }
10086
10087 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10088 uiout->field_signed ("number", number);
10089 uiout->text (": ");
10090 uiout->field_string ("exp", exp_string.get ());
10091 }
10092
10093 /* Implement the "print_recreate" method for watchpoints. */
10094
10095 void
10096 watchpoint::print_recreate (struct ui_file *fp) const
10097 {
10098 switch (type)
10099 {
10100 case bp_watchpoint:
10101 case bp_hardware_watchpoint:
10102 gdb_printf (fp, "watch");
10103 break;
10104 case bp_read_watchpoint:
10105 gdb_printf (fp, "rwatch");
10106 break;
10107 case bp_access_watchpoint:
10108 gdb_printf (fp, "awatch");
10109 break;
10110 default:
10111 internal_error (_("Invalid watchpoint type."));
10112 }
10113
10114 gdb_printf (fp, " %s", exp_string.get ());
10115 print_recreate_thread (fp);
10116 }
10117
10118 /* Implement the "explains_signal" method for watchpoints. */
10119
10120 bool
10121 watchpoint::explains_signal (enum gdb_signal sig)
10122 {
10123 /* A software watchpoint cannot cause a signal other than
10124 GDB_SIGNAL_TRAP. */
10125 if (type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10126 return false;
10127
10128 return true;
10129 }
10130
10131 struct masked_watchpoint : public watchpoint
10132 {
10133 using watchpoint::watchpoint;
10134
10135 int insert_location (struct bp_location *) override;
10136 int remove_location (struct bp_location *,
10137 enum remove_bp_reason reason) override;
10138 int resources_needed (const struct bp_location *) override;
10139 bool works_in_software_mode () const override;
10140 enum print_stop_action print_it (const bpstat *bs) const override;
10141 void print_one_detail (struct ui_out *) const override;
10142 void print_mention () const override;
10143 void print_recreate (struct ui_file *fp) const override;
10144 };
10145
10146 /* Implement the "insert" method for masked hardware watchpoints. */
10147
10148 int
10149 masked_watchpoint::insert_location (struct bp_location *bl)
10150 {
10151 return target_insert_mask_watchpoint (bl->address, hw_wp_mask,
10152 bl->watchpoint_type);
10153 }
10154
10155 /* Implement the "remove" method for masked hardware watchpoints. */
10156
10157 int
10158 masked_watchpoint::remove_location (struct bp_location *bl,
10159 enum remove_bp_reason reason)
10160 {
10161 return target_remove_mask_watchpoint (bl->address, hw_wp_mask,
10162 bl->watchpoint_type);
10163 }
10164
10165 /* Implement the "resources_needed" method for masked hardware
10166 watchpoints. */
10167
10168 int
10169 masked_watchpoint::resources_needed (const struct bp_location *bl)
10170 {
10171 return target_masked_watch_num_registers (bl->address, hw_wp_mask);
10172 }
10173
10174 /* Implement the "works_in_software_mode" method for masked hardware
10175 watchpoints. */
10176
10177 bool
10178 masked_watchpoint::works_in_software_mode () const
10179 {
10180 return false;
10181 }
10182
10183 /* Implement the "print_it" method for masked hardware
10184 watchpoints. */
10185
10186 enum print_stop_action
10187 masked_watchpoint::print_it (const bpstat *bs) const
10188 {
10189 struct ui_out *uiout = current_uiout;
10190
10191 /* Masked watchpoints have only one location. */
10192 gdb_assert (this->has_single_location ());
10193
10194 annotate_watchpoint (this->number);
10195 maybe_print_thread_hit_breakpoint (uiout);
10196
10197 switch (this->type)
10198 {
10199 case bp_hardware_watchpoint:
10200 if (uiout->is_mi_like_p ())
10201 uiout->field_string
10202 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10203 break;
10204
10205 case bp_read_watchpoint:
10206 if (uiout->is_mi_like_p ())
10207 uiout->field_string
10208 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10209 break;
10210
10211 case bp_access_watchpoint:
10212 if (uiout->is_mi_like_p ())
10213 uiout->field_string
10214 ("reason",
10215 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10216 break;
10217 default:
10218 internal_error (_("Invalid hardware watchpoint type."));
10219 }
10220
10221 mention (this);
10222 uiout->text (_("\n\
10223 Check the underlying instruction at PC for the memory\n\
10224 address and value which triggered this watchpoint.\n"));
10225 uiout->text ("\n");
10226
10227 /* More than one watchpoint may have been triggered. */
10228 return PRINT_UNKNOWN;
10229 }
10230
10231 /* Implement the "print_one_detail" method for masked hardware
10232 watchpoints. */
10233
10234 void
10235 masked_watchpoint::print_one_detail (struct ui_out *uiout) const
10236 {
10237 /* Masked watchpoints have only one location. */
10238 gdb_assert (this->has_single_location ());
10239
10240 uiout->text ("\tmask ");
10241 uiout->field_core_addr ("mask", this->first_loc ().gdbarch, hw_wp_mask);
10242 uiout->text ("\n");
10243 }
10244
10245 /* Implement the "print_mention" method for masked hardware
10246 watchpoints. */
10247
10248 void
10249 masked_watchpoint::print_mention () const
10250 {
10251 struct ui_out *uiout = current_uiout;
10252 const char *tuple_name;
10253
10254 switch (type)
10255 {
10256 case bp_hardware_watchpoint:
10257 uiout->text ("Masked hardware watchpoint ");
10258 tuple_name = "wpt";
10259 break;
10260 case bp_read_watchpoint:
10261 uiout->text ("Masked hardware read watchpoint ");
10262 tuple_name = "hw-rwpt";
10263 break;
10264 case bp_access_watchpoint:
10265 uiout->text ("Masked hardware access (read/write) watchpoint ");
10266 tuple_name = "hw-awpt";
10267 break;
10268 default:
10269 internal_error (_("Invalid hardware watchpoint type."));
10270 }
10271
10272 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10273 uiout->field_signed ("number", number);
10274 uiout->text (": ");
10275 uiout->field_string ("exp", exp_string.get ());
10276 }
10277
10278 /* Implement the "print_recreate" method for masked hardware
10279 watchpoints. */
10280
10281 void
10282 masked_watchpoint::print_recreate (struct ui_file *fp) const
10283 {
10284 switch (type)
10285 {
10286 case bp_hardware_watchpoint:
10287 gdb_printf (fp, "watch");
10288 break;
10289 case bp_read_watchpoint:
10290 gdb_printf (fp, "rwatch");
10291 break;
10292 case bp_access_watchpoint:
10293 gdb_printf (fp, "awatch");
10294 break;
10295 default:
10296 internal_error (_("Invalid hardware watchpoint type."));
10297 }
10298
10299 gdb_printf (fp, " %s mask 0x%s", exp_string.get (),
10300 phex (hw_wp_mask));
10301 print_recreate_thread (fp);
10302 }
10303
10304 /* Tell whether the given watchpoint is a masked hardware watchpoint. */
10305
10306 static bool
10307 is_masked_watchpoint (const struct breakpoint *b)
10308 {
10309 return dynamic_cast<const masked_watchpoint *> (b) != nullptr;
10310 }
10311
10312 /* accessflag: hw_write: watch write,
10313 hw_read: watch read,
10314 hw_access: watch access (read or write) */
10315 static void
10316 watch_command_1 (const char *arg, int accessflag, int from_tty,
10317 bool just_location, bool internal)
10318 {
10319 struct breakpoint *scope_breakpoint = NULL;
10320 const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10321 struct value *result;
10322 int saved_bitpos = 0, saved_bitsize = 0;
10323 const char *exp_start = NULL;
10324 const char *exp_end = NULL;
10325 const char *tok, *end_tok;
10326 int toklen = -1;
10327 const char *cond_start = NULL;
10328 const char *cond_end = NULL;
10329 enum bptype bp_type;
10330 int thread = -1;
10331 int inferior = -1;
10332 /* Flag to indicate whether we are going to use masks for
10333 the hardware watchpoint. */
10334 bool use_mask = false;
10335 CORE_ADDR mask = 0;
10336 int task = -1;
10337
10338 /* Make sure that we actually have parameters to parse. */
10339 if (arg != NULL && arg[0] != '\0')
10340 {
10341 const char *value_start;
10342
10343 exp_end = arg + strlen (arg);
10344
10345 /* Look for "parameter value" pairs at the end
10346 of the arguments string. */
10347 for (tok = exp_end - 1; tok > arg; tok--)
10348 {
10349 /* Skip whitespace at the end of the argument list. */
10350 while (tok > arg && (*tok == ' ' || *tok == '\t'))
10351 tok--;
10352
10353 /* Find the beginning of the last token.
10354 This is the value of the parameter. */
10355 while (tok > arg && (*tok != ' ' && *tok != '\t'))
10356 tok--;
10357 value_start = tok + 1;
10358
10359 /* Skip whitespace. */
10360 while (tok > arg && (*tok == ' ' || *tok == '\t'))
10361 tok--;
10362
10363 end_tok = tok;
10364
10365 /* Find the beginning of the second to last token.
10366 This is the parameter itself. */
10367 while (tok > arg && (*tok != ' ' && *tok != '\t'))
10368 tok--;
10369 tok++;
10370 toklen = end_tok - tok + 1;
10371
10372 if (toklen == 6 && startswith (tok, "thread"))
10373 {
10374 struct thread_info *thr;
10375 /* At this point we've found a "thread" token, which means
10376 the user is trying to set a watchpoint that triggers
10377 only in a specific thread. */
10378 const char *endp;
10379
10380 if (thread != -1)
10381 error(_("You can specify only one thread."));
10382
10383 if (task != -1)
10384 error (_("You can specify only one of thread or task."));
10385
10386 if (inferior != -1)
10387 error (_("You can specify only one of inferior or thread."));
10388
10389 /* Extract the thread ID from the next token. */
10390 thr = parse_thread_id (value_start, &endp);
10391 if (value_start == endp)
10392 error (_("Junk after thread keyword."));
10393
10394 thread = thr->global_num;
10395 }
10396 else if (toklen == 4 && startswith (tok, "task"))
10397 {
10398 char *tmp;
10399
10400 if (task != -1)
10401 error(_("You can specify only one task."));
10402
10403 if (thread != -1)
10404 error (_("You can specify only one of thread or task."));
10405
10406 if (inferior != -1)
10407 error (_("You can specify only one of inferior or task."));
10408
10409 task = strtol (value_start, &tmp, 0);
10410 if (tmp == value_start)
10411 error (_("Junk after task keyword."));
10412 if (!valid_task_id (task))
10413 error (_("Unknown task %d."), task);
10414 }
10415 else if (toklen == 8 && startswith (tok, "inferior"))
10416 {
10417 /* Support for watchpoints will be added in a later commit. */
10418 error (_("Cannot use 'inferior' keyword with watchpoints"));
10419 }
10420 else if (toklen == 4 && startswith (tok, "mask"))
10421 {
10422 /* We've found a "mask" token, which means the user wants to
10423 create a hardware watchpoint that is going to have the mask
10424 facility. */
10425 struct value *mask_value;
10426
10427 if (use_mask)
10428 error(_("You can specify only one mask."));
10429
10430 use_mask = just_location = true;
10431
10432 scoped_value_mark mark;
10433 mask_value = parse_to_comma_and_eval (&value_start);
10434 mask = value_as_address (mask_value);
10435 }
10436 else
10437 /* We didn't recognize what we found. We should stop here. */
10438 break;
10439
10440 /* Truncate the string and get rid of the "parameter value" pair before
10441 the arguments string is parsed by the parse_exp_1 function. */
10442 exp_end = tok;
10443 }
10444 }
10445 else
10446 exp_end = arg;
10447
10448 /* Parse the rest of the arguments. From here on out, everything
10449 is in terms of a newly allocated string instead of the original
10450 ARG. */
10451 std::string expression (arg, exp_end - arg);
10452 exp_start = arg = expression.c_str ();
10453 innermost_block_tracker tracker;
10454 expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10455 exp_end = arg;
10456 /* Remove trailing whitespace from the expression before saving it.
10457 This makes the eventual display of the expression string a bit
10458 prettier. */
10459 while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10460 --exp_end;
10461
10462 /* Checking if the expression is not constant. */
10463 if (watchpoint_exp_is_const (exp.get ()))
10464 {
10465 int len;
10466
10467 len = exp_end - exp_start;
10468 while (len > 0 && isspace (exp_start[len - 1]))
10469 len--;
10470 error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10471 }
10472
10473 exp_valid_block = tracker.block ();
10474 struct value *mark = value_mark ();
10475 struct value *val_as_value = nullptr;
10476 fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
10477 just_location);
10478
10479 if (val_as_value != NULL && just_location)
10480 {
10481 saved_bitpos = val_as_value->bitpos ();
10482 saved_bitsize = val_as_value->bitsize ();
10483 }
10484
10485 value_ref_ptr val;
10486 if (just_location)
10487 {
10488 int ret;
10489
10490 exp_valid_block = NULL;
10491 val = release_value (value_addr (result));
10492 value_free_to_mark (mark);
10493
10494 if (use_mask)
10495 {
10496 ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10497 mask);
10498 if (ret == -1)
10499 error (_("This target does not support masked watchpoints."));
10500 else if (ret == -2)
10501 error (_("Invalid mask or memory region."));
10502 }
10503 }
10504 else if (val_as_value != NULL)
10505 val = release_value (val_as_value);
10506
10507 tok = skip_spaces (arg);
10508 end_tok = skip_to_space (tok);
10509
10510 toklen = end_tok - tok;
10511 if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10512 {
10513 tok = cond_start = end_tok + 1;
10514 innermost_block_tracker if_tracker;
10515 parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10516
10517 /* The watchpoint expression may not be local, but the condition
10518 may still be. E.g.: `watch global if local > 0'. */
10519 cond_exp_valid_block = if_tracker.block ();
10520
10521 cond_end = tok;
10522 }
10523 if (*tok)
10524 error (_("Junk at end of command."));
10525
10526 frame_info_ptr wp_frame = block_innermost_frame (exp_valid_block);
10527
10528 /* Save this because create_internal_breakpoint below invalidates
10529 'wp_frame'. */
10530 frame_id watchpoint_frame = get_frame_id (wp_frame);
10531
10532 /* Now set up the breakpoint. We create all watchpoints as hardware
10533 watchpoints here even if hardware watchpoints are turned off, a call
10534 to update_watchpoint later in this function will cause the type to
10535 drop back to bp_watchpoint (software watchpoint) if required. */
10536
10537 if (accessflag == hw_read)
10538 bp_type = bp_read_watchpoint;
10539 else if (accessflag == hw_access)
10540 bp_type = bp_access_watchpoint;
10541 else
10542 bp_type = bp_hardware_watchpoint;
10543
10544 std::unique_ptr<watchpoint> w;
10545 if (use_mask)
10546 w = std::make_unique<masked_watchpoint> (nullptr, bp_type);
10547 else
10548 w = std::make_unique<watchpoint> (nullptr, bp_type);
10549
10550 /* At most one of thread or task can be set on a watchpoint. */
10551 gdb_assert (thread == -1 || task == -1);
10552 w->thread = thread;
10553 w->inferior = inferior;
10554 w->task = task;
10555 w->disposition = disp_donttouch;
10556 w->pspace = current_program_space;
10557 w->exp = std::move (exp);
10558 w->exp_valid_block = exp_valid_block;
10559 w->cond_exp_valid_block = cond_exp_valid_block;
10560 if (just_location)
10561 {
10562 struct type *t = val->type ();
10563 CORE_ADDR addr = value_as_address (val.get ());
10564
10565 w->exp_string_reparse
10566 = current_language->watch_location_expression (t, addr);
10567
10568 w->exp_string = xstrprintf ("-location %.*s",
10569 (int) (exp_end - exp_start), exp_start);
10570 }
10571 else
10572 w->exp_string.reset (savestring (exp_start, exp_end - exp_start));
10573
10574 if (use_mask)
10575 {
10576 w->hw_wp_mask = mask;
10577 }
10578 else
10579 {
10580 w->val = val;
10581 w->val_bitpos = saved_bitpos;
10582 w->val_bitsize = saved_bitsize;
10583 w->val_valid = true;
10584 }
10585
10586 if (cond_start)
10587 w->cond_string.reset (savestring (cond_start, cond_end - cond_start));
10588 else
10589 w->cond_string = 0;
10590
10591 if (frame_id_p (watchpoint_frame))
10592 {
10593 w->watchpoint_frame = watchpoint_frame;
10594 w->watchpoint_thread = inferior_ptid;
10595 }
10596 else
10597 {
10598 w->watchpoint_frame = null_frame_id;
10599 w->watchpoint_thread = null_ptid;
10600 }
10601
10602 if (!just_location)
10603 value_free_to_mark (mark);
10604
10605 /* Finally update the new watchpoint. This creates the locations
10606 that should be inserted. */
10607 update_watchpoint (w.get (), true /* reparse */);
10608
10609 /* If the expression is "local", then set up a "watchpoint scope"
10610 breakpoint at the point where we've left the scope of the watchpoint
10611 expression. Create the scope breakpoint before the watchpoint, so
10612 that we will encounter it first in bpstat_stop_status. */
10613 if (exp_valid_block != nullptr && wp_frame != nullptr)
10614 {
10615 frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10616
10617 if (frame_id_p (caller_frame_id))
10618 {
10619 gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10620 CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10621
10622 scope_breakpoint
10623 = create_internal_breakpoint (caller_arch, caller_pc,
10624 bp_watchpoint_scope);
10625
10626 /* create_internal_breakpoint could invalidate WP_FRAME. */
10627 wp_frame = nullptr;
10628
10629 scope_breakpoint->enable_state = bp_enabled;
10630
10631 /* Automatically delete the breakpoint when it hits. */
10632 scope_breakpoint->disposition = disp_del;
10633
10634 /* Only break in the proper frame (help with recursion). */
10635 scope_breakpoint->frame_id = caller_frame_id;
10636
10637 /* Set the address at which we will stop. */
10638 bp_location &loc = scope_breakpoint->first_loc ();
10639 loc.gdbarch = caller_arch;
10640 loc.requested_address = caller_pc;
10641 loc.address
10642 = adjust_breakpoint_address (loc.gdbarch, loc.requested_address,
10643 scope_breakpoint->type,
10644 current_program_space);
10645 }
10646 }
10647
10648 if (scope_breakpoint != nullptr)
10649 {
10650 /* The scope breakpoint is related to the watchpoint. We will
10651 need to act on them together. */
10652 w->related_breakpoint = scope_breakpoint;
10653 scope_breakpoint->related_breakpoint = w.get ();
10654 }
10655
10656 /* Verify that the scope breakpoint comes before the watchpoint in the
10657 breakpoint chain. */
10658 gdb_assert (scope_breakpoint == nullptr
10659 || &breakpoint_chain.back () == scope_breakpoint);
10660 watchpoint *watchpoint_ptr = w.get ();
10661 install_breakpoint (internal, std::move (w), 1);
10662 gdb_assert (&breakpoint_chain.back () == watchpoint_ptr);
10663 }
10664
10665 /* Return count of debug registers needed to watch the given expression.
10666 If the watchpoint cannot be handled in hardware return zero. */
10667
10668 static int
10669 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10670 {
10671 int found_memory_cnt = 0;
10672
10673 /* Did the user specifically forbid us to use hardware watchpoints? */
10674 if (!can_use_hw_watchpoints)
10675 return 0;
10676
10677 gdb_assert (!vals.empty ());
10678 struct value *head = vals[0].get ();
10679
10680 /* Make sure that the value of the expression depends only upon
10681 memory contents, and values computed from them within GDB. If we
10682 find any register references or function calls, we can't use a
10683 hardware watchpoint.
10684
10685 The idea here is that evaluating an expression generates a series
10686 of values, one holding the value of every subexpression. (The
10687 expression a*b+c has five subexpressions: a, b, a*b, c, and
10688 a*b+c.) GDB's values hold almost enough information to establish
10689 the criteria given above --- they identify memory lvalues,
10690 register lvalues, computed values, etcetera. So we can evaluate
10691 the expression, and then scan the chain of values that leaves
10692 behind to decide whether we can detect any possible change to the
10693 expression's final value using only hardware watchpoints.
10694
10695 However, I don't think that the values returned by inferior
10696 function calls are special in any way. So this function may not
10697 notice that an expression involving an inferior function call
10698 can't be watched with hardware watchpoints. FIXME. */
10699 for (const value_ref_ptr &iter : vals)
10700 {
10701 struct value *v = iter.get ();
10702
10703 if (v->lval () == lval_memory)
10704 {
10705 if (v != head && v->lazy ())
10706 /* A lazy memory lvalue in the chain is one that GDB never
10707 needed to fetch; we either just used its address (e.g.,
10708 `a' in `a.b') or we never needed it at all (e.g., `a'
10709 in `a,b'). This doesn't apply to HEAD; if that is
10710 lazy then it was not readable, but watch it anyway. */
10711 ;
10712 else
10713 {
10714 /* Ahh, memory we actually used! Check if we can cover
10715 it with hardware watchpoints. */
10716 struct type *vtype = check_typedef (v->type ());
10717
10718 /* We only watch structs and arrays if user asked for it
10719 explicitly, never if they just happen to appear in a
10720 middle of some value chain. */
10721 if (v == head
10722 || (vtype->code () != TYPE_CODE_STRUCT
10723 && vtype->code () != TYPE_CODE_ARRAY))
10724 {
10725 CORE_ADDR vaddr = v->address ();
10726 int len;
10727 int num_regs;
10728
10729 len = (target_exact_watchpoints
10730 && is_scalar_type_recursive (vtype))?
10731 1 : v->type ()->length ();
10732
10733 num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10734 if (!num_regs)
10735 return 0;
10736 else
10737 found_memory_cnt += num_regs;
10738 }
10739 }
10740 }
10741 else if (v->lval () != not_lval && !v->deprecated_modifiable ())
10742 return 0; /* These are values from the history (e.g., $1). */
10743 else if (v->lval () == lval_register)
10744 return 0; /* Cannot watch a register with a HW watchpoint. */
10745 }
10746
10747 /* The expression itself looks suitable for using a hardware
10748 watchpoint, but give the target machine a chance to reject it. */
10749 return found_memory_cnt;
10750 }
10751
10752 void
10753 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10754 {
10755 watch_command_1 (arg, hw_write, from_tty, 0, internal);
10756 }
10757
10758 /* Options for the watch, awatch, and rwatch commands. */
10759
10760 struct watch_options
10761 {
10762 /* For -location. */
10763 bool location = false;
10764 };
10765
10766 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10767
10768 Historically GDB always accepted both '-location' and '-l' flags for
10769 these commands (both flags being synonyms). When converting to the
10770 newer option scheme only '-location' is added here. That's fine (for
10771 backward compatibility) as any non-ambiguous prefix of a flag will be
10772 accepted, so '-l', '-loc', are now all accepted.
10773
10774 What this means is that, if in the future, we add any new flag here
10775 that starts with '-l' then this will break backward compatibility, so
10776 please, don't do that! */
10777
10778 static const gdb::option::option_def watch_option_defs[] = {
10779 gdb::option::flag_option_def<watch_options> {
10780 "location",
10781 [] (watch_options *opt) { return &opt->location; },
10782 N_("\
10783 This evaluates EXPRESSION and watches the memory to which it refers.\n\
10784 -l can be used as a short form of -location."),
10785 },
10786 };
10787
10788 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
10789 commands. */
10790
10791 static gdb::option::option_def_group
10792 make_watch_options_def_group (watch_options *opts)
10793 {
10794 return {{watch_option_defs}, opts};
10795 }
10796
10797 /* A helper function that looks for the "-location" argument and then
10798 calls watch_command_1. */
10799
10800 static void
10801 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10802 {
10803 watch_options opts;
10804 auto grp = make_watch_options_def_group (&opts);
10805 gdb::option::process_options
10806 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
10807 if (arg != nullptr && *arg == '\0')
10808 arg = nullptr;
10809
10810 watch_command_1 (arg, accessflag, from_tty, opts.location, false);
10811 }
10812
10813 /* Command completion for 'watch', 'awatch', and 'rwatch' commands. */
10814 static void
10815 watch_command_completer (struct cmd_list_element *ignore,
10816 completion_tracker &tracker,
10817 const char *text, const char * /*word*/)
10818 {
10819 const auto group = make_watch_options_def_group (nullptr);
10820 if (gdb::option::complete_options
10821 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
10822 return;
10823
10824 const char *word = advance_to_expression_complete_word_point (tracker, text);
10825 expression_completer (ignore, tracker, text, word);
10826 }
10827
10828 static void
10829 watch_command (const char *arg, int from_tty)
10830 {
10831 watch_maybe_just_location (arg, hw_write, from_tty);
10832 }
10833
10834 void
10835 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
10836 {
10837 watch_command_1 (arg, hw_read, from_tty, 0, internal);
10838 }
10839
10840 static void
10841 rwatch_command (const char *arg, int from_tty)
10842 {
10843 watch_maybe_just_location (arg, hw_read, from_tty);
10844 }
10845
10846 void
10847 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
10848 {
10849 watch_command_1 (arg, hw_access, from_tty, 0, internal);
10850 }
10851
10852 static void
10853 awatch_command (const char *arg, int from_tty)
10854 {
10855 watch_maybe_just_location (arg, hw_access, from_tty);
10856 }
10857 \f
10858
10859 /* Data for the FSM that manages the until(location)/advance commands
10860 in infcmd.c. Here because it uses the mechanisms of
10861 breakpoints. */
10862
10863 struct until_break_fsm : public thread_fsm
10864 {
10865 /* The thread that was current when the command was executed. */
10866 int thread;
10867
10868 /* The breakpoint set at the return address in the caller frame,
10869 plus breakpoints at all the destination locations. */
10870 std::vector<breakpoint_up> breakpoints;
10871
10872 until_break_fsm (struct interp *cmd_interp, int thread,
10873 std::vector<breakpoint_up> &&breakpoints)
10874 : thread_fsm (cmd_interp),
10875 thread (thread),
10876 breakpoints (std::move (breakpoints))
10877 {
10878 }
10879
10880 void clean_up (struct thread_info *thread) override;
10881 bool should_stop (struct thread_info *thread) override;
10882 enum async_reply_reason do_async_reply_reason () override;
10883 };
10884
10885 /* Implementation of the 'should_stop' FSM method for the
10886 until(location)/advance commands. */
10887
10888 bool
10889 until_break_fsm::should_stop (struct thread_info *tp)
10890 {
10891 for (const breakpoint_up &bp : breakpoints)
10892 if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10893 bp.get ()) != NULL)
10894 {
10895 set_finished ();
10896 break;
10897 }
10898
10899 return true;
10900 }
10901
10902 /* Implementation of the 'clean_up' FSM method for the
10903 until(location)/advance commands. */
10904
10905 void
10906 until_break_fsm::clean_up (struct thread_info *)
10907 {
10908 /* Clean up our temporary breakpoints. */
10909 breakpoints.clear ();
10910 delete_longjmp_breakpoint (thread);
10911 }
10912
10913 /* Implementation of the 'async_reply_reason' FSM method for the
10914 until(location)/advance commands. */
10915
10916 enum async_reply_reason
10917 until_break_fsm::do_async_reply_reason ()
10918 {
10919 return EXEC_ASYNC_LOCATION_REACHED;
10920 }
10921
10922 void
10923 until_break_command (const char *arg, int from_tty, int anywhere)
10924 {
10925 frame_info_ptr frame;
10926 struct gdbarch *frame_gdbarch;
10927 struct frame_id stack_frame_id;
10928 struct frame_id caller_frame_id;
10929 int thread;
10930 struct thread_info *tp;
10931
10932 clear_proceed_status (0);
10933
10934 /* Set a breakpoint where the user wants it and at return from
10935 this function. */
10936
10937 location_spec_up locspec = string_to_location_spec (&arg, current_language);
10938
10939 std::vector<symtab_and_line> sals
10940 = (last_displayed_sal_is_valid ()
10941 ? decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10942 get_last_displayed_symtab (),
10943 get_last_displayed_line ())
10944 : decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE,
10945 NULL, NULL, 0));
10946
10947 if (sals.empty ())
10948 error (_("Couldn't get information on specified line."));
10949
10950 if (*arg)
10951 error (_("Junk at end of arguments."));
10952
10953 tp = inferior_thread ();
10954 thread = tp->global_num;
10955
10956 /* Note linespec handling above invalidates the frame chain.
10957 Installing a breakpoint also invalidates the frame chain (as it
10958 may need to switch threads), so do any frame handling before
10959 that. */
10960
10961 frame = get_selected_frame (NULL);
10962 frame_gdbarch = get_frame_arch (frame);
10963 stack_frame_id = get_stack_frame_id (frame);
10964 caller_frame_id = frame_unwind_caller_id (frame);
10965
10966 /* Keep within the current frame, or in frames called by the current
10967 one. */
10968
10969 std::vector<breakpoint_up> breakpoints;
10970
10971 std::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
10972
10973 if (frame_id_p (caller_frame_id))
10974 {
10975 struct symtab_and_line sal2;
10976 struct gdbarch *caller_gdbarch;
10977
10978 sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10979 sal2.pc = frame_unwind_caller_pc (frame);
10980 caller_gdbarch = frame_unwind_caller_arch (frame);
10981
10982 breakpoint_up caller_breakpoint
10983 = set_momentary_breakpoint (caller_gdbarch, sal2,
10984 caller_frame_id, bp_until);
10985 breakpoints.emplace_back (std::move (caller_breakpoint));
10986
10987 set_longjmp_breakpoint (tp, stack_frame_id);
10988 lj_deleter.emplace (thread);
10989 }
10990
10991 /* If the user told us to continue until a specified location, we
10992 don't specify a frame at which we need to stop. Otherwise,
10993 specify the selected frame, because we want to stop only at the
10994 very same frame. */
10995 frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
10996
10997 for (symtab_and_line &sal : sals)
10998 {
10999 resolve_sal_pc (&sal);
11000
11001 breakpoint_up location_breakpoint
11002 = set_momentary_breakpoint (frame_gdbarch, sal,
11003 stop_frame_id, bp_until);
11004 breakpoints.emplace_back (std::move (location_breakpoint));
11005 }
11006
11007 tp->set_thread_fsm
11008 (std::unique_ptr<thread_fsm>
11009 (new until_break_fsm (command_interp (), tp->global_num,
11010 std::move (breakpoints))));
11011
11012 if (lj_deleter)
11013 lj_deleter->release ();
11014
11015 proceed (-1, GDB_SIGNAL_DEFAULT);
11016 }
11017
11018 \f
11019
11020 /* Compare two breakpoints and return a strcmp-like result. */
11021
11022 static int
11023 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11024 {
11025 uintptr_t ua = (uintptr_t) a;
11026 uintptr_t ub = (uintptr_t) b;
11027
11028 if (a->number < b->number)
11029 return -1;
11030 else if (a->number > b->number)
11031 return 1;
11032
11033 /* Now sort by address, in case we see, e..g, two breakpoints with
11034 the number 0. */
11035 if (ua < ub)
11036 return -1;
11037 return ua > ub ? 1 : 0;
11038 }
11039
11040 /* Delete breakpoints by address or line. */
11041
11042 static void
11043 clear_command (const char *arg, int from_tty)
11044 {
11045 int default_match;
11046
11047 std::vector<symtab_and_line> decoded_sals;
11048 symtab_and_line last_sal;
11049 gdb::array_view<symtab_and_line> sals;
11050 if (arg)
11051 {
11052 decoded_sals
11053 = decode_line_with_current_source (arg,
11054 (DECODE_LINE_FUNFIRSTLINE
11055 | DECODE_LINE_LIST_MODE));
11056 default_match = 0;
11057 sals = decoded_sals;
11058 }
11059 else
11060 {
11061 /* Set sal's line, symtab, pc, and pspace to the values
11062 corresponding to the last call to print_frame_info. If the
11063 codepoint is not valid, this will set all the fields to 0. */
11064 last_sal = get_last_displayed_sal ();
11065 if (last_sal.symtab == 0)
11066 error (_("No source file specified."));
11067
11068 default_match = 1;
11069 sals = last_sal;
11070 }
11071
11072 /* We don't call resolve_sal_pc here. That's not as bad as it
11073 seems, because all existing breakpoints typically have both
11074 file/line and pc set. So, if clear is given file/line, we can
11075 match this to existing breakpoint without obtaining pc at all.
11076
11077 We only support clearing given the address explicitly
11078 present in breakpoint table. Say, we've set breakpoint
11079 at file:line. There were several PC values for that file:line,
11080 due to optimization, all in one block.
11081
11082 We've picked one PC value. If "clear" is issued with another
11083 PC corresponding to the same file:line, the breakpoint won't
11084 be cleared. We probably can still clear the breakpoint, but
11085 since the other PC value is never presented to user, user
11086 can only find it by guessing, and it does not seem important
11087 to support that. */
11088
11089 /* For each line spec given, delete bps which correspond to it. Do
11090 it in two passes, solely to preserve the current behavior that
11091 from_tty is forced true if we delete more than one
11092 breakpoint. */
11093
11094 std::vector<struct breakpoint *> found;
11095 for (const auto &sal : sals)
11096 {
11097 const char *sal_fullname;
11098
11099 /* If exact pc given, clear bpts at that pc.
11100 If line given (pc == 0), clear all bpts on specified line.
11101 If defaulting, clear all bpts on default line
11102 or at default pc.
11103
11104 defaulting sal.pc != 0 tests to do
11105
11106 0 1 pc
11107 1 1 pc _and_ line
11108 0 0 line
11109 1 0 <can't happen> */
11110
11111 sal_fullname = (sal.symtab == NULL
11112 ? NULL : symtab_to_fullname (sal.symtab));
11113
11114 /* Find all matching breakpoints and add them to 'found'. */
11115 for (breakpoint &b : all_breakpoints ())
11116 {
11117 int match = 0;
11118 /* Are we going to delete b? */
11119 if (b.type != bp_none && !is_watchpoint (&b)
11120 && user_breakpoint_p (&b))
11121 {
11122 for (bp_location &loc : b.locations ())
11123 {
11124 /* If the user specified file:line, don't allow a PC
11125 match. This matches historical gdb behavior. */
11126 int pc_match = (!sal.explicit_line
11127 && sal.pc
11128 && (loc.pspace == sal.pspace)
11129 && (loc.address == sal.pc)
11130 && (!section_is_overlay (loc.section)
11131 || loc.section == sal.section));
11132 int line_match = 0;
11133
11134 if ((default_match || sal.explicit_line)
11135 && loc.symtab != NULL
11136 && sal_fullname != NULL
11137 && sal.pspace == loc.pspace
11138 && loc.line_number == sal.line
11139 && filename_cmp (symtab_to_fullname (loc.symtab),
11140 sal_fullname) == 0)
11141 line_match = 1;
11142
11143 if (pc_match || line_match)
11144 {
11145 match = 1;
11146 break;
11147 }
11148 }
11149 }
11150
11151 if (match)
11152 found.push_back (&b);
11153 }
11154 }
11155
11156 /* Now go through the 'found' chain and delete them. */
11157 if (found.empty ())
11158 {
11159 if (arg)
11160 error (_("No breakpoint at %s."), arg);
11161 else
11162 error (_("No breakpoint at this line."));
11163 }
11164
11165 /* Remove duplicates from the vec. */
11166 std::sort (found.begin (), found.end (),
11167 [] (const breakpoint *bp_a, const breakpoint *bp_b)
11168 {
11169 return compare_breakpoints (bp_a, bp_b) < 0;
11170 });
11171 found.erase (std::unique (found.begin (), found.end (),
11172 [] (const breakpoint *bp_a, const breakpoint *bp_b)
11173 {
11174 return compare_breakpoints (bp_a, bp_b) == 0;
11175 }),
11176 found.end ());
11177
11178 if (found.size () > 1)
11179 from_tty = 1; /* Always report if deleted more than one. */
11180 if (from_tty)
11181 {
11182 if (found.size () == 1)
11183 gdb_printf (_("Deleted breakpoint "));
11184 else
11185 gdb_printf (_("Deleted breakpoints "));
11186 }
11187
11188 for (breakpoint *iter : found)
11189 {
11190 if (from_tty)
11191 gdb_printf ("%d ", iter->number);
11192 delete_breakpoint (iter);
11193 }
11194 if (from_tty)
11195 gdb_putc ('\n');
11196 }
11197 \f
11198 /* Delete breakpoint in BS if they are `delete' breakpoints and
11199 all breakpoints that are marked for deletion, whether hit or not.
11200 This is called after any breakpoint is hit, or after errors. */
11201
11202 void
11203 breakpoint_auto_delete (bpstat *bs)
11204 {
11205 for (; bs; bs = bs->next)
11206 if (bs->breakpoint_at
11207 && bs->breakpoint_at->disposition == disp_del
11208 && bs->stop)
11209 delete_breakpoint (bs->breakpoint_at);
11210
11211 for (breakpoint &b : all_breakpoints_safe ())
11212 if (b.disposition == disp_del_at_next_stop)
11213 delete_breakpoint (&b);
11214 }
11215
11216 /* A comparison function for bp_location pointers A and B being interfaced to
11217 std::sort, for instance to sort an std::vector<bp_location *>. Sort
11218 elements:
11219 - primarily by their ADDRESS (no matter what bl_address_is_meaningful
11220 says),
11221 - secondarily by ordering first permanent elements, and
11222 - tertiarily just ensuring the array is sorted in a stable way despite
11223 std::sort being an unstable algorithm. */
11224
11225 static bool
11226 bp_location_ptr_is_less_than (const bp_location *a, const bp_location *b)
11227 {
11228 if (a->address != b->address)
11229 return a->address < b->address;
11230
11231 /* Sort locations at the same address by their pspace number, keeping
11232 locations of the same inferior (in a multi-inferior environment)
11233 grouped. */
11234
11235 if (a->pspace->num != b->pspace->num)
11236 return a->pspace->num < b->pspace->num;
11237
11238 /* Sort permanent breakpoints first. */
11239 if (a->permanent != b->permanent)
11240 return a->permanent > b->permanent;
11241
11242 /* Sort by type in order to make duplicate determination easier.
11243 See update_global_location_list. This is kept in sync with
11244 breakpoint_locations_match. */
11245 if (a->loc_type < b->loc_type)
11246 return true;
11247
11248 /* Likewise, for range-breakpoints, sort by length. */
11249 if (a->loc_type == bp_loc_hardware_breakpoint
11250 && b->loc_type == bp_loc_hardware_breakpoint
11251 && a->length < b->length)
11252 return true;
11253
11254 /* Make the internal GDB representation stable across GDB runs
11255 where A and B memory inside GDB can differ. Breakpoint locations of
11256 the same type at the same address can be sorted in arbitrary order. */
11257
11258 if (a->owner->number != b->owner->number)
11259 return a->owner->number < b->owner->number;
11260
11261 return a < b;
11262 }
11263
11264 /* A comparison function for bp_locations A and B being interfaced to
11265 std::sort, for instance to sort an std::vector<bp_location>. */
11266
11267 static bool
11268 bp_location_is_less_than (const bp_location &a, const bp_location &b)
11269 {
11270 return bp_location_ptr_is_less_than (&a, &b);
11271 }
11272
11273 /* Set bp_locations_placed_address_before_address_max and
11274 bp_locations_shadow_len_after_address_max according to the current
11275 content of the bp_locations array. */
11276
11277 static void
11278 bp_locations_target_extensions_update (void)
11279 {
11280 bp_locations_placed_address_before_address_max = 0;
11281 bp_locations_shadow_len_after_address_max = 0;
11282
11283 for (bp_location *bl : all_bp_locations ())
11284 {
11285 CORE_ADDR start, end, addr;
11286
11287 if (!bp_location_has_shadow (bl))
11288 continue;
11289
11290 start = bl->target_info.placed_address;
11291 end = start + bl->target_info.shadow_len;
11292
11293 gdb_assert (bl->address >= start);
11294 addr = bl->address - start;
11295 if (addr > bp_locations_placed_address_before_address_max)
11296 bp_locations_placed_address_before_address_max = addr;
11297
11298 /* Zero SHADOW_LEN would not pass bp_location_has_shadow. */
11299
11300 gdb_assert (bl->address < end);
11301 addr = end - bl->address;
11302 if (addr > bp_locations_shadow_len_after_address_max)
11303 bp_locations_shadow_len_after_address_max = addr;
11304 }
11305 }
11306
11307 /* Download tracepoint locations if they haven't been. */
11308
11309 static void
11310 download_tracepoint_locations (void)
11311 {
11312 enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11313
11314 scoped_restore_current_pspace_and_thread restore_pspace_thread;
11315
11316 for (breakpoint &b : all_tracepoints ())
11317 {
11318 bool bp_location_downloaded = false;
11319
11320 if ((b.type == bp_fast_tracepoint
11321 ? !may_insert_fast_tracepoints
11322 : !may_insert_tracepoints))
11323 continue;
11324
11325 if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11326 {
11327 if (target_can_download_tracepoint ())
11328 can_download_tracepoint = TRIBOOL_TRUE;
11329 else
11330 can_download_tracepoint = TRIBOOL_FALSE;
11331 }
11332
11333 if (can_download_tracepoint == TRIBOOL_FALSE)
11334 break;
11335
11336 for (bp_location &bl : b.locations ())
11337 {
11338 /* In tracepoint, locations are _never_ duplicated, so
11339 should_be_inserted is equivalent to
11340 unduplicated_should_be_inserted. */
11341 if (!should_be_inserted (&bl) || bl.inserted)
11342 continue;
11343
11344 switch_to_program_space_and_thread (bl.pspace);
11345
11346 target_download_tracepoint (&bl);
11347
11348 bl.inserted = 1;
11349 bp_location_downloaded = true;
11350 }
11351
11352 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
11353 t.number_on_target = b.number;
11354 if (bp_location_downloaded)
11355 notify_breakpoint_modified (&b);
11356 }
11357 }
11358
11359 /* Swap the insertion/duplication state between two locations. */
11360
11361 static void
11362 swap_insertion (struct bp_location *left, struct bp_location *right)
11363 {
11364 const int left_inserted = left->inserted;
11365 const int left_duplicate = left->duplicate;
11366 const int left_needs_update = left->needs_update;
11367 const struct bp_target_info left_target_info = left->target_info;
11368
11369 /* Locations of tracepoints can never be duplicated. */
11370 if (is_tracepoint (left->owner))
11371 gdb_assert (!left->duplicate);
11372 if (is_tracepoint (right->owner))
11373 gdb_assert (!right->duplicate);
11374
11375 left->inserted = right->inserted;
11376 left->duplicate = right->duplicate;
11377 left->needs_update = right->needs_update;
11378 left->target_info = right->target_info;
11379 right->inserted = left_inserted;
11380 right->duplicate = left_duplicate;
11381 right->needs_update = left_needs_update;
11382 right->target_info = left_target_info;
11383 }
11384
11385 /* Force the re-insertion of the locations at ADDRESS. This is called
11386 once a new/deleted/modified duplicate location is found and we are evaluating
11387 conditions on the target's side. Such conditions need to be updated on
11388 the target. */
11389
11390 static void
11391 force_breakpoint_reinsertion (struct bp_location *bl)
11392 {
11393 CORE_ADDR address = 0;
11394 int pspace_num;
11395
11396 address = bl->address;
11397 pspace_num = bl->pspace->num;
11398
11399 /* This is only meaningful if the target is
11400 evaluating conditions and if the user has
11401 opted for condition evaluation on the target's
11402 side. */
11403 if (gdb_evaluates_breakpoint_condition_p ()
11404 || !target_supports_evaluation_of_breakpoint_conditions ())
11405 return;
11406
11407 /* Flag all breakpoint locations with this address and
11408 the same program space as the location
11409 as "its condition has changed". We need to
11410 update the conditions on the target's side. */
11411 for (bp_location *loc : all_bp_locations_at_addr (address))
11412 {
11413 if (!is_breakpoint (loc->owner)
11414 || pspace_num != loc->pspace->num)
11415 continue;
11416
11417 /* Flag the location appropriately. We use a different state to
11418 let everyone know that we already updated the set of locations
11419 with addr bl->address and program space bl->pspace. This is so
11420 we don't have to keep calling these functions just to mark locations
11421 that have already been marked. */
11422 loc->condition_changed = condition_updated;
11423
11424 /* Free the agent expression bytecode as well. We will compute
11425 it later on. */
11426 loc->cond_bytecode.reset ();
11427 }
11428 }
11429
11430 /* Called whether new breakpoints are created, or existing breakpoints
11431 deleted, to update the global location list and recompute which
11432 locations are duplicate of which.
11433
11434 The INSERT_MODE flag determines whether locations may not, may, or
11435 shall be inserted now. See 'enum ugll_insert_mode' for more
11436 info. */
11437
11438 static void
11439 update_global_location_list (enum ugll_insert_mode insert_mode)
11440 {
11441 /* Last breakpoint location address that was marked for update. */
11442 CORE_ADDR last_addr = 0;
11443 /* Last breakpoint location program space that was marked for update. */
11444 int last_pspace_num = -1;
11445
11446 breakpoint_debug_printf ("insert_mode = %s",
11447 ugll_insert_mode_text (insert_mode));
11448
11449 /* Used in the duplicates detection below. When iterating over all
11450 bp_locations, points to the first bp_location of a given address.
11451 Breakpoints and watchpoints of different types are never
11452 duplicates of each other. Keep one pointer for each type of
11453 breakpoint/watchpoint, so we only need to loop over all locations
11454 once. */
11455 struct bp_location *bp_loc_first; /* breakpoint */
11456 struct bp_location *wp_loc_first; /* hardware watchpoint */
11457 struct bp_location *awp_loc_first; /* access watchpoint */
11458 struct bp_location *rwp_loc_first; /* read watchpoint */
11459
11460 /* Saved former bp_locations array which we compare against the newly
11461 built bp_locations from the current state of ALL_BREAKPOINTS. */
11462 std::vector<bp_location *> old_locations = std::move (bp_locations);
11463 bp_locations.clear ();
11464
11465 for (breakpoint &b : all_breakpoints ())
11466 for (bp_location &loc : b.locations ())
11467 bp_locations.push_back (&loc);
11468
11469 /* See if we need to "upgrade" a software breakpoint to a hardware
11470 breakpoint. Do this before deciding whether locations are
11471 duplicates. Also do this before sorting because sorting order
11472 depends on location type. */
11473 for (bp_location *loc : bp_locations)
11474 if (!loc->inserted && should_be_inserted (loc))
11475 handle_automatic_hardware_breakpoints (loc);
11476
11477 std::sort (bp_locations.begin (), bp_locations.end (),
11478 bp_location_ptr_is_less_than);
11479
11480 bp_locations_target_extensions_update ();
11481
11482 /* Identify bp_location instances that are no longer present in the
11483 new list, and therefore should be freed. Note that it's not
11484 necessary that those locations should be removed from inferior --
11485 if there's another location at the same address (previously
11486 marked as duplicate), we don't need to remove/insert the
11487 location.
11488
11489 LOCP is kept in sync with OLD_LOCP, each pointing to the current
11490 and former bp_location array state respectively. */
11491
11492 size_t loc_i = 0;
11493 for (bp_location *old_loc : old_locations)
11494 {
11495 /* Tells if 'old_loc' is found among the new locations. If
11496 not, we have to free it. */
11497 bool found_object = false;
11498 /* Tells if the location should remain inserted in the target. */
11499 bool keep_in_target = false;
11500 bool removed = false;
11501
11502 /* Skip LOCP entries which will definitely never be needed.
11503 Stop either at or being the one matching OLD_LOC. */
11504 while (loc_i < bp_locations.size ()
11505 && bp_locations[loc_i]->address < old_loc->address)
11506 loc_i++;
11507
11508 for (size_t loc2_i = loc_i;
11509 (loc2_i < bp_locations.size ()
11510 && bp_locations[loc2_i]->address == old_loc->address);
11511 loc2_i++)
11512 {
11513 /* Check if this is a new/duplicated location or a duplicated
11514 location that had its condition modified. If so, we want to send
11515 its condition to the target if evaluation of conditions is taking
11516 place there. */
11517 if (bp_locations[loc2_i]->condition_changed == condition_modified
11518 && (last_addr != old_loc->address
11519 || last_pspace_num != old_loc->pspace->num))
11520 {
11521 force_breakpoint_reinsertion (bp_locations[loc2_i]);
11522 last_pspace_num = old_loc->pspace->num;
11523 }
11524
11525 if (bp_locations[loc2_i] == old_loc)
11526 found_object = true;
11527 }
11528
11529 /* We have already handled this address, update it so that we don't
11530 have to go through updates again. */
11531 last_addr = old_loc->address;
11532
11533 /* Target-side condition evaluation: Handle deleted locations. */
11534 if (!found_object)
11535 force_breakpoint_reinsertion (old_loc);
11536
11537 /* If this location is no longer present, and inserted, look if
11538 there's maybe a new location at the same address. If so,
11539 mark that one inserted, and don't remove this one. This is
11540 needed so that we don't have a time window where a breakpoint
11541 at certain location is not inserted. */
11542
11543 if (old_loc->inserted)
11544 {
11545 /* If the location is inserted now, we might have to remove
11546 it. */
11547
11548 if (found_object && should_be_inserted (old_loc))
11549 {
11550 /* The location is still present in the location list,
11551 and still should be inserted. Don't do anything. */
11552 keep_in_target = true;
11553 }
11554 else
11555 {
11556 /* This location still exists, but it won't be kept in the
11557 target since it may have been disabled. We proceed to
11558 remove its target-side condition. */
11559
11560 /* The location is either no longer present, or got
11561 disabled. See if there's another location at the
11562 same address, in which case we don't need to remove
11563 this one from the target. */
11564
11565 /* OLD_LOC comes from existing struct breakpoint. */
11566 if (bl_address_is_meaningful (old_loc))
11567 {
11568 for (size_t loc2_i = loc_i;
11569 (loc2_i < bp_locations.size ()
11570 && bp_locations[loc2_i]->address == old_loc->address);
11571 loc2_i++)
11572 {
11573 bp_location *loc2 = bp_locations[loc2_i];
11574
11575 if (loc2 == old_loc)
11576 continue;
11577
11578 if (breakpoint_locations_match (loc2, old_loc))
11579 {
11580 /* Read watchpoint locations are switched to
11581 access watchpoints, if the former are not
11582 supported, but the latter are. */
11583 if (is_hardware_watchpoint (old_loc->owner))
11584 {
11585 gdb_assert (is_hardware_watchpoint (loc2->owner));
11586 loc2->watchpoint_type = old_loc->watchpoint_type;
11587 }
11588
11589 /* loc2 is a duplicated location. We need to check
11590 if it should be inserted in case it will be
11591 unduplicated. */
11592 if (unduplicated_should_be_inserted (loc2))
11593 {
11594 swap_insertion (old_loc, loc2);
11595 keep_in_target = true;
11596 break;
11597 }
11598 }
11599 }
11600 }
11601 }
11602
11603 if (!keep_in_target)
11604 {
11605 if (remove_breakpoint (old_loc))
11606 {
11607 /* This is just about all we can do. We could keep
11608 this location on the global list, and try to
11609 remove it next time, but there's no particular
11610 reason why we will succeed next time.
11611
11612 Note that at this point, old_loc->owner is still
11613 valid, as delete_breakpoint frees the breakpoint
11614 only after calling us. */
11615 warning (_("error removing breakpoint %d at %s"),
11616 old_loc->owner->number,
11617 paddress (old_loc->gdbarch, old_loc->address));
11618 }
11619 removed = true;
11620 }
11621 }
11622
11623 if (!found_object)
11624 {
11625 if (removed && target_is_non_stop_p ()
11626 && need_moribund_for_location_type (old_loc))
11627 {
11628 /* This location was removed from the target. In
11629 non-stop mode, a race condition is possible where
11630 we've removed a breakpoint, but stop events for that
11631 breakpoint are already queued and will arrive later.
11632 We apply an heuristic to be able to distinguish such
11633 SIGTRAPs from other random SIGTRAPs: we keep this
11634 breakpoint location for a bit, and will retire it
11635 after we see some number of events. The theory here
11636 is that reporting of events should, "on the average",
11637 be fair, so after a while we'll see events from all
11638 threads that have anything of interest, and no longer
11639 need to keep this breakpoint location around. We
11640 don't hold locations forever so to reduce chances of
11641 mistaking a non-breakpoint SIGTRAP for a breakpoint
11642 SIGTRAP.
11643
11644 The heuristic failing can be disastrous on
11645 decr_pc_after_break targets.
11646
11647 On decr_pc_after_break targets, like e.g., x86-linux,
11648 if we fail to recognize a late breakpoint SIGTRAP,
11649 because events_till_retirement has reached 0 too
11650 soon, we'll fail to do the PC adjustment, and report
11651 a random SIGTRAP to the user. When the user resumes
11652 the inferior, it will most likely immediately crash
11653 with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11654 corrupted, because of being resumed e.g., in the
11655 middle of a multi-byte instruction, or skipped a
11656 one-byte instruction. This was actually seen happen
11657 on native x86-linux, and should be less rare on
11658 targets that do not support new thread events, like
11659 remote, due to the heuristic depending on
11660 thread_count.
11661
11662 Mistaking a random SIGTRAP for a breakpoint trap
11663 causes similar symptoms (PC adjustment applied when
11664 it shouldn't), but then again, playing with SIGTRAPs
11665 behind the debugger's back is asking for trouble.
11666
11667 Since hardware watchpoint traps are always
11668 distinguishable from other traps, so we don't need to
11669 apply keep hardware watchpoint moribund locations
11670 around. We simply always ignore hardware watchpoint
11671 traps we can no longer explain. */
11672
11673 process_stratum_target *proc_target = nullptr;
11674 for (inferior *inf : all_inferiors ())
11675 if (inf->pspace == old_loc->pspace)
11676 {
11677 proc_target = inf->process_target ();
11678 break;
11679 }
11680 if (proc_target != nullptr)
11681 old_loc->events_till_retirement
11682 = 3 * (thread_count (proc_target) + 1);
11683 else
11684 old_loc->events_till_retirement = 1;
11685 old_loc->owner = NULL;
11686
11687 moribund_locations.push_back (old_loc);
11688 }
11689 else
11690 {
11691 old_loc->owner = NULL;
11692 decref_bp_location (&old_loc);
11693 }
11694 }
11695 }
11696
11697 /* Rescan breakpoints at the same address and section, marking the
11698 first one as "first" and any others as "duplicates". This is so
11699 that the bpt instruction is only inserted once. If we have a
11700 permanent breakpoint at the same place as BPT, make that one the
11701 official one, and the rest as duplicates. Permanent breakpoints
11702 are sorted first for the same address.
11703
11704 Do the same for hardware watchpoints, but also considering the
11705 watchpoint's type (regular/access/read) and length. */
11706
11707 bp_loc_first = NULL;
11708 wp_loc_first = NULL;
11709 awp_loc_first = NULL;
11710 rwp_loc_first = NULL;
11711
11712 for (bp_location *loc : all_bp_locations ())
11713 {
11714 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11715 non-NULL. */
11716 struct bp_location **loc_first_p;
11717 breakpoint *b = loc->owner;
11718
11719 if (!unduplicated_should_be_inserted (loc)
11720 || !bl_address_is_meaningful (loc)
11721 /* Don't detect duplicate for tracepoint locations because they are
11722 never duplicated. See the comments in field `duplicate' of
11723 `struct bp_location'. */
11724 || is_tracepoint (b))
11725 {
11726 /* Clear the condition modification flag. */
11727 loc->condition_changed = condition_unchanged;
11728 continue;
11729 }
11730
11731 if (b->type == bp_hardware_watchpoint)
11732 loc_first_p = &wp_loc_first;
11733 else if (b->type == bp_read_watchpoint)
11734 loc_first_p = &rwp_loc_first;
11735 else if (b->type == bp_access_watchpoint)
11736 loc_first_p = &awp_loc_first;
11737 else
11738 loc_first_p = &bp_loc_first;
11739
11740 if (*loc_first_p == NULL
11741 || (overlay_debugging && loc->section != (*loc_first_p)->section)
11742 || !breakpoint_locations_match (loc, *loc_first_p))
11743 {
11744 *loc_first_p = loc;
11745 loc->duplicate = 0;
11746
11747 if (is_breakpoint (loc->owner) && loc->condition_changed)
11748 {
11749 loc->needs_update = 1;
11750 /* Clear the condition modification flag. */
11751 loc->condition_changed = condition_unchanged;
11752 }
11753 continue;
11754 }
11755
11756
11757 /* This and the above ensure the invariant that the first location
11758 is not duplicated, and is the inserted one.
11759 All following are marked as duplicated, and are not inserted. */
11760 if (loc->inserted)
11761 swap_insertion (loc, *loc_first_p);
11762 loc->duplicate = 1;
11763
11764 /* Clear the condition modification flag. */
11765 loc->condition_changed = condition_unchanged;
11766 }
11767
11768 if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
11769 {
11770 if (insert_mode != UGLL_DONT_INSERT)
11771 insert_breakpoint_locations ();
11772 else
11773 {
11774 /* Even though the caller told us to not insert new
11775 locations, we may still need to update conditions on the
11776 target's side of breakpoints that were already inserted
11777 if the target is evaluating breakpoint conditions. We
11778 only update conditions for locations that are marked
11779 "needs_update". */
11780 update_inserted_breakpoint_locations ();
11781 }
11782 }
11783
11784 if (insert_mode != UGLL_DONT_INSERT)
11785 download_tracepoint_locations ();
11786 }
11787
11788 void
11789 breakpoint_retire_moribund (void)
11790 {
11791 for (int ix = 0; ix < moribund_locations.size (); ++ix)
11792 {
11793 struct bp_location *loc = moribund_locations[ix];
11794 if (--(loc->events_till_retirement) == 0)
11795 {
11796 decref_bp_location (&loc);
11797 unordered_remove (moribund_locations, ix);
11798 --ix;
11799 }
11800 }
11801 }
11802
11803 static void
11804 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
11805 {
11806
11807 try
11808 {
11809 update_global_location_list (insert_mode);
11810 }
11811 catch (const gdb_exception_error &e)
11812 {
11813 }
11814 }
11815
11816 /* Clear BKP from a BPS. */
11817
11818 static void
11819 bpstat_remove_bp_location (bpstat *bps, struct breakpoint *bpt)
11820 {
11821 bpstat *bs;
11822
11823 for (bs = bps; bs; bs = bs->next)
11824 if (bs->breakpoint_at == bpt)
11825 {
11826 bs->breakpoint_at = NULL;
11827 bs->old_val = NULL;
11828 /* bs->commands will be freed later. */
11829 }
11830 }
11831
11832 /* See breakpoint.h. */
11833
11834 void
11835 code_breakpoint::say_where () const
11836 {
11837 struct value_print_options opts;
11838
11839 get_user_print_options (&opts);
11840
11841 /* i18n: cagney/2005-02-11: Below needs to be merged into a
11842 single string. */
11843 if (!this->has_locations ())
11844 {
11845 /* For pending locations, the output differs slightly based
11846 on extra_string. If this is non-NULL, it contains either
11847 a condition or dprintf arguments. */
11848 if (extra_string == NULL)
11849 {
11850 gdb_printf (_(" (%s) pending."), locspec->to_string ());
11851 }
11852 else if (type == bp_dprintf)
11853 {
11854 gdb_printf (_(" (%s,%s) pending."),
11855 locspec->to_string (),
11856 extra_string.get ());
11857 }
11858 else
11859 {
11860 gdb_printf (_(" (%s %s) pending."),
11861 locspec->to_string (),
11862 extra_string.get ());
11863 }
11864 }
11865 else
11866 {
11867 const bp_location &bl = this->first_loc ();
11868 if (opts.addressprint || bl.symtab == nullptr)
11869 gdb_printf (" at %ps",
11870 styled_string (address_style.style (),
11871 paddress (bl.gdbarch,
11872 bl.address)));
11873 if (bl.symtab != NULL)
11874 {
11875 /* If there is a single location, we can print the location
11876 more nicely. */
11877 if (!this->has_multiple_locations ())
11878 {
11879 const char *filename
11880 = symtab_to_filename_for_display (bl.symtab);
11881 gdb_printf (": file %ps, line %ps.",
11882 styled_string (file_name_style.style (),
11883 filename),
11884 styled_string (line_number_style.style (),
11885 pulongest (bl.line_number)));
11886 }
11887 else
11888 /* This is not ideal, but each location may have a
11889 different file name, and this at least reflects the
11890 real situation somewhat. */
11891 gdb_printf (": %s.", locspec->to_string ());
11892 }
11893
11894 if (this->has_multiple_locations ())
11895 {
11896 int n = std::distance (m_locations.begin (), m_locations.end ());
11897 gdb_printf (" (%d locations)", n);
11898 }
11899 }
11900 }
11901
11902 /* See breakpoint.h. */
11903
11904 bp_location_range
11905 breakpoint::locations () const
11906 {
11907 return bp_location_range (m_locations.begin (), m_locations.end ());
11908 }
11909
11910 struct bp_location *
11911 breakpoint::allocate_location ()
11912 {
11913 return new bp_location (this);
11914 }
11915
11916 /* See breakpoint.h. */
11917
11918 void
11919 breakpoint::add_location (bp_location &loc)
11920 {
11921 gdb_assert (loc.owner == this);
11922 gdb_assert (!loc.is_linked ());
11923
11924 auto ub = std::upper_bound (m_locations.begin (), m_locations.end (),
11925 loc,
11926 bp_location_is_less_than);
11927 m_locations.insert (ub, loc);
11928 }
11929
11930 /* See breakpoint.h. */
11931
11932 void
11933 breakpoint::unadd_location (bp_location &loc)
11934 {
11935 gdb_assert (loc.owner == this);
11936 gdb_assert (loc.is_linked ());
11937
11938 m_locations.erase (m_locations.iterator_to (loc));
11939 }
11940
11941 #define internal_error_pure_virtual_called() \
11942 gdb_assert_not_reached ("pure virtual function called")
11943
11944 int
11945 breakpoint::insert_location (struct bp_location *bl)
11946 {
11947 internal_error_pure_virtual_called ();
11948 }
11949
11950 int
11951 breakpoint::remove_location (struct bp_location *bl,
11952 enum remove_bp_reason reason)
11953 {
11954 internal_error_pure_virtual_called ();
11955 }
11956
11957 int
11958 breakpoint::breakpoint_hit (const struct bp_location *bl,
11959 const address_space *aspace,
11960 CORE_ADDR bp_addr,
11961 const target_waitstatus &ws)
11962 {
11963 internal_error_pure_virtual_called ();
11964 }
11965
11966 int
11967 breakpoint::resources_needed (const struct bp_location *bl)
11968 {
11969 internal_error_pure_virtual_called ();
11970 }
11971
11972 enum print_stop_action
11973 breakpoint::print_it (const bpstat *bs) const
11974 {
11975 internal_error_pure_virtual_called ();
11976 }
11977
11978 void
11979 breakpoint::print_mention () const
11980 {
11981 internal_error_pure_virtual_called ();
11982 }
11983
11984 void
11985 breakpoint::print_recreate (struct ui_file *fp) const
11986 {
11987 internal_error_pure_virtual_called ();
11988 }
11989
11990 /* Default breakpoint_ops methods. */
11991
11992 void
11993 code_breakpoint::re_set (struct program_space *pspace)
11994 {
11995 /* FIXME: is this still reachable? */
11996 if (breakpoint_location_spec_empty_p (this))
11997 {
11998 /* Anything without a location can't be re-set. */
11999 delete_breakpoint (this);
12000 return;
12001 }
12002
12003 re_set_default (pspace);
12004 }
12005
12006 int
12007 code_breakpoint::insert_location (struct bp_location *bl)
12008 {
12009 CORE_ADDR addr = bl->target_info.reqstd_address;
12010
12011 bl->target_info.kind = breakpoint_kind (bl, &addr);
12012 bl->target_info.placed_address = addr;
12013
12014 int result;
12015 if (bl->loc_type == bp_loc_hardware_breakpoint)
12016 result = target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12017 else
12018 result = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12019
12020 if (result == 0 && bl->probe.prob != nullptr)
12021 {
12022 /* The insertion was successful, now let's set the probe's semaphore
12023 if needed. */
12024 bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12025 }
12026
12027 return result;
12028 }
12029
12030 int
12031 code_breakpoint::remove_location (struct bp_location *bl,
12032 enum remove_bp_reason reason)
12033 {
12034 if (bl->probe.prob != nullptr)
12035 {
12036 /* Let's clear the semaphore before removing the location. */
12037 bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12038 }
12039
12040 if (bl->loc_type == bp_loc_hardware_breakpoint)
12041 return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12042 else
12043 return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12044 }
12045
12046 int
12047 code_breakpoint::breakpoint_hit (const struct bp_location *bl,
12048 const address_space *aspace,
12049 CORE_ADDR bp_addr,
12050 const target_waitstatus &ws)
12051 {
12052 if (ws.kind () != TARGET_WAITKIND_STOPPED
12053 || ws.sig () != GDB_SIGNAL_TRAP)
12054 return 0;
12055
12056 if (!breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
12057 aspace, bp_addr))
12058 return 0;
12059
12060 if (overlay_debugging /* unmapped overlay section */
12061 && section_is_overlay (bl->section)
12062 && !section_is_mapped (bl->section))
12063 return 0;
12064
12065 return 1;
12066 }
12067
12068 int
12069 dprintf_breakpoint::breakpoint_hit (const struct bp_location *bl,
12070 const address_space *aspace,
12071 CORE_ADDR bp_addr,
12072 const target_waitstatus &ws)
12073 {
12074 if (dprintf_style == dprintf_style_agent
12075 && target_can_run_breakpoint_commands ())
12076 {
12077 /* An agent-style dprintf never causes a stop. If we see a trap
12078 for this address it must be for a breakpoint that happens to
12079 be set at the same address. */
12080 return 0;
12081 }
12082
12083 return this->ordinary_breakpoint::breakpoint_hit (bl, aspace, bp_addr, ws);
12084 }
12085
12086 int
12087 ordinary_breakpoint::resources_needed (const struct bp_location *bl)
12088 {
12089 gdb_assert (type == bp_hardware_breakpoint);
12090
12091 return 1;
12092 }
12093
12094 enum print_stop_action
12095 ordinary_breakpoint::print_it (const bpstat *bs) const
12096 {
12097 const struct bp_location *bl;
12098 int bp_temp;
12099 struct ui_out *uiout = current_uiout;
12100
12101 bl = bs->bp_location_at.get ();
12102
12103 bp_temp = disposition == disp_del;
12104 if (bl->address != bl->requested_address)
12105 breakpoint_adjustment_warning (bl->requested_address,
12106 bl->address,
12107 number, true);
12108 annotate_breakpoint (number);
12109 maybe_print_thread_hit_breakpoint (uiout);
12110
12111 if (uiout->is_mi_like_p ())
12112 {
12113 uiout->field_string ("reason",
12114 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12115 uiout->field_string ("disp", bpdisp_text (disposition));
12116 }
12117
12118 if (bp_temp)
12119 uiout->text ("Temporary breakpoint ");
12120 else
12121 uiout->text ("Breakpoint ");
12122 print_num_locno (bs, uiout);
12123 uiout->text (", ");
12124
12125 return PRINT_SRC_AND_LOC;
12126 }
12127
12128 void
12129 ordinary_breakpoint::print_mention () const
12130 {
12131 if (current_uiout->is_mi_like_p ())
12132 return;
12133
12134 switch (type)
12135 {
12136 case bp_breakpoint:
12137 case bp_gnu_ifunc_resolver:
12138 if (disposition == disp_del)
12139 gdb_printf (_("Temporary breakpoint"));
12140 else
12141 gdb_printf (_("Breakpoint"));
12142 gdb_printf (_(" %d"), number);
12143 if (type == bp_gnu_ifunc_resolver)
12144 gdb_printf (_(" at gnu-indirect-function resolver"));
12145 break;
12146 case bp_hardware_breakpoint:
12147 gdb_printf (_("Hardware assisted breakpoint %d"), number);
12148 break;
12149 case bp_dprintf:
12150 gdb_printf (_("Dprintf %d"), number);
12151 break;
12152 }
12153
12154 say_where ();
12155 }
12156
12157 void
12158 ordinary_breakpoint::print_recreate (struct ui_file *fp) const
12159 {
12160 if (type == bp_breakpoint && disposition == disp_del)
12161 gdb_printf (fp, "tbreak");
12162 else if (type == bp_breakpoint)
12163 gdb_printf (fp, "break");
12164 else if (type == bp_hardware_breakpoint
12165 && disposition == disp_del)
12166 gdb_printf (fp, "thbreak");
12167 else if (type == bp_hardware_breakpoint)
12168 gdb_printf (fp, "hbreak");
12169 else
12170 internal_error (_("unhandled breakpoint type %d"), (int) type);
12171
12172 gdb_printf (fp, " %s", locspec->to_string ());
12173
12174 /* Print out extra_string if this breakpoint is pending. It might
12175 contain, for example, conditions that were set by the user. */
12176 if (!this->has_locations () && extra_string != NULL)
12177 gdb_printf (fp, " %s", extra_string.get ());
12178
12179 print_recreate_thread (fp);
12180 }
12181
12182 std::vector<symtab_and_line>
12183 code_breakpoint::decode_location_spec (location_spec *locspec,
12184 program_space *search_pspace)
12185 {
12186 if (locspec->type () == PROBE_LOCATION_SPEC)
12187 return bkpt_probe_decode_location_spec (this, locspec, search_pspace);
12188
12189 struct linespec_result canonical;
12190
12191 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
12192 NULL, 0, &canonical, multiple_symbols_all,
12193 filter.get ());
12194
12195 /* We should get 0 or 1 resulting SALs. */
12196 gdb_assert (canonical.lsals.size () < 2);
12197
12198 if (!canonical.lsals.empty ())
12199 {
12200 const linespec_sals &lsal = canonical.lsals[0];
12201 return std::move (lsal.sals);
12202 }
12203 return {};
12204 }
12205
12206 /* Virtual table for internal breakpoints. */
12207
12208 void
12209 internal_breakpoint::re_set (struct program_space *pspace)
12210 {
12211 switch (type)
12212 {
12213 /* Delete overlay event and longjmp master breakpoints; they
12214 will be reset later by breakpoint_re_set. */
12215 case bp_overlay_event:
12216 case bp_longjmp_master:
12217 case bp_std_terminate_master:
12218 case bp_exception_master:
12219 delete_breakpoint (this);
12220 break;
12221
12222 /* This breakpoint is special, it's set up when the inferior
12223 starts and we really don't want to touch it. */
12224 case bp_shlib_event:
12225
12226 /* Like bp_shlib_event, this breakpoint type is special. Once
12227 it is set up, we do not want to touch it. */
12228 case bp_thread_event:
12229 break;
12230 }
12231 }
12232
12233 void
12234 internal_breakpoint::check_status (bpstat *bs)
12235 {
12236 if (type == bp_shlib_event)
12237 {
12238 /* If requested, stop when the dynamic linker notifies GDB of
12239 events. This allows the user to get control and place
12240 breakpoints in initializer routines for dynamically loaded
12241 objects (among other things). */
12242 bs->stop = stop_on_solib_events != 0;
12243 bs->print = stop_on_solib_events != 0;
12244 }
12245 else
12246 bs->stop = false;
12247 }
12248
12249 enum print_stop_action
12250 internal_breakpoint::print_it (const bpstat *bs) const
12251 {
12252 switch (type)
12253 {
12254 case bp_shlib_event:
12255 /* Did we stop because the user set the stop_on_solib_events
12256 variable? (If so, we report this as a generic, "Stopped due
12257 to shlib event" message.) */
12258 print_solib_event (false);
12259 break;
12260
12261 case bp_thread_event:
12262 /* Not sure how we will get here.
12263 GDB should not stop for these breakpoints. */
12264 gdb_printf (_("Thread Event Breakpoint: gdb should not stop!\n"));
12265 break;
12266
12267 case bp_overlay_event:
12268 /* By analogy with the thread event, GDB should not stop for these. */
12269 gdb_printf (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12270 break;
12271
12272 case bp_longjmp_master:
12273 /* These should never be enabled. */
12274 gdb_printf (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12275 break;
12276
12277 case bp_std_terminate_master:
12278 /* These should never be enabled. */
12279 gdb_printf (_("std::terminate Master Breakpoint: "
12280 "gdb should not stop!\n"));
12281 break;
12282
12283 case bp_exception_master:
12284 /* These should never be enabled. */
12285 gdb_printf (_("Exception Master Breakpoint: "
12286 "gdb should not stop!\n"));
12287 break;
12288 }
12289
12290 return PRINT_NOTHING;
12291 }
12292
12293 void
12294 internal_breakpoint::print_mention () const
12295 {
12296 /* Nothing to mention. These breakpoints are internal. */
12297 }
12298
12299 /* Virtual table for momentary breakpoints */
12300
12301 void
12302 momentary_breakpoint::re_set (struct program_space *pspace)
12303 {
12304 /* Keep temporary breakpoints, which can be encountered when we step
12305 over a dlopen call and solib_add is resetting the breakpoints.
12306 Otherwise these should have been blown away via the cleanup chain
12307 or by breakpoint_init_inferior when we rerun the executable. */
12308 }
12309
12310 void
12311 momentary_breakpoint::check_status (bpstat *bs)
12312 {
12313 /* Nothing. The point of these breakpoints is causing a stop. */
12314 }
12315
12316 enum print_stop_action
12317 momentary_breakpoint::print_it (const bpstat *bs) const
12318 {
12319 return PRINT_UNKNOWN;
12320 }
12321
12322 void
12323 momentary_breakpoint::print_mention () const
12324 {
12325 /* Nothing to mention. These breakpoints are internal. */
12326 }
12327
12328 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12329
12330 It gets cleared already on the removal of the first one of such placed
12331 breakpoints. This is OK as they get all removed altogether. */
12332
12333 longjmp_breakpoint::~longjmp_breakpoint ()
12334 {
12335 thread_info *tp = find_thread_global_id (this->thread);
12336
12337 if (tp != NULL)
12338 tp->initiating_frame = null_frame_id;
12339 }
12340
12341 static void
12342 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
12343 struct linespec_result *canonical,
12344 struct program_space *search_pspace)
12345
12346 {
12347 struct linespec_sals lsal;
12348
12349 lsal.sals = parse_probes (locspec, search_pspace, canonical);
12350 lsal.canonical = xstrdup (canonical->locspec->to_string ());
12351 canonical->lsals.push_back (std::move (lsal));
12352 }
12353
12354 static std::vector<symtab_and_line>
12355 bkpt_probe_decode_location_spec (struct breakpoint *b,
12356 location_spec *locspec,
12357 program_space *search_pspace)
12358 {
12359 std::vector<symtab_and_line> sals
12360 = parse_probes (locspec, search_pspace, NULL);
12361 if (sals.empty ())
12362 error (_("probe not found"));
12363 return sals;
12364 }
12365
12366 int
12367 tracepoint::breakpoint_hit (const struct bp_location *bl,
12368 const address_space *aspace, CORE_ADDR bp_addr,
12369 const target_waitstatus &ws)
12370 {
12371 /* By definition, the inferior does not report stops at
12372 tracepoints. */
12373 return 0;
12374 }
12375
12376 void
12377 tracepoint::print_one_detail (struct ui_out *uiout) const
12378 {
12379 if (!static_trace_marker_id.empty ())
12380 {
12381 gdb_assert (type == bp_static_tracepoint
12382 || type == bp_static_marker_tracepoint);
12383
12384 uiout->message ("\tmarker id is %pF\n",
12385 string_field ("static-tracepoint-marker-string-id",
12386 static_trace_marker_id.c_str ()));
12387 }
12388 }
12389
12390 void
12391 tracepoint::print_mention () const
12392 {
12393 if (current_uiout->is_mi_like_p ())
12394 return;
12395
12396 switch (type)
12397 {
12398 case bp_tracepoint:
12399 gdb_printf (_("Tracepoint"));
12400 gdb_printf (_(" %d"), number);
12401 break;
12402 case bp_fast_tracepoint:
12403 gdb_printf (_("Fast tracepoint"));
12404 gdb_printf (_(" %d"), number);
12405 break;
12406 case bp_static_tracepoint:
12407 case bp_static_marker_tracepoint:
12408 gdb_printf (_("Static tracepoint"));
12409 gdb_printf (_(" %d"), number);
12410 break;
12411 default:
12412 internal_error (_("unhandled tracepoint type %d"), (int) type);
12413 }
12414
12415 say_where ();
12416 }
12417
12418 void
12419 tracepoint::print_recreate (struct ui_file *fp) const
12420 {
12421 if (type == bp_fast_tracepoint)
12422 gdb_printf (fp, "ftrace");
12423 else if (type == bp_static_tracepoint
12424 || type == bp_static_marker_tracepoint)
12425 gdb_printf (fp, "strace");
12426 else if (type == bp_tracepoint)
12427 gdb_printf (fp, "trace");
12428 else
12429 internal_error (_("unhandled tracepoint type %d"), (int) type);
12430
12431 gdb_printf (fp, " %s", locspec->to_string ());
12432 print_recreate_thread (fp);
12433
12434 if (pass_count)
12435 gdb_printf (fp, " passcount %d\n", pass_count);
12436 }
12437
12438 void
12439 dprintf_breakpoint::re_set (struct program_space *pspace)
12440 {
12441 re_set_default (pspace);
12442
12443 /* 1 - connect to target 1, that can run breakpoint commands.
12444 2 - create a dprintf, which resolves fine.
12445 3 - disconnect from target 1
12446 4 - connect to target 2, that can NOT run breakpoint commands.
12447
12448 After steps #3/#4, you'll want the dprintf command list to
12449 be updated, because target 1 and 2 may well return different
12450 answers for target_can_run_breakpoint_commands().
12451 Given absence of finer grained resetting, we get to do
12452 it all the time. */
12453 update_dprintf_command_list (this);
12454 }
12455
12456 /* Implement the "print_recreate" method for dprintf. */
12457
12458 void
12459 dprintf_breakpoint::print_recreate (struct ui_file *fp) const
12460 {
12461 gdb_printf (fp, "dprintf %s,%s", locspec->to_string (), extra_string.get ());
12462 print_recreate_thread (fp);
12463 }
12464
12465 /* Implement the "after_condition_true" method for dprintf.
12466
12467 dprintf's are implemented with regular commands in their command
12468 list, but we run the commands here instead of before presenting the
12469 stop to the user, as dprintf's don't actually cause a stop. This
12470 also makes it so that the commands of multiple dprintfs at the same
12471 address are all handled. */
12472
12473 void
12474 dprintf_breakpoint::after_condition_true (struct bpstat *bs)
12475 {
12476 /* dprintf's never cause a stop. This wasn't set in the
12477 check_status hook instead because that would make the dprintf's
12478 condition not be evaluated. */
12479 bs->stop = false;
12480
12481 /* Run the command list here. Take ownership of it instead of
12482 copying. We never want these commands to run later in
12483 bpstat_do_actions, if a breakpoint that causes a stop happens to
12484 be set at same address as this dprintf, or even if running the
12485 commands here throws. */
12486 counted_command_line cmds = std::move (bs->commands);
12487 gdb_assert (cmds != nullptr);
12488 execute_control_commands (cmds.get (), 0);
12489 }
12490
12491 /* The breakpoint_ops structure to be used on static tracepoints with
12492 markers (`-m'). */
12493
12494 static void
12495 strace_marker_create_sals_from_location_spec
12496 (location_spec *locspec,
12497 struct linespec_result *canonical,
12498 struct program_space *search_pspace)
12499 {
12500 struct linespec_sals lsal;
12501 const char *arg_start, *arg;
12502
12503 arg = arg_start = as_linespec_location_spec (locspec)->spec_string.get ();
12504 lsal.sals = decode_static_tracepoint_spec (&arg);
12505
12506 std::string str (arg_start, arg - arg_start);
12507 const char *ptr = str.c_str ();
12508 canonical->locspec
12509 = new_linespec_location_spec (&ptr, symbol_name_match_type::FULL);
12510
12511 lsal.canonical = xstrdup (canonical->locspec->to_string ());
12512 canonical->lsals.push_back (std::move (lsal));
12513 }
12514
12515 static void
12516 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12517 struct linespec_result *canonical,
12518 gdb::unique_xmalloc_ptr<char> cond_string,
12519 gdb::unique_xmalloc_ptr<char> extra_string,
12520 enum bptype type_wanted,
12521 enum bpdisp disposition,
12522 int thread,
12523 int task, int inferior,
12524 int ignore_count,
12525 int from_tty, int enabled,
12526 int internal, unsigned flags)
12527 {
12528 const linespec_sals &lsal = canonical->lsals[0];
12529
12530 /* If the user is creating a static tracepoint by marker id
12531 (strace -m MARKER_ID), then store the sals index, so that
12532 breakpoint_re_set can try to match up which of the newly
12533 found markers corresponds to this one, and, don't try to
12534 expand multiple locations for each sal, given than SALS
12535 already should contain all sals for MARKER_ID. */
12536
12537 for (size_t i = 0; i < lsal.sals.size (); i++)
12538 {
12539 location_spec_up locspec = canonical->locspec->clone ();
12540
12541 std::unique_ptr<tracepoint> tp
12542 (new tracepoint (gdbarch,
12543 type_wanted,
12544 lsal.sals[i],
12545 std::move (locspec),
12546 NULL,
12547 std::move (cond_string),
12548 std::move (extra_string),
12549 disposition,
12550 thread, task, inferior, ignore_count,
12551 from_tty, enabled, flags,
12552 canonical->special_display));
12553
12554 /* Given that its possible to have multiple markers with
12555 the same string id, if the user is creating a static
12556 tracepoint by marker id ("strace -m MARKER_ID"), then
12557 store the sals index, so that breakpoint_re_set can
12558 try to match up which of the newly found markers
12559 corresponds to this one */
12560 tp->static_trace_marker_id_idx = i;
12561
12562 install_breakpoint (internal, std::move (tp), 0);
12563 }
12564 }
12565
12566 std::vector<symtab_and_line>
12567 static_marker_tracepoint::decode_location_spec (location_spec *locspec,
12568 program_space *search_pspace)
12569 {
12570 const char *s = as_linespec_location_spec (locspec)->spec_string.get ();
12571
12572 std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
12573 if (sals.size () > static_trace_marker_id_idx)
12574 {
12575 sals[0] = sals[static_trace_marker_id_idx];
12576 sals.resize (1);
12577 return sals;
12578 }
12579 else
12580 error (_("marker %s not found"), static_trace_marker_id.c_str ());
12581 }
12582
12583 /* Static tracepoints with marker (`-m'). */
12584 static struct breakpoint_ops strace_marker_breakpoint_ops =
12585 {
12586 strace_marker_create_sals_from_location_spec,
12587 strace_marker_create_breakpoints_sal,
12588 };
12589
12590 static bool
12591 strace_marker_p (struct breakpoint *b)
12592 {
12593 return b->type == bp_static_marker_tracepoint;
12594 }
12595
12596 /* Notify interpreters and observers that breakpoint B was deleted. */
12597
12598 static void
12599 notify_breakpoint_deleted (breakpoint *b)
12600 {
12601 interps_notify_breakpoint_deleted (b);
12602 gdb::observers::breakpoint_deleted.notify (b);
12603 }
12604
12605 /* Delete a breakpoint and clean up all traces of it in the data
12606 structures. */
12607
12608 void
12609 delete_breakpoint (struct breakpoint *bpt)
12610 {
12611 gdb_assert (bpt != NULL);
12612
12613 /* Has this bp already been deleted? This can happen because
12614 multiple lists can hold pointers to bp's. bpstat lists are
12615 especial culprits.
12616
12617 One example of this happening is a watchpoint's scope bp. When
12618 the scope bp triggers, we notice that the watchpoint is out of
12619 scope, and delete it. We also delete its scope bp. But the
12620 scope bp is marked "auto-deleting", and is already on a bpstat.
12621 That bpstat is then checked for auto-deleting bp's, which are
12622 deleted.
12623
12624 A real solution to this problem might involve reference counts in
12625 bp's, and/or giving them pointers back to their referencing
12626 bpstat's, and teaching delete_breakpoint to only free a bp's
12627 storage when no more references were extent. A cheaper bandaid
12628 was chosen. */
12629 if (bpt->type == bp_none)
12630 return;
12631
12632 /* At least avoid this stale reference until the reference counting
12633 of breakpoints gets resolved. */
12634 if (bpt->related_breakpoint != bpt)
12635 {
12636 struct breakpoint *related;
12637 struct watchpoint *w;
12638
12639 if (bpt->type == bp_watchpoint_scope)
12640 w = gdb::checked_static_cast<watchpoint *> (bpt->related_breakpoint);
12641 else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12642 w = gdb::checked_static_cast<watchpoint *> (bpt);
12643 else
12644 w = NULL;
12645 if (w != NULL)
12646 watchpoint_del_at_next_stop (w);
12647
12648 /* Unlink bpt from the bpt->related_breakpoint ring. */
12649 for (related = bpt; related->related_breakpoint != bpt;
12650 related = related->related_breakpoint);
12651 related->related_breakpoint = bpt->related_breakpoint;
12652 bpt->related_breakpoint = bpt;
12653 }
12654
12655 /* watch_command_1 creates a watchpoint but only sets its number if
12656 update_watchpoint succeeds in creating its bp_locations. If there's
12657 a problem in that process, we'll be asked to delete the half-created
12658 watchpoint. In that case, don't announce the deletion. */
12659 if (bpt->number)
12660 notify_breakpoint_deleted (bpt);
12661
12662 breakpoint_chain.erase (breakpoint_chain.iterator_to (*bpt));
12663
12664 /* Be sure no bpstat's are pointing at the breakpoint after it's
12665 been freed. */
12666 /* FIXME, how can we find all bpstat's? We just check stop_bpstat
12667 in all threads for now. Note that we cannot just remove bpstats
12668 pointing at bpt from the stop_bpstat list entirely, as breakpoint
12669 commands are associated with the bpstat; if we remove it here,
12670 then the later call to bpstat_do_actions (&stop_bpstat); in
12671 event-top.c won't do anything, and temporary breakpoints with
12672 commands won't work. */
12673
12674 iterate_over_threads ([&] (struct thread_info *th)
12675 {
12676 bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12677 return false;
12678 });
12679
12680 /* Now that breakpoint is removed from breakpoint list, update the
12681 global location list. This will remove locations that used to
12682 belong to this breakpoint. Do this before freeing the breakpoint
12683 itself, since remove_breakpoint looks at location's owner. It
12684 might be better design to have location completely
12685 self-contained, but it's not the case now.
12686
12687 Clear the location linked list first, otherwise, the intrusive_list
12688 destructor accesses the locations after they are freed. */
12689 bpt->clear_locations ();
12690 update_global_location_list (UGLL_DONT_INSERT);
12691
12692 /* On the chance that someone will soon try again to delete this
12693 same bp, we mark it as deleted before freeing its storage. */
12694 bpt->type = bp_none;
12695 delete bpt;
12696 }
12697
12698 /* Iterator function to call a user-provided callback function once
12699 for each of B and its related breakpoints. */
12700
12701 static void
12702 iterate_over_related_breakpoints (struct breakpoint *b,
12703 gdb::function_view<void (breakpoint *)> function)
12704 {
12705 struct breakpoint *related;
12706
12707 related = b;
12708 do
12709 {
12710 struct breakpoint *next;
12711
12712 /* FUNCTION may delete RELATED. */
12713 next = related->related_breakpoint;
12714
12715 if (next == related)
12716 {
12717 /* RELATED is the last ring entry. */
12718 function (related);
12719
12720 /* FUNCTION may have deleted it, so we'd never reach back to
12721 B. There's nothing left to do anyway, so just break
12722 out. */
12723 break;
12724 }
12725 else
12726 function (related);
12727
12728 related = next;
12729 }
12730 while (related != b);
12731 }
12732
12733 static void
12734 delete_command (const char *arg, int from_tty)
12735 {
12736 dont_repeat ();
12737
12738 if (arg == 0)
12739 {
12740 int breaks_to_delete = 0;
12741
12742 /* Delete all breakpoints, watchpoints, tracepoints, and catchpoints
12743 if no argument. Do not delete internal breakpoints, these have to
12744 be deleted with an explicit breakpoint number argument. */
12745 for (breakpoint &b : all_breakpoints ())
12746 if (user_breakpoint_p (&b))
12747 {
12748 breaks_to_delete = 1;
12749 break;
12750 }
12751
12752 /* Ask user only if there are some breakpoints to delete. */
12753 if (!from_tty
12754 || (breaks_to_delete
12755 && query (_("Delete all breakpoints, watchpoints, tracepoints, "
12756 "and catchpoints? "))))
12757 for (breakpoint &b : all_breakpoints_safe ())
12758 if (user_breakpoint_p (&b))
12759 delete_breakpoint (&b);
12760 }
12761 else
12762 map_breakpoint_numbers
12763 (arg, [&] (breakpoint *br)
12764 {
12765 iterate_over_related_breakpoints (br, delete_breakpoint);
12766 });
12767 }
12768
12769 /* Return true if all locations of B bound to PSPACE are pending. If
12770 PSPACE is NULL, all locations of all program spaces are
12771 considered. */
12772
12773 static bool
12774 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
12775 {
12776 for (bp_location &loc : b->locations ())
12777 if ((pspace == NULL
12778 || loc.pspace == pspace)
12779 && !loc.shlib_disabled
12780 && !loc.pspace->executing_startup)
12781 return false;
12782 return true;
12783 }
12784
12785 /* Subroutine of update_breakpoint_locations to simplify it.
12786 Return true if multiple fns in list LOCS have the same name.
12787 Null names are ignored. */
12788
12789 static bool
12790 ambiguous_names_p (const bp_location_range &locs)
12791 {
12792 gdb::unordered_set<std::string_view> htab;
12793
12794 for (const bp_location &l : locs)
12795 {
12796 const char *name = l.function_name.get ();
12797
12798 /* Allow for some names to be NULL, ignore them. */
12799 if (name == NULL)
12800 continue;
12801
12802 if (!htab.insert (name).second)
12803 return true;
12804 }
12805
12806 return false;
12807 }
12808
12809 /* When symbols change, it probably means the sources changed as well,
12810 and it might mean the static tracepoint markers are no longer at
12811 the same address or line numbers they used to be at last we
12812 checked. Losing your static tracepoints whenever you rebuild is
12813 undesirable. This function tries to resync/rematch gdb static
12814 tracepoints with the markers on the target, for static tracepoints
12815 that have not been set by marker id. Static tracepoint that have
12816 been set by marker id are reset by marker id in breakpoint_re_set.
12817 The heuristic is:
12818
12819 1) For a tracepoint set at a specific address, look for a marker at
12820 the old PC. If one is found there, assume to be the same marker.
12821 If the name / string id of the marker found is different from the
12822 previous known name, assume that means the user renamed the marker
12823 in the sources, and output a warning.
12824
12825 2) For a tracepoint set at a given line number, look for a marker
12826 at the new address of the old line number. If one is found there,
12827 assume to be the same marker. If the name / string id of the
12828 marker found is different from the previous known name, assume that
12829 means the user renamed the marker in the sources, and output a
12830 warning.
12831
12832 3) If a marker is no longer found at the same address or line, it
12833 may mean the marker no longer exists. But it may also just mean
12834 the code changed a bit. Maybe the user added a few lines of code
12835 that made the marker move up or down (in line number terms). Ask
12836 the target for info about the marker with the string id as we knew
12837 it. If found, update line number and address in the matching
12838 static tracepoint. This will get confused if there's more than one
12839 marker with the same ID (possible in UST, although unadvised
12840 precisely because it confuses tools). */
12841
12842 static struct symtab_and_line
12843 update_static_tracepoint (tracepoint *tp, struct symtab_and_line sal)
12844 {
12845 struct static_tracepoint_marker marker;
12846 CORE_ADDR pc;
12847
12848 pc = sal.pc;
12849 if (sal.line)
12850 find_line_pc (sal.symtab, sal.line, &pc);
12851
12852 if (target_static_tracepoint_marker_at (pc, &marker))
12853 {
12854 if (tp->static_trace_marker_id != marker.str_id)
12855 warning (_("static tracepoint %d changed probed marker from %s to %s"),
12856 tp->number, tp->static_trace_marker_id.c_str (),
12857 marker.str_id.c_str ());
12858
12859 tp->static_trace_marker_id = std::move (marker.str_id);
12860
12861 return sal;
12862 }
12863
12864 /* Old marker wasn't found on target at lineno. Try looking it up
12865 by string ID. */
12866 if (!sal.explicit_pc
12867 && sal.line != 0
12868 && sal.symtab != NULL
12869 && !tp->static_trace_marker_id.empty ())
12870 {
12871 std::vector<static_tracepoint_marker> markers
12872 = target_static_tracepoint_markers_by_strid
12873 (tp->static_trace_marker_id.c_str ());
12874
12875 if (!markers.empty ())
12876 {
12877 struct symbol *sym;
12878 struct static_tracepoint_marker *tpmarker;
12879 struct ui_out *uiout = current_uiout;
12880
12881 tpmarker = &markers[0];
12882
12883 tp->static_trace_marker_id = std::move (tpmarker->str_id);
12884
12885 warning (_("marker for static tracepoint %d (%s) not "
12886 "found at previous line number"),
12887 tp->number, tp->static_trace_marker_id.c_str ());
12888
12889 symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
12890 sym = find_pc_sect_function (tpmarker->address, NULL);
12891 uiout->text ("Now in ");
12892 if (sym)
12893 {
12894 uiout->field_string ("func", sym->print_name (),
12895 function_name_style.style ());
12896 uiout->text (" at ");
12897 }
12898 uiout->field_string ("file",
12899 symtab_to_filename_for_display (sal2.symtab),
12900 file_name_style.style ());
12901 uiout->text (":");
12902
12903 if (uiout->is_mi_like_p ())
12904 {
12905 const char *fullname = symtab_to_fullname (sal2.symtab);
12906
12907 uiout->field_string ("fullname", fullname);
12908 }
12909
12910 uiout->field_signed ("line", sal2.line, line_number_style.style ());
12911 uiout->text ("\n");
12912
12913 tp->first_loc ().line_number = sal2.line;
12914 tp->first_loc ().symtab = sym != NULL ? sal2.symtab : NULL;
12915
12916 std::unique_ptr<explicit_location_spec> els
12917 (new explicit_location_spec
12918 (symtab_to_filename_for_display (sal2.symtab)));
12919 els->line_offset.offset = tp->first_loc ().line_number;
12920 els->line_offset.sign = LINE_OFFSET_NONE;
12921
12922 tp->locspec = std::move (els);
12923
12924 /* Might be nice to check if function changed, and warn if
12925 so. */
12926 }
12927 }
12928 return sal;
12929 }
12930
12931 /* Returns true iff location lists A and B are sufficiently same that
12932 we don't need to report breakpoint as changed. */
12933
12934 static bool
12935 locations_are_equal (const bp_location_list &a, const bp_location_range &b)
12936 {
12937 auto a_iter = a.begin ();
12938 auto b_iter = b.begin ();
12939
12940 for (; a_iter != a.end () && b_iter != b.end (); ++a_iter, ++b_iter)
12941 {
12942 if (a_iter->address != b_iter->address)
12943 return false;
12944
12945 if (a_iter->shlib_disabled != b_iter->shlib_disabled)
12946 return false;
12947
12948 if (a_iter->enabled != b_iter->enabled)
12949 return false;
12950
12951 if (a_iter->disabled_by_cond != b_iter->disabled_by_cond)
12952 return false;
12953
12954 /* When a breakpoint is set by address, it is not created as
12955 pending; but then during an solib event or the like it may
12956 acquire a symbol. So, check this here. */
12957 if (a_iter->symbol != b_iter->symbol
12958 || a_iter->msymbol != b_iter->msymbol)
12959 return false;
12960 }
12961
12962 return (a_iter == a.end ()) == (b_iter == b.end ());
12963 }
12964
12965 /* See breakpoint.h. */
12966
12967 bp_location_list
12968 breakpoint::steal_locations (program_space *pspace)
12969 {
12970 if (pspace == NULL)
12971 return std::move (m_locations);
12972
12973 bp_location_list ret;
12974
12975 for (auto it = m_locations.begin (); it != m_locations.end (); )
12976 {
12977 if (it->pspace == pspace)
12978 {
12979 bp_location &loc = *it;
12980 it = m_locations.erase (it);
12981 ret.push_back (loc);
12982 }
12983 else
12984 ++it;
12985 }
12986
12987 return ret;
12988 }
12989
12990 /* Create new breakpoint locations for B (a hardware or software
12991 breakpoint) based on SALS and SALS_END. If SALS_END.NELTS is not
12992 zero, then B is a ranged breakpoint. Only recreates locations for
12993 FILTER_PSPACE. Locations of other program spaces are left
12994 untouched. */
12995
12996 void
12997 update_breakpoint_locations (code_breakpoint *b,
12998 struct program_space *filter_pspace,
12999 gdb::array_view<const symtab_and_line> sals,
13000 gdb::array_view<const symtab_and_line> sals_end)
13001 {
13002 if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13003 {
13004 /* Ranged breakpoints have only one start location and one end
13005 location. */
13006 b->enable_state = bp_disabled;
13007 gdb_printf (gdb_stderr,
13008 _("Could not reset ranged breakpoint %d: "
13009 "multiple locations found\n"),
13010 b->number);
13011 return;
13012 }
13013
13014 /* If there's no new locations, and all existing locations are
13015 pending, don't do anything. This optimizes the common case where
13016 all locations are in the same shared library, that was unloaded.
13017 We'd like to retain the location, so that when the library is
13018 loaded again, we don't loose the enabled/disabled status of the
13019 individual locations. */
13020 if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13021 return;
13022
13023 bp_location_list existing_locations = b->steal_locations (filter_pspace);
13024
13025 for (const auto &sal : sals)
13026 {
13027 struct bp_location *new_loc;
13028
13029 switch_to_program_space_and_thread (sal.pspace);
13030
13031 new_loc = b->add_location (sal);
13032
13033 /* Reparse conditions, they might contain references to the
13034 old symtab. */
13035 if (b->cond_string != NULL)
13036 {
13037 const char *s;
13038
13039 s = b->cond_string.get ();
13040 try
13041 {
13042 new_loc->cond = parse_exp_1 (&s, sal.pc,
13043 block_for_pc (sal.pc),
13044 0);
13045 }
13046 catch (const gdb_exception_error &e)
13047 {
13048 new_loc->disabled_by_cond = true;
13049 }
13050 }
13051
13052 if (!sals_end.empty ())
13053 {
13054 CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13055
13056 new_loc->length = end - sals[0].pc + 1;
13057 }
13058 }
13059
13060 /* If possible, carry over 'disable' status from existing
13061 breakpoints.
13062
13063 If there are multiple breakpoints with the same function name,
13064 e.g. for inline functions, comparing function names won't work.
13065 Instead compare pc addresses; this is just a heuristic as things
13066 may have moved, but in practice it gives the correct answer
13067 often enough until a better solution is found. */
13068 bool have_ambiguous_names = ambiguous_names_p (b->locations ());
13069
13070 for (const bp_location &e : existing_locations)
13071 {
13072 if (e.function_name == nullptr || e.enabled)
13073 continue;
13074
13075 if (have_ambiguous_names)
13076 {
13077 for (bp_location &l : b->locations ())
13078 {
13079 /* Ignore software vs hardware location type at
13080 this point, because with "set breakpoint
13081 auto-hw", after a re-set, locations that were
13082 hardware can end up as software, or vice versa.
13083 As mentioned above, this is an heuristic and in
13084 practice should give the correct answer often
13085 enough. */
13086 if (breakpoint_locations_match (&e, &l, true))
13087 {
13088 l.enabled = e.enabled;
13089 break;
13090 }
13091 }
13092 }
13093 else
13094 {
13095 for (bp_location &l : b->locations ())
13096 if (l.function_name
13097 && strcmp (e.function_name.get (),
13098 l.function_name.get ()) == 0)
13099 {
13100 l.enabled = e.enabled;
13101 break;
13102 }
13103 }
13104 }
13105
13106 if (!locations_are_equal (existing_locations, b->locations ()))
13107 notify_breakpoint_modified (b);
13108 }
13109
13110 /* Find the SaL locations corresponding to the given LOCSPEC.
13111 On return, FOUND will be 1 if any SaL was found, zero otherwise. */
13112
13113 std::vector<symtab_and_line>
13114 code_breakpoint::location_spec_to_sals (location_spec *locspec,
13115 struct program_space *search_pspace,
13116 int *found)
13117 {
13118 struct gdb_exception exception;
13119
13120 std::vector<symtab_and_line> sals;
13121
13122 try
13123 {
13124 sals = decode_location_spec (locspec, search_pspace);
13125 }
13126 catch (gdb_exception_error &e)
13127 {
13128 int not_found_and_ok = false;
13129
13130 /* For pending breakpoints, it's expected that parsing will
13131 fail until the right shared library is loaded. User has
13132 already told to create pending breakpoints and don't need
13133 extra messages. If breakpoint is in bp_shlib_disabled
13134 state, then user already saw the message about that
13135 breakpoint being disabled, and don't want to see more
13136 errors. */
13137 if (e.error == NOT_FOUND_ERROR
13138 && (condition_not_parsed
13139 || (this->has_locations ()
13140 && search_pspace != NULL
13141 && this->first_loc ().pspace != search_pspace)
13142 || (this->has_locations () && this->first_loc ().shlib_disabled)
13143 || (this->has_locations ()
13144 && this->first_loc ().pspace->executing_startup)
13145 || enable_state == bp_disabled))
13146 not_found_and_ok = true;
13147
13148 if (!not_found_and_ok)
13149 {
13150 /* We surely don't want to warn about the same breakpoint
13151 10 times. One solution, implemented here, is disable
13152 the breakpoint on error. Another solution would be to
13153 have separate 'warning emitted' flag. Since this
13154 happens only when a binary has changed, I don't know
13155 which approach is better. */
13156 enable_state = bp_disabled;
13157 throw;
13158 }
13159
13160 exception = std::move (e);
13161 }
13162
13163 if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13164 {
13165 for (auto &sal : sals)
13166 resolve_sal_pc (&sal);
13167
13168 if (type == bp_static_tracepoint)
13169 {
13170 tracepoint *t = gdb::checked_static_cast<tracepoint *> (this);
13171 sals[0] = update_static_tracepoint (t, sals[0]);
13172 }
13173
13174 *found = 1;
13175 }
13176 else
13177 *found = 0;
13178
13179 return sals;
13180 }
13181
13182 /* The default re_set method, for typical hardware or software
13183 breakpoints. Reevaluate the breakpoint and recreate its
13184 locations. */
13185
13186 void
13187 code_breakpoint::re_set_default (struct program_space *filter_pspace)
13188 {
13189 std::vector<symtab_and_line> expanded, expanded_end;
13190
13191 /* If this breakpoint is thread- or inferior-specific, then find the
13192 program space in which this breakpoint exists. Otherwise, for
13193 breakpoints that are not thread- or inferior-specific, BP_PSPACE will
13194 be nullptr. */
13195 program_space *bp_pspace
13196 = find_program_space_for_breakpoint (this->thread, this->inferior);
13197
13198 /* If this is not a thread or inferior specific breakpoint, or it is a
13199 thread or inferior specific breakpoint but we are looking for new
13200 locations in the program space that the specific thread or inferior is
13201 running, then look for new locations for this breakpoint. */
13202 if (bp_pspace == nullptr || filter_pspace == bp_pspace)
13203 {
13204 int found;
13205 std::vector<symtab_and_line> sals
13206 = location_spec_to_sals (locspec.get (), filter_pspace, &found);
13207 if (found)
13208 expanded = std::move (sals);
13209
13210 if (locspec_range_end != nullptr)
13211 {
13212 std::vector<symtab_and_line> sals_end
13213 = location_spec_to_sals (locspec_range_end.get (),
13214 filter_pspace, &found);
13215 if (found)
13216 expanded_end = std::move (sals_end);
13217 }
13218 }
13219
13220 /* Update the locations for this breakpoint. For thread-specific
13221 breakpoints this will remove any old locations that are for the wrong
13222 program space -- this can happen if the user changes the thread of a
13223 thread-specific breakpoint. */
13224 update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
13225 }
13226
13227 /* Re-set breakpoint locations for the current program space.
13228 Locations bound to other program spaces are left untouched. */
13229
13230 void
13231 breakpoint_re_set (void)
13232 {
13233 {
13234 scoped_restore_current_language save_language;
13235 scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13236 scoped_restore_current_pspace_and_thread restore_pspace_thread;
13237
13238 /* To ::re_set each breakpoint we set the current_language to the
13239 language of the breakpoint before re-evaluating the breakpoint's
13240 location. This change can unfortunately get undone by accident if
13241 the language_mode is set to auto, and we either switch frames, or
13242 more likely in this context, we select the current frame.
13243
13244 We prevent this by temporarily turning the language_mode to
13245 language_mode_manual. We restore it once all breakpoints
13246 have been reset. */
13247 scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13248 language_mode = language_mode_manual;
13249
13250 /* Note: we must not try to insert locations until after all
13251 breakpoints have been re-set. Otherwise, e.g., when re-setting
13252 breakpoint 1, we'd insert the locations of breakpoint 2, which
13253 hadn't been re-set yet, and thus may have stale locations. */
13254
13255 for (breakpoint &b : all_breakpoints_safe ())
13256 {
13257 try
13258 {
13259 input_radix = b.input_radix;
13260 set_language (b.language);
13261 b.re_set (current_program_space);
13262 }
13263 catch (const gdb_exception &ex)
13264 {
13265 exception_fprintf (gdb_stderr, ex,
13266 "Error in re-setting breakpoint %d: ",
13267 b.number);
13268 }
13269 }
13270
13271 jit_breakpoint_re_set ();
13272 }
13273
13274 create_overlay_event_breakpoint ();
13275 create_longjmp_master_breakpoint ();
13276 create_std_terminate_master_breakpoint ();
13277 create_exception_master_breakpoint ();
13278
13279 /* Now we can insert. */
13280 update_global_location_list (UGLL_MAY_INSERT);
13281 }
13282
13283 /* Re-set locations for breakpoint B in FILTER_PSPACE. If FILTER_PSPACE is
13284 nullptr then re-set locations for B in all program spaces. Locations
13285 bound to program spaces other than FILTER_PSPACE are left untouched. */
13286
13287 static void
13288 breakpoint_re_set_one (breakpoint *b, program_space *filter_pspace)
13289 {
13290 {
13291 scoped_restore_current_language save_language;
13292 scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13293 scoped_restore_current_pspace_and_thread restore_pspace_thread;
13294
13295 /* To ::re_set each breakpoint we set the current_language to the
13296 language of the breakpoint before re-evaluating the breakpoint's
13297 location. This change can unfortunately get undone by accident if
13298 the language_mode is set to auto, and we either switch frames, or
13299 more likely in this context, we select the current frame.
13300
13301 We prevent this by temporarily turning the language_mode to
13302 language_mode_manual. We restore it once all breakpoints
13303 have been reset. */
13304 scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13305 language_mode = language_mode_manual;
13306
13307 /* Note: we must not try to insert locations until after all
13308 breakpoints have been re-set. Otherwise, e.g., when re-setting
13309 breakpoint 1, we'd insert the locations of breakpoint 2, which
13310 hadn't been re-set yet, and thus may have stale locations. */
13311
13312 try
13313 {
13314 input_radix = b->input_radix;
13315 set_language (b->language);
13316 b->re_set (filter_pspace);
13317 }
13318 catch (const gdb_exception &ex)
13319 {
13320 exception_fprintf (gdb_stderr, ex,
13321 "Error in re-setting breakpoint %d: ",
13322 b->number);
13323 }
13324 }
13325
13326 /* Now we can insert. */
13327 update_global_location_list (UGLL_MAY_INSERT);
13328 }
13329 \f
13330 /* Reset the thread number of this breakpoint:
13331
13332 - If the breakpoint is for all threads, leave it as-is.
13333 - Else, reset it to the current thread for inferior_ptid. */
13334 void
13335 breakpoint_re_set_thread (struct breakpoint *b)
13336 {
13337 if (b->thread != -1)
13338 {
13339 b->thread = inferior_thread ()->global_num;
13340
13341 /* We're being called after following a fork. The new fork is
13342 selected as current, and unless this was a vfork will have a
13343 different program space from the original thread. Reset that
13344 as well. */
13345 b->first_loc ().pspace = current_program_space;
13346 }
13347 }
13348
13349 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13350 If from_tty is nonzero, it prints a message to that effect,
13351 which ends with a period (no newline). */
13352
13353 void
13354 set_ignore_count (int bptnum, int count, int from_tty)
13355 {
13356 if (count < 0)
13357 count = 0;
13358
13359 for (breakpoint &b : all_breakpoints ())
13360 if (b.number == bptnum)
13361 {
13362 if (is_tracepoint (&b))
13363 {
13364 if (from_tty && count != 0)
13365 gdb_printf (_("Ignore count ignored for tracepoint %d."),
13366 bptnum);
13367 return;
13368 }
13369
13370 b.ignore_count = count;
13371 if (from_tty)
13372 {
13373 if (count == 0)
13374 gdb_printf (_("Will stop next time "
13375 "breakpoint %d is reached."),
13376 bptnum);
13377 else if (count == 1)
13378 gdb_printf (_("Will ignore next crossing of breakpoint %d."),
13379 bptnum);
13380 else
13381 gdb_printf (_("Will ignore next %d "
13382 "crossings of breakpoint %d."),
13383 count, bptnum);
13384 }
13385 notify_breakpoint_modified (&b);
13386 return;
13387 }
13388
13389 error (_("No breakpoint number %d."), bptnum);
13390 }
13391
13392 /* Command to set ignore-count of breakpoint N to COUNT. */
13393
13394 static void
13395 ignore_command (const char *args, int from_tty)
13396 {
13397 const char *p = args;
13398 int num;
13399
13400 if (p == 0)
13401 error_no_arg (_("a breakpoint number"));
13402
13403 num = get_number (&p);
13404 if (num == 0)
13405 error (_("bad breakpoint number: '%s'"), args);
13406 if (*p == 0)
13407 error (_("Second argument (specified ignore-count) is missing."));
13408
13409 set_ignore_count (num,
13410 longest_to_int (value_as_long (parse_and_eval (p))),
13411 from_tty);
13412 if (from_tty)
13413 gdb_printf ("\n");
13414 }
13415 \f
13416
13417 /* Call FUNCTION on each of the breakpoints with numbers in the range
13418 defined by BP_NUM_RANGE (an inclusive range). */
13419
13420 static void
13421 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13422 gdb::function_view<void (breakpoint *)> function)
13423 {
13424 if (bp_num_range.first == 0)
13425 {
13426 warning (_("bad breakpoint number at or near '%d'"),
13427 bp_num_range.first);
13428 }
13429 else
13430 {
13431 for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
13432 {
13433 bool match = false;
13434
13435 for (breakpoint &b : all_breakpoints_safe ())
13436 if (b.number == i)
13437 {
13438 match = true;
13439 function (&b);
13440 break;
13441 }
13442 if (!match)
13443 gdb_printf (_("No breakpoint number %d.\n"), i);
13444 }
13445 }
13446 }
13447
13448 /* Call FUNCTION on each of the breakpoints whose numbers are given in
13449 ARGS. */
13450
13451 static void
13452 map_breakpoint_numbers (const char *args,
13453 gdb::function_view<void (breakpoint *)> function)
13454 {
13455 if (args == NULL || *args == '\0')
13456 error_no_arg (_("one or more breakpoint numbers"));
13457
13458 number_or_range_parser parser (args);
13459
13460 while (!parser.finished ())
13461 {
13462 int num = parser.get_number ();
13463 map_breakpoint_number_range (std::make_pair (num, num), function);
13464 }
13465 }
13466
13467 /* Return the breakpoint location structure corresponding to the
13468 BP_NUM and LOC_NUM values. */
13469
13470 static struct bp_location *
13471 find_location_by_number (int bp_num, int loc_num)
13472 {
13473 breakpoint *b = get_breakpoint (bp_num);
13474
13475 if (!b || b->number != bp_num)
13476 error (_("Bad breakpoint number '%d'"), bp_num);
13477
13478 if (loc_num == 0)
13479 error (_("Bad breakpoint location number '%d'"), loc_num);
13480
13481 int n = 0;
13482 for (bp_location &loc : b->locations ())
13483 if (++n == loc_num)
13484 return &loc;
13485
13486 error (_("Bad breakpoint location number '%d'"), loc_num);
13487 }
13488
13489 /* Modes of operation for extract_bp_num. */
13490 enum class extract_bp_kind
13491 {
13492 /* Extracting a breakpoint number. */
13493 bp,
13494
13495 /* Extracting a location number. */
13496 loc,
13497 };
13498
13499 /* Extract a breakpoint or location number (as determined by KIND)
13500 from the string starting at START. TRAILER is a character which
13501 can be found after the number. If you don't want a trailer, use
13502 '\0'. If END_OUT is not NULL, it is set to point after the parsed
13503 string. This always returns a positive integer. */
13504
13505 static int
13506 extract_bp_num (extract_bp_kind kind, const char *start,
13507 int trailer, const char **end_out = NULL)
13508 {
13509 const char *end = start;
13510 int num = get_number_trailer (&end, trailer);
13511 if (num < 0)
13512 error (kind == extract_bp_kind::bp
13513 ? _("Negative breakpoint number '%.*s'")
13514 : _("Negative breakpoint location number '%.*s'"),
13515 int (end - start), start);
13516 if (num == 0)
13517 error (kind == extract_bp_kind::bp
13518 ? _("Bad breakpoint number '%.*s'")
13519 : _("Bad breakpoint location number '%.*s'"),
13520 int (end - start), start);
13521
13522 if (end_out != NULL)
13523 *end_out = end;
13524 return num;
13525 }
13526
13527 /* Extract a breakpoint or location range (as determined by KIND) in
13528 the form NUM1-NUM2 stored at &ARG[arg_offset]. Returns a std::pair
13529 representing the (inclusive) range. The returned pair's elements
13530 are always positive integers. */
13531
13532 static std::pair<int, int>
13533 extract_bp_or_bp_range (extract_bp_kind kind,
13534 const std::string &arg,
13535 std::string::size_type arg_offset)
13536 {
13537 std::pair<int, int> range;
13538 const char *bp_loc = &arg[arg_offset];
13539 std::string::size_type dash = arg.find ('-', arg_offset);
13540 if (dash != std::string::npos)
13541 {
13542 /* bp_loc is a range (x-z). */
13543 if (arg.length () == dash + 1)
13544 error (kind == extract_bp_kind::bp
13545 ? _("Bad breakpoint number at or near: '%s'")
13546 : _("Bad breakpoint location number at or near: '%s'"),
13547 bp_loc);
13548
13549 const char *end;
13550 const char *start_first = bp_loc;
13551 const char *start_second = &arg[dash + 1];
13552 range.first = extract_bp_num (kind, start_first, '-');
13553 range.second = extract_bp_num (kind, start_second, '\0', &end);
13554
13555 if (range.first > range.second)
13556 error (kind == extract_bp_kind::bp
13557 ? _("Inverted breakpoint range at '%.*s'")
13558 : _("Inverted breakpoint location range at '%.*s'"),
13559 int (end - start_first), start_first);
13560 }
13561 else
13562 {
13563 /* bp_loc is a single value. */
13564 range.first = extract_bp_num (kind, bp_loc, '\0');
13565 range.second = range.first;
13566 }
13567 return range;
13568 }
13569
13570 /* Extract the breakpoint/location range specified by ARG. Returns
13571 the breakpoint range in BP_NUM_RANGE, and the location range in
13572 BP_LOC_RANGE.
13573
13574 ARG may be in any of the following forms:
13575
13576 x where 'x' is a breakpoint number.
13577 x-y where 'x' and 'y' specify a breakpoint numbers range.
13578 x.y where 'x' is a breakpoint number and 'y' a location number.
13579 x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
13580 location number range.
13581 */
13582
13583 static void
13584 extract_bp_number_and_location (const std::string &arg,
13585 std::pair<int, int> &bp_num_range,
13586 std::pair<int, int> &bp_loc_range)
13587 {
13588 std::string::size_type dot = arg.find ('.');
13589
13590 if (dot != std::string::npos)
13591 {
13592 /* Handle 'x.y' and 'x.y-z' cases. */
13593
13594 if (arg.length () == dot + 1 || dot == 0)
13595 error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
13596
13597 bp_num_range.first
13598 = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
13599 bp_num_range.second = bp_num_range.first;
13600
13601 bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
13602 arg, dot + 1);
13603 }
13604 else
13605 {
13606 /* Handle x and x-y cases. */
13607
13608 bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
13609 bp_loc_range.first = 0;
13610 bp_loc_range.second = 0;
13611 }
13612 }
13613
13614 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM. ENABLE
13615 specifies whether to enable or disable. */
13616
13617 static void
13618 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
13619 {
13620 struct bp_location *loc = find_location_by_number (bp_num, loc_num);
13621 if (loc != NULL)
13622 {
13623 if (loc->disabled_by_cond && enable)
13624 error (_("Breakpoint %d's condition is invalid at location %d, "
13625 "cannot enable."), bp_num, loc_num);
13626
13627 if (loc->enabled != enable)
13628 {
13629 loc->enabled = enable;
13630 mark_breakpoint_location_modified (loc);
13631 }
13632 if (target_supports_enable_disable_tracepoint ()
13633 && current_trace_status ()->running && loc->owner
13634 && is_tracepoint (loc->owner))
13635 target_disable_tracepoint (loc);
13636 }
13637 update_global_location_list (UGLL_DONT_INSERT);
13638
13639 notify_breakpoint_modified (loc->owner);
13640 }
13641
13642 /* Calculates LOC_NUM for LOC by traversing the bp_location chain of LOC's
13643 owner. 1-based indexing. -1 signals NOT FOUND. */
13644
13645 static int
13646 find_loc_num_by_location (const bp_location *loc)
13647 {
13648 if (loc != nullptr && loc->owner != nullptr)
13649 {
13650 /* Locations use 1-based indexing. */
13651 int loc_num = 1;
13652 for (bp_location &it : loc->owner->locations ())
13653 {
13654 if (&it == loc)
13655 return loc_num;
13656 loc_num++;
13657 }
13658 }
13659 return -1;
13660 }
13661
13662 /* Enable or disable a breakpoint location LOC. ENABLE
13663 specifies whether to enable or disable. */
13664
13665 void
13666 enable_disable_bp_location (bp_location *loc, bool enable)
13667 {
13668 if (loc == nullptr)
13669 error (_("Breakpoint location is invalid."));
13670
13671 if (loc->owner == nullptr)
13672 error (_("Breakpoint location does not have an owner breakpoint."));
13673
13674 if (loc->disabled_by_cond && enable)
13675 {
13676 int loc_num = find_loc_num_by_location (loc);
13677 if (loc_num == -1)
13678 error (_("Breakpoint location LOC_NUM could not be found."));
13679 else
13680 error (_("Breakpoint %d's condition is invalid at location %d, "
13681 "cannot enable."), loc->owner->number, loc_num);
13682 }
13683
13684 if (loc->enabled != enable)
13685 {
13686 loc->enabled = enable;
13687 mark_breakpoint_location_modified (loc);
13688 }
13689
13690 if (target_supports_enable_disable_tracepoint ()
13691 && current_trace_status ()->running && loc->owner
13692 && is_tracepoint (loc->owner))
13693 target_disable_tracepoint (loc);
13694
13695 update_global_location_list (UGLL_DONT_INSERT);
13696 notify_breakpoint_modified (loc->owner);
13697 }
13698
13699 /* Enable or disable a range of breakpoint locations. BP_NUM is the
13700 number of the breakpoint, and BP_LOC_RANGE specifies the
13701 (inclusive) range of location numbers of that breakpoint to
13702 enable/disable. ENABLE specifies whether to enable or disable the
13703 location. */
13704
13705 static void
13706 enable_disable_breakpoint_location_range (int bp_num,
13707 std::pair<int, int> &bp_loc_range,
13708 bool enable)
13709 {
13710 for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
13711 enable_disable_bp_num_loc (bp_num, i, enable);
13712 }
13713
13714 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13715 If from_tty is nonzero, it prints a message to that effect,
13716 which ends with a period (no newline). */
13717
13718 void
13719 disable_breakpoint (struct breakpoint *bpt)
13720 {
13721 /* Never disable a watchpoint scope breakpoint; we want to
13722 hit them when we leave scope so we can delete both the
13723 watchpoint and its scope breakpoint at that time. */
13724 if (bpt->type == bp_watchpoint_scope)
13725 return;
13726
13727 bpt->enable_state = bp_disabled;
13728
13729 /* Mark breakpoint locations modified. */
13730 mark_breakpoint_modified (bpt);
13731
13732 if (target_supports_enable_disable_tracepoint ()
13733 && current_trace_status ()->running && is_tracepoint (bpt))
13734 {
13735 for (bp_location &location : bpt->locations ())
13736 target_disable_tracepoint (&location);
13737 }
13738
13739 update_global_location_list (UGLL_DONT_INSERT);
13740
13741 notify_breakpoint_modified (bpt);
13742 }
13743
13744 /* Enable or disable the breakpoint(s) or breakpoint location(s)
13745 specified in ARGS. ARGS may be in any of the formats handled by
13746 extract_bp_number_and_location. ENABLE specifies whether to enable
13747 or disable the breakpoints/locations. */
13748
13749 static void
13750 enable_disable_command (const char *args, int from_tty, bool enable)
13751 {
13752 if (args == 0)
13753 {
13754 for (breakpoint &bpt : all_breakpoints ())
13755 if (user_breakpoint_p (&bpt))
13756 {
13757 if (enable)
13758 enable_breakpoint (&bpt);
13759 else
13760 disable_breakpoint (&bpt);
13761 }
13762 }
13763 else
13764 {
13765 std::string num = extract_arg (&args);
13766
13767 while (!num.empty ())
13768 {
13769 std::pair<int, int> bp_num_range, bp_loc_range;
13770
13771 extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
13772
13773 if (bp_loc_range.first == bp_loc_range.second
13774 && (bp_loc_range.first == 0
13775 || (bp_loc_range.first == 1
13776 && bp_num_range.first == bp_num_range.second
13777 && !has_multiple_locations (bp_num_range.first))))
13778 {
13779 /* Handle breakpoint ids with formats 'x' or 'x-z'
13780 or 'y.1' where y has only one code location. */
13781 map_breakpoint_number_range (bp_num_range,
13782 enable
13783 ? enable_breakpoint
13784 : disable_breakpoint);
13785 }
13786 else
13787 {
13788 /* Handle breakpoint ids with formats 'x.y' or
13789 'x.y-z'. */
13790 enable_disable_breakpoint_location_range
13791 (bp_num_range.first, bp_loc_range, enable);
13792 }
13793 num = extract_arg (&args);
13794 }
13795 }
13796 }
13797
13798 /* The disable command disables the specified breakpoints/locations
13799 (or all defined breakpoints) so they're no longer effective in
13800 stopping the inferior. ARGS may be in any of the forms defined in
13801 extract_bp_number_and_location. */
13802
13803 static void
13804 disable_command (const char *args, int from_tty)
13805 {
13806 enable_disable_command (args, from_tty, false);
13807 }
13808
13809 static void
13810 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13811 int count)
13812 {
13813 int target_resources_ok;
13814
13815 if (bpt->type == bp_hardware_breakpoint)
13816 {
13817 int i;
13818 i = hw_breakpoint_used_count ();
13819 target_resources_ok =
13820 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
13821 i + 1, 0);
13822 if (target_resources_ok == 0)
13823 error (_("No hardware breakpoint support in the target."));
13824 else if (target_resources_ok < 0)
13825 error (_("Hardware breakpoints used exceeds limit."));
13826 }
13827
13828 if (is_watchpoint (bpt))
13829 {
13830 /* Initialize it just to avoid a GCC false warning. */
13831 enum enable_state orig_enable_state = bp_disabled;
13832
13833 try
13834 {
13835 watchpoint *w = gdb::checked_static_cast<watchpoint *> (bpt);
13836
13837 orig_enable_state = bpt->enable_state;
13838 bpt->enable_state = bp_enabled;
13839 update_watchpoint (w, true /* reparse */);
13840 }
13841 catch (const gdb_exception_error &e)
13842 {
13843 bpt->enable_state = orig_enable_state;
13844 exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13845 bpt->number);
13846 return;
13847 }
13848 }
13849
13850 bpt->enable_state = bp_enabled;
13851
13852 /* Mark breakpoint locations modified. */
13853 mark_breakpoint_modified (bpt);
13854
13855 if (target_supports_enable_disable_tracepoint ()
13856 && current_trace_status ()->running && is_tracepoint (bpt))
13857 {
13858 for (bp_location &location : bpt->locations ())
13859 target_enable_tracepoint (&location);
13860 }
13861
13862 bpt->disposition = disposition;
13863 bpt->enable_count = count;
13864 update_global_location_list (UGLL_MAY_INSERT);
13865
13866 notify_breakpoint_modified (bpt);
13867 }
13868
13869
13870 void
13871 enable_breakpoint (struct breakpoint *bpt)
13872 {
13873 enable_breakpoint_disp (bpt, bpt->disposition, 0);
13874 }
13875
13876 /* The enable command enables the specified breakpoints/locations (or
13877 all defined breakpoints) so they once again become (or continue to
13878 be) effective in stopping the inferior. ARGS may be in any of the
13879 forms defined in extract_bp_number_and_location. */
13880
13881 static void
13882 enable_command (const char *args, int from_tty)
13883 {
13884 enable_disable_command (args, from_tty, true);
13885 }
13886
13887 static void
13888 enable_once_command (const char *args, int from_tty)
13889 {
13890 map_breakpoint_numbers
13891 (args, [&] (breakpoint *b)
13892 {
13893 iterate_over_related_breakpoints
13894 (b, [&] (breakpoint *bpt)
13895 {
13896 enable_breakpoint_disp (bpt, disp_disable, 1);
13897 });
13898 });
13899 }
13900
13901 static void
13902 enable_count_command (const char *args, int from_tty)
13903 {
13904 int count;
13905
13906 if (args == NULL)
13907 error_no_arg (_("hit count"));
13908
13909 count = get_number (&args);
13910
13911 map_breakpoint_numbers
13912 (args, [&] (breakpoint *b)
13913 {
13914 iterate_over_related_breakpoints
13915 (b, [&] (breakpoint *bpt)
13916 {
13917 enable_breakpoint_disp (bpt, disp_disable, count);
13918 });
13919 });
13920 }
13921
13922 static void
13923 enable_delete_command (const char *args, int from_tty)
13924 {
13925 map_breakpoint_numbers
13926 (args, [&] (breakpoint *b)
13927 {
13928 iterate_over_related_breakpoints
13929 (b, [&] (breakpoint *bpt)
13930 {
13931 enable_breakpoint_disp (bpt, disp_del, 1);
13932 });
13933 });
13934 }
13935 \f
13936 /* Invalidate last known value of any hardware watchpoint if
13937 the memory which that value represents has been written to by
13938 GDB itself. */
13939
13940 static void
13941 invalidate_bp_value_on_memory_change (struct inferior *inferior,
13942 CORE_ADDR addr, ssize_t len,
13943 const bfd_byte *data)
13944 {
13945 for (breakpoint &bp : all_breakpoints ())
13946 if (bp.enable_state == bp_enabled
13947 && bp.type == bp_hardware_watchpoint)
13948 {
13949 watchpoint &wp = gdb::checked_static_cast<watchpoint &> (bp);
13950
13951 if (wp.val_valid && wp.val != nullptr)
13952 {
13953 for (bp_location &loc : bp.locations ())
13954 if (loc.loc_type == bp_loc_hardware_watchpoint
13955 && loc.address + loc.length > addr
13956 && addr + len > loc.address)
13957 {
13958 wp.val = NULL;
13959 wp.val_valid = false;
13960 }
13961 }
13962 }
13963 }
13964
13965 /* Create and insert a breakpoint for software single step. */
13966
13967 void
13968 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13969 const address_space *aspace,
13970 CORE_ADDR next_pc)
13971 {
13972 struct thread_info *tp = inferior_thread ();
13973 struct symtab_and_line sal;
13974 CORE_ADDR pc = next_pc;
13975
13976 if (tp->control.single_step_breakpoints == NULL)
13977 {
13978 std::unique_ptr<breakpoint> b
13979 (new momentary_breakpoint (gdbarch, bp_single_step,
13980 current_program_space,
13981 null_frame_id,
13982 tp->global_num));
13983
13984 tp->control.single_step_breakpoints
13985 = add_to_breakpoint_chain (std::move (b));
13986 }
13987
13988 sal = find_pc_line (pc, 0);
13989 sal.pc = pc;
13990 sal.section = find_pc_overlay (pc);
13991 sal.explicit_pc = 1;
13992
13993 auto *ss_bp
13994 = (gdb::checked_static_cast<momentary_breakpoint *>
13995 (tp->control.single_step_breakpoints));
13996 ss_bp->add_location (sal);
13997
13998 update_global_location_list (UGLL_INSERT);
13999 }
14000
14001 /* Insert single step breakpoints according to the current state. */
14002
14003 int
14004 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14005 {
14006 regcache *regcache = get_thread_regcache (inferior_thread ());
14007 std::vector<CORE_ADDR> next_pcs;
14008
14009 next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14010
14011 if (!next_pcs.empty ())
14012 {
14013 frame_info_ptr frame = get_current_frame ();
14014 const address_space *aspace = get_frame_address_space (frame);
14015
14016 for (CORE_ADDR pc : next_pcs)
14017 insert_single_step_breakpoint (gdbarch, aspace, pc);
14018
14019 return 1;
14020 }
14021 else
14022 return 0;
14023 }
14024
14025 /* See breakpoint.h. */
14026
14027 int
14028 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14029 const address_space *aspace,
14030 CORE_ADDR pc)
14031 {
14032 for (bp_location &loc : bp->locations ())
14033 if (loc.inserted
14034 && breakpoint_location_address_match (&loc, aspace, pc))
14035 return 1;
14036
14037 return 0;
14038 }
14039
14040 /* Check whether a software single-step breakpoint is inserted at
14041 PC. */
14042
14043 int
14044 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14045 CORE_ADDR pc)
14046 {
14047 for (breakpoint &bpt : all_breakpoints ())
14048 {
14049 if (bpt.type == bp_single_step
14050 && breakpoint_has_location_inserted_here (&bpt, aspace, pc))
14051 return 1;
14052 }
14053 return 0;
14054 }
14055
14056 /* Tracepoint-specific operations. */
14057
14058 /* Set tracepoint count to NUM. */
14059 static void
14060 set_tracepoint_count (int num)
14061 {
14062 tracepoint_count = num;
14063 set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14064 }
14065
14066 static void
14067 trace_command (const char *arg, int from_tty)
14068 {
14069 location_spec_up locspec = string_to_location_spec (&arg,
14070 current_language);
14071 const struct breakpoint_ops *ops = breakpoint_ops_for_location_spec
14072 (locspec.get (), true /* is_tracepoint */);
14073
14074 create_breakpoint (get_current_arch (),
14075 locspec.get (),
14076 NULL, -1, -1, arg, false, 1 /* parse arg */,
14077 0 /* tempflag */,
14078 bp_tracepoint /* type_wanted */,
14079 0 /* Ignore count */,
14080 pending_break_support,
14081 ops,
14082 from_tty,
14083 1 /* enabled */,
14084 0 /* internal */, 0);
14085 }
14086
14087 static void
14088 ftrace_command (const char *arg, int from_tty)
14089 {
14090 location_spec_up locspec = string_to_location_spec (&arg,
14091 current_language);
14092 create_breakpoint (get_current_arch (),
14093 locspec.get (),
14094 NULL, -1, -1, arg, false, 1 /* parse arg */,
14095 0 /* tempflag */,
14096 bp_fast_tracepoint /* type_wanted */,
14097 0 /* Ignore count */,
14098 pending_break_support,
14099 &code_breakpoint_ops,
14100 from_tty,
14101 1 /* enabled */,
14102 0 /* internal */, 0);
14103 }
14104
14105 /* strace command implementation. Creates a static tracepoint. */
14106
14107 static void
14108 strace_command (const char *arg, int from_tty)
14109 {
14110 const struct breakpoint_ops *ops;
14111 location_spec_up locspec;
14112 enum bptype type;
14113
14114 /* Decide if we are dealing with a static tracepoint marker (`-m'),
14115 or with a normal static tracepoint. */
14116 if (arg && startswith (arg, "-m") && isspace (arg[2]))
14117 {
14118 ops = &strace_marker_breakpoint_ops;
14119 locspec = new_linespec_location_spec (&arg,
14120 symbol_name_match_type::FULL);
14121 type = bp_static_marker_tracepoint;
14122 }
14123 else
14124 {
14125 ops = &code_breakpoint_ops;
14126 locspec = string_to_location_spec (&arg, current_language);
14127 type = bp_static_tracepoint;
14128 }
14129
14130 create_breakpoint (get_current_arch (),
14131 locspec.get (),
14132 NULL, -1, -1, arg, false, 1 /* parse arg */,
14133 0 /* tempflag */,
14134 type /* type_wanted */,
14135 0 /* Ignore count */,
14136 pending_break_support,
14137 ops,
14138 from_tty,
14139 1 /* enabled */,
14140 0 /* internal */, 0);
14141 }
14142
14143 /* Set up a fake reader function that gets command lines from a linked
14144 list that was acquired during tracepoint uploading. */
14145
14146 static struct uploaded_tp *this_utp;
14147 static int next_cmd;
14148
14149 static const char *
14150 read_uploaded_action (std::string &buffer)
14151 {
14152 char *rslt = nullptr;
14153
14154 if (next_cmd < this_utp->cmd_strings.size ())
14155 {
14156 rslt = this_utp->cmd_strings[next_cmd].get ();
14157 next_cmd++;
14158 }
14159
14160 return rslt;
14161 }
14162
14163 /* Given information about a tracepoint as recorded on a target (which
14164 can be either a live system or a trace file), attempt to create an
14165 equivalent GDB tracepoint. This is not a reliable process, since
14166 the target does not necessarily have all the information used when
14167 the tracepoint was originally defined. */
14168
14169 struct tracepoint *
14170 create_tracepoint_from_upload (struct uploaded_tp *utp)
14171 {
14172 const char *addr_str;
14173 char small_buf[100];
14174 struct tracepoint *tp;
14175
14176 if (utp->at_string)
14177 addr_str = utp->at_string.get ();
14178 else
14179 {
14180 /* In the absence of a source location, fall back to raw
14181 address. Since there is no way to confirm that the address
14182 means the same thing as when the trace was started, warn the
14183 user. */
14184 warning (_("Uploaded tracepoint %d has no "
14185 "source location, using raw address"),
14186 utp->number);
14187 xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14188 addr_str = small_buf;
14189 }
14190
14191 /* There's not much we can do with a sequence of bytecodes. */
14192 if (utp->cond && !utp->cond_string)
14193 warning (_("Uploaded tracepoint %d condition "
14194 "has no source form, ignoring it"),
14195 utp->number);
14196
14197 location_spec_up locspec = string_to_location_spec (&addr_str,
14198 current_language);
14199
14200
14201 gdb_assert (addr_str != nullptr);
14202 if (*addr_str != '\0')
14203 error (_("Garbage '%s' at end of location"), addr_str);
14204
14205 if (!create_breakpoint (get_current_arch (),
14206 locspec.get (),
14207 utp->cond_string.get (), -1, -1, addr_str,
14208 false /* force_condition */,
14209 0 /* parse cond/thread */,
14210 0 /* tempflag */,
14211 utp->type /* type_wanted */,
14212 0 /* Ignore count */,
14213 pending_break_support,
14214 &code_breakpoint_ops,
14215 0 /* from_tty */,
14216 utp->enabled /* enabled */,
14217 0 /* internal */,
14218 CREATE_BREAKPOINT_FLAGS_INSERTED))
14219 return NULL;
14220
14221 /* Get the tracepoint we just created. */
14222 tp = get_tracepoint (tracepoint_count);
14223 gdb_assert (tp != NULL);
14224
14225 if (utp->pass > 0)
14226 {
14227 xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14228 tp->number);
14229
14230 trace_pass_command (small_buf, 0);
14231 }
14232
14233 /* If we have uploaded versions of the original commands, set up a
14234 special-purpose "reader" function and call the usual command line
14235 reader, then pass the result to the breakpoint command-setting
14236 function. */
14237 if (!utp->cmd_strings.empty ())
14238 {
14239 counted_command_line cmd_list;
14240
14241 this_utp = utp;
14242 next_cmd = 0;
14243
14244 cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14245
14246 breakpoint_set_commands (tp, std::move (cmd_list));
14247 }
14248 else if (!utp->actions.empty ()
14249 || !utp->step_actions.empty ())
14250 warning (_("Uploaded tracepoint %d actions "
14251 "have no source form, ignoring them"),
14252 utp->number);
14253
14254 /* Copy any status information that might be available. */
14255 tp->hit_count = utp->hit_count;
14256 tp->traceframe_usage = utp->traceframe_usage;
14257
14258 return tp;
14259 }
14260
14261 /* Print information on tracepoint number TPNUM_EXP, or all if
14262 omitted. */
14263
14264 static void
14265 info_tracepoints_command (const char *args, int from_tty)
14266 {
14267 struct ui_out *uiout = current_uiout;
14268 int num_printed;
14269
14270 num_printed = breakpoint_1 (args, false, is_tracepoint);
14271
14272 if (num_printed == 0)
14273 {
14274 if (args == NULL || *args == '\0')
14275 uiout->message ("No tracepoints.\n");
14276 else
14277 uiout->message ("No tracepoint matching '%s'.\n", args);
14278 }
14279
14280 default_collect_info ();
14281 }
14282
14283 /* The 'enable trace' command enables tracepoints.
14284 Not supported by all targets. */
14285 static void
14286 enable_trace_command (const char *args, int from_tty)
14287 {
14288 enable_command (args, from_tty);
14289 }
14290
14291 /* The 'disable trace' command disables tracepoints.
14292 Not supported by all targets. */
14293 static void
14294 disable_trace_command (const char *args, int from_tty)
14295 {
14296 disable_command (args, from_tty);
14297 }
14298
14299 /* Remove a tracepoint (or all if no argument). */
14300 static void
14301 delete_trace_command (const char *arg, int from_tty)
14302 {
14303 dont_repeat ();
14304
14305 if (arg == 0)
14306 {
14307 int breaks_to_delete = 0;
14308
14309 /* Delete all tracepoints if no argument.
14310 Do not delete internal or call-dummy breakpoints, these
14311 have to be deleted with an explicit breakpoint number
14312 argument. */
14313 for (breakpoint &tp : all_tracepoints ())
14314 if (is_tracepoint (&tp) && user_breakpoint_p (&tp))
14315 {
14316 breaks_to_delete = 1;
14317 break;
14318 }
14319
14320 /* Ask user only if there are some breakpoints to delete. */
14321 if (!from_tty
14322 || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14323 {
14324 for (breakpoint &b : all_breakpoints_safe ())
14325 if (is_tracepoint (&b) && user_breakpoint_p (&b))
14326 delete_breakpoint (&b);
14327 }
14328 }
14329 else
14330 map_breakpoint_numbers
14331 (arg, [&] (breakpoint *br)
14332 {
14333 iterate_over_related_breakpoints (br, delete_breakpoint);
14334 });
14335 }
14336
14337 /* Helper function for trace_pass_command. */
14338
14339 static void
14340 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14341 {
14342 tp->pass_count = count;
14343 notify_breakpoint_modified (tp);
14344 if (from_tty)
14345 gdb_printf (_("Setting tracepoint %d's passcount to %d\n"),
14346 tp->number, count);
14347 }
14348
14349 /* Set passcount for tracepoint.
14350
14351 First command argument is passcount, second is tracepoint number.
14352 If tracepoint number omitted, apply to most recently defined.
14353 Also accepts special argument "all". */
14354
14355 static void
14356 trace_pass_command (const char *args, int from_tty)
14357 {
14358 ULONGEST count;
14359
14360 if (args == 0 || *args == 0)
14361 error (_("passcount command requires an "
14362 "argument (count + optional TP num)"));
14363
14364 count = strtoulst (args, &args, 10); /* Count comes first, then TP num. */
14365
14366 args = skip_spaces (args);
14367 if (*args && strncasecmp (args, "all", 3) == 0)
14368 {
14369 args += 3; /* Skip special argument "all". */
14370 if (*args)
14371 error (_("Junk at end of arguments."));
14372
14373 for (breakpoint &b : all_tracepoints ())
14374 {
14375 tracepoint &t1 = gdb::checked_static_cast<tracepoint &> (b);
14376 trace_pass_set_count (&t1, count, from_tty);
14377 }
14378 }
14379 else if (*args == '\0')
14380 {
14381 tracepoint *t1 = get_tracepoint_by_number (&args, NULL);
14382 if (t1)
14383 trace_pass_set_count (t1, count, from_tty);
14384 }
14385 else
14386 {
14387 number_or_range_parser parser (args);
14388 while (!parser.finished ())
14389 {
14390 tracepoint *t1 = get_tracepoint_by_number (&args, &parser);
14391 if (t1)
14392 trace_pass_set_count (t1, count, from_tty);
14393 }
14394 }
14395 }
14396
14397 struct tracepoint *
14398 get_tracepoint (int num)
14399 {
14400 for (breakpoint &t : all_tracepoints ())
14401 if (t.number == num)
14402 return gdb::checked_static_cast<tracepoint *> (&t);
14403
14404 return NULL;
14405 }
14406
14407 /* Find the tracepoint with the given target-side number (which may be
14408 different from the tracepoint number after disconnecting and
14409 reconnecting). */
14410
14411 struct tracepoint *
14412 get_tracepoint_by_number_on_target (int num)
14413 {
14414 for (breakpoint &b : all_tracepoints ())
14415 {
14416 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
14417
14418 if (t.number_on_target == num)
14419 return &t;
14420 }
14421
14422 return NULL;
14423 }
14424
14425 /* Utility: parse a tracepoint number and look it up in the list.
14426 If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14427 If the argument is missing, the most recent tracepoint
14428 (tracepoint_count) is returned. */
14429
14430 struct tracepoint *
14431 get_tracepoint_by_number (const char **arg,
14432 number_or_range_parser *parser)
14433 {
14434 int tpnum;
14435 const char *instring = arg == NULL ? NULL : *arg;
14436
14437 if (parser != NULL)
14438 {
14439 gdb_assert (!parser->finished ());
14440 tpnum = parser->get_number ();
14441 }
14442 else if (arg == NULL || *arg == NULL || ! **arg)
14443 tpnum = tracepoint_count;
14444 else
14445 tpnum = get_number (arg);
14446
14447 if (tpnum <= 0)
14448 {
14449 if (instring && *instring)
14450 gdb_printf (_("bad tracepoint number at or near '%s'\n"),
14451 instring);
14452 else
14453 gdb_printf (_("No previous tracepoint\n"));
14454 return NULL;
14455 }
14456
14457 for (breakpoint &t : all_tracepoints ())
14458 if (t.number == tpnum)
14459 return gdb::checked_static_cast<tracepoint *> (&t);
14460
14461 gdb_printf ("No tracepoint number %d.\n", tpnum);
14462 return NULL;
14463 }
14464
14465 void
14466 breakpoint::print_recreate_thread (struct ui_file *fp) const
14467 {
14468 if (thread != -1)
14469 {
14470 struct thread_info *thr = find_thread_global_id (thread);
14471 gdb_printf (fp, " thread %s", print_full_thread_id (thr));
14472 }
14473
14474 if (task != -1)
14475 gdb_printf (fp, " task %d", task);
14476
14477 gdb_printf (fp, "\n");
14478 }
14479
14480 /* Save information on user settable breakpoints (watchpoints, etc) to
14481 a new script file named FILENAME. If FILTER is non-NULL, call it
14482 on each breakpoint and only include the ones for which it returns
14483 true. */
14484
14485 static void
14486 save_breakpoints (const char *filename, int from_tty,
14487 bool (*filter) (const struct breakpoint *))
14488 {
14489 bool any = false;
14490 int extra_trace_bits = 0;
14491
14492 if (filename == 0 || *filename == 0)
14493 error (_("Argument required (file name in which to save)"));
14494
14495 /* See if we have anything to save. */
14496 for (breakpoint &tp : all_breakpoints ())
14497 {
14498 /* Skip internal and momentary breakpoints. */
14499 if (!user_breakpoint_p (&tp))
14500 continue;
14501
14502 /* If we have a filter, only save the breakpoints it accepts. */
14503 if (filter && !filter (&tp))
14504 continue;
14505
14506 any = true;
14507
14508 if (is_tracepoint (&tp))
14509 {
14510 extra_trace_bits = 1;
14511
14512 /* We can stop searching. */
14513 break;
14514 }
14515 }
14516
14517 if (!any)
14518 {
14519 warning (_("Nothing to save."));
14520 return;
14521 }
14522
14523 gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
14524
14525 stdio_file fp;
14526
14527 if (!fp.open (expanded_filename.get (), "w"))
14528 error (_("Unable to open file '%s' for saving (%s)"),
14529 expanded_filename.get (), safe_strerror (errno));
14530
14531 if (extra_trace_bits)
14532 save_trace_state_variables (&fp);
14533
14534 for (breakpoint &tp : all_breakpoints ())
14535 {
14536 /* Skip internal and momentary breakpoints. */
14537 if (!user_breakpoint_p (&tp))
14538 continue;
14539
14540 /* If we have a filter, only save the breakpoints it accepts. */
14541 if (filter && !filter (&tp))
14542 continue;
14543
14544 tp.print_recreate (&fp);
14545
14546 /* Note, we can't rely on tp->number for anything, as we can't
14547 assume the recreated breakpoint numbers will match. Use $bpnum
14548 instead. */
14549
14550 if (tp.cond_string)
14551 fp.printf (" condition $bpnum %s\n", tp.cond_string.get ());
14552
14553 if (tp.ignore_count)
14554 fp.printf (" ignore $bpnum %d\n", tp.ignore_count);
14555
14556 if (tp.type != bp_dprintf && tp.commands)
14557 {
14558 fp.puts (" commands\n");
14559
14560 ui_out_redirect_pop redir (current_uiout, &fp);
14561 print_command_lines (current_uiout, tp.commands.get (), 2);
14562
14563 fp.puts (" end\n");
14564 }
14565
14566 if (tp.enable_state == bp_disabled)
14567 fp.puts ("disable $bpnum\n");
14568
14569 /* If this is a multi-location breakpoint, check if the locations
14570 should be individually disabled. Watchpoint locations are
14571 special, and not user visible. */
14572 if (!is_watchpoint (&tp) && tp.has_multiple_locations ())
14573 {
14574 int n = 1;
14575
14576 for (bp_location &loc : tp.locations ())
14577 {
14578 if (!loc.enabled)
14579 fp.printf ("disable $bpnum.%d\n", n);
14580
14581 n++;
14582 }
14583 }
14584 }
14585
14586 if (extra_trace_bits && !default_collect.empty ())
14587 fp.printf ("set default-collect %s\n", default_collect.c_str ());
14588
14589 if (from_tty)
14590 gdb_printf (_("Saved to file '%s'.\n"), expanded_filename.get ());
14591 }
14592
14593 /* The `save breakpoints' command. */
14594
14595 static void
14596 save_breakpoints_command (const char *args, int from_tty)
14597 {
14598 save_breakpoints (args, from_tty, NULL);
14599 }
14600
14601 /* The `save tracepoints' command. */
14602
14603 static void
14604 save_tracepoints_command (const char *args, int from_tty)
14605 {
14606 save_breakpoints (args, from_tty, is_tracepoint);
14607 }
14608
14609 \f
14610 /* This help string is used to consolidate all the help string for specifying
14611 locations used by several commands. */
14612
14613 #define LOCATION_SPEC_HELP_STRING \
14614 "Linespecs are colon-separated lists of location parameters, such as\n\
14615 source filename, function name, label name, and line number.\n\
14616 Example: To specify the start of a label named \"the_top\" in the\n\
14617 function \"fact\" in the file \"factorial.c\", use\n\
14618 \"factorial.c:fact:the_top\".\n\
14619 \n\
14620 Address locations begin with \"*\" and specify an exact address in the\n\
14621 program. Example: To specify the fourth byte past the start function\n\
14622 \"main\", use \"*main + 4\".\n\
14623 \n\
14624 Explicit locations are similar to linespecs but use an option/argument\n\
14625 syntax to specify location parameters.\n\
14626 Example: To specify the start of the label named \"the_top\" in the\n\
14627 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
14628 -function fact -label the_top\".\n\
14629 \n\
14630 By default, a specified function is matched against the program's\n\
14631 functions in all scopes. For C++, this means in all namespaces and\n\
14632 classes. For Ada, this means in all packages. E.g., in C++,\n\
14633 \"func()\" matches \"A::func()\", \"A::B::func()\", etc. The\n\
14634 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
14635 specified name as a complete fully-qualified name instead."
14636
14637 /* This help string is used for the break, hbreak, tbreak and thbreak
14638 commands. It is defined as a macro to prevent duplication.
14639 COMMAND should be a string constant containing the name of the
14640 command. */
14641
14642 #define BREAK_ARGS_HELP(command) \
14643 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
14644 \t[-force-condition] [if CONDITION]\n\
14645 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
14646 probe point. Accepted values are `-probe' (for a generic, automatically\n\
14647 guessed probe type), `-probe-stap' (for a SystemTap probe) or\n\
14648 `-probe-dtrace' (for a DTrace probe).\n\
14649 LOCATION may be a linespec, address, or explicit location as described\n\
14650 below.\n\
14651 \n\
14652 With no LOCATION, uses current execution address of the selected\n\
14653 stack frame. This is useful for breaking on return to a stack frame.\n\
14654 \n\
14655 THREADNUM is the number from \"info threads\".\n\
14656 CONDITION is a boolean expression.\n\
14657 \n\
14658 With the \"-force-condition\" flag, the condition is defined even when\n\
14659 it is invalid for all current locations.\n\
14660 \n" LOCATION_SPEC_HELP_STRING "\n\n\
14661 Multiple breakpoints at one place are permitted, and useful if their\n\
14662 conditions are different.\n\
14663 \n\
14664 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14665
14666 /* List of subcommands for "catch". */
14667 static struct cmd_list_element *catch_cmdlist;
14668
14669 /* List of subcommands for "tcatch". */
14670 static struct cmd_list_element *tcatch_cmdlist;
14671
14672 void
14673 add_catch_command (const char *name, const char *docstring,
14674 cmd_func_ftype *func,
14675 completer_ftype *completer,
14676 void *user_data_catch,
14677 void *user_data_tcatch)
14678 {
14679 struct cmd_list_element *command;
14680
14681 command = add_cmd (name, class_breakpoint, docstring,
14682 &catch_cmdlist);
14683 command->func = func;
14684 command->set_context (user_data_catch);
14685 set_cmd_completer (command, completer);
14686
14687 command = add_cmd (name, class_breakpoint, docstring,
14688 &tcatch_cmdlist);
14689 command->func = func;
14690 command->set_context (user_data_tcatch);
14691 set_cmd_completer (command, completer);
14692 }
14693
14694 /* False if any of the breakpoint's locations could be a location where
14695 functions have been inlined, true otherwise. */
14696
14697 static bool
14698 is_non_inline_function (struct breakpoint *b)
14699 {
14700 /* The shared library event breakpoint is set on the address of a
14701 non-inline function. */
14702 return (b->type == bp_shlib_event);
14703 }
14704
14705 /* Nonzero if the specified PC cannot be a location where functions
14706 have been inlined. */
14707
14708 int
14709 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
14710 const target_waitstatus &ws)
14711 {
14712 for (breakpoint &b : all_breakpoints ())
14713 {
14714 if (!is_non_inline_function (&b))
14715 continue;
14716
14717 for (bp_location &bl : b.locations ())
14718 {
14719 if (!bl.shlib_disabled
14720 && bpstat_check_location (&bl, aspace, pc, ws))
14721 return 1;
14722 }
14723 }
14724
14725 return 0;
14726 }
14727
14728 /* Remove any references to OBJFILE which is going to be freed. */
14729
14730 void
14731 breakpoint_free_objfile (struct objfile *objfile)
14732 {
14733 for (bp_location *loc : all_bp_locations ())
14734 {
14735 if (loc->symtab != nullptr
14736 && loc->symtab->compunit ()->objfile () == objfile)
14737 {
14738 loc->symtab = nullptr;
14739 loc->symbol = nullptr;
14740 loc->msymbol = nullptr;
14741 }
14742
14743 if (loc->section != nullptr
14744 && loc->section->objfile == objfile)
14745 {
14746 /* If symtab was set then it should have already been cleared.
14747 But if bp_location::msymbol was set then the symbol and symtab
14748 might already have been nullptr. */
14749 gdb_assert (loc->symtab == nullptr);
14750 loc->section = nullptr;
14751 loc->symbol = nullptr;
14752 loc->msymbol = nullptr;
14753 }
14754
14755 if (loc->probe.objfile == objfile)
14756 loc->probe = bound_probe ();
14757 }
14758 }
14759
14760 /* Chain containing all defined "enable breakpoint" subcommands. */
14761
14762 static struct cmd_list_element *enablebreaklist = NULL;
14763
14764 /* See breakpoint.h. */
14765
14766 cmd_list_element *commands_cmd_element = nullptr;
14767
14768 INIT_GDB_FILE (breakpoint)
14769 {
14770 struct cmd_list_element *c;
14771
14772 gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
14773 "breakpoint");
14774 gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
14775 "breakpoint");
14776 gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
14777 "breakpoint");
14778
14779 /* Don't bother to call set_breakpoint_count. $bpnum isn't useful
14780 before a breakpoint is set. */
14781 breakpoint_count = 0;
14782
14783 tracepoint_count = 0;
14784
14785 add_com ("ignore", class_breakpoint, ignore_command, _("\
14786 Set ignore-count of breakpoint number N to COUNT.\n\
14787 Usage is `ignore N COUNT'."));
14788
14789 commands_cmd_element = add_com ("commands", class_breakpoint,
14790 commands_command, _("\
14791 Set commands to be executed when the given breakpoints are hit.\n\
14792 Give a space-separated breakpoint list as argument after \"commands\".\n\
14793 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
14794 (e.g. `5-7').\n\
14795 With no argument, the targeted breakpoint is the last one set.\n\
14796 The commands themselves follow starting on the next line.\n\
14797 Type a line containing \"end\" to indicate the end of them.\n\
14798 Give \"silent\" as the first line to make the breakpoint silent;\n\
14799 then no output is printed when it is hit, except what the commands print."));
14800
14801 const auto cc_opts = make_condition_command_options_def_group (nullptr);
14802 static std::string condition_command_help
14803 = gdb::option::build_help (_("\
14804 Specify breakpoint number N to break only if COND is true.\n\
14805 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
14806 is an expression to be evaluated whenever breakpoint N is reached.\n\
14807 \n\
14808 Options:\n\
14809 %OPTIONS%"), cc_opts);
14810
14811 c = add_com ("condition", class_breakpoint, condition_command,
14812 condition_command_help.c_str ());
14813 set_cmd_completer_handle_brkchars (c, condition_completer);
14814
14815 c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14816 Set a temporary breakpoint.\n\
14817 Like \"break\" except the breakpoint is only temporary,\n\
14818 so it will be deleted when hit. Equivalent to \"break\" followed\n\
14819 by using \"enable delete\" on the breakpoint number.\n\
14820 \n"
14821 BREAK_ARGS_HELP ("tbreak")));
14822 set_cmd_completer (c, location_completer);
14823
14824 c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
14825 Set a hardware assisted breakpoint.\n\
14826 Like \"break\" except the breakpoint requires hardware support,\n\
14827 some target hardware may not have this support.\n\
14828 \n"
14829 BREAK_ARGS_HELP ("hbreak")));
14830 set_cmd_completer (c, location_completer);
14831
14832 c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
14833 Set a temporary hardware assisted breakpoint.\n\
14834 Like \"hbreak\" except the breakpoint is only temporary,\n\
14835 so it will be deleted when hit.\n\
14836 \n"
14837 BREAK_ARGS_HELP ("thbreak")));
14838 set_cmd_completer (c, location_completer);
14839
14840 cmd_list_element *enable_cmd
14841 = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
14842 Enable all or some breakpoints.\n\
14843 Usage: enable [BREAKPOINTNUM]...\n\
14844 Give breakpoint numbers (separated by spaces) as arguments.\n\
14845 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14846 This is used to cancel the effect of the \"disable\" command.\n\
14847 With a subcommand you can enable temporarily."),
14848 &enablelist, 1, &cmdlist);
14849
14850 add_com_alias ("en", enable_cmd, class_breakpoint, 1);
14851
14852 add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
14853 Enable all or some breakpoints.\n\
14854 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
14855 Give breakpoint numbers (separated by spaces) as arguments.\n\
14856 This is used to cancel the effect of the \"disable\" command.\n\
14857 May be abbreviated to simply \"enable\"."),
14858 &enablebreaklist, 1, &enablelist);
14859
14860 add_cmd ("once", no_class, enable_once_command, _("\
14861 Enable some breakpoints for one hit.\n\
14862 Usage: enable breakpoints once BREAKPOINTNUM...\n\
14863 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14864 &enablebreaklist);
14865
14866 add_cmd ("delete", no_class, enable_delete_command, _("\
14867 Enable some breakpoints and delete when hit.\n\
14868 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
14869 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14870 &enablebreaklist);
14871
14872 add_cmd ("count", no_class, enable_count_command, _("\
14873 Enable some breakpoints for COUNT hits.\n\
14874 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
14875 If a breakpoint is hit while enabled in this fashion,\n\
14876 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14877 &enablebreaklist);
14878
14879 add_cmd ("delete", no_class, enable_delete_command, _("\
14880 Enable some breakpoints and delete when hit.\n\
14881 Usage: enable delete BREAKPOINTNUM...\n\
14882 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14883 &enablelist);
14884
14885 add_cmd ("once", no_class, enable_once_command, _("\
14886 Enable some breakpoints for one hit.\n\
14887 Usage: enable once BREAKPOINTNUM...\n\
14888 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14889 &enablelist);
14890
14891 add_cmd ("count", no_class, enable_count_command, _("\
14892 Enable some breakpoints for COUNT hits.\n\
14893 Usage: enable count COUNT BREAKPOINTNUM...\n\
14894 If a breakpoint is hit while enabled in this fashion,\n\
14895 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14896 &enablelist);
14897
14898 cmd_list_element *disable_cmd
14899 = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
14900 Disable all or some breakpoints.\n\
14901 Usage: disable [BREAKPOINTNUM]...\n\
14902 Arguments are breakpoint numbers with spaces in between.\n\
14903 To disable all breakpoints, give no argument.\n\
14904 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
14905 &disablelist, 1, &cmdlist);
14906 add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
14907 add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
14908
14909 add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
14910 Disable all or some breakpoints.\n\
14911 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
14912 Arguments are breakpoint numbers with spaces in between.\n\
14913 To disable all breakpoints, give no argument.\n\
14914 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
14915 This command may be abbreviated \"disable\"."),
14916 &disablelist);
14917
14918 cmd_list_element *delete_cmd
14919 = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
14920 Delete all or some breakpoints.\n\
14921 Usage: delete [BREAKPOINTNUM]...\n\
14922 Arguments are breakpoint numbers with spaces in between.\n\
14923 To delete all breakpoints, watchpoints, tracepoints, and catchpoints,\n\
14924 give no argument.\n\
14925 \n\
14926 Also a prefix command for deletion of other GDB objects."),
14927 &deletelist, 1, &cmdlist);
14928 add_com_alias ("d", delete_cmd, class_breakpoint, 1);
14929 add_com_alias ("del", delete_cmd, class_breakpoint, 1);
14930
14931 add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
14932 Delete all or some breakpoints or auto-display expressions.\n\
14933 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
14934 Arguments are breakpoint numbers with spaces in between.\n\
14935 To delete all breakpoints, watchpoints, tracepoints, and catchpoints,\n\
14936 give no argument.\n\
14937 This command may be abbreviated \"delete\"."),
14938 &deletelist);
14939
14940 cmd_list_element *clear_cmd
14941 = add_com ("clear", class_breakpoint, clear_command, _("\
14942 Clear breakpoint at specified location.\n\
14943 Argument may be a linespec, explicit, or address location as described below.\n\
14944 \n\
14945 With no argument, clears all breakpoints in the line that the selected frame\n\
14946 is executing in.\n"
14947 "\n" LOCATION_SPEC_HELP_STRING "\n\n\
14948 See also the \"delete\" command which clears breakpoints by number."));
14949 add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
14950
14951 cmd_list_element *break_cmd
14952 = add_com ("break", class_breakpoint, break_command, _("\
14953 Set breakpoint at specified location.\n"
14954 BREAK_ARGS_HELP ("break")));
14955 set_cmd_completer (break_cmd, location_completer);
14956
14957 add_com_alias ("b", break_cmd, class_run, 1);
14958 add_com_alias ("br", break_cmd, class_run, 1);
14959 add_com_alias ("bre", break_cmd, class_run, 1);
14960 add_com_alias ("brea", break_cmd, class_run, 1);
14961
14962 cmd_list_element *info_breakpoints_cmd
14963 = add_info ("breakpoints", info_breakpoints_command, _("\
14964 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14965 The \"Type\" column indicates one of:\n\
14966 \tbreakpoint - normal breakpoint\n\
14967 \twatchpoint - watchpoint\n\
14968 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14969 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14970 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14971 address and file/line number respectively.\n\
14972 \n\
14973 Convenience variable \"$_\" and default examine address for \"x\"\n\
14974 are set to the address of the last breakpoint listed unless the command\n\
14975 is prefixed with \"server \".\n\n\
14976 Convenience variable \"$bpnum\" contains the number of the last\n\
14977 breakpoint set."));
14978
14979 add_info_alias ("b", info_breakpoints_cmd, 1);
14980
14981 add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14982 Status of all breakpoints, or breakpoint number NUMBER.\n\
14983 The \"Type\" column indicates one of:\n\
14984 \tbreakpoint - normal breakpoint\n\
14985 \twatchpoint - watchpoint\n\
14986 \tlongjmp - internal breakpoint used to step through longjmp()\n\
14987 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14988 \tuntil - internal breakpoint used by the \"until\" command\n\
14989 \tfinish - internal breakpoint used by the \"finish\" command\n\
14990 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14991 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14992 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14993 address and file/line number respectively.\n\
14994 \n\
14995 Convenience variable \"$_\" and default examine address for \"x\"\n\
14996 are set to the address of the last breakpoint listed unless the command\n\
14997 is prefixed with \"server \".\n\n\
14998 Convenience variable \"$bpnum\" contains the number of the last\n\
14999 breakpoint set."),
15000 &maintenanceinfolist);
15001
15002 add_basic_prefix_cmd ("catch", class_breakpoint, _("\
15003 Set catchpoints to catch events."),
15004 &catch_cmdlist,
15005 0/*allow-unknown*/, &cmdlist);
15006
15007 add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
15008 Set temporary catchpoints to catch events."),
15009 &tcatch_cmdlist,
15010 0/*allow-unknown*/, &cmdlist);
15011
15012 const auto opts = make_watch_options_def_group (nullptr);
15013
15014 static const std::string watch_help = gdb::option::build_help (_("\
15015 Set a watchpoint for EXPRESSION.\n\
15016 Usage: watch [-location] EXPRESSION\n\
15017 \n\
15018 Options:\n\
15019 %OPTIONS%\n\
15020 \n\
15021 A watchpoint stops execution of your program whenever the value of\n\
15022 an expression changes."), opts);
15023 c = add_com ("watch", class_breakpoint, watch_command,
15024 watch_help.c_str ());
15025 set_cmd_completer_handle_brkchars (c, watch_command_completer);
15026
15027 static const std::string rwatch_help = gdb::option::build_help (_("\
15028 Set a read watchpoint for EXPRESSION.\n\
15029 Usage: rwatch [-location] EXPRESSION\n\
15030 \n\
15031 Options:\n\
15032 %OPTIONS%\n\
15033 \n\
15034 A read watchpoint stops execution of your program whenever the value of\n\
15035 an expression is read."), opts);
15036 c = add_com ("rwatch", class_breakpoint, rwatch_command,
15037 rwatch_help.c_str ());
15038 set_cmd_completer_handle_brkchars (c, watch_command_completer);
15039
15040 static const std::string awatch_help = gdb::option::build_help (_("\
15041 Set an access watchpoint for EXPRESSION.\n\
15042 Usage: awatch [-location] EXPRESSION\n\
15043 \n\
15044 Options:\n\
15045 %OPTIONS%\n\
15046 \n\
15047 An access watchpoint stops execution of your program whenever the value\n\
15048 of an expression is either read or written."), opts);
15049 c = add_com ("awatch", class_breakpoint, awatch_command,
15050 awatch_help.c_str ());
15051 set_cmd_completer_handle_brkchars (c, watch_command_completer);
15052
15053 add_info ("watchpoints", info_watchpoints_command, _("\
15054 Status of specified watchpoints (all watchpoints if no argument)."));
15055
15056 /* XXX: cagney/2005-02-23: This should be a boolean, and should
15057 respond to changes - contrary to the description. */
15058 add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15059 &can_use_hw_watchpoints, _("\
15060 Set debugger's willingness to use watchpoint hardware."), _("\
15061 Show debugger's willingness to use watchpoint hardware."), _("\
15062 If zero, gdb will not use hardware for new watchpoints, even if\n\
15063 such is available. (However, any hardware watchpoints that were\n\
15064 created before setting this to nonzero, will continue to use watchpoint\n\
15065 hardware.)"),
15066 NULL,
15067 show_can_use_hw_watchpoints,
15068 &setlist, &showlist);
15069
15070 can_use_hw_watchpoints = 1;
15071
15072 /* Tracepoint manipulation commands. */
15073
15074 cmd_list_element *trace_cmd
15075 = add_com ("trace", class_breakpoint, trace_command, _("\
15076 Set a tracepoint at specified location.\n\
15077 \n"
15078 BREAK_ARGS_HELP ("trace") "\n\
15079 Do \"help tracepoints\" for info on other tracepoint commands."));
15080 set_cmd_completer (trace_cmd, location_completer);
15081
15082 add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
15083 add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
15084 add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
15085 add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
15086
15087 c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15088 Set a fast tracepoint at specified location.\n\
15089 \n"
15090 BREAK_ARGS_HELP ("ftrace") "\n\
15091 Do \"help tracepoints\" for info on other tracepoint commands."));
15092 set_cmd_completer (c, location_completer);
15093
15094 c = add_com ("strace", class_breakpoint, strace_command, _("\
15095 Set a static tracepoint at location or marker.\n\
15096 \n\
15097 strace [LOCATION] [if CONDITION]\n\
15098 LOCATION may be a linespec, explicit, or address location (described below)\n\
15099 or -m MARKER_ID.\n\n\
15100 If a marker id is specified, probe the marker with that name. With\n\
15101 no LOCATION, uses current execution address of the selected stack frame.\n\
15102 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15103 This collects arbitrary user data passed in the probe point call to the\n\
15104 tracing library. You can inspect it when analyzing the trace buffer,\n\
15105 by printing the $_sdata variable like any other convenience variable.\n\
15106 \n\
15107 CONDITION is a boolean expression.\n\
15108 \n" LOCATION_SPEC_HELP_STRING "\n\n\
15109 Multiple tracepoints at one place are permitted, and useful if their\n\
15110 conditions are different.\n\
15111 \n\
15112 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15113 Do \"help tracepoints\" for info on other tracepoint commands."));
15114 set_cmd_completer (c, location_completer);
15115
15116 cmd_list_element *info_tracepoints_cmd
15117 = add_info ("tracepoints", info_tracepoints_command, _("\
15118 Status of specified tracepoints (all tracepoints if no argument).\n\
15119 Convenience variable \"$tpnum\" contains the number of the\n\
15120 last tracepoint set."));
15121
15122 add_info_alias ("tp", info_tracepoints_cmd, 1);
15123
15124 cmd_list_element *delete_tracepoints_cmd
15125 = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15126 Delete specified tracepoints.\n\
15127 Arguments are tracepoint numbers, separated by spaces.\n\
15128 No argument means delete all tracepoints."),
15129 &deletelist);
15130 add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
15131
15132 c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15133 Disable specified tracepoints.\n\
15134 Arguments are tracepoint numbers, separated by spaces.\n\
15135 No argument means disable all tracepoints."),
15136 &disablelist);
15137 deprecate_cmd (c, "disable");
15138
15139 c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15140 Enable specified tracepoints.\n\
15141 Arguments are tracepoint numbers, separated by spaces.\n\
15142 No argument means enable all tracepoints."),
15143 &enablelist);
15144 deprecate_cmd (c, "enable");
15145
15146 add_com ("passcount", class_trace, trace_pass_command, _("\
15147 Set the passcount for a tracepoint.\n\
15148 The trace will end when the tracepoint has been passed 'count' times.\n\
15149 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15150 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15151
15152 add_basic_prefix_cmd ("save", class_breakpoint,
15153 _("Save breakpoint definitions as a script."),
15154 &save_cmdlist,
15155 0/*allow-unknown*/, &cmdlist);
15156
15157 c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15158 Save current breakpoint definitions as a script.\n\
15159 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15160 catchpoints, tracepoints). Use the 'source' command in another debug\n\
15161 session to restore them."),
15162 &save_cmdlist);
15163 set_cmd_completer (c, deprecated_filename_completer);
15164
15165 cmd_list_element *save_tracepoints_cmd
15166 = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15167 Save current tracepoint definitions as a script.\n\
15168 Use the 'source' command in another debug session to restore them."),
15169 &save_cmdlist);
15170 set_cmd_completer (save_tracepoints_cmd, deprecated_filename_completer);
15171
15172 c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
15173 deprecate_cmd (c, "save tracepoints");
15174
15175 add_setshow_prefix_cmd ("breakpoint", class_maintenance,
15176 _("\
15177 Breakpoint specific settings.\n\
15178 Configure various breakpoint-specific variables such as\n\
15179 pending breakpoint behavior."),
15180 _("\
15181 Breakpoint specific settings.\n\
15182 Configure various breakpoint-specific variables such as\n\
15183 pending breakpoint behavior."),
15184 &breakpoint_set_cmdlist, &breakpoint_show_cmdlist,
15185 &setlist, &showlist);
15186
15187 add_setshow_auto_boolean_cmd ("pending", no_class,
15188 &pending_break_support, _("\
15189 Set debugger's behavior regarding pending breakpoints."), _("\
15190 Show debugger's behavior regarding pending breakpoints."), _("\
15191 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15192 pending breakpoint. If off, an unrecognized breakpoint location results in\n\
15193 an error. If auto, an unrecognized breakpoint location results in a\n\
15194 user-query to see if a pending breakpoint should be created."),
15195 NULL,
15196 show_pending_break_support,
15197 &breakpoint_set_cmdlist,
15198 &breakpoint_show_cmdlist);
15199
15200 pending_break_support = AUTO_BOOLEAN_AUTO;
15201
15202 add_setshow_boolean_cmd ("auto-hw", no_class,
15203 &automatic_hardware_breakpoints, _("\
15204 Set automatic usage of hardware breakpoints."), _("\
15205 Show automatic usage of hardware breakpoints."), _("\
15206 If set, the debugger will automatically use hardware breakpoints for\n\
15207 breakpoints set with \"break\" but falling in read-only memory. If not set,\n\
15208 a warning will be emitted for such breakpoints."),
15209 NULL,
15210 show_automatic_hardware_breakpoints,
15211 &breakpoint_set_cmdlist,
15212 &breakpoint_show_cmdlist);
15213
15214 add_setshow_boolean_cmd ("always-inserted", class_support,
15215 &always_inserted_mode, _("\
15216 Set mode for inserting breakpoints."), _("\
15217 Show mode for inserting breakpoints."), _("\
15218 When this mode is on, breakpoints are inserted immediately as soon as\n\
15219 they're created, kept inserted even when execution stops, and removed\n\
15220 only when the user deletes them. When this mode is off (the default),\n\
15221 breakpoints are inserted only when execution continues, and removed\n\
15222 when execution stops."),
15223 NULL,
15224 &show_always_inserted_mode,
15225 &breakpoint_set_cmdlist,
15226 &breakpoint_show_cmdlist);
15227
15228 add_setshow_boolean_cmd ("breakpoint", class_maintenance,
15229 &debug_breakpoint, _("\
15230 Set breakpoint location debugging."), _("\
15231 Show breakpoint location debugging."), _("\
15232 When on, breakpoint location specific debugging is enabled."),
15233 NULL,
15234 show_debug_breakpoint,
15235 &setdebuglist, &showdebuglist);
15236
15237 add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15238 condition_evaluation_enums,
15239 &condition_evaluation_mode_1, _("\
15240 Set mode of breakpoint condition evaluation."), _("\
15241 Show mode of breakpoint condition evaluation."), _("\
15242 When this is set to \"host\", breakpoint conditions will be\n\
15243 evaluated on the host's side by GDB. When it is set to \"target\",\n\
15244 breakpoint conditions will be downloaded to the target (if the target\n\
15245 supports such feature) and conditions will be evaluated on the target's side.\n\
15246 If this is set to \"auto\" (default), this will be automatically set to\n\
15247 \"target\" if it supports condition evaluation, otherwise it will\n\
15248 be set to \"host\"."),
15249 &set_condition_evaluation_mode,
15250 &show_condition_evaluation_mode,
15251 &breakpoint_set_cmdlist,
15252 &breakpoint_show_cmdlist);
15253
15254 add_com ("break-range", class_breakpoint, break_range_command, _("\
15255 Set a breakpoint for an address range.\n\
15256 break-range START-LOCATION, END-LOCATION\n\
15257 where START-LOCATION and END-LOCATION can be one of the following:\n\
15258 LINENUM, for that line in the current file,\n\
15259 FILE:LINENUM, for that line in that file,\n\
15260 +OFFSET, for that number of lines after the current line\n\
15261 or the start of the range\n\
15262 FUNCTION, for the first line in that function,\n\
15263 FILE:FUNCTION, to distinguish among like-named static functions.\n\
15264 *ADDRESS, for the instruction at that address.\n\
15265 \n\
15266 The breakpoint will stop execution of the inferior whenever it executes\n\
15267 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15268 range (including START-LOCATION and END-LOCATION)."));
15269
15270 c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
15271 Set a dynamic printf at specified location.\n\
15272 dprintf location,format string,arg1,arg2,...\n\
15273 location may be a linespec, explicit, or address location.\n"
15274 "\n" LOCATION_SPEC_HELP_STRING));
15275 set_cmd_completer (c, location_completer);
15276
15277 add_setshow_enum_cmd ("dprintf-style", class_support,
15278 dprintf_style_enums, &dprintf_style, _("\
15279 Set the style of usage for dynamic printf."), _("\
15280 Show the style of usage for dynamic printf."), _("\
15281 This setting chooses how GDB will do a dynamic printf.\n\
15282 If the value is \"gdb\", then the printing is done by GDB to its own\n\
15283 console, as with the \"printf\" command.\n\
15284 If the value is \"call\", the print is done by calling a function in your\n\
15285 program; by default printf(), but you can choose a different function or\n\
15286 output stream by setting dprintf-function and dprintf-channel."),
15287 update_dprintf_commands, NULL,
15288 &setlist, &showlist);
15289
15290 add_setshow_string_cmd ("dprintf-function", class_support,
15291 &dprintf_function, _("\
15292 Set the function to use for dynamic printf."), _("\
15293 Show the function to use for dynamic printf."), NULL,
15294 update_dprintf_commands, NULL,
15295 &setlist, &showlist);
15296
15297 add_setshow_string_cmd ("dprintf-channel", class_support,
15298 &dprintf_channel, _("\
15299 Set the channel to use for dynamic printf."), _("\
15300 Show the channel to use for dynamic printf."), NULL,
15301 update_dprintf_commands, NULL,
15302 &setlist, &showlist);
15303
15304 add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
15305 &disconnected_dprintf, _("\
15306 Set whether dprintf continues after GDB disconnects."), _("\
15307 Show whether dprintf continues after GDB disconnects."), _("\
15308 Use this to let dprintf commands continue to hit and produce output\n\
15309 even if GDB disconnects or detaches from the target."),
15310 NULL,
15311 NULL,
15312 &setlist, &showlist);
15313
15314 add_com ("agent-printf", class_vars, agent_printf_command, _("\
15315 Target agent only formatted printing, like the C \"printf\" function.\n\
15316 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
15317 This supports most C printf format specifications, like %s, %d, etc.\n\
15318 This is useful for formatted output in user-defined commands."));
15319
15320 automatic_hardware_breakpoints = true;
15321
15322 gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
15323 "breakpoint");
15324 gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
15325 "breakpoint");
15326 gdb::observers::inferior_removed.attach (remove_inferior_breakpoints,
15327 "breakpoint");
15328 }