]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/breakpoint.c
Update copyright year range in header of all files managed by GDB
[thirdparty/binutils-gdb.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observable.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "ui.h"
57 #include "valprint.h"
58 #include "jit.h"
59 #include "parser-defs.h"
60 #include "gdbsupport/gdb_regex.h"
61 #include "probe.h"
62 #include "cli/cli-utils.h"
63 #include "stack.h"
64 #include "ax-gdb.h"
65 #include "dummy-frame.h"
66 #include "interps.h"
67 #include "gdbsupport/format.h"
68 #include "thread-fsm.h"
69 #include "tid-parse.h"
70 #include "cli/cli-style.h"
71 #include "cli/cli-decode.h"
72 #include <unordered_set>
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
94 create_sals_from_location_spec_default (location_spec *locspec,
95 linespec_result *canonical);
96
97 static void create_breakpoints_sal (struct gdbarch *,
98 struct linespec_result *,
99 gdb::unique_xmalloc_ptr<char>,
100 gdb::unique_xmalloc_ptr<char>,
101 enum bptype,
102 enum bpdisp, int, int, int,
103 int,
104 int, int, int, unsigned);
105
106 static int can_use_hardware_watchpoint
107 (const std::vector<value_ref_ptr> &vals);
108
109 static void mention (const breakpoint *);
110
111 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
112
113 static breakpoint *add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b);
114
115 static struct breakpoint *
116 momentary_breakpoint_from_master (struct breakpoint *orig,
117 enum bptype type,
118 int loc_enabled, int thread);
119
120 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, bool);
121
122 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
123 CORE_ADDR bpaddr,
124 enum bptype bptype,
125 struct program_space *pspace);
126
127 static bool watchpoint_locations_match (const struct bp_location *loc1,
128 const struct bp_location *loc2);
129
130 static bool breakpoint_locations_match (const struct bp_location *loc1,
131 const struct bp_location *loc2,
132 bool sw_hw_bps_match = false);
133
134 static bool breakpoint_location_address_match (struct bp_location *bl,
135 const struct address_space *aspace,
136 CORE_ADDR addr);
137
138 static bool breakpoint_location_address_range_overlap (struct bp_location *,
139 const address_space *,
140 CORE_ADDR, int);
141
142 static int remove_breakpoint (struct bp_location *);
143 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
144
145 static enum print_stop_action print_bp_stop_message (bpstat *bs);
146
147 static int hw_breakpoint_used_count (void);
148
149 static int hw_watchpoint_use_count (struct breakpoint *);
150
151 static int hw_watchpoint_used_count_others (struct breakpoint *except,
152 enum bptype type,
153 int *other_type_used);
154
155 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
156 int count);
157
158 static void decref_bp_location (struct bp_location **loc);
159
160 static std::vector<symtab_and_line> bkpt_probe_decode_location_spec
161 (struct breakpoint *b,
162 location_spec *locspec,
163 struct program_space *search_pspace);
164
165 static bool bl_address_is_meaningful (bp_location *loc);
166
167 static int find_loc_num_by_location (const bp_location *loc);
168
169 /* update_global_location_list's modes of operation wrt to whether to
170 insert locations now. */
171 enum ugll_insert_mode
172 {
173 /* Don't insert any breakpoint locations into the inferior, only
174 remove already-inserted locations that no longer should be
175 inserted. Functions that delete a breakpoint or breakpoints
176 should specify this mode, so that deleting a breakpoint doesn't
177 have the side effect of inserting the locations of other
178 breakpoints that are marked not-inserted, but should_be_inserted
179 returns true on them.
180
181 This behavior is useful is situations close to tear-down -- e.g.,
182 after an exec, while the target still has execution, but
183 breakpoint shadows of the previous executable image should *NOT*
184 be restored to the new image; or before detaching, where the
185 target still has execution and wants to delete breakpoints from
186 GDB's lists, and all breakpoints had already been removed from
187 the inferior. */
188 UGLL_DONT_INSERT,
189
190 /* May insert breakpoints iff breakpoints_should_be_inserted_now
191 claims breakpoints should be inserted now. */
192 UGLL_MAY_INSERT,
193
194 /* Insert locations now, irrespective of
195 breakpoints_should_be_inserted_now. E.g., say all threads are
196 stopped right now, and the user did "continue". We need to
197 insert breakpoints _before_ resuming the target, but
198 UGLL_MAY_INSERT wouldn't insert them, because
199 breakpoints_should_be_inserted_now returns false at that point,
200 as no thread is running yet. */
201 UGLL_INSERT
202 };
203
204 /* Return a textual version of INSERT_MODE. */
205
206 static const char *
207 ugll_insert_mode_text (ugll_insert_mode insert_mode)
208 {
209 /* Make sure the compiler warns if a new ugll_insert_mode enumerator is added
210 but not handled here. */
211 DIAGNOSTIC_PUSH
212 DIAGNOSTIC_ERROR_SWITCH
213 switch (insert_mode)
214 {
215 case UGLL_DONT_INSERT:
216 return "UGLL_DONT_INSERT";
217 case UGLL_MAY_INSERT:
218 return "UGLL_MAY_INSERT";
219 case UGLL_INSERT:
220 return "UGLL_INSERT";
221 }
222 DIAGNOSTIC_POP
223
224 gdb_assert_not_reached ("must handle all enum values");
225 }
226
227 /* Return a textual version of REASON. */
228
229 static const char *
230 remove_bp_reason_str (remove_bp_reason reason)
231 {
232 /* Make sure the compiler warns if a new remove_bp_reason enumerator is added
233 but not handled here. */
234 DIAGNOSTIC_PUSH
235 DIAGNOSTIC_ERROR_SWITCH
236 switch (reason)
237 {
238 case REMOVE_BREAKPOINT:
239 return "regular remove";
240 case DETACH_BREAKPOINT:
241 return "detach";
242 }
243 DIAGNOSTIC_POP
244
245 gdb_assert_not_reached ("must handle all enum values");
246 }
247
248 /* Return a textual version of breakpoint location BL describing number,
249 location and address. */
250
251 static std::string
252 breakpoint_location_address_str (const bp_location *bl)
253 {
254 std::string str = string_printf ("Breakpoint %d (%s) at address %s",
255 bl->owner->number,
256 host_address_to_string (bl),
257 paddress (bl->gdbarch, bl->address));
258
259 std::string loc_string = bl->to_string ();
260 if (!loc_string.empty ())
261 str += string_printf (" %s", loc_string.c_str ());
262
263 return str;
264 }
265
266 static void update_global_location_list (enum ugll_insert_mode);
267
268 static void update_global_location_list_nothrow (enum ugll_insert_mode);
269
270 static void insert_breakpoint_locations (void);
271
272 static void trace_pass_command (const char *, int);
273
274 static void set_tracepoint_count (int num);
275
276 static bool is_masked_watchpoint (const struct breakpoint *b);
277
278 /* Return true if B refers to a static tracepoint set by marker ("-m"),
279 zero otherwise. */
280
281 static bool strace_marker_p (struct breakpoint *b);
282
283 static void bkpt_probe_create_sals_from_location_spec
284 (location_spec *locspec,
285 struct linespec_result *canonical);
286 static void tracepoint_probe_create_sals_from_location_spec
287 (location_spec *locspec,
288 struct linespec_result *canonical);
289
290 const struct breakpoint_ops code_breakpoint_ops =
291 {
292 create_sals_from_location_spec_default,
293 create_breakpoints_sal,
294 };
295
296 /* Breakpoints set on probes. */
297 static const struct breakpoint_ops bkpt_probe_breakpoint_ops =
298 {
299 bkpt_probe_create_sals_from_location_spec,
300 create_breakpoints_sal,
301 };
302
303 /* Tracepoints set on probes. */
304 static const struct breakpoint_ops tracepoint_probe_breakpoint_ops =
305 {
306 tracepoint_probe_create_sals_from_location_spec,
307 create_breakpoints_sal,
308 };
309
310 /* Implementation of abstract dtors. These must exist to satisfy the
311 linker. */
312
313 breakpoint::~breakpoint ()
314 {
315 }
316
317 code_breakpoint::~code_breakpoint ()
318 {
319 }
320
321 catchpoint::~catchpoint ()
322 {
323 }
324
325 /* The structure to be used in regular breakpoints. */
326 struct ordinary_breakpoint : public code_breakpoint
327 {
328 using code_breakpoint::code_breakpoint;
329
330 int resources_needed (const struct bp_location *) override;
331 enum print_stop_action print_it (const bpstat *bs) const override;
332 void print_mention () const override;
333 void print_recreate (struct ui_file *fp) const override;
334 };
335
336 /* Internal breakpoints. These typically have a lifetime the same as
337 the program, and they end up installed on the breakpoint chain with
338 a negative breakpoint number. They're visible in "maint info
339 breakpoints", but not "info breakpoints". */
340 struct internal_breakpoint : public code_breakpoint
341 {
342 internal_breakpoint (struct gdbarch *gdbarch,
343 enum bptype type, CORE_ADDR address)
344 : code_breakpoint (gdbarch, type)
345 {
346 symtab_and_line sal;
347 sal.pc = address;
348 sal.section = find_pc_overlay (sal.pc);
349 sal.pspace = current_program_space;
350 add_location (sal);
351
352 pspace = current_program_space;
353 disposition = disp_donttouch;
354 }
355
356 void re_set () override;
357 void check_status (struct bpstat *bs) override;
358 enum print_stop_action print_it (const bpstat *bs) const override;
359 void print_mention () const override;
360 };
361
362 /* Momentary breakpoints. These typically have a lifetime of some run
363 control command only, are always thread-specific, and have 0 for
364 breakpoint number. I.e., there can be many momentary breakpoints
365 on the breakpoint chain and they all same the same number (zero).
366 They're visible in "maint info breakpoints", but not "info
367 breakpoints". */
368 struct momentary_breakpoint : public code_breakpoint
369 {
370 momentary_breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
371 program_space *pspace_,
372 const struct frame_id &frame_id_,
373 int thread_)
374 : code_breakpoint (gdbarch_, bptype)
375 {
376 /* If FRAME_ID is valid, it should be a real frame, not an inlined
377 or tail-called one. */
378 gdb_assert (!frame_id_artificial_p (frame_id));
379
380 /* Momentary breakpoints are always thread-specific. */
381 gdb_assert (thread_ > 0);
382
383 pspace = pspace_;
384 enable_state = bp_enabled;
385 disposition = disp_donttouch;
386 frame_id = frame_id_;
387 thread = thread_;
388
389 /* The inferior should have been set by the parent constructor. */
390 gdb_assert (inferior == -1);
391 }
392
393 void re_set () override;
394 void check_status (struct bpstat *bs) override;
395 enum print_stop_action print_it (const bpstat *bs) const override;
396 void print_mention () const override;
397 };
398
399 /* DPrintf breakpoints. */
400 struct dprintf_breakpoint : public ordinary_breakpoint
401 {
402 using ordinary_breakpoint::ordinary_breakpoint;
403
404 void re_set () override;
405 int breakpoint_hit (const struct bp_location *bl,
406 const address_space *aspace,
407 CORE_ADDR bp_addr,
408 const target_waitstatus &ws) override;
409 void print_recreate (struct ui_file *fp) const override;
410 void after_condition_true (struct bpstat *bs) override;
411 };
412
413 /* Ranged breakpoints. */
414 struct ranged_breakpoint : public ordinary_breakpoint
415 {
416 explicit ranged_breakpoint (struct gdbarch *gdbarch,
417 const symtab_and_line &sal_start,
418 int length,
419 location_spec_up start_locspec,
420 location_spec_up end_locspec)
421 : ordinary_breakpoint (gdbarch, bp_hardware_breakpoint)
422 {
423 bp_location *bl = add_location (sal_start);
424 bl->length = length;
425
426 disposition = disp_donttouch;
427
428 locspec = std::move (start_locspec);
429 locspec_range_end = std::move (end_locspec);
430 }
431
432 int breakpoint_hit (const struct bp_location *bl,
433 const address_space *aspace,
434 CORE_ADDR bp_addr,
435 const target_waitstatus &ws) override;
436 int resources_needed (const struct bp_location *) override;
437 enum print_stop_action print_it (const bpstat *bs) const override;
438 bool print_one (const bp_location **) const override;
439 void print_one_detail (struct ui_out *) const override;
440 void print_mention () const override;
441 void print_recreate (struct ui_file *fp) const override;
442 };
443
444 /* Static tracepoints with marker (`-m'). */
445 struct static_marker_tracepoint : public tracepoint
446 {
447 using tracepoint::tracepoint;
448
449 std::vector<symtab_and_line> decode_location_spec
450 (struct location_spec *locspec,
451 struct program_space *search_pspace) override;
452 };
453
454 /* The style in which to perform a dynamic printf. This is a user
455 option because different output options have different tradeoffs;
456 if GDB does the printing, there is better error handling if there
457 is a problem with any of the arguments, but using an inferior
458 function lets you have special-purpose printers and sending of
459 output to the same place as compiled-in print functions. */
460
461 static const char dprintf_style_gdb[] = "gdb";
462 static const char dprintf_style_call[] = "call";
463 static const char dprintf_style_agent[] = "agent";
464 static const char *const dprintf_style_enums[] = {
465 dprintf_style_gdb,
466 dprintf_style_call,
467 dprintf_style_agent,
468 NULL
469 };
470 static const char *dprintf_style = dprintf_style_gdb;
471
472 /* The function to use for dynamic printf if the preferred style is to
473 call into the inferior. The value is simply a string that is
474 copied into the command, so it can be anything that GDB can
475 evaluate to a callable address, not necessarily a function name. */
476
477 static std::string dprintf_function = "printf";
478
479 /* The channel to use for dynamic printf if the preferred style is to
480 call into the inferior; if a nonempty string, it will be passed to
481 the call as the first argument, with the format string as the
482 second. As with the dprintf function, this can be anything that
483 GDB knows how to evaluate, so in addition to common choices like
484 "stderr", this could be an app-specific expression like
485 "mystreams[curlogger]". */
486
487 static std::string dprintf_channel;
488
489 /* True if dprintf commands should continue to operate even if GDB
490 has disconnected. */
491 static bool disconnected_dprintf = true;
492
493 struct command_line *
494 breakpoint_commands (struct breakpoint *b)
495 {
496 return b->commands ? b->commands.get () : NULL;
497 }
498
499 /* Flag indicating that a command has proceeded the inferior past the
500 current breakpoint. */
501
502 static bool breakpoint_proceeded;
503
504 const char *
505 bpdisp_text (enum bpdisp disp)
506 {
507 /* NOTE: the following values are a part of MI protocol and
508 represent values of 'disp' field returned when inferior stops at
509 a breakpoint. */
510 static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
511
512 return bpdisps[(int) disp];
513 }
514
515 /* Prototypes for exported functions. */
516 /* If FALSE, gdb will not use hardware support for watchpoints, even
517 if such is available. */
518 static int can_use_hw_watchpoints;
519
520 static void
521 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
522 struct cmd_list_element *c,
523 const char *value)
524 {
525 gdb_printf (file,
526 _("Debugger's willingness to use "
527 "watchpoint hardware is %s.\n"),
528 value);
529 }
530
531 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
532 If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
533 for unrecognized breakpoint locations.
534 If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized. */
535 static enum auto_boolean pending_break_support;
536 static void
537 show_pending_break_support (struct ui_file *file, int from_tty,
538 struct cmd_list_element *c,
539 const char *value)
540 {
541 gdb_printf (file,
542 _("Debugger's behavior regarding "
543 "pending breakpoints is %s.\n"),
544 value);
545 }
546
547 /* If true, gdb will automatically use hardware breakpoints for breakpoints
548 set with "break" but falling in read-only memory.
549 If false, gdb will warn about such breakpoints, but won't automatically
550 use hardware breakpoints. */
551 static bool automatic_hardware_breakpoints;
552 static void
553 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
554 struct cmd_list_element *c,
555 const char *value)
556 {
557 gdb_printf (file,
558 _("Automatic usage of hardware breakpoints is %s.\n"),
559 value);
560 }
561
562 /* If on, GDB keeps breakpoints inserted even if the inferior is
563 stopped, and immediately inserts any new breakpoints as soon as
564 they're created. If off (default), GDB keeps breakpoints off of
565 the target as long as possible. That is, it delays inserting
566 breakpoints until the next resume, and removes them again when the
567 target fully stops. This is a bit safer in case GDB crashes while
568 processing user input. */
569 static bool always_inserted_mode = false;
570
571 static void
572 show_always_inserted_mode (struct ui_file *file, int from_tty,
573 struct cmd_list_element *c, const char *value)
574 {
575 gdb_printf (file, _("Always inserted breakpoint mode is %s.\n"),
576 value);
577 }
578
579 /* True if breakpoint debug output is enabled. */
580 static bool debug_breakpoint = false;
581
582 /* Print a "breakpoint" debug statement. */
583 #define breakpoint_debug_printf(fmt, ...) \
584 debug_prefixed_printf_cond (debug_breakpoint, "breakpoint", fmt, \
585 ##__VA_ARGS__)
586
587 /* "show debug breakpoint" implementation. */
588 static void
589 show_debug_breakpoint (struct ui_file *file, int from_tty,
590 struct cmd_list_element *c, const char *value)
591 {
592 gdb_printf (file, _("Breakpoint location debugging is %s.\n"), value);
593 }
594
595 /* See breakpoint.h. */
596
597 int
598 breakpoints_should_be_inserted_now (void)
599 {
600 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
601 {
602 /* If breakpoints are global, they should be inserted even if no
603 thread under gdb's control is running, or even if there are
604 no threads under GDB's control yet. */
605 return 1;
606 }
607 else
608 {
609 if (always_inserted_mode)
610 {
611 /* The user wants breakpoints inserted even if all threads
612 are stopped. */
613 return 1;
614 }
615
616 for (inferior *inf : all_inferiors ())
617 if (inf->has_execution ()
618 && threads_are_executing (inf->process_target ()))
619 return 1;
620
621 /* Don't remove breakpoints yet if, even though all threads are
622 stopped, we still have events to process. */
623 for (thread_info *tp : all_non_exited_threads ())
624 if (tp->resumed () && tp->has_pending_waitstatus ())
625 return 1;
626 }
627 return 0;
628 }
629
630 static const char condition_evaluation_both[] = "host or target";
631
632 /* Modes for breakpoint condition evaluation. */
633 static const char condition_evaluation_auto[] = "auto";
634 static const char condition_evaluation_host[] = "host";
635 static const char condition_evaluation_target[] = "target";
636 static const char *const condition_evaluation_enums[] = {
637 condition_evaluation_auto,
638 condition_evaluation_host,
639 condition_evaluation_target,
640 NULL
641 };
642
643 /* Global that holds the current mode for breakpoint condition evaluation. */
644 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
645
646 /* Global that we use to display information to the user (gets its value from
647 condition_evaluation_mode_1. */
648 static const char *condition_evaluation_mode = condition_evaluation_auto;
649
650 /* Translate a condition evaluation mode MODE into either "host"
651 or "target". This is used mostly to translate from "auto" to the
652 real setting that is being used. It returns the translated
653 evaluation mode. */
654
655 static const char *
656 translate_condition_evaluation_mode (const char *mode)
657 {
658 if (mode == condition_evaluation_auto)
659 {
660 if (target_supports_evaluation_of_breakpoint_conditions ())
661 return condition_evaluation_target;
662 else
663 return condition_evaluation_host;
664 }
665 else
666 return mode;
667 }
668
669 /* Discovers what condition_evaluation_auto translates to. */
670
671 static const char *
672 breakpoint_condition_evaluation_mode (void)
673 {
674 return translate_condition_evaluation_mode (condition_evaluation_mode);
675 }
676
677 /* Return true if GDB should evaluate breakpoint conditions or false
678 otherwise. */
679
680 static bool
681 gdb_evaluates_breakpoint_condition_p (void)
682 {
683 const char *mode = breakpoint_condition_evaluation_mode ();
684
685 return (mode == condition_evaluation_host);
686 }
687
688 /* Are we executing breakpoint commands? */
689 static int executing_breakpoint_commands;
690
691 /* Are overlay event breakpoints enabled? */
692 static int overlay_events_enabled;
693
694 /* See description in breakpoint.h. */
695 bool target_exact_watchpoints = false;
696
697 /* Chains of all breakpoints defined. */
698
699 static intrusive_list<breakpoint> breakpoint_chain;
700
701 /* See breakpoint.h. */
702
703 breakpoint_range
704 all_breakpoints ()
705 {
706 return breakpoint_range (breakpoint_chain.begin (), breakpoint_chain.end ());
707 }
708
709 /* See breakpoint.h. */
710
711 breakpoint_safe_range
712 all_breakpoints_safe ()
713 {
714 return breakpoint_safe_range (all_breakpoints ());
715 }
716
717 /* See breakpoint.h. */
718
719 tracepoint_range
720 all_tracepoints ()
721 {
722 return tracepoint_range (tracepoint_iterator (breakpoint_chain.begin ()),
723 tracepoint_iterator (breakpoint_chain.end ()));
724 }
725
726 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS. */
727
728 static std::vector<bp_location *> bp_locations;
729
730 /* See breakpoint.h. */
731
732 const std::vector<bp_location *> &
733 all_bp_locations ()
734 {
735 return bp_locations;
736 }
737
738 /* Range to iterate over breakpoint locations at a given address. */
739
740 struct bp_locations_at_addr_range
741 {
742 using iterator = std::vector<bp_location *>::iterator;
743
744 bp_locations_at_addr_range (CORE_ADDR addr)
745 {
746 struct compare
747 {
748 bool operator() (const bp_location *loc, CORE_ADDR addr_) const
749 { return loc->address < addr_; }
750
751 bool operator() (CORE_ADDR addr_, const bp_location *loc) const
752 { return addr_ < loc->address; }
753 };
754
755 auto it_pair = std::equal_range (bp_locations.begin (), bp_locations.end (),
756 addr, compare ());
757
758 m_begin = it_pair.first;
759 m_end = it_pair.second;
760 }
761
762 iterator begin () const
763 { return m_begin; }
764
765 iterator end () const
766 { return m_end; }
767
768 private:
769 iterator m_begin;
770 iterator m_end;
771 };
772
773 /* Return a range to iterate over all breakpoint locations exactly at address
774 ADDR.
775
776 If it's needed to iterate multiple times on the same range, it's possible
777 to save the range in a local variable and use it multiple times:
778
779 auto range = all_bp_locations_at_addr (addr);
780
781 for (bp_location *loc : range)
782 // use loc
783
784 for (bp_location *loc : range)
785 // use loc
786
787 This saves a bit of time, as it avoids re-doing the binary searches to find
788 the range's boundaries. Just remember not to change the bp_locations vector
789 in the mean time, as it could make the range's iterators stale. */
790
791 static bp_locations_at_addr_range
792 all_bp_locations_at_addr (CORE_ADDR addr)
793 {
794 return bp_locations_at_addr_range (addr);
795 }
796
797 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
798 ADDRESS for the current elements of BP_LOCATIONS which get a valid
799 result from bp_location_has_shadow. You can use it for roughly
800 limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
801 an address you need to read. */
802
803 static CORE_ADDR bp_locations_placed_address_before_address_max;
804
805 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
806 + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
807 BP_LOCATIONS which get a valid result from bp_location_has_shadow.
808 You can use it for roughly limiting the subrange of BP_LOCATIONS to
809 scan for shadow bytes for an address you need to read. */
810
811 static CORE_ADDR bp_locations_shadow_len_after_address_max;
812
813 /* The locations that no longer correspond to any breakpoint, unlinked
814 from the bp_locations array, but for which a hit may still be
815 reported by a target. */
816 static std::vector<bp_location *> moribund_locations;
817
818 /* Number of last breakpoint made. */
819
820 static int breakpoint_count;
821
822 /* The value of `breakpoint_count' before the last command that
823 created breakpoints. If the last (break-like) command created more
824 than one breakpoint, then the difference between BREAKPOINT_COUNT
825 and PREV_BREAKPOINT_COUNT is more than one. */
826 static int prev_breakpoint_count;
827
828 /* Number of last tracepoint made. */
829
830 static int tracepoint_count;
831
832 static struct cmd_list_element *breakpoint_set_cmdlist;
833 static struct cmd_list_element *breakpoint_show_cmdlist;
834 struct cmd_list_element *save_cmdlist;
835
836 /* Return whether a breakpoint is an active enabled breakpoint. */
837 static bool
838 breakpoint_enabled (struct breakpoint *b)
839 {
840 return (b->enable_state == bp_enabled);
841 }
842
843 /* Set breakpoint count to NUM. */
844
845 static void
846 set_breakpoint_count (int num)
847 {
848 prev_breakpoint_count = breakpoint_count;
849 breakpoint_count = num;
850 set_internalvar_integer (lookup_internalvar ("bpnum"), num);
851 }
852
853 /* Used by `start_rbreak_breakpoints' below, to record the current
854 breakpoint count before "rbreak" creates any breakpoint. */
855 static int rbreak_start_breakpoint_count;
856
857 /* Called at the start an "rbreak" command to record the first
858 breakpoint made. */
859
860 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
861 {
862 rbreak_start_breakpoint_count = breakpoint_count;
863 }
864
865 /* Called at the end of an "rbreak" command to record the last
866 breakpoint made. */
867
868 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
869 {
870 prev_breakpoint_count = rbreak_start_breakpoint_count;
871 }
872
873 /* Used in run_command to zero the hit count when a new run starts. */
874
875 void
876 clear_breakpoint_hit_counts (void)
877 {
878 for (breakpoint &b : all_breakpoints ())
879 b.hit_count = 0;
880 }
881
882 \f
883 /* Return the breakpoint with the specified number, or NULL
884 if the number does not refer to an existing breakpoint. */
885
886 struct breakpoint *
887 get_breakpoint (int num)
888 {
889 for (breakpoint &b : all_breakpoints ())
890 if (b.number == num)
891 return &b;
892
893 return nullptr;
894 }
895
896 /* Return TRUE if NUM refer to an existing breakpoint that has
897 multiple code locations. */
898
899 static bool
900 has_multiple_locations (int num)
901 {
902 for (breakpoint &b : all_breakpoints ())
903 if (b.number == num)
904 return b.has_multiple_locations ();
905
906 return false;
907 }
908
909 \f
910
911 /* Mark locations as "conditions have changed" in case the target supports
912 evaluating conditions on its side. */
913
914 static void
915 mark_breakpoint_modified (struct breakpoint *b)
916 {
917 /* This is only meaningful if the target is
918 evaluating conditions and if the user has
919 opted for condition evaluation on the target's
920 side. */
921 if (gdb_evaluates_breakpoint_condition_p ()
922 || !target_supports_evaluation_of_breakpoint_conditions ())
923 return;
924
925 if (!is_breakpoint (b))
926 return;
927
928 for (bp_location &loc : b->locations ())
929 loc.condition_changed = condition_modified;
930 }
931
932 /* Mark location as "conditions have changed" in case the target supports
933 evaluating conditions on its side. */
934
935 static void
936 mark_breakpoint_location_modified (struct bp_location *loc)
937 {
938 /* This is only meaningful if the target is
939 evaluating conditions and if the user has
940 opted for condition evaluation on the target's
941 side. */
942 if (gdb_evaluates_breakpoint_condition_p ()
943 || !target_supports_evaluation_of_breakpoint_conditions ())
944
945 return;
946
947 if (!is_breakpoint (loc->owner))
948 return;
949
950 loc->condition_changed = condition_modified;
951 }
952
953 /* Sets the condition-evaluation mode using the static global
954 condition_evaluation_mode. */
955
956 static void
957 set_condition_evaluation_mode (const char *args, int from_tty,
958 struct cmd_list_element *c)
959 {
960 const char *old_mode, *new_mode;
961
962 if ((condition_evaluation_mode_1 == condition_evaluation_target)
963 && !target_supports_evaluation_of_breakpoint_conditions ())
964 {
965 condition_evaluation_mode_1 = condition_evaluation_mode;
966 warning (_("Target does not support breakpoint condition evaluation.\n"
967 "Using host evaluation mode instead."));
968 return;
969 }
970
971 new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
972 old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
973
974 /* Flip the switch. Flip it even if OLD_MODE == NEW_MODE as one of the
975 settings was "auto". */
976 condition_evaluation_mode = condition_evaluation_mode_1;
977
978 /* Only update the mode if the user picked a different one. */
979 if (new_mode != old_mode)
980 {
981 /* If the user switched to a different evaluation mode, we
982 need to synch the changes with the target as follows:
983
984 "host" -> "target": Send all (valid) conditions to the target.
985 "target" -> "host": Remove all the conditions from the target.
986 */
987
988 if (new_mode == condition_evaluation_target)
989 {
990 /* Mark everything modified and synch conditions with the
991 target. */
992 for (bp_location *loc : all_bp_locations ())
993 mark_breakpoint_location_modified (loc);
994 }
995 else
996 {
997 /* Manually mark non-duplicate locations to synch conditions
998 with the target. We do this to remove all the conditions the
999 target knows about. */
1000 for (bp_location *loc : all_bp_locations ())
1001 if (is_breakpoint (loc->owner) && loc->inserted)
1002 loc->needs_update = 1;
1003 }
1004
1005 /* Do the update. */
1006 update_global_location_list (UGLL_MAY_INSERT);
1007 }
1008
1009 return;
1010 }
1011
1012 /* Shows the current mode of breakpoint condition evaluation. Explicitly shows
1013 what "auto" is translating to. */
1014
1015 static void
1016 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
1017 struct cmd_list_element *c, const char *value)
1018 {
1019 if (condition_evaluation_mode == condition_evaluation_auto)
1020 gdb_printf (file,
1021 _("Breakpoint condition evaluation "
1022 "mode is %s (currently %s).\n"),
1023 value,
1024 breakpoint_condition_evaluation_mode ());
1025 else
1026 gdb_printf (file, _("Breakpoint condition evaluation mode is %s.\n"),
1027 value);
1028 }
1029
1030 /* Parse COND_STRING in the context of LOC and set as the condition
1031 expression of LOC. BP_NUM is the number of LOC's owner, LOC_NUM is
1032 the number of LOC within its owner. In case of parsing error, mark
1033 LOC as DISABLED_BY_COND. In case of success, unset DISABLED_BY_COND. */
1034
1035 static void
1036 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
1037 int bp_num, int loc_num)
1038 {
1039 bool has_junk = false;
1040 try
1041 {
1042 expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
1043 block_for_pc (loc->address), 0);
1044 if (*cond_string != 0)
1045 has_junk = true;
1046 else
1047 {
1048 loc->cond = std::move (new_exp);
1049 if (loc->disabled_by_cond && loc->enabled)
1050 gdb_printf (_("Breakpoint %d's condition is now valid at "
1051 "location %d, enabling.\n"),
1052 bp_num, loc_num);
1053
1054 loc->disabled_by_cond = false;
1055 }
1056 }
1057 catch (const gdb_exception_error &e)
1058 {
1059 if (loc->enabled)
1060 {
1061 /* Warn if a user-enabled location is now becoming disabled-by-cond.
1062 BP_NUM is 0 if the breakpoint is being defined for the first
1063 time using the "break ... if ..." command, and non-zero if
1064 already defined. */
1065 if (bp_num != 0)
1066 warning (_("failed to validate condition at location %d.%d, "
1067 "disabling:\n %s"), bp_num, loc_num, e.what ());
1068 else
1069 warning (_("failed to validate condition at location %d, "
1070 "disabling:\n %s"), loc_num, e.what ());
1071 }
1072
1073 loc->disabled_by_cond = true;
1074 }
1075
1076 if (has_junk)
1077 error (_("Garbage '%s' follows condition"), cond_string);
1078 }
1079
1080 /* See breakpoint.h. */
1081
1082 void
1083 notify_breakpoint_modified (breakpoint *b)
1084 {
1085 interps_notify_breakpoint_modified (b);
1086 gdb::observers::breakpoint_modified.notify (b);
1087 }
1088
1089 void
1090 set_breakpoint_condition (struct breakpoint *b, const char *exp,
1091 int from_tty, bool force)
1092 {
1093 if (*exp == 0)
1094 {
1095 b->cond_string.reset ();
1096
1097 if (is_watchpoint (b))
1098 gdb::checked_static_cast<watchpoint *> (b)->cond_exp.reset ();
1099 else
1100 {
1101 int loc_num = 1;
1102 for (bp_location &loc : b->locations ())
1103 {
1104 loc.cond.reset ();
1105 if (loc.disabled_by_cond && loc.enabled)
1106 gdb_printf (_("Breakpoint %d's condition is now valid at "
1107 "location %d, enabling.\n"),
1108 b->number, loc_num);
1109 loc.disabled_by_cond = false;
1110 loc_num++;
1111
1112 /* No need to free the condition agent expression
1113 bytecode (if we have one). We will handle this
1114 when we go through update_global_location_list. */
1115 }
1116 }
1117
1118 if (from_tty)
1119 gdb_printf (_("Breakpoint %d now unconditional.\n"), b->number);
1120 }
1121 else
1122 {
1123 if (is_watchpoint (b))
1124 {
1125 innermost_block_tracker tracker;
1126 const char *arg = exp;
1127 expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
1128 if (*arg != 0)
1129 error (_("Junk at end of expression"));
1130 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
1131 w->cond_exp = std::move (new_exp);
1132 w->cond_exp_valid_block = tracker.block ();
1133 }
1134 else
1135 {
1136 /* Parse and set condition expressions. We make two passes.
1137 In the first, we parse the condition string to see if it
1138 is valid in at least one location. If so, the condition
1139 would be accepted. So we go ahead and set the locations'
1140 conditions. In case no valid case is found, we throw
1141 the error and the condition string will be rejected.
1142 This two-pass approach is taken to avoid setting the
1143 state of locations in case of a reject. */
1144 for (const bp_location &loc : b->locations ())
1145 {
1146 try
1147 {
1148 const char *arg = exp;
1149 parse_exp_1 (&arg, loc.address,
1150 block_for_pc (loc.address), 0);
1151 if (*arg != 0)
1152 error (_("Junk at end of expression"));
1153 break;
1154 }
1155 catch (const gdb_exception_error &e)
1156 {
1157 /* Condition string is invalid. If this happens to
1158 be the last loc, abandon (if not forced) or continue
1159 (if forced). */
1160 if (&loc == &b->last_loc () && !force)
1161 throw;
1162 }
1163 }
1164
1165 /* If we reach here, the condition is valid at some locations. */
1166 int loc_num = 1;
1167 for (bp_location &loc : b->locations ())
1168 {
1169 set_breakpoint_location_condition (exp, &loc, b->number, loc_num);
1170 loc_num++;
1171 }
1172 }
1173
1174 /* We know that the new condition parsed successfully. The
1175 condition string of the breakpoint can be safely updated. */
1176 b->cond_string = make_unique_xstrdup (exp);
1177 b->condition_not_parsed = 0;
1178 }
1179 mark_breakpoint_modified (b);
1180
1181 notify_breakpoint_modified (b);
1182 }
1183
1184 /* See breakpoint.h. */
1185
1186 void
1187 set_breakpoint_condition (int bpnum, const char *exp, int from_tty,
1188 bool force)
1189 {
1190 for (breakpoint &b : all_breakpoints ())
1191 if (b.number == bpnum)
1192 {
1193 /* Check if this breakpoint has a "stop" method implemented in an
1194 extension language. This method and conditions entered into GDB
1195 from the CLI are mutually exclusive. */
1196 const struct extension_language_defn *extlang
1197 = get_breakpoint_cond_ext_lang (&b, EXT_LANG_NONE);
1198
1199 if (extlang != NULL)
1200 {
1201 error (_("Only one stop condition allowed. There is currently"
1202 " a %s stop condition defined for this breakpoint."),
1203 ext_lang_capitalized_name (extlang));
1204 }
1205 set_breakpoint_condition (&b, exp, from_tty, force);
1206
1207 if (is_breakpoint (&b))
1208 update_global_location_list (UGLL_MAY_INSERT);
1209
1210 return;
1211 }
1212
1213 error (_("No breakpoint number %d."), bpnum);
1214 }
1215
1216 /* The options for the "condition" command. */
1217
1218 struct condition_command_opts
1219 {
1220 /* For "-force". */
1221 bool force_condition = false;
1222 };
1223
1224 static const gdb::option::option_def condition_command_option_defs[] = {
1225
1226 gdb::option::flag_option_def<condition_command_opts> {
1227 "force",
1228 [] (condition_command_opts *opts) { return &opts->force_condition; },
1229 N_("Set the condition even if it is invalid for all current locations."),
1230 },
1231
1232 };
1233
1234 /* Create an option_def_group for the "condition" options, with
1235 CC_OPTS as context. */
1236
1237 static inline gdb::option::option_def_group
1238 make_condition_command_options_def_group (condition_command_opts *cc_opts)
1239 {
1240 return {{condition_command_option_defs}, cc_opts};
1241 }
1242
1243 /* Completion for the "condition" command. */
1244
1245 static void
1246 condition_completer (struct cmd_list_element *cmd,
1247 completion_tracker &tracker,
1248 const char *text, const char * /*word*/)
1249 {
1250 bool has_no_arguments = (*text == '\0');
1251 condition_command_opts cc_opts;
1252 const auto group = make_condition_command_options_def_group (&cc_opts);
1253 if (gdb::option::complete_options
1254 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1255 return;
1256
1257 text = skip_spaces (text);
1258 const char *space = skip_to_space (text);
1259 if (*space == '\0')
1260 {
1261 int len;
1262
1263 if (text[0] == '$')
1264 {
1265 tracker.advance_custom_word_point_by (1);
1266 /* We don't support completion of history indices. */
1267 if (!isdigit (text[1]))
1268 complete_internalvar (tracker, &text[1]);
1269 return;
1270 }
1271
1272 /* Suggest the "-force" flag if no arguments are given. If
1273 arguments were passed, they either already include the flag,
1274 or we are beyond the point of suggesting it because it's
1275 positionally the first argument. */
1276 if (has_no_arguments)
1277 gdb::option::complete_on_all_options (tracker, group);
1278
1279 /* We're completing the breakpoint number. */
1280 len = strlen (text);
1281
1282 for (breakpoint &b : all_breakpoints ())
1283 {
1284 char number[50];
1285
1286 xsnprintf (number, sizeof (number), "%d", b.number);
1287
1288 if (strncmp (number, text, len) == 0)
1289 tracker.add_completion (make_unique_xstrdup (number));
1290 }
1291
1292 return;
1293 }
1294
1295 /* We're completing the expression part. Skip the breakpoint num. */
1296 const char *exp_start = skip_spaces (space);
1297 tracker.advance_custom_word_point_by (exp_start - text);
1298 text = exp_start;
1299 const char *word = advance_to_expression_complete_word_point (tracker, text);
1300 expression_completer (cmd, tracker, text, word);
1301 }
1302
1303 /* condition N EXP -- set break condition of breakpoint N to EXP. */
1304
1305 static void
1306 condition_command (const char *arg, int from_tty)
1307 {
1308 const char *p;
1309 int bnum;
1310
1311 if (arg == 0)
1312 error_no_arg (_("breakpoint number"));
1313
1314 p = arg;
1315
1316 /* Check if the "-force" flag was passed. */
1317 condition_command_opts cc_opts;
1318 const auto group = make_condition_command_options_def_group (&cc_opts);
1319 gdb::option::process_options
1320 (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1321
1322 bnum = get_number (&p);
1323 if (bnum == 0)
1324 error (_("Bad breakpoint argument: '%s'"), arg);
1325
1326 set_breakpoint_condition (bnum, p, from_tty, cc_opts.force_condition);
1327 }
1328
1329 /* Check that COMMAND do not contain commands that are suitable
1330 only for tracepoints and not suitable for ordinary breakpoints.
1331 Throw if any such commands is found. */
1332
1333 static void
1334 check_no_tracepoint_commands (struct command_line *commands)
1335 {
1336 struct command_line *c;
1337
1338 for (c = commands; c; c = c->next)
1339 {
1340 if (c->control_type == while_stepping_control)
1341 error (_("The 'while-stepping' command can "
1342 "only be used for tracepoints"));
1343
1344 check_no_tracepoint_commands (c->body_list_0.get ());
1345 check_no_tracepoint_commands (c->body_list_1.get ());
1346
1347 /* Not that command parsing removes leading whitespace and comment
1348 lines and also empty lines. So, we only need to check for
1349 command directly. */
1350 if (strstr (c->line, "collect ") == c->line)
1351 error (_("The 'collect' command can only be used for tracepoints"));
1352
1353 if (strstr (c->line, "teval ") == c->line)
1354 error (_("The 'teval' command can only be used for tracepoints"));
1355 }
1356 }
1357
1358 struct longjmp_breakpoint : public momentary_breakpoint
1359 {
1360 using momentary_breakpoint::momentary_breakpoint;
1361
1362 ~longjmp_breakpoint () override;
1363 };
1364
1365 /* Encapsulate tests for different types of tracepoints. */
1366
1367 static bool
1368 is_tracepoint_type (bptype type)
1369 {
1370 return (type == bp_tracepoint
1371 || type == bp_fast_tracepoint
1372 || type == bp_static_tracepoint
1373 || type == bp_static_marker_tracepoint);
1374 }
1375
1376 /* See breakpoint.h. */
1377
1378 bool
1379 is_tracepoint (const struct breakpoint *b)
1380 {
1381 return is_tracepoint_type (b->type);
1382 }
1383
1384 /* Factory function to create an appropriate instance of breakpoint given
1385 TYPE. */
1386
1387 template<typename... Arg>
1388 static std::unique_ptr<code_breakpoint>
1389 new_breakpoint_from_type (struct gdbarch *gdbarch, bptype type,
1390 Arg&&... args)
1391 {
1392 code_breakpoint *b;
1393
1394 switch (type)
1395 {
1396 case bp_breakpoint:
1397 case bp_hardware_breakpoint:
1398 b = new ordinary_breakpoint (gdbarch, type,
1399 std::forward<Arg> (args)...);
1400 break;
1401
1402 case bp_fast_tracepoint:
1403 case bp_static_tracepoint:
1404 case bp_tracepoint:
1405 b = new tracepoint (gdbarch, type,
1406 std::forward<Arg> (args)...);
1407 break;
1408
1409 case bp_static_marker_tracepoint:
1410 b = new static_marker_tracepoint (gdbarch, type,
1411 std::forward<Arg> (args)...);
1412 break;
1413
1414 case bp_dprintf:
1415 b = new dprintf_breakpoint (gdbarch, type,
1416 std::forward<Arg> (args)...);
1417 break;
1418
1419 default:
1420 gdb_assert_not_reached ("invalid type");
1421 }
1422
1423 return std::unique_ptr<code_breakpoint> (b);
1424 }
1425
1426 /* A helper function that validates that COMMANDS are valid for a
1427 breakpoint. This function will throw an exception if a problem is
1428 found. */
1429
1430 static void
1431 validate_commands_for_breakpoint (struct breakpoint *b,
1432 struct command_line *commands)
1433 {
1434 if (is_tracepoint (b))
1435 {
1436 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
1437 struct command_line *c;
1438 struct command_line *while_stepping = 0;
1439
1440 /* Reset the while-stepping step count. The previous commands
1441 might have included a while-stepping action, while the new
1442 ones might not. */
1443 t->step_count = 0;
1444
1445 /* We need to verify that each top-level element of commands is
1446 valid for tracepoints, that there's at most one
1447 while-stepping element, and that the while-stepping's body
1448 has valid tracing commands excluding nested while-stepping.
1449 We also need to validate the tracepoint action line in the
1450 context of the tracepoint --- validate_actionline actually
1451 has side effects, like setting the tracepoint's
1452 while-stepping STEP_COUNT, in addition to checking if the
1453 collect/teval actions parse and make sense in the
1454 tracepoint's context. */
1455 for (c = commands; c; c = c->next)
1456 {
1457 if (c->control_type == while_stepping_control)
1458 {
1459 if (b->type == bp_fast_tracepoint)
1460 error (_("The 'while-stepping' command "
1461 "cannot be used for fast tracepoint"));
1462 else if (b->type == bp_static_tracepoint
1463 || b->type == bp_static_marker_tracepoint)
1464 error (_("The 'while-stepping' command "
1465 "cannot be used for static tracepoint"));
1466
1467 if (while_stepping)
1468 error (_("The 'while-stepping' command "
1469 "can be used only once"));
1470 else
1471 while_stepping = c;
1472 }
1473
1474 validate_actionline (c->line, t);
1475 }
1476 if (while_stepping)
1477 {
1478 struct command_line *c2;
1479
1480 gdb_assert (while_stepping->body_list_1 == nullptr);
1481 c2 = while_stepping->body_list_0.get ();
1482 for (; c2; c2 = c2->next)
1483 {
1484 if (c2->control_type == while_stepping_control)
1485 error (_("The 'while-stepping' command cannot be nested"));
1486 }
1487 }
1488 }
1489 else
1490 {
1491 check_no_tracepoint_commands (commands);
1492 }
1493 }
1494
1495 /* Return a vector of all the static tracepoints set at ADDR. The
1496 caller is responsible for releasing the vector. */
1497
1498 std::vector<breakpoint *>
1499 static_tracepoints_here (CORE_ADDR addr)
1500 {
1501 std::vector<breakpoint *> found;
1502
1503 for (breakpoint &b : all_breakpoints ())
1504 if (b.type == bp_static_tracepoint
1505 || b.type == bp_static_marker_tracepoint)
1506 {
1507 for (bp_location &loc : b.locations ())
1508 if (loc.address == addr)
1509 found.push_back (&b);
1510 }
1511
1512 return found;
1513 }
1514
1515 /* Set the command list of B to COMMANDS. If breakpoint is tracepoint,
1516 validate that only allowed commands are included. */
1517
1518 void
1519 breakpoint_set_commands (struct breakpoint *b,
1520 counted_command_line &&commands)
1521 {
1522 validate_commands_for_breakpoint (b, commands.get ());
1523
1524 b->commands = std::move (commands);
1525 notify_breakpoint_modified (b);
1526 }
1527
1528 /* Set the internal `silent' flag on the breakpoint. Note that this
1529 is not the same as the "silent" that may appear in the breakpoint's
1530 commands. */
1531
1532 void
1533 breakpoint_set_silent (struct breakpoint *b, int silent)
1534 {
1535 int old_silent = b->silent;
1536
1537 b->silent = silent;
1538 if (old_silent != silent)
1539 notify_breakpoint_modified (b);
1540 }
1541
1542 /* See breakpoint.h. */
1543
1544 void
1545 breakpoint_set_thread (struct breakpoint *b, int thread)
1546 {
1547 /* THREAD should be -1, meaning no thread restriction, or it should be a
1548 valid global thread-id, which are greater than zero. */
1549 gdb_assert (thread == -1 || thread > 0);
1550
1551 /* It is not valid to set a thread restriction for a breakpoint that
1552 already has task or inferior restriction. */
1553 gdb_assert (thread == -1 || (b->task == -1 && b->inferior == -1));
1554
1555 int old_thread = b->thread;
1556 b->thread = thread;
1557 if (old_thread != thread)
1558 notify_breakpoint_modified (b);
1559 }
1560
1561 /* See breakpoint.h. */
1562
1563 void
1564 breakpoint_set_inferior (struct breakpoint *b, int inferior)
1565 {
1566 /* INFERIOR should be -1, meaning no inferior restriction, or it should
1567 be a valid inferior number, which are greater than zero. */
1568 gdb_assert (inferior == -1 || inferior > 0);
1569
1570 /* It is not valid to set an inferior restriction for a breakpoint that
1571 already has a task or thread restriction. */
1572 gdb_assert (inferior == -1 || (b->task == -1 && b->thread == -1));
1573
1574 int old_inferior = b->inferior;
1575 b->inferior = inferior;
1576 if (old_inferior != inferior)
1577 notify_breakpoint_modified (b);
1578 }
1579
1580 /* See breakpoint.h. */
1581
1582 void
1583 breakpoint_set_task (struct breakpoint *b, int task)
1584 {
1585 /* TASK should be -1, meaning no task restriction, or it should be a
1586 valid task-id, which are greater than zero. */
1587 gdb_assert (task == -1 || task > 0);
1588
1589 /* It is not valid to set a task restriction for a breakpoint that
1590 already has a thread or inferior restriction. */
1591 gdb_assert (task == -1 || (b->thread == -1 && b->inferior == -1));
1592
1593 int old_task = b->task;
1594 b->task = task;
1595 if (old_task != task)
1596 notify_breakpoint_modified (b);
1597 }
1598
1599 static void
1600 commands_command_1 (const char *arg, int from_tty,
1601 struct command_line *control)
1602 {
1603 counted_command_line cmd;
1604 /* cmd_read will be true once we have read cmd. Note that cmd might still be
1605 NULL after the call to read_command_lines if the user provides an empty
1606 list of command by just typing "end". */
1607 bool cmd_read = false;
1608
1609 std::string new_arg;
1610
1611 if (arg == NULL || !*arg)
1612 {
1613 /* Argument not explicitly given. Synthesize it. */
1614 if (breakpoint_count - prev_breakpoint_count > 1)
1615 new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1616 breakpoint_count);
1617 else if (breakpoint_count > 0)
1618 new_arg = string_printf ("%d", breakpoint_count);
1619 }
1620 else
1621 {
1622 /* Create a copy of ARG. This is needed because the "commands"
1623 command may be coming from a script. In that case, the read
1624 line buffer is going to be overwritten in the lambda of
1625 'map_breakpoint_numbers' below when reading the next line
1626 before we are are done parsing the breakpoint numbers. */
1627 new_arg = arg;
1628 }
1629 arg = new_arg.c_str ();
1630
1631 map_breakpoint_numbers
1632 (arg, [&] (breakpoint *b)
1633 {
1634 if (!cmd_read)
1635 {
1636 gdb_assert (cmd == NULL);
1637 if (control != NULL)
1638 cmd = control->body_list_0;
1639 else
1640 {
1641 std::string str
1642 = string_printf (_("Type commands for breakpoint(s) "
1643 "%s, one per line."),
1644 arg);
1645
1646 auto do_validate = [=] (const char *line)
1647 {
1648 tracepoint *t
1649 = gdb::checked_static_cast<tracepoint *> (b);
1650 validate_actionline (line, t);
1651 };
1652 gdb::function_view<void (const char *)> validator;
1653 if (is_tracepoint (b))
1654 validator = do_validate;
1655
1656 cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1657 }
1658 cmd_read = true;
1659 }
1660
1661 /* If a breakpoint was on the list more than once, we don't need to
1662 do anything. */
1663 if (b->commands != cmd)
1664 {
1665 validate_commands_for_breakpoint (b, cmd.get ());
1666 b->commands = cmd;
1667 notify_breakpoint_modified (b);
1668 }
1669 });
1670 }
1671
1672 static void
1673 commands_command (const char *arg, int from_tty)
1674 {
1675 commands_command_1 (arg, from_tty, NULL);
1676 }
1677
1678 /* Like commands_command, but instead of reading the commands from
1679 input stream, takes them from an already parsed command structure.
1680
1681 This is used by cli-script.c to DTRT with breakpoint commands
1682 that are part of if and while bodies. */
1683 enum command_control_type
1684 commands_from_control_command (const char *arg, struct command_line *cmd)
1685 {
1686 commands_command_1 (arg, 0, cmd);
1687 return simple_control;
1688 }
1689
1690 /* Return true if BL->TARGET_INFO contains valid information. */
1691
1692 static bool
1693 bp_location_has_shadow (struct bp_location *bl)
1694 {
1695 if (bl->loc_type != bp_loc_software_breakpoint)
1696 return false;
1697 if (!bl->inserted)
1698 return false;
1699 if (bl->target_info.shadow_len == 0)
1700 /* BL isn't valid, or doesn't shadow memory. */
1701 return false;
1702 return true;
1703 }
1704
1705 /* Update BUF, which is LEN bytes read from the target address
1706 MEMADDR, by replacing a memory breakpoint with its shadowed
1707 contents.
1708
1709 If READBUF is not NULL, this buffer must not overlap with the of
1710 the breakpoint location's shadow_contents buffer. Otherwise, a
1711 failed assertion internal error will be raised. */
1712
1713 static void
1714 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1715 const gdb_byte *writebuf_org,
1716 ULONGEST memaddr, LONGEST len,
1717 struct bp_target_info *target_info,
1718 struct gdbarch *gdbarch)
1719 {
1720 /* Now do full processing of the found relevant range of elements. */
1721 CORE_ADDR bp_addr = 0;
1722 int bp_size = 0;
1723 int bptoffset = 0;
1724
1725 if (!breakpoint_address_match (target_info->placed_address_space, 0,
1726 current_program_space->aspace.get (), 0))
1727 {
1728 /* The breakpoint is inserted in a different address space. */
1729 return;
1730 }
1731
1732 /* Addresses and length of the part of the breakpoint that
1733 we need to copy. */
1734 bp_addr = target_info->placed_address;
1735 bp_size = target_info->shadow_len;
1736
1737 if (bp_addr + bp_size <= memaddr)
1738 {
1739 /* The breakpoint is entirely before the chunk of memory we are
1740 reading. */
1741 return;
1742 }
1743
1744 if (bp_addr >= memaddr + len)
1745 {
1746 /* The breakpoint is entirely after the chunk of memory we are
1747 reading. */
1748 return;
1749 }
1750
1751 /* Offset within shadow_contents. */
1752 if (bp_addr < memaddr)
1753 {
1754 /* Only copy the second part of the breakpoint. */
1755 bp_size -= memaddr - bp_addr;
1756 bptoffset = memaddr - bp_addr;
1757 bp_addr = memaddr;
1758 }
1759
1760 if (bp_addr + bp_size > memaddr + len)
1761 {
1762 /* Only copy the first part of the breakpoint. */
1763 bp_size -= (bp_addr + bp_size) - (memaddr + len);
1764 }
1765
1766 if (readbuf != NULL)
1767 {
1768 /* Verify that the readbuf buffer does not overlap with the
1769 shadow_contents buffer. */
1770 gdb_assert (target_info->shadow_contents >= readbuf + len
1771 || readbuf >= (target_info->shadow_contents
1772 + target_info->shadow_len));
1773
1774 /* Update the read buffer with this inserted breakpoint's
1775 shadow. */
1776 memcpy (readbuf + bp_addr - memaddr,
1777 target_info->shadow_contents + bptoffset, bp_size);
1778 }
1779 else
1780 {
1781 const unsigned char *bp;
1782 CORE_ADDR addr = target_info->reqstd_address;
1783 int placed_size;
1784
1785 /* Update the shadow with what we want to write to memory. */
1786 memcpy (target_info->shadow_contents + bptoffset,
1787 writebuf_org + bp_addr - memaddr, bp_size);
1788
1789 /* Determine appropriate breakpoint contents and size for this
1790 address. */
1791 bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1792
1793 /* Update the final write buffer with this inserted
1794 breakpoint's INSN. */
1795 memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1796 }
1797 }
1798
1799 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1800 by replacing any memory breakpoints with their shadowed contents.
1801
1802 If READBUF is not NULL, this buffer must not overlap with any of
1803 the breakpoint location's shadow_contents buffers. Otherwise,
1804 a failed assertion internal error will be raised.
1805
1806 The range of shadowed area by each bp_location is:
1807 bl->address - bp_locations_placed_address_before_address_max
1808 up to bl->address + bp_locations_shadow_len_after_address_max
1809 The range we were requested to resolve shadows for is:
1810 memaddr ... memaddr + len
1811 Thus the safe cutoff boundaries for performance optimization are
1812 memaddr + len <= (bl->address
1813 - bp_locations_placed_address_before_address_max)
1814 and:
1815 bl->address + bp_locations_shadow_len_after_address_max <= memaddr */
1816
1817 void
1818 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1819 const gdb_byte *writebuf_org,
1820 ULONGEST memaddr, LONGEST len)
1821 {
1822 /* Left boundary, right boundary and median element of our binary
1823 search. */
1824 unsigned bc_l, bc_r, bc;
1825
1826 /* Find BC_L which is a leftmost element which may affect BUF
1827 content. It is safe to report lower value but a failure to
1828 report higher one. */
1829
1830 bc_l = 0;
1831 bc_r = bp_locations.size ();
1832 while (bc_l + 1 < bc_r)
1833 {
1834 struct bp_location *bl;
1835
1836 bc = (bc_l + bc_r) / 2;
1837 bl = bp_locations[bc];
1838
1839 /* Check first BL->ADDRESS will not overflow due to the added
1840 constant. Then advance the left boundary only if we are sure
1841 the BC element can in no way affect the BUF content (MEMADDR
1842 to MEMADDR + LEN range).
1843
1844 Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1845 offset so that we cannot miss a breakpoint with its shadow
1846 range tail still reaching MEMADDR. */
1847
1848 if ((bl->address + bp_locations_shadow_len_after_address_max
1849 >= bl->address)
1850 && (bl->address + bp_locations_shadow_len_after_address_max
1851 <= memaddr))
1852 bc_l = bc;
1853 else
1854 bc_r = bc;
1855 }
1856
1857 /* Due to the binary search above, we need to make sure we pick the
1858 first location that's at BC_L's address. E.g., if there are
1859 multiple locations at the same address, BC_L may end up pointing
1860 at a duplicate location, and miss the "master"/"inserted"
1861 location. Say, given locations L1, L2 and L3 at addresses A and
1862 B:
1863
1864 L1@A, L2@A, L3@B, ...
1865
1866 BC_L could end up pointing at location L2, while the "master"
1867 location could be L1. Since the `loc->inserted' flag is only set
1868 on "master" locations, we'd forget to restore the shadow of L1
1869 and L2. */
1870 while (bc_l > 0
1871 && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1872 bc_l--;
1873
1874 /* Now do full processing of the found relevant range of elements. */
1875
1876 for (bc = bc_l; bc < bp_locations.size (); bc++)
1877 {
1878 struct bp_location *bl = bp_locations[bc];
1879
1880 /* bp_location array has BL->OWNER always non-NULL. */
1881 if (bl->owner->type == bp_none)
1882 warning (_("reading through apparently deleted breakpoint #%d?"),
1883 bl->owner->number);
1884
1885 /* Performance optimization: any further element can no longer affect BUF
1886 content. */
1887
1888 if (bl->address >= bp_locations_placed_address_before_address_max
1889 && (memaddr + len
1890 <= (bl->address
1891 - bp_locations_placed_address_before_address_max)))
1892 break;
1893
1894 if (!bp_location_has_shadow (bl))
1895 continue;
1896
1897 one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1898 memaddr, len, &bl->target_info, bl->gdbarch);
1899 }
1900 }
1901
1902 /* See breakpoint.h. */
1903
1904 bool
1905 is_breakpoint (const struct breakpoint *bpt)
1906 {
1907 return (bpt->type == bp_breakpoint
1908 || bpt->type == bp_hardware_breakpoint
1909 || bpt->type == bp_dprintf);
1910 }
1911
1912 /* Return true if BPT is of any hardware watchpoint kind. */
1913
1914 static bool
1915 is_hardware_watchpoint (const struct breakpoint *bpt)
1916 {
1917 return (bpt->type == bp_hardware_watchpoint
1918 || bpt->type == bp_read_watchpoint
1919 || bpt->type == bp_access_watchpoint);
1920 }
1921
1922 /* See breakpoint.h. */
1923
1924 bool
1925 is_watchpoint (const struct breakpoint *bpt)
1926 {
1927 return (is_hardware_watchpoint (bpt)
1928 || bpt->type == bp_watchpoint);
1929 }
1930
1931 /* Returns true if the current thread and its running state are safe
1932 to evaluate or update watchpoint B. Watchpoints on local
1933 expressions need to be evaluated in the context of the thread that
1934 was current when the watchpoint was created, and, that thread needs
1935 to be stopped to be able to select the correct frame context.
1936 Watchpoints on global expressions can be evaluated on any thread,
1937 and in any state. It is presently left to the target allowing
1938 memory accesses when threads are running. */
1939
1940 static bool
1941 watchpoint_in_thread_scope (struct watchpoint *b)
1942 {
1943 return (b->pspace == current_program_space
1944 && (b->watchpoint_thread == null_ptid
1945 || (inferior_ptid == b->watchpoint_thread
1946 && !inferior_thread ()->executing ())));
1947 }
1948
1949 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1950 associated bp_watchpoint_scope breakpoint. */
1951
1952 static void
1953 watchpoint_del_at_next_stop (struct watchpoint *w)
1954 {
1955 if (w->related_breakpoint != w)
1956 {
1957 gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1958 gdb_assert (w->related_breakpoint->related_breakpoint == w);
1959 w->related_breakpoint->disposition = disp_del_at_next_stop;
1960 w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1961 w->related_breakpoint = w;
1962 }
1963 w->disposition = disp_del_at_next_stop;
1964 disable_breakpoint (w);
1965 }
1966
1967 /* Extract a bitfield value from value VAL using the bit parameters contained in
1968 watchpoint W. */
1969
1970 static struct value *
1971 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1972 {
1973 struct value *bit_val;
1974
1975 if (val == NULL)
1976 return NULL;
1977
1978 bit_val = value::allocate (val->type ());
1979
1980 val->unpack_bitfield (bit_val,
1981 w->val_bitpos,
1982 w->val_bitsize,
1983 val->contents_for_printing ().data (),
1984 val->offset ());
1985
1986 return bit_val;
1987 }
1988
1989 /* Allocate a dummy location and add it to B. This is required
1990 because bpstat_stop_status requires a location to be able to report
1991 stops. */
1992
1993 static void
1994 add_dummy_location (struct breakpoint *b,
1995 struct program_space *pspace)
1996 {
1997 gdb_assert (!b->has_locations ());
1998
1999 bp_location *loc = new bp_location (b, bp_loc_other);
2000 loc->pspace = pspace;
2001 b->add_location (*loc);
2002 }
2003
2004 /* Assuming that B is a watchpoint:
2005 - Reparse watchpoint expression, if REPARSE is true
2006 - Evaluate expression and store the result in B->val
2007 - Evaluate the condition if there is one, and store the result
2008 in b->loc->cond.
2009 - Update the list of values that must be watched in B->loc.
2010
2011 If the watchpoint disposition is disp_del_at_next_stop, then do
2012 nothing. If this is local watchpoint that is out of scope, delete
2013 it.
2014
2015 Even with `set breakpoint always-inserted on' the watchpoints are
2016 removed + inserted on each stop here. Normal breakpoints must
2017 never be removed because they might be missed by a running thread
2018 when debugging in non-stop mode. On the other hand, hardware
2019 watchpoints (is_hardware_watchpoint; processed here) are specific
2020 to each LWP since they are stored in each LWP's hardware debug
2021 registers. Therefore, such LWP must be stopped first in order to
2022 be able to modify its hardware watchpoints.
2023
2024 Hardware watchpoints must be reset exactly once after being
2025 presented to the user. It cannot be done sooner, because it would
2026 reset the data used to present the watchpoint hit to the user. And
2027 it must not be done later because it could display the same single
2028 watchpoint hit during multiple GDB stops. Note that the latter is
2029 relevant only to the hardware watchpoint types bp_read_watchpoint
2030 and bp_access_watchpoint. False hit by bp_hardware_watchpoint is
2031 not user-visible - its hit is suppressed if the memory content has
2032 not changed.
2033
2034 The following constraints influence the location where we can reset
2035 hardware watchpoints:
2036
2037 * target_stopped_by_watchpoint and target_stopped_data_address are
2038 called several times when GDB stops.
2039
2040 [linux]
2041 * Multiple hardware watchpoints can be hit at the same time,
2042 causing GDB to stop. GDB only presents one hardware watchpoint
2043 hit at a time as the reason for stopping, and all the other hits
2044 are presented later, one after the other, each time the user
2045 requests the execution to be resumed. Execution is not resumed
2046 for the threads still having pending hit event stored in
2047 LWP_INFO->STATUS. While the watchpoint is already removed from
2048 the inferior on the first stop the thread hit event is kept being
2049 reported from its cached value by linux_nat_stopped_data_address
2050 until the real thread resume happens after the watchpoint gets
2051 presented and thus its LWP_INFO->STATUS gets reset.
2052
2053 Therefore the hardware watchpoint hit can get safely reset on the
2054 watchpoint removal from inferior. */
2055
2056 static void
2057 update_watchpoint (struct watchpoint *b, bool reparse)
2058 {
2059 bool within_current_scope;
2060
2061 /* If this is a local watchpoint, we only want to check if the
2062 watchpoint frame is in scope if the current thread is the thread
2063 that was used to create the watchpoint. */
2064 if (!watchpoint_in_thread_scope (b))
2065 return;
2066
2067 if (b->disposition == disp_del_at_next_stop)
2068 return;
2069
2070 std::optional<scoped_restore_selected_frame> restore_frame;
2071
2072 /* Determine if the watchpoint is within scope. */
2073 if (b->exp_valid_block == NULL)
2074 within_current_scope = true;
2075 else
2076 {
2077 frame_info_ptr fi = get_current_frame ();
2078 struct gdbarch *frame_arch = get_frame_arch (fi);
2079 CORE_ADDR frame_pc = get_frame_pc (fi);
2080
2081 /* If we're at a point where the stack has been destroyed
2082 (e.g. in a function epilogue), unwinding may not work
2083 properly. Do not attempt to recreate locations at this
2084 point. See similar comments in watchpoint_check. */
2085 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
2086 return;
2087
2088 /* Save the current frame's ID so we can restore it after
2089 evaluating the watchpoint expression on its own frame. */
2090 /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
2091 took a frame parameter, so that we didn't have to change the
2092 selected frame. */
2093 restore_frame.emplace ();
2094
2095 fi = frame_find_by_id (b->watchpoint_frame);
2096 within_current_scope = (fi != NULL);
2097 if (within_current_scope)
2098 select_frame (fi);
2099 }
2100
2101 /* We don't free locations. They are stored in the bp_location array
2102 and update_global_location_list will eventually delete them and
2103 remove breakpoints if needed. */
2104 b->clear_locations ();
2105
2106 if (within_current_scope && reparse)
2107 {
2108 const char *s;
2109
2110 b->exp.reset ();
2111 s = (b->exp_string_reparse
2112 ? b->exp_string_reparse.get ()
2113 : b->exp_string.get ());
2114 b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
2115 /* If the meaning of expression itself changed, the old value is
2116 no longer relevant. We don't want to report a watchpoint hit
2117 to the user when the old value and the new value may actually
2118 be completely different objects. */
2119 b->val = NULL;
2120 b->val_valid = false;
2121
2122 /* Note that unlike with breakpoints, the watchpoint's condition
2123 expression is stored in the breakpoint object, not in the
2124 locations (re)created below. */
2125 if (b->cond_string != NULL)
2126 {
2127 b->cond_exp.reset ();
2128
2129 s = b->cond_string.get ();
2130 b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
2131 }
2132 }
2133
2134 /* If we failed to parse the expression, for example because
2135 it refers to a global variable in a not-yet-loaded shared library,
2136 don't try to insert watchpoint. We don't automatically delete
2137 such watchpoint, though, since failure to parse expression
2138 is different from out-of-scope watchpoint. */
2139 if (!target_has_execution ())
2140 {
2141 /* Without execution, memory can't change. No use to try and
2142 set watchpoint locations. The watchpoint will be reset when
2143 the target gains execution, through breakpoint_re_set. */
2144 if (!can_use_hw_watchpoints)
2145 {
2146 if (b->works_in_software_mode ())
2147 b->type = bp_watchpoint;
2148 else
2149 error (_("Can't set read/access watchpoint when "
2150 "hardware watchpoints are disabled."));
2151 }
2152 }
2153 else if (within_current_scope && b->exp)
2154 {
2155 std::vector<value_ref_ptr> val_chain;
2156 struct value *v, *result;
2157 struct program_space *frame_pspace;
2158
2159 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &v, &result,
2160 &val_chain, false);
2161
2162 /* Avoid setting b->val if it's already set. The meaning of
2163 b->val is 'the last value' user saw, and we should update
2164 it only if we reported that last value to user. As it
2165 happens, the code that reports it updates b->val directly.
2166 We don't keep track of the memory value for masked
2167 watchpoints. */
2168 if (!b->val_valid && !is_masked_watchpoint (b))
2169 {
2170 if (b->val_bitsize != 0)
2171 v = extract_bitfield_from_watchpoint_value (b, v);
2172 b->val = release_value (v);
2173 b->val_valid = true;
2174 }
2175
2176 frame_pspace = get_frame_program_space (get_selected_frame (NULL));
2177
2178 /* Look at each value on the value chain. */
2179 gdb_assert (!val_chain.empty ());
2180 for (const value_ref_ptr &iter : val_chain)
2181 {
2182 v = iter.get ();
2183
2184 /* If it's a memory location, and GDB actually needed
2185 its contents to evaluate the expression, then we
2186 must watch it. If the first value returned is
2187 still lazy, that means an error occurred reading it;
2188 watch it anyway in case it becomes readable. */
2189 if (v->lval () == lval_memory
2190 && (v == val_chain[0] || ! v->lazy ()))
2191 {
2192 struct type *vtype = check_typedef (v->type ());
2193
2194 /* We only watch structs and arrays if user asked
2195 for it explicitly, never if they just happen to
2196 appear in the middle of some value chain. */
2197 if (v == result
2198 || (vtype->code () != TYPE_CODE_STRUCT
2199 && vtype->code () != TYPE_CODE_ARRAY))
2200 {
2201 CORE_ADDR addr;
2202 enum target_hw_bp_type type;
2203 int bitpos = 0, bitsize = 0;
2204
2205 if (v->bitsize () != 0)
2206 {
2207 /* Extract the bit parameters out from the bitfield
2208 sub-expression. */
2209 bitpos = v->bitpos ();
2210 bitsize = v->bitsize ();
2211 }
2212 else if (v == result && b->val_bitsize != 0)
2213 {
2214 /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2215 lvalue whose bit parameters are saved in the fields
2216 VAL_BITPOS and VAL_BITSIZE. */
2217 bitpos = b->val_bitpos;
2218 bitsize = b->val_bitsize;
2219 }
2220
2221 addr = v->address ();
2222 if (bitsize != 0)
2223 {
2224 /* Skip the bytes that don't contain the bitfield. */
2225 addr += bitpos / 8;
2226 }
2227
2228 type = hw_write;
2229 if (b->type == bp_read_watchpoint)
2230 type = hw_read;
2231 else if (b->type == bp_access_watchpoint)
2232 type = hw_access;
2233
2234 bp_location *loc = b->allocate_location ();
2235 loc->gdbarch = v->type ()->arch ();
2236 loc->pspace = frame_pspace;
2237 loc->address
2238 = gdbarch_remove_non_address_bits (loc->gdbarch, addr);
2239 b->add_location (*loc);
2240
2241 if (bitsize != 0)
2242 {
2243 /* Just cover the bytes that make up the bitfield. */
2244 loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2245 }
2246 else
2247 loc->length = v->type ()->length ();
2248
2249 loc->watchpoint_type = type;
2250 }
2251 }
2252 }
2253
2254 /* Helper function to bundle possibly emitting a warning along with
2255 changing the type of B to bp_watchpoint. */
2256 auto change_type_to_bp_watchpoint = [] (breakpoint *bp)
2257 {
2258 /* Only warn for breakpoints that have been assigned a +ve number,
2259 anything else is either an internal watchpoint (which we don't
2260 currently create) or has not yet been finalized, in which case
2261 this change of type will be occurring before the user is told
2262 the type of this watchpoint. */
2263 if (bp->type == bp_hardware_watchpoint && bp->number > 0)
2264 warning (_("watchpoint %d downgraded to software watchpoint"),
2265 bp->number);
2266 bp->type = bp_watchpoint;
2267 };
2268
2269 /* Change the type of breakpoint between hardware assisted or
2270 an ordinary watchpoint depending on the hardware support and
2271 free hardware slots. Recheck the number of free hardware slots
2272 as the value chain may have changed. */
2273 {
2274 int reg_cnt;
2275 enum bp_loc_type loc_type;
2276
2277 reg_cnt = can_use_hardware_watchpoint (val_chain);
2278
2279 if (reg_cnt)
2280 {
2281 int i, target_resources_ok, other_type_used;
2282 enum bptype type;
2283
2284 /* Use an exact watchpoint when there's only one memory region to be
2285 watched, and only one debug register is needed to watch it. */
2286 b->exact = target_exact_watchpoints && reg_cnt == 1;
2287
2288 /* We need to determine how many resources are already
2289 used for all other hardware watchpoints plus this one
2290 to see if we still have enough resources to also fit
2291 this watchpoint in as well. */
2292
2293 /* If this is a software watchpoint, we try to turn it
2294 to a hardware one -- count resources as if B was of
2295 hardware watchpoint type. */
2296 type = b->type;
2297 if (type == bp_watchpoint)
2298 type = bp_hardware_watchpoint;
2299
2300 /* This watchpoint may or may not have been placed on
2301 the list yet at this point (it won't be in the list
2302 if we're trying to create it for the first time,
2303 through watch_command), so always account for it
2304 manually. */
2305
2306 /* Count resources used by all watchpoints except B. */
2307 i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2308
2309 /* Add in the resources needed for B. */
2310 i += hw_watchpoint_use_count (b);
2311
2312 target_resources_ok
2313 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2314 if (target_resources_ok <= 0)
2315 {
2316 bool sw_mode = b->works_in_software_mode ();
2317
2318 if (target_resources_ok == 0 && !sw_mode)
2319 error (_("Target does not support this type of "
2320 "hardware watchpoint."));
2321 else if (target_resources_ok < 0 && !sw_mode)
2322 error (_("There are not enough available hardware "
2323 "resources for this watchpoint."));
2324
2325 /* Downgrade to software watchpoint. */
2326 change_type_to_bp_watchpoint (b);
2327 }
2328 else
2329 {
2330 /* If this was a software watchpoint, we've just
2331 found we have enough resources to turn it to a
2332 hardware watchpoint. Otherwise, this is a
2333 nop. */
2334 b->type = type;
2335 }
2336 }
2337 else if (!b->works_in_software_mode ())
2338 {
2339 if (!can_use_hw_watchpoints)
2340 error (_("Can't set read/access watchpoint when "
2341 "hardware watchpoints are disabled."));
2342 else
2343 error (_("Expression cannot be implemented with "
2344 "read/access watchpoint."));
2345 }
2346 else
2347 change_type_to_bp_watchpoint (b);
2348
2349 loc_type = (b->type == bp_watchpoint? bp_loc_software_watchpoint
2350 : bp_loc_hardware_watchpoint);
2351
2352 for (bp_location &bl : b->locations ())
2353 bl.loc_type = loc_type;
2354 }
2355
2356 /* If a software watchpoint is not watching any memory, then the
2357 above left it without any location set up. But,
2358 bpstat_stop_status requires a location to be able to report
2359 stops, so make sure there's at least a dummy one. */
2360 if (b->type == bp_watchpoint && !b->has_locations ())
2361 add_dummy_location (b, frame_pspace);
2362 }
2363 else if (!within_current_scope)
2364 {
2365 gdb_printf (_("\
2366 Watchpoint %d deleted because the program has left the block\n\
2367 in which its expression is valid.\n"),
2368 b->number);
2369 watchpoint_del_at_next_stop (b);
2370 }
2371 }
2372
2373 /* Returns true iff breakpoint location should be
2374 inserted in the inferior. We don't differentiate the type of BL's owner
2375 (breakpoint vs. tracepoint), although insert_location in tracepoint's
2376 breakpoint_ops is not defined, because in insert_bp_location,
2377 tracepoint's insert_location will not be called. */
2378
2379 static bool
2380 should_be_inserted (struct bp_location *bl)
2381 {
2382 if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2383 return false;
2384
2385 if (bl->owner->disposition == disp_del_at_next_stop)
2386 return false;
2387
2388 if (!bl->enabled || bl->disabled_by_cond
2389 || bl->shlib_disabled || bl->duplicate)
2390 return false;
2391
2392 if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2393 return false;
2394
2395 /* This is set for example, when we're attached to the parent of a
2396 vfork, and have detached from the child. The child is running
2397 free, and we expect it to do an exec or exit, at which point the
2398 OS makes the parent schedulable again (and the target reports
2399 that the vfork is done). Until the child is done with the shared
2400 memory region, do not insert breakpoints in the parent, otherwise
2401 the child could still trip on the parent's breakpoints. Since
2402 the parent is blocked anyway, it won't miss any breakpoint. */
2403 if (bl->pspace->breakpoints_not_allowed)
2404 return false;
2405
2406 /* Don't insert a breakpoint if we're trying to step past its
2407 location, except if the breakpoint is a single-step breakpoint,
2408 and the breakpoint's thread is the thread which is stepping past
2409 a breakpoint. */
2410 if ((bl->loc_type == bp_loc_software_breakpoint
2411 || bl->loc_type == bp_loc_hardware_breakpoint)
2412 && stepping_past_instruction_at (bl->pspace->aspace.get (),
2413 bl->address)
2414 /* The single-step breakpoint may be inserted at the location
2415 we're trying to step if the instruction branches to itself.
2416 However, the instruction won't be executed at all and it may
2417 break the semantics of the instruction, for example, the
2418 instruction is a conditional branch or updates some flags.
2419 We can't fix it unless GDB is able to emulate the instruction
2420 or switch to displaced stepping. */
2421 && !(bl->owner->type == bp_single_step
2422 && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2423 {
2424 infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2425 paddress (bl->gdbarch, bl->address));
2426 return false;
2427 }
2428
2429 /* Don't insert watchpoints if we're trying to step past the
2430 instruction that triggered one. */
2431 if ((bl->loc_type == bp_loc_hardware_watchpoint)
2432 && stepping_past_nonsteppable_watchpoint ())
2433 {
2434 infrun_debug_printf ("stepping past non-steppable watchpoint. "
2435 "skipping watchpoint at %s:%d",
2436 paddress (bl->gdbarch, bl->address), bl->length);
2437 return false;
2438 }
2439
2440 return true;
2441 }
2442
2443 /* Same as should_be_inserted but does the check assuming
2444 that the location is not duplicated. */
2445
2446 static bool
2447 unduplicated_should_be_inserted (struct bp_location *bl)
2448 {
2449 scoped_restore restore_bl_duplicate
2450 = make_scoped_restore (&bl->duplicate, 0);
2451
2452 return should_be_inserted (bl);
2453 }
2454
2455 /* Parses a conditional described by an expression COND into an
2456 agent expression bytecode suitable for evaluation
2457 by the bytecode interpreter. Return NULL if there was
2458 any error during parsing. */
2459
2460 static agent_expr_up
2461 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2462 {
2463 if (cond == NULL)
2464 return NULL;
2465
2466 agent_expr_up aexpr;
2467
2468 /* We don't want to stop processing, so catch any errors
2469 that may show up. */
2470 try
2471 {
2472 aexpr = gen_eval_for_expr (scope, cond);
2473 }
2474
2475 catch (const gdb_exception_error &ex)
2476 {
2477 /* If we got here, it means the condition could not be parsed to a valid
2478 bytecode expression and thus can't be evaluated on the target's side.
2479 It's no use iterating through the conditions. */
2480 }
2481
2482 /* We have a valid agent expression. */
2483 return aexpr;
2484 }
2485
2486 /* Based on location BL, create a list of breakpoint conditions to be
2487 passed on to the target. If we have duplicated locations with different
2488 conditions, we will add such conditions to the list. The idea is that the
2489 target will evaluate the list of conditions and will only notify GDB when
2490 one of them is true. */
2491
2492 static void
2493 build_target_condition_list (struct bp_location *bl)
2494 {
2495 bool null_condition_or_parse_error = false;
2496 int modified = bl->needs_update;
2497
2498 /* Release conditions left over from a previous insert. */
2499 bl->target_info.conditions.clear ();
2500
2501 /* This is only meaningful if the target is
2502 evaluating conditions and if the user has
2503 opted for condition evaluation on the target's
2504 side. */
2505 if (gdb_evaluates_breakpoint_condition_p ()
2506 || !target_supports_evaluation_of_breakpoint_conditions ())
2507 return;
2508
2509 auto loc_range = all_bp_locations_at_addr (bl->address);
2510
2511 /* Do a first pass to check for locations with no assigned
2512 conditions or conditions that fail to parse to a valid agent
2513 expression bytecode. If any of these happen, then it's no use to
2514 send conditions to the target since this location will always
2515 trigger and generate a response back to GDB. Note we consider
2516 all locations at the same address irrespective of type, i.e.,
2517 even if the locations aren't considered duplicates (e.g.,
2518 software breakpoint and hardware breakpoint at the same
2519 address). */
2520 for (bp_location *loc : loc_range)
2521 {
2522 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2523 {
2524 if (modified)
2525 {
2526 /* Re-parse the conditions since something changed. In that
2527 case we already freed the condition bytecodes (see
2528 force_breakpoint_reinsertion). We just
2529 need to parse the condition to bytecodes again. */
2530 loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2531 loc->cond.get ());
2532 }
2533
2534 /* If we have a NULL bytecode expression, it means something
2535 went wrong or we have a null condition expression. */
2536 if (!loc->cond_bytecode)
2537 {
2538 null_condition_or_parse_error = true;
2539 break;
2540 }
2541 }
2542 }
2543
2544 /* If any of these happened, it means we will have to evaluate the conditions
2545 for the location's address on gdb's side. It is no use keeping bytecodes
2546 for all the other duplicate locations, thus we free all of them here.
2547
2548 This is so we have a finer control over which locations' conditions are
2549 being evaluated by GDB or the remote stub. */
2550 if (null_condition_or_parse_error)
2551 {
2552 for (bp_location *loc : loc_range)
2553 {
2554 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2555 {
2556 /* Only go as far as the first NULL bytecode is
2557 located. */
2558 if (!loc->cond_bytecode)
2559 return;
2560
2561 loc->cond_bytecode.reset ();
2562 }
2563 }
2564 }
2565
2566 /* No NULL conditions or failed bytecode generation. Build a
2567 condition list for this location's address. If we have software
2568 and hardware locations at the same address, they aren't
2569 considered duplicates, but we still merge all the conditions
2570 anyway, as it's simpler, and doesn't really make a practical
2571 difference. */
2572 for (bp_location *loc : loc_range)
2573 if (loc->cond
2574 && is_breakpoint (loc->owner)
2575 && loc->pspace->num == bl->pspace->num
2576 && loc->owner->enable_state == bp_enabled
2577 && loc->enabled
2578 && !loc->disabled_by_cond)
2579 {
2580 /* Add the condition to the vector. This will be used later
2581 to send the conditions to the target. */
2582 bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2583 }
2584
2585 return;
2586 }
2587
2588 /* Parses a command described by string CMD into an agent expression
2589 bytecode suitable for evaluation by the bytecode interpreter.
2590 Return NULL if there was any error during parsing. */
2591
2592 static agent_expr_up
2593 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2594 {
2595 const char *cmdrest;
2596 const char *format_start, *format_end;
2597 struct gdbarch *gdbarch = get_current_arch ();
2598
2599 if (cmd == NULL)
2600 return NULL;
2601
2602 cmdrest = cmd;
2603
2604 if (*cmdrest == ',')
2605 ++cmdrest;
2606 cmdrest = skip_spaces (cmdrest);
2607
2608 if (*cmdrest++ != '"')
2609 error (_("No format string following the location"));
2610
2611 format_start = cmdrest;
2612
2613 format_pieces fpieces (&cmdrest);
2614
2615 format_end = cmdrest;
2616
2617 if (*cmdrest++ != '"')
2618 error (_("Bad format string, non-terminated '\"'."));
2619
2620 cmdrest = skip_spaces (cmdrest);
2621
2622 if (!(*cmdrest == ',' || *cmdrest == '\0'))
2623 error (_("Invalid argument syntax"));
2624
2625 if (*cmdrest == ',')
2626 cmdrest++;
2627 cmdrest = skip_spaces (cmdrest);
2628
2629 /* For each argument, make an expression. */
2630
2631 std::vector<struct expression *> argvec;
2632 while (*cmdrest != '\0')
2633 {
2634 const char *cmd1;
2635
2636 cmd1 = cmdrest;
2637 expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope),
2638 PARSER_COMMA_TERMINATES);
2639 argvec.push_back (expr.release ());
2640 cmdrest = cmd1;
2641 if (*cmdrest == ',')
2642 ++cmdrest;
2643 }
2644
2645 agent_expr_up aexpr;
2646
2647 /* We don't want to stop processing, so catch any errors
2648 that may show up. */
2649 try
2650 {
2651 aexpr = gen_printf (scope, gdbarch, 0, 0,
2652 format_start, format_end - format_start,
2653 argvec.size (), argvec.data ());
2654 }
2655 catch (const gdb_exception_error &ex)
2656 {
2657 /* If we got here, it means the command could not be parsed to a valid
2658 bytecode expression and thus can't be evaluated on the target's side.
2659 It's no use iterating through the other commands. */
2660 }
2661
2662 /* We have a valid agent expression, return it. */
2663 return aexpr;
2664 }
2665
2666 /* Based on location BL, create a list of breakpoint commands to be
2667 passed on to the target. If we have duplicated locations with
2668 different commands, we will add any such to the list. */
2669
2670 static void
2671 build_target_command_list (struct bp_location *bl)
2672 {
2673 bool null_command_or_parse_error = false;
2674 int modified = bl->needs_update;
2675
2676 /* Clear commands left over from a previous insert. */
2677 bl->target_info.tcommands.clear ();
2678
2679 if (!target_can_run_breakpoint_commands ())
2680 return;
2681
2682 /* For now, limit to agent-style dprintf breakpoints. */
2683 if (dprintf_style != dprintf_style_agent)
2684 return;
2685
2686 auto loc_range = all_bp_locations_at_addr (bl->address);
2687
2688 /* For now, if we have any location at the same address that isn't a
2689 dprintf, don't install the target-side commands, as that would
2690 make the breakpoint not be reported to the core, and we'd lose
2691 control. */
2692 for (bp_location *loc : loc_range)
2693 if (is_breakpoint (loc->owner)
2694 && loc->pspace->num == bl->pspace->num
2695 && loc->owner->type != bp_dprintf)
2696 return;
2697
2698 /* Do a first pass to check for locations with no assigned
2699 conditions or conditions that fail to parse to a valid agent expression
2700 bytecode. If any of these happen, then it's no use to send conditions
2701 to the target since this location will always trigger and generate a
2702 response back to GDB. */
2703 for (bp_location *loc : loc_range)
2704 {
2705 if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2706 {
2707 if (modified)
2708 {
2709 /* Re-parse the commands since something changed. In that
2710 case we already freed the command bytecodes (see
2711 force_breakpoint_reinsertion). We just
2712 need to parse the command to bytecodes again. */
2713 loc->cmd_bytecode
2714 = parse_cmd_to_aexpr (bl->address,
2715 loc->owner->extra_string.get ());
2716 }
2717
2718 /* If we have a NULL bytecode expression, it means something
2719 went wrong or we have a null command expression. */
2720 if (!loc->cmd_bytecode)
2721 {
2722 null_command_or_parse_error = true;
2723 break;
2724 }
2725 }
2726 }
2727
2728 /* If anything failed, then we're not doing target-side commands,
2729 and so clean up. */
2730 if (null_command_or_parse_error)
2731 {
2732 for (bp_location *loc : loc_range)
2733 if (is_breakpoint (loc->owner)
2734 && loc->pspace->num == bl->pspace->num)
2735 {
2736 /* Only go as far as the first NULL bytecode is
2737 located. */
2738 if (loc->cmd_bytecode == NULL)
2739 return;
2740
2741 loc->cmd_bytecode.reset ();
2742 }
2743 }
2744
2745 /* No NULL commands or failed bytecode generation. Build a command
2746 list for all duplicate locations at this location's address.
2747 Note that here we must care for whether the breakpoint location
2748 types are considered duplicates, otherwise, say, if we have a
2749 software and hardware location at the same address, the target
2750 could end up running the commands twice. For the moment, we only
2751 support targets-side commands with dprintf, but it doesn't hurt
2752 to be pedantically correct in case that changes. */
2753 for (bp_location *loc : loc_range)
2754 if (breakpoint_locations_match (bl, loc)
2755 && loc->owner->extra_string
2756 && is_breakpoint (loc->owner)
2757 && loc->pspace->num == bl->pspace->num
2758 && loc->owner->enable_state == bp_enabled
2759 && loc->enabled
2760 && !loc->disabled_by_cond)
2761 {
2762 /* Add the command to the vector. This will be used later
2763 to send the commands to the target. */
2764 bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2765 }
2766
2767 bl->target_info.persist = 0;
2768 /* Maybe flag this location as persistent. */
2769 if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2770 bl->target_info.persist = 1;
2771 }
2772
2773 /* Return the kind of breakpoint on address *ADDR. Get the kind
2774 of breakpoint according to ADDR except single-step breakpoint.
2775 Get the kind of single-step breakpoint according to the current
2776 registers state. */
2777
2778 static int
2779 breakpoint_kind (const struct bp_location *bl, CORE_ADDR *addr)
2780 {
2781 if (bl->owner->type == bp_single_step)
2782 {
2783 struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2784 struct regcache *regcache;
2785
2786 regcache = get_thread_regcache (thr);
2787
2788 return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2789 regcache, addr);
2790 }
2791 else
2792 return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2793 }
2794
2795 /* Rethrow the currently handled exception, if it's a TARGET_CLOSE_ERROR.
2796 E is either the currently handled exception, or a copy, or a sliced copy,
2797 so we can't rethrow that one, but we can use it to inspect the properties
2798 of the currently handled exception. */
2799
2800 static void
2801 rethrow_on_target_close_error (const gdb_exception &e)
2802 {
2803 if (e.reason == 0)
2804 return;
2805 /* Can't set the breakpoint. */
2806
2807 if (e.error != TARGET_CLOSE_ERROR)
2808 return;
2809
2810 /* If the target has closed then it will have deleted any breakpoints
2811 inserted within the target inferior, as a result any further attempts
2812 to interact with the breakpoint objects is not possible. Just rethrow
2813 the error. Don't use e to rethrow, to prevent object slicing of the
2814 exception. */
2815 throw;
2816 }
2817
2818 /* Insert a low-level "breakpoint" of some type. BL is the breakpoint
2819 location. Any error messages are printed to TMP_ERROR_STREAM; and
2820 DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2821 Returns 0 for success, 1 if the bp_location type is not supported or
2822 -1 for failure.
2823
2824 NOTE drow/2003-09-09: This routine could be broken down to an
2825 object-style method for each breakpoint or catchpoint type. */
2826 static int
2827 insert_bp_location (struct bp_location *bl,
2828 struct ui_file *tmp_error_stream,
2829 int *disabled_breaks,
2830 int *hw_breakpoint_error,
2831 int *hw_bp_error_explained_already)
2832 {
2833 gdb_exception bp_excpt;
2834
2835 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2836 return 0;
2837
2838 breakpoint_debug_printf ("%s", breakpoint_location_address_str (bl).c_str ());
2839
2840 /* Note we don't initialize bl->target_info, as that wipes out
2841 the breakpoint location's shadow_contents if the breakpoint
2842 is still inserted at that location. This in turn breaks
2843 target_read_memory which depends on these buffers when
2844 a memory read is requested at the breakpoint location:
2845 Once the target_info has been wiped, we fail to see that
2846 we have a breakpoint inserted at that address and thus
2847 read the breakpoint instead of returning the data saved in
2848 the breakpoint location's shadow contents. */
2849 bl->target_info.reqstd_address = bl->address;
2850 bl->target_info.placed_address_space = bl->pspace->aspace.get ();
2851 bl->target_info.length = bl->length;
2852
2853 /* When working with target-side conditions, we must pass all the conditions
2854 for the same breakpoint address down to the target since GDB will not
2855 insert those locations. With a list of breakpoint conditions, the target
2856 can decide when to stop and notify GDB. */
2857
2858 if (is_breakpoint (bl->owner))
2859 {
2860 build_target_condition_list (bl);
2861 build_target_command_list (bl);
2862 /* Reset the modification marker. */
2863 bl->needs_update = 0;
2864 }
2865
2866 /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2867 set at a read-only address, then a breakpoint location will have
2868 been changed to hardware breakpoint before we get here. If it is
2869 "off" however, error out before actually trying to insert the
2870 breakpoint, with a nicer error message. */
2871 if (bl->loc_type == bp_loc_software_breakpoint
2872 && !automatic_hardware_breakpoints)
2873 {
2874 mem_region *mr = lookup_mem_region (bl->address);
2875
2876 if (mr != nullptr && mr->attrib.mode != MEM_RW)
2877 {
2878 gdb_printf (tmp_error_stream,
2879 _("Cannot insert breakpoint %d.\n"
2880 "Cannot set software breakpoint "
2881 "at read-only address %s\n"),
2882 bl->owner->number,
2883 paddress (bl->gdbarch, bl->address));
2884 return 1;
2885 }
2886 }
2887
2888 if (bl->loc_type == bp_loc_software_breakpoint
2889 || bl->loc_type == bp_loc_hardware_breakpoint)
2890 {
2891 /* First check to see if we have to handle an overlay. */
2892 if (overlay_debugging == ovly_off
2893 || bl->section == NULL
2894 || !(section_is_overlay (bl->section)))
2895 {
2896 /* No overlay handling: just set the breakpoint. */
2897 try
2898 {
2899 int val;
2900
2901 val = bl->owner->insert_location (bl);
2902 if (val)
2903 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2904 }
2905 catch (gdb_exception &e)
2906 {
2907 rethrow_on_target_close_error (e);
2908 bp_excpt = std::move (e);
2909 }
2910 }
2911 else
2912 {
2913 /* This breakpoint is in an overlay section.
2914 Shall we set a breakpoint at the LMA? */
2915 if (!overlay_events_enabled)
2916 {
2917 /* Yes -- overlay event support is not active,
2918 so we must try to set a breakpoint at the LMA.
2919 This will not work for a hardware breakpoint. */
2920 if (bl->loc_type == bp_loc_hardware_breakpoint)
2921 warning (_("hardware breakpoint %d not supported in overlay!"),
2922 bl->owner->number);
2923 else
2924 {
2925 CORE_ADDR addr = overlay_unmapped_address (bl->address,
2926 bl->section);
2927 /* Set a software (trap) breakpoint at the LMA. */
2928 bl->overlay_target_info = bl->target_info;
2929 bl->overlay_target_info.reqstd_address = addr;
2930
2931 /* No overlay handling: just set the breakpoint. */
2932 try
2933 {
2934 int val;
2935
2936 bl->overlay_target_info.kind
2937 = breakpoint_kind (bl, &addr);
2938 bl->overlay_target_info.placed_address = addr;
2939 val = target_insert_breakpoint (bl->gdbarch,
2940 &bl->overlay_target_info);
2941 if (val)
2942 bp_excpt
2943 = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2944 }
2945 catch (gdb_exception &e)
2946 {
2947 rethrow_on_target_close_error (e);
2948 bp_excpt = std::move (e);
2949 }
2950
2951 if (bp_excpt.reason != 0)
2952 gdb_printf (tmp_error_stream,
2953 "Overlay breakpoint %d "
2954 "failed: in ROM?\n",
2955 bl->owner->number);
2956 }
2957 }
2958 /* Shall we set a breakpoint at the VMA? */
2959 if (section_is_mapped (bl->section))
2960 {
2961 /* Yes. This overlay section is mapped into memory. */
2962 try
2963 {
2964 int val;
2965
2966 val = bl->owner->insert_location (bl);
2967 if (val)
2968 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2969 }
2970 catch (gdb_exception_error &e)
2971 {
2972 rethrow_on_target_close_error (e);
2973 bp_excpt = std::move (e);
2974 }
2975 }
2976 else
2977 {
2978 /* No. This breakpoint will not be inserted.
2979 No error, but do not mark the bp as 'inserted'. */
2980 return 0;
2981 }
2982 }
2983
2984 if (bp_excpt.reason != 0)
2985 {
2986 /* Can't set the breakpoint. */
2987 gdb_assert (bl->owner != nullptr);
2988
2989 /* In some cases, we might not be able to insert a
2990 breakpoint in a shared library that has already been
2991 removed, but we have not yet processed the shlib unload
2992 event. Unfortunately, some targets that implement
2993 breakpoint insertion themselves can't tell why the
2994 breakpoint insertion failed (e.g., the remote target
2995 doesn't define error codes), so we must treat generic
2996 errors as memory errors. */
2997 if (bp_excpt.reason == RETURN_ERROR
2998 && (bp_excpt.error == GENERIC_ERROR
2999 || bp_excpt.error == MEMORY_ERROR)
3000 && bl->loc_type == bp_loc_software_breakpoint
3001 && (solib_name_from_address (bl->pspace, bl->address)
3002 || shared_objfile_contains_address_p (bl->pspace,
3003 bl->address)))
3004 {
3005 /* See also: disable_breakpoints_in_shlibs. */
3006 bl->shlib_disabled = 1;
3007 notify_breakpoint_modified (bl->owner);
3008 if (!*disabled_breaks)
3009 {
3010 gdb_printf (tmp_error_stream,
3011 "Cannot insert breakpoint %d.\n",
3012 bl->owner->number);
3013 gdb_printf (tmp_error_stream,
3014 "Temporarily disabling shared "
3015 "library breakpoints:\n");
3016 }
3017 *disabled_breaks = 1;
3018 gdb_printf (tmp_error_stream,
3019 "breakpoint #%d\n", bl->owner->number);
3020 return 0;
3021 }
3022 else
3023 {
3024 if (bl->loc_type == bp_loc_hardware_breakpoint)
3025 {
3026 *hw_breakpoint_error = 1;
3027 *hw_bp_error_explained_already = bp_excpt.message != NULL;
3028 gdb_printf (tmp_error_stream,
3029 "Cannot insert hardware breakpoint %d%s",
3030 bl->owner->number,
3031 bp_excpt.message ? ":" : ".\n");
3032 if (bp_excpt.message != NULL)
3033 gdb_printf (tmp_error_stream, "%s.\n",
3034 bp_excpt.what ());
3035 }
3036 else
3037 {
3038 if (bp_excpt.message == NULL)
3039 {
3040 std::string message
3041 = memory_error_message (TARGET_XFER_E_IO,
3042 bl->gdbarch, bl->address);
3043
3044 gdb_printf (tmp_error_stream,
3045 "Cannot insert breakpoint %d.\n"
3046 "%s\n",
3047 bl->owner->number, message.c_str ());
3048 }
3049 else
3050 {
3051 gdb_printf (tmp_error_stream,
3052 "Cannot insert breakpoint %d: %s\n",
3053 bl->owner->number,
3054 bp_excpt.what ());
3055 }
3056 }
3057 return 1;
3058
3059 }
3060 }
3061 else
3062 bl->inserted = 1;
3063
3064 return 0;
3065 }
3066
3067 else if (bl->loc_type == bp_loc_hardware_watchpoint
3068 && bl->owner->disposition != disp_del_at_next_stop)
3069 {
3070 int val;
3071
3072 val = bl->owner->insert_location (bl);
3073
3074 /* If trying to set a read-watchpoint, and it turns out it's not
3075 supported, try emulating one with an access watchpoint. */
3076 if (val == 1 && bl->watchpoint_type == hw_read)
3077 {
3078 /* But don't try to insert it, if there's already another
3079 hw_access location that would be considered a duplicate
3080 of this one. */
3081 for (bp_location *loc : all_bp_locations ())
3082 if (loc != bl
3083 && loc->watchpoint_type == hw_access
3084 && watchpoint_locations_match (bl, loc))
3085 {
3086 bl->duplicate = 1;
3087 bl->inserted = 1;
3088 bl->target_info = loc->target_info;
3089 bl->watchpoint_type = hw_access;
3090 val = 0;
3091 break;
3092 }
3093
3094 if (val == 1)
3095 {
3096 bl->watchpoint_type = hw_access;
3097 val = bl->owner->insert_location (bl);
3098
3099 if (val)
3100 /* Back to the original value. */
3101 bl->watchpoint_type = hw_read;
3102 }
3103 }
3104
3105 bl->inserted = (val == 0);
3106 }
3107
3108 else if (bl->owner->type == bp_catchpoint)
3109 {
3110 int val;
3111
3112 val = bl->owner->insert_location (bl);
3113 if (val)
3114 {
3115 bl->owner->enable_state = bp_disabled;
3116
3117 if (val == 1)
3118 warning (_("\
3119 Error inserting catchpoint %d: Your system does not support this type\n\
3120 of catchpoint."), bl->owner->number);
3121 else
3122 warning (_("Error inserting catchpoint %d."), bl->owner->number);
3123 }
3124
3125 bl->inserted = (val == 0);
3126
3127 /* We've already printed an error message if there was a problem
3128 inserting this catchpoint, and we've disabled the catchpoint,
3129 so just return success. */
3130 return 0;
3131 }
3132
3133 return 0;
3134 }
3135
3136 /* This function is called when program space PSPACE is about to be
3137 deleted. It takes care of updating breakpoints to not reference
3138 PSPACE anymore. */
3139
3140 void
3141 breakpoint_program_space_exit (struct program_space *pspace)
3142 {
3143 /* Remove any breakpoint that was set through this program space. */
3144 for (breakpoint &b : all_breakpoints_safe ())
3145 if (b.pspace == pspace)
3146 delete_breakpoint (&b);
3147
3148 /* Breakpoints set through other program spaces could have locations
3149 bound to PSPACE as well. Remove those. */
3150 for (bp_location *loc : all_bp_locations ())
3151 if (loc->pspace == pspace)
3152 {
3153 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
3154 loc->owner->unadd_location (*loc);
3155 }
3156
3157 /* Now update the global location list to permanently delete the
3158 removed locations above. */
3159 update_global_location_list (UGLL_DONT_INSERT);
3160 }
3161
3162 /* Make sure all breakpoints are inserted in inferior.
3163 Throws exception on any error.
3164 A breakpoint that is already inserted won't be inserted
3165 again, so calling this function twice is safe. */
3166 void
3167 insert_breakpoints (void)
3168 {
3169 for (breakpoint &bpt : all_breakpoints ())
3170 if (is_hardware_watchpoint (&bpt))
3171 {
3172 watchpoint &w = gdb::checked_static_cast<watchpoint &> (bpt);
3173
3174 update_watchpoint (&w, false /* don't reparse. */);
3175 }
3176
3177 /* Updating watchpoints creates new locations, so update the global
3178 location list. Explicitly tell ugll to insert locations and
3179 ignore breakpoints_always_inserted_mode. Also,
3180 update_global_location_list tries to "upgrade" software
3181 breakpoints to hardware breakpoints to handle "set breakpoint
3182 auto-hw", so we need to call it even if we don't have new
3183 locations. */
3184 update_global_location_list (UGLL_INSERT);
3185 }
3186
3187 /* This is used when we need to synch breakpoint conditions between GDB and the
3188 target. It is the case with deleting and disabling of breakpoints when using
3189 always-inserted mode. */
3190
3191 static void
3192 update_inserted_breakpoint_locations (void)
3193 {
3194 int error_flag = 0;
3195 int val = 0;
3196 int disabled_breaks = 0;
3197 int hw_breakpoint_error = 0;
3198 int hw_bp_details_reported = 0;
3199
3200 string_file tmp_error_stream;
3201
3202 /* Explicitly mark the warning -- this will only be printed if
3203 there was an error. */
3204 tmp_error_stream.puts ("Warning:\n");
3205
3206 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3207
3208 for (bp_location *bl : all_bp_locations ())
3209 {
3210 /* We only want to update software breakpoints and hardware
3211 breakpoints. */
3212 if (!is_breakpoint (bl->owner))
3213 continue;
3214
3215 /* We only want to update locations that are already inserted
3216 and need updating. This is to avoid unwanted insertion during
3217 deletion of breakpoints. */
3218 if (!bl->inserted || !bl->needs_update)
3219 continue;
3220
3221 switch_to_program_space_and_thread (bl->pspace);
3222
3223 /* For targets that support global breakpoints, there's no need
3224 to select an inferior to insert breakpoint to. In fact, even
3225 if we aren't attached to any process yet, we should still
3226 insert breakpoints. */
3227 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
3228 && (inferior_ptid == null_ptid || !target_has_execution ()))
3229 continue;
3230
3231 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3232 &hw_breakpoint_error, &hw_bp_details_reported);
3233 if (val)
3234 error_flag = val;
3235 }
3236
3237 if (error_flag)
3238 {
3239 target_terminal::ours_for_output ();
3240 error (("%s"), tmp_error_stream.c_str ());
3241 }
3242 }
3243
3244 /* Used when starting or continuing the program. */
3245
3246 static void
3247 insert_breakpoint_locations (void)
3248 {
3249 int error_flag = 0;
3250 int val = 0;
3251 int disabled_breaks = 0;
3252 int hw_breakpoint_error = 0;
3253 int hw_bp_error_explained_already = 0;
3254
3255 string_file tmp_error_stream;
3256
3257 /* Explicitly mark the warning -- this will only be printed if
3258 there was an error. */
3259 tmp_error_stream.puts ("Warning:\n");
3260
3261 scoped_restore_current_pspace_and_thread restore_pspace_thread;
3262
3263 for (bp_location *bl : all_bp_locations ())
3264 {
3265 if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3266 continue;
3267
3268 /* There is no point inserting thread-specific breakpoints if
3269 the thread no longer exists. ALL_BP_LOCATIONS bp_location
3270 has BL->OWNER always non-NULL. */
3271 if (bl->owner->thread != -1
3272 && !valid_global_thread_id (bl->owner->thread))
3273 continue;
3274
3275 /* Or inferior specific breakpoints if the inferior no longer
3276 exists. */
3277 if (bl->owner->inferior != -1
3278 && !valid_global_inferior_id (bl->owner->inferior))
3279 continue;
3280
3281 switch_to_program_space_and_thread (bl->pspace);
3282
3283 /* For targets that support global breakpoints, there's no need
3284 to select an inferior to insert breakpoint to. In fact, even
3285 if we aren't attached to any process yet, we should still
3286 insert breakpoints. */
3287 if (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
3288 && (inferior_ptid == null_ptid || !target_has_execution ()))
3289 continue;
3290
3291 val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3292 &hw_breakpoint_error, &hw_bp_error_explained_already);
3293 if (val)
3294 error_flag = val;
3295 }
3296
3297 /* If we failed to insert all locations of a watchpoint, remove
3298 them, as half-inserted watchpoint is of limited use. */
3299 for (breakpoint &bpt : all_breakpoints ())
3300 {
3301 bool some_failed = false;
3302
3303 if (!is_hardware_watchpoint (&bpt))
3304 continue;
3305
3306 if (!breakpoint_enabled (&bpt))
3307 continue;
3308
3309 if (bpt.disposition == disp_del_at_next_stop)
3310 continue;
3311
3312 for (bp_location &loc : bpt.locations ())
3313 if (!loc.inserted && should_be_inserted (&loc))
3314 {
3315 some_failed = true;
3316 break;
3317 }
3318
3319 if (some_failed)
3320 {
3321 for (bp_location &loc : bpt.locations ())
3322 if (loc.inserted)
3323 remove_breakpoint (&loc);
3324
3325 hw_breakpoint_error = 1;
3326 tmp_error_stream.printf ("Could not insert "
3327 "hardware watchpoint %d.\n",
3328 bpt.number);
3329 error_flag = -1;
3330 }
3331 }
3332
3333 if (error_flag)
3334 {
3335 /* If a hardware breakpoint or watchpoint was inserted, add a
3336 message about possibly exhausted resources. */
3337 if (hw_breakpoint_error && !hw_bp_error_explained_already)
3338 {
3339 tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3340 You may have requested too many hardware breakpoints/watchpoints.\n");
3341 }
3342 target_terminal::ours_for_output ();
3343 error (("%s"), tmp_error_stream.c_str ());
3344 }
3345 }
3346
3347 /* Used when the program stops.
3348 Returns zero if successful, or non-zero if there was a problem
3349 removing a breakpoint location. */
3350
3351 int
3352 remove_breakpoints (void)
3353 {
3354 int val = 0;
3355
3356 for (bp_location *bl : all_bp_locations ())
3357 if (bl->inserted && !is_tracepoint (bl->owner))
3358 val |= remove_breakpoint (bl);
3359
3360 return val;
3361 }
3362
3363 /* When a thread exits, remove breakpoints that are related to
3364 that thread. */
3365
3366 static void
3367 remove_threaded_breakpoints (thread_info *tp,
3368 std::optional<ULONGEST> /* exit_code */,
3369 int /* silent */)
3370 {
3371 for (breakpoint &b : all_breakpoints_safe ())
3372 {
3373 if (b.thread == tp->global_num && user_breakpoint_p (&b))
3374 {
3375 gdb_printf (_("\
3376 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3377 b.number, print_thread_id (tp));
3378 delete_breakpoint (&b);
3379 }
3380 }
3381 }
3382
3383 /* Called when inferior INF has been removed from GDB. Remove associated
3384 per-inferior breakpoints. */
3385
3386 static void
3387 remove_inferior_breakpoints (struct inferior *inf)
3388 {
3389 for (breakpoint &b : all_breakpoints_safe ())
3390 {
3391 if (b.inferior == inf->num && user_breakpoint_p (&b))
3392 {
3393 /* Tell the user the breakpoint has been deleted. But only for
3394 breakpoints that would not normally have been deleted at the
3395 next stop anyway. */
3396 if (b.disposition != disp_del
3397 && b.disposition != disp_del_at_next_stop)
3398 gdb_printf (_("\
3399 Inferior-specific breakpoint %d deleted - inferior %d has been removed.\n"),
3400 b.number, inf->num);
3401 delete_breakpoint (&b);
3402 }
3403 }
3404 }
3405
3406 /* See breakpoint.h. */
3407
3408 void
3409 remove_breakpoints_inf (inferior *inf)
3410 {
3411 int val;
3412
3413 breakpoint_debug_printf ("inf->num = %d", inf->num);
3414
3415 for (bp_location *bl : all_bp_locations ())
3416 {
3417 if (bl->pspace != inf->pspace)
3418 continue;
3419
3420 if (bl->inserted && !bl->target_info.persist)
3421 {
3422 val = remove_breakpoint (bl);
3423 if (val != 0)
3424 return;
3425 }
3426 }
3427 }
3428
3429 static int internal_breakpoint_number = -1;
3430
3431 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3432 If INTERNAL is non-zero, the breakpoint number will be populated
3433 from internal_breakpoint_number and that variable decremented.
3434 Otherwise the breakpoint number will be populated from
3435 breakpoint_count and that value incremented. Internal breakpoints
3436 do not set the internal var bpnum. */
3437 static void
3438 set_breakpoint_number (int internal, struct breakpoint *b)
3439 {
3440 if (internal)
3441 b->number = internal_breakpoint_number--;
3442 else
3443 {
3444 set_breakpoint_count (breakpoint_count + 1);
3445 b->number = breakpoint_count;
3446 }
3447 }
3448
3449 /* Create a TYPE breakpoint on ADDRESS from an object file with GDBARCH. */
3450
3451 static struct breakpoint *
3452 create_internal_breakpoint (struct gdbarch *gdbarch,
3453 CORE_ADDR address, enum bptype type)
3454 {
3455 std::unique_ptr<internal_breakpoint> b
3456 (new internal_breakpoint (gdbarch, type, address));
3457
3458 b->number = internal_breakpoint_number--;
3459
3460 return add_to_breakpoint_chain (std::move (b));
3461 }
3462
3463 /* Create a TYPE breakpoint on minimal symbol MSYM from an object file with
3464 GDBARCH. */
3465
3466 static struct breakpoint *
3467 create_internal_breakpoint (struct gdbarch *gdbarch,
3468 struct bound_minimal_symbol &msym, enum bptype type)
3469 {
3470 CORE_ADDR address;
3471
3472 address = msym.value_address ();
3473
3474 address = gdbarch_convert_from_func_ptr_addr
3475 (gdbarch, address, current_inferior ()->top_target ());
3476
3477 /* Note that we're not using gdbarch_addr_bits_remove here, because that's
3478 related to addresses in $pc. We're getting the address from the
3479 minimal symbol table. */
3480
3481 /* Is gdbarch_deprecated_function_start_offset needed here? Or is that dealt
3482 with elsewhere? Needs testing on vax. */
3483
3484 if (gdbarch_skip_entrypoint_p (gdbarch))
3485 address = gdbarch_skip_entrypoint (gdbarch, address);
3486
3487 return create_internal_breakpoint (gdbarch, address, type);
3488 }
3489
3490 static const char *const longjmp_names[] =
3491 {
3492 "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3493 };
3494 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3495
3496 /* Per-objfile data private to breakpoint.c. */
3497 struct breakpoint_objfile_data
3498 {
3499 /* Minimal symbol for "_ovly_debug_event" (if any). */
3500 struct bound_minimal_symbol overlay_msym;
3501
3502 /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any). */
3503 struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3504
3505 /* True if we have looked for longjmp probes. */
3506 int longjmp_searched = 0;
3507
3508 /* SystemTap probe points for longjmp (if any). These are non-owning
3509 references. */
3510 std::vector<probe *> longjmp_probes;
3511
3512 /* Minimal symbol for "std::terminate()" (if any). */
3513 struct bound_minimal_symbol terminate_msym;
3514
3515 /* Minimal symbol for "_Unwind_DebugHook" (if any). */
3516 struct bound_minimal_symbol exception_msym;
3517
3518 /* True if we have looked for exception probes. */
3519 int exception_searched = 0;
3520
3521 /* SystemTap probe points for unwinding (if any). These are non-owning
3522 references. */
3523 std::vector<probe *> exception_probes;
3524 };
3525
3526 static const registry<objfile>::key<breakpoint_objfile_data>
3527 breakpoint_objfile_key;
3528
3529 /* Minimal symbol not found sentinel. */
3530 static struct minimal_symbol msym_not_found;
3531
3532 /* Returns TRUE if MSYM point to the "not found" sentinel. */
3533
3534 static bool
3535 msym_not_found_p (const struct minimal_symbol *msym)
3536 {
3537 return msym == &msym_not_found;
3538 }
3539
3540 /* Return per-objfile data needed by breakpoint.c.
3541 Allocate the data if necessary. */
3542
3543 static struct breakpoint_objfile_data *
3544 get_breakpoint_objfile_data (struct objfile *objfile)
3545 {
3546 struct breakpoint_objfile_data *bp_objfile_data;
3547
3548 bp_objfile_data = breakpoint_objfile_key.get (objfile);
3549 if (bp_objfile_data == NULL)
3550 bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3551 return bp_objfile_data;
3552 }
3553
3554 static void
3555 create_overlay_event_breakpoint (void)
3556 {
3557 const char *const func_name = "_ovly_debug_event";
3558
3559 for (objfile *objfile : current_program_space->objfiles ())
3560 {
3561 struct breakpoint *b;
3562 struct breakpoint_objfile_data *bp_objfile_data;
3563 CORE_ADDR addr;
3564
3565 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3566
3567 if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3568 continue;
3569
3570 if (bp_objfile_data->overlay_msym.minsym == NULL)
3571 {
3572 struct bound_minimal_symbol m;
3573
3574 m = lookup_minimal_symbol_text (func_name, objfile);
3575 if (m.minsym == NULL)
3576 {
3577 /* Avoid future lookups in this objfile. */
3578 bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3579 continue;
3580 }
3581 bp_objfile_data->overlay_msym = m;
3582 }
3583
3584 addr = bp_objfile_data->overlay_msym.value_address ();
3585 b = create_internal_breakpoint (objfile->arch (), addr,
3586 bp_overlay_event);
3587 b->locspec = new_explicit_location_spec_function (func_name);
3588
3589 if (overlay_debugging == ovly_auto)
3590 {
3591 b->enable_state = bp_enabled;
3592 overlay_events_enabled = 1;
3593 }
3594 else
3595 {
3596 b->enable_state = bp_disabled;
3597 overlay_events_enabled = 0;
3598 }
3599 }
3600 }
3601
3602 /* Install a master longjmp breakpoint for OBJFILE using a probe. Return
3603 true if a breakpoint was installed. */
3604
3605 static bool
3606 create_longjmp_master_breakpoint_probe (objfile *objfile)
3607 {
3608 struct gdbarch *gdbarch = objfile->arch ();
3609 struct breakpoint_objfile_data *bp_objfile_data
3610 = get_breakpoint_objfile_data (objfile);
3611
3612 if (!bp_objfile_data->longjmp_searched)
3613 {
3614 std::vector<probe *> ret
3615 = find_probes_in_objfile (objfile, "libc", "longjmp");
3616
3617 if (!ret.empty ())
3618 {
3619 /* We are only interested in checking one element. */
3620 probe *p = ret[0];
3621
3622 if (!p->can_evaluate_arguments ())
3623 {
3624 /* We cannot use the probe interface here,
3625 because it does not know how to evaluate
3626 arguments. */
3627 ret.clear ();
3628 }
3629 }
3630 bp_objfile_data->longjmp_probes = ret;
3631 bp_objfile_data->longjmp_searched = 1;
3632 }
3633
3634 if (bp_objfile_data->longjmp_probes.empty ())
3635 return false;
3636
3637 for (probe *p : bp_objfile_data->longjmp_probes)
3638 {
3639 struct breakpoint *b;
3640
3641 b = create_internal_breakpoint (gdbarch,
3642 p->get_relocated_address (objfile),
3643 bp_longjmp_master);
3644 b->locspec = new_probe_location_spec ("-probe-stap libc:longjmp");
3645 b->enable_state = bp_disabled;
3646 }
3647
3648 return true;
3649 }
3650
3651 /* Install master longjmp breakpoints for OBJFILE using longjmp_names.
3652 Return true if at least one breakpoint was installed. */
3653
3654 static bool
3655 create_longjmp_master_breakpoint_names (objfile *objfile)
3656 {
3657 struct gdbarch *gdbarch = objfile->arch ();
3658 if (!gdbarch_get_longjmp_target_p (gdbarch))
3659 return false;
3660
3661 struct breakpoint_objfile_data *bp_objfile_data
3662 = get_breakpoint_objfile_data (objfile);
3663 unsigned int installed_bp = 0;
3664
3665 for (int i = 0; i < NUM_LONGJMP_NAMES; i++)
3666 {
3667 struct breakpoint *b;
3668 const char *func_name;
3669 CORE_ADDR addr;
3670
3671 if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3672 continue;
3673
3674 func_name = longjmp_names[i];
3675 if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3676 {
3677 struct bound_minimal_symbol m;
3678
3679 m = lookup_minimal_symbol_text (func_name, objfile);
3680 if (m.minsym == NULL)
3681 {
3682 /* Prevent future lookups in this objfile. */
3683 bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3684 continue;
3685 }
3686 bp_objfile_data->longjmp_msym[i] = m;
3687 }
3688
3689 addr = bp_objfile_data->longjmp_msym[i].value_address ();
3690 b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master);
3691 b->locspec = new_explicit_location_spec_function (func_name);
3692 b->enable_state = bp_disabled;
3693 installed_bp++;
3694 }
3695
3696 return installed_bp > 0;
3697 }
3698
3699 /* Create a master longjmp breakpoint. */
3700
3701 static void
3702 create_longjmp_master_breakpoint (void)
3703 {
3704 scoped_restore_current_program_space restore_pspace;
3705
3706 for (struct program_space *pspace : program_spaces)
3707 {
3708 set_current_program_space (pspace);
3709
3710 for (objfile *obj : current_program_space->objfiles ())
3711 {
3712 /* Skip separate debug object, it's handled in the loop below. */
3713 if (obj->separate_debug_objfile_backlink != nullptr)
3714 continue;
3715
3716 /* Try a probe kind breakpoint on main objfile. */
3717 if (create_longjmp_master_breakpoint_probe (obj))
3718 continue;
3719
3720 /* Try longjmp_names kind breakpoints on main and separate_debug
3721 objfiles. */
3722 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3723 if (create_longjmp_master_breakpoint_names (debug_objfile))
3724 break;
3725 }
3726 }
3727 }
3728
3729 /* Create a master std::terminate breakpoint. */
3730 static void
3731 create_std_terminate_master_breakpoint (void)
3732 {
3733 const char *const func_name = "std::terminate()";
3734
3735 scoped_restore_current_program_space restore_pspace;
3736 scoped_restore_current_language save_language;
3737 set_language (language_cplus);
3738
3739 for (struct program_space *pspace : program_spaces)
3740 {
3741 set_current_program_space (pspace);
3742
3743 for (objfile *objfile : current_program_space->objfiles ())
3744 {
3745 struct breakpoint *b;
3746 struct breakpoint_objfile_data *bp_objfile_data;
3747
3748 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3749
3750 if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3751 continue;
3752
3753 if (bp_objfile_data->terminate_msym.minsym == NULL)
3754 {
3755 struct bound_minimal_symbol m;
3756
3757 m = lookup_minimal_symbol (func_name, NULL, objfile);
3758 if (m.minsym == NULL || (m.minsym->type () != mst_text
3759 && m.minsym->type () != mst_file_text))
3760 {
3761 /* Prevent future lookups in this objfile. */
3762 bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3763 continue;
3764 }
3765 bp_objfile_data->terminate_msym = m;
3766 }
3767
3768 b = create_internal_breakpoint (objfile->arch (),
3769 bp_objfile_data->terminate_msym,
3770 bp_std_terminate_master);
3771 b->locspec = new_explicit_location_spec_function (func_name);
3772 b->enable_state = bp_disabled;
3773 }
3774 }
3775 }
3776
3777 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using a
3778 probe. Return true if a breakpoint was installed. */
3779
3780 static bool
3781 create_exception_master_breakpoint_probe (objfile *objfile)
3782 {
3783 struct breakpoint *b;
3784 struct gdbarch *gdbarch;
3785 struct breakpoint_objfile_data *bp_objfile_data;
3786
3787 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3788
3789 /* We prefer the SystemTap probe point if it exists. */
3790 if (!bp_objfile_data->exception_searched)
3791 {
3792 std::vector<probe *> ret
3793 = find_probes_in_objfile (objfile, "libgcc", "unwind");
3794
3795 if (!ret.empty ())
3796 {
3797 /* We are only interested in checking one element. */
3798 probe *p = ret[0];
3799
3800 if (!p->can_evaluate_arguments ())
3801 {
3802 /* We cannot use the probe interface here, because it does
3803 not know how to evaluate arguments. */
3804 ret.clear ();
3805 }
3806 }
3807 bp_objfile_data->exception_probes = ret;
3808 bp_objfile_data->exception_searched = 1;
3809 }
3810
3811 if (bp_objfile_data->exception_probes.empty ())
3812 return false;
3813
3814 gdbarch = objfile->arch ();
3815
3816 for (probe *p : bp_objfile_data->exception_probes)
3817 {
3818 b = create_internal_breakpoint (gdbarch,
3819 p->get_relocated_address (objfile),
3820 bp_exception_master);
3821 b->locspec = new_probe_location_spec ("-probe-stap libgcc:unwind");
3822 b->enable_state = bp_disabled;
3823 }
3824
3825 return true;
3826 }
3827
3828 /* Install a master breakpoint on the unwinder's debug hook for OBJFILE using
3829 _Unwind_DebugHook. Return true if a breakpoint was installed. */
3830
3831 static bool
3832 create_exception_master_breakpoint_hook (objfile *objfile)
3833 {
3834 const char *const func_name = "_Unwind_DebugHook";
3835 struct breakpoint *b;
3836 struct gdbarch *gdbarch;
3837 struct breakpoint_objfile_data *bp_objfile_data;
3838
3839 bp_objfile_data = get_breakpoint_objfile_data (objfile);
3840
3841 if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3842 return false;
3843
3844 gdbarch = objfile->arch ();
3845
3846 if (bp_objfile_data->exception_msym.minsym == NULL)
3847 {
3848 struct bound_minimal_symbol debug_hook;
3849
3850 debug_hook = lookup_minimal_symbol_text (func_name, objfile);
3851 if (debug_hook.minsym == NULL)
3852 {
3853 bp_objfile_data->exception_msym.minsym = &msym_not_found;
3854 return false;
3855 }
3856
3857 bp_objfile_data->exception_msym = debug_hook;
3858 }
3859
3860 b = create_internal_breakpoint (gdbarch, bp_objfile_data->exception_msym,
3861 bp_exception_master);
3862 b->locspec = new_explicit_location_spec_function (func_name);
3863 b->enable_state = bp_disabled;
3864
3865 return true;
3866 }
3867
3868 /* Install a master breakpoint on the unwinder's debug hook. */
3869
3870 static void
3871 create_exception_master_breakpoint (void)
3872 {
3873 for (objfile *obj : current_program_space->objfiles ())
3874 {
3875 /* Skip separate debug object. */
3876 if (obj->separate_debug_objfile_backlink)
3877 continue;
3878
3879 /* Try a probe kind breakpoint. */
3880 if (create_exception_master_breakpoint_probe (obj))
3881 continue;
3882
3883 /* Iterate over main and separate debug objects and try an
3884 _Unwind_DebugHook kind breakpoint. */
3885 for (objfile *debug_objfile : obj->separate_debug_objfiles ())
3886 if (create_exception_master_breakpoint_hook (debug_objfile))
3887 break;
3888 }
3889 }
3890
3891 /* Does B have a location spec? */
3892
3893 static bool
3894 breakpoint_location_spec_empty_p (const struct breakpoint *b)
3895 {
3896 return (b->locspec != nullptr && b->locspec->empty_p ());
3897 }
3898
3899 void
3900 update_breakpoints_after_exec (void)
3901 {
3902 /* We're about to delete breakpoints from GDB's lists. If the
3903 INSERTED flag is true, GDB will try to lift the breakpoints by
3904 writing the breakpoints' "shadow contents" back into memory. The
3905 "shadow contents" are NOT valid after an exec, so GDB should not
3906 do that. Instead, the target is responsible from marking
3907 breakpoints out as soon as it detects an exec. We don't do that
3908 here instead, because there may be other attempts to delete
3909 breakpoints after detecting an exec and before reaching here. */
3910 for (bp_location *bploc : all_bp_locations ())
3911 if (bploc->pspace == current_program_space)
3912 gdb_assert (!bploc->inserted);
3913
3914 for (breakpoint &b : all_breakpoints_safe ())
3915 {
3916 if (b.pspace != current_program_space)
3917 continue;
3918
3919 /* Solib breakpoints must be explicitly reset after an exec(). */
3920 if (b.type == bp_shlib_event)
3921 {
3922 delete_breakpoint (&b);
3923 continue;
3924 }
3925
3926 /* JIT breakpoints must be explicitly reset after an exec(). */
3927 if (b.type == bp_jit_event)
3928 {
3929 delete_breakpoint (&b);
3930 continue;
3931 }
3932
3933 /* Thread event breakpoints must be set anew after an exec(),
3934 as must overlay event and longjmp master breakpoints. */
3935 if (b.type == bp_thread_event || b.type == bp_overlay_event
3936 || b.type == bp_longjmp_master || b.type == bp_std_terminate_master
3937 || b.type == bp_exception_master)
3938 {
3939 delete_breakpoint (&b);
3940 continue;
3941 }
3942
3943 /* Step-resume breakpoints are meaningless after an exec(). */
3944 if (b.type == bp_step_resume || b.type == bp_hp_step_resume)
3945 {
3946 delete_breakpoint (&b);
3947 continue;
3948 }
3949
3950 /* Just like single-step breakpoints. */
3951 if (b.type == bp_single_step)
3952 {
3953 delete_breakpoint (&b);
3954 continue;
3955 }
3956
3957 /* Longjmp and longjmp-resume breakpoints are also meaningless
3958 after an exec. */
3959 if (b.type == bp_longjmp || b.type == bp_longjmp_resume
3960 || b.type == bp_longjmp_call_dummy
3961 || b.type == bp_exception || b.type == bp_exception_resume)
3962 {
3963 delete_breakpoint (&b);
3964 continue;
3965 }
3966
3967 if (b.type == bp_catchpoint)
3968 {
3969 /* For now, none of the bp_catchpoint breakpoints need to
3970 do anything at this point. In the future, if some of
3971 the catchpoints need to something, we will need to add
3972 a new method, and call this method from here. */
3973 continue;
3974 }
3975
3976 /* bp_finish is a special case. The only way we ought to be able
3977 to see one of these when an exec() has happened, is if the user
3978 caught a vfork, and then said "finish". Ordinarily a finish just
3979 carries them to the call-site of the current callee, by setting
3980 a temporary bp there and resuming. But in this case, the finish
3981 will carry them entirely through the vfork & exec.
3982
3983 We don't want to allow a bp_finish to remain inserted now. But
3984 we can't safely delete it, 'cause finish_command has a handle to
3985 the bp on a bpstat, and will later want to delete it. There's a
3986 chance (and I've seen it happen) that if we delete the bp_finish
3987 here, that its storage will get reused by the time finish_command
3988 gets 'round to deleting the "use to be a bp_finish" breakpoint.
3989 We really must allow finish_command to delete a bp_finish.
3990
3991 In the absence of a general solution for the "how do we know
3992 it's safe to delete something others may have handles to?"
3993 problem, what we'll do here is just uninsert the bp_finish, and
3994 let finish_command delete it.
3995
3996 (We know the bp_finish is "doomed" in the sense that it's
3997 momentary, and will be deleted as soon as finish_command sees
3998 the inferior stopped. So it doesn't matter that the bp's
3999 address is probably bogus in the new a.out, unlike e.g., the
4000 solib breakpoints.) */
4001
4002 if (b.type == bp_finish)
4003 {
4004 continue;
4005 }
4006
4007 /* Without a symbolic address, we have little hope of the
4008 pre-exec() address meaning the same thing in the post-exec()
4009 a.out. */
4010 if (breakpoint_location_spec_empty_p (&b))
4011 {
4012 delete_breakpoint (&b);
4013 continue;
4014 }
4015 }
4016 }
4017
4018 int
4019 detach_breakpoints (ptid_t ptid)
4020 {
4021 int val = 0;
4022 scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
4023 struct inferior *inf = current_inferior ();
4024
4025 if (ptid.pid () == inferior_ptid.pid ())
4026 error (_("Cannot detach breakpoints of inferior_ptid"));
4027
4028 /* Set inferior_ptid; remove_breakpoint_1 uses this global. */
4029 inferior_ptid = ptid;
4030 for (bp_location *bl : all_bp_locations ())
4031 {
4032 if (bl->pspace != inf->pspace)
4033 continue;
4034
4035 /* This function must physically remove breakpoints locations
4036 from the specified ptid, without modifying the breakpoint
4037 package's state. Locations of type bp_loc_other and
4038 bp_loc_software_watchpoint are only maintained at GDB side,
4039 so there is no need to remove them. Moreover, removing these
4040 would modify the breakpoint package's state. */
4041 if (bl->loc_type == bp_loc_other
4042 || bl->loc_type == bp_loc_software_watchpoint)
4043 continue;
4044
4045 if (bl->inserted)
4046 val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
4047 }
4048
4049 return val;
4050 }
4051
4052 /* Remove the breakpoint location BL from the current address space.
4053 Note that this is used to detach breakpoints from a child fork.
4054 When we get here, the child isn't in the inferior list, and neither
4055 do we have objects to represent its address space --- we should
4056 *not* look at bl->pspace->aspace here. */
4057
4058 static int
4059 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
4060 {
4061 breakpoint_debug_printf ("%s due to %s",
4062 breakpoint_location_address_str (bl).c_str (),
4063 remove_bp_reason_str (reason));
4064
4065 int val;
4066
4067 /* BL is never in moribund_locations by our callers. */
4068 gdb_assert (bl->owner != NULL);
4069
4070 /* The type of none suggests that owner is actually deleted.
4071 This should not ever happen. */
4072 gdb_assert (bl->owner->type != bp_none);
4073
4074 if (bl->loc_type == bp_loc_software_breakpoint
4075 || bl->loc_type == bp_loc_hardware_breakpoint)
4076 {
4077 /* "Normal" instruction breakpoint: either the standard
4078 trap-instruction bp (bp_breakpoint), or a
4079 bp_hardware_breakpoint. */
4080
4081 /* First check to see if we have to handle an overlay. */
4082 if (overlay_debugging == ovly_off
4083 || bl->section == NULL
4084 || !(section_is_overlay (bl->section)))
4085 {
4086 /* No overlay handling: just remove the breakpoint. */
4087
4088 /* If we're trying to uninsert a memory breakpoint that we
4089 know is set in a dynamic object that is marked
4090 shlib_disabled, then either the dynamic object was
4091 removed with "remove-symbol-file" or with
4092 "nosharedlibrary". In the former case, we don't know
4093 whether another dynamic object might have loaded over the
4094 breakpoint's address -- the user might well let us know
4095 about it next with add-symbol-file (the whole point of
4096 add-symbol-file is letting the user manually maintain a
4097 list of dynamically loaded objects). If we have the
4098 breakpoint's shadow memory, that is, this is a software
4099 breakpoint managed by GDB, check whether the breakpoint
4100 is still inserted in memory, to avoid overwriting wrong
4101 code with stale saved shadow contents. Note that HW
4102 breakpoints don't have shadow memory, as they're
4103 implemented using a mechanism that is not dependent on
4104 being able to modify the target's memory, and as such
4105 they should always be removed. */
4106 if (bl->shlib_disabled
4107 && bl->target_info.shadow_len != 0
4108 && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
4109 val = 0;
4110 else
4111 val = bl->owner->remove_location (bl, reason);
4112 }
4113 else
4114 {
4115 /* This breakpoint is in an overlay section.
4116 Did we set a breakpoint at the LMA? */
4117 if (!overlay_events_enabled)
4118 {
4119 /* Yes -- overlay event support is not active, so we
4120 should have set a breakpoint at the LMA. Remove it.
4121 */
4122 /* Ignore any failures: if the LMA is in ROM, we will
4123 have already warned when we failed to insert it. */
4124 if (bl->loc_type == bp_loc_hardware_breakpoint)
4125 target_remove_hw_breakpoint (bl->gdbarch,
4126 &bl->overlay_target_info);
4127 else
4128 target_remove_breakpoint (bl->gdbarch,
4129 &bl->overlay_target_info,
4130 reason);
4131 }
4132 /* Did we set a breakpoint at the VMA?
4133 If so, we will have marked the breakpoint 'inserted'. */
4134 if (bl->inserted)
4135 {
4136 /* Yes -- remove it. Previously we did not bother to
4137 remove the breakpoint if the section had been
4138 unmapped, but let's not rely on that being safe. We
4139 don't know what the overlay manager might do. */
4140
4141 /* However, we should remove *software* breakpoints only
4142 if the section is still mapped, or else we overwrite
4143 wrong code with the saved shadow contents. */
4144 if (bl->loc_type == bp_loc_hardware_breakpoint
4145 || section_is_mapped (bl->section))
4146 val = bl->owner->remove_location (bl, reason);
4147 else
4148 val = 0;
4149 }
4150 else
4151 {
4152 /* No -- not inserted, so no need to remove. No error. */
4153 val = 0;
4154 }
4155 }
4156
4157 /* In some cases, we might not be able to remove a breakpoint in
4158 a shared library that has already been removed, but we have
4159 not yet processed the shlib unload event. Similarly for an
4160 unloaded add-symbol-file object - the user might not yet have
4161 had the chance to remove-symbol-file it. shlib_disabled will
4162 be set if the library/object has already been removed, but
4163 the breakpoint hasn't been uninserted yet, e.g., after
4164 "nosharedlibrary" or "remove-symbol-file" with breakpoints
4165 always-inserted mode. */
4166 if (val
4167 && (bl->loc_type == bp_loc_software_breakpoint
4168 && (bl->shlib_disabled
4169 || solib_name_from_address (bl->pspace, bl->address)
4170 || shared_objfile_contains_address_p (bl->pspace,
4171 bl->address))))
4172 val = 0;
4173
4174 if (val)
4175 return val;
4176 bl->inserted = (reason == DETACH_BREAKPOINT);
4177 }
4178 else if (bl->loc_type == bp_loc_hardware_watchpoint)
4179 {
4180 bl->inserted = (reason == DETACH_BREAKPOINT);
4181 bl->owner->remove_location (bl, reason);
4182
4183 /* Failure to remove any of the hardware watchpoints comes here. */
4184 if (reason == REMOVE_BREAKPOINT && bl->inserted)
4185 warning (_("Could not remove hardware watchpoint %d."),
4186 bl->owner->number);
4187 }
4188 else if (bl->owner->type == bp_catchpoint
4189 && breakpoint_enabled (bl->owner)
4190 && !bl->duplicate)
4191 {
4192 val = bl->owner->remove_location (bl, reason);
4193 if (val)
4194 return val;
4195
4196 bl->inserted = (reason == DETACH_BREAKPOINT);
4197 }
4198
4199 return 0;
4200 }
4201
4202 static int
4203 remove_breakpoint (struct bp_location *bl)
4204 {
4205 /* BL is never in moribund_locations by our callers. */
4206 gdb_assert (bl->owner != NULL);
4207
4208 /* The type of none suggests that owner is actually deleted.
4209 This should not ever happen. */
4210 gdb_assert (bl->owner->type != bp_none);
4211
4212 scoped_restore_current_pspace_and_thread restore_pspace_thread;
4213
4214 switch_to_program_space_and_thread (bl->pspace);
4215
4216 return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
4217 }
4218
4219 /* Clear the "inserted" flag in all breakpoints. */
4220
4221 void
4222 mark_breakpoints_out (void)
4223 {
4224 for (bp_location *bl : all_bp_locations ())
4225 if (bl->pspace == current_program_space)
4226 bl->inserted = 0;
4227 }
4228
4229 /* Clear the "inserted" flag in all breakpoints and delete any
4230 breakpoints which should go away between runs of the program.
4231
4232 Plus other such housekeeping that has to be done for breakpoints
4233 between runs.
4234
4235 Note: this function gets called at the end of a run (by
4236 generic_mourn_inferior) and when a run begins (by
4237 init_wait_for_inferior). */
4238
4239
4240
4241 void
4242 breakpoint_init_inferior (enum inf_context context)
4243 {
4244 struct program_space *pspace = current_program_space;
4245
4246 /* If breakpoint locations are shared across processes, then there's
4247 nothing to do. */
4248 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ()))
4249 return;
4250
4251 mark_breakpoints_out ();
4252
4253 for (breakpoint &b : all_breakpoints_safe ())
4254 {
4255 if (b.has_locations () && b.first_loc ().pspace != pspace)
4256 continue;
4257
4258 switch (b.type)
4259 {
4260 case bp_call_dummy:
4261 case bp_longjmp_call_dummy:
4262
4263 /* If the call dummy breakpoint is at the entry point it will
4264 cause problems when the inferior is rerun, so we better get
4265 rid of it. */
4266
4267 case bp_watchpoint_scope:
4268
4269 /* Also get rid of scope breakpoints. */
4270
4271 case bp_shlib_event:
4272
4273 /* Also remove solib event breakpoints. Their addresses may
4274 have changed since the last time we ran the program.
4275 Actually we may now be debugging against different target;
4276 and so the solib backend that installed this breakpoint may
4277 not be used in by the target. E.g.,
4278
4279 (gdb) file prog-linux
4280 (gdb) run # native linux target
4281 ...
4282 (gdb) kill
4283 (gdb) file prog-win.exe
4284 (gdb) tar rem :9999 # remote Windows gdbserver.
4285 */
4286
4287 case bp_step_resume:
4288
4289 /* Also remove step-resume breakpoints. */
4290
4291 case bp_single_step:
4292
4293 /* Also remove single-step breakpoints. */
4294
4295 delete_breakpoint (&b);
4296 break;
4297
4298 case bp_watchpoint:
4299 case bp_hardware_watchpoint:
4300 case bp_read_watchpoint:
4301 case bp_access_watchpoint:
4302 {
4303 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
4304
4305 /* Likewise for watchpoints on local expressions. */
4306 if (w.exp_valid_block != NULL)
4307 delete_breakpoint (&b);
4308 else
4309 {
4310 /* Get rid of existing locations, which are no longer
4311 valid. New ones will be created in
4312 update_watchpoint, when the inferior is restarted.
4313 The next update_global_location_list call will
4314 garbage collect them. */
4315 b.clear_locations ();
4316
4317 if (context == inf_starting)
4318 {
4319 /* Reset val field to force reread of starting value in
4320 insert_breakpoints. */
4321 w.val.reset (nullptr);
4322 w.val_valid = false;
4323 }
4324 }
4325 }
4326 break;
4327 default:
4328 break;
4329 }
4330 }
4331
4332 /* Get rid of the moribund locations. */
4333 for (bp_location *bl : moribund_locations)
4334 decref_bp_location (&bl);
4335 moribund_locations.clear ();
4336 }
4337
4338 /* These functions concern about actual breakpoints inserted in the
4339 target --- to e.g. check if we need to do decr_pc adjustment or if
4340 we need to hop over the bkpt --- so we check for address space
4341 match, not program space. */
4342
4343 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4344 exists at PC. It returns ordinary_breakpoint_here if it's an
4345 ordinary breakpoint, or permanent_breakpoint_here if it's a
4346 permanent breakpoint.
4347 - When continuing from a location with an ordinary breakpoint, we
4348 actually single step once before calling insert_breakpoints.
4349 - When continuing from a location with a permanent breakpoint, we
4350 need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4351 the target, to advance the PC past the breakpoint. */
4352
4353 enum breakpoint_here
4354 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4355 {
4356 bool any_breakpoint_here = false;
4357
4358 for (bp_location *bl : all_bp_locations ())
4359 {
4360 if (bl->loc_type != bp_loc_software_breakpoint
4361 && bl->loc_type != bp_loc_hardware_breakpoint)
4362 continue;
4363
4364 /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL. */
4365 if ((breakpoint_enabled (bl->owner)
4366 || bl->permanent)
4367 && breakpoint_location_address_match (bl, aspace, pc))
4368 {
4369 if (overlay_debugging
4370 && section_is_overlay (bl->section)
4371 && !section_is_mapped (bl->section))
4372 continue; /* unmapped overlay -- can't be a match */
4373 else if (bl->permanent)
4374 return permanent_breakpoint_here;
4375 else
4376 any_breakpoint_here = true;
4377 }
4378 }
4379
4380 return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4381 }
4382
4383 /* See breakpoint.h. */
4384
4385 int
4386 breakpoint_in_range_p (const address_space *aspace,
4387 CORE_ADDR addr, ULONGEST len)
4388 {
4389 for (bp_location *bl : all_bp_locations ())
4390 {
4391 if (bl->loc_type != bp_loc_software_breakpoint
4392 && bl->loc_type != bp_loc_hardware_breakpoint)
4393 continue;
4394
4395 if ((breakpoint_enabled (bl->owner)
4396 || bl->permanent)
4397 && breakpoint_location_address_range_overlap (bl, aspace,
4398 addr, len))
4399 {
4400 if (overlay_debugging
4401 && section_is_overlay (bl->section)
4402 && !section_is_mapped (bl->section))
4403 {
4404 /* Unmapped overlay -- can't be a match. */
4405 continue;
4406 }
4407
4408 return 1;
4409 }
4410 }
4411
4412 return 0;
4413 }
4414
4415 /* Return true if there's a moribund breakpoint at PC. */
4416
4417 int
4418 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4419 {
4420 for (bp_location *loc : moribund_locations)
4421 if (breakpoint_location_address_match (loc, aspace, pc))
4422 return 1;
4423
4424 return 0;
4425 }
4426
4427 /* Returns true iff BL is inserted at PC, in address space ASPACE. */
4428
4429 static bool
4430 bp_location_inserted_here_p (const struct bp_location *bl,
4431 const address_space *aspace, CORE_ADDR pc)
4432 {
4433 if (bl->inserted
4434 && breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
4435 aspace, pc))
4436 {
4437 /* An unmapped overlay can't be a match. */
4438 return !(overlay_debugging
4439 && section_is_overlay (bl->section)
4440 && !section_is_mapped (bl->section));
4441 }
4442 return false;
4443 }
4444
4445 /* Returns non-zero iff there's a breakpoint inserted at PC. */
4446
4447 int
4448 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4449 {
4450 for (bp_location *bl : all_bp_locations_at_addr (pc))
4451 {
4452 if (bl->loc_type != bp_loc_software_breakpoint
4453 && bl->loc_type != bp_loc_hardware_breakpoint)
4454 continue;
4455
4456 if (bp_location_inserted_here_p (bl, aspace, pc))
4457 return 1;
4458 }
4459 return 0;
4460 }
4461
4462 /* This function returns non-zero iff there is a software breakpoint
4463 inserted at PC. */
4464
4465 int
4466 software_breakpoint_inserted_here_p (const address_space *aspace,
4467 CORE_ADDR pc)
4468 {
4469 for (bp_location *bl : all_bp_locations_at_addr (pc))
4470 {
4471 if (bl->loc_type != bp_loc_software_breakpoint)
4472 continue;
4473
4474 if (bp_location_inserted_here_p (bl, aspace, pc))
4475 return 1;
4476 }
4477
4478 return 0;
4479 }
4480
4481 /* See breakpoint.h. */
4482
4483 int
4484 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4485 CORE_ADDR pc)
4486 {
4487 for (bp_location *bl : all_bp_locations_at_addr (pc))
4488 {
4489 if (bl->loc_type != bp_loc_hardware_breakpoint)
4490 continue;
4491
4492 if (bp_location_inserted_here_p (bl, aspace, pc))
4493 return 1;
4494 }
4495
4496 return 0;
4497 }
4498
4499 int
4500 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4501 CORE_ADDR addr, ULONGEST len)
4502 {
4503 for (breakpoint &bpt : all_breakpoints ())
4504 {
4505 if (bpt.type != bp_hardware_watchpoint
4506 && bpt.type != bp_access_watchpoint)
4507 continue;
4508
4509 if (!breakpoint_enabled (&bpt))
4510 continue;
4511
4512 for (bp_location &loc : bpt.locations ())
4513 if (loc.pspace->aspace.get () == aspace && loc.inserted)
4514 {
4515 CORE_ADDR l, h;
4516
4517 /* Check for intersection. */
4518 l = std::max<CORE_ADDR> (loc.address, addr);
4519 h = std::min<CORE_ADDR> (loc.address + loc.length, addr + len);
4520 if (l < h)
4521 return 1;
4522 }
4523 }
4524 return 0;
4525 }
4526
4527 /* See breakpoint.h. */
4528
4529 bool
4530 is_catchpoint (struct breakpoint *b)
4531 {
4532 return (b->type == bp_catchpoint);
4533 }
4534
4535 /* Clear a bpstat so that it says we are not at any breakpoint.
4536 Also free any storage that is part of a bpstat. */
4537
4538 void
4539 bpstat_clear (bpstat **bsp)
4540 {
4541 bpstat *p;
4542 bpstat *q;
4543
4544 if (bsp == 0)
4545 return;
4546 p = *bsp;
4547 while (p != NULL)
4548 {
4549 q = p->next;
4550 delete p;
4551 p = q;
4552 }
4553 *bsp = NULL;
4554 }
4555
4556 bpstat::bpstat (const bpstat &other)
4557 : next (NULL),
4558 bp_location_at (other.bp_location_at),
4559 breakpoint_at (other.breakpoint_at),
4560 commands (other.commands),
4561 print (other.print),
4562 stop (other.stop),
4563 print_it (other.print_it)
4564 {
4565 if (other.old_val != NULL)
4566 old_val = release_value (other.old_val->copy ());
4567 }
4568
4569 /* Return a copy of a bpstat. Like "bs1 = bs2" but all storage that
4570 is part of the bpstat is copied as well. */
4571
4572 bpstat *
4573 bpstat_copy (bpstat *bs)
4574 {
4575 bpstat *p = nullptr;
4576 bpstat *tmp;
4577 bpstat *retval = nullptr;
4578
4579 if (bs == NULL)
4580 return bs;
4581
4582 for (; bs != NULL; bs = bs->next)
4583 {
4584 tmp = new bpstat (*bs);
4585
4586 if (p == NULL)
4587 /* This is the first thing in the chain. */
4588 retval = tmp;
4589 else
4590 p->next = tmp;
4591 p = tmp;
4592 }
4593 p->next = NULL;
4594 return retval;
4595 }
4596
4597 /* Find the bpstat associated with this breakpoint. */
4598
4599 bpstat *
4600 bpstat_find_breakpoint (bpstat *bsp, struct breakpoint *breakpoint)
4601 {
4602 if (bsp == NULL)
4603 return NULL;
4604
4605 for (; bsp != NULL; bsp = bsp->next)
4606 {
4607 if (bsp->breakpoint_at == breakpoint)
4608 return bsp;
4609 }
4610 return NULL;
4611 }
4612
4613 /* See breakpoint.h. */
4614
4615 bool
4616 bpstat_explains_signal (bpstat *bsp, enum gdb_signal sig)
4617 {
4618 for (; bsp != NULL; bsp = bsp->next)
4619 {
4620 if (bsp->breakpoint_at == NULL)
4621 {
4622 /* A moribund location can never explain a signal other than
4623 GDB_SIGNAL_TRAP. */
4624 if (sig == GDB_SIGNAL_TRAP)
4625 return true;
4626 }
4627 else
4628 {
4629 if (bsp->breakpoint_at->explains_signal (sig))
4630 return true;
4631 }
4632 }
4633
4634 return false;
4635 }
4636
4637 /* See breakpoint.h. */
4638
4639 int
4640 bpstat_num (bpstat **bsp, int *num)
4641 {
4642 struct breakpoint *b;
4643
4644 if ((*bsp) == NULL)
4645 return 0; /* No more breakpoint values */
4646
4647 /* We assume we'll never have several bpstats that correspond to a
4648 single breakpoint -- otherwise, this function might return the
4649 same number more than once and this will look ugly. */
4650 b = (*bsp)->breakpoint_at;
4651 *bsp = (*bsp)->next;
4652 if (b == NULL)
4653 return -1; /* breakpoint that's been deleted since */
4654
4655 *num = b->number; /* We have its number */
4656 return 1;
4657 }
4658
4659 /* See breakpoint.h */
4660
4661 int
4662 bpstat_locno (const bpstat *bs)
4663 {
4664 const struct breakpoint *b = bs->breakpoint_at;
4665 const struct bp_location *bl = bs->bp_location_at.get ();
4666
4667 if (b != nullptr && b->has_multiple_locations ())
4668 {
4669 int locno = 1;
4670
4671 for (bp_location &loc : b->locations ())
4672 {
4673 if (bl == &loc)
4674 return locno;
4675
4676 ++locno;
4677 }
4678
4679 warning (_("location number not found for breakpoint %d address %s."),
4680 b->number, paddress (bl->gdbarch, bl->address));
4681 }
4682
4683 return 0;
4684 }
4685
4686 /* See breakpoint.h. */
4687
4688 void
4689 print_num_locno (const bpstat *bs, struct ui_out *uiout)
4690 {
4691 struct breakpoint *b = bs->breakpoint_at;
4692
4693 if (b == nullptr)
4694 uiout->text (_("deleted breakpoint"));
4695 else
4696 {
4697 uiout->field_signed ("bkptno", b->number);
4698
4699 int locno = bpstat_locno (bs);
4700 if (locno != 0)
4701 uiout->message (".%pF", signed_field ("locno", locno));
4702 }
4703 }
4704
4705 /* See breakpoint.h. */
4706
4707 void
4708 bpstat_clear_actions (void)
4709 {
4710 bpstat *bs;
4711
4712 if (inferior_ptid == null_ptid)
4713 return;
4714
4715 thread_info *tp = inferior_thread ();
4716 for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4717 {
4718 bs->commands = NULL;
4719 bs->old_val.reset (nullptr);
4720 }
4721 }
4722
4723 /* Called when a command is about to proceed the inferior. */
4724
4725 static void
4726 breakpoint_about_to_proceed (void)
4727 {
4728 if (inferior_ptid != null_ptid)
4729 {
4730 struct thread_info *tp = inferior_thread ();
4731
4732 /* Allow inferior function calls in breakpoint commands to not
4733 interrupt the command list. When the call finishes
4734 successfully, the inferior will be standing at the same
4735 breakpoint as if nothing happened. */
4736 if (tp->control.in_infcall)
4737 return;
4738 }
4739
4740 breakpoint_proceeded = 1;
4741 }
4742
4743 /* Return true iff CMD as the first line of a command sequence is `silent'
4744 or its equivalent. */
4745
4746 static bool
4747 command_line_is_silent (struct command_line *cmd)
4748 {
4749 return cmd && (strcmp ("silent", cmd->line) == 0);
4750 }
4751
4752 /* Sets the $_hit_bpnum and $_hit_locno to bpnum and locno.
4753 A locno 0 is changed to 1 to e.g. let the user do
4754 (gdb) disable $_hit_bpnum.$_hit_locno
4755 for a single location breakpoint. */
4756
4757 static void
4758 set_hit_convenience_vars (int bpnum, int locno)
4759 {
4760 set_internalvar_integer (lookup_internalvar ("_hit_bpnum"), bpnum);
4761 set_internalvar_integer (lookup_internalvar ("_hit_locno"),
4762 (locno > 0 ? locno : 1));
4763 }
4764
4765 /* Execute all the commands associated with all the breakpoints at
4766 this location. Any of these commands could cause the process to
4767 proceed beyond this point, etc. We look out for such changes by
4768 checking the global "breakpoint_proceeded" after each command.
4769
4770 Returns true if a breakpoint command resumed the inferior. In that
4771 case, it is the caller's responsibility to recall it again with the
4772 bpstat of the current thread. */
4773
4774 static bool
4775 bpstat_do_actions_1 (bpstat **bsp)
4776 {
4777 bpstat *bs;
4778 bool again = false;
4779
4780 /* Avoid endless recursion if a `source' command is contained
4781 in bs->commands. */
4782 if (executing_breakpoint_commands)
4783 return false;
4784
4785 scoped_restore save_executing
4786 = make_scoped_restore (&executing_breakpoint_commands, 1);
4787
4788 scoped_restore preventer = prevent_dont_repeat ();
4789
4790 /* This pointer will iterate over the list of bpstat's. */
4791 bs = *bsp;
4792
4793 /* The $_hit_* convenience variables are set before running the
4794 commands of BS. In case we have several bs, after the loop,
4795 we set again the variables to the first printed bpnum and locno.
4796 For multiple breakpoints, this ensures the variables are set to the
4797 breakpoint printed for the user. */
4798 int printed_hit_bpnum = -1;
4799 int printed_hit_locno = -1;
4800
4801 breakpoint_proceeded = 0;
4802 for (; bs != NULL; bs = bs->next)
4803 {
4804 struct command_line *cmd = NULL;
4805
4806 /* Set the _hit_* convenience variables before running BS's commands. */
4807 {
4808 const struct breakpoint *b = bs->breakpoint_at;
4809 if (b != nullptr)
4810 {
4811 int locno = bpstat_locno (bs);
4812
4813 set_hit_convenience_vars (b->number, locno);
4814 if (printed_hit_locno == -1 && bs->print)
4815 {
4816 printed_hit_bpnum = b->number;
4817 printed_hit_locno = locno;
4818 }
4819 }
4820 }
4821
4822 /* Take ownership of the BSP's command tree, if it has one.
4823
4824 The command tree could legitimately contain commands like
4825 'step' and 'next', which call clear_proceed_status, which
4826 frees the bpstat BS and its command tree. To make sure this doesn't
4827 free the tree we're executing out from under us, we need to
4828 take ownership of the tree ourselves. Since a given bpstat's
4829 commands are only executed once, we don't need to copy it; we
4830 can clear the pointer in the bpstat, and make sure we free
4831 the tree when we're done. */
4832 counted_command_line ccmd = bs->commands;
4833 bs->commands = NULL;
4834 if (ccmd != NULL)
4835 cmd = ccmd.get ();
4836 if (command_line_is_silent (cmd))
4837 {
4838 /* The action has been already done by bpstat_stop_status. */
4839 cmd = cmd->next;
4840 }
4841
4842 while (cmd != NULL)
4843 {
4844 execute_control_command (cmd);
4845 /* After execute_control_command, if breakpoint_proceeded is true,
4846 BS has been freed and cannot be accessed anymore. */
4847
4848 if (breakpoint_proceeded)
4849 break;
4850 else
4851 cmd = cmd->next;
4852 }
4853
4854 if (breakpoint_proceeded)
4855 {
4856 if (current_ui->async)
4857 /* If we are in async mode, then the target might be still
4858 running, not stopped at any breakpoint, so nothing for
4859 us to do here -- just return to the event loop. */
4860 ;
4861 else
4862 /* In sync mode, when execute_control_command returns
4863 we're already standing on the next breakpoint.
4864 Breakpoint commands for that stop were not run, since
4865 execute_command does not run breakpoint commands --
4866 only command_line_handler does, but that one is not
4867 involved in execution of breakpoint commands. So, we
4868 can now execute breakpoint commands. It should be
4869 noted that making execute_command do bpstat actions is
4870 not an option -- in this case we'll have recursive
4871 invocation of bpstat for each breakpoint with a
4872 command, and can easily blow up GDB stack. Instead, we
4873 return true, which will trigger the caller to recall us
4874 with the new stop_bpstat. */
4875 again = true;
4876 break;
4877 }
4878 }
4879
4880 /* Now that we have executed the commands of all bs, set the _hit_*
4881 convenience variables to the printed values. */
4882 if (printed_hit_locno != -1)
4883 set_hit_convenience_vars (printed_hit_bpnum, printed_hit_locno);
4884
4885 return again;
4886 }
4887
4888 /* Helper for bpstat_do_actions. Get the current thread, if there's
4889 one, is alive and has execution. Return NULL otherwise. */
4890
4891 static thread_info *
4892 get_bpstat_thread ()
4893 {
4894 if (inferior_ptid == null_ptid || !target_has_execution ())
4895 return NULL;
4896
4897 thread_info *tp = inferior_thread ();
4898 if (tp->state == THREAD_EXITED || tp->executing ())
4899 return NULL;
4900 return tp;
4901 }
4902
4903 void
4904 bpstat_do_actions (void)
4905 {
4906 auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4907 thread_info *tp;
4908
4909 /* Do any commands attached to breakpoint we are stopped at. */
4910 while ((tp = get_bpstat_thread ()) != NULL)
4911 {
4912 /* Since in sync mode, bpstat_do_actions may resume the
4913 inferior, and only return when it is stopped at the next
4914 breakpoint, we keep doing breakpoint actions until it returns
4915 false to indicate the inferior was not resumed. */
4916 if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4917 break;
4918 }
4919
4920 cleanup_if_error.release ();
4921 }
4922
4923 /* Print out the (old or new) value associated with a watchpoint. */
4924
4925 static void
4926 watchpoint_value_print (struct value *val, struct ui_file *stream)
4927 {
4928 if (val == NULL)
4929 fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4930 else
4931 {
4932 struct value_print_options opts;
4933 get_user_print_options (&opts);
4934 value_print (val, stream, &opts);
4935 }
4936 }
4937
4938 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4939 debugging multiple threads. */
4940
4941 void
4942 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4943 {
4944 if (uiout->is_mi_like_p ())
4945 return;
4946
4947 uiout->text ("\n");
4948
4949 if (show_thread_that_caused_stop ())
4950 {
4951 struct thread_info *thr = inferior_thread ();
4952
4953 uiout->text ("Thread ");
4954 uiout->field_string ("thread-id", print_thread_id (thr));
4955
4956 const char *name = thread_name (thr);
4957 if (name != NULL)
4958 {
4959 uiout->text (" \"");
4960 uiout->field_string ("name", name);
4961 uiout->text ("\"");
4962 }
4963
4964 uiout->text (" hit ");
4965 }
4966 }
4967
4968 /* Generic routine for printing messages indicating why we
4969 stopped. The behavior of this function depends on the value
4970 'print_it' in the bpstat structure. Under some circumstances we
4971 may decide not to print anything here and delegate the task to
4972 normal_stop(). */
4973
4974 static enum print_stop_action
4975 print_bp_stop_message (bpstat *bs)
4976 {
4977 switch (bs->print_it)
4978 {
4979 case print_it_noop:
4980 /* Nothing should be printed for this bpstat entry. */
4981 return PRINT_UNKNOWN;
4982
4983 case print_it_done:
4984 /* We still want to print the frame, but we already printed the
4985 relevant messages. */
4986 return PRINT_SRC_AND_LOC;
4987
4988 case print_it_normal:
4989 {
4990 struct breakpoint *b = bs->breakpoint_at;
4991
4992 /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4993 which has since been deleted. */
4994 if (b == NULL)
4995 return PRINT_UNKNOWN;
4996
4997 /* Normal case. Call the breakpoint's print_it method. */
4998 return b->print_it (bs);
4999 }
5000
5001 default:
5002 internal_error (_("print_bp_stop_message: unrecognized enum value"));
5003 }
5004 }
5005
5006 /* See breakpoint.h. */
5007
5008 void
5009 print_solib_event (bool is_catchpoint)
5010 {
5011 bool any_deleted = !current_program_space->deleted_solibs.empty ();
5012 bool any_added = !current_program_space->added_solibs.empty ();
5013
5014 if (!is_catchpoint)
5015 {
5016 if (any_added || any_deleted)
5017 current_uiout->text (_("Stopped due to shared library event:\n"));
5018 else
5019 current_uiout->text (_("Stopped due to shared library event (no "
5020 "libraries added or removed)\n"));
5021 }
5022
5023 if (current_uiout->is_mi_like_p ())
5024 current_uiout->field_string ("reason",
5025 async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
5026
5027 if (any_deleted)
5028 {
5029 current_uiout->text (_(" Inferior unloaded "));
5030 ui_out_emit_list list_emitter (current_uiout, "removed");
5031 for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
5032 {
5033 const std::string &name = current_program_space->deleted_solibs[ix];
5034
5035 if (ix > 0)
5036 current_uiout->text (" ");
5037 current_uiout->field_string ("library", name);
5038 current_uiout->text ("\n");
5039 }
5040 }
5041
5042 if (any_added)
5043 {
5044 current_uiout->text (_(" Inferior loaded "));
5045 ui_out_emit_list list_emitter (current_uiout, "added");
5046 bool first = true;
5047 for (shobj *iter : current_program_space->added_solibs)
5048 {
5049 if (!first)
5050 current_uiout->text (" ");
5051 first = false;
5052 current_uiout->field_string ("library", iter->so_name);
5053 current_uiout->text ("\n");
5054 }
5055 }
5056 }
5057
5058 /* Print a message indicating what happened. This is called from
5059 normal_stop(). The input to this routine is the head of the bpstat
5060 list - a list of the eventpoints that caused this stop. KIND is
5061 the target_waitkind for the stopping event. This
5062 routine calls the generic print routine for printing a message
5063 about reasons for stopping. This will print (for example) the
5064 "Breakpoint n," part of the output. The return value of this
5065 routine is one of:
5066
5067 PRINT_UNKNOWN: Means we printed nothing.
5068 PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
5069 code to print the location. An example is
5070 "Breakpoint 1, " which should be followed by
5071 the location.
5072 PRINT_SRC_ONLY: Means we printed something, but there is no need
5073 to also print the location part of the message.
5074 An example is the catch/throw messages, which
5075 don't require a location appended to the end.
5076 PRINT_NOTHING: We have done some printing and we don't need any
5077 further info to be printed. */
5078
5079 enum print_stop_action
5080 bpstat_print (bpstat *bs, target_waitkind kind)
5081 {
5082 enum print_stop_action val;
5083
5084 /* Maybe another breakpoint in the chain caused us to stop.
5085 (Currently all watchpoints go on the bpstat whether hit or not.
5086 That probably could (should) be changed, provided care is taken
5087 with respect to bpstat_explains_signal). */
5088 for (; bs; bs = bs->next)
5089 {
5090 val = print_bp_stop_message (bs);
5091 if (val == PRINT_SRC_ONLY
5092 || val == PRINT_SRC_AND_LOC
5093 || val == PRINT_NOTHING)
5094 return val;
5095 }
5096
5097 /* If we had hit a shared library event breakpoint,
5098 print_bp_stop_message would print out this message. If we hit an
5099 OS-level shared library event, do the same thing. */
5100 if (kind == TARGET_WAITKIND_LOADED)
5101 {
5102 print_solib_event (false);
5103 return PRINT_NOTHING;
5104 }
5105
5106 /* We reached the end of the chain, or we got a null BS to start
5107 with and nothing was printed. */
5108 return PRINT_UNKNOWN;
5109 }
5110
5111 /* Evaluate the boolean expression EXP and return the result. */
5112
5113 static bool
5114 breakpoint_cond_eval (expression *exp)
5115 {
5116 scoped_value_mark mark;
5117 return value_true (exp->evaluate ());
5118 }
5119
5120 /* Allocate a new bpstat. Link it to the FIFO list by BS_LINK_POINTER. */
5121
5122 bpstat::bpstat (struct bp_location *bl, bpstat ***bs_link_pointer)
5123 : next (NULL),
5124 bp_location_at (bp_location_ref_ptr::new_reference (bl)),
5125 breakpoint_at (bl->owner),
5126 commands (NULL),
5127 print (0),
5128 stop (0),
5129 print_it (print_it_normal)
5130 {
5131 **bs_link_pointer = this;
5132 *bs_link_pointer = &next;
5133 }
5134
5135 bpstat::bpstat ()
5136 : next (NULL),
5137 breakpoint_at (NULL),
5138 commands (NULL),
5139 print (0),
5140 stop (0),
5141 print_it (print_it_normal)
5142 {
5143 }
5144 \f
5145 /* The target has stopped with waitstatus WS. Check if any hardware
5146 watchpoints have triggered, according to the target. */
5147
5148 int
5149 watchpoints_triggered (const target_waitstatus &ws)
5150 {
5151 bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
5152 CORE_ADDR addr;
5153
5154 if (!stopped_by_watchpoint)
5155 {
5156 /* We were not stopped by a watchpoint. Mark all watchpoints
5157 as not triggered. */
5158 for (breakpoint &b : all_breakpoints ())
5159 if (is_hardware_watchpoint (&b))
5160 {
5161 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5162
5163 w.watchpoint_triggered = watch_triggered_no;
5164 }
5165
5166 return 0;
5167 }
5168
5169 if (!target_stopped_data_address (current_inferior ()->top_target (), &addr))
5170 {
5171 /* We were stopped by a watchpoint, but we don't know where.
5172 Mark all watchpoints as unknown. */
5173 for (breakpoint &b : all_breakpoints ())
5174 if (is_hardware_watchpoint (&b))
5175 {
5176 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5177
5178 w.watchpoint_triggered = watch_triggered_unknown;
5179 }
5180
5181 return 1;
5182 }
5183
5184 /* The target could report the data address. Mark watchpoints
5185 affected by this data address as triggered, and all others as not
5186 triggered. */
5187
5188 for (breakpoint &b : all_breakpoints ())
5189 if (is_hardware_watchpoint (&b))
5190 {
5191 watchpoint &w = gdb::checked_static_cast<watchpoint &> (b);
5192
5193 w.watchpoint_triggered = watch_triggered_no;
5194 for (bp_location &loc : b.locations ())
5195 {
5196 if (is_masked_watchpoint (&b))
5197 {
5198 CORE_ADDR newaddr = addr & w.hw_wp_mask;
5199 CORE_ADDR start = loc.address & w.hw_wp_mask;
5200
5201 if (newaddr == start)
5202 {
5203 w.watchpoint_triggered = watch_triggered_yes;
5204 break;
5205 }
5206 }
5207 /* Exact match not required. Within range is sufficient. */
5208 else if (target_watchpoint_addr_within_range
5209 (current_inferior ()->top_target (), addr, loc.address,
5210 loc.length))
5211 {
5212 w.watchpoint_triggered = watch_triggered_yes;
5213 break;
5214 }
5215 }
5216 }
5217
5218 return 1;
5219 }
5220
5221 /* Possible return values for watchpoint_check. */
5222 enum wp_check_result
5223 {
5224 /* The watchpoint has been deleted. */
5225 WP_DELETED = 1,
5226
5227 /* The value has changed. */
5228 WP_VALUE_CHANGED = 2,
5229
5230 /* The value has not changed. */
5231 WP_VALUE_NOT_CHANGED = 3,
5232
5233 /* Ignore this watchpoint, no matter if the value changed or not. */
5234 WP_IGNORE = 4,
5235 };
5236
5237 #define BP_TEMPFLAG 1
5238 #define BP_HARDWAREFLAG 2
5239
5240 /* Evaluate watchpoint condition expression and check if its value
5241 changed. */
5242
5243 static wp_check_result
5244 watchpoint_check (bpstat *bs)
5245 {
5246 frame_info_ptr fr;
5247 bool within_current_scope;
5248
5249 /* BS is built from an existing struct breakpoint. */
5250 gdb_assert (bs->breakpoint_at != NULL);
5251 watchpoint *b = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5252
5253 /* If this is a local watchpoint, we only want to check if the
5254 watchpoint frame is in scope if the current thread is the thread
5255 that was used to create the watchpoint. */
5256 if (!watchpoint_in_thread_scope (b))
5257 return WP_IGNORE;
5258
5259 if (b->exp_valid_block == NULL)
5260 within_current_scope = true;
5261 else
5262 {
5263 frame_info_ptr frame = get_current_frame ();
5264 struct gdbarch *frame_arch = get_frame_arch (frame);
5265 CORE_ADDR frame_pc = get_frame_pc (frame);
5266
5267 /* stack_frame_destroyed_p() returns a non-zero value if we're
5268 still in the function but the stack frame has already been
5269 invalidated. Since we can't rely on the values of local
5270 variables after the stack has been destroyed, we are treating
5271 the watchpoint in that state as `not changed' without further
5272 checking. Don't mark watchpoints as changed if the current
5273 frame is in an epilogue - even if they are in some other
5274 frame, our view of the stack is likely to be wrong and
5275 frame_find_by_id could error out. */
5276 if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
5277 return WP_IGNORE;
5278
5279 fr = frame_find_by_id (b->watchpoint_frame);
5280 within_current_scope = (fr != NULL);
5281
5282 /* If we've gotten confused in the unwinder, we might have
5283 returned a frame that can't describe this variable. */
5284 if (within_current_scope)
5285 {
5286 struct symbol *function;
5287
5288 function = get_frame_function (fr);
5289 if (function == NULL
5290 || !function->value_block ()->contains (b->exp_valid_block))
5291 within_current_scope = false;
5292 }
5293
5294 if (within_current_scope)
5295 /* If we end up stopping, the current frame will get selected
5296 in normal_stop. So this call to select_frame won't affect
5297 the user. */
5298 select_frame (fr);
5299 }
5300
5301 if (within_current_scope)
5302 {
5303 /* We use value_{,free_to_}mark because it could be a *long*
5304 time before we return to the command level and call
5305 free_all_values. We can't call free_all_values because we
5306 might be in the middle of evaluating a function call. */
5307
5308 struct value *mark;
5309 struct value *new_val;
5310
5311 if (is_masked_watchpoint (b))
5312 /* Since we don't know the exact trigger address (from
5313 stopped_data_address), just tell the user we've triggered
5314 a mask watchpoint. */
5315 return WP_VALUE_CHANGED;
5316
5317 mark = value_mark ();
5318 fetch_subexp_value (b->exp.get (), b->exp->op.get (), &new_val,
5319 NULL, NULL, false);
5320
5321 if (b->val_bitsize != 0)
5322 new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5323
5324 /* We use value_equal_contents instead of value_equal because
5325 the latter coerces an array to a pointer, thus comparing just
5326 the address of the array instead of its contents. This is
5327 not what we want. */
5328 if ((b->val != NULL) != (new_val != NULL)
5329 || (b->val != NULL && !value_equal_contents (b->val.get (),
5330 new_val)))
5331 {
5332 bs->old_val = b->val;
5333 b->val = release_value (new_val);
5334 b->val_valid = true;
5335 if (new_val != NULL)
5336 value_free_to_mark (mark);
5337 return WP_VALUE_CHANGED;
5338 }
5339 else
5340 {
5341 /* Nothing changed. */
5342 value_free_to_mark (mark);
5343 return WP_VALUE_NOT_CHANGED;
5344 }
5345 }
5346 else
5347 {
5348 /* This seems like the only logical thing to do because
5349 if we temporarily ignored the watchpoint, then when
5350 we reenter the block in which it is valid it contains
5351 garbage (in the case of a function, it may have two
5352 garbage values, one before and one after the prologue).
5353 So we can't even detect the first assignment to it and
5354 watch after that (since the garbage may or may not equal
5355 the first value assigned). */
5356 /* We print all the stop information in
5357 breakpointprint_it, but in this case, by the time we
5358 call breakpoint->print_it this bp will be deleted
5359 already. So we have no choice but print the information
5360 here. */
5361
5362 SWITCH_THRU_ALL_UIS ()
5363 {
5364 struct ui_out *uiout = current_uiout;
5365
5366 if (uiout->is_mi_like_p ())
5367 uiout->field_string
5368 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5369 uiout->message ("\nWatchpoint %pF deleted because the program has "
5370 "left the block in\n"
5371 "which its expression is valid.\n",
5372 signed_field ("wpnum", b->number));
5373 }
5374
5375 /* Make sure the watchpoint's commands aren't executed. */
5376 b->commands = NULL;
5377 watchpoint_del_at_next_stop (b);
5378
5379 return WP_DELETED;
5380 }
5381 }
5382
5383 /* Return true if it looks like target has stopped due to hitting
5384 breakpoint location BL. This function does not check if we should
5385 stop, only if BL explains the stop. */
5386
5387 static bool
5388 bpstat_check_location (const struct bp_location *bl,
5389 const address_space *aspace, CORE_ADDR bp_addr,
5390 const target_waitstatus &ws)
5391 {
5392 struct breakpoint *b = bl->owner;
5393
5394 /* BL is from an existing breakpoint. */
5395 gdb_assert (b != NULL);
5396
5397 return b->breakpoint_hit (bl, aspace, bp_addr, ws);
5398 }
5399
5400 /* Determine if the watched values have actually changed, and we
5401 should stop. If not, set BS->stop to false. */
5402
5403 static void
5404 bpstat_check_watchpoint (bpstat *bs)
5405 {
5406 const struct bp_location *bl;
5407
5408 /* BS is built for existing struct breakpoint. */
5409 bl = bs->bp_location_at.get ();
5410 gdb_assert (bl != NULL);
5411 watchpoint *b = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5412
5413 bool must_check_value = false;
5414
5415 if (b->type == bp_watchpoint)
5416 /* For a software watchpoint, we must always check the
5417 watched value. */
5418 must_check_value = true;
5419 else if (b->watchpoint_triggered == watch_triggered_yes)
5420 /* We have a hardware watchpoint (read, write, or access)
5421 and the target earlier reported an address watched by
5422 this watchpoint. */
5423 must_check_value = true;
5424 else if (b->watchpoint_triggered == watch_triggered_unknown
5425 && b->type == bp_hardware_watchpoint)
5426 /* We were stopped by a hardware watchpoint, but the target could
5427 not report the data address. We must check the watchpoint's
5428 value. Access and read watchpoints are out of luck; without
5429 a data address, we can't figure it out. */
5430 must_check_value = true;
5431
5432 if (must_check_value)
5433 {
5434 wp_check_result e;
5435
5436 try
5437 {
5438 e = watchpoint_check (bs);
5439 }
5440 catch (const gdb_exception_error &ex)
5441 {
5442 exception_fprintf (gdb_stderr, ex,
5443 "Error evaluating expression "
5444 "for watchpoint %d\n",
5445 b->number);
5446
5447 SWITCH_THRU_ALL_UIS ()
5448 {
5449 gdb_printf (_("Watchpoint %d deleted.\n"),
5450 b->number);
5451 }
5452 watchpoint_del_at_next_stop (b);
5453 e = WP_DELETED;
5454 }
5455
5456 switch (e)
5457 {
5458 case WP_DELETED:
5459 /* We've already printed what needs to be printed. */
5460 bs->print_it = print_it_done;
5461 /* Stop. */
5462 break;
5463 case WP_IGNORE:
5464 bs->print_it = print_it_noop;
5465 bs->stop = false;
5466 break;
5467 case WP_VALUE_CHANGED:
5468 if (b->type == bp_read_watchpoint)
5469 {
5470 /* There are two cases to consider here:
5471
5472 1. We're watching the triggered memory for reads.
5473 In that case, trust the target, and always report
5474 the watchpoint hit to the user. Even though
5475 reads don't cause value changes, the value may
5476 have changed since the last time it was read, and
5477 since we're not trapping writes, we will not see
5478 those, and as such we should ignore our notion of
5479 old value.
5480
5481 2. We're watching the triggered memory for both
5482 reads and writes. There are two ways this may
5483 happen:
5484
5485 2.1. This is a target that can't break on data
5486 reads only, but can break on accesses (reads or
5487 writes), such as e.g., x86. We detect this case
5488 at the time we try to insert read watchpoints.
5489
5490 2.2. Otherwise, the target supports read
5491 watchpoints, but, the user set an access or write
5492 watchpoint watching the same memory as this read
5493 watchpoint.
5494
5495 If we're watching memory writes as well as reads,
5496 ignore watchpoint hits when we find that the
5497 value hasn't changed, as reads don't cause
5498 changes. This still gives false positives when
5499 the program writes the same value to memory as
5500 what there was already in memory (we will confuse
5501 it for a read), but it's much better than
5502 nothing. */
5503
5504 int other_write_watchpoint = 0;
5505
5506 if (bl->watchpoint_type == hw_read)
5507 {
5508 for (breakpoint &other_b : all_breakpoints ())
5509 if (other_b.type == bp_hardware_watchpoint
5510 || other_b.type == bp_access_watchpoint)
5511 {
5512 watchpoint &other_w =
5513 gdb::checked_static_cast<watchpoint &> (other_b);
5514
5515 if (other_w.watchpoint_triggered
5516 == watch_triggered_yes)
5517 {
5518 other_write_watchpoint = 1;
5519 break;
5520 }
5521 }
5522 }
5523
5524 if (other_write_watchpoint
5525 || bl->watchpoint_type == hw_access)
5526 {
5527 /* We're watching the same memory for writes,
5528 and the value changed since the last time we
5529 updated it, so this trap must be for a write.
5530 Ignore it. */
5531 bs->print_it = print_it_noop;
5532 bs->stop = false;
5533 }
5534 }
5535 break;
5536 case WP_VALUE_NOT_CHANGED:
5537 if (b->type == bp_hardware_watchpoint
5538 || b->type == bp_watchpoint)
5539 {
5540 /* Don't stop: write watchpoints shouldn't fire if
5541 the value hasn't changed. */
5542 bs->print_it = print_it_noop;
5543 bs->stop = false;
5544 }
5545 /* Stop. */
5546 break;
5547 default:
5548 /* Can't happen. */
5549 break;
5550 }
5551 }
5552 else /* !must_check_value */
5553 {
5554 /* This is a case where some watchpoint(s) triggered, but
5555 not at the address of this watchpoint, or else no
5556 watchpoint triggered after all. So don't print
5557 anything for this watchpoint. */
5558 bs->print_it = print_it_noop;
5559 bs->stop = false;
5560 }
5561 }
5562
5563 /* For breakpoints that are currently marked as telling gdb to stop,
5564 check conditions (condition proper, frame, thread and ignore count)
5565 of breakpoint referred to by BS. If we should not stop for this
5566 breakpoint, set BS->stop to 0. */
5567
5568 static void
5569 bpstat_check_breakpoint_conditions (bpstat *bs, thread_info *thread)
5570 {
5571 INFRUN_SCOPED_DEBUG_ENTER_EXIT;
5572
5573 const struct bp_location *bl;
5574 struct breakpoint *b;
5575 /* Assume stop. */
5576 bool condition_result = true;
5577 struct expression *cond;
5578
5579 gdb_assert (bs->stop);
5580
5581 /* BS is built for existing struct breakpoint. */
5582 bl = bs->bp_location_at.get ();
5583 gdb_assert (bl != NULL);
5584 b = bs->breakpoint_at;
5585 gdb_assert (b != NULL);
5586
5587 infrun_debug_printf ("thread = %s, breakpoint %d.%d",
5588 thread->ptid.to_string ().c_str (),
5589 b->number, find_loc_num_by_location (bl));
5590
5591 /* Even if the target evaluated the condition on its end and notified GDB, we
5592 need to do so again since GDB does not know if we stopped due to a
5593 breakpoint or a single step breakpoint. */
5594
5595 if (frame_id_p (b->frame_id)
5596 && b->frame_id != get_stack_frame_id (get_current_frame ()))
5597 {
5598 infrun_debug_printf ("incorrect frame %s not %s, not stopping",
5599 get_stack_frame_id (get_current_frame ()).to_string ().c_str (),
5600 b->frame_id.to_string ().c_str ());
5601 bs->stop = false;
5602 return;
5603 }
5604
5605 /* If this is a thread/task-specific breakpoint, don't waste cpu
5606 evaluating the condition if this isn't the specified
5607 thread/task. */
5608 if ((b->thread != -1 && b->thread != thread->global_num)
5609 || (b->inferior != -1 && b->inferior != thread->inf->num)
5610 || (b->task != -1 && b->task != ada_get_task_number (thread)))
5611 {
5612 infrun_debug_printf ("incorrect thread or task, not stopping");
5613 bs->stop = false;
5614 return;
5615 }
5616
5617 /* Evaluate extension language breakpoints that have a "stop" method
5618 implemented. */
5619 bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5620
5621 if (is_watchpoint (b))
5622 {
5623 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
5624
5625 cond = w->cond_exp.get ();
5626 }
5627 else
5628 cond = bl->cond.get ();
5629
5630 if (cond != nullptr && b->disposition != disp_del_at_next_stop)
5631 {
5632 bool within_current_scope = true;
5633
5634 /* We use scoped_value_mark because it could be a long time
5635 before we return to the command level and call
5636 free_all_values. We can't call free_all_values because we
5637 might be in the middle of evaluating a function call. */
5638 scoped_value_mark mark;
5639
5640 watchpoint *w = nullptr;
5641 if (is_watchpoint (b))
5642 w = gdb::checked_static_cast<watchpoint *> (b);
5643
5644 /* Need to select the frame, with all that implies so that
5645 the conditions will have the right context. Because we
5646 use the frame, we will not see an inlined function's
5647 variables when we arrive at a breakpoint at the start
5648 of the inlined function; the current frame will be the
5649 call site. */
5650 if (w == NULL || w->cond_exp_valid_block == NULL)
5651 select_frame (get_current_frame ());
5652 else
5653 {
5654 frame_info_ptr frame;
5655
5656 /* For local watchpoint expressions, which particular
5657 instance of a local is being watched matters, so we
5658 keep track of the frame to evaluate the expression
5659 in. To evaluate the condition however, it doesn't
5660 really matter which instantiation of the function
5661 where the condition makes sense triggers the
5662 watchpoint. This allows an expression like "watch
5663 global if q > 10" set in `func', catch writes to
5664 global on all threads that call `func', or catch
5665 writes on all recursive calls of `func' by a single
5666 thread. We simply always evaluate the condition in
5667 the innermost frame that's executing where it makes
5668 sense to evaluate the condition. It seems
5669 intuitive. */
5670 frame = block_innermost_frame (w->cond_exp_valid_block);
5671 if (frame != NULL)
5672 select_frame (frame);
5673 else
5674 within_current_scope = false;
5675 }
5676 if (within_current_scope)
5677 {
5678 try
5679 {
5680 condition_result = breakpoint_cond_eval (cond);
5681 }
5682 catch (const gdb_exception_error &ex)
5683 {
5684 int locno = bpstat_locno (bs);
5685 if (locno != 0)
5686 exception_fprintf
5687 (gdb_stderr, ex,
5688 "Error in testing condition for breakpoint %d.%d:\n",
5689 b->number, locno);
5690 else
5691 exception_fprintf
5692 (gdb_stderr, ex,
5693 "Error in testing condition for breakpoint %d:\n",
5694 b->number);
5695 }
5696 }
5697 else
5698 {
5699 warning (_("Watchpoint condition cannot be tested "
5700 "in the current scope"));
5701 /* If we failed to set the right context for this
5702 watchpoint, unconditionally report it. */
5703 }
5704 /* FIXME-someday, should give breakpoint #. */
5705 }
5706
5707 if (cond != nullptr && !condition_result)
5708 {
5709 infrun_debug_printf ("condition_result = false, not stopping");
5710 bs->stop = false;
5711 return;
5712 }
5713 else if (b->ignore_count > 0)
5714 {
5715 infrun_debug_printf ("ignore count %d, not stopping",
5716 b->ignore_count);
5717 b->ignore_count--;
5718 bs->stop = false;
5719 /* Increase the hit count even though we don't stop. */
5720 ++(b->hit_count);
5721 notify_breakpoint_modified (b);
5722 return;
5723 }
5724
5725 if (bs->stop)
5726 infrun_debug_printf ("stopping at this breakpoint");
5727 else
5728 infrun_debug_printf ("not stopping at this breakpoint");
5729 }
5730
5731 /* Returns true if we need to track moribund locations of LOC's type
5732 on the current target. */
5733
5734 static bool
5735 need_moribund_for_location_type (const struct bp_location *loc)
5736 {
5737 return ((loc->loc_type == bp_loc_software_breakpoint
5738 && !target_supports_stopped_by_sw_breakpoint ())
5739 || (loc->loc_type == bp_loc_hardware_breakpoint
5740 && !target_supports_stopped_by_hw_breakpoint ()));
5741 }
5742
5743 /* See breakpoint.h. */
5744
5745 bpstat *
5746 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5747 const target_waitstatus &ws)
5748 {
5749 bpstat *bs_head = nullptr, **bs_link = &bs_head;
5750
5751 for (breakpoint &b : all_breakpoints ())
5752 {
5753 if (!breakpoint_enabled (&b))
5754 continue;
5755
5756 for (bp_location &bl : b.locations ())
5757 {
5758 /* For hardware watchpoints, we look only at the first
5759 location. The watchpoint_check function will work on the
5760 entire expression, not the individual locations. For
5761 read watchpoints, the watchpoints_triggered function has
5762 checked all locations already. */
5763 if (b.type == bp_hardware_watchpoint && &bl != &b.first_loc ())
5764 break;
5765
5766 if (!bl.enabled || bl.disabled_by_cond || bl.shlib_disabled)
5767 continue;
5768
5769 if (!bpstat_check_location (&bl, aspace, bp_addr, ws))
5770 continue;
5771
5772 /* Come here if it's a watchpoint, or if the break address
5773 matches. */
5774
5775 bpstat *bs = new bpstat (&bl, &bs_link); /* Alloc a bpstat to
5776 explain stop. */
5777
5778 /* Assume we stop. Should we find a watchpoint that is not
5779 actually triggered, or if the condition of the breakpoint
5780 evaluates as false, we'll reset 'stop' to 0. */
5781 bs->stop = true;
5782 bs->print = true;
5783
5784 /* If this is a scope breakpoint, mark the associated
5785 watchpoint as triggered so that we will handle the
5786 out-of-scope event. We'll get to the watchpoint next
5787 iteration. */
5788 if (b.type == bp_watchpoint_scope && b.related_breakpoint != &b)
5789 {
5790 watchpoint *w
5791 = gdb::checked_static_cast<watchpoint *> (b.related_breakpoint);
5792
5793 w->watchpoint_triggered = watch_triggered_yes;
5794 }
5795 }
5796 }
5797
5798 /* Check if a moribund breakpoint explains the stop. */
5799 if (!target_supports_stopped_by_sw_breakpoint ()
5800 || !target_supports_stopped_by_hw_breakpoint ())
5801 {
5802 for (bp_location *loc : moribund_locations)
5803 {
5804 if (breakpoint_location_address_match (loc, aspace, bp_addr)
5805 && need_moribund_for_location_type (loc))
5806 {
5807 bpstat *bs = new bpstat (loc, &bs_link);
5808 /* For hits of moribund locations, we should just proceed. */
5809 bs->stop = false;
5810 bs->print = false;
5811 bs->print_it = print_it_noop;
5812 }
5813 }
5814 }
5815
5816 return bs_head;
5817 }
5818
5819 /* See breakpoint.h. */
5820
5821 bpstat *
5822 bpstat_stop_status (const address_space *aspace,
5823 CORE_ADDR bp_addr, thread_info *thread,
5824 const target_waitstatus &ws,
5825 bpstat *stop_chain)
5826 {
5827 struct breakpoint *b = NULL;
5828 /* First item of allocated bpstat's. */
5829 bpstat *bs_head = stop_chain;
5830 bpstat *bs;
5831 int need_remove_insert;
5832 int removed_any;
5833
5834 /* First, build the bpstat chain with locations that explain a
5835 target stop, while being careful to not set the target running,
5836 as that may invalidate locations (in particular watchpoint
5837 locations are recreated). Resuming will happen here with
5838 breakpoint conditions or watchpoint expressions that include
5839 inferior function calls. */
5840 if (bs_head == NULL)
5841 bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5842
5843 /* A bit of special processing for shlib breakpoints. We need to
5844 process solib loading here, so that the lists of loaded and
5845 unloaded libraries are correct before we handle "catch load" and
5846 "catch unload". */
5847 for (bs = bs_head; bs != NULL; bs = bs->next)
5848 {
5849 if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5850 {
5851 handle_solib_event ();
5852 break;
5853 }
5854 }
5855
5856 /* Now go through the locations that caused the target to stop, and
5857 check whether we're interested in reporting this stop to higher
5858 layers, or whether we should resume the target transparently. */
5859
5860 removed_any = 0;
5861
5862 for (bs = bs_head; bs != NULL; bs = bs->next)
5863 {
5864 if (!bs->stop)
5865 continue;
5866
5867 b = bs->breakpoint_at;
5868 b->check_status (bs);
5869 if (bs->stop)
5870 {
5871 bpstat_check_breakpoint_conditions (bs, thread);
5872
5873 if (bs->stop)
5874 {
5875 ++(b->hit_count);
5876
5877 /* We will stop here. */
5878 if (b->disposition == disp_disable)
5879 {
5880 --(b->enable_count);
5881 if (b->enable_count <= 0)
5882 b->enable_state = bp_disabled;
5883 removed_any = 1;
5884 }
5885 notify_breakpoint_modified (b);
5886 if (b->silent)
5887 bs->print = false;
5888 bs->commands = b->commands;
5889 if (command_line_is_silent (bs->commands
5890 ? bs->commands.get () : NULL))
5891 bs->print = false;
5892
5893 b->after_condition_true (bs);
5894 }
5895
5896 }
5897
5898 /* Print nothing for this entry if we don't stop or don't
5899 print. */
5900 if (!bs->stop || !bs->print)
5901 bs->print_it = print_it_noop;
5902 }
5903
5904 /* If we aren't stopping, the value of some hardware watchpoint may
5905 not have changed, but the intermediate memory locations we are
5906 watching may have. Don't bother if we're stopping; this will get
5907 done later. */
5908 need_remove_insert = 0;
5909 if (! bpstat_causes_stop (bs_head))
5910 for (bs = bs_head; bs != NULL; bs = bs->next)
5911 if (!bs->stop
5912 && bs->breakpoint_at
5913 && is_hardware_watchpoint (bs->breakpoint_at))
5914 {
5915 watchpoint *w
5916 = gdb::checked_static_cast<watchpoint *> (bs->breakpoint_at);
5917
5918 update_watchpoint (w, false /* don't reparse. */);
5919 need_remove_insert = 1;
5920 }
5921
5922 if (need_remove_insert)
5923 update_global_location_list (UGLL_MAY_INSERT);
5924 else if (removed_any)
5925 update_global_location_list (UGLL_DONT_INSERT);
5926
5927 return bs_head;
5928 }
5929
5930 /* See breakpoint.h. */
5931
5932 bpstat *
5933 bpstat_stop_status_nowatch (const address_space *aspace, CORE_ADDR bp_addr,
5934 thread_info *thread, const target_waitstatus &ws)
5935 {
5936 gdb_assert (!target_stopped_by_watchpoint ());
5937
5938 /* Clear all watchpoints' 'watchpoint_triggered' value from a
5939 previous stop to avoid confusing bpstat_stop_status. */
5940 watchpoints_triggered (ws);
5941
5942 return bpstat_stop_status (aspace, bp_addr, thread, ws);
5943 }
5944
5945 static void
5946 handle_jit_event (CORE_ADDR address)
5947 {
5948 struct gdbarch *gdbarch;
5949
5950 infrun_debug_printf ("handling bp_jit_event");
5951
5952 /* Switch terminal for any messages produced by
5953 breakpoint_re_set. */
5954 target_terminal::ours_for_output ();
5955
5956 gdbarch = get_frame_arch (get_current_frame ());
5957 /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5958 thus it is expected that its objectfile can be found through
5959 minimal symbol lookup. If it doesn't work (and assert fails), it
5960 most likely means that `jit_breakpoint_re_set` was changes and this
5961 function needs to be updated too. */
5962 bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5963 gdb_assert (jit_bp_sym.objfile != nullptr);
5964 objfile *objfile = jit_bp_sym.objfile;
5965 if (objfile->separate_debug_objfile_backlink)
5966 objfile = objfile->separate_debug_objfile_backlink;
5967 jit_event_handler (gdbarch, objfile);
5968
5969 target_terminal::inferior ();
5970 }
5971
5972 /* Prepare WHAT final decision for infrun. */
5973
5974 /* Decide what infrun needs to do with this bpstat. */
5975
5976 struct bpstat_what
5977 bpstat_what (bpstat *bs_head)
5978 {
5979 struct bpstat_what retval;
5980 bpstat *bs;
5981
5982 retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5983 retval.call_dummy = STOP_NONE;
5984 retval.is_longjmp = false;
5985
5986 for (bs = bs_head; bs != NULL; bs = bs->next)
5987 {
5988 /* Extract this BS's action. After processing each BS, we check
5989 if its action overrides all we've seem so far. */
5990 enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5991 enum bptype bptype;
5992
5993 if (bs->breakpoint_at == NULL)
5994 {
5995 /* I suspect this can happen if it was a momentary
5996 breakpoint which has since been deleted. */
5997 bptype = bp_none;
5998 }
5999 else
6000 bptype = bs->breakpoint_at->type;
6001
6002 switch (bptype)
6003 {
6004 case bp_none:
6005 break;
6006 case bp_breakpoint:
6007 case bp_hardware_breakpoint:
6008 case bp_single_step:
6009 case bp_until:
6010 case bp_finish:
6011 case bp_shlib_event:
6012 if (bs->stop)
6013 {
6014 if (bs->print)
6015 this_action = BPSTAT_WHAT_STOP_NOISY;
6016 else
6017 this_action = BPSTAT_WHAT_STOP_SILENT;
6018 }
6019 else
6020 this_action = BPSTAT_WHAT_SINGLE;
6021 break;
6022 case bp_watchpoint:
6023 case bp_hardware_watchpoint:
6024 case bp_read_watchpoint:
6025 case bp_access_watchpoint:
6026 if (bs->stop)
6027 {
6028 if (bs->print)
6029 this_action = BPSTAT_WHAT_STOP_NOISY;
6030 else
6031 this_action = BPSTAT_WHAT_STOP_SILENT;
6032 }
6033 else
6034 {
6035 /* There was a watchpoint, but we're not stopping.
6036 This requires no further action. */
6037 }
6038 break;
6039 case bp_longjmp:
6040 case bp_longjmp_call_dummy:
6041 case bp_exception:
6042 if (bs->stop)
6043 {
6044 this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
6045 retval.is_longjmp = bptype != bp_exception;
6046 }
6047 else
6048 this_action = BPSTAT_WHAT_SINGLE;
6049 break;
6050 case bp_longjmp_resume:
6051 case bp_exception_resume:
6052 if (bs->stop)
6053 {
6054 this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
6055 retval.is_longjmp = bptype == bp_longjmp_resume;
6056 }
6057 else
6058 this_action = BPSTAT_WHAT_SINGLE;
6059 break;
6060 case bp_step_resume:
6061 if (bs->stop)
6062 this_action = BPSTAT_WHAT_STEP_RESUME;
6063 else
6064 {
6065 /* It is for the wrong frame. */
6066 this_action = BPSTAT_WHAT_SINGLE;
6067 }
6068 break;
6069 case bp_hp_step_resume:
6070 if (bs->stop)
6071 this_action = BPSTAT_WHAT_HP_STEP_RESUME;
6072 else
6073 {
6074 /* It is for the wrong frame. */
6075 this_action = BPSTAT_WHAT_SINGLE;
6076 }
6077 break;
6078 case bp_watchpoint_scope:
6079 case bp_thread_event:
6080 case bp_overlay_event:
6081 case bp_longjmp_master:
6082 case bp_std_terminate_master:
6083 case bp_exception_master:
6084 this_action = BPSTAT_WHAT_SINGLE;
6085 break;
6086 case bp_catchpoint:
6087 if (bs->stop)
6088 {
6089 if (bs->print)
6090 this_action = BPSTAT_WHAT_STOP_NOISY;
6091 else
6092 this_action = BPSTAT_WHAT_STOP_SILENT;
6093 }
6094 else
6095 {
6096 /* Some catchpoints are implemented with breakpoints.
6097 For those, we need to step over the breakpoint. */
6098 if (bs->bp_location_at->loc_type == bp_loc_software_breakpoint
6099 || bs->bp_location_at->loc_type == bp_loc_hardware_breakpoint)
6100 this_action = BPSTAT_WHAT_SINGLE;
6101 }
6102 break;
6103 case bp_jit_event:
6104 this_action = BPSTAT_WHAT_SINGLE;
6105 break;
6106 case bp_call_dummy:
6107 /* Make sure the action is stop (silent or noisy),
6108 so infrun.c pops the dummy frame. */
6109 retval.call_dummy = STOP_STACK_DUMMY;
6110 this_action = BPSTAT_WHAT_STOP_SILENT;
6111 break;
6112 case bp_std_terminate:
6113 /* Make sure the action is stop (silent or noisy),
6114 so infrun.c pops the dummy frame. */
6115 retval.call_dummy = STOP_STD_TERMINATE;
6116 this_action = BPSTAT_WHAT_STOP_SILENT;
6117 break;
6118 case bp_tracepoint:
6119 case bp_fast_tracepoint:
6120 case bp_static_tracepoint:
6121 case bp_static_marker_tracepoint:
6122 /* Tracepoint hits should not be reported back to GDB, and
6123 if one got through somehow, it should have been filtered
6124 out already. */
6125 internal_error (_("bpstat_what: tracepoint encountered"));
6126 break;
6127 case bp_gnu_ifunc_resolver:
6128 /* Step over it (and insert bp_gnu_ifunc_resolver_return). */
6129 this_action = BPSTAT_WHAT_SINGLE;
6130 break;
6131 case bp_gnu_ifunc_resolver_return:
6132 /* The breakpoint will be removed, execution will restart from the
6133 PC of the former breakpoint. */
6134 this_action = BPSTAT_WHAT_KEEP_CHECKING;
6135 break;
6136
6137 case bp_dprintf:
6138 if (bs->stop)
6139 this_action = BPSTAT_WHAT_STOP_SILENT;
6140 else
6141 this_action = BPSTAT_WHAT_SINGLE;
6142 break;
6143
6144 default:
6145 internal_error (_("bpstat_what: unhandled bptype %d"), (int) bptype);
6146 }
6147
6148 retval.main_action = std::max (retval.main_action, this_action);
6149 }
6150
6151 return retval;
6152 }
6153
6154 void
6155 bpstat_run_callbacks (bpstat *bs_head)
6156 {
6157 bpstat *bs;
6158
6159 for (bs = bs_head; bs != NULL; bs = bs->next)
6160 {
6161 struct breakpoint *b = bs->breakpoint_at;
6162
6163 if (b == NULL)
6164 continue;
6165 switch (b->type)
6166 {
6167 case bp_jit_event:
6168 handle_jit_event (bs->bp_location_at->address);
6169 break;
6170 case bp_gnu_ifunc_resolver:
6171 gnu_ifunc_resolver_stop
6172 (gdb::checked_static_cast<code_breakpoint *> (b));
6173 break;
6174 case bp_gnu_ifunc_resolver_return:
6175 gnu_ifunc_resolver_return_stop
6176 (gdb::checked_static_cast<code_breakpoint *> (b));
6177 break;
6178 }
6179 }
6180 }
6181
6182 /* See breakpoint.h. */
6183
6184 bool
6185 bpstat_should_step ()
6186 {
6187 for (breakpoint &b : all_breakpoints ())
6188 if (breakpoint_enabled (&b)
6189 && b.type == bp_watchpoint
6190 && b.has_locations ())
6191 return true;
6192
6193 return false;
6194 }
6195
6196 /* See breakpoint.h. */
6197
6198 bool
6199 bpstat_causes_stop (bpstat *bs)
6200 {
6201 for (; bs != NULL; bs = bs->next)
6202 if (bs->stop)
6203 return true;
6204
6205 return false;
6206 }
6207
6208 \f
6209
6210 /* Compute a number of spaces suitable to indent the next line
6211 so it starts at the position corresponding to the table column
6212 named COL_NAME in the currently active table of UIOUT. */
6213
6214 static int
6215 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
6216 {
6217 int i, total_width, width, align;
6218 const char *text;
6219
6220 total_width = 0;
6221 for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
6222 {
6223 if (strcmp (text, col_name) == 0)
6224 return total_width;
6225
6226 total_width += width + 1;
6227 }
6228
6229 return 0;
6230 }
6231
6232 /* Determine if the locations of this breakpoint will have their conditions
6233 evaluated by the target, host or a mix of both. Returns the following:
6234
6235 "host": Host evals condition.
6236 "host or target": Host or Target evals condition.
6237 "target": Target evals condition.
6238 */
6239
6240 static const char *
6241 bp_condition_evaluator (const breakpoint *b)
6242 {
6243 char host_evals = 0;
6244 char target_evals = 0;
6245
6246 if (!b)
6247 return NULL;
6248
6249 if (!is_breakpoint (b))
6250 return NULL;
6251
6252 if (gdb_evaluates_breakpoint_condition_p ()
6253 || !target_supports_evaluation_of_breakpoint_conditions ())
6254 return condition_evaluation_host;
6255
6256 for (bp_location &bl : b->locations ())
6257 {
6258 if (bl.cond_bytecode)
6259 target_evals++;
6260 else
6261 host_evals++;
6262 }
6263
6264 if (host_evals && target_evals)
6265 return condition_evaluation_both;
6266 else if (target_evals)
6267 return condition_evaluation_target;
6268 else
6269 return condition_evaluation_host;
6270 }
6271
6272 /* Determine the breakpoint location's condition evaluator. This is
6273 similar to bp_condition_evaluator, but for locations. */
6274
6275 static const char *
6276 bp_location_condition_evaluator (const struct bp_location *bl)
6277 {
6278 if (bl && !is_breakpoint (bl->owner))
6279 return NULL;
6280
6281 if (gdb_evaluates_breakpoint_condition_p ()
6282 || !target_supports_evaluation_of_breakpoint_conditions ())
6283 return condition_evaluation_host;
6284
6285 if (bl && bl->cond_bytecode)
6286 return condition_evaluation_target;
6287 else
6288 return condition_evaluation_host;
6289 }
6290
6291 /* Print the LOC location out of the list of B->LOC locations. */
6292
6293 static void
6294 print_breakpoint_location (const breakpoint *b, const bp_location *loc)
6295 {
6296 struct ui_out *uiout = current_uiout;
6297
6298 scoped_restore_current_program_space restore_pspace;
6299
6300 if (loc != NULL && loc->shlib_disabled)
6301 loc = NULL;
6302
6303 if (loc != NULL)
6304 set_current_program_space (loc->pspace);
6305
6306 if (b->display_canonical)
6307 uiout->field_string ("what", b->locspec->to_string ());
6308 else if (loc && loc->symtab)
6309 {
6310 const struct symbol *sym = loc->symbol;
6311
6312 if (sym)
6313 {
6314 uiout->text ("in ");
6315 uiout->field_string ("func", sym->print_name (),
6316 function_name_style.style ());
6317 uiout->text (" ");
6318 uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
6319 uiout->text ("at ");
6320 }
6321 uiout->field_string ("file",
6322 symtab_to_filename_for_display (loc->symtab),
6323 file_name_style.style ());
6324 uiout->text (":");
6325
6326 if (uiout->is_mi_like_p ())
6327 uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
6328
6329 uiout->field_signed ("line", loc->line_number);
6330 }
6331 else if (loc)
6332 {
6333 string_file stb;
6334
6335 print_address_symbolic (loc->gdbarch, loc->address, &stb,
6336 demangle, "");
6337 uiout->field_stream ("at", stb);
6338 }
6339 else
6340 {
6341 uiout->field_string ("pending", b->locspec->to_string ());
6342 /* If extra_string is available, it could be holding a condition
6343 or dprintf arguments. In either case, make sure it is printed,
6344 too, but only for non-MI streams. */
6345 if (!uiout->is_mi_like_p () && b->extra_string != NULL)
6346 {
6347 if (b->type == bp_dprintf)
6348 uiout->text (",");
6349 else
6350 uiout->text (" ");
6351 uiout->text (b->extra_string.get ());
6352 }
6353 }
6354
6355 if (loc && is_breakpoint (b)
6356 && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6357 && bp_condition_evaluator (b) == condition_evaluation_both)
6358 {
6359 uiout->text (" (");
6360 uiout->field_string ("evaluated-by",
6361 bp_location_condition_evaluator (loc));
6362 uiout->text (")");
6363 }
6364 }
6365
6366 static const char *
6367 bptype_string (enum bptype type)
6368 {
6369 struct ep_type_description
6370 {
6371 enum bptype type;
6372 const char *description;
6373 };
6374 static struct ep_type_description bptypes[] =
6375 {
6376 {bp_none, "?deleted?"},
6377 {bp_breakpoint, "breakpoint"},
6378 {bp_hardware_breakpoint, "hw breakpoint"},
6379 {bp_single_step, "sw single-step"},
6380 {bp_until, "until"},
6381 {bp_finish, "finish"},
6382 {bp_watchpoint, "watchpoint"},
6383 {bp_hardware_watchpoint, "hw watchpoint"},
6384 {bp_read_watchpoint, "read watchpoint"},
6385 {bp_access_watchpoint, "acc watchpoint"},
6386 {bp_longjmp, "longjmp"},
6387 {bp_longjmp_resume, "longjmp resume"},
6388 {bp_longjmp_call_dummy, "longjmp for call dummy"},
6389 {bp_exception, "exception"},
6390 {bp_exception_resume, "exception resume"},
6391 {bp_step_resume, "step resume"},
6392 {bp_hp_step_resume, "high-priority step resume"},
6393 {bp_watchpoint_scope, "watchpoint scope"},
6394 {bp_call_dummy, "call dummy"},
6395 {bp_std_terminate, "std::terminate"},
6396 {bp_shlib_event, "shlib events"},
6397 {bp_thread_event, "thread events"},
6398 {bp_overlay_event, "overlay events"},
6399 {bp_longjmp_master, "longjmp master"},
6400 {bp_std_terminate_master, "std::terminate master"},
6401 {bp_exception_master, "exception master"},
6402 {bp_catchpoint, "catchpoint"},
6403 {bp_tracepoint, "tracepoint"},
6404 {bp_fast_tracepoint, "fast tracepoint"},
6405 {bp_static_tracepoint, "static tracepoint"},
6406 {bp_static_marker_tracepoint, "static marker tracepoint"},
6407 {bp_dprintf, "dprintf"},
6408 {bp_jit_event, "jit events"},
6409 {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6410 {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6411 };
6412
6413 if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6414 || ((int) type != bptypes[(int) type].type))
6415 internal_error (_("bptypes table does not describe type #%d."),
6416 (int) type);
6417
6418 return bptypes[(int) type].description;
6419 }
6420
6421 /* For MI, output a field named 'thread-groups' with a list as the value.
6422 For CLI, prefix the list with the string 'inf'. */
6423
6424 static void
6425 output_thread_groups (struct ui_out *uiout,
6426 const char *field_name,
6427 const std::vector<int> &inf_nums,
6428 int mi_only)
6429 {
6430 int is_mi = uiout->is_mi_like_p ();
6431
6432 /* For backward compatibility, don't display inferiors in CLI unless
6433 there are several. Always display them for MI. */
6434 if (!is_mi && mi_only)
6435 return;
6436
6437 ui_out_emit_list list_emitter (uiout, field_name);
6438
6439 for (size_t i = 0; i < inf_nums.size (); i++)
6440 {
6441 if (is_mi)
6442 {
6443 char mi_group[10];
6444
6445 xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6446 uiout->field_string (NULL, mi_group);
6447 }
6448 else
6449 {
6450 if (i == 0)
6451 uiout->text (" inf ");
6452 else
6453 uiout->text (", ");
6454
6455 uiout->text (plongest (inf_nums[i]));
6456 }
6457 }
6458 }
6459
6460 /* See breakpoint.h. */
6461
6462 bool fix_breakpoint_script_output_globally = false;
6463
6464 /* Print B to gdb_stdout. If RAW_LOC, print raw breakpoint locations
6465 instead of going via breakpoint_ops::print_one. This makes "maint
6466 info breakpoints" show the software breakpoint locations of
6467 catchpoints, which are considered internal implementation
6468 detail. Returns true if RAW_LOC is false and if the breakpoint's
6469 print_one method did something; false otherwise. */
6470
6471 static bool
6472 print_one_breakpoint_location (struct breakpoint *b,
6473 struct bp_location *loc,
6474 int loc_number,
6475 const bp_location **last_loc,
6476 int allflag, bool raw_loc)
6477 {
6478 struct command_line *l;
6479 static char bpenables[] = "nynny";
6480
6481 struct ui_out *uiout = current_uiout;
6482 bool header_of_multiple = false;
6483 bool part_of_multiple = (loc != NULL);
6484 struct value_print_options opts;
6485
6486 get_user_print_options (&opts);
6487
6488 gdb_assert (!loc || loc_number != 0);
6489 /* See comment in print_one_breakpoint concerning treatment of
6490 breakpoints with single disabled location. */
6491 if (loc == NULL
6492 && (b->has_locations ()
6493 && (b->has_multiple_locations ()
6494 || !b->first_loc ().enabled || b->first_loc ().disabled_by_cond)))
6495 header_of_multiple = true;
6496
6497 if (loc == NULL && b->has_locations ())
6498 loc = &b->first_loc ();
6499
6500 annotate_record ();
6501
6502 /* 1 */
6503 annotate_field (0);
6504 if (part_of_multiple)
6505 uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6506 else
6507 uiout->field_signed ("number", b->number);
6508
6509 /* 2 */
6510 annotate_field (1);
6511 if (part_of_multiple)
6512 uiout->field_skip ("type");
6513 else
6514 uiout->field_string ("type", bptype_string (b->type));
6515
6516 /* 3 */
6517 annotate_field (2);
6518 if (part_of_multiple)
6519 uiout->field_skip ("disp");
6520 else
6521 uiout->field_string ("disp", bpdisp_text (b->disposition));
6522
6523 /* 4 */
6524 annotate_field (3);
6525 if (part_of_multiple)
6526 {
6527 /* For locations that are disabled because of an invalid
6528 condition, display "N*" on the CLI, where "*" refers to a
6529 footnote below the table. For MI, simply display a "N"
6530 without a footnote. On the CLI, for enabled locations whose
6531 breakpoint is disabled, display "y-". */
6532 auto get_enable_state = [uiout, loc] () -> const char *
6533 {
6534 if (uiout->is_mi_like_p ())
6535 {
6536 if (loc->disabled_by_cond)
6537 return "N";
6538 else if (!loc->enabled)
6539 return "n";
6540 else
6541 return "y";
6542 }
6543 else
6544 {
6545 if (loc->disabled_by_cond)
6546 return "N*";
6547 else if (!loc->enabled)
6548 return "n";
6549 else if (!breakpoint_enabled (loc->owner))
6550 return "y-";
6551 else
6552 return "y";
6553 }
6554 };
6555 uiout->field_string ("enabled", get_enable_state ());
6556 }
6557 else
6558 uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6559
6560 /* 5 and 6 */
6561 bool result = false;
6562 if (!raw_loc && b->print_one (last_loc))
6563 result = true;
6564 else
6565 {
6566 if (is_watchpoint (b))
6567 {
6568 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
6569
6570 /* Field 4, the address, is omitted (which makes the columns
6571 not line up too nicely with the headers, but the effect
6572 is relatively readable). */
6573 if (opts.addressprint)
6574 uiout->field_skip ("addr");
6575 annotate_field (5);
6576 uiout->field_string ("what", w->exp_string.get ());
6577 }
6578 else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6579 || is_ada_exception_catchpoint (b))
6580 {
6581 if (opts.addressprint)
6582 {
6583 annotate_field (4);
6584 if (header_of_multiple)
6585 uiout->field_string ("addr", "<MULTIPLE>",
6586 metadata_style.style ());
6587 else if (!b->has_locations () || loc->shlib_disabled)
6588 uiout->field_string ("addr", "<PENDING>",
6589 metadata_style.style ());
6590 else
6591 uiout->field_core_addr ("addr",
6592 loc->gdbarch, loc->address);
6593 }
6594 annotate_field (5);
6595 if (!header_of_multiple)
6596 print_breakpoint_location (b, loc);
6597 if (b->has_locations ())
6598 *last_loc = &b->first_loc ();
6599 }
6600 }
6601
6602 if (loc != NULL && !header_of_multiple)
6603 {
6604 std::vector<int> inf_nums;
6605 int mi_only = 1;
6606
6607 for (inferior *inf : all_inferiors ())
6608 {
6609 if (inf->pspace == loc->pspace)
6610 inf_nums.push_back (inf->num);
6611 }
6612
6613 /* For backward compatibility, don't display inferiors in CLI unless
6614 there are several. Always display for MI. */
6615 if (allflag
6616 || (!gdbarch_has_global_breakpoints (current_inferior ()->arch ())
6617 && (program_spaces.size () > 1
6618 || number_of_inferiors () > 1)
6619 /* LOC is for existing B, it cannot be in
6620 moribund_locations and thus having NULL OWNER. */
6621 && loc->owner->type != bp_catchpoint))
6622 mi_only = 0;
6623 output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6624 }
6625
6626 /* In the MI output, each location of a thread or task specific
6627 breakpoint includes the relevant thread or task ID. This is done for
6628 backwards compatibility reasons.
6629
6630 For the CLI output, the thread/task information is printed on a
6631 separate line, see the 'stop only in thread' and 'stop only in task'
6632 output below. */
6633 if (part_of_multiple && uiout->is_mi_like_p ())
6634 {
6635 if (b->thread != -1)
6636 uiout->field_signed ("thread", b->thread);
6637 else if (b->task != -1)
6638 uiout->field_signed ("task", b->task);
6639 else if (b->inferior != -1)
6640 uiout->field_signed ("inferior", b->inferior);
6641 }
6642
6643 uiout->text ("\n");
6644
6645 if (!part_of_multiple)
6646 b->print_one_detail (uiout);
6647
6648 if (part_of_multiple && frame_id_p (b->frame_id))
6649 {
6650 annotate_field (6);
6651 uiout->text ("\tstop only in stack frame at ");
6652 /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6653 the frame ID. */
6654 uiout->field_core_addr ("frame",
6655 b->gdbarch, b->frame_id.stack_addr);
6656 uiout->text ("\n");
6657 }
6658
6659 if (!part_of_multiple && b->cond_string)
6660 {
6661 annotate_field (7);
6662 if (is_tracepoint (b))
6663 uiout->text ("\ttrace only if ");
6664 else
6665 uiout->text ("\tstop only if ");
6666 uiout->field_string ("cond", b->cond_string.get ());
6667
6668 /* Print whether the target is doing the breakpoint's condition
6669 evaluation. If GDB is doing the evaluation, don't print anything. */
6670 if (is_breakpoint (b)
6671 && breakpoint_condition_evaluation_mode ()
6672 == condition_evaluation_target)
6673 {
6674 uiout->message (" (%pF evals)",
6675 string_field ("evaluated-by",
6676 bp_condition_evaluator (b)));
6677 }
6678 uiout->text ("\n");
6679 }
6680
6681 if (!part_of_multiple && b->thread != -1)
6682 {
6683 /* FIXME should make an annotation for this. */
6684 uiout->text ("\tstop only in thread ");
6685 if (uiout->is_mi_like_p ())
6686 uiout->field_signed ("thread", b->thread);
6687 else
6688 {
6689 struct thread_info *thr = find_thread_global_id (b->thread);
6690
6691 uiout->field_string ("thread", print_thread_id (thr));
6692 }
6693 uiout->text ("\n");
6694 }
6695
6696 if (!part_of_multiple && b->task != -1)
6697 {
6698 uiout->text ("\tstop only in task ");
6699 uiout->field_signed ("task", b->task);
6700 uiout->text ("\n");
6701 }
6702
6703 if (!part_of_multiple && b->inferior != -1)
6704 {
6705 uiout->text ("\tstop only in inferior ");
6706 uiout->field_signed ("inferior", b->inferior);
6707 uiout->text ("\n");
6708 }
6709
6710 if (!part_of_multiple)
6711 {
6712 if (b->hit_count)
6713 {
6714 /* FIXME should make an annotation for this. */
6715 if (is_catchpoint (b))
6716 uiout->text ("\tcatchpoint");
6717 else if (is_tracepoint (b))
6718 uiout->text ("\ttracepoint");
6719 else
6720 uiout->text ("\tbreakpoint");
6721 uiout->text (" already hit ");
6722 uiout->field_signed ("times", b->hit_count);
6723 if (b->hit_count == 1)
6724 uiout->text (" time\n");
6725 else
6726 uiout->text (" times\n");
6727 }
6728 else
6729 {
6730 /* Output the count also if it is zero, but only if this is mi. */
6731 if (uiout->is_mi_like_p ())
6732 uiout->field_signed ("times", b->hit_count);
6733 }
6734 }
6735
6736 if (!part_of_multiple && b->ignore_count)
6737 {
6738 annotate_field (8);
6739 uiout->message ("\tignore next %pF hits\n",
6740 signed_field ("ignore", b->ignore_count));
6741 }
6742
6743 /* Note that an enable count of 1 corresponds to "enable once"
6744 behavior, which is reported by the combination of enablement and
6745 disposition, so we don't need to mention it here. */
6746 if (!part_of_multiple && b->enable_count > 1)
6747 {
6748 annotate_field (8);
6749 uiout->text ("\tdisable after ");
6750 /* Tweak the wording to clarify that ignore and enable counts
6751 are distinct, and have additive effect. */
6752 if (b->ignore_count)
6753 uiout->text ("additional ");
6754 else
6755 uiout->text ("next ");
6756 uiout->field_signed ("enable", b->enable_count);
6757 uiout->text (" hits\n");
6758 }
6759
6760 if (!part_of_multiple && is_tracepoint (b))
6761 {
6762 tracepoint *tp = gdb::checked_static_cast<tracepoint *> (b);
6763
6764 if (tp->traceframe_usage)
6765 {
6766 uiout->text ("\ttrace buffer usage ");
6767 uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6768 uiout->text (" bytes\n");
6769 }
6770 }
6771
6772 l = b->commands ? b->commands.get () : NULL;
6773 if (!part_of_multiple && l)
6774 {
6775 annotate_field (9);
6776
6777 bool use_fixed_output =
6778 (uiout->test_flags (fix_breakpoint_script_output)
6779 || fix_breakpoint_script_output_globally);
6780
6781 std::optional<ui_out_emit_tuple> tuple_emitter;
6782 std::optional<ui_out_emit_list> list_emitter;
6783
6784 if (use_fixed_output)
6785 list_emitter.emplace (uiout, "script");
6786 else
6787 tuple_emitter.emplace (uiout, "script");
6788
6789 print_command_lines (uiout, l, 4);
6790 }
6791
6792 if (is_tracepoint (b))
6793 {
6794 tracepoint *t = gdb::checked_static_cast<tracepoint *> (b);
6795
6796 if (!part_of_multiple && t->pass_count)
6797 {
6798 annotate_field (10);
6799 uiout->text ("\tpass count ");
6800 uiout->field_signed ("pass", t->pass_count);
6801 uiout->text (" \n");
6802 }
6803
6804 /* Don't display it when tracepoint or tracepoint location is
6805 pending. */
6806 if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6807 {
6808 annotate_field (11);
6809
6810 if (uiout->is_mi_like_p ())
6811 uiout->field_string ("installed",
6812 loc->inserted ? "y" : "n");
6813 else
6814 {
6815 if (loc->inserted)
6816 uiout->text ("\t");
6817 else
6818 uiout->text ("\tnot ");
6819 uiout->text ("installed on target\n");
6820 }
6821 }
6822 }
6823
6824 if (uiout->is_mi_like_p () && !part_of_multiple)
6825 {
6826 if (is_watchpoint (b))
6827 {
6828 watchpoint *w = gdb::checked_static_cast<watchpoint *> (b);
6829
6830 uiout->field_string ("original-location", w->exp_string.get ());
6831 }
6832 else if (b->locspec != nullptr)
6833 {
6834 const char *str = b->locspec->to_string ();
6835 if (str != nullptr)
6836 uiout->field_string ("original-location", str);
6837 }
6838 }
6839
6840 return result;
6841 }
6842
6843 /* See breakpoint.h. */
6844
6845 bool fix_multi_location_breakpoint_output_globally = false;
6846
6847 static void
6848 print_one_breakpoint (breakpoint *b, const bp_location **last_loc, int allflag)
6849 {
6850 struct ui_out *uiout = current_uiout;
6851 bool use_fixed_output
6852 = (uiout->test_flags (fix_multi_location_breakpoint_output)
6853 || fix_multi_location_breakpoint_output_globally);
6854
6855 std::optional<ui_out_emit_tuple> bkpt_tuple_emitter (std::in_place, uiout,
6856 "bkpt");
6857 bool printed = print_one_breakpoint_location (b, NULL, 0, last_loc,
6858 allflag, false);
6859
6860 /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6861 are outside. */
6862 if (!use_fixed_output)
6863 bkpt_tuple_emitter.reset ();
6864
6865 /* If this breakpoint has custom print function,
6866 it's already printed. Otherwise, print individual
6867 locations, if any. */
6868 if (!printed || allflag)
6869 {
6870 /* If breakpoint has a single location that is disabled, we
6871 print it as if it had several locations, since otherwise it's
6872 hard to represent "breakpoint enabled, location disabled"
6873 situation.
6874
6875 Note that while hardware watchpoints have several locations
6876 internally, that's not a property exposed to users.
6877
6878 Likewise, while catchpoints may be implemented with
6879 breakpoints (e.g., catch throw), that's not a property
6880 exposed to users. We do however display the internal
6881 breakpoint locations with "maint info breakpoints". */
6882 if (!is_hardware_watchpoint (b)
6883 && (!is_catchpoint (b) || is_exception_catchpoint (b)
6884 || is_ada_exception_catchpoint (b))
6885 && (allflag
6886 || (b->has_locations ()
6887 && (b->has_multiple_locations ()
6888 || !b->first_loc ().enabled
6889 || b->first_loc ().disabled_by_cond))))
6890 {
6891 std::optional<ui_out_emit_list> locations_list;
6892
6893 /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6894 MI record. For later versions, place breakpoint locations in a
6895 list. */
6896 if (uiout->is_mi_like_p () && use_fixed_output)
6897 locations_list.emplace (uiout, "locations");
6898
6899 int n = 1;
6900 for (bp_location &loc : b->locations ())
6901 {
6902 ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6903 print_one_breakpoint_location (b, &loc, n, last_loc,
6904 allflag, allflag);
6905 n++;
6906 }
6907 }
6908 }
6909 }
6910
6911 static int
6912 breakpoint_address_bits (struct breakpoint *b)
6913 {
6914 int print_address_bits = 0;
6915
6916 for (bp_location &loc : b->locations ())
6917 {
6918 if (!bl_address_is_meaningful (&loc))
6919 continue;
6920
6921 int addr_bit = gdbarch_addr_bit (loc.gdbarch);
6922 if (addr_bit > print_address_bits)
6923 print_address_bits = addr_bit;
6924 }
6925
6926 return print_address_bits;
6927 }
6928
6929 /* See breakpoint.h. */
6930
6931 void
6932 print_breakpoint (breakpoint *b)
6933 {
6934 const bp_location *dummy_loc = nullptr;
6935 print_one_breakpoint (b, &dummy_loc, 0);
6936 }
6937
6938 /* Return true if this breakpoint was set by the user, false if it is
6939 internal or momentary. */
6940
6941 int
6942 user_breakpoint_p (struct breakpoint *b)
6943 {
6944 return b->number > 0;
6945 }
6946
6947 /* See breakpoint.h. */
6948
6949 int
6950 pending_breakpoint_p (struct breakpoint *b)
6951 {
6952 return !b->has_locations ();
6953 }
6954
6955 /* Print information on breakpoints (including watchpoints and tracepoints).
6956
6957 If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6958 understood by number_or_range_parser. Only breakpoints included in this
6959 list are then printed.
6960
6961 If SHOW_INTERNAL is true, print internal breakpoints.
6962
6963 If FILTER is non-NULL, call it on each breakpoint and only include the
6964 ones for which it returns true.
6965
6966 Return the total number of breakpoints listed. */
6967
6968 static int
6969 breakpoint_1 (const char *bp_num_list, bool show_internal,
6970 bool (*filter) (const struct breakpoint *))
6971 {
6972 const bp_location *last_loc = nullptr;
6973 int nr_printable_breakpoints;
6974 struct value_print_options opts;
6975 int print_address_bits = 0;
6976 int print_type_col_width = 14;
6977 struct ui_out *uiout = current_uiout;
6978 bool has_disabled_by_cond_location = false;
6979
6980 get_user_print_options (&opts);
6981
6982 /* Compute the number of rows in the table, as well as the size
6983 required for address fields. */
6984 nr_printable_breakpoints = 0;
6985 for (breakpoint &b : all_breakpoints ())
6986 {
6987 /* If we have a filter, only list the breakpoints it accepts. */
6988 if (filter && !filter (&b))
6989 continue;
6990
6991 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6992 accept. Skip the others. */
6993 if (bp_num_list != NULL && *bp_num_list != '\0')
6994 {
6995 if (show_internal && parse_and_eval_long (bp_num_list) != b.number)
6996 continue;
6997 if (!show_internal && !number_is_in_list (bp_num_list, b.number))
6998 continue;
6999 }
7000
7001 if (show_internal || user_breakpoint_p (&b))
7002 {
7003 int addr_bit, type_len;
7004
7005 addr_bit = breakpoint_address_bits (&b);
7006 if (addr_bit > print_address_bits)
7007 print_address_bits = addr_bit;
7008
7009 type_len = strlen (bptype_string (b.type));
7010 if (type_len > print_type_col_width)
7011 print_type_col_width = type_len;
7012
7013 nr_printable_breakpoints++;
7014 }
7015 }
7016
7017 {
7018 ui_out_emit_table table_emitter (uiout,
7019 opts.addressprint ? 6 : 5,
7020 nr_printable_breakpoints,
7021 "BreakpointTable");
7022
7023 if (nr_printable_breakpoints > 0)
7024 annotate_breakpoints_headers ();
7025 if (nr_printable_breakpoints > 0)
7026 annotate_field (0);
7027 uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
7028 if (nr_printable_breakpoints > 0)
7029 annotate_field (1);
7030 uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
7031 if (nr_printable_breakpoints > 0)
7032 annotate_field (2);
7033 uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
7034 if (nr_printable_breakpoints > 0)
7035 annotate_field (3);
7036 uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
7037 if (opts.addressprint)
7038 {
7039 if (nr_printable_breakpoints > 0)
7040 annotate_field (4);
7041 if (print_address_bits <= 32)
7042 uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
7043 else
7044 uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
7045 }
7046 if (nr_printable_breakpoints > 0)
7047 annotate_field (5);
7048 uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
7049 uiout->table_body ();
7050 if (nr_printable_breakpoints > 0)
7051 annotate_breakpoints_table ();
7052
7053 for (breakpoint &b : all_breakpoints ())
7054 {
7055 QUIT;
7056 /* If we have a filter, only list the breakpoints it accepts. */
7057 if (filter && !filter (&b))
7058 continue;
7059
7060 /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
7061 accept. Skip the others. */
7062
7063 if (bp_num_list != NULL && *bp_num_list != '\0')
7064 {
7065 if (show_internal) /* maintenance info breakpoint */
7066 {
7067 if (parse_and_eval_long (bp_num_list) != b.number)
7068 continue;
7069 }
7070 else /* all others */
7071 {
7072 if (!number_is_in_list (bp_num_list, b.number))
7073 continue;
7074 }
7075 }
7076 /* We only print out user settable breakpoints unless the
7077 show_internal is set. */
7078 if (show_internal || user_breakpoint_p (&b))
7079 {
7080 print_one_breakpoint (&b, &last_loc, show_internal);
7081 for (bp_location &loc : b.locations ())
7082 if (loc.disabled_by_cond)
7083 has_disabled_by_cond_location = true;
7084 }
7085 }
7086 }
7087
7088 if (nr_printable_breakpoints == 0)
7089 {
7090 /* If there's a filter, let the caller decide how to report
7091 empty list. */
7092 if (!filter)
7093 {
7094 if (bp_num_list == NULL || *bp_num_list == '\0')
7095 uiout->message ("No breakpoints or watchpoints.\n");
7096 else
7097 uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
7098 bp_num_list);
7099 }
7100 }
7101 else
7102 {
7103 if (last_loc && !server_command)
7104 set_next_address (last_loc->gdbarch, last_loc->address);
7105
7106 if (has_disabled_by_cond_location && !uiout->is_mi_like_p ())
7107 uiout->message (_("(*): Breakpoint condition is invalid at this "
7108 "location.\n"));
7109 }
7110
7111 /* FIXME? Should this be moved up so that it is only called when
7112 there have been breakpoints? */
7113 annotate_breakpoints_table_end ();
7114
7115 return nr_printable_breakpoints;
7116 }
7117
7118 /* Display the value of default-collect in a way that is generally
7119 compatible with the breakpoint list. */
7120
7121 static void
7122 default_collect_info (void)
7123 {
7124 struct ui_out *uiout = current_uiout;
7125
7126 /* If it has no value (which is frequently the case), say nothing; a
7127 message like "No default-collect." gets in user's face when it's
7128 not wanted. */
7129 if (default_collect.empty ())
7130 return;
7131
7132 /* The following phrase lines up nicely with per-tracepoint collect
7133 actions. */
7134 uiout->text ("default collect ");
7135 uiout->field_string ("default-collect", default_collect);
7136 uiout->text (" \n");
7137 }
7138
7139 static void
7140 info_breakpoints_command (const char *args, int from_tty)
7141 {
7142 breakpoint_1 (args, false, NULL);
7143
7144 default_collect_info ();
7145 }
7146
7147 static void
7148 info_watchpoints_command (const char *args, int from_tty)
7149 {
7150 int num_printed = breakpoint_1 (args, false, is_watchpoint);
7151 struct ui_out *uiout = current_uiout;
7152
7153 if (num_printed == 0)
7154 {
7155 if (args == NULL || *args == '\0')
7156 uiout->message ("No watchpoints.\n");
7157 else
7158 uiout->message ("No watchpoint matching '%s'.\n", args);
7159 }
7160 }
7161
7162 static void
7163 maintenance_info_breakpoints (const char *args, int from_tty)
7164 {
7165 breakpoint_1 (args, true, NULL);
7166
7167 default_collect_info ();
7168 }
7169
7170 static bool
7171 breakpoint_has_pc (struct breakpoint *b,
7172 struct program_space *pspace,
7173 CORE_ADDR pc, struct obj_section *section)
7174 {
7175 for (bp_location &bl : b->locations ())
7176 {
7177 if (bl.pspace == pspace
7178 && bl.address == pc
7179 && (!overlay_debugging || bl.section == section))
7180 return true;
7181 }
7182 return false;
7183 }
7184
7185 /* See breakpoint.h. */
7186
7187 void
7188 describe_other_breakpoints (struct gdbarch *gdbarch,
7189 struct program_space *pspace, CORE_ADDR pc,
7190 struct obj_section *section, int thread)
7191 {
7192 int others = 0;
7193
7194 for (breakpoint &b : all_breakpoints ())
7195 others += (user_breakpoint_p (&b)
7196 && breakpoint_has_pc (&b, pspace, pc, section));
7197
7198 if (others > 0)
7199 {
7200 if (others == 1)
7201 gdb_printf (_("Note: breakpoint "));
7202 else /* if (others == ???) */
7203 gdb_printf (_("Note: breakpoints "));
7204 for (breakpoint &b : all_breakpoints ())
7205 if (user_breakpoint_p (&b)
7206 && breakpoint_has_pc (&b, pspace, pc, section))
7207 {
7208 others--;
7209 gdb_printf ("%d", b.number);
7210 if (b.thread == -1 && thread != -1)
7211 gdb_printf (" (all threads)");
7212 else if (b.thread != -1)
7213 {
7214 struct thread_info *thr = find_thread_global_id (b.thread);
7215 gdb_printf (" (thread %s)", print_thread_id (thr));
7216 }
7217 else if (b.task != -1)
7218 gdb_printf (" (task %d)", b.task);
7219 gdb_printf ("%s%s ",
7220 ((b.enable_state == bp_disabled
7221 || b.enable_state == bp_call_disabled)
7222 ? " (disabled)"
7223 : ""),
7224 (others > 1) ? ","
7225 : ((others == 1) ? " and" : ""));
7226 }
7227 current_uiout->message (_("also set at pc %ps.\n"),
7228 styled_string (address_style.style (),
7229 paddress (gdbarch, pc)));
7230 }
7231 }
7232 \f
7233
7234 /* Return true iff it is meaningful to use the address member of LOC.
7235 For some breakpoint types, the locations' address members are
7236 irrelevant and it makes no sense to attempt to compare them to
7237 other addresses (or use them for any other purpose either).
7238
7239 More specifically, software watchpoints and catchpoints that are
7240 not backed by breakpoints always have a zero valued location
7241 address and we don't want to mark breakpoints of any of these types
7242 to be a duplicate of an actual breakpoint location at address
7243 zero. */
7244
7245 static bool
7246 bl_address_is_meaningful (bp_location *loc)
7247 {
7248 return loc->loc_type != bp_loc_other;
7249 }
7250
7251 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
7252 true if LOC1 and LOC2 represent the same watchpoint location. */
7253
7254 static bool
7255 watchpoint_locations_match (const struct bp_location *loc1,
7256 const struct bp_location *loc2)
7257 {
7258 watchpoint *w1 = gdb::checked_static_cast<watchpoint *> (loc1->owner);
7259 watchpoint *w2 = gdb::checked_static_cast<watchpoint *> (loc2->owner);
7260
7261 /* Both of them must exist. */
7262 gdb_assert (w1 != NULL);
7263 gdb_assert (w2 != NULL);
7264
7265 /* If the target can evaluate the condition expression in hardware,
7266 then we we need to insert both watchpoints even if they are at
7267 the same place. Otherwise the watchpoint will only trigger when
7268 the condition of whichever watchpoint was inserted evaluates to
7269 true, not giving a chance for GDB to check the condition of the
7270 other watchpoint. */
7271 if ((w1->cond_exp
7272 && target_can_accel_watchpoint_condition (loc1->address,
7273 loc1->length,
7274 loc1->watchpoint_type,
7275 w1->cond_exp.get ()))
7276 || (w2->cond_exp
7277 && target_can_accel_watchpoint_condition (loc2->address,
7278 loc2->length,
7279 loc2->watchpoint_type,
7280 w2->cond_exp.get ())))
7281 return false;
7282
7283 /* Note that this checks the owner's type, not the location's. In
7284 case the target does not support read watchpoints, but does
7285 support access watchpoints, we'll have bp_read_watchpoint
7286 watchpoints with hw_access locations. Those should be considered
7287 duplicates of hw_read locations. The hw_read locations will
7288 become hw_access locations later. */
7289 return (loc1->owner->type == loc2->owner->type
7290 && loc1->pspace->aspace == loc2->pspace->aspace
7291 && loc1->address == loc2->address
7292 && loc1->length == loc2->length);
7293 }
7294
7295 /* See breakpoint.h. */
7296
7297 int
7298 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
7299 const address_space *aspace2, CORE_ADDR addr2)
7300 {
7301 return ((gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7302 || aspace1 == aspace2)
7303 && addr1 == addr2);
7304 }
7305
7306 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7307 {ASPACE1,ADDR1,LEN1}. In most targets, this can only be true if ASPACE1
7308 matches ASPACE2. On targets that have global breakpoints, the address
7309 space doesn't really matter. */
7310
7311 static bool
7312 breakpoint_address_match_range (const address_space *aspace1,
7313 CORE_ADDR addr1,
7314 int len1, const address_space *aspace2,
7315 CORE_ADDR addr2)
7316 {
7317 return ((gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7318 || aspace1 == aspace2)
7319 && addr2 >= addr1 && addr2 < addr1 + len1);
7320 }
7321
7322 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL. BL may be
7323 a ranged breakpoint. In most targets, a match happens only if ASPACE
7324 matches the breakpoint's address space. On targets that have global
7325 breakpoints, the address space doesn't really matter. */
7326
7327 static bool
7328 breakpoint_location_address_match (struct bp_location *bl,
7329 const address_space *aspace,
7330 CORE_ADDR addr)
7331 {
7332 return (breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
7333 aspace, addr)
7334 || (bl->length
7335 && breakpoint_address_match_range (bl->pspace->aspace.get (),
7336 bl->address, bl->length,
7337 aspace, addr)));
7338 }
7339
7340 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
7341 breakpoint BL. BL may be a ranged breakpoint. In most targets, a
7342 match happens only if ASPACE matches the breakpoint's address
7343 space. On targets that have global breakpoints, the address space
7344 doesn't really matter. */
7345
7346 static bool
7347 breakpoint_location_address_range_overlap (struct bp_location *bl,
7348 const address_space *aspace,
7349 CORE_ADDR addr, int len)
7350 {
7351 if (gdbarch_has_global_breakpoints (current_inferior ()->arch ())
7352 || bl->pspace->aspace.get () == aspace)
7353 {
7354 int bl_len = bl->length != 0 ? bl->length : 1;
7355
7356 if (mem_ranges_overlap (addr, len, bl->address, bl_len))
7357 return 1;
7358 }
7359 return 0;
7360 }
7361
7362 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7363 Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7364 true, otherwise returns false. */
7365
7366 static bool
7367 tracepoint_locations_match (const struct bp_location *loc1,
7368 const struct bp_location *loc2)
7369 {
7370 if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7371 /* Since tracepoint locations are never duplicated with others', tracepoint
7372 locations at the same address of different tracepoints are regarded as
7373 different locations. */
7374 return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7375 else
7376 return false;
7377 }
7378
7379 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7380 (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
7381 the same location. If SW_HW_BPS_MATCH is true, then software
7382 breakpoint locations and hardware breakpoint locations match,
7383 otherwise they don't. */
7384
7385 static bool
7386 breakpoint_locations_match (const struct bp_location *loc1,
7387 const struct bp_location *loc2,
7388 bool sw_hw_bps_match)
7389 {
7390 int hw_point1, hw_point2;
7391
7392 /* Both of them must not be in moribund_locations. */
7393 gdb_assert (loc1->owner != NULL);
7394 gdb_assert (loc2->owner != NULL);
7395
7396 hw_point1 = is_hardware_watchpoint (loc1->owner);
7397 hw_point2 = is_hardware_watchpoint (loc2->owner);
7398
7399 if (hw_point1 != hw_point2)
7400 return false;
7401 else if (hw_point1)
7402 return watchpoint_locations_match (loc1, loc2);
7403 else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7404 return tracepoint_locations_match (loc1, loc2);
7405 else
7406 /* We compare bp_location.length in order to cover ranged
7407 breakpoints. Keep this in sync with
7408 bp_location_is_less_than. */
7409 return (breakpoint_address_match (loc1->pspace->aspace.get (),
7410 loc1->address,
7411 loc2->pspace->aspace.get (),
7412 loc2->address)
7413 && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
7414 && loc1->length == loc2->length);
7415 }
7416
7417 static void
7418 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7419 int bnum, bool have_bnum)
7420 {
7421 /* The longest string possibly returned by hex_string_custom
7422 is 50 chars. These must be at least that big for safety. */
7423 char astr1[64];
7424 char astr2[64];
7425
7426 strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7427 strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7428 if (have_bnum)
7429 warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7430 bnum, astr1, astr2);
7431 else
7432 warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7433 }
7434
7435 /* Adjust a breakpoint's address to account for architectural
7436 constraints on breakpoint placement. Return the adjusted address.
7437 Note: Very few targets require this kind of adjustment. For most
7438 targets, this function is simply the identity function. */
7439
7440 static CORE_ADDR
7441 adjust_breakpoint_address (struct gdbarch *gdbarch,
7442 CORE_ADDR bpaddr, enum bptype bptype,
7443 struct program_space *pspace)
7444 {
7445 gdb_assert (pspace != nullptr);
7446
7447 if (bptype == bp_watchpoint
7448 || bptype == bp_hardware_watchpoint
7449 || bptype == bp_read_watchpoint
7450 || bptype == bp_access_watchpoint
7451 || bptype == bp_catchpoint)
7452 {
7453 /* Watchpoints and the various bp_catch_* eventpoints should not
7454 have their addresses modified. */
7455 return bpaddr;
7456 }
7457 else if (bptype == bp_single_step)
7458 {
7459 /* Single-step breakpoints should not have their addresses
7460 modified. If there's any architectural constrain that
7461 applies to this address, then it should have already been
7462 taken into account when the breakpoint was created in the
7463 first place. If we didn't do this, stepping through e.g.,
7464 Thumb-2 IT blocks would break. */
7465 return bpaddr;
7466 }
7467 else
7468 {
7469 CORE_ADDR adjusted_bpaddr = bpaddr;
7470
7471 /* Some targets have architectural constraints on the placement
7472 of breakpoint instructions. Obtain the adjusted address. */
7473 if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7474 {
7475 /* Targets that implement this adjustment function will likely
7476 inspect either the symbol table, target memory at BPADDR, or
7477 even state registers, so ensure a suitable thread (and its
7478 associated program space) are currently selected. */
7479 scoped_restore_current_pspace_and_thread restore_pspace_thread;
7480 switch_to_program_space_and_thread (pspace);
7481 adjusted_bpaddr
7482 = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7483 }
7484
7485 adjusted_bpaddr
7486 = gdbarch_remove_non_address_bits (gdbarch, adjusted_bpaddr);
7487
7488 /* An adjusted breakpoint address can significantly alter
7489 a user's expectations. Print a warning if an adjustment
7490 is required. */
7491 if (adjusted_bpaddr != bpaddr)
7492 breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, false);
7493
7494 return adjusted_bpaddr;
7495 }
7496 }
7497
7498 static bp_loc_type
7499 bp_location_from_bp_type (bptype type)
7500 {
7501 switch (type)
7502 {
7503 case bp_breakpoint:
7504 case bp_single_step:
7505 case bp_until:
7506 case bp_finish:
7507 case bp_longjmp:
7508 case bp_longjmp_resume:
7509 case bp_longjmp_call_dummy:
7510 case bp_exception:
7511 case bp_exception_resume:
7512 case bp_step_resume:
7513 case bp_hp_step_resume:
7514 case bp_watchpoint_scope:
7515 case bp_call_dummy:
7516 case bp_std_terminate:
7517 case bp_shlib_event:
7518 case bp_thread_event:
7519 case bp_overlay_event:
7520 case bp_jit_event:
7521 case bp_longjmp_master:
7522 case bp_std_terminate_master:
7523 case bp_exception_master:
7524 case bp_gnu_ifunc_resolver:
7525 case bp_gnu_ifunc_resolver_return:
7526 case bp_dprintf:
7527 return bp_loc_software_breakpoint;
7528
7529 case bp_hardware_breakpoint:
7530 return bp_loc_hardware_breakpoint;
7531
7532 case bp_hardware_watchpoint:
7533 case bp_read_watchpoint:
7534 case bp_access_watchpoint:
7535 return bp_loc_hardware_watchpoint;
7536
7537 case bp_watchpoint:
7538 return bp_loc_software_watchpoint;
7539
7540 case bp_tracepoint:
7541 case bp_fast_tracepoint:
7542 case bp_static_tracepoint:
7543 case bp_static_marker_tracepoint:
7544 return bp_loc_tracepoint;
7545
7546 case bp_catchpoint:
7547 return bp_loc_other;
7548
7549 default:
7550 internal_error (_("unknown breakpoint type"));
7551 }
7552 }
7553
7554 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7555 {
7556 this->owner = owner;
7557 this->cond_bytecode = NULL;
7558 this->shlib_disabled = 0;
7559 this->enabled = 1;
7560 this->disabled_by_cond = false;
7561
7562 this->loc_type = type;
7563
7564 if (this->loc_type == bp_loc_software_breakpoint
7565 || this->loc_type == bp_loc_hardware_breakpoint)
7566 mark_breakpoint_location_modified (this);
7567
7568 incref ();
7569 }
7570
7571 bp_location::bp_location (breakpoint *owner)
7572 : bp_location::bp_location (owner,
7573 bp_location_from_bp_type (owner->type))
7574 {
7575 }
7576
7577 /* See breakpoint.h. */
7578
7579 std::string
7580 bp_location::to_string () const
7581 {
7582 string_file stb;
7583 ui_out_redirect_pop redir (current_uiout, &stb);
7584 print_breakpoint_location (this->owner, this);
7585 return stb.release ();
7586 }
7587
7588 /* Decrement reference count. If the reference count reaches 0,
7589 destroy the bp_location. Sets *BLP to NULL. */
7590
7591 static void
7592 decref_bp_location (struct bp_location **blp)
7593 {
7594 bp_location_ref_policy::decref (*blp);
7595 *blp = NULL;
7596 }
7597
7598 /* Add breakpoint B at the end of the global breakpoint chain. */
7599
7600 static breakpoint *
7601 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7602 {
7603 /* Add this breakpoint to the end of the chain so that a list of
7604 breakpoints will come out in order of increasing numbers. */
7605
7606 breakpoint_chain.push_back (*b.release ());
7607
7608 return &breakpoint_chain.back ();
7609 }
7610
7611 /* Initialize loc->function_name. */
7612
7613 static void
7614 set_breakpoint_location_function (struct bp_location *loc)
7615 {
7616 gdb_assert (loc->owner != NULL);
7617
7618 if (loc->owner->type == bp_breakpoint
7619 || loc->owner->type == bp_hardware_breakpoint
7620 || is_tracepoint (loc->owner))
7621 {
7622 const char *function_name;
7623
7624 if (loc->msymbol != NULL
7625 && (loc->msymbol->type () == mst_text_gnu_ifunc
7626 || loc->msymbol->type () == mst_data_gnu_ifunc))
7627 {
7628 struct breakpoint *b = loc->owner;
7629
7630 function_name = loc->msymbol->linkage_name ();
7631
7632 if (b->type == bp_breakpoint
7633 && b->has_single_location ()
7634 && b->related_breakpoint == b)
7635 {
7636 /* Create only the whole new breakpoint of this type but do not
7637 mess more complicated breakpoints with multiple locations. */
7638 b->type = bp_gnu_ifunc_resolver;
7639 /* Remember the resolver's address for use by the return
7640 breakpoint. */
7641 loc->related_address = loc->address;
7642 }
7643 }
7644 else
7645 find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7646
7647 if (function_name)
7648 loc->function_name = make_unique_xstrdup (function_name);
7649 }
7650 }
7651
7652 /* Attempt to determine architecture of location identified by SAL. */
7653 struct gdbarch *
7654 get_sal_arch (struct symtab_and_line sal)
7655 {
7656 if (sal.section)
7657 return sal.section->objfile->arch ();
7658 if (sal.symtab)
7659 return sal.symtab->compunit ()->objfile ()->arch ();
7660
7661 return NULL;
7662 }
7663
7664 /* Call this routine when stepping and nexting to enable a breakpoint
7665 if we do a longjmp() or 'throw' in TP. FRAME is the frame which
7666 initiated the operation. */
7667
7668 void
7669 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7670 {
7671 int thread = tp->global_num;
7672
7673 /* To avoid having to rescan all objfile symbols at every step,
7674 we maintain a list of continually-inserted but always disabled
7675 longjmp "master" breakpoints. Here, we simply create momentary
7676 clones of those and enable them for the requested thread. */
7677 for (breakpoint &b : all_breakpoints_safe ())
7678 if (b.pspace == current_program_space
7679 && (b.type == bp_longjmp_master
7680 || b.type == bp_exception_master))
7681 {
7682 bptype type = b.type == bp_longjmp_master ? bp_longjmp : bp_exception;
7683 /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7684 after their removal. */
7685 momentary_breakpoint_from_master (&b, type, 1, thread);
7686 }
7687
7688 tp->initiating_frame = frame;
7689 }
7690
7691 /* Delete all longjmp breakpoints from THREAD. */
7692 void
7693 delete_longjmp_breakpoint (int thread)
7694 {
7695 for (breakpoint &b : all_breakpoints_safe ())
7696 if (b.type == bp_longjmp || b.type == bp_exception)
7697 {
7698 if (b.thread == thread)
7699 {
7700 gdb_assert (b.inferior == -1);
7701 delete_breakpoint (&b);
7702 }
7703 }
7704 }
7705
7706 void
7707 delete_longjmp_breakpoint_at_next_stop (int thread)
7708 {
7709 for (breakpoint &b : all_breakpoints_safe ())
7710 if (b.type == bp_longjmp || b.type == bp_exception)
7711 {
7712 if (b.thread == thread)
7713 {
7714 gdb_assert (b.inferior == -1);
7715 b.disposition = disp_del_at_next_stop;
7716 }
7717 }
7718 }
7719
7720 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7721 INFERIOR_PTID thread. Chain them all by RELATED_BREAKPOINT and return
7722 pointer to any of them. Return NULL if this system cannot place longjmp
7723 breakpoints. */
7724
7725 struct breakpoint *
7726 set_longjmp_breakpoint_for_call_dummy (void)
7727 {
7728 breakpoint *retval = nullptr;
7729
7730 for (breakpoint &b : all_breakpoints ())
7731 if (b.pspace == current_program_space && b.type == bp_longjmp_master)
7732 {
7733 int thread = inferior_thread ()->global_num;
7734 breakpoint *new_b
7735 = momentary_breakpoint_from_master (&b, bp_longjmp_call_dummy,
7736 1, thread);
7737
7738 /* Link NEW_B into the chain of RETVAL breakpoints. */
7739
7740 gdb_assert (new_b->related_breakpoint == new_b);
7741 if (retval == NULL)
7742 retval = new_b;
7743 new_b->related_breakpoint = retval;
7744 while (retval->related_breakpoint != new_b->related_breakpoint)
7745 retval = retval->related_breakpoint;
7746 retval->related_breakpoint = new_b;
7747 }
7748
7749 return retval;
7750 }
7751
7752 /* Verify all existing dummy frames and their associated breakpoints for
7753 TP. Remove those which can no longer be found in the current frame
7754 stack.
7755
7756 If the unwind fails then there is not sufficient information to discard
7757 dummy frames. In this case, elide the clean up and the dummy frames will
7758 be cleaned up next time this function is called from a location where
7759 unwinding is possible. */
7760
7761 void
7762 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7763 {
7764 /* We would need to delete breakpoints other than the current one while
7765 iterating, so all_breakpoints_safe is not sufficient to make that safe.
7766 Save all breakpoints to delete in that set and delete them at the end. */
7767 std::unordered_set<breakpoint *> to_delete;
7768
7769 for (struct breakpoint &b : all_breakpoints ())
7770 {
7771 if (b.type == bp_longjmp_call_dummy && b.thread == tp->global_num)
7772 {
7773 gdb_assert (b.inferior == -1);
7774 struct breakpoint *dummy_b = b.related_breakpoint;
7775
7776 /* Find the bp_call_dummy breakpoint in the list of breakpoints
7777 chained off b->related_breakpoint. */
7778 while (dummy_b != &b && dummy_b->type != bp_call_dummy)
7779 dummy_b = dummy_b->related_breakpoint;
7780
7781 /* If there was no bp_call_dummy breakpoint then there's nothing
7782 more to do. Or, if the dummy frame associated with the
7783 bp_call_dummy is still on the stack then we need to leave this
7784 bp_call_dummy in place. */
7785 if (dummy_b->type != bp_call_dummy
7786 || frame_find_by_id (dummy_b->frame_id) != NULL)
7787 continue;
7788
7789 /* We didn't find the dummy frame on the stack, this could be
7790 because we have longjmp'd to a stack frame that is previous to
7791 the dummy frame, or it could be because the stack unwind is
7792 broken at some point between the longjmp frame and the dummy
7793 frame.
7794
7795 Next we figure out why the stack unwind stopped. If it looks
7796 like the unwind is complete then we assume the dummy frame has
7797 been jumped over, however, if the unwind stopped for an
7798 unexpected reason then we assume the stack unwind is currently
7799 broken, and that we will (eventually) return to the dummy
7800 frame.
7801
7802 It might be tempting to consider using frame_id_inner here, but
7803 that is not safe. There is no guarantee that the stack frames
7804 we are looking at here are even on the same stack as the
7805 original dummy frame, hence frame_id_inner can't be used. See
7806 the comments on frame_id_inner for more details. */
7807 bool unwind_finished_unexpectedly = false;
7808 for (frame_info_ptr fi = get_current_frame (); fi != nullptr; )
7809 {
7810 frame_info_ptr prev = get_prev_frame (fi);
7811 if (prev == nullptr)
7812 {
7813 /* FI is the last stack frame. Why did this frame not
7814 unwind further? */
7815 auto stop_reason = get_frame_unwind_stop_reason (fi);
7816 if (stop_reason != UNWIND_NO_REASON
7817 && stop_reason != UNWIND_OUTERMOST)
7818 unwind_finished_unexpectedly = true;
7819 }
7820 fi = prev;
7821 }
7822 if (unwind_finished_unexpectedly)
7823 continue;
7824
7825 dummy_frame_discard (dummy_b->frame_id, tp);
7826
7827 for (breakpoint *related_breakpoint = b.related_breakpoint;
7828 related_breakpoint != &b;
7829 related_breakpoint = related_breakpoint->related_breakpoint)
7830 to_delete.insert (b.related_breakpoint);
7831
7832 to_delete.insert (&b);
7833 }
7834 }
7835
7836 for (breakpoint *b : to_delete)
7837 delete_breakpoint (b);
7838 }
7839
7840 void
7841 enable_overlay_breakpoints (void)
7842 {
7843 for (breakpoint &b : all_breakpoints ())
7844 if (b.type == bp_overlay_event)
7845 {
7846 b.enable_state = bp_enabled;
7847 update_global_location_list (UGLL_MAY_INSERT);
7848 overlay_events_enabled = 1;
7849 }
7850 }
7851
7852 void
7853 disable_overlay_breakpoints (void)
7854 {
7855 for (breakpoint &b : all_breakpoints ())
7856 if (b.type == bp_overlay_event)
7857 {
7858 b.enable_state = bp_disabled;
7859 update_global_location_list (UGLL_DONT_INSERT);
7860 overlay_events_enabled = 0;
7861 }
7862 }
7863
7864 /* Set an active std::terminate breakpoint for each std::terminate
7865 master breakpoint. */
7866 void
7867 set_std_terminate_breakpoint (void)
7868 {
7869 for (breakpoint &b : all_breakpoints_safe ())
7870 if (b.pspace == current_program_space
7871 && b.type == bp_std_terminate_master)
7872 {
7873 momentary_breakpoint_from_master (&b, bp_std_terminate, 1,
7874 inferior_thread ()->global_num);
7875 }
7876 }
7877
7878 /* Delete all the std::terminate breakpoints. */
7879 void
7880 delete_std_terminate_breakpoint (void)
7881 {
7882 for (breakpoint &b : all_breakpoints_safe ())
7883 if (b.type == bp_std_terminate)
7884 delete_breakpoint (&b);
7885 }
7886
7887 struct breakpoint *
7888 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7889 {
7890 struct breakpoint *b;
7891
7892 b = create_internal_breakpoint (gdbarch, address, bp_thread_event);
7893
7894 b->enable_state = bp_enabled;
7895 /* locspec has to be used or breakpoint_re_set will delete me. */
7896 b->locspec = new_address_location_spec (b->first_loc ().address, NULL, 0);
7897
7898 update_global_location_list_nothrow (UGLL_MAY_INSERT);
7899
7900 return b;
7901 }
7902
7903 struct lang_and_radix
7904 {
7905 enum language lang;
7906 int radix;
7907 };
7908
7909 /* Create a breakpoint for JIT code registration and unregistration. */
7910
7911 struct breakpoint *
7912 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7913 {
7914 return create_internal_breakpoint (gdbarch, address, bp_jit_event);
7915 }
7916
7917 /* Remove JIT code registration and unregistration breakpoint(s). */
7918
7919 void
7920 remove_jit_event_breakpoints (void)
7921 {
7922 for (breakpoint &b : all_breakpoints_safe ())
7923 if (b.type == bp_jit_event
7924 && b.first_loc ().pspace == current_program_space)
7925 delete_breakpoint (&b);
7926 }
7927
7928 void
7929 remove_solib_event_breakpoints (void)
7930 {
7931 for (breakpoint &b : all_breakpoints_safe ())
7932 if (b.type == bp_shlib_event
7933 && b.first_loc ().pspace == current_program_space)
7934 delete_breakpoint (&b);
7935 }
7936
7937 /* See breakpoint.h. */
7938
7939 void
7940 remove_solib_event_breakpoints_at_next_stop (void)
7941 {
7942 for (breakpoint &b : all_breakpoints_safe ())
7943 if (b.type == bp_shlib_event
7944 && b.first_loc ().pspace == current_program_space)
7945 b.disposition = disp_del_at_next_stop;
7946 }
7947
7948 /* Helper for create_solib_event_breakpoint /
7949 create_and_insert_solib_event_breakpoint. Allows specifying which
7950 INSERT_MODE to pass through to update_global_location_list. */
7951
7952 static struct breakpoint *
7953 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7954 enum ugll_insert_mode insert_mode)
7955 {
7956 struct breakpoint *b;
7957
7958 b = create_internal_breakpoint (gdbarch, address, bp_shlib_event);
7959 update_global_location_list_nothrow (insert_mode);
7960 return b;
7961 }
7962
7963 struct breakpoint *
7964 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7965 {
7966 return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7967 }
7968
7969 /* See breakpoint.h. */
7970
7971 struct breakpoint *
7972 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7973 {
7974 struct breakpoint *b;
7975
7976 /* Explicitly tell update_global_location_list to insert
7977 locations. */
7978 b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7979 if (!b->first_loc ().inserted)
7980 {
7981 delete_breakpoint (b);
7982 return NULL;
7983 }
7984 return b;
7985 }
7986
7987 /* Disable any breakpoints that are on code in shared libraries. Only
7988 apply to enabled breakpoints, disabled ones can just stay disabled. */
7989
7990 void
7991 disable_breakpoints_in_shlibs (void)
7992 {
7993 for (bp_location *loc : all_bp_locations ())
7994 {
7995 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
7996 struct breakpoint *b = loc->owner;
7997
7998 /* We apply the check to all breakpoints, including disabled for
7999 those with loc->duplicate set. This is so that when breakpoint
8000 becomes enabled, or the duplicate is removed, gdb will try to
8001 insert all breakpoints. If we don't set shlib_disabled here,
8002 we'll try to insert those breakpoints and fail. */
8003 if (((b->type == bp_breakpoint)
8004 || (b->type == bp_jit_event)
8005 || (b->type == bp_hardware_breakpoint)
8006 || (is_tracepoint (b)))
8007 && loc->pspace == current_program_space
8008 && !loc->shlib_disabled
8009 && solib_name_from_address (loc->pspace, loc->address)
8010 )
8011 {
8012 loc->shlib_disabled = 1;
8013 }
8014 }
8015 }
8016
8017 /* Disable any breakpoints and tracepoints that are in SOLIB upon
8018 notification of unloaded_shlib. Only apply to enabled breakpoints,
8019 disabled ones can just stay disabled. */
8020
8021 static void
8022 disable_breakpoints_in_unloaded_shlib (program_space *pspace, const shobj &solib)
8023 {
8024 bool disabled_shlib_breaks = false;
8025
8026 for (bp_location *loc : all_bp_locations ())
8027 {
8028 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL. */
8029 struct breakpoint *b = loc->owner;
8030
8031 if (pspace == loc->pspace
8032 && !loc->shlib_disabled
8033 && (((b->type == bp_breakpoint
8034 || b->type == bp_jit_event
8035 || b->type == bp_hardware_breakpoint)
8036 && (loc->loc_type == bp_loc_hardware_breakpoint
8037 || loc->loc_type == bp_loc_software_breakpoint))
8038 || is_tracepoint (b))
8039 && solib_contains_address_p (solib, loc->address))
8040 {
8041 loc->shlib_disabled = 1;
8042 /* At this point, we cannot rely on remove_breakpoint
8043 succeeding so we must mark the breakpoint as not inserted
8044 to prevent future errors occurring in remove_breakpoints. */
8045 loc->inserted = 0;
8046
8047 /* This may cause duplicate notifications for the same breakpoint. */
8048 notify_breakpoint_modified (b);
8049
8050 if (!disabled_shlib_breaks)
8051 {
8052 target_terminal::ours_for_output ();
8053 warning (_("Temporarily disabling breakpoints "
8054 "for unloaded shared library \"%s\""),
8055 solib.so_name.c_str ());
8056 }
8057 disabled_shlib_breaks = true;
8058 }
8059 }
8060 }
8061
8062 /* Disable any breakpoints and tracepoints in OBJFILE upon
8063 notification of free_objfile. Only apply to enabled breakpoints,
8064 disabled ones can just stay disabled. */
8065
8066 static void
8067 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
8068 {
8069 /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
8070 managed by the user with add-symbol-file/remove-symbol-file.
8071 Similarly to how breakpoints in shared libraries are handled in
8072 response to "nosharedlibrary", mark breakpoints in such modules
8073 shlib_disabled so they end up uninserted on the next global
8074 location list update. Shared libraries not loaded by the user
8075 aren't handled here -- they're already handled in
8076 disable_breakpoints_in_unloaded_shlib, called by solib.c's
8077 solib_unloaded observer. We skip objfiles that are not
8078 OBJF_SHARED as those aren't considered dynamic objects (e.g. the
8079 main objfile). */
8080 if ((objfile->flags & OBJF_SHARED) == 0
8081 || (objfile->flags & OBJF_USERLOADED) == 0)
8082 return;
8083
8084 for (breakpoint &b : all_breakpoints ())
8085 {
8086 bool bp_modified = false;
8087
8088 if (!is_breakpoint (&b) && !is_tracepoint (&b))
8089 continue;
8090
8091 for (bp_location &loc : b.locations ())
8092 {
8093 CORE_ADDR loc_addr = loc.address;
8094
8095 if (loc.loc_type != bp_loc_hardware_breakpoint
8096 && loc.loc_type != bp_loc_software_breakpoint)
8097 continue;
8098
8099 if (loc.shlib_disabled != 0)
8100 continue;
8101
8102 if (objfile->pspace != loc.pspace)
8103 continue;
8104
8105 if (loc.loc_type != bp_loc_hardware_breakpoint
8106 && loc.loc_type != bp_loc_software_breakpoint)
8107 continue;
8108
8109 if (is_addr_in_objfile (loc_addr, objfile))
8110 {
8111 loc.shlib_disabled = 1;
8112 /* At this point, we don't know whether the object was
8113 unmapped from the inferior or not, so leave the
8114 inserted flag alone. We'll handle failure to
8115 uninsert quietly, in case the object was indeed
8116 unmapped. */
8117
8118 mark_breakpoint_location_modified (&loc);
8119
8120 bp_modified = true;
8121 }
8122 }
8123
8124 if (bp_modified)
8125 notify_breakpoint_modified (&b);
8126 }
8127 }
8128
8129 /* See breakpoint.h. */
8130
8131 breakpoint::breakpoint (struct gdbarch *gdbarch_, enum bptype bptype,
8132 bool temp, const char *cond_string_)
8133 : type (bptype),
8134 disposition (temp ? disp_del : disp_donttouch),
8135 gdbarch (gdbarch_),
8136 language (current_language->la_language),
8137 input_radix (::input_radix),
8138 cond_string (cond_string_ != nullptr
8139 ? make_unique_xstrdup (cond_string_)
8140 : nullptr),
8141 related_breakpoint (this)
8142 {
8143 }
8144
8145 /* See breakpoint.h. */
8146
8147 catchpoint::catchpoint (struct gdbarch *gdbarch, bool temp,
8148 const char *cond_string)
8149 : breakpoint (gdbarch, bp_catchpoint, temp, cond_string)
8150 {
8151 add_dummy_location (this, current_program_space);
8152
8153 pspace = current_program_space;
8154 }
8155
8156 /* Notify interpreters and observers that breakpoint B was created. */
8157
8158 static void
8159 notify_breakpoint_created (breakpoint *b)
8160 {
8161 interps_notify_breakpoint_created (b);
8162 gdb::observers::breakpoint_created.notify (b);
8163 }
8164
8165 breakpoint *
8166 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8167 {
8168 breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8169 set_breakpoint_number (internal, b);
8170 if (is_tracepoint (b))
8171 set_tracepoint_count (breakpoint_count);
8172 if (!internal)
8173 mention (b);
8174
8175 notify_breakpoint_created (b);
8176
8177 if (update_gll)
8178 update_global_location_list (UGLL_MAY_INSERT);
8179
8180 return b;
8181 }
8182
8183 static int
8184 hw_breakpoint_used_count (void)
8185 {
8186 int i = 0;
8187
8188 for (breakpoint &b : all_breakpoints ())
8189 if (b.type == bp_hardware_breakpoint && breakpoint_enabled (&b))
8190 for (bp_location &bl : b.locations ())
8191 {
8192 /* Special types of hardware breakpoints may use more than
8193 one register. */
8194 i += b.resources_needed (&bl);
8195 }
8196
8197 return i;
8198 }
8199
8200 /* Returns the resources B would use if it were a hardware
8201 watchpoint. */
8202
8203 static int
8204 hw_watchpoint_use_count (struct breakpoint *b)
8205 {
8206 int i = 0;
8207
8208 if (!breakpoint_enabled (b))
8209 return 0;
8210
8211 for (bp_location &bl : b->locations ())
8212 {
8213 /* Special types of hardware watchpoints may use more than
8214 one register. */
8215 i += b->resources_needed (&bl);
8216 }
8217
8218 return i;
8219 }
8220
8221 /* Returns the sum the used resources of all hardware watchpoints of
8222 type TYPE in the breakpoints list. Also returns in OTHER_TYPE_USED
8223 the sum of the used resources of all hardware watchpoints of other
8224 types _not_ TYPE. */
8225
8226 static int
8227 hw_watchpoint_used_count_others (struct breakpoint *except,
8228 enum bptype type, int *other_type_used)
8229 {
8230 int i = 0;
8231
8232 *other_type_used = 0;
8233 for (breakpoint &b : all_breakpoints ())
8234 {
8235 if (&b == except)
8236 continue;
8237 if (!breakpoint_enabled (&b))
8238 continue;
8239
8240 if (b.type == type)
8241 i += hw_watchpoint_use_count (&b);
8242 else if (is_hardware_watchpoint (&b))
8243 *other_type_used = 1;
8244 }
8245
8246 return i;
8247 }
8248
8249 void
8250 disable_watchpoints_before_interactive_call_start (void)
8251 {
8252 for (breakpoint &b : all_breakpoints ())
8253 if (is_watchpoint (&b) && breakpoint_enabled (&b))
8254 {
8255 b.enable_state = bp_call_disabled;
8256 update_global_location_list (UGLL_DONT_INSERT);
8257 }
8258 }
8259
8260 void
8261 enable_watchpoints_after_interactive_call_stop (void)
8262 {
8263 for (breakpoint &b : all_breakpoints ())
8264 if (is_watchpoint (&b) && b.enable_state == bp_call_disabled)
8265 {
8266 b.enable_state = bp_enabled;
8267 update_global_location_list (UGLL_MAY_INSERT);
8268 }
8269 }
8270
8271 void
8272 disable_breakpoints_before_startup (void)
8273 {
8274 current_program_space->executing_startup = 1;
8275 update_global_location_list (UGLL_DONT_INSERT);
8276 }
8277
8278 void
8279 enable_breakpoints_after_startup (void)
8280 {
8281 current_program_space->executing_startup = 0;
8282 breakpoint_re_set ();
8283 }
8284
8285 /* Allocate a new momentary breakpoint. */
8286
8287 template<typename... Arg>
8288 static momentary_breakpoint *
8289 new_momentary_breakpoint (struct gdbarch *gdbarch, enum bptype type,
8290 Arg&&... args)
8291 {
8292 if (type == bp_longjmp || type == bp_exception)
8293 return new longjmp_breakpoint (gdbarch, type,
8294 std::forward<Arg> (args)...);
8295 else
8296 return new momentary_breakpoint (gdbarch, type,
8297 std::forward<Arg> (args)...);
8298 }
8299
8300 /* Set a momentary breakpoint of type TYPE at address specified by
8301 SAL. If FRAME_ID is valid, the breakpoint is restricted to that
8302 frame. */
8303
8304 breakpoint_up
8305 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8306 struct frame_id frame_id, enum bptype type)
8307 {
8308 /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8309 tail-called one. */
8310 gdb_assert (!frame_id_artificial_p (frame_id));
8311
8312 std::unique_ptr<momentary_breakpoint> b
8313 (new_momentary_breakpoint (gdbarch, type, sal.pspace, frame_id,
8314 inferior_thread ()->global_num));
8315
8316 b->add_location (sal);
8317
8318 breakpoint_up bp (add_to_breakpoint_chain (std::move (b)));
8319
8320 update_global_location_list_nothrow (UGLL_MAY_INSERT);
8321
8322 return bp;
8323 }
8324
8325 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8326 The new breakpoint will have type TYPE, use OPS as its
8327 breakpoint_ops, and will set enabled to LOC_ENABLED. */
8328
8329 static struct breakpoint *
8330 momentary_breakpoint_from_master (struct breakpoint *orig,
8331 enum bptype type,
8332 int loc_enabled,
8333 int thread)
8334 {
8335 std::unique_ptr<breakpoint> copy
8336 (new_momentary_breakpoint (orig->gdbarch, type, orig->pspace,
8337 orig->frame_id, thread));
8338 const bp_location &orig_loc = orig->first_loc ();
8339 bp_location *copy_loc = copy->allocate_location ();
8340 copy->add_location (*copy_loc);
8341 set_breakpoint_location_function (copy_loc);
8342
8343 copy_loc->gdbarch = orig_loc.gdbarch;
8344 copy_loc->requested_address = orig_loc.requested_address;
8345 copy_loc->address = orig_loc.address;
8346 copy_loc->section = orig_loc.section;
8347 copy_loc->pspace = orig_loc.pspace;
8348 copy_loc->probe = orig_loc.probe;
8349 copy_loc->line_number = orig_loc.line_number;
8350 copy_loc->symtab = orig_loc.symtab;
8351 copy_loc->enabled = loc_enabled;
8352
8353 breakpoint *b = add_to_breakpoint_chain (std::move (copy));
8354 update_global_location_list_nothrow (UGLL_DONT_INSERT);
8355 return b;
8356 }
8357
8358 /* Make a deep copy of momentary breakpoint ORIG. Returns NULL if
8359 ORIG is NULL. */
8360
8361 struct breakpoint *
8362 clone_momentary_breakpoint (struct breakpoint *orig)
8363 {
8364 /* If there's nothing to clone, then return nothing. */
8365 if (orig == NULL)
8366 return NULL;
8367
8368 return momentary_breakpoint_from_master (orig, orig->type, 0,
8369 orig->thread);
8370 }
8371
8372 breakpoint_up
8373 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8374 enum bptype type)
8375 {
8376 struct symtab_and_line sal;
8377
8378 sal = find_pc_line (pc, 0);
8379 sal.pc = pc;
8380 sal.section = find_pc_overlay (pc);
8381 sal.explicit_pc = 1;
8382
8383 return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8384 }
8385 \f
8386
8387 /* Tell the user we have just set a breakpoint B. */
8388
8389 static void
8390 mention (const breakpoint *b)
8391 {
8392 b->print_mention ();
8393 current_uiout->text ("\n");
8394 }
8395 \f
8396
8397 static bool bp_loc_is_permanent (struct bp_location *loc);
8398
8399 /* Handle "set breakpoint auto-hw on".
8400
8401 If the explicitly specified breakpoint type is not hardware
8402 breakpoint, check the memory map to see whether the breakpoint
8403 address is in read-only memory.
8404
8405 - location type is not hardware breakpoint, memory is read-only.
8406 We change the type of the location to hardware breakpoint.
8407
8408 - location type is hardware breakpoint, memory is read-write. This
8409 means we've previously made the location hardware one, but then the
8410 memory map changed, so we undo.
8411 */
8412
8413 static void
8414 handle_automatic_hardware_breakpoints (bp_location *bl)
8415 {
8416 if (automatic_hardware_breakpoints
8417 && bl->owner->type != bp_hardware_breakpoint
8418 && (bl->loc_type == bp_loc_software_breakpoint
8419 || bl->loc_type == bp_loc_hardware_breakpoint))
8420 {
8421 /* When breakpoints are removed, remove_breakpoints will use
8422 location types we've just set here, the only possible problem
8423 is that memory map has changed during running program, but
8424 it's not going to work anyway with current gdb. */
8425 mem_region *mr = lookup_mem_region (bl->address);
8426
8427 if (mr != nullptr)
8428 {
8429 enum bp_loc_type new_type;
8430
8431 if (mr->attrib.mode != MEM_RW)
8432 new_type = bp_loc_hardware_breakpoint;
8433 else
8434 new_type = bp_loc_software_breakpoint;
8435
8436 if (new_type != bl->loc_type)
8437 {
8438 static bool said = false;
8439
8440 bl->loc_type = new_type;
8441 if (!said)
8442 {
8443 gdb_printf (_("Note: automatically using "
8444 "hardware breakpoints for "
8445 "read-only addresses.\n"));
8446 said = true;
8447 }
8448 }
8449 }
8450 }
8451 }
8452
8453 bp_location *
8454 code_breakpoint::add_location (const symtab_and_line &sal)
8455 {
8456 CORE_ADDR adjusted_address;
8457 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8458
8459 if (loc_gdbarch == NULL)
8460 loc_gdbarch = gdbarch;
8461
8462 /* Adjust the breakpoint's address prior to allocating a location.
8463 Once we call allocate_location(), that mostly uninitialized
8464 location will be placed on the location chain. Adjustment of the
8465 breakpoint may cause target_read_memory() to be called and we do
8466 not want its scan of the location chain to find a breakpoint and
8467 location that's only been partially initialized. */
8468 adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8469 sal.pc, type,
8470 sal.pspace);
8471
8472 /* Sort the locations by their ADDRESS. */
8473 bp_location *new_loc = this->allocate_location ();
8474
8475 new_loc->requested_address = sal.pc;
8476 new_loc->address = adjusted_address;
8477 new_loc->pspace = sal.pspace;
8478 new_loc->probe.prob = sal.prob;
8479 new_loc->probe.objfile = sal.objfile;
8480 gdb_assert (new_loc->pspace != NULL);
8481 new_loc->section = sal.section;
8482 new_loc->gdbarch = loc_gdbarch;
8483 new_loc->line_number = sal.line;
8484 new_loc->symtab = sal.symtab;
8485 new_loc->symbol = sal.symbol;
8486 new_loc->msymbol = sal.msymbol;
8487 new_loc->objfile = sal.objfile;
8488
8489 breakpoint::add_location (*new_loc);
8490
8491 set_breakpoint_location_function (new_loc);
8492
8493 /* While by definition, permanent breakpoints are already present in the
8494 code, we don't mark the location as inserted. Normally one would expect
8495 that GDB could rely on that breakpoint instruction to stop the program,
8496 thus removing the need to insert its own breakpoint, except that executing
8497 the breakpoint instruction can kill the target instead of reporting a
8498 SIGTRAP. E.g., on SPARC, when interrupts are disabled, executing the
8499 instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8500 with "Trap 0x02 while interrupts disabled, Error state". Letting the
8501 breakpoint be inserted normally results in QEMU knowing about the GDB
8502 breakpoint, and thus trap before the breakpoint instruction is executed.
8503 (If GDB later needs to continue execution past the permanent breakpoint,
8504 it manually increments the PC, thus avoiding executing the breakpoint
8505 instruction.) */
8506 if (bp_loc_is_permanent (new_loc))
8507 new_loc->permanent = 1;
8508
8509 return new_loc;
8510 }
8511 \f
8512
8513 /* Return true if LOC is pointing to a permanent breakpoint,
8514 return false otherwise. */
8515
8516 static bool
8517 bp_loc_is_permanent (struct bp_location *loc)
8518 {
8519 gdb_assert (loc != NULL);
8520
8521 /* If we have a non-breakpoint-backed catchpoint or a software
8522 watchpoint, just return 0. We should not attempt to read from
8523 the addresses the locations of these breakpoint types point to.
8524 gdbarch_program_breakpoint_here_p, below, will attempt to read
8525 memory. */
8526 if (!bl_address_is_meaningful (loc))
8527 return false;
8528
8529 scoped_restore_current_pspace_and_thread restore_pspace_thread;
8530 switch_to_program_space_and_thread (loc->pspace);
8531 return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8532 }
8533
8534 /* Build a command list for the dprintf corresponding to the current
8535 settings of the dprintf style options. */
8536
8537 static void
8538 update_dprintf_command_list (struct breakpoint *b)
8539 {
8540 const char *dprintf_args = b->extra_string.get ();
8541 gdb::unique_xmalloc_ptr<char> printf_line = nullptr;
8542
8543 if (!dprintf_args)
8544 return;
8545
8546 dprintf_args = skip_spaces (dprintf_args);
8547
8548 /* Allow a comma, as it may have terminated a location, but don't
8549 insist on it. */
8550 if (*dprintf_args == ',')
8551 ++dprintf_args;
8552 dprintf_args = skip_spaces (dprintf_args);
8553
8554 if (*dprintf_args != '"')
8555 error (_("Bad format string, missing '\"'."));
8556
8557 if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8558 printf_line = xstrprintf ("printf %s", dprintf_args);
8559 else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8560 {
8561 if (dprintf_function.empty ())
8562 error (_("No function supplied for dprintf call"));
8563
8564 if (!dprintf_channel.empty ())
8565 printf_line = xstrprintf ("call (void) %s (%s,%s)",
8566 dprintf_function.c_str (),
8567 dprintf_channel.c_str (),
8568 dprintf_args);
8569 else
8570 printf_line = xstrprintf ("call (void) %s (%s)",
8571 dprintf_function.c_str (),
8572 dprintf_args);
8573 }
8574 else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8575 {
8576 if (target_can_run_breakpoint_commands ())
8577 printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8578 else
8579 {
8580 warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8581 printf_line = xstrprintf ("printf %s", dprintf_args);
8582 }
8583 }
8584 else
8585 internal_error (_("Invalid dprintf style."));
8586
8587 gdb_assert (printf_line != NULL);
8588
8589 /* Manufacture a printf sequence. */
8590 struct command_line *printf_cmd_line
8591 = new struct command_line (simple_control, printf_line.release ());
8592 breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8593 command_lines_deleter ()));
8594 }
8595
8596 /* Update all dprintf commands, making their command lists reflect
8597 current style settings. */
8598
8599 static void
8600 update_dprintf_commands (const char *args, int from_tty,
8601 struct cmd_list_element *c)
8602 {
8603 for (breakpoint &b : all_breakpoints ())
8604 if (b.type == bp_dprintf)
8605 update_dprintf_command_list (&b);
8606 }
8607
8608 code_breakpoint::code_breakpoint (struct gdbarch *gdbarch_,
8609 enum bptype type_,
8610 gdb::array_view<const symtab_and_line> sals,
8611 location_spec_up &&locspec_,
8612 gdb::unique_xmalloc_ptr<char> filter_,
8613 gdb::unique_xmalloc_ptr<char> cond_string_,
8614 gdb::unique_xmalloc_ptr<char> extra_string_,
8615 enum bpdisp disposition_,
8616 int thread_, int task_, int inferior_,
8617 int ignore_count_,
8618 int from_tty,
8619 int enabled_, unsigned flags,
8620 int display_canonical_)
8621 : breakpoint (gdbarch_, type_)
8622 {
8623 int i;
8624
8625 if (type == bp_hardware_breakpoint)
8626 {
8627 int target_resources_ok;
8628
8629 i = hw_breakpoint_used_count ();
8630 target_resources_ok =
8631 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8632 i + 1, 0);
8633 if (target_resources_ok == 0)
8634 error (_("No hardware breakpoint support in the target."));
8635 else if (target_resources_ok < 0)
8636 error (_("Hardware breakpoints used exceeds limit."));
8637 }
8638
8639 gdb_assert (!sals.empty ());
8640
8641 /* At most one of thread, task, or inferior can be set on any breakpoint. */
8642 gdb_assert (((thread == -1 ? 0 : 1)
8643 + (task == -1 ? 0 : 1)
8644 + (inferior == -1 ? 0 : 1)) <= 1);
8645
8646 thread = thread_;
8647 task = task_;
8648 inferior = inferior_;
8649
8650 cond_string = std::move (cond_string_);
8651 extra_string = std::move (extra_string_);
8652 ignore_count = ignore_count_;
8653 enable_state = enabled_ ? bp_enabled : bp_disabled;
8654 disposition = disposition_;
8655
8656 if (type == bp_static_tracepoint
8657 || type == bp_static_marker_tracepoint)
8658 {
8659 auto *t = gdb::checked_static_cast<tracepoint *> (this);
8660 struct static_tracepoint_marker marker;
8661
8662 if (strace_marker_p (this))
8663 {
8664 /* We already know the marker exists, otherwise, we wouldn't
8665 see a sal for it. */
8666 const char *p = &locspec_->to_string ()[3];
8667 const char *endp;
8668
8669 p = skip_spaces (p);
8670
8671 endp = skip_to_space (p);
8672
8673 t->static_trace_marker_id.assign (p, endp - p);
8674
8675 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8676 t->static_trace_marker_id.c_str ());
8677 }
8678 else if (target_static_tracepoint_marker_at (sals[0].pc, &marker))
8679 {
8680 t->static_trace_marker_id = std::move (marker.str_id);
8681
8682 gdb_printf (_("Probed static tracepoint marker \"%s\"\n"),
8683 t->static_trace_marker_id.c_str ());
8684 }
8685 else
8686 warning (_("Couldn't determine the static tracepoint marker to probe"));
8687 }
8688
8689 for (const auto &sal : sals)
8690 {
8691 if (from_tty)
8692 {
8693 struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8694 if (loc_gdbarch == nullptr)
8695 loc_gdbarch = gdbarch;
8696
8697 describe_other_breakpoints (loc_gdbarch,
8698 sal.pspace, sal.pc, sal.section, thread);
8699 }
8700
8701 bp_location *new_loc = add_location (sal);
8702 if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8703 new_loc->inserted = 1;
8704
8705 /* Do not set breakpoint locations conditions yet. As locations
8706 are inserted, they get sorted based on their addresses. Let
8707 the list stabilize to have reliable location numbers. */
8708
8709 /* Dynamic printf requires and uses additional arguments on the
8710 command line, otherwise it's an error. */
8711 if (type == bp_dprintf)
8712 {
8713 if (extra_string != nullptr)
8714 update_dprintf_command_list (this);
8715 else
8716 error (_("Format string required"));
8717 }
8718 else if (extra_string != nullptr)
8719 error (_("Garbage '%s' at end of command"), extra_string.get ());
8720 }
8721
8722 /* The order of the locations is now stable. Set the location
8723 condition using the location's number. */
8724 int loc_num = 1;
8725 for (bp_location &bl : locations ())
8726 {
8727 if (cond_string != nullptr)
8728 set_breakpoint_location_condition (cond_string.get (), &bl,
8729 number, loc_num);
8730
8731 ++loc_num;
8732 }
8733
8734 display_canonical = display_canonical_;
8735 if (locspec_ != nullptr)
8736 locspec = std::move (locspec_);
8737 else
8738 locspec = new_address_location_spec (this->first_loc ().address, NULL, 0);
8739 filter = std::move (filter_);
8740 }
8741
8742 static void
8743 create_breakpoint_sal (struct gdbarch *gdbarch,
8744 gdb::array_view<const symtab_and_line> sals,
8745 location_spec_up &&locspec,
8746 gdb::unique_xmalloc_ptr<char> filter,
8747 gdb::unique_xmalloc_ptr<char> cond_string,
8748 gdb::unique_xmalloc_ptr<char> extra_string,
8749 enum bptype type, enum bpdisp disposition,
8750 int thread, int task, int inferior, int ignore_count,
8751 int from_tty,
8752 int enabled, int internal, unsigned flags,
8753 int display_canonical)
8754 {
8755 std::unique_ptr<code_breakpoint> b
8756 = new_breakpoint_from_type (gdbarch,
8757 type,
8758 sals,
8759 std::move (locspec),
8760 std::move (filter),
8761 std::move (cond_string),
8762 std::move (extra_string),
8763 disposition,
8764 thread, task, inferior, ignore_count,
8765 from_tty,
8766 enabled, flags,
8767 display_canonical);
8768
8769 install_breakpoint (internal, std::move (b), 0);
8770 }
8771
8772 /* Add SALS.nelts breakpoints to the breakpoint table. For each
8773 SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8774 value. COND_STRING, if not NULL, specified the condition to be
8775 used for all breakpoints. Essentially the only case where
8776 SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8777 function. In that case, it's still not possible to specify
8778 separate conditions for different overloaded functions, so
8779 we take just a single condition string.
8780
8781 NOTE: If the function succeeds, the caller is expected to cleanup
8782 the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8783 array contents). If the function fails (error() is called), the
8784 caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8785 COND and SALS arrays and each of those arrays contents. */
8786
8787 static void
8788 create_breakpoints_sal (struct gdbarch *gdbarch,
8789 struct linespec_result *canonical,
8790 gdb::unique_xmalloc_ptr<char> cond_string,
8791 gdb::unique_xmalloc_ptr<char> extra_string,
8792 enum bptype type, enum bpdisp disposition,
8793 int thread, int task, int inferior,
8794 int ignore_count,
8795 int from_tty,
8796 int enabled, int internal, unsigned flags)
8797 {
8798 if (canonical->pre_expanded)
8799 gdb_assert (canonical->lsals.size () == 1);
8800
8801 for (const auto &lsal : canonical->lsals)
8802 {
8803 /* Note that 'location' can be NULL in the case of a plain
8804 'break', without arguments. */
8805 location_spec_up locspec
8806 = (canonical->locspec != nullptr
8807 ? canonical->locspec->clone ()
8808 : nullptr);
8809 gdb::unique_xmalloc_ptr<char> filter_string
8810 (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
8811
8812 create_breakpoint_sal (gdbarch, lsal.sals,
8813 std::move (locspec),
8814 std::move (filter_string),
8815 std::move (cond_string),
8816 std::move (extra_string),
8817 type, disposition,
8818 thread, task, inferior, ignore_count,
8819 from_tty, enabled, internal, flags,
8820 canonical->special_display);
8821 }
8822 }
8823
8824 /* Parse LOCSPEC which is assumed to be a SAL specification possibly
8825 followed by conditionals. On return, SALS contains an array of SAL
8826 addresses found. LOCSPEC points to the end of the SAL (for
8827 linespec locspecs).
8828
8829 The array and the line spec strings are allocated on the heap, it is
8830 the caller's responsibility to free them. */
8831
8832 static void
8833 parse_breakpoint_sals (location_spec *locspec,
8834 struct linespec_result *canonical)
8835 {
8836 struct symtab_and_line cursal;
8837
8838 if (locspec->type () == LINESPEC_LOCATION_SPEC)
8839 {
8840 const char *spec
8841 = as_linespec_location_spec (locspec)->spec_string.get ();
8842
8843 if (spec == NULL)
8844 {
8845 /* The last displayed codepoint, if it's valid, is our default
8846 breakpoint address. */
8847 if (last_displayed_sal_is_valid ())
8848 {
8849 /* Set sal's pspace, pc, symtab, and line to the values
8850 corresponding to the last call to print_frame_info.
8851 Be sure to reinitialize LINE with NOTCURRENT == 0
8852 as the breakpoint line number is inappropriate otherwise.
8853 find_pc_line would adjust PC, re-set it back. */
8854 symtab_and_line sal = get_last_displayed_sal ();
8855 CORE_ADDR pc = sal.pc;
8856
8857 sal = find_pc_line (pc, 0);
8858
8859 /* "break" without arguments is equivalent to "break *PC"
8860 where PC is the last displayed codepoint's address. So
8861 make sure to set sal.explicit_pc to prevent GDB from
8862 trying to expand the list of sals to include all other
8863 instances with the same symtab and line. */
8864 sal.pc = pc;
8865 sal.explicit_pc = 1;
8866
8867 struct linespec_sals lsal;
8868 lsal.sals = {sal};
8869 lsal.canonical = NULL;
8870
8871 canonical->lsals.push_back (std::move (lsal));
8872 return;
8873 }
8874 else
8875 error (_("No default breakpoint address now."));
8876 }
8877 }
8878
8879 /* Force almost all breakpoints to be in terms of the
8880 current_source_symtab (which is decode_line_1's default).
8881 This should produce the results we want almost all of the
8882 time while leaving default_breakpoint_* alone.
8883
8884 ObjC: However, don't match an Objective-C method name which
8885 may have a '+' or '-' succeeded by a '['. */
8886 cursal = get_current_source_symtab_and_line ();
8887 if (last_displayed_sal_is_valid ())
8888 {
8889 const char *spec = NULL;
8890
8891 if (locspec->type () == LINESPEC_LOCATION_SPEC)
8892 spec = as_linespec_location_spec (locspec)->spec_string.get ();
8893
8894 if (!cursal.symtab
8895 || (spec != NULL
8896 && strchr ("+-", spec[0]) != NULL
8897 && spec[1] != '['))
8898 {
8899 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8900 get_last_displayed_symtab (),
8901 get_last_displayed_line (),
8902 canonical, NULL, NULL);
8903 return;
8904 }
8905 }
8906
8907 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, NULL,
8908 cursal.symtab, cursal.line, canonical, NULL, NULL);
8909 }
8910
8911
8912 /* Convert each SAL into a real PC. Verify that the PC can be
8913 inserted as a breakpoint. If it can't throw an error. */
8914
8915 static void
8916 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
8917 {
8918 for (auto &sal : sals)
8919 resolve_sal_pc (&sal);
8920 }
8921
8922 /* Fast tracepoints may have restrictions on valid locations. For
8923 instance, a fast tracepoint using a jump instead of a trap will
8924 likely have to overwrite more bytes than a trap would, and so can
8925 only be placed where the instruction is longer than the jump, or a
8926 multi-instruction sequence does not have a jump into the middle of
8927 it, etc. */
8928
8929 static void
8930 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8931 gdb::array_view<const symtab_and_line> sals)
8932 {
8933 for (const auto &sal : sals)
8934 {
8935 struct gdbarch *sarch;
8936
8937 sarch = get_sal_arch (sal);
8938 /* We fall back to GDBARCH if there is no architecture
8939 associated with SAL. */
8940 if (sarch == NULL)
8941 sarch = gdbarch;
8942 std::string msg;
8943 if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
8944 error (_("May not have a fast tracepoint at %s%s"),
8945 paddress (sarch, sal.pc), msg.c_str ());
8946 }
8947 }
8948
8949 /* Given TOK, a string specification of condition and thread, as accepted
8950 by the 'break' command, extract the condition string into *COND_STRING.
8951 If no condition string is found then *COND_STRING is set to nullptr.
8952
8953 If the breakpoint specification has an associated thread, task, or
8954 inferior, these are extracted into *THREAD, *TASK, and *INFERIOR
8955 respectively, otherwise these arguments are set to -1 (for THREAD and
8956 INFERIOR) or 0 (for TASK).
8957
8958 PC identifies the context at which the condition should be parsed. */
8959
8960 static void
8961 find_condition_and_thread (const char *tok, CORE_ADDR pc,
8962 gdb::unique_xmalloc_ptr<char> *cond_string,
8963 int *thread, int *inferior, int *task,
8964 gdb::unique_xmalloc_ptr<char> *rest)
8965 {
8966 cond_string->reset ();
8967 *thread = -1;
8968 *inferior = -1;
8969 *task = -1;
8970 rest->reset ();
8971 bool force = false;
8972
8973 while (tok && *tok)
8974 {
8975 const char *end_tok;
8976 int toklen;
8977 const char *cond_start = NULL;
8978 const char *cond_end = NULL;
8979
8980 tok = skip_spaces (tok);
8981
8982 if ((*tok == '"' || *tok == ',') && rest)
8983 {
8984 rest->reset (savestring (tok, strlen (tok)));
8985 break;
8986 }
8987
8988 end_tok = skip_to_space (tok);
8989
8990 toklen = end_tok - tok;
8991
8992 if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8993 {
8994 tok = cond_start = end_tok + 1;
8995 try
8996 {
8997 parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
8998 }
8999 catch (const gdb_exception_error &)
9000 {
9001 if (!force)
9002 throw;
9003 else
9004 tok = tok + strlen (tok);
9005 }
9006 cond_end = tok;
9007 cond_string->reset (savestring (cond_start, cond_end - cond_start));
9008 }
9009 else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
9010 {
9011 tok = tok + toklen;
9012 force = true;
9013 }
9014 else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9015 {
9016 const char *tmptok;
9017 struct thread_info *thr;
9018
9019 if (*thread != -1)
9020 error(_("You can specify only one thread."));
9021
9022 if (*task != -1)
9023 error (_("You can specify only one of thread or task."));
9024
9025 if (*inferior != -1)
9026 error (_("You can specify only one of inferior or thread."));
9027
9028 tok = end_tok + 1;
9029 thr = parse_thread_id (tok, &tmptok);
9030 if (tok == tmptok)
9031 error (_("Junk after thread keyword."));
9032 *thread = thr->global_num;
9033 tok = tmptok;
9034 }
9035 else if (toklen >= 1 && strncmp (tok, "inferior", toklen) == 0)
9036 {
9037 if (*inferior != -1)
9038 error(_("You can specify only one inferior."));
9039
9040 if (*task != -1)
9041 error (_("You can specify only one of inferior or task."));
9042
9043 if (*thread != -1)
9044 error (_("You can specify only one of inferior or thread."));
9045
9046 char *tmptok;
9047 tok = end_tok + 1;
9048 *inferior = strtol (tok, &tmptok, 0);
9049 if (tok == tmptok)
9050 error (_("Junk after inferior keyword."));
9051 if (!valid_global_inferior_id (*inferior))
9052 error (_("Unknown inferior number %d."), *inferior);
9053 tok = tmptok;
9054 }
9055 else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9056 {
9057 char *tmptok;
9058
9059 if (*task != -1)
9060 error(_("You can specify only one task."));
9061
9062 if (*thread != -1)
9063 error (_("You can specify only one of thread or task."));
9064
9065 if (*inferior != -1)
9066 error (_("You can specify only one of inferior or task."));
9067
9068 tok = end_tok + 1;
9069 *task = strtol (tok, &tmptok, 0);
9070 if (tok == tmptok)
9071 error (_("Junk after task keyword."));
9072 if (!valid_task_id (*task))
9073 error (_("Unknown task %d."), *task);
9074 tok = tmptok;
9075 }
9076 else if (rest)
9077 {
9078 rest->reset (savestring (tok, strlen (tok)));
9079 break;
9080 }
9081 else
9082 error (_("Junk at end of arguments."));
9083 }
9084 }
9085
9086 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
9087 succeeds. The parsed values are written to COND_STRING, THREAD,
9088 TASK, and REST. See the comment of 'find_condition_and_thread'
9089 for the description of these parameters and INPUT. */
9090
9091 static void
9092 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
9093 const char *input,
9094 gdb::unique_xmalloc_ptr<char> *cond_string,
9095 int *thread, int *inferior, int *task,
9096 gdb::unique_xmalloc_ptr<char> *rest)
9097 {
9098 int num_failures = 0;
9099 for (auto &sal : sals)
9100 {
9101 gdb::unique_xmalloc_ptr<char> cond;
9102 int thread_id = -1;
9103 int inferior_id = -1;
9104 int task_id = -1;
9105 gdb::unique_xmalloc_ptr<char> remaining;
9106
9107 /* Here we want to parse 'arg' to separate condition from thread
9108 number. But because parsing happens in a context and the
9109 contexts of sals might be different, try each until there is
9110 success. Finding one successful parse is sufficient for our
9111 goal. When setting the breakpoint we'll re-parse the
9112 condition in the context of each sal. */
9113 try
9114 {
9115 find_condition_and_thread (input, sal.pc, &cond, &thread_id,
9116 &inferior_id, &task_id, &remaining);
9117 *cond_string = std::move (cond);
9118 /* A value of -1 indicates that these fields are unset. At most
9119 one of these fields should be set (to a value other than -1)
9120 at this point. */
9121 gdb_assert (((thread_id == -1 ? 1 : 0)
9122 + (task_id == -1 ? 1 : 0)
9123 + (inferior_id == -1 ? 1 : 0)) >= 2);
9124 *thread = thread_id;
9125 *inferior = inferior_id;
9126 *task = task_id;
9127 *rest = std::move (remaining);
9128 break;
9129 }
9130 catch (const gdb_exception_error &e)
9131 {
9132 num_failures++;
9133 /* If no sal remains, do not continue. */
9134 if (num_failures == sals.size ())
9135 throw;
9136 }
9137 }
9138 }
9139
9140 /* Decode a static tracepoint marker spec. */
9141
9142 static std::vector<symtab_and_line>
9143 decode_static_tracepoint_spec (const char **arg_p)
9144 {
9145 const char *p = &(*arg_p)[3];
9146 const char *endp;
9147
9148 p = skip_spaces (p);
9149
9150 endp = skip_to_space (p);
9151
9152 std::string marker_str (p, endp - p);
9153
9154 std::vector<static_tracepoint_marker> markers
9155 = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9156 if (markers.empty ())
9157 error (_("No known static tracepoint marker named %s"),
9158 marker_str.c_str ());
9159
9160 std::vector<symtab_and_line> sals;
9161 sals.reserve (markers.size ());
9162
9163 for (const static_tracepoint_marker &marker : markers)
9164 {
9165 symtab_and_line sal = find_pc_line (marker.address, 0);
9166 sal.pc = marker.address;
9167 sals.push_back (sal);
9168 }
9169
9170 *arg_p = endp;
9171 return sals;
9172 }
9173
9174 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
9175 according to IS_TRACEPOINT. */
9176
9177 static const struct breakpoint_ops *
9178 breakpoint_ops_for_location_spec_type (enum location_spec_type locspec_type,
9179 bool is_tracepoint)
9180 {
9181 if (is_tracepoint)
9182 {
9183 if (locspec_type == PROBE_LOCATION_SPEC)
9184 return &tracepoint_probe_breakpoint_ops;
9185 else
9186 return &code_breakpoint_ops;
9187 }
9188 else
9189 {
9190 if (locspec_type == PROBE_LOCATION_SPEC)
9191 return &bkpt_probe_breakpoint_ops;
9192 else
9193 return &code_breakpoint_ops;
9194 }
9195 }
9196
9197 /* See breakpoint.h. */
9198
9199 const struct breakpoint_ops *
9200 breakpoint_ops_for_location_spec (const location_spec *locspec,
9201 bool is_tracepoint)
9202 {
9203 if (locspec != nullptr)
9204 return (breakpoint_ops_for_location_spec_type
9205 (locspec->type (), is_tracepoint));
9206 return &code_breakpoint_ops;
9207 }
9208
9209 /* See breakpoint.h. */
9210
9211 int
9212 create_breakpoint (struct gdbarch *gdbarch,
9213 location_spec *locspec,
9214 const char *cond_string,
9215 int thread, int inferior,
9216 const char *extra_string,
9217 bool force_condition, int parse_extra,
9218 int tempflag, enum bptype type_wanted,
9219 int ignore_count,
9220 enum auto_boolean pending_break_support,
9221 const struct breakpoint_ops *ops,
9222 int from_tty, int enabled, int internal,
9223 unsigned flags)
9224 {
9225 struct linespec_result canonical;
9226 bool pending = false;
9227 int task = -1;
9228 int prev_bkpt_count = breakpoint_count;
9229
9230 gdb_assert (thread == -1 || thread > 0);
9231 gdb_assert (inferior == -1 || inferior > 0);
9232 gdb_assert (thread == -1 || inferior == -1);
9233
9234 gdb_assert (ops != NULL);
9235
9236 /* If extra_string isn't useful, set it to NULL. */
9237 if (extra_string != NULL && *extra_string == '\0')
9238 extra_string = NULL;
9239
9240 try
9241 {
9242 ops->create_sals_from_location_spec (locspec, &canonical);
9243 }
9244 catch (const gdb_exception_error &e)
9245 {
9246 /* If caller is interested in rc value from parse, set
9247 value. */
9248 if (e.error == NOT_FOUND_ERROR)
9249 {
9250 /* If pending breakpoint support is turned off, throw
9251 error. */
9252
9253 if (pending_break_support == AUTO_BOOLEAN_FALSE)
9254 throw;
9255
9256 exception_print (gdb_stderr, e);
9257
9258 /* If pending breakpoint support is auto query and the user
9259 selects no, then simply return the error code. */
9260 if (pending_break_support == AUTO_BOOLEAN_AUTO
9261 && !nquery (_("Make %s pending on future shared library load? "),
9262 bptype_string (type_wanted)))
9263 return 0;
9264
9265 /* At this point, either the user was queried about setting
9266 a pending breakpoint and selected yes, or pending
9267 breakpoint behavior is on and thus a pending breakpoint
9268 is defaulted on behalf of the user. */
9269 pending = true;
9270 }
9271 else
9272 throw;
9273 }
9274
9275 if (!pending && canonical.lsals.empty ())
9276 return 0;
9277
9278 /* Resolve all line numbers to PC's and verify that the addresses
9279 are ok for the target. */
9280 if (!pending)
9281 {
9282 for (auto &lsal : canonical.lsals)
9283 breakpoint_sals_to_pc (lsal.sals);
9284 }
9285
9286 /* Fast tracepoints may have additional restrictions on location. */
9287 if (!pending && type_wanted == bp_fast_tracepoint)
9288 {
9289 for (const auto &lsal : canonical.lsals)
9290 check_fast_tracepoint_sals (gdbarch, lsal.sals);
9291 }
9292
9293 /* Verify that condition can be parsed, before setting any
9294 breakpoints. Allocate a separate condition expression for each
9295 breakpoint. */
9296 if (!pending)
9297 {
9298 gdb::unique_xmalloc_ptr<char> cond_string_copy;
9299 gdb::unique_xmalloc_ptr<char> extra_string_copy;
9300
9301 if (parse_extra)
9302 {
9303 gdb::unique_xmalloc_ptr<char> rest;
9304 gdb::unique_xmalloc_ptr<char> cond;
9305
9306 const linespec_sals &lsal = canonical.lsals[0];
9307
9308 find_condition_and_thread_for_sals (lsal.sals, extra_string,
9309 &cond, &thread, &inferior,
9310 &task, &rest);
9311 cond_string_copy = std::move (cond);
9312 extra_string_copy = std::move (rest);
9313 }
9314 else
9315 {
9316 if (type_wanted != bp_dprintf
9317 && extra_string != NULL && *extra_string != '\0')
9318 error (_("Garbage '%s' at end of location"), extra_string);
9319
9320 /* Check the validity of the condition. We should error out
9321 if the condition is invalid at all of the locations and
9322 if it is not forced. In the PARSE_EXTRA case above, this
9323 check is done when parsing the EXTRA_STRING. */
9324 if (cond_string != nullptr && !force_condition)
9325 {
9326 int num_failures = 0;
9327 const linespec_sals &lsal = canonical.lsals[0];
9328 for (const auto &sal : lsal.sals)
9329 {
9330 const char *cond = cond_string;
9331 try
9332 {
9333 parse_exp_1 (&cond, sal.pc, block_for_pc (sal.pc), 0);
9334 /* One success is sufficient to keep going. */
9335 break;
9336 }
9337 catch (const gdb_exception_error &)
9338 {
9339 num_failures++;
9340 /* If this is the last sal, error out. */
9341 if (num_failures == lsal.sals.size ())
9342 throw;
9343 }
9344 }
9345 }
9346
9347 /* Create a private copy of condition string. */
9348 if (cond_string)
9349 cond_string_copy.reset (xstrdup (cond_string));
9350 /* Create a private copy of any extra string. */
9351 if (extra_string)
9352 extra_string_copy.reset (xstrdup (extra_string));
9353 }
9354
9355 ops->create_breakpoints_sal (gdbarch, &canonical,
9356 std::move (cond_string_copy),
9357 std::move (extra_string_copy),
9358 type_wanted,
9359 tempflag ? disp_del : disp_donttouch,
9360 thread, task, inferior, ignore_count,
9361 from_tty, enabled, internal, flags);
9362 }
9363 else
9364 {
9365 std::unique_ptr <breakpoint> b = new_breakpoint_from_type (gdbarch,
9366 type_wanted);
9367 b->locspec = locspec->clone ();
9368
9369 if (parse_extra)
9370 b->cond_string = NULL;
9371 else
9372 {
9373 /* Create a private copy of condition string. */
9374 b->cond_string.reset (cond_string != NULL
9375 ? xstrdup (cond_string)
9376 : NULL);
9377 b->thread = thread;
9378 }
9379
9380 /* Create a private copy of any extra string. */
9381 b->extra_string.reset (extra_string != NULL
9382 ? xstrdup (extra_string)
9383 : NULL);
9384 b->ignore_count = ignore_count;
9385 b->disposition = tempflag ? disp_del : disp_donttouch;
9386 b->condition_not_parsed = 1;
9387 b->enable_state = enabled ? bp_enabled : bp_disabled;
9388 if ((type_wanted != bp_breakpoint
9389 && type_wanted != bp_hardware_breakpoint) || thread != -1)
9390 b->pspace = current_program_space;
9391
9392 install_breakpoint (internal, std::move (b), 0);
9393 }
9394
9395 if (canonical.lsals.size () > 1)
9396 {
9397 warning (_("Multiple breakpoints were set.\nUse the "
9398 "\"delete\" command to delete unwanted breakpoints."));
9399 prev_breakpoint_count = prev_bkpt_count;
9400 }
9401
9402 update_global_location_list (UGLL_MAY_INSERT);
9403
9404 return 1;
9405 }
9406
9407 /* Set a breakpoint.
9408 ARG is a string describing breakpoint address,
9409 condition, and thread.
9410 FLAG specifies if a breakpoint is hardware on,
9411 and if breakpoint is temporary, using BP_HARDWARE_FLAG
9412 and BP_TEMPFLAG. */
9413
9414 static void
9415 break_command_1 (const char *arg, int flag, int from_tty)
9416 {
9417 int tempflag = flag & BP_TEMPFLAG;
9418 enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9419 ? bp_hardware_breakpoint
9420 : bp_breakpoint);
9421
9422 location_spec_up locspec = string_to_location_spec (&arg, current_language);
9423 const struct breakpoint_ops *ops
9424 = breakpoint_ops_for_location_spec (locspec.get (),
9425 false /* is_tracepoint */);
9426
9427 create_breakpoint (get_current_arch (),
9428 locspec.get (),
9429 NULL,
9430 -1 /* thread */, -1 /* inferior */,
9431 arg, false, 1 /* parse arg */,
9432 tempflag, type_wanted,
9433 0 /* Ignore count */,
9434 pending_break_support,
9435 ops,
9436 from_tty,
9437 1 /* enabled */,
9438 0 /* internal */,
9439 0);
9440 }
9441
9442 /* Helper function for break_command_1 and disassemble_command. */
9443
9444 void
9445 resolve_sal_pc (struct symtab_and_line *sal)
9446 {
9447 CORE_ADDR pc;
9448
9449 if (sal->pc == 0 && sal->symtab != NULL)
9450 {
9451 if (!find_line_pc (sal->symtab, sal->line, &pc))
9452 error (_("No line %d in file \"%s\"."),
9453 sal->line, symtab_to_filename_for_display (sal->symtab));
9454 sal->pc = pc;
9455
9456 /* If this SAL corresponds to a breakpoint inserted using a line
9457 number, then skip the function prologue if necessary. */
9458 if (sal->explicit_line)
9459 skip_prologue_sal (sal);
9460 }
9461
9462 if (sal->section == 0 && sal->symtab != NULL)
9463 {
9464 const struct blockvector *bv;
9465 const struct block *b;
9466 struct symbol *sym;
9467
9468 bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9469 sal->symtab->compunit ());
9470 if (bv != NULL)
9471 {
9472 sym = b->linkage_function ();
9473 if (sym != NULL)
9474 sal->section
9475 = sym->obj_section (sal->symtab->compunit ()->objfile ());
9476 else
9477 {
9478 /* It really is worthwhile to have the section, so we'll
9479 just have to look harder. This case can be executed
9480 if we have line numbers but no functions (as can
9481 happen in assembly source). */
9482
9483 scoped_restore_current_pspace_and_thread restore_pspace_thread;
9484 switch_to_program_space_and_thread (sal->pspace);
9485
9486 bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9487 if (msym.minsym)
9488 sal->section = msym.obj_section ();
9489 }
9490 }
9491 }
9492 }
9493
9494 void
9495 break_command (const char *arg, int from_tty)
9496 {
9497 break_command_1 (arg, 0, from_tty);
9498 }
9499
9500 void
9501 tbreak_command (const char *arg, int from_tty)
9502 {
9503 break_command_1 (arg, BP_TEMPFLAG, from_tty);
9504 }
9505
9506 static void
9507 hbreak_command (const char *arg, int from_tty)
9508 {
9509 break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9510 }
9511
9512 static void
9513 thbreak_command (const char *arg, int from_tty)
9514 {
9515 break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9516 }
9517
9518 /* The dynamic printf command is mostly like a regular breakpoint, but
9519 with a prewired command list consisting of a single output command,
9520 built from extra arguments supplied on the dprintf command
9521 line. */
9522
9523 static void
9524 dprintf_command (const char *arg, int from_tty)
9525 {
9526 location_spec_up locspec = string_to_location_spec (&arg, current_language);
9527
9528 /* If non-NULL, ARG should have been advanced past the location;
9529 the next character must be ','. */
9530 if (arg != NULL)
9531 {
9532 if (arg[0] != ',' || arg[1] == '\0')
9533 error (_("Format string required"));
9534 else
9535 {
9536 /* Skip the comma. */
9537 ++arg;
9538 }
9539 }
9540
9541 create_breakpoint (get_current_arch (),
9542 locspec.get (),
9543 NULL, -1, -1,
9544 arg, false, 1 /* parse arg */,
9545 0, bp_dprintf,
9546 0 /* Ignore count */,
9547 pending_break_support,
9548 &code_breakpoint_ops,
9549 from_tty,
9550 1 /* enabled */,
9551 0 /* internal */,
9552 0);
9553 }
9554
9555 static void
9556 agent_printf_command (const char *arg, int from_tty)
9557 {
9558 error (_("May only run agent-printf on the target"));
9559 }
9560
9561 /* Implement the "breakpoint_hit" method for ranged breakpoints. */
9562
9563 int
9564 ranged_breakpoint::breakpoint_hit (const struct bp_location *bl,
9565 const address_space *aspace,
9566 CORE_ADDR bp_addr,
9567 const target_waitstatus &ws)
9568 {
9569 if (ws.kind () != TARGET_WAITKIND_STOPPED
9570 || ws.sig () != GDB_SIGNAL_TRAP)
9571 return 0;
9572
9573 return breakpoint_address_match_range (bl->pspace->aspace.get (),
9574 bl->address, bl->length, aspace,
9575 bp_addr);
9576 }
9577
9578 /* Implement the "resources_needed" method for ranged breakpoints. */
9579
9580 int
9581 ranged_breakpoint::resources_needed (const struct bp_location *bl)
9582 {
9583 return target_ranged_break_num_registers ();
9584 }
9585
9586 /* Implement the "print_it" method for ranged breakpoints. */
9587
9588 enum print_stop_action
9589 ranged_breakpoint::print_it (const bpstat *bs) const
9590 {
9591 struct ui_out *uiout = current_uiout;
9592
9593 gdb_assert (type == bp_hardware_breakpoint);
9594
9595 /* Ranged breakpoints have only one location. */
9596 gdb_assert (this->has_single_location ());
9597
9598 annotate_breakpoint (number);
9599
9600 maybe_print_thread_hit_breakpoint (uiout);
9601
9602 if (disposition == disp_del)
9603 uiout->text ("Temporary ranged breakpoint ");
9604 else
9605 uiout->text ("Ranged breakpoint ");
9606 if (uiout->is_mi_like_p ())
9607 {
9608 uiout->field_string ("reason",
9609 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9610 uiout->field_string ("disp", bpdisp_text (disposition));
9611 }
9612 print_num_locno (bs, uiout);
9613 uiout->text (", ");
9614
9615 return PRINT_SRC_AND_LOC;
9616 }
9617
9618 /* Implement the "print_one" method for ranged breakpoints. */
9619
9620 bool
9621 ranged_breakpoint::print_one (const bp_location **last_loc) const
9622 {
9623 struct value_print_options opts;
9624 struct ui_out *uiout = current_uiout;
9625
9626 /* Ranged breakpoints have only one location. */
9627 gdb_assert (this->has_single_location ());
9628
9629 get_user_print_options (&opts);
9630
9631 if (opts.addressprint)
9632 /* We don't print the address range here, it will be printed later
9633 by ranged_breakpoint::print_one_detail. */
9634 uiout->field_skip ("addr");
9635 annotate_field (5);
9636 print_breakpoint_location (this, &this->first_loc ());
9637 *last_loc = &this->first_loc ();
9638
9639 return true;
9640 }
9641
9642 /* Implement the "print_one_detail" method for ranged breakpoints. */
9643
9644 void
9645 ranged_breakpoint::print_one_detail (struct ui_out *uiout) const
9646 {
9647 CORE_ADDR address_start, address_end;
9648 const bp_location &bl = this->first_loc ();
9649 string_file stb;
9650
9651 address_start = bl.address;
9652 address_end = address_start + bl.length - 1;
9653
9654 uiout->text ("\taddress range: ");
9655 stb.printf ("[%s, %s]",
9656 print_core_address (bl.gdbarch, address_start),
9657 print_core_address (bl.gdbarch, address_end));
9658 uiout->field_stream ("addr", stb);
9659 uiout->text ("\n");
9660 }
9661
9662 /* Implement the "print_mention" method for ranged breakpoints. */
9663
9664 void
9665 ranged_breakpoint::print_mention () const
9666 {
9667 const bp_location &bl = this->first_loc ();
9668 struct ui_out *uiout = current_uiout;
9669
9670 gdb_assert (type == bp_hardware_breakpoint);
9671
9672 uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9673 number, paddress (bl.gdbarch, bl.address),
9674 paddress (bl.gdbarch, bl.address + bl.length - 1));
9675 }
9676
9677 /* Implement the "print_recreate" method for ranged breakpoints. */
9678
9679 void
9680 ranged_breakpoint::print_recreate (struct ui_file *fp) const
9681 {
9682 gdb_printf (fp, "break-range %s, %s",
9683 locspec->to_string (),
9684 locspec_range_end->to_string ());
9685 print_recreate_thread (fp);
9686 }
9687
9688 /* Find the address where the end of the breakpoint range should be
9689 placed, given the SAL of the end of the range. This is so that if
9690 the user provides a line number, the end of the range is set to the
9691 last instruction of the given line. */
9692
9693 static CORE_ADDR
9694 find_breakpoint_range_end (struct symtab_and_line sal)
9695 {
9696 CORE_ADDR end;
9697
9698 /* If the user provided a PC value, use it. Otherwise,
9699 find the address of the end of the given location. */
9700 if (sal.explicit_pc)
9701 end = sal.pc;
9702 else
9703 {
9704 int ret;
9705 CORE_ADDR start;
9706
9707 ret = find_line_pc_range (sal, &start, &end);
9708 if (!ret)
9709 error (_("Could not find location of the end of the range."));
9710
9711 /* find_line_pc_range returns the start of the next line. */
9712 end--;
9713 }
9714
9715 return end;
9716 }
9717
9718 /* Implement the "break-range" CLI command. */
9719
9720 static void
9721 break_range_command (const char *arg, int from_tty)
9722 {
9723 const char *arg_start;
9724 struct linespec_result canonical_start, canonical_end;
9725 int bp_count, can_use_bp, length;
9726 CORE_ADDR end;
9727
9728 /* We don't support software ranged breakpoints. */
9729 if (target_ranged_break_num_registers () < 0)
9730 error (_("This target does not support hardware ranged breakpoints."));
9731
9732 bp_count = hw_breakpoint_used_count ();
9733 bp_count += target_ranged_break_num_registers ();
9734 can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9735 bp_count, 0);
9736 if (can_use_bp < 0)
9737 error (_("Hardware breakpoints used exceeds limit."));
9738
9739 arg = skip_spaces (arg);
9740 if (arg == NULL || arg[0] == '\0')
9741 error(_("No address range specified."));
9742
9743 arg_start = arg;
9744 location_spec_up start_locspec
9745 = string_to_location_spec (&arg, current_language);
9746 parse_breakpoint_sals (start_locspec.get (), &canonical_start);
9747
9748 if (arg[0] != ',')
9749 error (_("Too few arguments."));
9750 else if (canonical_start.lsals.empty ())
9751 error (_("Could not find location of the beginning of the range."));
9752
9753 const linespec_sals &lsal_start = canonical_start.lsals[0];
9754
9755 if (canonical_start.lsals.size () > 1
9756 || lsal_start.sals.size () != 1)
9757 error (_("Cannot create a ranged breakpoint with multiple locations."));
9758
9759 const symtab_and_line &sal_start = lsal_start.sals[0];
9760 std::string addr_string_start (arg_start, arg - arg_start);
9761
9762 arg++; /* Skip the comma. */
9763 arg = skip_spaces (arg);
9764
9765 /* Parse the end location specification. */
9766
9767 arg_start = arg;
9768
9769 /* We call decode_line_full directly here instead of using
9770 parse_breakpoint_sals because we need to specify the start
9771 location spec's symtab and line as the default symtab and line
9772 for the end of the range. This makes it possible to have ranges
9773 like "foo.c:27, +14", where +14 means 14 lines from the start
9774 location spec. */
9775 location_spec_up end_locspec
9776 = string_to_location_spec (&arg, current_language);
9777 decode_line_full (end_locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
9778 sal_start.symtab, sal_start.line,
9779 &canonical_end, NULL, NULL);
9780
9781 if (canonical_end.lsals.empty ())
9782 error (_("Could not find location of the end of the range."));
9783
9784 const linespec_sals &lsal_end = canonical_end.lsals[0];
9785 if (canonical_end.lsals.size () > 1
9786 || lsal_end.sals.size () != 1)
9787 error (_("Cannot create a ranged breakpoint with multiple locations."));
9788
9789 const symtab_and_line &sal_end = lsal_end.sals[0];
9790
9791 end = find_breakpoint_range_end (sal_end);
9792 if (sal_start.pc > end)
9793 error (_("Invalid address range, end precedes start."));
9794
9795 length = end - sal_start.pc + 1;
9796 if (length < 0)
9797 /* Length overflowed. */
9798 error (_("Address range too large."));
9799 else if (length == 1)
9800 {
9801 /* This range is simple enough to be handled by
9802 the `hbreak' command. */
9803 hbreak_command (&addr_string_start[0], 1);
9804
9805 return;
9806 }
9807
9808 /* Now set up the breakpoint and install it. */
9809
9810 std::unique_ptr<breakpoint> br
9811 (new ranged_breakpoint (get_current_arch (),
9812 sal_start, length,
9813 std::move (start_locspec),
9814 std::move (end_locspec)));
9815
9816 install_breakpoint (false, std::move (br), true);
9817 }
9818
9819 /* See breakpoint.h. */
9820
9821 watchpoint::~watchpoint ()
9822 {
9823 /* Make sure to unlink the destroyed watchpoint from the related
9824 breakpoint ring. */
9825
9826 breakpoint *bpt = this;
9827 while (bpt->related_breakpoint != this)
9828 bpt = bpt->related_breakpoint;
9829
9830 bpt->related_breakpoint = this->related_breakpoint;
9831 }
9832
9833 /* Return non-zero if EXP is verified as constant. Returned zero
9834 means EXP is variable. Also the constant detection may fail for
9835 some constant expressions and in such case still falsely return
9836 zero. */
9837
9838 static bool
9839 watchpoint_exp_is_const (const struct expression *exp)
9840 {
9841 return exp->op->constant_p ();
9842 }
9843
9844 /* Implement the "re_set" method for watchpoints. */
9845
9846 void
9847 watchpoint::re_set ()
9848 {
9849 /* Watchpoint can be either on expression using entirely global
9850 variables, or it can be on local variables.
9851
9852 Watchpoints of the first kind are never auto-deleted, and even
9853 persist across program restarts. Since they can use variables
9854 from shared libraries, we need to reparse expression as libraries
9855 are loaded and unloaded.
9856
9857 Watchpoints on local variables can also change meaning as result
9858 of solib event. For example, if a watchpoint uses both a local
9859 and a global variables in expression, it's a local watchpoint,
9860 but unloading of a shared library will make the expression
9861 invalid. This is not a very common use case, but we still
9862 re-evaluate expression, to avoid surprises to the user.
9863
9864 Note that for local watchpoints, we re-evaluate it only if
9865 watchpoints frame id is still valid. If it's not, it means the
9866 watchpoint is out of scope and will be deleted soon. In fact,
9867 I'm not sure we'll ever be called in this case.
9868
9869 If a local watchpoint's frame id is still valid, then
9870 exp_valid_block is likewise valid, and we can safely use it.
9871
9872 Don't do anything about disabled watchpoints, since they will be
9873 reevaluated again when enabled. */
9874 update_watchpoint (this, true /* reparse */);
9875 }
9876
9877 /* Implement the "insert" method for hardware watchpoints. */
9878
9879 int
9880 watchpoint::insert_location (struct bp_location *bl)
9881 {
9882 int length = exact ? 1 : bl->length;
9883
9884 return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9885 cond_exp.get ());
9886 }
9887
9888 /* Implement the "remove" method for hardware watchpoints. */
9889
9890 int
9891 watchpoint::remove_location (struct bp_location *bl,
9892 enum remove_bp_reason reason)
9893 {
9894 int length = exact ? 1 : bl->length;
9895
9896 return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9897 cond_exp.get ());
9898 }
9899
9900 int
9901 watchpoint::breakpoint_hit (const struct bp_location *bl,
9902 const address_space *aspace, CORE_ADDR bp_addr,
9903 const target_waitstatus &ws)
9904 {
9905 struct breakpoint *b = bl->owner;
9906
9907 /* Continuable hardware watchpoints are treated as non-existent if the
9908 reason we stopped wasn't a hardware watchpoint (we didn't stop on
9909 some data address). Otherwise gdb won't stop on a break instruction
9910 in the code (not from a breakpoint) when a hardware watchpoint has
9911 been defined. Also skip watchpoints which we know did not trigger
9912 (did not match the data address). */
9913 if (is_hardware_watchpoint (b)
9914 && watchpoint_triggered == watch_triggered_no)
9915 return 0;
9916
9917 return 1;
9918 }
9919
9920 void
9921 watchpoint::check_status (bpstat *bs)
9922 {
9923 bpstat_check_watchpoint (bs);
9924 }
9925
9926 /* Implement the "resources_needed" method for hardware
9927 watchpoints. */
9928
9929 int
9930 watchpoint::resources_needed (const struct bp_location *bl)
9931 {
9932 int length = exact? 1 : bl->length;
9933
9934 return target_region_ok_for_hw_watchpoint (bl->address, length);
9935 }
9936
9937 /* Implement the "works_in_software_mode" method for hardware
9938 watchpoints. */
9939
9940 bool
9941 watchpoint::works_in_software_mode () const
9942 {
9943 /* Read and access watchpoints only work with hardware support. */
9944 return type == bp_watchpoint || type == bp_hardware_watchpoint;
9945 }
9946
9947 enum print_stop_action
9948 watchpoint::print_it (const bpstat *bs) const
9949 {
9950 enum print_stop_action result;
9951 struct ui_out *uiout = current_uiout;
9952
9953 gdb_assert (bs->bp_location_at != NULL);
9954
9955 annotate_watchpoint (this->number);
9956 maybe_print_thread_hit_breakpoint (uiout);
9957
9958 string_file stb;
9959
9960 std::optional<ui_out_emit_tuple> tuple_emitter;
9961 switch (this->type)
9962 {
9963 case bp_watchpoint:
9964 case bp_hardware_watchpoint:
9965 if (uiout->is_mi_like_p ())
9966 uiout->field_string
9967 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9968 mention (this);
9969 tuple_emitter.emplace (uiout, "value");
9970 uiout->text ("\nOld value = ");
9971 watchpoint_value_print (bs->old_val.get (), &stb);
9972 uiout->field_stream ("old", stb);
9973 uiout->text ("\nNew value = ");
9974 watchpoint_value_print (val.get (), &stb);
9975 uiout->field_stream ("new", stb);
9976 uiout->text ("\n");
9977 /* More than one watchpoint may have been triggered. */
9978 result = PRINT_UNKNOWN;
9979 break;
9980
9981 case bp_read_watchpoint:
9982 if (uiout->is_mi_like_p ())
9983 uiout->field_string
9984 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9985 mention (this);
9986 tuple_emitter.emplace (uiout, "value");
9987 uiout->text ("\nValue = ");
9988 watchpoint_value_print (val.get (), &stb);
9989 uiout->field_stream ("value", stb);
9990 uiout->text ("\n");
9991 result = PRINT_UNKNOWN;
9992 break;
9993
9994 case bp_access_watchpoint:
9995 if (bs->old_val != NULL)
9996 {
9997 if (uiout->is_mi_like_p ())
9998 uiout->field_string
9999 ("reason",
10000 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10001 mention (this);
10002 tuple_emitter.emplace (uiout, "value");
10003 uiout->text ("\nOld value = ");
10004 watchpoint_value_print (bs->old_val.get (), &stb);
10005 uiout->field_stream ("old", stb);
10006 uiout->text ("\nNew value = ");
10007 }
10008 else
10009 {
10010 mention (this);
10011 if (uiout->is_mi_like_p ())
10012 uiout->field_string
10013 ("reason",
10014 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10015 tuple_emitter.emplace (uiout, "value");
10016 uiout->text ("\nValue = ");
10017 }
10018 watchpoint_value_print (val.get (), &stb);
10019 uiout->field_stream ("new", stb);
10020 uiout->text ("\n");
10021 result = PRINT_UNKNOWN;
10022 break;
10023 default:
10024 result = PRINT_UNKNOWN;
10025 }
10026
10027 return result;
10028 }
10029
10030 /* Implement the "print_mention" method for hardware watchpoints. */
10031
10032 void
10033 watchpoint::print_mention () const
10034 {
10035 struct ui_out *uiout = current_uiout;
10036 const char *tuple_name;
10037
10038 switch (type)
10039 {
10040 case bp_watchpoint:
10041 uiout->text ("Watchpoint ");
10042 tuple_name = "wpt";
10043 break;
10044 case bp_hardware_watchpoint:
10045 uiout->text ("Hardware watchpoint ");
10046 tuple_name = "wpt";
10047 break;
10048 case bp_read_watchpoint:
10049 uiout->text ("Hardware read watchpoint ");
10050 tuple_name = "hw-rwpt";
10051 break;
10052 case bp_access_watchpoint:
10053 uiout->text ("Hardware access (read/write) watchpoint ");
10054 tuple_name = "hw-awpt";
10055 break;
10056 default:
10057 internal_error (_("Invalid hardware watchpoint type."));
10058 }
10059
10060 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10061 uiout->field_signed ("number", number);
10062 uiout->text (": ");
10063 uiout->field_string ("exp", exp_string.get ());
10064 }
10065
10066 /* Implement the "print_recreate" method for watchpoints. */
10067
10068 void
10069 watchpoint::print_recreate (struct ui_file *fp) const
10070 {
10071 switch (type)
10072 {
10073 case bp_watchpoint:
10074 case bp_hardware_watchpoint:
10075 gdb_printf (fp, "watch");
10076 break;
10077 case bp_read_watchpoint:
10078 gdb_printf (fp, "rwatch");
10079 break;
10080 case bp_access_watchpoint:
10081 gdb_printf (fp, "awatch");
10082 break;
10083 default:
10084 internal_error (_("Invalid watchpoint type."));
10085 }
10086
10087 gdb_printf (fp, " %s", exp_string.get ());
10088 print_recreate_thread (fp);
10089 }
10090
10091 /* Implement the "explains_signal" method for watchpoints. */
10092
10093 bool
10094 watchpoint::explains_signal (enum gdb_signal sig)
10095 {
10096 /* A software watchpoint cannot cause a signal other than
10097 GDB_SIGNAL_TRAP. */
10098 if (type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10099 return false;
10100
10101 return true;
10102 }
10103
10104 struct masked_watchpoint : public watchpoint
10105 {
10106 using watchpoint::watchpoint;
10107
10108 int insert_location (struct bp_location *) override;
10109 int remove_location (struct bp_location *,
10110 enum remove_bp_reason reason) override;
10111 int resources_needed (const struct bp_location *) override;
10112 bool works_in_software_mode () const override;
10113 enum print_stop_action print_it (const bpstat *bs) const override;
10114 void print_one_detail (struct ui_out *) const override;
10115 void print_mention () const override;
10116 void print_recreate (struct ui_file *fp) const override;
10117 };
10118
10119 /* Implement the "insert" method for masked hardware watchpoints. */
10120
10121 int
10122 masked_watchpoint::insert_location (struct bp_location *bl)
10123 {
10124 return target_insert_mask_watchpoint (bl->address, hw_wp_mask,
10125 bl->watchpoint_type);
10126 }
10127
10128 /* Implement the "remove" method for masked hardware watchpoints. */
10129
10130 int
10131 masked_watchpoint::remove_location (struct bp_location *bl,
10132 enum remove_bp_reason reason)
10133 {
10134 return target_remove_mask_watchpoint (bl->address, hw_wp_mask,
10135 bl->watchpoint_type);
10136 }
10137
10138 /* Implement the "resources_needed" method for masked hardware
10139 watchpoints. */
10140
10141 int
10142 masked_watchpoint::resources_needed (const struct bp_location *bl)
10143 {
10144 return target_masked_watch_num_registers (bl->address, hw_wp_mask);
10145 }
10146
10147 /* Implement the "works_in_software_mode" method for masked hardware
10148 watchpoints. */
10149
10150 bool
10151 masked_watchpoint::works_in_software_mode () const
10152 {
10153 return false;
10154 }
10155
10156 /* Implement the "print_it" method for masked hardware
10157 watchpoints. */
10158
10159 enum print_stop_action
10160 masked_watchpoint::print_it (const bpstat *bs) const
10161 {
10162 struct ui_out *uiout = current_uiout;
10163
10164 /* Masked watchpoints have only one location. */
10165 gdb_assert (this->has_single_location ());
10166
10167 annotate_watchpoint (this->number);
10168 maybe_print_thread_hit_breakpoint (uiout);
10169
10170 switch (this->type)
10171 {
10172 case bp_hardware_watchpoint:
10173 if (uiout->is_mi_like_p ())
10174 uiout->field_string
10175 ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10176 break;
10177
10178 case bp_read_watchpoint:
10179 if (uiout->is_mi_like_p ())
10180 uiout->field_string
10181 ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10182 break;
10183
10184 case bp_access_watchpoint:
10185 if (uiout->is_mi_like_p ())
10186 uiout->field_string
10187 ("reason",
10188 async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10189 break;
10190 default:
10191 internal_error (_("Invalid hardware watchpoint type."));
10192 }
10193
10194 mention (this);
10195 uiout->text (_("\n\
10196 Check the underlying instruction at PC for the memory\n\
10197 address and value which triggered this watchpoint.\n"));
10198 uiout->text ("\n");
10199
10200 /* More than one watchpoint may have been triggered. */
10201 return PRINT_UNKNOWN;
10202 }
10203
10204 /* Implement the "print_one_detail" method for masked hardware
10205 watchpoints. */
10206
10207 void
10208 masked_watchpoint::print_one_detail (struct ui_out *uiout) const
10209 {
10210 /* Masked watchpoints have only one location. */
10211 gdb_assert (this->has_single_location ());
10212
10213 uiout->text ("\tmask ");
10214 uiout->field_core_addr ("mask", this->first_loc ().gdbarch, hw_wp_mask);
10215 uiout->text ("\n");
10216 }
10217
10218 /* Implement the "print_mention" method for masked hardware
10219 watchpoints. */
10220
10221 void
10222 masked_watchpoint::print_mention () const
10223 {
10224 struct ui_out *uiout = current_uiout;
10225 const char *tuple_name;
10226
10227 switch (type)
10228 {
10229 case bp_hardware_watchpoint:
10230 uiout->text ("Masked hardware watchpoint ");
10231 tuple_name = "wpt";
10232 break;
10233 case bp_read_watchpoint:
10234 uiout->text ("Masked hardware read watchpoint ");
10235 tuple_name = "hw-rwpt";
10236 break;
10237 case bp_access_watchpoint:
10238 uiout->text ("Masked hardware access (read/write) watchpoint ");
10239 tuple_name = "hw-awpt";
10240 break;
10241 default:
10242 internal_error (_("Invalid hardware watchpoint type."));
10243 }
10244
10245 ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10246 uiout->field_signed ("number", number);
10247 uiout->text (": ");
10248 uiout->field_string ("exp", exp_string.get ());
10249 }
10250
10251 /* Implement the "print_recreate" method for masked hardware
10252 watchpoints. */
10253
10254 void
10255 masked_watchpoint::print_recreate (struct ui_file *fp) const
10256 {
10257 switch (type)
10258 {
10259 case bp_hardware_watchpoint:
10260 gdb_printf (fp, "watch");
10261 break;
10262 case bp_read_watchpoint:
10263 gdb_printf (fp, "rwatch");
10264 break;
10265 case bp_access_watchpoint:
10266 gdb_printf (fp, "awatch");
10267 break;
10268 default:
10269 internal_error (_("Invalid hardware watchpoint type."));
10270 }
10271
10272 gdb_printf (fp, " %s mask 0x%s", exp_string.get (),
10273 phex (hw_wp_mask, sizeof (CORE_ADDR)));
10274 print_recreate_thread (fp);
10275 }
10276
10277 /* Tell whether the given watchpoint is a masked hardware watchpoint. */
10278
10279 static bool
10280 is_masked_watchpoint (const struct breakpoint *b)
10281 {
10282 return dynamic_cast<const masked_watchpoint *> (b) != nullptr;
10283 }
10284
10285 /* accessflag: hw_write: watch write,
10286 hw_read: watch read,
10287 hw_access: watch access (read or write) */
10288 static void
10289 watch_command_1 (const char *arg, int accessflag, int from_tty,
10290 bool just_location, bool internal)
10291 {
10292 struct breakpoint *scope_breakpoint = NULL;
10293 const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10294 struct value *result;
10295 int saved_bitpos = 0, saved_bitsize = 0;
10296 const char *exp_start = NULL;
10297 const char *exp_end = NULL;
10298 const char *tok, *end_tok;
10299 int toklen = -1;
10300 const char *cond_start = NULL;
10301 const char *cond_end = NULL;
10302 enum bptype bp_type;
10303 int thread = -1;
10304 int inferior = -1;
10305 /* Flag to indicate whether we are going to use masks for
10306 the hardware watchpoint. */
10307 bool use_mask = false;
10308 CORE_ADDR mask = 0;
10309 int task = -1;
10310
10311 /* Make sure that we actually have parameters to parse. */
10312 if (arg != NULL && arg[0] != '\0')
10313 {
10314 const char *value_start;
10315
10316 exp_end = arg + strlen (arg);
10317
10318 /* Look for "parameter value" pairs at the end
10319 of the arguments string. */
10320 for (tok = exp_end - 1; tok > arg; tok--)
10321 {
10322 /* Skip whitespace at the end of the argument list. */
10323 while (tok > arg && (*tok == ' ' || *tok == '\t'))
10324 tok--;
10325
10326 /* Find the beginning of the last token.
10327 This is the value of the parameter. */
10328 while (tok > arg && (*tok != ' ' && *tok != '\t'))
10329 tok--;
10330 value_start = tok + 1;
10331
10332 /* Skip whitespace. */
10333 while (tok > arg && (*tok == ' ' || *tok == '\t'))
10334 tok--;
10335
10336 end_tok = tok;
10337
10338 /* Find the beginning of the second to last token.
10339 This is the parameter itself. */
10340 while (tok > arg && (*tok != ' ' && *tok != '\t'))
10341 tok--;
10342 tok++;
10343 toklen = end_tok - tok + 1;
10344
10345 if (toklen == 6 && startswith (tok, "thread"))
10346 {
10347 struct thread_info *thr;
10348 /* At this point we've found a "thread" token, which means
10349 the user is trying to set a watchpoint that triggers
10350 only in a specific thread. */
10351 const char *endp;
10352
10353 if (thread != -1)
10354 error(_("You can specify only one thread."));
10355
10356 if (task != -1)
10357 error (_("You can specify only one of thread or task."));
10358
10359 if (inferior != -1)
10360 error (_("You can specify only one of inferior or thread."));
10361
10362 /* Extract the thread ID from the next token. */
10363 thr = parse_thread_id (value_start, &endp);
10364 if (value_start == endp)
10365 error (_("Junk after thread keyword."));
10366
10367 thread = thr->global_num;
10368 }
10369 else if (toklen == 4 && startswith (tok, "task"))
10370 {
10371 char *tmp;
10372
10373 if (task != -1)
10374 error(_("You can specify only one task."));
10375
10376 if (thread != -1)
10377 error (_("You can specify only one of thread or task."));
10378
10379 if (inferior != -1)
10380 error (_("You can specify only one of inferior or task."));
10381
10382 task = strtol (value_start, &tmp, 0);
10383 if (tmp == value_start)
10384 error (_("Junk after task keyword."));
10385 if (!valid_task_id (task))
10386 error (_("Unknown task %d."), task);
10387 }
10388 else if (toklen == 8 && startswith (tok, "inferior"))
10389 {
10390 /* Support for watchpoints will be added in a later commit. */
10391 error (_("Cannot use 'inferior' keyword with watchpoints"));
10392 }
10393 else if (toklen == 4 && startswith (tok, "mask"))
10394 {
10395 /* We've found a "mask" token, which means the user wants to
10396 create a hardware watchpoint that is going to have the mask
10397 facility. */
10398 struct value *mask_value;
10399
10400 if (use_mask)
10401 error(_("You can specify only one mask."));
10402
10403 use_mask = just_location = true;
10404
10405 scoped_value_mark mark;
10406 mask_value = parse_to_comma_and_eval (&value_start);
10407 mask = value_as_address (mask_value);
10408 }
10409 else
10410 /* We didn't recognize what we found. We should stop here. */
10411 break;
10412
10413 /* Truncate the string and get rid of the "parameter value" pair before
10414 the arguments string is parsed by the parse_exp_1 function. */
10415 exp_end = tok;
10416 }
10417 }
10418 else
10419 exp_end = arg;
10420
10421 /* Parse the rest of the arguments. From here on out, everything
10422 is in terms of a newly allocated string instead of the original
10423 ARG. */
10424 std::string expression (arg, exp_end - arg);
10425 exp_start = arg = expression.c_str ();
10426 innermost_block_tracker tracker;
10427 expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10428 exp_end = arg;
10429 /* Remove trailing whitespace from the expression before saving it.
10430 This makes the eventual display of the expression string a bit
10431 prettier. */
10432 while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10433 --exp_end;
10434
10435 /* Checking if the expression is not constant. */
10436 if (watchpoint_exp_is_const (exp.get ()))
10437 {
10438 int len;
10439
10440 len = exp_end - exp_start;
10441 while (len > 0 && isspace (exp_start[len - 1]))
10442 len--;
10443 error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10444 }
10445
10446 exp_valid_block = tracker.block ();
10447 struct value *mark = value_mark ();
10448 struct value *val_as_value = nullptr;
10449 fetch_subexp_value (exp.get (), exp->op.get (), &val_as_value, &result, NULL,
10450 just_location);
10451
10452 if (val_as_value != NULL && just_location)
10453 {
10454 saved_bitpos = val_as_value->bitpos ();
10455 saved_bitsize = val_as_value->bitsize ();
10456 }
10457
10458 value_ref_ptr val;
10459 if (just_location)
10460 {
10461 int ret;
10462
10463 exp_valid_block = NULL;
10464 val = release_value (value_addr (result));
10465 value_free_to_mark (mark);
10466
10467 if (use_mask)
10468 {
10469 ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10470 mask);
10471 if (ret == -1)
10472 error (_("This target does not support masked watchpoints."));
10473 else if (ret == -2)
10474 error (_("Invalid mask or memory region."));
10475 }
10476 }
10477 else if (val_as_value != NULL)
10478 val = release_value (val_as_value);
10479
10480 tok = skip_spaces (arg);
10481 end_tok = skip_to_space (tok);
10482
10483 toklen = end_tok - tok;
10484 if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10485 {
10486 tok = cond_start = end_tok + 1;
10487 innermost_block_tracker if_tracker;
10488 parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10489
10490 /* The watchpoint expression may not be local, but the condition
10491 may still be. E.g.: `watch global if local > 0'. */
10492 cond_exp_valid_block = if_tracker.block ();
10493
10494 cond_end = tok;
10495 }
10496 if (*tok)
10497 error (_("Junk at end of command."));
10498
10499 frame_info_ptr wp_frame = block_innermost_frame (exp_valid_block);
10500
10501 /* Save this because create_internal_breakpoint below invalidates
10502 'wp_frame'. */
10503 frame_id watchpoint_frame = get_frame_id (wp_frame);
10504
10505 /* If the expression is "local", then set up a "watchpoint scope"
10506 breakpoint at the point where we've left the scope of the watchpoint
10507 expression. Create the scope breakpoint before the watchpoint, so
10508 that we will encounter it first in bpstat_stop_status. */
10509 if (exp_valid_block != NULL && wp_frame != NULL)
10510 {
10511 frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10512
10513 if (frame_id_p (caller_frame_id))
10514 {
10515 gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10516 CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10517
10518 scope_breakpoint
10519 = create_internal_breakpoint (caller_arch, caller_pc,
10520 bp_watchpoint_scope);
10521
10522 /* create_internal_breakpoint could invalidate WP_FRAME. */
10523 wp_frame = NULL;
10524
10525 scope_breakpoint->enable_state = bp_enabled;
10526
10527 /* Automatically delete the breakpoint when it hits. */
10528 scope_breakpoint->disposition = disp_del;
10529
10530 /* Only break in the proper frame (help with recursion). */
10531 scope_breakpoint->frame_id = caller_frame_id;
10532
10533 /* Set the address at which we will stop. */
10534 bp_location &loc = scope_breakpoint->first_loc ();
10535 loc.gdbarch = caller_arch;
10536 loc.requested_address = caller_pc;
10537 loc.address
10538 = adjust_breakpoint_address (loc.gdbarch, loc.requested_address,
10539 scope_breakpoint->type,
10540 current_program_space);
10541 }
10542 }
10543
10544 /* Now set up the breakpoint. We create all watchpoints as hardware
10545 watchpoints here even if hardware watchpoints are turned off, a call
10546 to update_watchpoint later in this function will cause the type to
10547 drop back to bp_watchpoint (software watchpoint) if required. */
10548
10549 if (accessflag == hw_read)
10550 bp_type = bp_read_watchpoint;
10551 else if (accessflag == hw_access)
10552 bp_type = bp_access_watchpoint;
10553 else
10554 bp_type = bp_hardware_watchpoint;
10555
10556 std::unique_ptr<watchpoint> w;
10557 if (use_mask)
10558 w.reset (new masked_watchpoint (nullptr, bp_type));
10559 else
10560 w.reset (new watchpoint (nullptr, bp_type));
10561
10562 /* At most one of thread or task can be set on a watchpoint. */
10563 gdb_assert (thread == -1 || task == -1);
10564 w->thread = thread;
10565 w->inferior = inferior;
10566 w->task = task;
10567 w->disposition = disp_donttouch;
10568 w->pspace = current_program_space;
10569 w->exp = std::move (exp);
10570 w->exp_valid_block = exp_valid_block;
10571 w->cond_exp_valid_block = cond_exp_valid_block;
10572 if (just_location)
10573 {
10574 struct type *t = val->type ();
10575 CORE_ADDR addr = value_as_address (val.get ());
10576
10577 w->exp_string_reparse
10578 = current_language->watch_location_expression (t, addr);
10579
10580 w->exp_string = xstrprintf ("-location %.*s",
10581 (int) (exp_end - exp_start), exp_start);
10582 }
10583 else
10584 w->exp_string.reset (savestring (exp_start, exp_end - exp_start));
10585
10586 if (use_mask)
10587 {
10588 w->hw_wp_mask = mask;
10589 }
10590 else
10591 {
10592 w->val = val;
10593 w->val_bitpos = saved_bitpos;
10594 w->val_bitsize = saved_bitsize;
10595 w->val_valid = true;
10596 }
10597
10598 if (cond_start)
10599 w->cond_string.reset (savestring (cond_start, cond_end - cond_start));
10600 else
10601 w->cond_string = 0;
10602
10603 if (frame_id_p (watchpoint_frame))
10604 {
10605 w->watchpoint_frame = watchpoint_frame;
10606 w->watchpoint_thread = inferior_ptid;
10607 }
10608 else
10609 {
10610 w->watchpoint_frame = null_frame_id;
10611 w->watchpoint_thread = null_ptid;
10612 }
10613
10614 if (scope_breakpoint != NULL)
10615 {
10616 /* The scope breakpoint is related to the watchpoint. We will
10617 need to act on them together. */
10618 w->related_breakpoint = scope_breakpoint;
10619 scope_breakpoint->related_breakpoint = w.get ();
10620 }
10621
10622 if (!just_location)
10623 value_free_to_mark (mark);
10624
10625 /* Finally update the new watchpoint. This creates the locations
10626 that should be inserted. */
10627 update_watchpoint (w.get (), true /* reparse */);
10628
10629 install_breakpoint (internal, std::move (w), 1);
10630 }
10631
10632 /* Return count of debug registers needed to watch the given expression.
10633 If the watchpoint cannot be handled in hardware return zero. */
10634
10635 static int
10636 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10637 {
10638 int found_memory_cnt = 0;
10639
10640 /* Did the user specifically forbid us to use hardware watchpoints? */
10641 if (!can_use_hw_watchpoints)
10642 return 0;
10643
10644 gdb_assert (!vals.empty ());
10645 struct value *head = vals[0].get ();
10646
10647 /* Make sure that the value of the expression depends only upon
10648 memory contents, and values computed from them within GDB. If we
10649 find any register references or function calls, we can't use a
10650 hardware watchpoint.
10651
10652 The idea here is that evaluating an expression generates a series
10653 of values, one holding the value of every subexpression. (The
10654 expression a*b+c has five subexpressions: a, b, a*b, c, and
10655 a*b+c.) GDB's values hold almost enough information to establish
10656 the criteria given above --- they identify memory lvalues,
10657 register lvalues, computed values, etcetera. So we can evaluate
10658 the expression, and then scan the chain of values that leaves
10659 behind to decide whether we can detect any possible change to the
10660 expression's final value using only hardware watchpoints.
10661
10662 However, I don't think that the values returned by inferior
10663 function calls are special in any way. So this function may not
10664 notice that an expression involving an inferior function call
10665 can't be watched with hardware watchpoints. FIXME. */
10666 for (const value_ref_ptr &iter : vals)
10667 {
10668 struct value *v = iter.get ();
10669
10670 if (v->lval () == lval_memory)
10671 {
10672 if (v != head && v->lazy ())
10673 /* A lazy memory lvalue in the chain is one that GDB never
10674 needed to fetch; we either just used its address (e.g.,
10675 `a' in `a.b') or we never needed it at all (e.g., `a'
10676 in `a,b'). This doesn't apply to HEAD; if that is
10677 lazy then it was not readable, but watch it anyway. */
10678 ;
10679 else
10680 {
10681 /* Ahh, memory we actually used! Check if we can cover
10682 it with hardware watchpoints. */
10683 struct type *vtype = check_typedef (v->type ());
10684
10685 /* We only watch structs and arrays if user asked for it
10686 explicitly, never if they just happen to appear in a
10687 middle of some value chain. */
10688 if (v == head
10689 || (vtype->code () != TYPE_CODE_STRUCT
10690 && vtype->code () != TYPE_CODE_ARRAY))
10691 {
10692 CORE_ADDR vaddr = v->address ();
10693 int len;
10694 int num_regs;
10695
10696 len = (target_exact_watchpoints
10697 && is_scalar_type_recursive (vtype))?
10698 1 : v->type ()->length ();
10699
10700 num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10701 if (!num_regs)
10702 return 0;
10703 else
10704 found_memory_cnt += num_regs;
10705 }
10706 }
10707 }
10708 else if (v->lval () != not_lval && !v->deprecated_modifiable ())
10709 return 0; /* These are values from the history (e.g., $1). */
10710 else if (v->lval () == lval_register)
10711 return 0; /* Cannot watch a register with a HW watchpoint. */
10712 }
10713
10714 /* The expression itself looks suitable for using a hardware
10715 watchpoint, but give the target machine a chance to reject it. */
10716 return found_memory_cnt;
10717 }
10718
10719 void
10720 watch_command_wrapper (const char *arg, int from_tty, bool internal)
10721 {
10722 watch_command_1 (arg, hw_write, from_tty, 0, internal);
10723 }
10724
10725 /* Options for the watch, awatch, and rwatch commands. */
10726
10727 struct watch_options
10728 {
10729 /* For -location. */
10730 bool location = false;
10731 };
10732
10733 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
10734
10735 Historically GDB always accepted both '-location' and '-l' flags for
10736 these commands (both flags being synonyms). When converting to the
10737 newer option scheme only '-location' is added here. That's fine (for
10738 backward compatibility) as any non-ambiguous prefix of a flag will be
10739 accepted, so '-l', '-loc', are now all accepted.
10740
10741 What this means is that, if in the future, we add any new flag here
10742 that starts with '-l' then this will break backward compatibility, so
10743 please, don't do that! */
10744
10745 static const gdb::option::option_def watch_option_defs[] = {
10746 gdb::option::flag_option_def<watch_options> {
10747 "location",
10748 [] (watch_options *opt) { return &opt->location; },
10749 N_("\
10750 This evaluates EXPRESSION and watches the memory to which is refers.\n\
10751 -l can be used as a short form of -location."),
10752 },
10753 };
10754
10755 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
10756 commands. */
10757
10758 static gdb::option::option_def_group
10759 make_watch_options_def_group (watch_options *opts)
10760 {
10761 return {{watch_option_defs}, opts};
10762 }
10763
10764 /* A helper function that looks for the "-location" argument and then
10765 calls watch_command_1. */
10766
10767 static void
10768 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
10769 {
10770 watch_options opts;
10771 auto grp = make_watch_options_def_group (&opts);
10772 gdb::option::process_options
10773 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
10774 if (arg != nullptr && *arg == '\0')
10775 arg = nullptr;
10776
10777 watch_command_1 (arg, accessflag, from_tty, opts.location, false);
10778 }
10779
10780 /* Command completion for 'watch', 'awatch', and 'rwatch' commands. */
10781 static void
10782 watch_command_completer (struct cmd_list_element *ignore,
10783 completion_tracker &tracker,
10784 const char *text, const char * /*word*/)
10785 {
10786 const auto group = make_watch_options_def_group (nullptr);
10787 if (gdb::option::complete_options
10788 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
10789 return;
10790
10791 const char *word = advance_to_expression_complete_word_point (tracker, text);
10792 expression_completer (ignore, tracker, text, word);
10793 }
10794
10795 static void
10796 watch_command (const char *arg, int from_tty)
10797 {
10798 watch_maybe_just_location (arg, hw_write, from_tty);
10799 }
10800
10801 void
10802 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
10803 {
10804 watch_command_1 (arg, hw_read, from_tty, 0, internal);
10805 }
10806
10807 static void
10808 rwatch_command (const char *arg, int from_tty)
10809 {
10810 watch_maybe_just_location (arg, hw_read, from_tty);
10811 }
10812
10813 void
10814 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
10815 {
10816 watch_command_1 (arg, hw_access, from_tty, 0, internal);
10817 }
10818
10819 static void
10820 awatch_command (const char *arg, int from_tty)
10821 {
10822 watch_maybe_just_location (arg, hw_access, from_tty);
10823 }
10824 \f
10825
10826 /* Data for the FSM that manages the until(location)/advance commands
10827 in infcmd.c. Here because it uses the mechanisms of
10828 breakpoints. */
10829
10830 struct until_break_fsm : public thread_fsm
10831 {
10832 /* The thread that was current when the command was executed. */
10833 int thread;
10834
10835 /* The breakpoint set at the return address in the caller frame,
10836 plus breakpoints at all the destination locations. */
10837 std::vector<breakpoint_up> breakpoints;
10838
10839 until_break_fsm (struct interp *cmd_interp, int thread,
10840 std::vector<breakpoint_up> &&breakpoints)
10841 : thread_fsm (cmd_interp),
10842 thread (thread),
10843 breakpoints (std::move (breakpoints))
10844 {
10845 }
10846
10847 void clean_up (struct thread_info *thread) override;
10848 bool should_stop (struct thread_info *thread) override;
10849 enum async_reply_reason do_async_reply_reason () override;
10850 };
10851
10852 /* Implementation of the 'should_stop' FSM method for the
10853 until(location)/advance commands. */
10854
10855 bool
10856 until_break_fsm::should_stop (struct thread_info *tp)
10857 {
10858 for (const breakpoint_up &bp : breakpoints)
10859 if (bpstat_find_breakpoint (tp->control.stop_bpstat,
10860 bp.get ()) != NULL)
10861 {
10862 set_finished ();
10863 break;
10864 }
10865
10866 return true;
10867 }
10868
10869 /* Implementation of the 'clean_up' FSM method for the
10870 until(location)/advance commands. */
10871
10872 void
10873 until_break_fsm::clean_up (struct thread_info *)
10874 {
10875 /* Clean up our temporary breakpoints. */
10876 breakpoints.clear ();
10877 delete_longjmp_breakpoint (thread);
10878 }
10879
10880 /* Implementation of the 'async_reply_reason' FSM method for the
10881 until(location)/advance commands. */
10882
10883 enum async_reply_reason
10884 until_break_fsm::do_async_reply_reason ()
10885 {
10886 return EXEC_ASYNC_LOCATION_REACHED;
10887 }
10888
10889 void
10890 until_break_command (const char *arg, int from_tty, int anywhere)
10891 {
10892 frame_info_ptr frame;
10893 struct gdbarch *frame_gdbarch;
10894 struct frame_id stack_frame_id;
10895 struct frame_id caller_frame_id;
10896 int thread;
10897 struct thread_info *tp;
10898
10899 clear_proceed_status (0);
10900
10901 /* Set a breakpoint where the user wants it and at return from
10902 this function. */
10903
10904 location_spec_up locspec = string_to_location_spec (&arg, current_language);
10905
10906 std::vector<symtab_and_line> sals
10907 = (last_displayed_sal_is_valid ()
10908 ? decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10909 get_last_displayed_symtab (),
10910 get_last_displayed_line ())
10911 : decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE,
10912 NULL, NULL, 0));
10913
10914 if (sals.empty ())
10915 error (_("Couldn't get information on specified line."));
10916
10917 if (*arg)
10918 error (_("Junk at end of arguments."));
10919
10920 tp = inferior_thread ();
10921 thread = tp->global_num;
10922
10923 /* Note linespec handling above invalidates the frame chain.
10924 Installing a breakpoint also invalidates the frame chain (as it
10925 may need to switch threads), so do any frame handling before
10926 that. */
10927
10928 frame = get_selected_frame (NULL);
10929 frame_gdbarch = get_frame_arch (frame);
10930 stack_frame_id = get_stack_frame_id (frame);
10931 caller_frame_id = frame_unwind_caller_id (frame);
10932
10933 /* Keep within the current frame, or in frames called by the current
10934 one. */
10935
10936 std::vector<breakpoint_up> breakpoints;
10937
10938 std::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
10939
10940 if (frame_id_p (caller_frame_id))
10941 {
10942 struct symtab_and_line sal2;
10943 struct gdbarch *caller_gdbarch;
10944
10945 sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10946 sal2.pc = frame_unwind_caller_pc (frame);
10947 caller_gdbarch = frame_unwind_caller_arch (frame);
10948
10949 breakpoint_up caller_breakpoint
10950 = set_momentary_breakpoint (caller_gdbarch, sal2,
10951 caller_frame_id, bp_until);
10952 breakpoints.emplace_back (std::move (caller_breakpoint));
10953
10954 set_longjmp_breakpoint (tp, stack_frame_id);
10955 lj_deleter.emplace (thread);
10956 }
10957
10958 /* If the user told us to continue until a specified location, we
10959 don't specify a frame at which we need to stop. Otherwise,
10960 specify the selected frame, because we want to stop only at the
10961 very same frame. */
10962 frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
10963
10964 for (symtab_and_line &sal : sals)
10965 {
10966 resolve_sal_pc (&sal);
10967
10968 breakpoint_up location_breakpoint
10969 = set_momentary_breakpoint (frame_gdbarch, sal,
10970 stop_frame_id, bp_until);
10971 breakpoints.emplace_back (std::move (location_breakpoint));
10972 }
10973
10974 tp->set_thread_fsm
10975 (std::unique_ptr<thread_fsm>
10976 (new until_break_fsm (command_interp (), tp->global_num,
10977 std::move (breakpoints))));
10978
10979 if (lj_deleter)
10980 lj_deleter->release ();
10981
10982 proceed (-1, GDB_SIGNAL_DEFAULT);
10983 }
10984
10985 \f
10986
10987 /* Compare two breakpoints and return a strcmp-like result. */
10988
10989 static int
10990 compare_breakpoints (const breakpoint *a, const breakpoint *b)
10991 {
10992 uintptr_t ua = (uintptr_t) a;
10993 uintptr_t ub = (uintptr_t) b;
10994
10995 if (a->number < b->number)
10996 return -1;
10997 else if (a->number > b->number)
10998 return 1;
10999
11000 /* Now sort by address, in case we see, e..g, two breakpoints with
11001 the number 0. */
11002 if (ua < ub)
11003 return -1;
11004 return ua > ub ? 1 : 0;
11005 }
11006
11007 /* Delete breakpoints by address or line. */
11008
11009 static void
11010 clear_command (const char *arg, int from_tty)
11011 {
11012 int default_match;
11013
11014 std::vector<symtab_and_line> decoded_sals;
11015 symtab_and_line last_sal;
11016 gdb::array_view<symtab_and_line> sals;
11017 if (arg)
11018 {
11019 decoded_sals
11020 = decode_line_with_current_source (arg,
11021 (DECODE_LINE_FUNFIRSTLINE
11022 | DECODE_LINE_LIST_MODE));
11023 default_match = 0;
11024 sals = decoded_sals;
11025 }
11026 else
11027 {
11028 /* Set sal's line, symtab, pc, and pspace to the values
11029 corresponding to the last call to print_frame_info. If the
11030 codepoint is not valid, this will set all the fields to 0. */
11031 last_sal = get_last_displayed_sal ();
11032 if (last_sal.symtab == 0)
11033 error (_("No source file specified."));
11034
11035 default_match = 1;
11036 sals = last_sal;
11037 }
11038
11039 /* We don't call resolve_sal_pc here. That's not as bad as it
11040 seems, because all existing breakpoints typically have both
11041 file/line and pc set. So, if clear is given file/line, we can
11042 match this to existing breakpoint without obtaining pc at all.
11043
11044 We only support clearing given the address explicitly
11045 present in breakpoint table. Say, we've set breakpoint
11046 at file:line. There were several PC values for that file:line,
11047 due to optimization, all in one block.
11048
11049 We've picked one PC value. If "clear" is issued with another
11050 PC corresponding to the same file:line, the breakpoint won't
11051 be cleared. We probably can still clear the breakpoint, but
11052 since the other PC value is never presented to user, user
11053 can only find it by guessing, and it does not seem important
11054 to support that. */
11055
11056 /* For each line spec given, delete bps which correspond to it. Do
11057 it in two passes, solely to preserve the current behavior that
11058 from_tty is forced true if we delete more than one
11059 breakpoint. */
11060
11061 std::vector<struct breakpoint *> found;
11062 for (const auto &sal : sals)
11063 {
11064 const char *sal_fullname;
11065
11066 /* If exact pc given, clear bpts at that pc.
11067 If line given (pc == 0), clear all bpts on specified line.
11068 If defaulting, clear all bpts on default line
11069 or at default pc.
11070
11071 defaulting sal.pc != 0 tests to do
11072
11073 0 1 pc
11074 1 1 pc _and_ line
11075 0 0 line
11076 1 0 <can't happen> */
11077
11078 sal_fullname = (sal.symtab == NULL
11079 ? NULL : symtab_to_fullname (sal.symtab));
11080
11081 /* Find all matching breakpoints and add them to 'found'. */
11082 for (breakpoint &b : all_breakpoints ())
11083 {
11084 int match = 0;
11085 /* Are we going to delete b? */
11086 if (b.type != bp_none && !is_watchpoint (&b)
11087 && user_breakpoint_p (&b))
11088 {
11089 for (bp_location &loc : b.locations ())
11090 {
11091 /* If the user specified file:line, don't allow a PC
11092 match. This matches historical gdb behavior. */
11093 int pc_match = (!sal.explicit_line
11094 && sal.pc
11095 && (loc.pspace == sal.pspace)
11096 && (loc.address == sal.pc)
11097 && (!section_is_overlay (loc.section)
11098 || loc.section == sal.section));
11099 int line_match = 0;
11100
11101 if ((default_match || sal.explicit_line)
11102 && loc.symtab != NULL
11103 && sal_fullname != NULL
11104 && sal.pspace == loc.pspace
11105 && loc.line_number == sal.line
11106 && filename_cmp (symtab_to_fullname (loc.symtab),
11107 sal_fullname) == 0)
11108 line_match = 1;
11109
11110 if (pc_match || line_match)
11111 {
11112 match = 1;
11113 break;
11114 }
11115 }
11116 }
11117
11118 if (match)
11119 found.push_back (&b);
11120 }
11121 }
11122
11123 /* Now go thru the 'found' chain and delete them. */
11124 if (found.empty ())
11125 {
11126 if (arg)
11127 error (_("No breakpoint at %s."), arg);
11128 else
11129 error (_("No breakpoint at this line."));
11130 }
11131
11132 /* Remove duplicates from the vec. */
11133 std::sort (found.begin (), found.end (),
11134 [] (const breakpoint *bp_a, const breakpoint *bp_b)
11135 {
11136 return compare_breakpoints (bp_a, bp_b) < 0;
11137 });
11138 found.erase (std::unique (found.begin (), found.end (),
11139 [] (const breakpoint *bp_a, const breakpoint *bp_b)
11140 {
11141 return compare_breakpoints (bp_a, bp_b) == 0;
11142 }),
11143 found.end ());
11144
11145 if (found.size () > 1)
11146 from_tty = 1; /* Always report if deleted more than one. */
11147 if (from_tty)
11148 {
11149 if (found.size () == 1)
11150 gdb_printf (_("Deleted breakpoint "));
11151 else
11152 gdb_printf (_("Deleted breakpoints "));
11153 }
11154
11155 for (breakpoint *iter : found)
11156 {
11157 if (from_tty)
11158 gdb_printf ("%d ", iter->number);
11159 delete_breakpoint (iter);
11160 }
11161 if (from_tty)
11162 gdb_putc ('\n');
11163 }
11164 \f
11165 /* Delete breakpoint in BS if they are `delete' breakpoints and
11166 all breakpoints that are marked for deletion, whether hit or not.
11167 This is called after any breakpoint is hit, or after errors. */
11168
11169 void
11170 breakpoint_auto_delete (bpstat *bs)
11171 {
11172 for (; bs; bs = bs->next)
11173 if (bs->breakpoint_at
11174 && bs->breakpoint_at->disposition == disp_del
11175 && bs->stop)
11176 delete_breakpoint (bs->breakpoint_at);
11177
11178 for (breakpoint &b : all_breakpoints_safe ())
11179 if (b.disposition == disp_del_at_next_stop)
11180 delete_breakpoint (&b);
11181 }
11182
11183 /* A comparison function for bp_location AP and BP being interfaced to
11184 std::sort. Sort elements primarily by their ADDRESS (no matter what
11185 bl_address_is_meaningful says), secondarily by ordering first
11186 permanent elements and tertiarily just ensuring the array is sorted
11187 stable way despite std::sort being an unstable algorithm. */
11188
11189 static int
11190 bp_location_is_less_than (const bp_location *a, const bp_location *b)
11191 {
11192 if (a->address != b->address)
11193 return a->address < b->address;
11194
11195 /* Sort locations at the same address by their pspace number, keeping
11196 locations of the same inferior (in a multi-inferior environment)
11197 grouped. */
11198
11199 if (a->pspace->num != b->pspace->num)
11200 return a->pspace->num < b->pspace->num;
11201
11202 /* Sort permanent breakpoints first. */
11203 if (a->permanent != b->permanent)
11204 return a->permanent > b->permanent;
11205
11206 /* Sort by type in order to make duplicate determination easier.
11207 See update_global_location_list. This is kept in sync with
11208 breakpoint_locations_match. */
11209 if (a->loc_type < b->loc_type)
11210 return true;
11211
11212 /* Likewise, for range-breakpoints, sort by length. */
11213 if (a->loc_type == bp_loc_hardware_breakpoint
11214 && b->loc_type == bp_loc_hardware_breakpoint
11215 && a->length < b->length)
11216 return true;
11217
11218 /* Make the internal GDB representation stable across GDB runs
11219 where A and B memory inside GDB can differ. Breakpoint locations of
11220 the same type at the same address can be sorted in arbitrary order. */
11221
11222 if (a->owner->number != b->owner->number)
11223 return a->owner->number < b->owner->number;
11224
11225 return a < b;
11226 }
11227
11228 /* Set bp_locations_placed_address_before_address_max and
11229 bp_locations_shadow_len_after_address_max according to the current
11230 content of the bp_locations array. */
11231
11232 static void
11233 bp_locations_target_extensions_update (void)
11234 {
11235 bp_locations_placed_address_before_address_max = 0;
11236 bp_locations_shadow_len_after_address_max = 0;
11237
11238 for (bp_location *bl : all_bp_locations ())
11239 {
11240 CORE_ADDR start, end, addr;
11241
11242 if (!bp_location_has_shadow (bl))
11243 continue;
11244
11245 start = bl->target_info.placed_address;
11246 end = start + bl->target_info.shadow_len;
11247
11248 gdb_assert (bl->address >= start);
11249 addr = bl->address - start;
11250 if (addr > bp_locations_placed_address_before_address_max)
11251 bp_locations_placed_address_before_address_max = addr;
11252
11253 /* Zero SHADOW_LEN would not pass bp_location_has_shadow. */
11254
11255 gdb_assert (bl->address < end);
11256 addr = end - bl->address;
11257 if (addr > bp_locations_shadow_len_after_address_max)
11258 bp_locations_shadow_len_after_address_max = addr;
11259 }
11260 }
11261
11262 /* Download tracepoint locations if they haven't been. */
11263
11264 static void
11265 download_tracepoint_locations (void)
11266 {
11267 enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11268
11269 scoped_restore_current_pspace_and_thread restore_pspace_thread;
11270
11271 for (breakpoint &b : all_tracepoints ())
11272 {
11273 bool bp_location_downloaded = false;
11274
11275 if ((b.type == bp_fast_tracepoint
11276 ? !may_insert_fast_tracepoints
11277 : !may_insert_tracepoints))
11278 continue;
11279
11280 if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11281 {
11282 if (target_can_download_tracepoint ())
11283 can_download_tracepoint = TRIBOOL_TRUE;
11284 else
11285 can_download_tracepoint = TRIBOOL_FALSE;
11286 }
11287
11288 if (can_download_tracepoint == TRIBOOL_FALSE)
11289 break;
11290
11291 for (bp_location &bl : b.locations ())
11292 {
11293 /* In tracepoint, locations are _never_ duplicated, so
11294 should_be_inserted is equivalent to
11295 unduplicated_should_be_inserted. */
11296 if (!should_be_inserted (&bl) || bl.inserted)
11297 continue;
11298
11299 switch_to_program_space_and_thread (bl.pspace);
11300
11301 target_download_tracepoint (&bl);
11302
11303 bl.inserted = 1;
11304 bp_location_downloaded = true;
11305 }
11306
11307 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
11308 t.number_on_target = b.number;
11309 if (bp_location_downloaded)
11310 notify_breakpoint_modified (&b);
11311 }
11312 }
11313
11314 /* Swap the insertion/duplication state between two locations. */
11315
11316 static void
11317 swap_insertion (struct bp_location *left, struct bp_location *right)
11318 {
11319 const int left_inserted = left->inserted;
11320 const int left_duplicate = left->duplicate;
11321 const int left_needs_update = left->needs_update;
11322 const struct bp_target_info left_target_info = left->target_info;
11323
11324 /* Locations of tracepoints can never be duplicated. */
11325 if (is_tracepoint (left->owner))
11326 gdb_assert (!left->duplicate);
11327 if (is_tracepoint (right->owner))
11328 gdb_assert (!right->duplicate);
11329
11330 left->inserted = right->inserted;
11331 left->duplicate = right->duplicate;
11332 left->needs_update = right->needs_update;
11333 left->target_info = right->target_info;
11334 right->inserted = left_inserted;
11335 right->duplicate = left_duplicate;
11336 right->needs_update = left_needs_update;
11337 right->target_info = left_target_info;
11338 }
11339
11340 /* Force the re-insertion of the locations at ADDRESS. This is called
11341 once a new/deleted/modified duplicate location is found and we are evaluating
11342 conditions on the target's side. Such conditions need to be updated on
11343 the target. */
11344
11345 static void
11346 force_breakpoint_reinsertion (struct bp_location *bl)
11347 {
11348 CORE_ADDR address = 0;
11349 int pspace_num;
11350
11351 address = bl->address;
11352 pspace_num = bl->pspace->num;
11353
11354 /* This is only meaningful if the target is
11355 evaluating conditions and if the user has
11356 opted for condition evaluation on the target's
11357 side. */
11358 if (gdb_evaluates_breakpoint_condition_p ()
11359 || !target_supports_evaluation_of_breakpoint_conditions ())
11360 return;
11361
11362 /* Flag all breakpoint locations with this address and
11363 the same program space as the location
11364 as "its condition has changed". We need to
11365 update the conditions on the target's side. */
11366 for (bp_location *loc : all_bp_locations_at_addr (address))
11367 {
11368 if (!is_breakpoint (loc->owner)
11369 || pspace_num != loc->pspace->num)
11370 continue;
11371
11372 /* Flag the location appropriately. We use a different state to
11373 let everyone know that we already updated the set of locations
11374 with addr bl->address and program space bl->pspace. This is so
11375 we don't have to keep calling these functions just to mark locations
11376 that have already been marked. */
11377 loc->condition_changed = condition_updated;
11378
11379 /* Free the agent expression bytecode as well. We will compute
11380 it later on. */
11381 loc->cond_bytecode.reset ();
11382 }
11383 }
11384
11385 /* Called whether new breakpoints are created, or existing breakpoints
11386 deleted, to update the global location list and recompute which
11387 locations are duplicate of which.
11388
11389 The INSERT_MODE flag determines whether locations may not, may, or
11390 shall be inserted now. See 'enum ugll_insert_mode' for more
11391 info. */
11392
11393 static void
11394 update_global_location_list (enum ugll_insert_mode insert_mode)
11395 {
11396 /* Last breakpoint location address that was marked for update. */
11397 CORE_ADDR last_addr = 0;
11398 /* Last breakpoint location program space that was marked for update. */
11399 int last_pspace_num = -1;
11400
11401 breakpoint_debug_printf ("insert_mode = %s",
11402 ugll_insert_mode_text (insert_mode));
11403
11404 /* Used in the duplicates detection below. When iterating over all
11405 bp_locations, points to the first bp_location of a given address.
11406 Breakpoints and watchpoints of different types are never
11407 duplicates of each other. Keep one pointer for each type of
11408 breakpoint/watchpoint, so we only need to loop over all locations
11409 once. */
11410 struct bp_location *bp_loc_first; /* breakpoint */
11411 struct bp_location *wp_loc_first; /* hardware watchpoint */
11412 struct bp_location *awp_loc_first; /* access watchpoint */
11413 struct bp_location *rwp_loc_first; /* read watchpoint */
11414
11415 /* Saved former bp_locations array which we compare against the newly
11416 built bp_locations from the current state of ALL_BREAKPOINTS. */
11417 std::vector<bp_location *> old_locations = std::move (bp_locations);
11418 bp_locations.clear ();
11419
11420 for (breakpoint &b : all_breakpoints ())
11421 for (bp_location &loc : b.locations ())
11422 bp_locations.push_back (&loc);
11423
11424 /* See if we need to "upgrade" a software breakpoint to a hardware
11425 breakpoint. Do this before deciding whether locations are
11426 duplicates. Also do this before sorting because sorting order
11427 depends on location type. */
11428 for (bp_location *loc : bp_locations)
11429 if (!loc->inserted && should_be_inserted (loc))
11430 handle_automatic_hardware_breakpoints (loc);
11431
11432 std::sort (bp_locations.begin (), bp_locations.end (),
11433 bp_location_is_less_than);
11434
11435 bp_locations_target_extensions_update ();
11436
11437 /* Identify bp_location instances that are no longer present in the
11438 new list, and therefore should be freed. Note that it's not
11439 necessary that those locations should be removed from inferior --
11440 if there's another location at the same address (previously
11441 marked as duplicate), we don't need to remove/insert the
11442 location.
11443
11444 LOCP is kept in sync with OLD_LOCP, each pointing to the current
11445 and former bp_location array state respectively. */
11446
11447 size_t loc_i = 0;
11448 for (bp_location *old_loc : old_locations)
11449 {
11450 /* Tells if 'old_loc' is found among the new locations. If
11451 not, we have to free it. */
11452 bool found_object = false;
11453 /* Tells if the location should remain inserted in the target. */
11454 bool keep_in_target = false;
11455 bool removed = false;
11456
11457 /* Skip LOCP entries which will definitely never be needed.
11458 Stop either at or being the one matching OLD_LOC. */
11459 while (loc_i < bp_locations.size ()
11460 && bp_locations[loc_i]->address < old_loc->address)
11461 loc_i++;
11462
11463 for (size_t loc2_i = loc_i;
11464 (loc2_i < bp_locations.size ()
11465 && bp_locations[loc2_i]->address == old_loc->address);
11466 loc2_i++)
11467 {
11468 /* Check if this is a new/duplicated location or a duplicated
11469 location that had its condition modified. If so, we want to send
11470 its condition to the target if evaluation of conditions is taking
11471 place there. */
11472 if (bp_locations[loc2_i]->condition_changed == condition_modified
11473 && (last_addr != old_loc->address
11474 || last_pspace_num != old_loc->pspace->num))
11475 {
11476 force_breakpoint_reinsertion (bp_locations[loc2_i]);
11477 last_pspace_num = old_loc->pspace->num;
11478 }
11479
11480 if (bp_locations[loc2_i] == old_loc)
11481 found_object = true;
11482 }
11483
11484 /* We have already handled this address, update it so that we don't
11485 have to go through updates again. */
11486 last_addr = old_loc->address;
11487
11488 /* Target-side condition evaluation: Handle deleted locations. */
11489 if (!found_object)
11490 force_breakpoint_reinsertion (old_loc);
11491
11492 /* If this location is no longer present, and inserted, look if
11493 there's maybe a new location at the same address. If so,
11494 mark that one inserted, and don't remove this one. This is
11495 needed so that we don't have a time window where a breakpoint
11496 at certain location is not inserted. */
11497
11498 if (old_loc->inserted)
11499 {
11500 /* If the location is inserted now, we might have to remove
11501 it. */
11502
11503 if (found_object && should_be_inserted (old_loc))
11504 {
11505 /* The location is still present in the location list,
11506 and still should be inserted. Don't do anything. */
11507 keep_in_target = true;
11508 }
11509 else
11510 {
11511 /* This location still exists, but it won't be kept in the
11512 target since it may have been disabled. We proceed to
11513 remove its target-side condition. */
11514
11515 /* The location is either no longer present, or got
11516 disabled. See if there's another location at the
11517 same address, in which case we don't need to remove
11518 this one from the target. */
11519
11520 /* OLD_LOC comes from existing struct breakpoint. */
11521 if (bl_address_is_meaningful (old_loc))
11522 {
11523 for (size_t loc2_i = loc_i;
11524 (loc2_i < bp_locations.size ()
11525 && bp_locations[loc2_i]->address == old_loc->address);
11526 loc2_i++)
11527 {
11528 bp_location *loc2 = bp_locations[loc2_i];
11529
11530 if (loc2 == old_loc)
11531 continue;
11532
11533 if (breakpoint_locations_match (loc2, old_loc))
11534 {
11535 /* Read watchpoint locations are switched to
11536 access watchpoints, if the former are not
11537 supported, but the latter are. */
11538 if (is_hardware_watchpoint (old_loc->owner))
11539 {
11540 gdb_assert (is_hardware_watchpoint (loc2->owner));
11541 loc2->watchpoint_type = old_loc->watchpoint_type;
11542 }
11543
11544 /* loc2 is a duplicated location. We need to check
11545 if it should be inserted in case it will be
11546 unduplicated. */
11547 if (unduplicated_should_be_inserted (loc2))
11548 {
11549 swap_insertion (old_loc, loc2);
11550 keep_in_target = true;
11551 break;
11552 }
11553 }
11554 }
11555 }
11556 }
11557
11558 if (!keep_in_target)
11559 {
11560 if (remove_breakpoint (old_loc))
11561 {
11562 /* This is just about all we can do. We could keep
11563 this location on the global list, and try to
11564 remove it next time, but there's no particular
11565 reason why we will succeed next time.
11566
11567 Note that at this point, old_loc->owner is still
11568 valid, as delete_breakpoint frees the breakpoint
11569 only after calling us. */
11570 warning (_("error removing breakpoint %d at %s"),
11571 old_loc->owner->number,
11572 paddress (old_loc->gdbarch, old_loc->address));
11573 }
11574 removed = true;
11575 }
11576 }
11577
11578 if (!found_object)
11579 {
11580 if (removed && target_is_non_stop_p ()
11581 && need_moribund_for_location_type (old_loc))
11582 {
11583 /* This location was removed from the target. In
11584 non-stop mode, a race condition is possible where
11585 we've removed a breakpoint, but stop events for that
11586 breakpoint are already queued and will arrive later.
11587 We apply an heuristic to be able to distinguish such
11588 SIGTRAPs from other random SIGTRAPs: we keep this
11589 breakpoint location for a bit, and will retire it
11590 after we see some number of events. The theory here
11591 is that reporting of events should, "on the average",
11592 be fair, so after a while we'll see events from all
11593 threads that have anything of interest, and no longer
11594 need to keep this breakpoint location around. We
11595 don't hold locations forever so to reduce chances of
11596 mistaking a non-breakpoint SIGTRAP for a breakpoint
11597 SIGTRAP.
11598
11599 The heuristic failing can be disastrous on
11600 decr_pc_after_break targets.
11601
11602 On decr_pc_after_break targets, like e.g., x86-linux,
11603 if we fail to recognize a late breakpoint SIGTRAP,
11604 because events_till_retirement has reached 0 too
11605 soon, we'll fail to do the PC adjustment, and report
11606 a random SIGTRAP to the user. When the user resumes
11607 the inferior, it will most likely immediately crash
11608 with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11609 corrupted, because of being resumed e.g., in the
11610 middle of a multi-byte instruction, or skipped a
11611 one-byte instruction. This was actually seen happen
11612 on native x86-linux, and should be less rare on
11613 targets that do not support new thread events, like
11614 remote, due to the heuristic depending on
11615 thread_count.
11616
11617 Mistaking a random SIGTRAP for a breakpoint trap
11618 causes similar symptoms (PC adjustment applied when
11619 it shouldn't), but then again, playing with SIGTRAPs
11620 behind the debugger's back is asking for trouble.
11621
11622 Since hardware watchpoint traps are always
11623 distinguishable from other traps, so we don't need to
11624 apply keep hardware watchpoint moribund locations
11625 around. We simply always ignore hardware watchpoint
11626 traps we can no longer explain. */
11627
11628 process_stratum_target *proc_target = nullptr;
11629 for (inferior *inf : all_inferiors ())
11630 if (inf->pspace == old_loc->pspace)
11631 {
11632 proc_target = inf->process_target ();
11633 break;
11634 }
11635 if (proc_target != nullptr)
11636 old_loc->events_till_retirement
11637 = 3 * (thread_count (proc_target) + 1);
11638 else
11639 old_loc->events_till_retirement = 1;
11640 old_loc->owner = NULL;
11641
11642 moribund_locations.push_back (old_loc);
11643 }
11644 else
11645 {
11646 old_loc->owner = NULL;
11647 decref_bp_location (&old_loc);
11648 }
11649 }
11650 }
11651
11652 /* Rescan breakpoints at the same address and section, marking the
11653 first one as "first" and any others as "duplicates". This is so
11654 that the bpt instruction is only inserted once. If we have a
11655 permanent breakpoint at the same place as BPT, make that one the
11656 official one, and the rest as duplicates. Permanent breakpoints
11657 are sorted first for the same address.
11658
11659 Do the same for hardware watchpoints, but also considering the
11660 watchpoint's type (regular/access/read) and length. */
11661
11662 bp_loc_first = NULL;
11663 wp_loc_first = NULL;
11664 awp_loc_first = NULL;
11665 rwp_loc_first = NULL;
11666
11667 for (bp_location *loc : all_bp_locations ())
11668 {
11669 /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11670 non-NULL. */
11671 struct bp_location **loc_first_p;
11672 breakpoint *b = loc->owner;
11673
11674 if (!unduplicated_should_be_inserted (loc)
11675 || !bl_address_is_meaningful (loc)
11676 /* Don't detect duplicate for tracepoint locations because they are
11677 never duplicated. See the comments in field `duplicate' of
11678 `struct bp_location'. */
11679 || is_tracepoint (b))
11680 {
11681 /* Clear the condition modification flag. */
11682 loc->condition_changed = condition_unchanged;
11683 continue;
11684 }
11685
11686 if (b->type == bp_hardware_watchpoint)
11687 loc_first_p = &wp_loc_first;
11688 else if (b->type == bp_read_watchpoint)
11689 loc_first_p = &rwp_loc_first;
11690 else if (b->type == bp_access_watchpoint)
11691 loc_first_p = &awp_loc_first;
11692 else
11693 loc_first_p = &bp_loc_first;
11694
11695 if (*loc_first_p == NULL
11696 || (overlay_debugging && loc->section != (*loc_first_p)->section)
11697 || !breakpoint_locations_match (loc, *loc_first_p))
11698 {
11699 *loc_first_p = loc;
11700 loc->duplicate = 0;
11701
11702 if (is_breakpoint (loc->owner) && loc->condition_changed)
11703 {
11704 loc->needs_update = 1;
11705 /* Clear the condition modification flag. */
11706 loc->condition_changed = condition_unchanged;
11707 }
11708 continue;
11709 }
11710
11711
11712 /* This and the above ensure the invariant that the first location
11713 is not duplicated, and is the inserted one.
11714 All following are marked as duplicated, and are not inserted. */
11715 if (loc->inserted)
11716 swap_insertion (loc, *loc_first_p);
11717 loc->duplicate = 1;
11718
11719 /* Clear the condition modification flag. */
11720 loc->condition_changed = condition_unchanged;
11721 }
11722
11723 if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
11724 {
11725 if (insert_mode != UGLL_DONT_INSERT)
11726 insert_breakpoint_locations ();
11727 else
11728 {
11729 /* Even though the caller told us to not insert new
11730 locations, we may still need to update conditions on the
11731 target's side of breakpoints that were already inserted
11732 if the target is evaluating breakpoint conditions. We
11733 only update conditions for locations that are marked
11734 "needs_update". */
11735 update_inserted_breakpoint_locations ();
11736 }
11737 }
11738
11739 if (insert_mode != UGLL_DONT_INSERT)
11740 download_tracepoint_locations ();
11741 }
11742
11743 void
11744 breakpoint_retire_moribund (void)
11745 {
11746 for (int ix = 0; ix < moribund_locations.size (); ++ix)
11747 {
11748 struct bp_location *loc = moribund_locations[ix];
11749 if (--(loc->events_till_retirement) == 0)
11750 {
11751 decref_bp_location (&loc);
11752 unordered_remove (moribund_locations, ix);
11753 --ix;
11754 }
11755 }
11756 }
11757
11758 static void
11759 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
11760 {
11761
11762 try
11763 {
11764 update_global_location_list (insert_mode);
11765 }
11766 catch (const gdb_exception_error &e)
11767 {
11768 }
11769 }
11770
11771 /* Clear BKP from a BPS. */
11772
11773 static void
11774 bpstat_remove_bp_location (bpstat *bps, struct breakpoint *bpt)
11775 {
11776 bpstat *bs;
11777
11778 for (bs = bps; bs; bs = bs->next)
11779 if (bs->breakpoint_at == bpt)
11780 {
11781 bs->breakpoint_at = NULL;
11782 bs->old_val = NULL;
11783 /* bs->commands will be freed later. */
11784 }
11785 }
11786
11787 /* Callback for iterate_over_threads. */
11788 static int
11789 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11790 {
11791 struct breakpoint *bpt = (struct breakpoint *) data;
11792
11793 bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11794 return 0;
11795 }
11796
11797 /* See breakpoint.h. */
11798
11799 void
11800 code_breakpoint::say_where () const
11801 {
11802 struct value_print_options opts;
11803
11804 get_user_print_options (&opts);
11805
11806 /* i18n: cagney/2005-02-11: Below needs to be merged into a
11807 single string. */
11808 if (!this->has_locations ())
11809 {
11810 /* For pending locations, the output differs slightly based
11811 on extra_string. If this is non-NULL, it contains either
11812 a condition or dprintf arguments. */
11813 if (extra_string == NULL)
11814 {
11815 gdb_printf (_(" (%s) pending."), locspec->to_string ());
11816 }
11817 else if (type == bp_dprintf)
11818 {
11819 gdb_printf (_(" (%s,%s) pending."),
11820 locspec->to_string (),
11821 extra_string.get ());
11822 }
11823 else
11824 {
11825 gdb_printf (_(" (%s %s) pending."),
11826 locspec->to_string (),
11827 extra_string.get ());
11828 }
11829 }
11830 else
11831 {
11832 const bp_location &bl = this->first_loc ();
11833 if (opts.addressprint || bl.symtab == nullptr)
11834 gdb_printf (" at %ps",
11835 styled_string (address_style.style (),
11836 paddress (bl.gdbarch,
11837 bl.address)));
11838 if (bl.symtab != NULL)
11839 {
11840 /* If there is a single location, we can print the location
11841 more nicely. */
11842 if (!this->has_multiple_locations ())
11843 {
11844 const char *filename
11845 = symtab_to_filename_for_display (bl.symtab);
11846 gdb_printf (": file %ps, line %d.",
11847 styled_string (file_name_style.style (),
11848 filename),
11849 bl.line_number);
11850 }
11851 else
11852 /* This is not ideal, but each location may have a
11853 different file name, and this at least reflects the
11854 real situation somewhat. */
11855 gdb_printf (": %s.", locspec->to_string ());
11856 }
11857
11858 if (this->has_multiple_locations ())
11859 {
11860 int n = std::distance (m_locations.begin (), m_locations.end ());
11861 gdb_printf (" (%d locations)", n);
11862 }
11863 }
11864 }
11865
11866 /* See breakpoint.h. */
11867
11868 bp_location_range breakpoint::locations () const
11869 {
11870 return bp_location_range (m_locations.begin (), m_locations.end ());
11871 }
11872
11873 struct bp_location *
11874 breakpoint::allocate_location ()
11875 {
11876 return new bp_location (this);
11877 }
11878
11879 /* See breakpoint.h. */
11880
11881 void
11882 breakpoint::add_location (bp_location &loc)
11883 {
11884 gdb_assert (loc.owner == this);
11885 gdb_assert (!loc.is_linked ());
11886
11887 auto ub = std::upper_bound (m_locations.begin (), m_locations.end (),
11888 loc,
11889 [] (const bp_location &left,
11890 const bp_location &right)
11891 { return left.address < right.address; });
11892 m_locations.insert (ub, loc);
11893 }
11894
11895 /* See breakpoint.h. */
11896
11897 void
11898 breakpoint::unadd_location (bp_location &loc)
11899 {
11900 gdb_assert (loc.owner == this);
11901 gdb_assert (loc.is_linked ());
11902
11903 m_locations.erase (m_locations.iterator_to (loc));
11904 }
11905
11906 #define internal_error_pure_virtual_called() \
11907 gdb_assert_not_reached ("pure virtual function called")
11908
11909 int
11910 breakpoint::insert_location (struct bp_location *bl)
11911 {
11912 internal_error_pure_virtual_called ();
11913 }
11914
11915 int
11916 breakpoint::remove_location (struct bp_location *bl,
11917 enum remove_bp_reason reason)
11918 {
11919 internal_error_pure_virtual_called ();
11920 }
11921
11922 int
11923 breakpoint::breakpoint_hit (const struct bp_location *bl,
11924 const address_space *aspace,
11925 CORE_ADDR bp_addr,
11926 const target_waitstatus &ws)
11927 {
11928 internal_error_pure_virtual_called ();
11929 }
11930
11931 int
11932 breakpoint::resources_needed (const struct bp_location *bl)
11933 {
11934 internal_error_pure_virtual_called ();
11935 }
11936
11937 enum print_stop_action
11938 breakpoint::print_it (const bpstat *bs) const
11939 {
11940 internal_error_pure_virtual_called ();
11941 }
11942
11943 void
11944 breakpoint::print_mention () const
11945 {
11946 internal_error_pure_virtual_called ();
11947 }
11948
11949 void
11950 breakpoint::print_recreate (struct ui_file *fp) const
11951 {
11952 internal_error_pure_virtual_called ();
11953 }
11954
11955 /* Default breakpoint_ops methods. */
11956
11957 void
11958 code_breakpoint::re_set ()
11959 {
11960 /* FIXME: is this still reachable? */
11961 if (breakpoint_location_spec_empty_p (this))
11962 {
11963 /* Anything without a location can't be re-set. */
11964 delete_breakpoint (this);
11965 return;
11966 }
11967
11968 re_set_default ();
11969 }
11970
11971 int
11972 code_breakpoint::insert_location (struct bp_location *bl)
11973 {
11974 CORE_ADDR addr = bl->target_info.reqstd_address;
11975
11976 bl->target_info.kind = breakpoint_kind (bl, &addr);
11977 bl->target_info.placed_address = addr;
11978
11979 int result;
11980 if (bl->loc_type == bp_loc_hardware_breakpoint)
11981 result = target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
11982 else
11983 result = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
11984
11985 if (result == 0 && bl->probe.prob != nullptr)
11986 {
11987 /* The insertion was successful, now let's set the probe's semaphore
11988 if needed. */
11989 bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
11990 }
11991
11992 return result;
11993 }
11994
11995 int
11996 code_breakpoint::remove_location (struct bp_location *bl,
11997 enum remove_bp_reason reason)
11998 {
11999 if (bl->probe.prob != nullptr)
12000 {
12001 /* Let's clear the semaphore before removing the location. */
12002 bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12003 }
12004
12005 if (bl->loc_type == bp_loc_hardware_breakpoint)
12006 return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12007 else
12008 return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12009 }
12010
12011 int
12012 code_breakpoint::breakpoint_hit (const struct bp_location *bl,
12013 const address_space *aspace,
12014 CORE_ADDR bp_addr,
12015 const target_waitstatus &ws)
12016 {
12017 if (ws.kind () != TARGET_WAITKIND_STOPPED
12018 || ws.sig () != GDB_SIGNAL_TRAP)
12019 return 0;
12020
12021 if (!breakpoint_address_match (bl->pspace->aspace.get (), bl->address,
12022 aspace, bp_addr))
12023 return 0;
12024
12025 if (overlay_debugging /* unmapped overlay section */
12026 && section_is_overlay (bl->section)
12027 && !section_is_mapped (bl->section))
12028 return 0;
12029
12030 return 1;
12031 }
12032
12033 int
12034 dprintf_breakpoint::breakpoint_hit (const struct bp_location *bl,
12035 const address_space *aspace,
12036 CORE_ADDR bp_addr,
12037 const target_waitstatus &ws)
12038 {
12039 if (dprintf_style == dprintf_style_agent
12040 && target_can_run_breakpoint_commands ())
12041 {
12042 /* An agent-style dprintf never causes a stop. If we see a trap
12043 for this address it must be for a breakpoint that happens to
12044 be set at the same address. */
12045 return 0;
12046 }
12047
12048 return this->ordinary_breakpoint::breakpoint_hit (bl, aspace, bp_addr, ws);
12049 }
12050
12051 int
12052 ordinary_breakpoint::resources_needed (const struct bp_location *bl)
12053 {
12054 gdb_assert (type == bp_hardware_breakpoint);
12055
12056 return 1;
12057 }
12058
12059 enum print_stop_action
12060 ordinary_breakpoint::print_it (const bpstat *bs) const
12061 {
12062 const struct bp_location *bl;
12063 int bp_temp;
12064 struct ui_out *uiout = current_uiout;
12065
12066 bl = bs->bp_location_at.get ();
12067
12068 bp_temp = disposition == disp_del;
12069 if (bl->address != bl->requested_address)
12070 breakpoint_adjustment_warning (bl->requested_address,
12071 bl->address,
12072 number, true);
12073 annotate_breakpoint (number);
12074 maybe_print_thread_hit_breakpoint (uiout);
12075
12076 if (uiout->is_mi_like_p ())
12077 {
12078 uiout->field_string ("reason",
12079 async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12080 uiout->field_string ("disp", bpdisp_text (disposition));
12081 }
12082
12083 if (bp_temp)
12084 uiout->text ("Temporary breakpoint ");
12085 else
12086 uiout->text ("Breakpoint ");
12087 print_num_locno (bs, uiout);
12088 uiout->text (", ");
12089
12090 return PRINT_SRC_AND_LOC;
12091 }
12092
12093 void
12094 ordinary_breakpoint::print_mention () const
12095 {
12096 if (current_uiout->is_mi_like_p ())
12097 return;
12098
12099 switch (type)
12100 {
12101 case bp_breakpoint:
12102 case bp_gnu_ifunc_resolver:
12103 if (disposition == disp_del)
12104 gdb_printf (_("Temporary breakpoint"));
12105 else
12106 gdb_printf (_("Breakpoint"));
12107 gdb_printf (_(" %d"), number);
12108 if (type == bp_gnu_ifunc_resolver)
12109 gdb_printf (_(" at gnu-indirect-function resolver"));
12110 break;
12111 case bp_hardware_breakpoint:
12112 gdb_printf (_("Hardware assisted breakpoint %d"), number);
12113 break;
12114 case bp_dprintf:
12115 gdb_printf (_("Dprintf %d"), number);
12116 break;
12117 }
12118
12119 say_where ();
12120 }
12121
12122 void
12123 ordinary_breakpoint::print_recreate (struct ui_file *fp) const
12124 {
12125 if (type == bp_breakpoint && disposition == disp_del)
12126 gdb_printf (fp, "tbreak");
12127 else if (type == bp_breakpoint)
12128 gdb_printf (fp, "break");
12129 else if (type == bp_hardware_breakpoint
12130 && disposition == disp_del)
12131 gdb_printf (fp, "thbreak");
12132 else if (type == bp_hardware_breakpoint)
12133 gdb_printf (fp, "hbreak");
12134 else
12135 internal_error (_("unhandled breakpoint type %d"), (int) type);
12136
12137 gdb_printf (fp, " %s", locspec->to_string ());
12138
12139 /* Print out extra_string if this breakpoint is pending. It might
12140 contain, for example, conditions that were set by the user. */
12141 if (!this->has_locations () && extra_string != NULL)
12142 gdb_printf (fp, " %s", extra_string.get ());
12143
12144 print_recreate_thread (fp);
12145 }
12146
12147 std::vector<symtab_and_line>
12148 code_breakpoint::decode_location_spec (location_spec *locspec,
12149 program_space *search_pspace)
12150 {
12151 if (locspec->type () == PROBE_LOCATION_SPEC)
12152 return bkpt_probe_decode_location_spec (this, locspec, search_pspace);
12153
12154 struct linespec_result canonical;
12155
12156 decode_line_full (locspec, DECODE_LINE_FUNFIRSTLINE, search_pspace,
12157 NULL, 0, &canonical, multiple_symbols_all,
12158 filter.get ());
12159
12160 /* We should get 0 or 1 resulting SALs. */
12161 gdb_assert (canonical.lsals.size () < 2);
12162
12163 if (!canonical.lsals.empty ())
12164 {
12165 const linespec_sals &lsal = canonical.lsals[0];
12166 return std::move (lsal.sals);
12167 }
12168 return {};
12169 }
12170
12171 /* Virtual table for internal breakpoints. */
12172
12173 void
12174 internal_breakpoint::re_set ()
12175 {
12176 switch (type)
12177 {
12178 /* Delete overlay event and longjmp master breakpoints; they
12179 will be reset later by breakpoint_re_set. */
12180 case bp_overlay_event:
12181 case bp_longjmp_master:
12182 case bp_std_terminate_master:
12183 case bp_exception_master:
12184 delete_breakpoint (this);
12185 break;
12186
12187 /* This breakpoint is special, it's set up when the inferior
12188 starts and we really don't want to touch it. */
12189 case bp_shlib_event:
12190
12191 /* Like bp_shlib_event, this breakpoint type is special. Once
12192 it is set up, we do not want to touch it. */
12193 case bp_thread_event:
12194 break;
12195 }
12196 }
12197
12198 void
12199 internal_breakpoint::check_status (bpstat *bs)
12200 {
12201 if (type == bp_shlib_event)
12202 {
12203 /* If requested, stop when the dynamic linker notifies GDB of
12204 events. This allows the user to get control and place
12205 breakpoints in initializer routines for dynamically loaded
12206 objects (among other things). */
12207 bs->stop = stop_on_solib_events != 0;
12208 bs->print = stop_on_solib_events != 0;
12209 }
12210 else
12211 bs->stop = false;
12212 }
12213
12214 enum print_stop_action
12215 internal_breakpoint::print_it (const bpstat *bs) const
12216 {
12217 switch (type)
12218 {
12219 case bp_shlib_event:
12220 /* Did we stop because the user set the stop_on_solib_events
12221 variable? (If so, we report this as a generic, "Stopped due
12222 to shlib event" message.) */
12223 print_solib_event (false);
12224 break;
12225
12226 case bp_thread_event:
12227 /* Not sure how we will get here.
12228 GDB should not stop for these breakpoints. */
12229 gdb_printf (_("Thread Event Breakpoint: gdb should not stop!\n"));
12230 break;
12231
12232 case bp_overlay_event:
12233 /* By analogy with the thread event, GDB should not stop for these. */
12234 gdb_printf (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12235 break;
12236
12237 case bp_longjmp_master:
12238 /* These should never be enabled. */
12239 gdb_printf (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12240 break;
12241
12242 case bp_std_terminate_master:
12243 /* These should never be enabled. */
12244 gdb_printf (_("std::terminate Master Breakpoint: "
12245 "gdb should not stop!\n"));
12246 break;
12247
12248 case bp_exception_master:
12249 /* These should never be enabled. */
12250 gdb_printf (_("Exception Master Breakpoint: "
12251 "gdb should not stop!\n"));
12252 break;
12253 }
12254
12255 return PRINT_NOTHING;
12256 }
12257
12258 void
12259 internal_breakpoint::print_mention () const
12260 {
12261 /* Nothing to mention. These breakpoints are internal. */
12262 }
12263
12264 /* Virtual table for momentary breakpoints */
12265
12266 void
12267 momentary_breakpoint::re_set ()
12268 {
12269 /* Keep temporary breakpoints, which can be encountered when we step
12270 over a dlopen call and solib_add is resetting the breakpoints.
12271 Otherwise these should have been blown away via the cleanup chain
12272 or by breakpoint_init_inferior when we rerun the executable. */
12273 }
12274
12275 void
12276 momentary_breakpoint::check_status (bpstat *bs)
12277 {
12278 /* Nothing. The point of these breakpoints is causing a stop. */
12279 }
12280
12281 enum print_stop_action
12282 momentary_breakpoint::print_it (const bpstat *bs) const
12283 {
12284 return PRINT_UNKNOWN;
12285 }
12286
12287 void
12288 momentary_breakpoint::print_mention () const
12289 {
12290 /* Nothing to mention. These breakpoints are internal. */
12291 }
12292
12293 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12294
12295 It gets cleared already on the removal of the first one of such placed
12296 breakpoints. This is OK as they get all removed altogether. */
12297
12298 longjmp_breakpoint::~longjmp_breakpoint ()
12299 {
12300 thread_info *tp = find_thread_global_id (this->thread);
12301
12302 if (tp != NULL)
12303 tp->initiating_frame = null_frame_id;
12304 }
12305
12306 static void
12307 bkpt_probe_create_sals_from_location_spec (location_spec *locspec,
12308 struct linespec_result *canonical)
12309
12310 {
12311 struct linespec_sals lsal;
12312
12313 lsal.sals = parse_probes (locspec, NULL, canonical);
12314 lsal.canonical = xstrdup (canonical->locspec->to_string ());
12315 canonical->lsals.push_back (std::move (lsal));
12316 }
12317
12318 static std::vector<symtab_and_line>
12319 bkpt_probe_decode_location_spec (struct breakpoint *b,
12320 location_spec *locspec,
12321 program_space *search_pspace)
12322 {
12323 std::vector<symtab_and_line> sals
12324 = parse_probes (locspec, search_pspace, NULL);
12325 if (sals.empty ())
12326 error (_("probe not found"));
12327 return sals;
12328 }
12329
12330 int
12331 tracepoint::breakpoint_hit (const struct bp_location *bl,
12332 const address_space *aspace, CORE_ADDR bp_addr,
12333 const target_waitstatus &ws)
12334 {
12335 /* By definition, the inferior does not report stops at
12336 tracepoints. */
12337 return 0;
12338 }
12339
12340 void
12341 tracepoint::print_one_detail (struct ui_out *uiout) const
12342 {
12343 if (!static_trace_marker_id.empty ())
12344 {
12345 gdb_assert (type == bp_static_tracepoint
12346 || type == bp_static_marker_tracepoint);
12347
12348 uiout->message ("\tmarker id is %pF\n",
12349 string_field ("static-tracepoint-marker-string-id",
12350 static_trace_marker_id.c_str ()));
12351 }
12352 }
12353
12354 void
12355 tracepoint::print_mention () const
12356 {
12357 if (current_uiout->is_mi_like_p ())
12358 return;
12359
12360 switch (type)
12361 {
12362 case bp_tracepoint:
12363 gdb_printf (_("Tracepoint"));
12364 gdb_printf (_(" %d"), number);
12365 break;
12366 case bp_fast_tracepoint:
12367 gdb_printf (_("Fast tracepoint"));
12368 gdb_printf (_(" %d"), number);
12369 break;
12370 case bp_static_tracepoint:
12371 case bp_static_marker_tracepoint:
12372 gdb_printf (_("Static tracepoint"));
12373 gdb_printf (_(" %d"), number);
12374 break;
12375 default:
12376 internal_error (_("unhandled tracepoint type %d"), (int) type);
12377 }
12378
12379 say_where ();
12380 }
12381
12382 void
12383 tracepoint::print_recreate (struct ui_file *fp) const
12384 {
12385 if (type == bp_fast_tracepoint)
12386 gdb_printf (fp, "ftrace");
12387 else if (type == bp_static_tracepoint
12388 || type == bp_static_marker_tracepoint)
12389 gdb_printf (fp, "strace");
12390 else if (type == bp_tracepoint)
12391 gdb_printf (fp, "trace");
12392 else
12393 internal_error (_("unhandled tracepoint type %d"), (int) type);
12394
12395 gdb_printf (fp, " %s", locspec->to_string ());
12396 print_recreate_thread (fp);
12397
12398 if (pass_count)
12399 gdb_printf (fp, " passcount %d\n", pass_count);
12400 }
12401
12402 /* Virtual table for tracepoints on static probes. */
12403
12404 static void
12405 tracepoint_probe_create_sals_from_location_spec
12406 (location_spec *locspec,
12407 struct linespec_result *canonical)
12408 {
12409 /* We use the same method for breakpoint on probes. */
12410 bkpt_probe_create_sals_from_location_spec (locspec, canonical);
12411 }
12412
12413 void
12414 dprintf_breakpoint::re_set ()
12415 {
12416 re_set_default ();
12417
12418 /* extra_string should never be non-NULL for dprintf. */
12419 gdb_assert (extra_string != NULL);
12420
12421 /* 1 - connect to target 1, that can run breakpoint commands.
12422 2 - create a dprintf, which resolves fine.
12423 3 - disconnect from target 1
12424 4 - connect to target 2, that can NOT run breakpoint commands.
12425
12426 After steps #3/#4, you'll want the dprintf command list to
12427 be updated, because target 1 and 2 may well return different
12428 answers for target_can_run_breakpoint_commands().
12429 Given absence of finer grained resetting, we get to do
12430 it all the time. */
12431 if (extra_string != NULL)
12432 update_dprintf_command_list (this);
12433 }
12434
12435 /* Implement the "print_recreate" method for dprintf. */
12436
12437 void
12438 dprintf_breakpoint::print_recreate (struct ui_file *fp) const
12439 {
12440 gdb_printf (fp, "dprintf %s,%s", locspec->to_string (), extra_string.get ());
12441 print_recreate_thread (fp);
12442 }
12443
12444 /* Implement the "after_condition_true" method for dprintf.
12445
12446 dprintf's are implemented with regular commands in their command
12447 list, but we run the commands here instead of before presenting the
12448 stop to the user, as dprintf's don't actually cause a stop. This
12449 also makes it so that the commands of multiple dprintfs at the same
12450 address are all handled. */
12451
12452 void
12453 dprintf_breakpoint::after_condition_true (struct bpstat *bs)
12454 {
12455 /* dprintf's never cause a stop. This wasn't set in the
12456 check_status hook instead because that would make the dprintf's
12457 condition not be evaluated. */
12458 bs->stop = false;
12459
12460 /* Run the command list here. Take ownership of it instead of
12461 copying. We never want these commands to run later in
12462 bpstat_do_actions, if a breakpoint that causes a stop happens to
12463 be set at same address as this dprintf, or even if running the
12464 commands here throws. */
12465 counted_command_line cmds = std::move (bs->commands);
12466 gdb_assert (cmds != nullptr);
12467 execute_control_commands (cmds.get (), 0);
12468 }
12469
12470 /* The breakpoint_ops structure to be used on static tracepoints with
12471 markers (`-m'). */
12472
12473 static void
12474 strace_marker_create_sals_from_location_spec (location_spec *locspec,
12475 struct linespec_result *canonical)
12476 {
12477 struct linespec_sals lsal;
12478 const char *arg_start, *arg;
12479
12480 arg = arg_start = as_linespec_location_spec (locspec)->spec_string.get ();
12481 lsal.sals = decode_static_tracepoint_spec (&arg);
12482
12483 std::string str (arg_start, arg - arg_start);
12484 const char *ptr = str.c_str ();
12485 canonical->locspec
12486 = new_linespec_location_spec (&ptr, symbol_name_match_type::FULL);
12487
12488 lsal.canonical = xstrdup (canonical->locspec->to_string ());
12489 canonical->lsals.push_back (std::move (lsal));
12490 }
12491
12492 static void
12493 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12494 struct linespec_result *canonical,
12495 gdb::unique_xmalloc_ptr<char> cond_string,
12496 gdb::unique_xmalloc_ptr<char> extra_string,
12497 enum bptype type_wanted,
12498 enum bpdisp disposition,
12499 int thread,
12500 int task, int inferior,
12501 int ignore_count,
12502 int from_tty, int enabled,
12503 int internal, unsigned flags)
12504 {
12505 const linespec_sals &lsal = canonical->lsals[0];
12506
12507 /* If the user is creating a static tracepoint by marker id
12508 (strace -m MARKER_ID), then store the sals index, so that
12509 breakpoint_re_set can try to match up which of the newly
12510 found markers corresponds to this one, and, don't try to
12511 expand multiple locations for each sal, given than SALS
12512 already should contain all sals for MARKER_ID. */
12513
12514 for (size_t i = 0; i < lsal.sals.size (); i++)
12515 {
12516 location_spec_up locspec = canonical->locspec->clone ();
12517
12518 std::unique_ptr<tracepoint> tp
12519 (new tracepoint (gdbarch,
12520 type_wanted,
12521 lsal.sals[i],
12522 std::move (locspec),
12523 NULL,
12524 std::move (cond_string),
12525 std::move (extra_string),
12526 disposition,
12527 thread, task, inferior, ignore_count,
12528 from_tty, enabled, flags,
12529 canonical->special_display));
12530
12531 /* Given that its possible to have multiple markers with
12532 the same string id, if the user is creating a static
12533 tracepoint by marker id ("strace -m MARKER_ID"), then
12534 store the sals index, so that breakpoint_re_set can
12535 try to match up which of the newly found markers
12536 corresponds to this one */
12537 tp->static_trace_marker_id_idx = i;
12538
12539 install_breakpoint (internal, std::move (tp), 0);
12540 }
12541 }
12542
12543 std::vector<symtab_and_line>
12544 static_marker_tracepoint::decode_location_spec (location_spec *locspec,
12545 program_space *search_pspace)
12546 {
12547 const char *s = as_linespec_location_spec (locspec)->spec_string.get ();
12548
12549 std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
12550 if (sals.size () > static_trace_marker_id_idx)
12551 {
12552 sals[0] = sals[static_trace_marker_id_idx];
12553 sals.resize (1);
12554 return sals;
12555 }
12556 else
12557 error (_("marker %s not found"), static_trace_marker_id.c_str ());
12558 }
12559
12560 /* Static tracepoints with marker (`-m'). */
12561 static struct breakpoint_ops strace_marker_breakpoint_ops =
12562 {
12563 strace_marker_create_sals_from_location_spec,
12564 strace_marker_create_breakpoints_sal,
12565 };
12566
12567 static bool
12568 strace_marker_p (struct breakpoint *b)
12569 {
12570 return b->type == bp_static_marker_tracepoint;
12571 }
12572
12573 /* Notify interpreters and observers that breakpoint B was deleted. */
12574
12575 static void
12576 notify_breakpoint_deleted (breakpoint *b)
12577 {
12578 interps_notify_breakpoint_deleted (b);
12579 gdb::observers::breakpoint_deleted.notify (b);
12580 }
12581
12582 /* Delete a breakpoint and clean up all traces of it in the data
12583 structures. */
12584
12585 void
12586 delete_breakpoint (struct breakpoint *bpt)
12587 {
12588 gdb_assert (bpt != NULL);
12589
12590 /* Has this bp already been deleted? This can happen because
12591 multiple lists can hold pointers to bp's. bpstat lists are
12592 especial culprits.
12593
12594 One example of this happening is a watchpoint's scope bp. When
12595 the scope bp triggers, we notice that the watchpoint is out of
12596 scope, and delete it. We also delete its scope bp. But the
12597 scope bp is marked "auto-deleting", and is already on a bpstat.
12598 That bpstat is then checked for auto-deleting bp's, which are
12599 deleted.
12600
12601 A real solution to this problem might involve reference counts in
12602 bp's, and/or giving them pointers back to their referencing
12603 bpstat's, and teaching delete_breakpoint to only free a bp's
12604 storage when no more references were extent. A cheaper bandaid
12605 was chosen. */
12606 if (bpt->type == bp_none)
12607 return;
12608
12609 /* At least avoid this stale reference until the reference counting
12610 of breakpoints gets resolved. */
12611 if (bpt->related_breakpoint != bpt)
12612 {
12613 struct breakpoint *related;
12614 struct watchpoint *w;
12615
12616 if (bpt->type == bp_watchpoint_scope)
12617 w = gdb::checked_static_cast<watchpoint *> (bpt->related_breakpoint);
12618 else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12619 w = gdb::checked_static_cast<watchpoint *> (bpt);
12620 else
12621 w = NULL;
12622 if (w != NULL)
12623 watchpoint_del_at_next_stop (w);
12624
12625 /* Unlink bpt from the bpt->related_breakpoint ring. */
12626 for (related = bpt; related->related_breakpoint != bpt;
12627 related = related->related_breakpoint);
12628 related->related_breakpoint = bpt->related_breakpoint;
12629 bpt->related_breakpoint = bpt;
12630 }
12631
12632 /* watch_command_1 creates a watchpoint but only sets its number if
12633 update_watchpoint succeeds in creating its bp_locations. If there's
12634 a problem in that process, we'll be asked to delete the half-created
12635 watchpoint. In that case, don't announce the deletion. */
12636 if (bpt->number)
12637 notify_breakpoint_deleted (bpt);
12638
12639 breakpoint_chain.erase (breakpoint_chain.iterator_to (*bpt));
12640
12641 /* Be sure no bpstat's are pointing at the breakpoint after it's
12642 been freed. */
12643 /* FIXME, how can we find all bpstat's? We just check stop_bpstat
12644 in all threads for now. Note that we cannot just remove bpstats
12645 pointing at bpt from the stop_bpstat list entirely, as breakpoint
12646 commands are associated with the bpstat; if we remove it here,
12647 then the later call to bpstat_do_actions (&stop_bpstat); in
12648 event-top.c won't do anything, and temporary breakpoints with
12649 commands won't work. */
12650
12651 iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12652
12653 /* Now that breakpoint is removed from breakpoint list, update the
12654 global location list. This will remove locations that used to
12655 belong to this breakpoint. Do this before freeing the breakpoint
12656 itself, since remove_breakpoint looks at location's owner. It
12657 might be better design to have location completely
12658 self-contained, but it's not the case now.
12659
12660 Clear the location linked list first, otherwise, the intrusive_list
12661 destructor accesses the locations after they are freed. */
12662 bpt->clear_locations ();
12663 update_global_location_list (UGLL_DONT_INSERT);
12664
12665 /* On the chance that someone will soon try again to delete this
12666 same bp, we mark it as deleted before freeing its storage. */
12667 bpt->type = bp_none;
12668 delete bpt;
12669 }
12670
12671 /* Iterator function to call a user-provided callback function once
12672 for each of B and its related breakpoints. */
12673
12674 static void
12675 iterate_over_related_breakpoints (struct breakpoint *b,
12676 gdb::function_view<void (breakpoint *)> function)
12677 {
12678 struct breakpoint *related;
12679
12680 related = b;
12681 do
12682 {
12683 struct breakpoint *next;
12684
12685 /* FUNCTION may delete RELATED. */
12686 next = related->related_breakpoint;
12687
12688 if (next == related)
12689 {
12690 /* RELATED is the last ring entry. */
12691 function (related);
12692
12693 /* FUNCTION may have deleted it, so we'd never reach back to
12694 B. There's nothing left to do anyway, so just break
12695 out. */
12696 break;
12697 }
12698 else
12699 function (related);
12700
12701 related = next;
12702 }
12703 while (related != b);
12704 }
12705
12706 static void
12707 delete_command (const char *arg, int from_tty)
12708 {
12709 dont_repeat ();
12710
12711 if (arg == 0)
12712 {
12713 int breaks_to_delete = 0;
12714
12715 /* Delete all breakpoints if no argument. Do not delete
12716 internal breakpoints, these have to be deleted with an
12717 explicit breakpoint number argument. */
12718 for (breakpoint &b : all_breakpoints ())
12719 if (user_breakpoint_p (&b))
12720 {
12721 breaks_to_delete = 1;
12722 break;
12723 }
12724
12725 /* Ask user only if there are some breakpoints to delete. */
12726 if (!from_tty
12727 || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12728 for (breakpoint &b : all_breakpoints_safe ())
12729 if (user_breakpoint_p (&b))
12730 delete_breakpoint (&b);
12731 }
12732 else
12733 map_breakpoint_numbers
12734 (arg, [&] (breakpoint *br)
12735 {
12736 iterate_over_related_breakpoints (br, delete_breakpoint);
12737 });
12738 }
12739
12740 /* Return true if all locations of B bound to PSPACE are pending. If
12741 PSPACE is NULL, all locations of all program spaces are
12742 considered. */
12743
12744 static bool
12745 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
12746 {
12747 for (bp_location &loc : b->locations ())
12748 if ((pspace == NULL
12749 || loc.pspace == pspace)
12750 && !loc.shlib_disabled
12751 && !loc.pspace->executing_startup)
12752 return false;
12753 return true;
12754 }
12755
12756 /* Subroutine of update_breakpoint_locations to simplify it.
12757 Return true if multiple fns in list LOCS have the same name.
12758 Null names are ignored. */
12759
12760 static bool
12761 ambiguous_names_p (const bp_location_range &locs)
12762 {
12763 htab_up htab (htab_create_alloc (13, htab_hash_string, htab_eq_string, NULL,
12764 xcalloc, xfree));
12765
12766 for (const bp_location &l : locs)
12767 {
12768 const char **slot;
12769 const char *name = l.function_name.get ();
12770
12771 /* Allow for some names to be NULL, ignore them. */
12772 if (name == NULL)
12773 continue;
12774
12775 slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
12776 INSERT);
12777 /* NOTE: We can assume slot != NULL here because xcalloc never
12778 returns NULL. */
12779 if (*slot != NULL)
12780 return true;
12781 *slot = name;
12782 }
12783
12784 return false;
12785 }
12786
12787 /* When symbols change, it probably means the sources changed as well,
12788 and it might mean the static tracepoint markers are no longer at
12789 the same address or line numbers they used to be at last we
12790 checked. Losing your static tracepoints whenever you rebuild is
12791 undesirable. This function tries to resync/rematch gdb static
12792 tracepoints with the markers on the target, for static tracepoints
12793 that have not been set by marker id. Static tracepoint that have
12794 been set by marker id are reset by marker id in breakpoint_re_set.
12795 The heuristic is:
12796
12797 1) For a tracepoint set at a specific address, look for a marker at
12798 the old PC. If one is found there, assume to be the same marker.
12799 If the name / string id of the marker found is different from the
12800 previous known name, assume that means the user renamed the marker
12801 in the sources, and output a warning.
12802
12803 2) For a tracepoint set at a given line number, look for a marker
12804 at the new address of the old line number. If one is found there,
12805 assume to be the same marker. If the name / string id of the
12806 marker found is different from the previous known name, assume that
12807 means the user renamed the marker in the sources, and output a
12808 warning.
12809
12810 3) If a marker is no longer found at the same address or line, it
12811 may mean the marker no longer exists. But it may also just mean
12812 the code changed a bit. Maybe the user added a few lines of code
12813 that made the marker move up or down (in line number terms). Ask
12814 the target for info about the marker with the string id as we knew
12815 it. If found, update line number and address in the matching
12816 static tracepoint. This will get confused if there's more than one
12817 marker with the same ID (possible in UST, although unadvised
12818 precisely because it confuses tools). */
12819
12820 static struct symtab_and_line
12821 update_static_tracepoint (tracepoint *tp, struct symtab_and_line sal)
12822 {
12823 struct static_tracepoint_marker marker;
12824 CORE_ADDR pc;
12825
12826 pc = sal.pc;
12827 if (sal.line)
12828 find_line_pc (sal.symtab, sal.line, &pc);
12829
12830 if (target_static_tracepoint_marker_at (pc, &marker))
12831 {
12832 if (tp->static_trace_marker_id != marker.str_id)
12833 warning (_("static tracepoint %d changed probed marker from %s to %s"),
12834 tp->number, tp->static_trace_marker_id.c_str (),
12835 marker.str_id.c_str ());
12836
12837 tp->static_trace_marker_id = std::move (marker.str_id);
12838
12839 return sal;
12840 }
12841
12842 /* Old marker wasn't found on target at lineno. Try looking it up
12843 by string ID. */
12844 if (!sal.explicit_pc
12845 && sal.line != 0
12846 && sal.symtab != NULL
12847 && !tp->static_trace_marker_id.empty ())
12848 {
12849 std::vector<static_tracepoint_marker> markers
12850 = target_static_tracepoint_markers_by_strid
12851 (tp->static_trace_marker_id.c_str ());
12852
12853 if (!markers.empty ())
12854 {
12855 struct symbol *sym;
12856 struct static_tracepoint_marker *tpmarker;
12857 struct ui_out *uiout = current_uiout;
12858
12859 tpmarker = &markers[0];
12860
12861 tp->static_trace_marker_id = std::move (tpmarker->str_id);
12862
12863 warning (_("marker for static tracepoint %d (%s) not "
12864 "found at previous line number"),
12865 tp->number, tp->static_trace_marker_id.c_str ());
12866
12867 symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
12868 sym = find_pc_sect_function (tpmarker->address, NULL);
12869 uiout->text ("Now in ");
12870 if (sym)
12871 {
12872 uiout->field_string ("func", sym->print_name (),
12873 function_name_style.style ());
12874 uiout->text (" at ");
12875 }
12876 uiout->field_string ("file",
12877 symtab_to_filename_for_display (sal2.symtab),
12878 file_name_style.style ());
12879 uiout->text (":");
12880
12881 if (uiout->is_mi_like_p ())
12882 {
12883 const char *fullname = symtab_to_fullname (sal2.symtab);
12884
12885 uiout->field_string ("fullname", fullname);
12886 }
12887
12888 uiout->field_signed ("line", sal2.line);
12889 uiout->text ("\n");
12890
12891 tp->first_loc ().line_number = sal2.line;
12892 tp->first_loc ().symtab = sym != NULL ? sal2.symtab : NULL;
12893
12894 std::unique_ptr<explicit_location_spec> els
12895 (new explicit_location_spec
12896 (symtab_to_filename_for_display (sal2.symtab)));
12897 els->line_offset.offset = tp->first_loc ().line_number;
12898 els->line_offset.sign = LINE_OFFSET_NONE;
12899
12900 tp->locspec = std::move (els);
12901
12902 /* Might be nice to check if function changed, and warn if
12903 so. */
12904 }
12905 }
12906 return sal;
12907 }
12908
12909 /* Returns true iff location lists A and B are sufficiently same that
12910 we don't need to report breakpoint as changed. */
12911
12912 static bool
12913 locations_are_equal (const bp_location_list &a, const bp_location_range &b)
12914 {
12915 auto a_iter = a.begin ();
12916 auto b_iter = b.begin ();
12917
12918 for (; a_iter != a.end () && b_iter != b.end (); ++a_iter, ++b_iter)
12919 {
12920 if (a_iter->address != b_iter->address)
12921 return false;
12922
12923 if (a_iter->shlib_disabled != b_iter->shlib_disabled)
12924 return false;
12925
12926 if (a_iter->enabled != b_iter->enabled)
12927 return false;
12928
12929 if (a_iter->disabled_by_cond != b_iter->disabled_by_cond)
12930 return false;
12931 }
12932
12933 return (a_iter == a.end ()) == (b_iter == b.end ());
12934 }
12935
12936 /* See breakpoint.h. */
12937
12938 bp_location_list
12939 breakpoint::steal_locations (program_space *pspace)
12940 {
12941 if (pspace == NULL)
12942 return std::move (m_locations);
12943
12944 bp_location_list ret;
12945
12946 for (auto it = m_locations.begin (); it != m_locations.end (); )
12947 {
12948 if (it->pspace == pspace)
12949 {
12950 bp_location &loc = *it;
12951 it = m_locations.erase (it);
12952 ret.push_back (loc);
12953 }
12954 else
12955 ++it;
12956 }
12957
12958 return ret;
12959 }
12960
12961 /* Create new breakpoint locations for B (a hardware or software
12962 breakpoint) based on SALS and SALS_END. If SALS_END.NELTS is not
12963 zero, then B is a ranged breakpoint. Only recreates locations for
12964 FILTER_PSPACE. Locations of other program spaces are left
12965 untouched. */
12966
12967 void
12968 update_breakpoint_locations (code_breakpoint *b,
12969 struct program_space *filter_pspace,
12970 gdb::array_view<const symtab_and_line> sals,
12971 gdb::array_view<const symtab_and_line> sals_end)
12972 {
12973 if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
12974 {
12975 /* Ranged breakpoints have only one start location and one end
12976 location. */
12977 b->enable_state = bp_disabled;
12978 gdb_printf (gdb_stderr,
12979 _("Could not reset ranged breakpoint %d: "
12980 "multiple locations found\n"),
12981 b->number);
12982 return;
12983 }
12984
12985 /* If there's no new locations, and all existing locations are
12986 pending, don't do anything. This optimizes the common case where
12987 all locations are in the same shared library, that was unloaded.
12988 We'd like to retain the location, so that when the library is
12989 loaded again, we don't loose the enabled/disabled status of the
12990 individual locations. */
12991 if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
12992 return;
12993
12994 bp_location_list existing_locations = b->steal_locations (filter_pspace);
12995
12996 for (const auto &sal : sals)
12997 {
12998 struct bp_location *new_loc;
12999
13000 switch_to_program_space_and_thread (sal.pspace);
13001
13002 new_loc = b->add_location (sal);
13003
13004 /* Reparse conditions, they might contain references to the
13005 old symtab. */
13006 if (b->cond_string != NULL)
13007 {
13008 const char *s;
13009
13010 s = b->cond_string.get ();
13011 try
13012 {
13013 new_loc->cond = parse_exp_1 (&s, sal.pc,
13014 block_for_pc (sal.pc),
13015 0);
13016 }
13017 catch (const gdb_exception_error &e)
13018 {
13019 new_loc->disabled_by_cond = true;
13020 }
13021 }
13022
13023 if (!sals_end.empty ())
13024 {
13025 CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13026
13027 new_loc->length = end - sals[0].pc + 1;
13028 }
13029 }
13030
13031 /* If possible, carry over 'disable' status from existing
13032 breakpoints. */
13033 {
13034 /* If there are multiple breakpoints with the same function name,
13035 e.g. for inline functions, comparing function names won't work.
13036 Instead compare pc addresses; this is just a heuristic as things
13037 may have moved, but in practice it gives the correct answer
13038 often enough until a better solution is found. */
13039 int have_ambiguous_names = ambiguous_names_p (b->locations ());
13040
13041 for (const bp_location &e : existing_locations)
13042 {
13043 if ((!e.enabled || e.disabled_by_cond) && e.function_name)
13044 {
13045 if (have_ambiguous_names)
13046 {
13047 for (bp_location &l : b->locations ())
13048 {
13049 /* Ignore software vs hardware location type at
13050 this point, because with "set breakpoint
13051 auto-hw", after a re-set, locations that were
13052 hardware can end up as software, or vice versa.
13053 As mentioned above, this is an heuristic and in
13054 practice should give the correct answer often
13055 enough. */
13056 if (breakpoint_locations_match (&e, &l, true))
13057 {
13058 l.enabled = e.enabled;
13059 l.disabled_by_cond = e.disabled_by_cond;
13060 break;
13061 }
13062 }
13063 }
13064 else
13065 {
13066 for (bp_location &l : b->locations ())
13067 if (l.function_name
13068 && strcmp (e.function_name.get (),
13069 l.function_name.get ()) == 0)
13070 {
13071 l.enabled = e.enabled;
13072 l.disabled_by_cond = e.disabled_by_cond;
13073 break;
13074 }
13075 }
13076 }
13077 }
13078 }
13079
13080 if (!locations_are_equal (existing_locations, b->locations ()))
13081 notify_breakpoint_modified (b);
13082 }
13083
13084 /* Find the SaL locations corresponding to the given LOCSPEC.
13085 On return, FOUND will be 1 if any SaL was found, zero otherwise. */
13086
13087 std::vector<symtab_and_line>
13088 code_breakpoint::location_spec_to_sals (location_spec *locspec,
13089 struct program_space *search_pspace,
13090 int *found)
13091 {
13092 struct gdb_exception exception;
13093
13094 std::vector<symtab_and_line> sals;
13095
13096 try
13097 {
13098 sals = decode_location_spec (locspec, search_pspace);
13099 }
13100 catch (gdb_exception_error &e)
13101 {
13102 int not_found_and_ok = false;
13103
13104 /* For pending breakpoints, it's expected that parsing will
13105 fail until the right shared library is loaded. User has
13106 already told to create pending breakpoints and don't need
13107 extra messages. If breakpoint is in bp_shlib_disabled
13108 state, then user already saw the message about that
13109 breakpoint being disabled, and don't want to see more
13110 errors. */
13111 if (e.error == NOT_FOUND_ERROR
13112 && (condition_not_parsed
13113 || (this->has_locations ()
13114 && search_pspace != NULL
13115 && this->first_loc ().pspace != search_pspace)
13116 || (this->has_locations () && this->first_loc ().shlib_disabled)
13117 || (this->has_locations ()
13118 && this->first_loc ().pspace->executing_startup)
13119 || enable_state == bp_disabled))
13120 not_found_and_ok = true;
13121
13122 if (!not_found_and_ok)
13123 {
13124 /* We surely don't want to warn about the same breakpoint
13125 10 times. One solution, implemented here, is disable
13126 the breakpoint on error. Another solution would be to
13127 have separate 'warning emitted' flag. Since this
13128 happens only when a binary has changed, I don't know
13129 which approach is better. */
13130 enable_state = bp_disabled;
13131 throw;
13132 }
13133
13134 exception = std::move (e);
13135 }
13136
13137 if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13138 {
13139 for (auto &sal : sals)
13140 resolve_sal_pc (&sal);
13141 if (condition_not_parsed && extra_string != NULL)
13142 {
13143 gdb::unique_xmalloc_ptr<char> local_cond, local_extra;
13144 int local_thread, local_task, local_inferior;
13145
13146 find_condition_and_thread_for_sals (sals, extra_string.get (),
13147 &local_cond, &local_thread,
13148 &local_inferior,
13149 &local_task, &local_extra);
13150 gdb_assert (cond_string == nullptr);
13151 if (local_cond != nullptr)
13152 cond_string = std::move (local_cond);
13153 thread = local_thread;
13154 task = local_task;
13155 if (local_extra != nullptr)
13156 extra_string = std::move (local_extra);
13157 condition_not_parsed = 0;
13158 }
13159
13160 if (type == bp_static_tracepoint)
13161 {
13162 tracepoint *t = gdb::checked_static_cast<tracepoint *> (this);
13163 sals[0] = update_static_tracepoint (t, sals[0]);
13164 }
13165
13166 *found = 1;
13167 }
13168 else
13169 *found = 0;
13170
13171 return sals;
13172 }
13173
13174 /* The default re_set method, for typical hardware or software
13175 breakpoints. Reevaluate the breakpoint and recreate its
13176 locations. */
13177
13178 void
13179 code_breakpoint::re_set_default ()
13180 {
13181 struct program_space *filter_pspace = current_program_space;
13182 std::vector<symtab_and_line> expanded, expanded_end;
13183
13184 int found;
13185 std::vector<symtab_and_line> sals = location_spec_to_sals (locspec.get (),
13186 filter_pspace,
13187 &found);
13188 if (found)
13189 expanded = std::move (sals);
13190
13191 if (locspec_range_end != nullptr)
13192 {
13193 std::vector<symtab_and_line> sals_end
13194 = location_spec_to_sals (locspec_range_end.get (),
13195 filter_pspace, &found);
13196 if (found)
13197 expanded_end = std::move (sals_end);
13198 }
13199
13200 update_breakpoint_locations (this, filter_pspace, expanded, expanded_end);
13201 }
13202
13203 /* Default method for creating SALs from an address string. It basically
13204 calls parse_breakpoint_sals. Return 1 for success, zero for failure. */
13205
13206 static void
13207 create_sals_from_location_spec_default (location_spec *locspec,
13208 struct linespec_result *canonical)
13209 {
13210 parse_breakpoint_sals (locspec, canonical);
13211 }
13212
13213 /* Reset a breakpoint. */
13214
13215 static void
13216 breakpoint_re_set_one (breakpoint *b)
13217 {
13218 input_radix = b->input_radix;
13219 set_language (b->language);
13220
13221 b->re_set ();
13222 }
13223
13224 /* Re-set breakpoint locations for the current program space.
13225 Locations bound to other program spaces are left untouched. */
13226
13227 void
13228 breakpoint_re_set (void)
13229 {
13230 {
13231 scoped_restore_current_language save_language;
13232 scoped_restore save_input_radix = make_scoped_restore (&input_radix);
13233 scoped_restore_current_pspace_and_thread restore_pspace_thread;
13234
13235 /* breakpoint_re_set_one sets the current_language to the language
13236 of the breakpoint it is resetting (see prepare_re_set_context)
13237 before re-evaluating the breakpoint's location. This change can
13238 unfortunately get undone by accident if the language_mode is set
13239 to auto, and we either switch frames, or more likely in this context,
13240 we select the current frame.
13241
13242 We prevent this by temporarily turning the language_mode to
13243 language_mode_manual. We restore it once all breakpoints
13244 have been reset. */
13245 scoped_restore save_language_mode = make_scoped_restore (&language_mode);
13246 language_mode = language_mode_manual;
13247
13248 /* Note: we must not try to insert locations until after all
13249 breakpoints have been re-set. Otherwise, e.g., when re-setting
13250 breakpoint 1, we'd insert the locations of breakpoint 2, which
13251 hadn't been re-set yet, and thus may have stale locations. */
13252
13253 for (breakpoint &b : all_breakpoints_safe ())
13254 {
13255 try
13256 {
13257 breakpoint_re_set_one (&b);
13258 }
13259 catch (const gdb_exception &ex)
13260 {
13261 exception_fprintf (gdb_stderr, ex,
13262 "Error in re-setting breakpoint %d: ",
13263 b.number);
13264 }
13265 }
13266
13267 jit_breakpoint_re_set ();
13268 }
13269
13270 create_overlay_event_breakpoint ();
13271 create_longjmp_master_breakpoint ();
13272 create_std_terminate_master_breakpoint ();
13273 create_exception_master_breakpoint ();
13274
13275 /* Now we can insert. */
13276 update_global_location_list (UGLL_MAY_INSERT);
13277 }
13278 \f
13279 /* Reset the thread number of this breakpoint:
13280
13281 - If the breakpoint is for all threads, leave it as-is.
13282 - Else, reset it to the current thread for inferior_ptid. */
13283 void
13284 breakpoint_re_set_thread (struct breakpoint *b)
13285 {
13286 if (b->thread != -1)
13287 {
13288 b->thread = inferior_thread ()->global_num;
13289
13290 /* We're being called after following a fork. The new fork is
13291 selected as current, and unless this was a vfork will have a
13292 different program space from the original thread. Reset that
13293 as well. */
13294 b->first_loc ().pspace = current_program_space;
13295 }
13296 }
13297
13298 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13299 If from_tty is nonzero, it prints a message to that effect,
13300 which ends with a period (no newline). */
13301
13302 void
13303 set_ignore_count (int bptnum, int count, int from_tty)
13304 {
13305 if (count < 0)
13306 count = 0;
13307
13308 for (breakpoint &b : all_breakpoints ())
13309 if (b.number == bptnum)
13310 {
13311 if (is_tracepoint (&b))
13312 {
13313 if (from_tty && count != 0)
13314 gdb_printf (_("Ignore count ignored for tracepoint %d."),
13315 bptnum);
13316 return;
13317 }
13318
13319 b.ignore_count = count;
13320 if (from_tty)
13321 {
13322 if (count == 0)
13323 gdb_printf (_("Will stop next time "
13324 "breakpoint %d is reached."),
13325 bptnum);
13326 else if (count == 1)
13327 gdb_printf (_("Will ignore next crossing of breakpoint %d."),
13328 bptnum);
13329 else
13330 gdb_printf (_("Will ignore next %d "
13331 "crossings of breakpoint %d."),
13332 count, bptnum);
13333 }
13334 notify_breakpoint_modified (&b);
13335 return;
13336 }
13337
13338 error (_("No breakpoint number %d."), bptnum);
13339 }
13340
13341 /* Command to set ignore-count of breakpoint N to COUNT. */
13342
13343 static void
13344 ignore_command (const char *args, int from_tty)
13345 {
13346 const char *p = args;
13347 int num;
13348
13349 if (p == 0)
13350 error_no_arg (_("a breakpoint number"));
13351
13352 num = get_number (&p);
13353 if (num == 0)
13354 error (_("bad breakpoint number: '%s'"), args);
13355 if (*p == 0)
13356 error (_("Second argument (specified ignore-count) is missing."));
13357
13358 set_ignore_count (num,
13359 longest_to_int (value_as_long (parse_and_eval (p))),
13360 from_tty);
13361 if (from_tty)
13362 gdb_printf ("\n");
13363 }
13364 \f
13365
13366 /* Call FUNCTION on each of the breakpoints with numbers in the range
13367 defined by BP_NUM_RANGE (an inclusive range). */
13368
13369 static void
13370 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
13371 gdb::function_view<void (breakpoint *)> function)
13372 {
13373 if (bp_num_range.first == 0)
13374 {
13375 warning (_("bad breakpoint number at or near '%d'"),
13376 bp_num_range.first);
13377 }
13378 else
13379 {
13380 for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
13381 {
13382 bool match = false;
13383
13384 for (breakpoint &b : all_breakpoints_safe ())
13385 if (b.number == i)
13386 {
13387 match = true;
13388 function (&b);
13389 break;
13390 }
13391 if (!match)
13392 gdb_printf (_("No breakpoint number %d.\n"), i);
13393 }
13394 }
13395 }
13396
13397 /* Call FUNCTION on each of the breakpoints whose numbers are given in
13398 ARGS. */
13399
13400 static void
13401 map_breakpoint_numbers (const char *args,
13402 gdb::function_view<void (breakpoint *)> function)
13403 {
13404 if (args == NULL || *args == '\0')
13405 error_no_arg (_("one or more breakpoint numbers"));
13406
13407 number_or_range_parser parser (args);
13408
13409 while (!parser.finished ())
13410 {
13411 int num = parser.get_number ();
13412 map_breakpoint_number_range (std::make_pair (num, num), function);
13413 }
13414 }
13415
13416 /* Return the breakpoint location structure corresponding to the
13417 BP_NUM and LOC_NUM values. */
13418
13419 static struct bp_location *
13420 find_location_by_number (int bp_num, int loc_num)
13421 {
13422 breakpoint *b = get_breakpoint (bp_num);
13423
13424 if (!b || b->number != bp_num)
13425 error (_("Bad breakpoint number '%d'"), bp_num);
13426
13427 if (loc_num == 0)
13428 error (_("Bad breakpoint location number '%d'"), loc_num);
13429
13430 int n = 0;
13431 for (bp_location &loc : b->locations ())
13432 if (++n == loc_num)
13433 return &loc;
13434
13435 error (_("Bad breakpoint location number '%d'"), loc_num);
13436 }
13437
13438 /* Modes of operation for extract_bp_num. */
13439 enum class extract_bp_kind
13440 {
13441 /* Extracting a breakpoint number. */
13442 bp,
13443
13444 /* Extracting a location number. */
13445 loc,
13446 };
13447
13448 /* Extract a breakpoint or location number (as determined by KIND)
13449 from the string starting at START. TRAILER is a character which
13450 can be found after the number. If you don't want a trailer, use
13451 '\0'. If END_OUT is not NULL, it is set to point after the parsed
13452 string. This always returns a positive integer. */
13453
13454 static int
13455 extract_bp_num (extract_bp_kind kind, const char *start,
13456 int trailer, const char **end_out = NULL)
13457 {
13458 const char *end = start;
13459 int num = get_number_trailer (&end, trailer);
13460 if (num < 0)
13461 error (kind == extract_bp_kind::bp
13462 ? _("Negative breakpoint number '%.*s'")
13463 : _("Negative breakpoint location number '%.*s'"),
13464 int (end - start), start);
13465 if (num == 0)
13466 error (kind == extract_bp_kind::bp
13467 ? _("Bad breakpoint number '%.*s'")
13468 : _("Bad breakpoint location number '%.*s'"),
13469 int (end - start), start);
13470
13471 if (end_out != NULL)
13472 *end_out = end;
13473 return num;
13474 }
13475
13476 /* Extract a breakpoint or location range (as determined by KIND) in
13477 the form NUM1-NUM2 stored at &ARG[arg_offset]. Returns a std::pair
13478 representing the (inclusive) range. The returned pair's elements
13479 are always positive integers. */
13480
13481 static std::pair<int, int>
13482 extract_bp_or_bp_range (extract_bp_kind kind,
13483 const std::string &arg,
13484 std::string::size_type arg_offset)
13485 {
13486 std::pair<int, int> range;
13487 const char *bp_loc = &arg[arg_offset];
13488 std::string::size_type dash = arg.find ('-', arg_offset);
13489 if (dash != std::string::npos)
13490 {
13491 /* bp_loc is a range (x-z). */
13492 if (arg.length () == dash + 1)
13493 error (kind == extract_bp_kind::bp
13494 ? _("Bad breakpoint number at or near: '%s'")
13495 : _("Bad breakpoint location number at or near: '%s'"),
13496 bp_loc);
13497
13498 const char *end;
13499 const char *start_first = bp_loc;
13500 const char *start_second = &arg[dash + 1];
13501 range.first = extract_bp_num (kind, start_first, '-');
13502 range.second = extract_bp_num (kind, start_second, '\0', &end);
13503
13504 if (range.first > range.second)
13505 error (kind == extract_bp_kind::bp
13506 ? _("Inverted breakpoint range at '%.*s'")
13507 : _("Inverted breakpoint location range at '%.*s'"),
13508 int (end - start_first), start_first);
13509 }
13510 else
13511 {
13512 /* bp_loc is a single value. */
13513 range.first = extract_bp_num (kind, bp_loc, '\0');
13514 range.second = range.first;
13515 }
13516 return range;
13517 }
13518
13519 /* Extract the breakpoint/location range specified by ARG. Returns
13520 the breakpoint range in BP_NUM_RANGE, and the location range in
13521 BP_LOC_RANGE.
13522
13523 ARG may be in any of the following forms:
13524
13525 x where 'x' is a breakpoint number.
13526 x-y where 'x' and 'y' specify a breakpoint numbers range.
13527 x.y where 'x' is a breakpoint number and 'y' a location number.
13528 x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
13529 location number range.
13530 */
13531
13532 static void
13533 extract_bp_number_and_location (const std::string &arg,
13534 std::pair<int, int> &bp_num_range,
13535 std::pair<int, int> &bp_loc_range)
13536 {
13537 std::string::size_type dot = arg.find ('.');
13538
13539 if (dot != std::string::npos)
13540 {
13541 /* Handle 'x.y' and 'x.y-z' cases. */
13542
13543 if (arg.length () == dot + 1 || dot == 0)
13544 error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
13545
13546 bp_num_range.first
13547 = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
13548 bp_num_range.second = bp_num_range.first;
13549
13550 bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
13551 arg, dot + 1);
13552 }
13553 else
13554 {
13555 /* Handle x and x-y cases. */
13556
13557 bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
13558 bp_loc_range.first = 0;
13559 bp_loc_range.second = 0;
13560 }
13561 }
13562
13563 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM. ENABLE
13564 specifies whether to enable or disable. */
13565
13566 static void
13567 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
13568 {
13569 struct bp_location *loc = find_location_by_number (bp_num, loc_num);
13570 if (loc != NULL)
13571 {
13572 if (loc->disabled_by_cond && enable)
13573 error (_("Breakpoint %d's condition is invalid at location %d, "
13574 "cannot enable."), bp_num, loc_num);
13575
13576 if (loc->enabled != enable)
13577 {
13578 loc->enabled = enable;
13579 mark_breakpoint_location_modified (loc);
13580 }
13581 if (target_supports_enable_disable_tracepoint ()
13582 && current_trace_status ()->running && loc->owner
13583 && is_tracepoint (loc->owner))
13584 target_disable_tracepoint (loc);
13585 }
13586 update_global_location_list (UGLL_DONT_INSERT);
13587
13588 notify_breakpoint_modified (loc->owner);
13589 }
13590
13591 /* Calculates LOC_NUM for LOC by traversing the bp_location chain of LOC's
13592 owner. 1-based indexing. -1 signals NOT FOUND. */
13593
13594 static int
13595 find_loc_num_by_location (const bp_location *loc)
13596 {
13597 if (loc != nullptr && loc->owner != nullptr)
13598 {
13599 /* Locations use 1-based indexing. */
13600 int loc_num = 1;
13601 for (bp_location &it : loc->owner->locations ())
13602 {
13603 if (&it == loc)
13604 return loc_num;
13605 loc_num++;
13606 }
13607 }
13608 return -1;
13609 }
13610
13611 /* Enable or disable a breakpoint location LOC. ENABLE
13612 specifies whether to enable or disable. */
13613
13614 void
13615 enable_disable_bp_location (bp_location *loc, bool enable)
13616 {
13617 if (loc == nullptr)
13618 error (_("Breakpoint location is invalid."));
13619
13620 if (loc->owner == nullptr)
13621 error (_("Breakpoint location does not have an owner breakpoint."));
13622
13623 if (loc->disabled_by_cond && enable)
13624 {
13625 int loc_num = find_loc_num_by_location (loc);
13626 if (loc_num == -1)
13627 error (_("Breakpoint location LOC_NUM could not be found."));
13628 else
13629 error (_("Breakpoint %d's condition is invalid at location %d, "
13630 "cannot enable."), loc->owner->number, loc_num);
13631 }
13632
13633 if (loc->enabled != enable)
13634 {
13635 loc->enabled = enable;
13636 mark_breakpoint_location_modified (loc);
13637 }
13638
13639 if (target_supports_enable_disable_tracepoint ()
13640 && current_trace_status ()->running && loc->owner
13641 && is_tracepoint (loc->owner))
13642 target_disable_tracepoint (loc);
13643
13644 update_global_location_list (UGLL_DONT_INSERT);
13645 notify_breakpoint_modified (loc->owner);
13646 }
13647
13648 /* Enable or disable a range of breakpoint locations. BP_NUM is the
13649 number of the breakpoint, and BP_LOC_RANGE specifies the
13650 (inclusive) range of location numbers of that breakpoint to
13651 enable/disable. ENABLE specifies whether to enable or disable the
13652 location. */
13653
13654 static void
13655 enable_disable_breakpoint_location_range (int bp_num,
13656 std::pair<int, int> &bp_loc_range,
13657 bool enable)
13658 {
13659 for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
13660 enable_disable_bp_num_loc (bp_num, i, enable);
13661 }
13662
13663 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13664 If from_tty is nonzero, it prints a message to that effect,
13665 which ends with a period (no newline). */
13666
13667 void
13668 disable_breakpoint (struct breakpoint *bpt)
13669 {
13670 /* Never disable a watchpoint scope breakpoint; we want to
13671 hit them when we leave scope so we can delete both the
13672 watchpoint and its scope breakpoint at that time. */
13673 if (bpt->type == bp_watchpoint_scope)
13674 return;
13675
13676 bpt->enable_state = bp_disabled;
13677
13678 /* Mark breakpoint locations modified. */
13679 mark_breakpoint_modified (bpt);
13680
13681 if (target_supports_enable_disable_tracepoint ()
13682 && current_trace_status ()->running && is_tracepoint (bpt))
13683 {
13684 for (bp_location &location : bpt->locations ())
13685 target_disable_tracepoint (&location);
13686 }
13687
13688 update_global_location_list (UGLL_DONT_INSERT);
13689
13690 notify_breakpoint_modified (bpt);
13691 }
13692
13693 /* Enable or disable the breakpoint(s) or breakpoint location(s)
13694 specified in ARGS. ARGS may be in any of the formats handled by
13695 extract_bp_number_and_location. ENABLE specifies whether to enable
13696 or disable the breakpoints/locations. */
13697
13698 static void
13699 enable_disable_command (const char *args, int from_tty, bool enable)
13700 {
13701 if (args == 0)
13702 {
13703 for (breakpoint &bpt : all_breakpoints ())
13704 if (user_breakpoint_p (&bpt))
13705 {
13706 if (enable)
13707 enable_breakpoint (&bpt);
13708 else
13709 disable_breakpoint (&bpt);
13710 }
13711 }
13712 else
13713 {
13714 std::string num = extract_arg (&args);
13715
13716 while (!num.empty ())
13717 {
13718 std::pair<int, int> bp_num_range, bp_loc_range;
13719
13720 extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
13721
13722 if (bp_loc_range.first == bp_loc_range.second
13723 && (bp_loc_range.first == 0
13724 || (bp_loc_range.first == 1
13725 && bp_num_range.first == bp_num_range.second
13726 && !has_multiple_locations (bp_num_range.first))))
13727 {
13728 /* Handle breakpoint ids with formats 'x' or 'x-z'
13729 or 'y.1' where y has only one code location. */
13730 map_breakpoint_number_range (bp_num_range,
13731 enable
13732 ? enable_breakpoint
13733 : disable_breakpoint);
13734 }
13735 else
13736 {
13737 /* Handle breakpoint ids with formats 'x.y' or
13738 'x.y-z'. */
13739 enable_disable_breakpoint_location_range
13740 (bp_num_range.first, bp_loc_range, enable);
13741 }
13742 num = extract_arg (&args);
13743 }
13744 }
13745 }
13746
13747 /* The disable command disables the specified breakpoints/locations
13748 (or all defined breakpoints) so they're no longer effective in
13749 stopping the inferior. ARGS may be in any of the forms defined in
13750 extract_bp_number_and_location. */
13751
13752 static void
13753 disable_command (const char *args, int from_tty)
13754 {
13755 enable_disable_command (args, from_tty, false);
13756 }
13757
13758 static void
13759 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13760 int count)
13761 {
13762 int target_resources_ok;
13763
13764 if (bpt->type == bp_hardware_breakpoint)
13765 {
13766 int i;
13767 i = hw_breakpoint_used_count ();
13768 target_resources_ok =
13769 target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
13770 i + 1, 0);
13771 if (target_resources_ok == 0)
13772 error (_("No hardware breakpoint support in the target."));
13773 else if (target_resources_ok < 0)
13774 error (_("Hardware breakpoints used exceeds limit."));
13775 }
13776
13777 if (is_watchpoint (bpt))
13778 {
13779 /* Initialize it just to avoid a GCC false warning. */
13780 enum enable_state orig_enable_state = bp_disabled;
13781
13782 try
13783 {
13784 watchpoint *w = gdb::checked_static_cast<watchpoint *> (bpt);
13785
13786 orig_enable_state = bpt->enable_state;
13787 bpt->enable_state = bp_enabled;
13788 update_watchpoint (w, true /* reparse */);
13789 }
13790 catch (const gdb_exception_error &e)
13791 {
13792 bpt->enable_state = orig_enable_state;
13793 exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13794 bpt->number);
13795 return;
13796 }
13797 }
13798
13799 bpt->enable_state = bp_enabled;
13800
13801 /* Mark breakpoint locations modified. */
13802 mark_breakpoint_modified (bpt);
13803
13804 if (target_supports_enable_disable_tracepoint ()
13805 && current_trace_status ()->running && is_tracepoint (bpt))
13806 {
13807 for (bp_location &location : bpt->locations ())
13808 target_enable_tracepoint (&location);
13809 }
13810
13811 bpt->disposition = disposition;
13812 bpt->enable_count = count;
13813 update_global_location_list (UGLL_MAY_INSERT);
13814
13815 notify_breakpoint_modified (bpt);
13816 }
13817
13818
13819 void
13820 enable_breakpoint (struct breakpoint *bpt)
13821 {
13822 enable_breakpoint_disp (bpt, bpt->disposition, 0);
13823 }
13824
13825 /* The enable command enables the specified breakpoints/locations (or
13826 all defined breakpoints) so they once again become (or continue to
13827 be) effective in stopping the inferior. ARGS may be in any of the
13828 forms defined in extract_bp_number_and_location. */
13829
13830 static void
13831 enable_command (const char *args, int from_tty)
13832 {
13833 enable_disable_command (args, from_tty, true);
13834 }
13835
13836 static void
13837 enable_once_command (const char *args, int from_tty)
13838 {
13839 map_breakpoint_numbers
13840 (args, [&] (breakpoint *b)
13841 {
13842 iterate_over_related_breakpoints
13843 (b, [&] (breakpoint *bpt)
13844 {
13845 enable_breakpoint_disp (bpt, disp_disable, 1);
13846 });
13847 });
13848 }
13849
13850 static void
13851 enable_count_command (const char *args, int from_tty)
13852 {
13853 int count;
13854
13855 if (args == NULL)
13856 error_no_arg (_("hit count"));
13857
13858 count = get_number (&args);
13859
13860 map_breakpoint_numbers
13861 (args, [&] (breakpoint *b)
13862 {
13863 iterate_over_related_breakpoints
13864 (b, [&] (breakpoint *bpt)
13865 {
13866 enable_breakpoint_disp (bpt, disp_disable, count);
13867 });
13868 });
13869 }
13870
13871 static void
13872 enable_delete_command (const char *args, int from_tty)
13873 {
13874 map_breakpoint_numbers
13875 (args, [&] (breakpoint *b)
13876 {
13877 iterate_over_related_breakpoints
13878 (b, [&] (breakpoint *bpt)
13879 {
13880 enable_breakpoint_disp (bpt, disp_del, 1);
13881 });
13882 });
13883 }
13884 \f
13885 /* Invalidate last known value of any hardware watchpoint if
13886 the memory which that value represents has been written to by
13887 GDB itself. */
13888
13889 static void
13890 invalidate_bp_value_on_memory_change (struct inferior *inferior,
13891 CORE_ADDR addr, ssize_t len,
13892 const bfd_byte *data)
13893 {
13894 for (breakpoint &bp : all_breakpoints ())
13895 if (bp.enable_state == bp_enabled
13896 && bp.type == bp_hardware_watchpoint)
13897 {
13898 watchpoint &wp = gdb::checked_static_cast<watchpoint &> (bp);
13899
13900 if (wp.val_valid && wp.val != nullptr)
13901 {
13902 for (bp_location &loc : bp.locations ())
13903 if (loc.loc_type == bp_loc_hardware_watchpoint
13904 && loc.address + loc.length > addr
13905 && addr + len > loc.address)
13906 {
13907 wp.val = NULL;
13908 wp.val_valid = false;
13909 }
13910 }
13911 }
13912 }
13913
13914 /* Create and insert a breakpoint for software single step. */
13915
13916 void
13917 insert_single_step_breakpoint (struct gdbarch *gdbarch,
13918 const address_space *aspace,
13919 CORE_ADDR next_pc)
13920 {
13921 struct thread_info *tp = inferior_thread ();
13922 struct symtab_and_line sal;
13923 CORE_ADDR pc = next_pc;
13924
13925 if (tp->control.single_step_breakpoints == NULL)
13926 {
13927 std::unique_ptr<breakpoint> b
13928 (new momentary_breakpoint (gdbarch, bp_single_step,
13929 current_program_space,
13930 null_frame_id,
13931 tp->global_num));
13932
13933 tp->control.single_step_breakpoints
13934 = add_to_breakpoint_chain (std::move (b));
13935 }
13936
13937 sal = find_pc_line (pc, 0);
13938 sal.pc = pc;
13939 sal.section = find_pc_overlay (pc);
13940 sal.explicit_pc = 1;
13941
13942 auto *ss_bp
13943 = (gdb::checked_static_cast<momentary_breakpoint *>
13944 (tp->control.single_step_breakpoints));
13945 ss_bp->add_location (sal);
13946
13947 update_global_location_list (UGLL_INSERT);
13948 }
13949
13950 /* Insert single step breakpoints according to the current state. */
13951
13952 int
13953 insert_single_step_breakpoints (struct gdbarch *gdbarch)
13954 {
13955 regcache *regcache = get_thread_regcache (inferior_thread ());
13956 std::vector<CORE_ADDR> next_pcs;
13957
13958 next_pcs = gdbarch_software_single_step (gdbarch, regcache);
13959
13960 if (!next_pcs.empty ())
13961 {
13962 frame_info_ptr frame = get_current_frame ();
13963 const address_space *aspace = get_frame_address_space (frame);
13964
13965 for (CORE_ADDR pc : next_pcs)
13966 insert_single_step_breakpoint (gdbarch, aspace, pc);
13967
13968 return 1;
13969 }
13970 else
13971 return 0;
13972 }
13973
13974 /* See breakpoint.h. */
13975
13976 int
13977 breakpoint_has_location_inserted_here (struct breakpoint *bp,
13978 const address_space *aspace,
13979 CORE_ADDR pc)
13980 {
13981 for (bp_location &loc : bp->locations ())
13982 if (loc.inserted
13983 && breakpoint_location_address_match (&loc, aspace, pc))
13984 return 1;
13985
13986 return 0;
13987 }
13988
13989 /* Check whether a software single-step breakpoint is inserted at
13990 PC. */
13991
13992 int
13993 single_step_breakpoint_inserted_here_p (const address_space *aspace,
13994 CORE_ADDR pc)
13995 {
13996 for (breakpoint &bpt : all_breakpoints ())
13997 {
13998 if (bpt.type == bp_single_step
13999 && breakpoint_has_location_inserted_here (&bpt, aspace, pc))
14000 return 1;
14001 }
14002 return 0;
14003 }
14004
14005 /* Tracepoint-specific operations. */
14006
14007 /* Set tracepoint count to NUM. */
14008 static void
14009 set_tracepoint_count (int num)
14010 {
14011 tracepoint_count = num;
14012 set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14013 }
14014
14015 static void
14016 trace_command (const char *arg, int from_tty)
14017 {
14018 location_spec_up locspec = string_to_location_spec (&arg,
14019 current_language);
14020 const struct breakpoint_ops *ops = breakpoint_ops_for_location_spec
14021 (locspec.get (), true /* is_tracepoint */);
14022
14023 create_breakpoint (get_current_arch (),
14024 locspec.get (),
14025 NULL, -1, -1, arg, false, 1 /* parse arg */,
14026 0 /* tempflag */,
14027 bp_tracepoint /* type_wanted */,
14028 0 /* Ignore count */,
14029 pending_break_support,
14030 ops,
14031 from_tty,
14032 1 /* enabled */,
14033 0 /* internal */, 0);
14034 }
14035
14036 static void
14037 ftrace_command (const char *arg, int from_tty)
14038 {
14039 location_spec_up locspec = string_to_location_spec (&arg,
14040 current_language);
14041 create_breakpoint (get_current_arch (),
14042 locspec.get (),
14043 NULL, -1, -1, arg, false, 1 /* parse arg */,
14044 0 /* tempflag */,
14045 bp_fast_tracepoint /* type_wanted */,
14046 0 /* Ignore count */,
14047 pending_break_support,
14048 &code_breakpoint_ops,
14049 from_tty,
14050 1 /* enabled */,
14051 0 /* internal */, 0);
14052 }
14053
14054 /* strace command implementation. Creates a static tracepoint. */
14055
14056 static void
14057 strace_command (const char *arg, int from_tty)
14058 {
14059 const struct breakpoint_ops *ops;
14060 location_spec_up locspec;
14061 enum bptype type;
14062
14063 /* Decide if we are dealing with a static tracepoint marker (`-m'),
14064 or with a normal static tracepoint. */
14065 if (arg && startswith (arg, "-m") && isspace (arg[2]))
14066 {
14067 ops = &strace_marker_breakpoint_ops;
14068 locspec = new_linespec_location_spec (&arg,
14069 symbol_name_match_type::FULL);
14070 type = bp_static_marker_tracepoint;
14071 }
14072 else
14073 {
14074 ops = &code_breakpoint_ops;
14075 locspec = string_to_location_spec (&arg, current_language);
14076 type = bp_static_tracepoint;
14077 }
14078
14079 create_breakpoint (get_current_arch (),
14080 locspec.get (),
14081 NULL, -1, -1, arg, false, 1 /* parse arg */,
14082 0 /* tempflag */,
14083 type /* type_wanted */,
14084 0 /* Ignore count */,
14085 pending_break_support,
14086 ops,
14087 from_tty,
14088 1 /* enabled */,
14089 0 /* internal */, 0);
14090 }
14091
14092 /* Set up a fake reader function that gets command lines from a linked
14093 list that was acquired during tracepoint uploading. */
14094
14095 static struct uploaded_tp *this_utp;
14096 static int next_cmd;
14097
14098 static const char *
14099 read_uploaded_action (std::string &buffer)
14100 {
14101 char *rslt = nullptr;
14102
14103 if (next_cmd < this_utp->cmd_strings.size ())
14104 {
14105 rslt = this_utp->cmd_strings[next_cmd].get ();
14106 next_cmd++;
14107 }
14108
14109 return rslt;
14110 }
14111
14112 /* Given information about a tracepoint as recorded on a target (which
14113 can be either a live system or a trace file), attempt to create an
14114 equivalent GDB tracepoint. This is not a reliable process, since
14115 the target does not necessarily have all the information used when
14116 the tracepoint was originally defined. */
14117
14118 struct tracepoint *
14119 create_tracepoint_from_upload (struct uploaded_tp *utp)
14120 {
14121 const char *addr_str;
14122 char small_buf[100];
14123 struct tracepoint *tp;
14124
14125 if (utp->at_string)
14126 addr_str = utp->at_string.get ();
14127 else
14128 {
14129 /* In the absence of a source location, fall back to raw
14130 address. Since there is no way to confirm that the address
14131 means the same thing as when the trace was started, warn the
14132 user. */
14133 warning (_("Uploaded tracepoint %d has no "
14134 "source location, using raw address"),
14135 utp->number);
14136 xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14137 addr_str = small_buf;
14138 }
14139
14140 /* There's not much we can do with a sequence of bytecodes. */
14141 if (utp->cond && !utp->cond_string)
14142 warning (_("Uploaded tracepoint %d condition "
14143 "has no source form, ignoring it"),
14144 utp->number);
14145
14146 location_spec_up locspec = string_to_location_spec (&addr_str,
14147 current_language);
14148 if (!create_breakpoint (get_current_arch (),
14149 locspec.get (),
14150 utp->cond_string.get (), -1, -1, addr_str,
14151 false /* force_condition */,
14152 0 /* parse cond/thread */,
14153 0 /* tempflag */,
14154 utp->type /* type_wanted */,
14155 0 /* Ignore count */,
14156 pending_break_support,
14157 &code_breakpoint_ops,
14158 0 /* from_tty */,
14159 utp->enabled /* enabled */,
14160 0 /* internal */,
14161 CREATE_BREAKPOINT_FLAGS_INSERTED))
14162 return NULL;
14163
14164 /* Get the tracepoint we just created. */
14165 tp = get_tracepoint (tracepoint_count);
14166 gdb_assert (tp != NULL);
14167
14168 if (utp->pass > 0)
14169 {
14170 xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14171 tp->number);
14172
14173 trace_pass_command (small_buf, 0);
14174 }
14175
14176 /* If we have uploaded versions of the original commands, set up a
14177 special-purpose "reader" function and call the usual command line
14178 reader, then pass the result to the breakpoint command-setting
14179 function. */
14180 if (!utp->cmd_strings.empty ())
14181 {
14182 counted_command_line cmd_list;
14183
14184 this_utp = utp;
14185 next_cmd = 0;
14186
14187 cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14188
14189 breakpoint_set_commands (tp, std::move (cmd_list));
14190 }
14191 else if (!utp->actions.empty ()
14192 || !utp->step_actions.empty ())
14193 warning (_("Uploaded tracepoint %d actions "
14194 "have no source form, ignoring them"),
14195 utp->number);
14196
14197 /* Copy any status information that might be available. */
14198 tp->hit_count = utp->hit_count;
14199 tp->traceframe_usage = utp->traceframe_usage;
14200
14201 return tp;
14202 }
14203
14204 /* Print information on tracepoint number TPNUM_EXP, or all if
14205 omitted. */
14206
14207 static void
14208 info_tracepoints_command (const char *args, int from_tty)
14209 {
14210 struct ui_out *uiout = current_uiout;
14211 int num_printed;
14212
14213 num_printed = breakpoint_1 (args, false, is_tracepoint);
14214
14215 if (num_printed == 0)
14216 {
14217 if (args == NULL || *args == '\0')
14218 uiout->message ("No tracepoints.\n");
14219 else
14220 uiout->message ("No tracepoint matching '%s'.\n", args);
14221 }
14222
14223 default_collect_info ();
14224 }
14225
14226 /* The 'enable trace' command enables tracepoints.
14227 Not supported by all targets. */
14228 static void
14229 enable_trace_command (const char *args, int from_tty)
14230 {
14231 enable_command (args, from_tty);
14232 }
14233
14234 /* The 'disable trace' command disables tracepoints.
14235 Not supported by all targets. */
14236 static void
14237 disable_trace_command (const char *args, int from_tty)
14238 {
14239 disable_command (args, from_tty);
14240 }
14241
14242 /* Remove a tracepoint (or all if no argument). */
14243 static void
14244 delete_trace_command (const char *arg, int from_tty)
14245 {
14246 dont_repeat ();
14247
14248 if (arg == 0)
14249 {
14250 int breaks_to_delete = 0;
14251
14252 /* Delete all breakpoints if no argument.
14253 Do not delete internal or call-dummy breakpoints, these
14254 have to be deleted with an explicit breakpoint number
14255 argument. */
14256 for (breakpoint &tp : all_tracepoints ())
14257 if (is_tracepoint (&tp) && user_breakpoint_p (&tp))
14258 {
14259 breaks_to_delete = 1;
14260 break;
14261 }
14262
14263 /* Ask user only if there are some breakpoints to delete. */
14264 if (!from_tty
14265 || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14266 {
14267 for (breakpoint &b : all_breakpoints_safe ())
14268 if (is_tracepoint (&b) && user_breakpoint_p (&b))
14269 delete_breakpoint (&b);
14270 }
14271 }
14272 else
14273 map_breakpoint_numbers
14274 (arg, [&] (breakpoint *br)
14275 {
14276 iterate_over_related_breakpoints (br, delete_breakpoint);
14277 });
14278 }
14279
14280 /* Helper function for trace_pass_command. */
14281
14282 static void
14283 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14284 {
14285 tp->pass_count = count;
14286 notify_breakpoint_modified (tp);
14287 if (from_tty)
14288 gdb_printf (_("Setting tracepoint %d's passcount to %d\n"),
14289 tp->number, count);
14290 }
14291
14292 /* Set passcount for tracepoint.
14293
14294 First command argument is passcount, second is tracepoint number.
14295 If tracepoint number omitted, apply to most recently defined.
14296 Also accepts special argument "all". */
14297
14298 static void
14299 trace_pass_command (const char *args, int from_tty)
14300 {
14301 ULONGEST count;
14302
14303 if (args == 0 || *args == 0)
14304 error (_("passcount command requires an "
14305 "argument (count + optional TP num)"));
14306
14307 count = strtoulst (args, &args, 10); /* Count comes first, then TP num. */
14308
14309 args = skip_spaces (args);
14310 if (*args && strncasecmp (args, "all", 3) == 0)
14311 {
14312 args += 3; /* Skip special argument "all". */
14313 if (*args)
14314 error (_("Junk at end of arguments."));
14315
14316 for (breakpoint &b : all_tracepoints ())
14317 {
14318 tracepoint &t1 = gdb::checked_static_cast<tracepoint &> (b);
14319 trace_pass_set_count (&t1, count, from_tty);
14320 }
14321 }
14322 else if (*args == '\0')
14323 {
14324 tracepoint *t1 = get_tracepoint_by_number (&args, NULL);
14325 if (t1)
14326 trace_pass_set_count (t1, count, from_tty);
14327 }
14328 else
14329 {
14330 number_or_range_parser parser (args);
14331 while (!parser.finished ())
14332 {
14333 tracepoint *t1 = get_tracepoint_by_number (&args, &parser);
14334 if (t1)
14335 trace_pass_set_count (t1, count, from_tty);
14336 }
14337 }
14338 }
14339
14340 struct tracepoint *
14341 get_tracepoint (int num)
14342 {
14343 for (breakpoint &t : all_tracepoints ())
14344 if (t.number == num)
14345 return gdb::checked_static_cast<tracepoint *> (&t);
14346
14347 return NULL;
14348 }
14349
14350 /* Find the tracepoint with the given target-side number (which may be
14351 different from the tracepoint number after disconnecting and
14352 reconnecting). */
14353
14354 struct tracepoint *
14355 get_tracepoint_by_number_on_target (int num)
14356 {
14357 for (breakpoint &b : all_tracepoints ())
14358 {
14359 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
14360
14361 if (t.number_on_target == num)
14362 return &t;
14363 }
14364
14365 return NULL;
14366 }
14367
14368 /* Utility: parse a tracepoint number and look it up in the list.
14369 If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14370 If the argument is missing, the most recent tracepoint
14371 (tracepoint_count) is returned. */
14372
14373 struct tracepoint *
14374 get_tracepoint_by_number (const char **arg,
14375 number_or_range_parser *parser)
14376 {
14377 int tpnum;
14378 const char *instring = arg == NULL ? NULL : *arg;
14379
14380 if (parser != NULL)
14381 {
14382 gdb_assert (!parser->finished ());
14383 tpnum = parser->get_number ();
14384 }
14385 else if (arg == NULL || *arg == NULL || ! **arg)
14386 tpnum = tracepoint_count;
14387 else
14388 tpnum = get_number (arg);
14389
14390 if (tpnum <= 0)
14391 {
14392 if (instring && *instring)
14393 gdb_printf (_("bad tracepoint number at or near '%s'\n"),
14394 instring);
14395 else
14396 gdb_printf (_("No previous tracepoint\n"));
14397 return NULL;
14398 }
14399
14400 for (breakpoint &t : all_tracepoints ())
14401 if (t.number == tpnum)
14402 return gdb::checked_static_cast<tracepoint *> (&t);
14403
14404 gdb_printf ("No tracepoint number %d.\n", tpnum);
14405 return NULL;
14406 }
14407
14408 void
14409 breakpoint::print_recreate_thread (struct ui_file *fp) const
14410 {
14411 if (thread != -1)
14412 {
14413 struct thread_info *thr = find_thread_global_id (thread);
14414 gdb_printf (fp, " thread %s", print_full_thread_id (thr));
14415 }
14416
14417 if (task != -1)
14418 gdb_printf (fp, " task %d", task);
14419
14420 gdb_printf (fp, "\n");
14421 }
14422
14423 /* Save information on user settable breakpoints (watchpoints, etc) to
14424 a new script file named FILENAME. If FILTER is non-NULL, call it
14425 on each breakpoint and only include the ones for which it returns
14426 true. */
14427
14428 static void
14429 save_breakpoints (const char *filename, int from_tty,
14430 bool (*filter) (const struct breakpoint *))
14431 {
14432 bool any = false;
14433 int extra_trace_bits = 0;
14434
14435 if (filename == 0 || *filename == 0)
14436 error (_("Argument required (file name in which to save)"));
14437
14438 /* See if we have anything to save. */
14439 for (breakpoint &tp : all_breakpoints ())
14440 {
14441 /* Skip internal and momentary breakpoints. */
14442 if (!user_breakpoint_p (&tp))
14443 continue;
14444
14445 /* If we have a filter, only save the breakpoints it accepts. */
14446 if (filter && !filter (&tp))
14447 continue;
14448
14449 any = true;
14450
14451 if (is_tracepoint (&tp))
14452 {
14453 extra_trace_bits = 1;
14454
14455 /* We can stop searching. */
14456 break;
14457 }
14458 }
14459
14460 if (!any)
14461 {
14462 warning (_("Nothing to save."));
14463 return;
14464 }
14465
14466 gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
14467
14468 stdio_file fp;
14469
14470 if (!fp.open (expanded_filename.get (), "w"))
14471 error (_("Unable to open file '%s' for saving (%s)"),
14472 expanded_filename.get (), safe_strerror (errno));
14473
14474 if (extra_trace_bits)
14475 save_trace_state_variables (&fp);
14476
14477 for (breakpoint &tp : all_breakpoints ())
14478 {
14479 /* Skip internal and momentary breakpoints. */
14480 if (!user_breakpoint_p (&tp))
14481 continue;
14482
14483 /* If we have a filter, only save the breakpoints it accepts. */
14484 if (filter && !filter (&tp))
14485 continue;
14486
14487 tp.print_recreate (&fp);
14488
14489 /* Note, we can't rely on tp->number for anything, as we can't
14490 assume the recreated breakpoint numbers will match. Use $bpnum
14491 instead. */
14492
14493 if (tp.cond_string)
14494 fp.printf (" condition $bpnum %s\n", tp.cond_string.get ());
14495
14496 if (tp.ignore_count)
14497 fp.printf (" ignore $bpnum %d\n", tp.ignore_count);
14498
14499 if (tp.type != bp_dprintf && tp.commands)
14500 {
14501 fp.puts (" commands\n");
14502
14503 ui_out_redirect_pop redir (current_uiout, &fp);
14504 print_command_lines (current_uiout, tp.commands.get (), 2);
14505
14506 fp.puts (" end\n");
14507 }
14508
14509 if (tp.enable_state == bp_disabled)
14510 fp.puts ("disable $bpnum\n");
14511
14512 /* If this is a multi-location breakpoint, check if the locations
14513 should be individually disabled. Watchpoint locations are
14514 special, and not user visible. */
14515 if (!is_watchpoint (&tp) && tp.has_multiple_locations ())
14516 {
14517 int n = 1;
14518
14519 for (bp_location &loc : tp.locations ())
14520 {
14521 if (!loc.enabled)
14522 fp.printf ("disable $bpnum.%d\n", n);
14523
14524 n++;
14525 }
14526 }
14527 }
14528
14529 if (extra_trace_bits && !default_collect.empty ())
14530 fp.printf ("set default-collect %s\n", default_collect.c_str ());
14531
14532 if (from_tty)
14533 gdb_printf (_("Saved to file '%s'.\n"), expanded_filename.get ());
14534 }
14535
14536 /* The `save breakpoints' command. */
14537
14538 static void
14539 save_breakpoints_command (const char *args, int from_tty)
14540 {
14541 save_breakpoints (args, from_tty, NULL);
14542 }
14543
14544 /* The `save tracepoints' command. */
14545
14546 static void
14547 save_tracepoints_command (const char *args, int from_tty)
14548 {
14549 save_breakpoints (args, from_tty, is_tracepoint);
14550 }
14551
14552 \f
14553 /* This help string is used to consolidate all the help string for specifying
14554 locations used by several commands. */
14555
14556 #define LOCATION_SPEC_HELP_STRING \
14557 "Linespecs are colon-separated lists of location parameters, such as\n\
14558 source filename, function name, label name, and line number.\n\
14559 Example: To specify the start of a label named \"the_top\" in the\n\
14560 function \"fact\" in the file \"factorial.c\", use\n\
14561 \"factorial.c:fact:the_top\".\n\
14562 \n\
14563 Address locations begin with \"*\" and specify an exact address in the\n\
14564 program. Example: To specify the fourth byte past the start function\n\
14565 \"main\", use \"*main + 4\".\n\
14566 \n\
14567 Explicit locations are similar to linespecs but use an option/argument\n\
14568 syntax to specify location parameters.\n\
14569 Example: To specify the start of the label named \"the_top\" in the\n\
14570 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
14571 -function fact -label the_top\".\n\
14572 \n\
14573 By default, a specified function is matched against the program's\n\
14574 functions in all scopes. For C++, this means in all namespaces and\n\
14575 classes. For Ada, this means in all packages. E.g., in C++,\n\
14576 \"func()\" matches \"A::func()\", \"A::B::func()\", etc. The\n\
14577 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
14578 specified name as a complete fully-qualified name instead."
14579
14580 /* This help string is used for the break, hbreak, tbreak and thbreak
14581 commands. It is defined as a macro to prevent duplication.
14582 COMMAND should be a string constant containing the name of the
14583 command. */
14584
14585 #define BREAK_ARGS_HELP(command) \
14586 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
14587 \t[-force-condition] [if CONDITION]\n\
14588 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
14589 probe point. Accepted values are `-probe' (for a generic, automatically\n\
14590 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
14591 `-probe-dtrace' (for a DTrace probe).\n\
14592 LOCATION may be a linespec, address, or explicit location as described\n\
14593 below.\n\
14594 \n\
14595 With no LOCATION, uses current execution address of the selected\n\
14596 stack frame. This is useful for breaking on return to a stack frame.\n\
14597 \n\
14598 THREADNUM is the number from \"info threads\".\n\
14599 CONDITION is a boolean expression.\n\
14600 \n\
14601 With the \"-force-condition\" flag, the condition is defined even when\n\
14602 it is invalid for all current locations.\n\
14603 \n" LOCATION_SPEC_HELP_STRING "\n\n\
14604 Multiple breakpoints at one place are permitted, and useful if their\n\
14605 conditions are different.\n\
14606 \n\
14607 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14608
14609 /* List of subcommands for "catch". */
14610 static struct cmd_list_element *catch_cmdlist;
14611
14612 /* List of subcommands for "tcatch". */
14613 static struct cmd_list_element *tcatch_cmdlist;
14614
14615 void
14616 add_catch_command (const char *name, const char *docstring,
14617 cmd_func_ftype *func,
14618 completer_ftype *completer,
14619 void *user_data_catch,
14620 void *user_data_tcatch)
14621 {
14622 struct cmd_list_element *command;
14623
14624 command = add_cmd (name, class_breakpoint, docstring,
14625 &catch_cmdlist);
14626 command->func = func;
14627 command->set_context (user_data_catch);
14628 set_cmd_completer (command, completer);
14629
14630 command = add_cmd (name, class_breakpoint, docstring,
14631 &tcatch_cmdlist);
14632 command->func = func;
14633 command->set_context (user_data_tcatch);
14634 set_cmd_completer (command, completer);
14635 }
14636
14637 /* False if any of the breakpoint's locations could be a location where
14638 functions have been inlined, true otherwise. */
14639
14640 static bool
14641 is_non_inline_function (struct breakpoint *b)
14642 {
14643 /* The shared library event breakpoint is set on the address of a
14644 non-inline function. */
14645 return (b->type == bp_shlib_event);
14646 }
14647
14648 /* Nonzero if the specified PC cannot be a location where functions
14649 have been inlined. */
14650
14651 int
14652 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
14653 const target_waitstatus &ws)
14654 {
14655 for (breakpoint &b : all_breakpoints ())
14656 {
14657 if (!is_non_inline_function (&b))
14658 continue;
14659
14660 for (bp_location &bl : b.locations ())
14661 {
14662 if (!bl.shlib_disabled
14663 && bpstat_check_location (&bl, aspace, pc, ws))
14664 return 1;
14665 }
14666 }
14667
14668 return 0;
14669 }
14670
14671 /* Remove any references to OBJFILE which is going to be freed. */
14672
14673 void
14674 breakpoint_free_objfile (struct objfile *objfile)
14675 {
14676 for (bp_location *loc : all_bp_locations ())
14677 if (loc->symtab != NULL && loc->symtab->compunit ()->objfile () == objfile)
14678 loc->symtab = NULL;
14679 }
14680
14681 /* Chain containing all defined "enable breakpoint" subcommands. */
14682
14683 static struct cmd_list_element *enablebreaklist = NULL;
14684
14685 /* See breakpoint.h. */
14686
14687 cmd_list_element *commands_cmd_element = nullptr;
14688
14689 void _initialize_breakpoint ();
14690 void
14691 _initialize_breakpoint ()
14692 {
14693 struct cmd_list_element *c;
14694
14695 gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib,
14696 "breakpoint");
14697 gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile,
14698 "breakpoint");
14699 gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change,
14700 "breakpoint");
14701
14702 /* Don't bother to call set_breakpoint_count. $bpnum isn't useful
14703 before a breakpoint is set. */
14704 breakpoint_count = 0;
14705
14706 tracepoint_count = 0;
14707
14708 add_com ("ignore", class_breakpoint, ignore_command, _("\
14709 Set ignore-count of breakpoint number N to COUNT.\n\
14710 Usage is `ignore N COUNT'."));
14711
14712 commands_cmd_element = add_com ("commands", class_breakpoint,
14713 commands_command, _("\
14714 Set commands to be executed when the given breakpoints are hit.\n\
14715 Give a space-separated breakpoint list as argument after \"commands\".\n\
14716 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
14717 (e.g. `5-7').\n\
14718 With no argument, the targeted breakpoint is the last one set.\n\
14719 The commands themselves follow starting on the next line.\n\
14720 Type a line containing \"end\" to indicate the end of them.\n\
14721 Give \"silent\" as the first line to make the breakpoint silent;\n\
14722 then no output is printed when it is hit, except what the commands print."));
14723
14724 const auto cc_opts = make_condition_command_options_def_group (nullptr);
14725 static std::string condition_command_help
14726 = gdb::option::build_help (_("\
14727 Specify breakpoint number N to break only if COND is true.\n\
14728 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
14729 is an expression to be evaluated whenever breakpoint N is reached.\n\
14730 \n\
14731 Options:\n\
14732 %OPTIONS%"), cc_opts);
14733
14734 c = add_com ("condition", class_breakpoint, condition_command,
14735 condition_command_help.c_str ());
14736 set_cmd_completer_handle_brkchars (c, condition_completer);
14737
14738 c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
14739 Set a temporary breakpoint.\n\
14740 Like \"break\" except the breakpoint is only temporary,\n\
14741 so it will be deleted when hit. Equivalent to \"break\" followed\n\
14742 by using \"enable delete\" on the breakpoint number.\n\
14743 \n"
14744 BREAK_ARGS_HELP ("tbreak")));
14745 set_cmd_completer (c, location_completer);
14746
14747 c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
14748 Set a hardware assisted breakpoint.\n\
14749 Like \"break\" except the breakpoint requires hardware support,\n\
14750 some target hardware may not have this support.\n\
14751 \n"
14752 BREAK_ARGS_HELP ("hbreak")));
14753 set_cmd_completer (c, location_completer);
14754
14755 c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
14756 Set a temporary hardware assisted breakpoint.\n\
14757 Like \"hbreak\" except the breakpoint is only temporary,\n\
14758 so it will be deleted when hit.\n\
14759 \n"
14760 BREAK_ARGS_HELP ("thbreak")));
14761 set_cmd_completer (c, location_completer);
14762
14763 cmd_list_element *enable_cmd
14764 = add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
14765 Enable all or some breakpoints.\n\
14766 Usage: enable [BREAKPOINTNUM]...\n\
14767 Give breakpoint numbers (separated by spaces) as arguments.\n\
14768 With no subcommand, breakpoints are enabled until you command otherwise.\n\
14769 This is used to cancel the effect of the \"disable\" command.\n\
14770 With a subcommand you can enable temporarily."),
14771 &enablelist, 1, &cmdlist);
14772
14773 add_com_alias ("en", enable_cmd, class_breakpoint, 1);
14774
14775 add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
14776 Enable all or some breakpoints.\n\
14777 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
14778 Give breakpoint numbers (separated by spaces) as arguments.\n\
14779 This is used to cancel the effect of the \"disable\" command.\n\
14780 May be abbreviated to simply \"enable\"."),
14781 &enablebreaklist, 1, &enablelist);
14782
14783 add_cmd ("once", no_class, enable_once_command, _("\
14784 Enable some breakpoints for one hit.\n\
14785 Usage: enable breakpoints once BREAKPOINTNUM...\n\
14786 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14787 &enablebreaklist);
14788
14789 add_cmd ("delete", no_class, enable_delete_command, _("\
14790 Enable some breakpoints and delete when hit.\n\
14791 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
14792 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14793 &enablebreaklist);
14794
14795 add_cmd ("count", no_class, enable_count_command, _("\
14796 Enable some breakpoints for COUNT hits.\n\
14797 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
14798 If a breakpoint is hit while enabled in this fashion,\n\
14799 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14800 &enablebreaklist);
14801
14802 add_cmd ("delete", no_class, enable_delete_command, _("\
14803 Enable some breakpoints and delete when hit.\n\
14804 Usage: enable delete BREAKPOINTNUM...\n\
14805 If a breakpoint is hit while enabled in this fashion, it is deleted."),
14806 &enablelist);
14807
14808 add_cmd ("once", no_class, enable_once_command, _("\
14809 Enable some breakpoints for one hit.\n\
14810 Usage: enable once BREAKPOINTNUM...\n\
14811 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
14812 &enablelist);
14813
14814 add_cmd ("count", no_class, enable_count_command, _("\
14815 Enable some breakpoints for COUNT hits.\n\
14816 Usage: enable count COUNT BREAKPOINTNUM...\n\
14817 If a breakpoint is hit while enabled in this fashion,\n\
14818 the count is decremented; when it reaches zero, the breakpoint is disabled."),
14819 &enablelist);
14820
14821 cmd_list_element *disable_cmd
14822 = add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
14823 Disable all or some breakpoints.\n\
14824 Usage: disable [BREAKPOINTNUM]...\n\
14825 Arguments are breakpoint numbers with spaces in between.\n\
14826 To disable all breakpoints, give no argument.\n\
14827 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
14828 &disablelist, 1, &cmdlist);
14829 add_com_alias ("dis", disable_cmd, class_breakpoint, 1);
14830 add_com_alias ("disa", disable_cmd, class_breakpoint, 1);
14831
14832 add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
14833 Disable all or some breakpoints.\n\
14834 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
14835 Arguments are breakpoint numbers with spaces in between.\n\
14836 To disable all breakpoints, give no argument.\n\
14837 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
14838 This command may be abbreviated \"disable\"."),
14839 &disablelist);
14840
14841 cmd_list_element *delete_cmd
14842 = add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
14843 Delete all or some breakpoints.\n\
14844 Usage: delete [BREAKPOINTNUM]...\n\
14845 Arguments are breakpoint numbers with spaces in between.\n\
14846 To delete all breakpoints, give no argument.\n\
14847 \n\
14848 Also a prefix command for deletion of other GDB objects."),
14849 &deletelist, 1, &cmdlist);
14850 add_com_alias ("d", delete_cmd, class_breakpoint, 1);
14851 add_com_alias ("del", delete_cmd, class_breakpoint, 1);
14852
14853 add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
14854 Delete all or some breakpoints or auto-display expressions.\n\
14855 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
14856 Arguments are breakpoint numbers with spaces in between.\n\
14857 To delete all breakpoints, give no argument.\n\
14858 This command may be abbreviated \"delete\"."),
14859 &deletelist);
14860
14861 cmd_list_element *clear_cmd
14862 = add_com ("clear", class_breakpoint, clear_command, _("\
14863 Clear breakpoint at specified location.\n\
14864 Argument may be a linespec, explicit, or address location as described below.\n\
14865 \n\
14866 With no argument, clears all breakpoints in the line that the selected frame\n\
14867 is executing in.\n"
14868 "\n" LOCATION_SPEC_HELP_STRING "\n\n\
14869 See also the \"delete\" command which clears breakpoints by number."));
14870 add_com_alias ("cl", clear_cmd, class_breakpoint, 1);
14871
14872 cmd_list_element *break_cmd
14873 = add_com ("break", class_breakpoint, break_command, _("\
14874 Set breakpoint at specified location.\n"
14875 BREAK_ARGS_HELP ("break")));
14876 set_cmd_completer (break_cmd, location_completer);
14877
14878 add_com_alias ("b", break_cmd, class_run, 1);
14879 add_com_alias ("br", break_cmd, class_run, 1);
14880 add_com_alias ("bre", break_cmd, class_run, 1);
14881 add_com_alias ("brea", break_cmd, class_run, 1);
14882
14883 cmd_list_element *info_breakpoints_cmd
14884 = add_info ("breakpoints", info_breakpoints_command, _("\
14885 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14886 The \"Type\" column indicates one of:\n\
14887 \tbreakpoint - normal breakpoint\n\
14888 \twatchpoint - watchpoint\n\
14889 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14890 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14891 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14892 address and file/line number respectively.\n\
14893 \n\
14894 Convenience variable \"$_\" and default examine address for \"x\"\n\
14895 are set to the address of the last breakpoint listed unless the command\n\
14896 is prefixed with \"server \".\n\n\
14897 Convenience variable \"$bpnum\" contains the number of the last\n\
14898 breakpoint set."));
14899
14900 add_info_alias ("b", info_breakpoints_cmd, 1);
14901
14902 add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14903 Status of all breakpoints, or breakpoint number NUMBER.\n\
14904 The \"Type\" column indicates one of:\n\
14905 \tbreakpoint - normal breakpoint\n\
14906 \twatchpoint - watchpoint\n\
14907 \tlongjmp - internal breakpoint used to step through longjmp()\n\
14908 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14909 \tuntil - internal breakpoint used by the \"until\" command\n\
14910 \tfinish - internal breakpoint used by the \"finish\" command\n\
14911 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14912 the disposition of the breakpoint after it gets hit. \"dis\" means that the\n\
14913 breakpoint will be disabled. The \"Address\" and \"What\" columns indicate the\n\
14914 address and file/line number respectively.\n\
14915 \n\
14916 Convenience variable \"$_\" and default examine address for \"x\"\n\
14917 are set to the address of the last breakpoint listed unless the command\n\
14918 is prefixed with \"server \".\n\n\
14919 Convenience variable \"$bpnum\" contains the number of the last\n\
14920 breakpoint set."),
14921 &maintenanceinfolist);
14922
14923 add_basic_prefix_cmd ("catch", class_breakpoint, _("\
14924 Set catchpoints to catch events."),
14925 &catch_cmdlist,
14926 0/*allow-unknown*/, &cmdlist);
14927
14928 add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
14929 Set temporary catchpoints to catch events."),
14930 &tcatch_cmdlist,
14931 0/*allow-unknown*/, &cmdlist);
14932
14933 const auto opts = make_watch_options_def_group (nullptr);
14934
14935 static const std::string watch_help = gdb::option::build_help (_("\
14936 Set a watchpoint for EXPRESSION.\n\
14937 Usage: watch [-location] EXPRESSION\n\
14938 \n\
14939 Options:\n\
14940 %OPTIONS%\n\
14941 \n\
14942 A watchpoint stops execution of your program whenever the value of\n\
14943 an expression changes."), opts);
14944 c = add_com ("watch", class_breakpoint, watch_command,
14945 watch_help.c_str ());
14946 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14947
14948 static const std::string rwatch_help = gdb::option::build_help (_("\
14949 Set a read watchpoint for EXPRESSION.\n\
14950 Usage: rwatch [-location] EXPRESSION\n\
14951 \n\
14952 Options:\n\
14953 %OPTIONS%\n\
14954 \n\
14955 A read watchpoint stops execution of your program whenever the value of\n\
14956 an expression is read."), opts);
14957 c = add_com ("rwatch", class_breakpoint, rwatch_command,
14958 rwatch_help.c_str ());
14959 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14960
14961 static const std::string awatch_help = gdb::option::build_help (_("\
14962 Set an access watchpoint for EXPRESSION.\n\
14963 Usage: awatch [-location] EXPRESSION\n\
14964 \n\
14965 Options:\n\
14966 %OPTIONS%\n\
14967 \n\
14968 An access watchpoint stops execution of your program whenever the value\n\
14969 of an expression is either read or written."), opts);
14970 c = add_com ("awatch", class_breakpoint, awatch_command,
14971 awatch_help.c_str ());
14972 set_cmd_completer_handle_brkchars (c, watch_command_completer);
14973
14974 add_info ("watchpoints", info_watchpoints_command, _("\
14975 Status of specified watchpoints (all watchpoints if no argument)."));
14976
14977 /* XXX: cagney/2005-02-23: This should be a boolean, and should
14978 respond to changes - contrary to the description. */
14979 add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
14980 &can_use_hw_watchpoints, _("\
14981 Set debugger's willingness to use watchpoint hardware."), _("\
14982 Show debugger's willingness to use watchpoint hardware."), _("\
14983 If zero, gdb will not use hardware for new watchpoints, even if\n\
14984 such is available. (However, any hardware watchpoints that were\n\
14985 created before setting this to nonzero, will continue to use watchpoint\n\
14986 hardware.)"),
14987 NULL,
14988 show_can_use_hw_watchpoints,
14989 &setlist, &showlist);
14990
14991 can_use_hw_watchpoints = 1;
14992
14993 /* Tracepoint manipulation commands. */
14994
14995 cmd_list_element *trace_cmd
14996 = add_com ("trace", class_breakpoint, trace_command, _("\
14997 Set a tracepoint at specified location.\n\
14998 \n"
14999 BREAK_ARGS_HELP ("trace") "\n\
15000 Do \"help tracepoints\" for info on other tracepoint commands."));
15001 set_cmd_completer (trace_cmd, location_completer);
15002
15003 add_com_alias ("tp", trace_cmd, class_breakpoint, 0);
15004 add_com_alias ("tr", trace_cmd, class_breakpoint, 1);
15005 add_com_alias ("tra", trace_cmd, class_breakpoint, 1);
15006 add_com_alias ("trac", trace_cmd, class_breakpoint, 1);
15007
15008 c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15009 Set a fast tracepoint at specified location.\n\
15010 \n"
15011 BREAK_ARGS_HELP ("ftrace") "\n\
15012 Do \"help tracepoints\" for info on other tracepoint commands."));
15013 set_cmd_completer (c, location_completer);
15014
15015 c = add_com ("strace", class_breakpoint, strace_command, _("\
15016 Set a static tracepoint at location or marker.\n\
15017 \n\
15018 strace [LOCATION] [if CONDITION]\n\
15019 LOCATION may be a linespec, explicit, or address location (described below) \n\
15020 or -m MARKER_ID.\n\n\
15021 If a marker id is specified, probe the marker with that name. With\n\
15022 no LOCATION, uses current execution address of the selected stack frame.\n\
15023 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15024 This collects arbitrary user data passed in the probe point call to the\n\
15025 tracing library. You can inspect it when analyzing the trace buffer,\n\
15026 by printing the $_sdata variable like any other convenience variable.\n\
15027 \n\
15028 CONDITION is a boolean expression.\n\
15029 \n" LOCATION_SPEC_HELP_STRING "\n\n\
15030 Multiple tracepoints at one place are permitted, and useful if their\n\
15031 conditions are different.\n\
15032 \n\
15033 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15034 Do \"help tracepoints\" for info on other tracepoint commands."));
15035 set_cmd_completer (c, location_completer);
15036
15037 cmd_list_element *info_tracepoints_cmd
15038 = add_info ("tracepoints", info_tracepoints_command, _("\
15039 Status of specified tracepoints (all tracepoints if no argument).\n\
15040 Convenience variable \"$tpnum\" contains the number of the\n\
15041 last tracepoint set."));
15042
15043 add_info_alias ("tp", info_tracepoints_cmd, 1);
15044
15045 cmd_list_element *delete_tracepoints_cmd
15046 = add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15047 Delete specified tracepoints.\n\
15048 Arguments are tracepoint numbers, separated by spaces.\n\
15049 No argument means delete all tracepoints."),
15050 &deletelist);
15051 add_alias_cmd ("tr", delete_tracepoints_cmd, class_trace, 1, &deletelist);
15052
15053 c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15054 Disable specified tracepoints.\n\
15055 Arguments are tracepoint numbers, separated by spaces.\n\
15056 No argument means disable all tracepoints."),
15057 &disablelist);
15058 deprecate_cmd (c, "disable");
15059
15060 c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15061 Enable specified tracepoints.\n\
15062 Arguments are tracepoint numbers, separated by spaces.\n\
15063 No argument means enable all tracepoints."),
15064 &enablelist);
15065 deprecate_cmd (c, "enable");
15066
15067 add_com ("passcount", class_trace, trace_pass_command, _("\
15068 Set the passcount for a tracepoint.\n\
15069 The trace will end when the tracepoint has been passed 'count' times.\n\
15070 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15071 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15072
15073 add_basic_prefix_cmd ("save", class_breakpoint,
15074 _("Save breakpoint definitions as a script."),
15075 &save_cmdlist,
15076 0/*allow-unknown*/, &cmdlist);
15077
15078 c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15079 Save current breakpoint definitions as a script.\n\
15080 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15081 catchpoints, tracepoints). Use the 'source' command in another debug\n\
15082 session to restore them."),
15083 &save_cmdlist);
15084 set_cmd_completer (c, filename_completer);
15085
15086 cmd_list_element *save_tracepoints_cmd
15087 = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15088 Save current tracepoint definitions as a script.\n\
15089 Use the 'source' command in another debug session to restore them."),
15090 &save_cmdlist);
15091 set_cmd_completer (save_tracepoints_cmd, filename_completer);
15092
15093 c = add_com_alias ("save-tracepoints", save_tracepoints_cmd, class_trace, 0);
15094 deprecate_cmd (c, "save tracepoints");
15095
15096 add_setshow_prefix_cmd ("breakpoint", class_maintenance,
15097 _("\
15098 Breakpoint specific settings.\n\
15099 Configure various breakpoint-specific variables such as\n\
15100 pending breakpoint behavior."),
15101 _("\
15102 Breakpoint specific settings.\n\
15103 Configure various breakpoint-specific variables such as\n\
15104 pending breakpoint behavior."),
15105 &breakpoint_set_cmdlist, &breakpoint_show_cmdlist,
15106 &setlist, &showlist);
15107
15108 add_setshow_auto_boolean_cmd ("pending", no_class,
15109 &pending_break_support, _("\
15110 Set debugger's behavior regarding pending breakpoints."), _("\
15111 Show debugger's behavior regarding pending breakpoints."), _("\
15112 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15113 pending breakpoint. If off, an unrecognized breakpoint location results in\n\
15114 an error. If auto, an unrecognized breakpoint location results in a\n\
15115 user-query to see if a pending breakpoint should be created."),
15116 NULL,
15117 show_pending_break_support,
15118 &breakpoint_set_cmdlist,
15119 &breakpoint_show_cmdlist);
15120
15121 pending_break_support = AUTO_BOOLEAN_AUTO;
15122
15123 add_setshow_boolean_cmd ("auto-hw", no_class,
15124 &automatic_hardware_breakpoints, _("\
15125 Set automatic usage of hardware breakpoints."), _("\
15126 Show automatic usage of hardware breakpoints."), _("\
15127 If set, the debugger will automatically use hardware breakpoints for\n\
15128 breakpoints set with \"break\" but falling in read-only memory. If not set,\n\
15129 a warning will be emitted for such breakpoints."),
15130 NULL,
15131 show_automatic_hardware_breakpoints,
15132 &breakpoint_set_cmdlist,
15133 &breakpoint_show_cmdlist);
15134
15135 add_setshow_boolean_cmd ("always-inserted", class_support,
15136 &always_inserted_mode, _("\
15137 Set mode for inserting breakpoints."), _("\
15138 Show mode for inserting breakpoints."), _("\
15139 When this mode is on, breakpoints are inserted immediately as soon as\n\
15140 they're created, kept inserted even when execution stops, and removed\n\
15141 only when the user deletes them. When this mode is off (the default),\n\
15142 breakpoints are inserted only when execution continues, and removed\n\
15143 when execution stops."),
15144 NULL,
15145 &show_always_inserted_mode,
15146 &breakpoint_set_cmdlist,
15147 &breakpoint_show_cmdlist);
15148
15149 add_setshow_boolean_cmd ("breakpoint", class_maintenance,
15150 &debug_breakpoint, _("\
15151 Set breakpoint location debugging."), _("\
15152 Show breakpoint location debugging."), _("\
15153 When on, breakpoint location specific debugging is enabled."),
15154 NULL,
15155 show_debug_breakpoint,
15156 &setdebuglist, &showdebuglist);
15157
15158 add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15159 condition_evaluation_enums,
15160 &condition_evaluation_mode_1, _("\
15161 Set mode of breakpoint condition evaluation."), _("\
15162 Show mode of breakpoint condition evaluation."), _("\
15163 When this is set to \"host\", breakpoint conditions will be\n\
15164 evaluated on the host's side by GDB. When it is set to \"target\",\n\
15165 breakpoint conditions will be downloaded to the target (if the target\n\
15166 supports such feature) and conditions will be evaluated on the target's side.\n\
15167 If this is set to \"auto\" (default), this will be automatically set to\n\
15168 \"target\" if it supports condition evaluation, otherwise it will\n\
15169 be set to \"host\"."),
15170 &set_condition_evaluation_mode,
15171 &show_condition_evaluation_mode,
15172 &breakpoint_set_cmdlist,
15173 &breakpoint_show_cmdlist);
15174
15175 add_com ("break-range", class_breakpoint, break_range_command, _("\
15176 Set a breakpoint for an address range.\n\
15177 break-range START-LOCATION, END-LOCATION\n\
15178 where START-LOCATION and END-LOCATION can be one of the following:\n\
15179 LINENUM, for that line in the current file,\n\
15180 FILE:LINENUM, for that line in that file,\n\
15181 +OFFSET, for that number of lines after the current line\n\
15182 or the start of the range\n\
15183 FUNCTION, for the first line in that function,\n\
15184 FILE:FUNCTION, to distinguish among like-named static functions.\n\
15185 *ADDRESS, for the instruction at that address.\n\
15186 \n\
15187 The breakpoint will stop execution of the inferior whenever it executes\n\
15188 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15189 range (including START-LOCATION and END-LOCATION)."));
15190
15191 c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
15192 Set a dynamic printf at specified location.\n\
15193 dprintf location,format string,arg1,arg2,...\n\
15194 location may be a linespec, explicit, or address location.\n"
15195 "\n" LOCATION_SPEC_HELP_STRING));
15196 set_cmd_completer (c, location_completer);
15197
15198 add_setshow_enum_cmd ("dprintf-style", class_support,
15199 dprintf_style_enums, &dprintf_style, _("\
15200 Set the style of usage for dynamic printf."), _("\
15201 Show the style of usage for dynamic printf."), _("\
15202 This setting chooses how GDB will do a dynamic printf.\n\
15203 If the value is \"gdb\", then the printing is done by GDB to its own\n\
15204 console, as with the \"printf\" command.\n\
15205 If the value is \"call\", the print is done by calling a function in your\n\
15206 program; by default printf(), but you can choose a different function or\n\
15207 output stream by setting dprintf-function and dprintf-channel."),
15208 update_dprintf_commands, NULL,
15209 &setlist, &showlist);
15210
15211 add_setshow_string_cmd ("dprintf-function", class_support,
15212 &dprintf_function, _("\
15213 Set the function to use for dynamic printf."), _("\
15214 Show the function to use for dynamic printf."), NULL,
15215 update_dprintf_commands, NULL,
15216 &setlist, &showlist);
15217
15218 add_setshow_string_cmd ("dprintf-channel", class_support,
15219 &dprintf_channel, _("\
15220 Set the channel to use for dynamic printf."), _("\
15221 Show the channel to use for dynamic printf."), NULL,
15222 update_dprintf_commands, NULL,
15223 &setlist, &showlist);
15224
15225 add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
15226 &disconnected_dprintf, _("\
15227 Set whether dprintf continues after GDB disconnects."), _("\
15228 Show whether dprintf continues after GDB disconnects."), _("\
15229 Use this to let dprintf commands continue to hit and produce output\n\
15230 even if GDB disconnects or detaches from the target."),
15231 NULL,
15232 NULL,
15233 &setlist, &showlist);
15234
15235 add_com ("agent-printf", class_vars, agent_printf_command, _("\
15236 Target agent only formatted printing, like the C \"printf\" function.\n\
15237 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
15238 This supports most C printf format specifications, like %s, %d, etc.\n\
15239 This is useful for formatted output in user-defined commands."));
15240
15241 automatic_hardware_breakpoints = true;
15242
15243 gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed,
15244 "breakpoint");
15245 gdb::observers::thread_exit.attach (remove_threaded_breakpoints,
15246 "breakpoint");
15247 gdb::observers::inferior_removed.attach (remove_inferior_breakpoints,
15248 "breakpoint");
15249 }