]> Git Repo - binutils.git/blob - gdb/breakpoint.c
gdb: move go_language class declaration into header file
[binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2020 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "ui-out.h"
48 #include "cli/cli-script.h"
49 #include "block.h"
50 #include "solib.h"
51 #include "solist.h"
52 #include "observable.h"
53 #include "memattr.h"
54 #include "ada-lang.h"
55 #include "top.h"
56 #include "valprint.h"
57 #include "jit.h"
58 #include "parser-defs.h"
59 #include "gdb_regex.h"
60 #include "probe.h"
61 #include "cli/cli-utils.h"
62 #include "stack.h"
63 #include "ax-gdb.h"
64 #include "dummy-frame.h"
65 #include "interps.h"
66 #include "gdbsupport/format.h"
67 #include "thread-fsm.h"
68 #include "tid-parse.h"
69 #include "cli/cli-style.h"
70
71 /* readline include files */
72 #include "readline/tilde.h"
73
74 /* readline defines this.  */
75 #undef savestring
76
77 #include "mi/mi-common.h"
78 #include "extension.h"
79 #include <algorithm>
80 #include "progspace-and-thread.h"
81 #include "gdbsupport/array-view.h"
82 #include "gdbsupport/gdb_optional.h"
83
84 /* Prototypes for local functions.  */
85
86 static void map_breakpoint_numbers (const char *,
87                                     gdb::function_view<void (breakpoint *)>);
88
89 static void breakpoint_re_set_default (struct breakpoint *);
90
91 static void
92   create_sals_from_location_default (struct event_location *location,
93                                      struct linespec_result *canonical,
94                                      enum bptype type_wanted);
95
96 static void create_breakpoints_sal_default (struct gdbarch *,
97                                             struct linespec_result *,
98                                             gdb::unique_xmalloc_ptr<char>,
99                                             gdb::unique_xmalloc_ptr<char>,
100                                             enum bptype,
101                                             enum bpdisp, int, int,
102                                             int,
103                                             const struct breakpoint_ops *,
104                                             int, int, int, unsigned);
105
106 static std::vector<symtab_and_line> decode_location_default
107   (struct breakpoint *b, struct event_location *location,
108    struct program_space *search_pspace);
109
110 static int can_use_hardware_watchpoint
111     (const std::vector<value_ref_ptr> &vals);
112
113 static void mention (struct breakpoint *);
114
115 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
116                                                                enum bptype,
117                                                                const struct breakpoint_ops *);
118 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
119                                                        const struct symtab_and_line *);
120
121 /* This function is used in gdbtk sources and thus can not be made
122    static.  */
123 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
124                                        struct symtab_and_line,
125                                        enum bptype,
126                                        const struct breakpoint_ops *);
127
128 static struct breakpoint *
129   momentary_breakpoint_from_master (struct breakpoint *orig,
130                                     enum bptype type,
131                                     const struct breakpoint_ops *ops,
132                                     int loc_enabled);
133
134 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
135
136 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
137                                             CORE_ADDR bpaddr,
138                                             enum bptype bptype);
139
140 static void describe_other_breakpoints (struct gdbarch *,
141                                         struct program_space *, CORE_ADDR,
142                                         struct obj_section *, int);
143
144 static int watchpoint_locations_match (struct bp_location *loc1,
145                                        struct bp_location *loc2);
146
147 static int breakpoint_locations_match (struct bp_location *loc1,
148                                        struct bp_location *loc2,
149                                        bool sw_hw_bps_match = false);
150
151 static int breakpoint_location_address_match (struct bp_location *bl,
152                                               const struct address_space *aspace,
153                                               CORE_ADDR addr);
154
155 static int breakpoint_location_address_range_overlap (struct bp_location *,
156                                                       const address_space *,
157                                                       CORE_ADDR, int);
158
159 static int remove_breakpoint (struct bp_location *);
160 static int remove_breakpoint_1 (struct bp_location *, enum remove_bp_reason);
161
162 static enum print_stop_action print_bp_stop_message (bpstat bs);
163
164 static int hw_breakpoint_used_count (void);
165
166 static int hw_watchpoint_use_count (struct breakpoint *);
167
168 static int hw_watchpoint_used_count_others (struct breakpoint *except,
169                                             enum bptype type,
170                                             int *other_type_used);
171
172 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
173                                     int count);
174
175 static void decref_bp_location (struct bp_location **loc);
176
177 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
178
179 /* update_global_location_list's modes of operation wrt to whether to
180    insert locations now.  */
181 enum ugll_insert_mode
182 {
183   /* Don't insert any breakpoint locations into the inferior, only
184      remove already-inserted locations that no longer should be
185      inserted.  Functions that delete a breakpoint or breakpoints
186      should specify this mode, so that deleting a breakpoint doesn't
187      have the side effect of inserting the locations of other
188      breakpoints that are marked not-inserted, but should_be_inserted
189      returns true on them.
190
191      This behavior is useful is situations close to tear-down -- e.g.,
192      after an exec, while the target still has execution, but
193      breakpoint shadows of the previous executable image should *NOT*
194      be restored to the new image; or before detaching, where the
195      target still has execution and wants to delete breakpoints from
196      GDB's lists, and all breakpoints had already been removed from
197      the inferior.  */
198   UGLL_DONT_INSERT,
199
200   /* May insert breakpoints iff breakpoints_should_be_inserted_now
201      claims breakpoints should be inserted now.  */
202   UGLL_MAY_INSERT,
203
204   /* Insert locations now, irrespective of
205      breakpoints_should_be_inserted_now.  E.g., say all threads are
206      stopped right now, and the user did "continue".  We need to
207      insert breakpoints _before_ resuming the target, but
208      UGLL_MAY_INSERT wouldn't insert them, because
209      breakpoints_should_be_inserted_now returns false at that point,
210      as no thread is running yet.  */
211   UGLL_INSERT
212 };
213
214 static void update_global_location_list (enum ugll_insert_mode);
215
216 static void update_global_location_list_nothrow (enum ugll_insert_mode);
217
218 static void insert_breakpoint_locations (void);
219
220 static void trace_pass_command (const char *, int);
221
222 static void set_tracepoint_count (int num);
223
224 static bool is_masked_watchpoint (const struct breakpoint *b);
225
226 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
227
228 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
229    otherwise.  */
230
231 static int strace_marker_p (struct breakpoint *b);
232
233 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
234    that are implemented on top of software or hardware breakpoints
235    (user breakpoints, internal and momentary breakpoints, etc.).  */
236 static struct breakpoint_ops bkpt_base_breakpoint_ops;
237
238 /* Internal breakpoints class type.  */
239 static struct breakpoint_ops internal_breakpoint_ops;
240
241 /* Momentary breakpoints class type.  */
242 static struct breakpoint_ops momentary_breakpoint_ops;
243
244 /* The breakpoint_ops structure to be used in regular user created
245    breakpoints.  */
246 struct breakpoint_ops bkpt_breakpoint_ops;
247
248 /* Breakpoints set on probes.  */
249 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
250
251 /* Tracepoints set on probes.  */
252 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
253
254 /* Dynamic printf class type.  */
255 struct breakpoint_ops dprintf_breakpoint_ops;
256
257 /* The style in which to perform a dynamic printf.  This is a user
258    option because different output options have different tradeoffs;
259    if GDB does the printing, there is better error handling if there
260    is a problem with any of the arguments, but using an inferior
261    function lets you have special-purpose printers and sending of
262    output to the same place as compiled-in print functions.  */
263
264 static const char dprintf_style_gdb[] = "gdb";
265 static const char dprintf_style_call[] = "call";
266 static const char dprintf_style_agent[] = "agent";
267 static const char *const dprintf_style_enums[] = {
268   dprintf_style_gdb,
269   dprintf_style_call,
270   dprintf_style_agent,
271   NULL
272 };
273 static const char *dprintf_style = dprintf_style_gdb;
274
275 /* The function to use for dynamic printf if the preferred style is to
276    call into the inferior.  The value is simply a string that is
277    copied into the command, so it can be anything that GDB can
278    evaluate to a callable address, not necessarily a function name.  */
279
280 static char *dprintf_function;
281
282 /* The channel to use for dynamic printf if the preferred style is to
283    call into the inferior; if a nonempty string, it will be passed to
284    the call as the first argument, with the format string as the
285    second.  As with the dprintf function, this can be anything that
286    GDB knows how to evaluate, so in addition to common choices like
287    "stderr", this could be an app-specific expression like
288    "mystreams[curlogger]".  */
289
290 static char *dprintf_channel;
291
292 /* True if dprintf commands should continue to operate even if GDB
293    has disconnected.  */
294 static bool disconnected_dprintf = true;
295
296 struct command_line *
297 breakpoint_commands (struct breakpoint *b)
298 {
299   return b->commands ? b->commands.get () : NULL;
300 }
301
302 /* Flag indicating that a command has proceeded the inferior past the
303    current breakpoint.  */
304
305 static bool breakpoint_proceeded;
306
307 const char *
308 bpdisp_text (enum bpdisp disp)
309 {
310   /* NOTE: the following values are a part of MI protocol and
311      represent values of 'disp' field returned when inferior stops at
312      a breakpoint.  */
313   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
314
315   return bpdisps[(int) disp];
316 }
317
318 /* Prototypes for exported functions.  */
319 /* If FALSE, gdb will not use hardware support for watchpoints, even
320    if such is available.  */
321 static int can_use_hw_watchpoints;
322
323 static void
324 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
325                              struct cmd_list_element *c,
326                              const char *value)
327 {
328   fprintf_filtered (file,
329                     _("Debugger's willingness to use "
330                       "watchpoint hardware is %s.\n"),
331                     value);
332 }
333
334 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
335    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
336    for unrecognized breakpoint locations.
337    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
338 static enum auto_boolean pending_break_support;
339 static void
340 show_pending_break_support (struct ui_file *file, int from_tty,
341                             struct cmd_list_element *c,
342                             const char *value)
343 {
344   fprintf_filtered (file,
345                     _("Debugger's behavior regarding "
346                       "pending breakpoints is %s.\n"),
347                     value);
348 }
349
350 /* If true, gdb will automatically use hardware breakpoints for breakpoints
351    set with "break" but falling in read-only memory.
352    If false, gdb will warn about such breakpoints, but won't automatically
353    use hardware breakpoints.  */
354 static bool automatic_hardware_breakpoints;
355 static void
356 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
357                                      struct cmd_list_element *c,
358                                      const char *value)
359 {
360   fprintf_filtered (file,
361                     _("Automatic usage of hardware breakpoints is %s.\n"),
362                     value);
363 }
364
365 /* If on, GDB keeps breakpoints inserted even if the inferior is
366    stopped, and immediately inserts any new breakpoints as soon as
367    they're created.  If off (default), GDB keeps breakpoints off of
368    the target as long as possible.  That is, it delays inserting
369    breakpoints until the next resume, and removes them again when the
370    target fully stops.  This is a bit safer in case GDB crashes while
371    processing user input.  */
372 static bool always_inserted_mode = false;
373
374 static void
375 show_always_inserted_mode (struct ui_file *file, int from_tty,
376                      struct cmd_list_element *c, const char *value)
377 {
378   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
379                     value);
380 }
381
382 /* See breakpoint.h.  */
383
384 int
385 breakpoints_should_be_inserted_now (void)
386 {
387   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
388     {
389       /* If breakpoints are global, they should be inserted even if no
390          thread under gdb's control is running, or even if there are
391          no threads under GDB's control yet.  */
392       return 1;
393     }
394   else
395     {
396       if (always_inserted_mode)
397         {
398           /* The user wants breakpoints inserted even if all threads
399              are stopped.  */
400           return 1;
401         }
402
403       for (inferior *inf : all_inferiors ())
404         if (inf->has_execution ()
405             && threads_are_executing (inf->process_target ()))
406           return 1;
407
408       /* Don't remove breakpoints yet if, even though all threads are
409          stopped, we still have events to process.  */
410       for (thread_info *tp : all_non_exited_threads ())
411         if (tp->resumed
412             && tp->suspend.waitstatus_pending_p)
413           return 1;
414     }
415   return 0;
416 }
417
418 static const char condition_evaluation_both[] = "host or target";
419
420 /* Modes for breakpoint condition evaluation.  */
421 static const char condition_evaluation_auto[] = "auto";
422 static const char condition_evaluation_host[] = "host";
423 static const char condition_evaluation_target[] = "target";
424 static const char *const condition_evaluation_enums[] = {
425   condition_evaluation_auto,
426   condition_evaluation_host,
427   condition_evaluation_target,
428   NULL
429 };
430
431 /* Global that holds the current mode for breakpoint condition evaluation.  */
432 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
433
434 /* Global that we use to display information to the user (gets its value from
435    condition_evaluation_mode_1.  */
436 static const char *condition_evaluation_mode = condition_evaluation_auto;
437
438 /* Translate a condition evaluation mode MODE into either "host"
439    or "target".  This is used mostly to translate from "auto" to the
440    real setting that is being used.  It returns the translated
441    evaluation mode.  */
442
443 static const char *
444 translate_condition_evaluation_mode (const char *mode)
445 {
446   if (mode == condition_evaluation_auto)
447     {
448       if (target_supports_evaluation_of_breakpoint_conditions ())
449         return condition_evaluation_target;
450       else
451         return condition_evaluation_host;
452     }
453   else
454     return mode;
455 }
456
457 /* Discovers what condition_evaluation_auto translates to.  */
458
459 static const char *
460 breakpoint_condition_evaluation_mode (void)
461 {
462   return translate_condition_evaluation_mode (condition_evaluation_mode);
463 }
464
465 /* Return true if GDB should evaluate breakpoint conditions or false
466    otherwise.  */
467
468 static int
469 gdb_evaluates_breakpoint_condition_p (void)
470 {
471   const char *mode = breakpoint_condition_evaluation_mode ();
472
473   return (mode == condition_evaluation_host);
474 }
475
476 /* Are we executing breakpoint commands?  */
477 static int executing_breakpoint_commands;
478
479 /* Are overlay event breakpoints enabled? */
480 static int overlay_events_enabled;
481
482 /* See description in breakpoint.h. */
483 bool target_exact_watchpoints = false;
484
485 /* Walk the following statement or block through all breakpoints.
486    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
487    current breakpoint.  */
488
489 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
490
491 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
492         for (B = breakpoint_chain;      \
493              B ? (TMP=B->next, 1): 0;   \
494              B = TMP)
495
496 /* Similar iterator for the low-level breakpoints.  SAFE variant is
497    not provided so update_global_location_list must not be called
498    while executing the block of ALL_BP_LOCATIONS.  */
499
500 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
501         for (BP_TMP = bp_locations;                                     \
502              BP_TMP < bp_locations + bp_locations_count && (B = *BP_TMP);\
503              BP_TMP++)
504
505 /* Iterates through locations with address ADDRESS for the currently selected
506    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
507    to where the loop should start from.
508    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
509    appropriate location to start with.  */
510
511 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
512         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
513              BP_LOCP_TMP = BP_LOCP_START;                               \
514              BP_LOCP_START                                              \
515              && (BP_LOCP_TMP < bp_locations + bp_locations_count        \
516              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
517              BP_LOCP_TMP++)
518
519 /* Iterator for tracepoints only.  */
520
521 #define ALL_TRACEPOINTS(B)  \
522   for (B = breakpoint_chain; B; B = B->next)  \
523     if (is_tracepoint (B))
524
525 /* Chains of all breakpoints defined.  */
526
527 static struct breakpoint *breakpoint_chain;
528
529 /* Array is sorted by bp_location_is_less_than - primarily by the ADDRESS.  */
530
531 static struct bp_location **bp_locations;
532
533 /* Number of elements of BP_LOCATIONS.  */
534
535 static unsigned bp_locations_count;
536
537 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
538    ADDRESS for the current elements of BP_LOCATIONS which get a valid
539    result from bp_location_has_shadow.  You can use it for roughly
540    limiting the subrange of BP_LOCATIONS to scan for shadow bytes for
541    an address you need to read.  */
542
543 static CORE_ADDR bp_locations_placed_address_before_address_max;
544
545 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
546    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
547    BP_LOCATIONS which get a valid result from bp_location_has_shadow.
548    You can use it for roughly limiting the subrange of BP_LOCATIONS to
549    scan for shadow bytes for an address you need to read.  */
550
551 static CORE_ADDR bp_locations_shadow_len_after_address_max;
552
553 /* The locations that no longer correspond to any breakpoint, unlinked
554    from the bp_locations array, but for which a hit may still be
555    reported by a target.  */
556 static std::vector<bp_location *> moribund_locations;
557
558 /* Number of last breakpoint made.  */
559
560 static int breakpoint_count;
561
562 /* The value of `breakpoint_count' before the last command that
563    created breakpoints.  If the last (break-like) command created more
564    than one breakpoint, then the difference between BREAKPOINT_COUNT
565    and PREV_BREAKPOINT_COUNT is more than one.  */
566 static int prev_breakpoint_count;
567
568 /* Number of last tracepoint made.  */
569
570 static int tracepoint_count;
571
572 static struct cmd_list_element *breakpoint_set_cmdlist;
573 static struct cmd_list_element *breakpoint_show_cmdlist;
574 struct cmd_list_element *save_cmdlist;
575
576 /* See declaration at breakpoint.h.  */
577
578 struct breakpoint *
579 breakpoint_find_if (int (*func) (struct breakpoint *b, void *d),
580                     void *user_data)
581 {
582   struct breakpoint *b = NULL;
583
584   ALL_BREAKPOINTS (b)
585     {
586       if (func (b, user_data) != 0)
587         break;
588     }
589
590   return b;
591 }
592
593 /* Return whether a breakpoint is an active enabled breakpoint.  */
594 static int
595 breakpoint_enabled (struct breakpoint *b)
596 {
597   return (b->enable_state == bp_enabled);
598 }
599
600 /* Set breakpoint count to NUM.  */
601
602 static void
603 set_breakpoint_count (int num)
604 {
605   prev_breakpoint_count = breakpoint_count;
606   breakpoint_count = num;
607   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
608 }
609
610 /* Used by `start_rbreak_breakpoints' below, to record the current
611    breakpoint count before "rbreak" creates any breakpoint.  */
612 static int rbreak_start_breakpoint_count;
613
614 /* Called at the start an "rbreak" command to record the first
615    breakpoint made.  */
616
617 scoped_rbreak_breakpoints::scoped_rbreak_breakpoints ()
618 {
619   rbreak_start_breakpoint_count = breakpoint_count;
620 }
621
622 /* Called at the end of an "rbreak" command to record the last
623    breakpoint made.  */
624
625 scoped_rbreak_breakpoints::~scoped_rbreak_breakpoints ()
626 {
627   prev_breakpoint_count = rbreak_start_breakpoint_count;
628 }
629
630 /* Used in run_command to zero the hit count when a new run starts.  */
631
632 void
633 clear_breakpoint_hit_counts (void)
634 {
635   struct breakpoint *b;
636
637   ALL_BREAKPOINTS (b)
638     b->hit_count = 0;
639 }
640
641 \f
642 /* Return the breakpoint with the specified number, or NULL
643    if the number does not refer to an existing breakpoint.  */
644
645 struct breakpoint *
646 get_breakpoint (int num)
647 {
648   struct breakpoint *b;
649
650   ALL_BREAKPOINTS (b)
651     if (b->number == num)
652       return b;
653   
654   return NULL;
655 }
656
657 \f
658
659 /* Mark locations as "conditions have changed" in case the target supports
660    evaluating conditions on its side.  */
661
662 static void
663 mark_breakpoint_modified (struct breakpoint *b)
664 {
665   struct bp_location *loc;
666
667   /* This is only meaningful if the target is
668      evaluating conditions and if the user has
669      opted for condition evaluation on the target's
670      side.  */
671   if (gdb_evaluates_breakpoint_condition_p ()
672       || !target_supports_evaluation_of_breakpoint_conditions ())
673     return;
674
675   if (!is_breakpoint (b))
676     return;
677
678   for (loc = b->loc; loc; loc = loc->next)
679     loc->condition_changed = condition_modified;
680 }
681
682 /* Mark location as "conditions have changed" in case the target supports
683    evaluating conditions on its side.  */
684
685 static void
686 mark_breakpoint_location_modified (struct bp_location *loc)
687 {
688   /* This is only meaningful if the target is
689      evaluating conditions and if the user has
690      opted for condition evaluation on the target's
691      side.  */
692   if (gdb_evaluates_breakpoint_condition_p ()
693       || !target_supports_evaluation_of_breakpoint_conditions ())
694
695     return;
696
697   if (!is_breakpoint (loc->owner))
698     return;
699
700   loc->condition_changed = condition_modified;
701 }
702
703 /* Sets the condition-evaluation mode using the static global
704    condition_evaluation_mode.  */
705
706 static void
707 set_condition_evaluation_mode (const char *args, int from_tty,
708                                struct cmd_list_element *c)
709 {
710   const char *old_mode, *new_mode;
711
712   if ((condition_evaluation_mode_1 == condition_evaluation_target)
713       && !target_supports_evaluation_of_breakpoint_conditions ())
714     {
715       condition_evaluation_mode_1 = condition_evaluation_mode;
716       warning (_("Target does not support breakpoint condition evaluation.\n"
717                  "Using host evaluation mode instead."));
718       return;
719     }
720
721   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
722   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
723
724   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
725      settings was "auto".  */
726   condition_evaluation_mode = condition_evaluation_mode_1;
727
728   /* Only update the mode if the user picked a different one.  */
729   if (new_mode != old_mode)
730     {
731       struct bp_location *loc, **loc_tmp;
732       /* If the user switched to a different evaluation mode, we
733          need to synch the changes with the target as follows:
734
735          "host" -> "target": Send all (valid) conditions to the target.
736          "target" -> "host": Remove all the conditions from the target.
737       */
738
739       if (new_mode == condition_evaluation_target)
740         {
741           /* Mark everything modified and synch conditions with the
742              target.  */
743           ALL_BP_LOCATIONS (loc, loc_tmp)
744             mark_breakpoint_location_modified (loc);
745         }
746       else
747         {
748           /* Manually mark non-duplicate locations to synch conditions
749              with the target.  We do this to remove all the conditions the
750              target knows about.  */
751           ALL_BP_LOCATIONS (loc, loc_tmp)
752             if (is_breakpoint (loc->owner) && loc->inserted)
753               loc->needs_update = 1;
754         }
755
756       /* Do the update.  */
757       update_global_location_list (UGLL_MAY_INSERT);
758     }
759
760   return;
761 }
762
763 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
764    what "auto" is translating to.  */
765
766 static void
767 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
768                                 struct cmd_list_element *c, const char *value)
769 {
770   if (condition_evaluation_mode == condition_evaluation_auto)
771     fprintf_filtered (file,
772                       _("Breakpoint condition evaluation "
773                         "mode is %s (currently %s).\n"),
774                       value,
775                       breakpoint_condition_evaluation_mode ());
776   else
777     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
778                       value);
779 }
780
781 /* A comparison function for bp_location AP and BP that is used by
782    bsearch.  This comparison function only cares about addresses, unlike
783    the more general bp_location_is_less_than function.  */
784
785 static int
786 bp_locations_compare_addrs (const void *ap, const void *bp)
787 {
788   const struct bp_location *a = *(const struct bp_location **) ap;
789   const struct bp_location *b = *(const struct bp_location **) bp;
790
791   if (a->address == b->address)
792     return 0;
793   else
794     return ((a->address > b->address) - (a->address < b->address));
795 }
796
797 /* Helper function to skip all bp_locations with addresses
798    less than ADDRESS.  It returns the first bp_location that
799    is greater than or equal to ADDRESS.  If none is found, just
800    return NULL.  */
801
802 static struct bp_location **
803 get_first_locp_gte_addr (CORE_ADDR address)
804 {
805   struct bp_location dummy_loc;
806   struct bp_location *dummy_locp = &dummy_loc;
807   struct bp_location **locp_found = NULL;
808
809   /* Initialize the dummy location's address field.  */
810   dummy_loc.address = address;
811
812   /* Find a close match to the first location at ADDRESS.  */
813   locp_found = ((struct bp_location **)
814                 bsearch (&dummy_locp, bp_locations, bp_locations_count,
815                          sizeof (struct bp_location **),
816                          bp_locations_compare_addrs));
817
818   /* Nothing was found, nothing left to do.  */
819   if (locp_found == NULL)
820     return NULL;
821
822   /* We may have found a location that is at ADDRESS but is not the first in the
823      location's list.  Go backwards (if possible) and locate the first one.  */
824   while ((locp_found - 1) >= bp_locations
825          && (*(locp_found - 1))->address == address)
826     locp_found--;
827
828   return locp_found;
829 }
830
831 /* Parse COND_STRING in the context of LOC and set as the condition
832    expression of LOC.  BP_NUM is the number of LOC's owner, LOC_NUM is
833    the number of LOC within its owner.  In case of parsing error, mark
834    LOC as DISABLED_BY_COND.  In case of success, unset DISABLED_BY_COND.  */
835
836 static void
837 set_breakpoint_location_condition (const char *cond_string, bp_location *loc,
838                                    int bp_num, int loc_num)
839 {
840   bool has_junk = false;
841   try
842     {
843       expression_up new_exp = parse_exp_1 (&cond_string, loc->address,
844                                            block_for_pc (loc->address), 0);
845       if (*cond_string != 0)
846         has_junk = true;
847       else
848         {
849           loc->cond = std::move (new_exp);
850           if (loc->disabled_by_cond && loc->enabled)
851             printf_filtered (_("Breakpoint %d's condition is now valid at "
852                                "location %d, enabling.\n"),
853                              bp_num, loc_num);
854
855           loc->disabled_by_cond = false;
856         }
857     }
858   catch (const gdb_exception_error &e)
859     {
860       if (loc->enabled)
861         {
862           /* Warn if a user-enabled location is now becoming disabled-by-cond.
863              BP_NUM is 0 if the breakpoint is being defined for the first
864              time using the "break ... if ..." command, and non-zero if
865              already defined.  */
866           if (bp_num != 0)
867             warning (_("failed to validate condition at location %d.%d, "
868                        "disabling:\n  %s"), bp_num, loc_num, e.what ());
869           else
870             warning (_("failed to validate condition at location %d, "
871                        "disabling:\n  %s"), loc_num, e.what ());
872         }
873
874       loc->disabled_by_cond = true;
875     }
876
877   if (has_junk)
878     error (_("Garbage '%s' follows condition"), cond_string);
879 }
880
881 void
882 set_breakpoint_condition (struct breakpoint *b, const char *exp,
883                           int from_tty, bool force)
884 {
885   if (*exp == 0)
886     {
887       xfree (b->cond_string);
888       b->cond_string = nullptr;
889
890       if (is_watchpoint (b))
891         static_cast<watchpoint *> (b)->cond_exp.reset ();
892       else
893         {
894           int loc_num = 1;
895           for (bp_location *loc = b->loc; loc != nullptr; loc = loc->next)
896             {
897               loc->cond.reset ();
898               if (loc->disabled_by_cond && loc->enabled)
899                 printf_filtered (_("Breakpoint %d's condition is now valid at "
900                                    "location %d, enabling.\n"),
901                                  b->number, loc_num);
902               loc->disabled_by_cond = false;
903               loc_num++;
904
905               /* No need to free the condition agent expression
906                  bytecode (if we have one).  We will handle this
907                  when we go through update_global_location_list.  */
908             }
909         }
910
911       if (from_tty)
912         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
913     }
914   else
915     {
916       if (is_watchpoint (b))
917         {
918           innermost_block_tracker tracker;
919           const char *arg = exp;
920           expression_up new_exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
921           if (*arg != 0)
922             error (_("Junk at end of expression"));
923           watchpoint *w = static_cast<watchpoint *> (b);
924           w->cond_exp = std::move (new_exp);
925           w->cond_exp_valid_block = tracker.block ();
926         }
927       else
928         {
929           /* Parse and set condition expressions.  We make two passes.
930              In the first, we parse the condition string to see if it
931              is valid in at least one location.  If so, the condition
932              would be accepted.  So we go ahead and set the locations'
933              conditions.  In case no valid case is found, we throw
934              the error and the condition string will be rejected.
935              This two-pass approach is taken to avoid setting the
936              state of locations in case of a reject.  */
937           for (bp_location *loc = b->loc; loc != nullptr; loc = loc->next)
938             {
939               try
940                 {
941                   const char *arg = exp;
942                   parse_exp_1 (&arg, loc->address,
943                                block_for_pc (loc->address), 0);
944                   if (*arg != 0)
945                     error (_("Junk at end of expression"));
946                   break;
947                 }
948               catch (const gdb_exception_error &e)
949                 {
950                   /* Condition string is invalid.  If this happens to
951                      be the last loc, abandon (if not forced) or continue
952                      (if forced).  */
953                   if (loc->next == nullptr && !force)
954                     throw;
955                 }
956             }
957
958           /* If we reach here, the condition is valid at some locations.  */
959           int loc_num = 1;
960           for (bp_location *loc = b->loc; loc != nullptr;
961                loc = loc->next, loc_num++)
962             set_breakpoint_location_condition (exp, loc, b->number, loc_num);
963         }
964
965       /* We know that the new condition parsed successfully.  The
966          condition string of the breakpoint can be safely updated.  */
967       xfree (b->cond_string);
968       b->cond_string = xstrdup (exp);
969       b->condition_not_parsed = 0;
970     }
971   mark_breakpoint_modified (b);
972
973   gdb::observers::breakpoint_modified.notify (b);
974 }
975
976 /* The options for the "condition" command.  */
977
978 struct condition_command_opts
979 {
980   /* For "-force".  */
981   bool force_condition = false;
982 };
983
984 static const gdb::option::option_def condition_command_option_defs[] = {
985
986   gdb::option::flag_option_def<condition_command_opts> {
987     "force",
988     [] (condition_command_opts *opts) { return &opts->force_condition; },
989     N_("Set the condition even if it is invalid for all current locations."),
990   },
991
992 };
993
994 /* Create an option_def_group for the "condition" options, with
995    CC_OPTS as context.  */
996
997 static inline gdb::option::option_def_group
998 make_condition_command_options_def_group (condition_command_opts *cc_opts)
999 {
1000   return {{condition_command_option_defs}, cc_opts};
1001 }
1002
1003 /* Completion for the "condition" command.  */
1004
1005 static void
1006 condition_completer (struct cmd_list_element *cmd,
1007                      completion_tracker &tracker,
1008                      const char *text, const char * /*word*/)
1009 {
1010   bool has_no_arguments = (*text == '\0');
1011   condition_command_opts cc_opts;
1012   const auto group = make_condition_command_options_def_group (&cc_opts);
1013   if (gdb::option::complete_options
1014       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
1015     return;
1016
1017   text = skip_spaces (text);
1018   const char *space = skip_to_space (text);
1019   if (*space == '\0')
1020     {
1021       int len;
1022       struct breakpoint *b;
1023
1024       if (text[0] == '$')
1025         {
1026           tracker.advance_custom_word_point_by (1);
1027           /* We don't support completion of history indices.  */
1028           if (!isdigit (text[1]))
1029             complete_internalvar (tracker, &text[1]);
1030           return;
1031         }
1032
1033       /* Suggest the "-force" flag if no arguments are given.  If
1034          arguments were passed, they either already include the flag,
1035          or we are beyond the point of suggesting it because it's
1036          positionally the first argument.  */
1037       if (has_no_arguments)
1038         gdb::option::complete_on_all_options (tracker, group);
1039
1040       /* We're completing the breakpoint number.  */
1041       len = strlen (text);
1042
1043       ALL_BREAKPOINTS (b)
1044         {
1045           char number[50];
1046
1047           xsnprintf (number, sizeof (number), "%d", b->number);
1048
1049           if (strncmp (number, text, len) == 0)
1050             tracker.add_completion (make_unique_xstrdup (number));
1051         }
1052
1053       return;
1054     }
1055
1056   /* We're completing the expression part.  Skip the breakpoint num.  */
1057   const char *exp_start = skip_spaces (space);
1058   tracker.advance_custom_word_point_by (exp_start - text);
1059   text = exp_start;
1060   const char *word = advance_to_expression_complete_word_point (tracker, text);
1061   expression_completer (cmd, tracker, text, word);
1062 }
1063
1064 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1065
1066 static void
1067 condition_command (const char *arg, int from_tty)
1068 {
1069   struct breakpoint *b;
1070   const char *p;
1071   int bnum;
1072
1073   if (arg == 0)
1074     error_no_arg (_("breakpoint number"));
1075
1076   p = arg;
1077
1078   /* Check if the "-force" flag was passed.  */
1079   condition_command_opts cc_opts;
1080   const auto group = make_condition_command_options_def_group (&cc_opts);
1081   gdb::option::process_options
1082     (&p, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
1083
1084   bnum = get_number (&p);
1085   if (bnum == 0)
1086     error (_("Bad breakpoint argument: '%s'"), arg);
1087
1088   ALL_BREAKPOINTS (b)
1089     if (b->number == bnum)
1090       {
1091         /* Check if this breakpoint has a "stop" method implemented in an
1092            extension language.  This method and conditions entered into GDB
1093            from the CLI are mutually exclusive.  */
1094         const struct extension_language_defn *extlang
1095           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1096
1097         if (extlang != NULL)
1098           {
1099             error (_("Only one stop condition allowed.  There is currently"
1100                      " a %s stop condition defined for this breakpoint."),
1101                    ext_lang_capitalized_name (extlang));
1102           }
1103         set_breakpoint_condition (b, p, from_tty, cc_opts.force_condition);
1104
1105         if (is_breakpoint (b))
1106           update_global_location_list (UGLL_MAY_INSERT);
1107
1108         return;
1109       }
1110
1111   error (_("No breakpoint number %d."), bnum);
1112 }
1113
1114 /* Check that COMMAND do not contain commands that are suitable
1115    only for tracepoints and not suitable for ordinary breakpoints.
1116    Throw if any such commands is found.  */
1117
1118 static void
1119 check_no_tracepoint_commands (struct command_line *commands)
1120 {
1121   struct command_line *c;
1122
1123   for (c = commands; c; c = c->next)
1124     {
1125       if (c->control_type == while_stepping_control)
1126         error (_("The 'while-stepping' command can "
1127                  "only be used for tracepoints"));
1128
1129       check_no_tracepoint_commands (c->body_list_0.get ());
1130       check_no_tracepoint_commands (c->body_list_1.get ());
1131
1132       /* Not that command parsing removes leading whitespace and comment
1133          lines and also empty lines.  So, we only need to check for
1134          command directly.  */
1135       if (strstr (c->line, "collect ") == c->line)
1136         error (_("The 'collect' command can only be used for tracepoints"));
1137
1138       if (strstr (c->line, "teval ") == c->line)
1139         error (_("The 'teval' command can only be used for tracepoints"));
1140     }
1141 }
1142
1143 struct longjmp_breakpoint : public breakpoint
1144 {
1145   ~longjmp_breakpoint () override;
1146 };
1147
1148 /* Encapsulate tests for different types of tracepoints.  */
1149
1150 static bool
1151 is_tracepoint_type (bptype type)
1152 {
1153   return (type == bp_tracepoint
1154           || type == bp_fast_tracepoint
1155           || type == bp_static_tracepoint);
1156 }
1157
1158 static bool
1159 is_longjmp_type (bptype type)
1160 {
1161   return type == bp_longjmp || type == bp_exception;
1162 }
1163
1164 /* See breakpoint.h.  */
1165
1166 bool
1167 is_tracepoint (const struct breakpoint *b)
1168 {
1169   return is_tracepoint_type (b->type);
1170 }
1171
1172 /* Factory function to create an appropriate instance of breakpoint given
1173    TYPE.  */
1174
1175 static std::unique_ptr<breakpoint>
1176 new_breakpoint_from_type (bptype type)
1177 {
1178   breakpoint *b;
1179
1180   if (is_tracepoint_type (type))
1181     b = new tracepoint ();
1182   else if (is_longjmp_type (type))
1183     b = new longjmp_breakpoint ();
1184   else
1185     b = new breakpoint ();
1186
1187   return std::unique_ptr<breakpoint> (b);
1188 }
1189
1190 /* A helper function that validates that COMMANDS are valid for a
1191    breakpoint.  This function will throw an exception if a problem is
1192    found.  */
1193
1194 static void
1195 validate_commands_for_breakpoint (struct breakpoint *b,
1196                                   struct command_line *commands)
1197 {
1198   if (is_tracepoint (b))
1199     {
1200       struct tracepoint *t = (struct tracepoint *) b;
1201       struct command_line *c;
1202       struct command_line *while_stepping = 0;
1203
1204       /* Reset the while-stepping step count.  The previous commands
1205          might have included a while-stepping action, while the new
1206          ones might not.  */
1207       t->step_count = 0;
1208
1209       /* We need to verify that each top-level element of commands is
1210          valid for tracepoints, that there's at most one
1211          while-stepping element, and that the while-stepping's body
1212          has valid tracing commands excluding nested while-stepping.
1213          We also need to validate the tracepoint action line in the
1214          context of the tracepoint --- validate_actionline actually
1215          has side effects, like setting the tracepoint's
1216          while-stepping STEP_COUNT, in addition to checking if the
1217          collect/teval actions parse and make sense in the
1218          tracepoint's context.  */
1219       for (c = commands; c; c = c->next)
1220         {
1221           if (c->control_type == while_stepping_control)
1222             {
1223               if (b->type == bp_fast_tracepoint)
1224                 error (_("The 'while-stepping' command "
1225                          "cannot be used for fast tracepoint"));
1226               else if (b->type == bp_static_tracepoint)
1227                 error (_("The 'while-stepping' command "
1228                          "cannot be used for static tracepoint"));
1229
1230               if (while_stepping)
1231                 error (_("The 'while-stepping' command "
1232                          "can be used only once"));
1233               else
1234                 while_stepping = c;
1235             }
1236
1237           validate_actionline (c->line, b);
1238         }
1239       if (while_stepping)
1240         {
1241           struct command_line *c2;
1242
1243           gdb_assert (while_stepping->body_list_1 == nullptr);
1244           c2 = while_stepping->body_list_0.get ();
1245           for (; c2; c2 = c2->next)
1246             {
1247               if (c2->control_type == while_stepping_control)
1248                 error (_("The 'while-stepping' command cannot be nested"));
1249             }
1250         }
1251     }
1252   else
1253     {
1254       check_no_tracepoint_commands (commands);
1255     }
1256 }
1257
1258 /* Return a vector of all the static tracepoints set at ADDR.  The
1259    caller is responsible for releasing the vector.  */
1260
1261 std::vector<breakpoint *>
1262 static_tracepoints_here (CORE_ADDR addr)
1263 {
1264   struct breakpoint *b;
1265   std::vector<breakpoint *> found;
1266   struct bp_location *loc;
1267
1268   ALL_BREAKPOINTS (b)
1269     if (b->type == bp_static_tracepoint)
1270       {
1271         for (loc = b->loc; loc; loc = loc->next)
1272           if (loc->address == addr)
1273             found.push_back (b);
1274       }
1275
1276   return found;
1277 }
1278
1279 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1280    validate that only allowed commands are included.  */
1281
1282 void
1283 breakpoint_set_commands (struct breakpoint *b, 
1284                          counted_command_line &&commands)
1285 {
1286   validate_commands_for_breakpoint (b, commands.get ());
1287
1288   b->commands = std::move (commands);
1289   gdb::observers::breakpoint_modified.notify (b);
1290 }
1291
1292 /* Set the internal `silent' flag on the breakpoint.  Note that this
1293    is not the same as the "silent" that may appear in the breakpoint's
1294    commands.  */
1295
1296 void
1297 breakpoint_set_silent (struct breakpoint *b, int silent)
1298 {
1299   int old_silent = b->silent;
1300
1301   b->silent = silent;
1302   if (old_silent != silent)
1303     gdb::observers::breakpoint_modified.notify (b);
1304 }
1305
1306 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1307    breakpoint work for any thread.  */
1308
1309 void
1310 breakpoint_set_thread (struct breakpoint *b, int thread)
1311 {
1312   int old_thread = b->thread;
1313
1314   b->thread = thread;
1315   if (old_thread != thread)
1316     gdb::observers::breakpoint_modified.notify (b);
1317 }
1318
1319 /* Set the task for this breakpoint.  If TASK is 0, make the
1320    breakpoint work for any task.  */
1321
1322 void
1323 breakpoint_set_task (struct breakpoint *b, int task)
1324 {
1325   int old_task = b->task;
1326
1327   b->task = task;
1328   if (old_task != task)
1329     gdb::observers::breakpoint_modified.notify (b);
1330 }
1331
1332 static void
1333 commands_command_1 (const char *arg, int from_tty,
1334                     struct command_line *control)
1335 {
1336   counted_command_line cmd;
1337   /* cmd_read will be true once we have read cmd.  Note that cmd might still be
1338      NULL after the call to read_command_lines if the user provides an empty
1339      list of command by just typing "end".  */
1340   bool cmd_read = false;
1341
1342   std::string new_arg;
1343
1344   if (arg == NULL || !*arg)
1345     {
1346       /* Argument not explicitly given.  Synthesize it.  */
1347       if (breakpoint_count - prev_breakpoint_count > 1)
1348         new_arg = string_printf ("%d-%d", prev_breakpoint_count + 1,
1349                                  breakpoint_count);
1350       else if (breakpoint_count > 0)
1351         new_arg = string_printf ("%d", breakpoint_count);
1352     }
1353   else
1354     {
1355       /* Create a copy of ARG.  This is needed because the "commands"
1356          command may be coming from a script.  In that case, the read
1357          line buffer is going to be overwritten in the lambda of
1358          'map_breakpoint_numbers' below when reading the next line
1359          before we are are done parsing the breakpoint numbers.  */
1360       new_arg = arg;
1361     }
1362   arg = new_arg.c_str ();
1363
1364   map_breakpoint_numbers
1365     (arg, [&] (breakpoint *b)
1366      {
1367        if (!cmd_read)
1368          {
1369            gdb_assert (cmd == NULL);
1370            if (control != NULL)
1371              cmd = control->body_list_0;
1372            else
1373              {
1374                std::string str
1375                  = string_printf (_("Type commands for breakpoint(s) "
1376                                     "%s, one per line."),
1377                                   arg);
1378
1379                auto do_validate = [=] (const char *line)
1380                                   {
1381                                     validate_actionline (line, b);
1382                                   };
1383                gdb::function_view<void (const char *)> validator;
1384                if (is_tracepoint (b))
1385                  validator = do_validate;
1386
1387                cmd = read_command_lines (str.c_str (), from_tty, 1, validator);
1388              }
1389            cmd_read = true;
1390          }
1391
1392        /* If a breakpoint was on the list more than once, we don't need to
1393           do anything.  */
1394        if (b->commands != cmd)
1395          {
1396            validate_commands_for_breakpoint (b, cmd.get ());
1397            b->commands = cmd;
1398            gdb::observers::breakpoint_modified.notify (b);
1399          }
1400      });
1401 }
1402
1403 static void
1404 commands_command (const char *arg, int from_tty)
1405 {
1406   commands_command_1 (arg, from_tty, NULL);
1407 }
1408
1409 /* Like commands_command, but instead of reading the commands from
1410    input stream, takes them from an already parsed command structure.
1411
1412    This is used by cli-script.c to DTRT with breakpoint commands
1413    that are part of if and while bodies.  */
1414 enum command_control_type
1415 commands_from_control_command (const char *arg, struct command_line *cmd)
1416 {
1417   commands_command_1 (arg, 0, cmd);
1418   return simple_control;
1419 }
1420
1421 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1422
1423 static int
1424 bp_location_has_shadow (struct bp_location *bl)
1425 {
1426   if (bl->loc_type != bp_loc_software_breakpoint)
1427     return 0;
1428   if (!bl->inserted)
1429     return 0;
1430   if (bl->target_info.shadow_len == 0)
1431     /* BL isn't valid, or doesn't shadow memory.  */
1432     return 0;
1433   return 1;
1434 }
1435
1436 /* Update BUF, which is LEN bytes read from the target address
1437    MEMADDR, by replacing a memory breakpoint with its shadowed
1438    contents.
1439
1440    If READBUF is not NULL, this buffer must not overlap with the of
1441    the breakpoint location's shadow_contents buffer.  Otherwise, a
1442    failed assertion internal error will be raised.  */
1443
1444 static void
1445 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1446                             const gdb_byte *writebuf_org,
1447                             ULONGEST memaddr, LONGEST len,
1448                             struct bp_target_info *target_info,
1449                             struct gdbarch *gdbarch)
1450 {
1451   /* Now do full processing of the found relevant range of elements.  */
1452   CORE_ADDR bp_addr = 0;
1453   int bp_size = 0;
1454   int bptoffset = 0;
1455
1456   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1457                                  current_program_space->aspace, 0))
1458     {
1459       /* The breakpoint is inserted in a different address space.  */
1460       return;
1461     }
1462
1463   /* Addresses and length of the part of the breakpoint that
1464      we need to copy.  */
1465   bp_addr = target_info->placed_address;
1466   bp_size = target_info->shadow_len;
1467
1468   if (bp_addr + bp_size <= memaddr)
1469     {
1470       /* The breakpoint is entirely before the chunk of memory we are
1471          reading.  */
1472       return;
1473     }
1474
1475   if (bp_addr >= memaddr + len)
1476     {
1477       /* The breakpoint is entirely after the chunk of memory we are
1478          reading.  */
1479       return;
1480     }
1481
1482   /* Offset within shadow_contents.  */
1483   if (bp_addr < memaddr)
1484     {
1485       /* Only copy the second part of the breakpoint.  */
1486       bp_size -= memaddr - bp_addr;
1487       bptoffset = memaddr - bp_addr;
1488       bp_addr = memaddr;
1489     }
1490
1491   if (bp_addr + bp_size > memaddr + len)
1492     {
1493       /* Only copy the first part of the breakpoint.  */
1494       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1495     }
1496
1497   if (readbuf != NULL)
1498     {
1499       /* Verify that the readbuf buffer does not overlap with the
1500          shadow_contents buffer.  */
1501       gdb_assert (target_info->shadow_contents >= readbuf + len
1502                   || readbuf >= (target_info->shadow_contents
1503                                  + target_info->shadow_len));
1504
1505       /* Update the read buffer with this inserted breakpoint's
1506          shadow.  */
1507       memcpy (readbuf + bp_addr - memaddr,
1508               target_info->shadow_contents + bptoffset, bp_size);
1509     }
1510   else
1511     {
1512       const unsigned char *bp;
1513       CORE_ADDR addr = target_info->reqstd_address;
1514       int placed_size;
1515
1516       /* Update the shadow with what we want to write to memory.  */
1517       memcpy (target_info->shadow_contents + bptoffset,
1518               writebuf_org + bp_addr - memaddr, bp_size);
1519
1520       /* Determine appropriate breakpoint contents and size for this
1521          address.  */
1522       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1523
1524       /* Update the final write buffer with this inserted
1525          breakpoint's INSN.  */
1526       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1527     }
1528 }
1529
1530 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1531    by replacing any memory breakpoints with their shadowed contents.
1532
1533    If READBUF is not NULL, this buffer must not overlap with any of
1534    the breakpoint location's shadow_contents buffers.  Otherwise,
1535    a failed assertion internal error will be raised.
1536
1537    The range of shadowed area by each bp_location is:
1538      bl->address - bp_locations_placed_address_before_address_max
1539      up to bl->address + bp_locations_shadow_len_after_address_max
1540    The range we were requested to resolve shadows for is:
1541      memaddr ... memaddr + len
1542    Thus the safe cutoff boundaries for performance optimization are
1543      memaddr + len <= (bl->address
1544                        - bp_locations_placed_address_before_address_max)
1545    and:
1546      bl->address + bp_locations_shadow_len_after_address_max <= memaddr  */
1547
1548 void
1549 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1550                         const gdb_byte *writebuf_org,
1551                         ULONGEST memaddr, LONGEST len)
1552 {
1553   /* Left boundary, right boundary and median element of our binary
1554      search.  */
1555   unsigned bc_l, bc_r, bc;
1556
1557   /* Find BC_L which is a leftmost element which may affect BUF
1558      content.  It is safe to report lower value but a failure to
1559      report higher one.  */
1560
1561   bc_l = 0;
1562   bc_r = bp_locations_count;
1563   while (bc_l + 1 < bc_r)
1564     {
1565       struct bp_location *bl;
1566
1567       bc = (bc_l + bc_r) / 2;
1568       bl = bp_locations[bc];
1569
1570       /* Check first BL->ADDRESS will not overflow due to the added
1571          constant.  Then advance the left boundary only if we are sure
1572          the BC element can in no way affect the BUF content (MEMADDR
1573          to MEMADDR + LEN range).
1574
1575          Use the BP_LOCATIONS_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1576          offset so that we cannot miss a breakpoint with its shadow
1577          range tail still reaching MEMADDR.  */
1578
1579       if ((bl->address + bp_locations_shadow_len_after_address_max
1580            >= bl->address)
1581           && (bl->address + bp_locations_shadow_len_after_address_max
1582               <= memaddr))
1583         bc_l = bc;
1584       else
1585         bc_r = bc;
1586     }
1587
1588   /* Due to the binary search above, we need to make sure we pick the
1589      first location that's at BC_L's address.  E.g., if there are
1590      multiple locations at the same address, BC_L may end up pointing
1591      at a duplicate location, and miss the "master"/"inserted"
1592      location.  Say, given locations L1, L2 and L3 at addresses A and
1593      B:
1594
1595       L1@A, L2@A, L3@B, ...
1596
1597      BC_L could end up pointing at location L2, while the "master"
1598      location could be L1.  Since the `loc->inserted' flag is only set
1599      on "master" locations, we'd forget to restore the shadow of L1
1600      and L2.  */
1601   while (bc_l > 0
1602          && bp_locations[bc_l]->address == bp_locations[bc_l - 1]->address)
1603     bc_l--;
1604
1605   /* Now do full processing of the found relevant range of elements.  */
1606
1607   for (bc = bc_l; bc < bp_locations_count; bc++)
1608   {
1609     struct bp_location *bl = bp_locations[bc];
1610
1611     /* bp_location array has BL->OWNER always non-NULL.  */
1612     if (bl->owner->type == bp_none)
1613       warning (_("reading through apparently deleted breakpoint #%d?"),
1614                bl->owner->number);
1615
1616     /* Performance optimization: any further element can no longer affect BUF
1617        content.  */
1618
1619     if (bl->address >= bp_locations_placed_address_before_address_max
1620         && memaddr + len <= (bl->address
1621                              - bp_locations_placed_address_before_address_max))
1622       break;
1623
1624     if (!bp_location_has_shadow (bl))
1625       continue;
1626
1627     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1628                                 memaddr, len, &bl->target_info, bl->gdbarch);
1629   }
1630 }
1631
1632 /* See breakpoint.h.  */
1633
1634 bool
1635 is_breakpoint (const struct breakpoint *bpt)
1636 {
1637   return (bpt->type == bp_breakpoint
1638           || bpt->type == bp_hardware_breakpoint
1639           || bpt->type == bp_dprintf);
1640 }
1641
1642 /* Return true if BPT is of any hardware watchpoint kind.  */
1643
1644 static bool
1645 is_hardware_watchpoint (const struct breakpoint *bpt)
1646 {
1647   return (bpt->type == bp_hardware_watchpoint
1648           || bpt->type == bp_read_watchpoint
1649           || bpt->type == bp_access_watchpoint);
1650 }
1651
1652 /* See breakpoint.h.  */
1653
1654 bool
1655 is_watchpoint (const struct breakpoint *bpt)
1656 {
1657   return (is_hardware_watchpoint (bpt)
1658           || bpt->type == bp_watchpoint);
1659 }
1660
1661 /* Returns true if the current thread and its running state are safe
1662    to evaluate or update watchpoint B.  Watchpoints on local
1663    expressions need to be evaluated in the context of the thread that
1664    was current when the watchpoint was created, and, that thread needs
1665    to be stopped to be able to select the correct frame context.
1666    Watchpoints on global expressions can be evaluated on any thread,
1667    and in any state.  It is presently left to the target allowing
1668    memory accesses when threads are running.  */
1669
1670 static int
1671 watchpoint_in_thread_scope (struct watchpoint *b)
1672 {
1673   return (b->pspace == current_program_space
1674           && (b->watchpoint_thread == null_ptid
1675               || (inferior_ptid == b->watchpoint_thread
1676                   && !inferior_thread ()->executing)));
1677 }
1678
1679 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1680    associated bp_watchpoint_scope breakpoint.  */
1681
1682 static void
1683 watchpoint_del_at_next_stop (struct watchpoint *w)
1684 {
1685   if (w->related_breakpoint != w)
1686     {
1687       gdb_assert (w->related_breakpoint->type == bp_watchpoint_scope);
1688       gdb_assert (w->related_breakpoint->related_breakpoint == w);
1689       w->related_breakpoint->disposition = disp_del_at_next_stop;
1690       w->related_breakpoint->related_breakpoint = w->related_breakpoint;
1691       w->related_breakpoint = w;
1692     }
1693   w->disposition = disp_del_at_next_stop;
1694 }
1695
1696 /* Extract a bitfield value from value VAL using the bit parameters contained in
1697    watchpoint W.  */
1698
1699 static struct value *
1700 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1701 {
1702   struct value *bit_val;
1703
1704   if (val == NULL)
1705     return NULL;
1706
1707   bit_val = allocate_value (value_type (val));
1708
1709   unpack_value_bitfield (bit_val,
1710                          w->val_bitpos,
1711                          w->val_bitsize,
1712                          value_contents_for_printing (val),
1713                          value_offset (val),
1714                          val);
1715
1716   return bit_val;
1717 }
1718
1719 /* Allocate a dummy location and add it to B, which must be a software
1720    watchpoint.  This is required because even if a software watchpoint
1721    is not watching any memory, bpstat_stop_status requires a location
1722    to be able to report stops.  */
1723
1724 static void
1725 software_watchpoint_add_no_memory_location (struct breakpoint *b,
1726                                             struct program_space *pspace)
1727 {
1728   gdb_assert (b->type == bp_watchpoint && b->loc == NULL);
1729
1730   b->loc = allocate_bp_location (b);
1731   b->loc->pspace = pspace;
1732   b->loc->address = -1;
1733   b->loc->length = -1;
1734 }
1735
1736 /* Returns true if B is a software watchpoint that is not watching any
1737    memory (e.g., "watch $pc").  */
1738
1739 static bool
1740 is_no_memory_software_watchpoint (struct breakpoint *b)
1741 {
1742   return (b->type == bp_watchpoint
1743           && b->loc != NULL
1744           && b->loc->next == NULL
1745           && b->loc->address == -1
1746           && b->loc->length == -1);
1747 }
1748
1749 /* Assuming that B is a watchpoint:
1750    - Reparse watchpoint expression, if REPARSE is non-zero
1751    - Evaluate expression and store the result in B->val
1752    - Evaluate the condition if there is one, and store the result
1753      in b->loc->cond.
1754    - Update the list of values that must be watched in B->loc.
1755
1756    If the watchpoint disposition is disp_del_at_next_stop, then do
1757    nothing.  If this is local watchpoint that is out of scope, delete
1758    it.
1759
1760    Even with `set breakpoint always-inserted on' the watchpoints are
1761    removed + inserted on each stop here.  Normal breakpoints must
1762    never be removed because they might be missed by a running thread
1763    when debugging in non-stop mode.  On the other hand, hardware
1764    watchpoints (is_hardware_watchpoint; processed here) are specific
1765    to each LWP since they are stored in each LWP's hardware debug
1766    registers.  Therefore, such LWP must be stopped first in order to
1767    be able to modify its hardware watchpoints.
1768
1769    Hardware watchpoints must be reset exactly once after being
1770    presented to the user.  It cannot be done sooner, because it would
1771    reset the data used to present the watchpoint hit to the user.  And
1772    it must not be done later because it could display the same single
1773    watchpoint hit during multiple GDB stops.  Note that the latter is
1774    relevant only to the hardware watchpoint types bp_read_watchpoint
1775    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1776    not user-visible - its hit is suppressed if the memory content has
1777    not changed.
1778
1779    The following constraints influence the location where we can reset
1780    hardware watchpoints:
1781
1782    * target_stopped_by_watchpoint and target_stopped_data_address are
1783      called several times when GDB stops.
1784
1785    [linux] 
1786    * Multiple hardware watchpoints can be hit at the same time,
1787      causing GDB to stop.  GDB only presents one hardware watchpoint
1788      hit at a time as the reason for stopping, and all the other hits
1789      are presented later, one after the other, each time the user
1790      requests the execution to be resumed.  Execution is not resumed
1791      for the threads still having pending hit event stored in
1792      LWP_INFO->STATUS.  While the watchpoint is already removed from
1793      the inferior on the first stop the thread hit event is kept being
1794      reported from its cached value by linux_nat_stopped_data_address
1795      until the real thread resume happens after the watchpoint gets
1796      presented and thus its LWP_INFO->STATUS gets reset.
1797
1798    Therefore the hardware watchpoint hit can get safely reset on the
1799    watchpoint removal from inferior.  */
1800
1801 static void
1802 update_watchpoint (struct watchpoint *b, int reparse)
1803 {
1804   int within_current_scope;
1805   struct frame_id saved_frame_id;
1806   int frame_saved;
1807
1808   /* If this is a local watchpoint, we only want to check if the
1809      watchpoint frame is in scope if the current thread is the thread
1810      that was used to create the watchpoint.  */
1811   if (!watchpoint_in_thread_scope (b))
1812     return;
1813
1814   if (b->disposition == disp_del_at_next_stop)
1815     return;
1816  
1817   frame_saved = 0;
1818
1819   /* Determine if the watchpoint is within scope.  */
1820   if (b->exp_valid_block == NULL)
1821     within_current_scope = 1;
1822   else
1823     {
1824       struct frame_info *fi = get_current_frame ();
1825       struct gdbarch *frame_arch = get_frame_arch (fi);
1826       CORE_ADDR frame_pc = get_frame_pc (fi);
1827
1828       /* If we're at a point where the stack has been destroyed
1829          (e.g. in a function epilogue), unwinding may not work
1830          properly. Do not attempt to recreate locations at this
1831          point.  See similar comments in watchpoint_check.  */
1832       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
1833         return;
1834
1835       /* Save the current frame's ID so we can restore it after
1836          evaluating the watchpoint expression on its own frame.  */
1837       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1838          took a frame parameter, so that we didn't have to change the
1839          selected frame.  */
1840       frame_saved = 1;
1841       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1842
1843       fi = frame_find_by_id (b->watchpoint_frame);
1844       within_current_scope = (fi != NULL);
1845       if (within_current_scope)
1846         select_frame (fi);
1847     }
1848
1849   /* We don't free locations.  They are stored in the bp_location array
1850      and update_global_location_list will eventually delete them and
1851      remove breakpoints if needed.  */
1852   b->loc = NULL;
1853
1854   if (within_current_scope && reparse)
1855     {
1856       const char *s;
1857
1858       b->exp.reset ();
1859       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1860       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1861       /* If the meaning of expression itself changed, the old value is
1862          no longer relevant.  We don't want to report a watchpoint hit
1863          to the user when the old value and the new value may actually
1864          be completely different objects.  */
1865       b->val = NULL;
1866       b->val_valid = false;
1867
1868       /* Note that unlike with breakpoints, the watchpoint's condition
1869          expression is stored in the breakpoint object, not in the
1870          locations (re)created below.  */
1871       if (b->cond_string != NULL)
1872         {
1873           b->cond_exp.reset ();
1874
1875           s = b->cond_string;
1876           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1877         }
1878     }
1879
1880   /* If we failed to parse the expression, for example because
1881      it refers to a global variable in a not-yet-loaded shared library,
1882      don't try to insert watchpoint.  We don't automatically delete
1883      such watchpoint, though, since failure to parse expression
1884      is different from out-of-scope watchpoint.  */
1885   if (!target_has_execution ())
1886     {
1887       /* Without execution, memory can't change.  No use to try and
1888          set watchpoint locations.  The watchpoint will be reset when
1889          the target gains execution, through breakpoint_re_set.  */
1890       if (!can_use_hw_watchpoints)
1891         {
1892           if (b->ops->works_in_software_mode (b))
1893             b->type = bp_watchpoint;
1894           else
1895             error (_("Can't set read/access watchpoint when "
1896                      "hardware watchpoints are disabled."));
1897         }
1898     }
1899   else if (within_current_scope && b->exp)
1900     {
1901       int pc = 0;
1902       std::vector<value_ref_ptr> val_chain;
1903       struct value *v, *result;
1904       struct program_space *frame_pspace;
1905
1906       fetch_subexp_value (b->exp.get (), &pc, &v, &result, &val_chain, false);
1907
1908       /* Avoid setting b->val if it's already set.  The meaning of
1909          b->val is 'the last value' user saw, and we should update
1910          it only if we reported that last value to user.  As it
1911          happens, the code that reports it updates b->val directly.
1912          We don't keep track of the memory value for masked
1913          watchpoints.  */
1914       if (!b->val_valid && !is_masked_watchpoint (b))
1915         {
1916           if (b->val_bitsize != 0)
1917             v = extract_bitfield_from_watchpoint_value (b, v);
1918           b->val = release_value (v);
1919           b->val_valid = true;
1920         }
1921
1922       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1923
1924       /* Look at each value on the value chain.  */
1925       gdb_assert (!val_chain.empty ());
1926       for (const value_ref_ptr &iter : val_chain)
1927         {
1928           v = iter.get ();
1929
1930           /* If it's a memory location, and GDB actually needed
1931              its contents to evaluate the expression, then we
1932              must watch it.  If the first value returned is
1933              still lazy, that means an error occurred reading it;
1934              watch it anyway in case it becomes readable.  */
1935           if (VALUE_LVAL (v) == lval_memory
1936               && (v == val_chain[0] || ! value_lazy (v)))
1937             {
1938               struct type *vtype = check_typedef (value_type (v));
1939
1940               /* We only watch structs and arrays if user asked
1941                  for it explicitly, never if they just happen to
1942                  appear in the middle of some value chain.  */
1943               if (v == result
1944                   || (vtype->code () != TYPE_CODE_STRUCT
1945                       && vtype->code () != TYPE_CODE_ARRAY))
1946                 {
1947                   CORE_ADDR addr;
1948                   enum target_hw_bp_type type;
1949                   struct bp_location *loc, **tmp;
1950                   int bitpos = 0, bitsize = 0;
1951
1952                   if (value_bitsize (v) != 0)
1953                     {
1954                       /* Extract the bit parameters out from the bitfield
1955                          sub-expression.  */
1956                       bitpos = value_bitpos (v);
1957                       bitsize = value_bitsize (v);
1958                     }
1959                   else if (v == result && b->val_bitsize != 0)
1960                     {
1961                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1962                         lvalue whose bit parameters are saved in the fields
1963                         VAL_BITPOS and VAL_BITSIZE.  */
1964                       bitpos = b->val_bitpos;
1965                       bitsize = b->val_bitsize;
1966                     }
1967
1968                   addr = value_address (v);
1969                   if (bitsize != 0)
1970                     {
1971                       /* Skip the bytes that don't contain the bitfield.  */
1972                       addr += bitpos / 8;
1973                     }
1974
1975                   type = hw_write;
1976                   if (b->type == bp_read_watchpoint)
1977                     type = hw_read;
1978                   else if (b->type == bp_access_watchpoint)
1979                     type = hw_access;
1980
1981                   loc = allocate_bp_location (b);
1982                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1983                     ;
1984                   *tmp = loc;
1985                   loc->gdbarch = get_type_arch (value_type (v));
1986
1987                   loc->pspace = frame_pspace;
1988                   loc->address = address_significant (loc->gdbarch, addr);
1989
1990                   if (bitsize != 0)
1991                     {
1992                       /* Just cover the bytes that make up the bitfield.  */
1993                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
1994                     }
1995                   else
1996                     loc->length = TYPE_LENGTH (value_type (v));
1997
1998                   loc->watchpoint_type = type;
1999                 }
2000             }
2001         }
2002
2003       /* Change the type of breakpoint between hardware assisted or
2004          an ordinary watchpoint depending on the hardware support
2005          and free hardware slots.  REPARSE is set when the inferior
2006          is started.  */
2007       if (reparse)
2008         {
2009           int reg_cnt;
2010           enum bp_loc_type loc_type;
2011           struct bp_location *bl;
2012
2013           reg_cnt = can_use_hardware_watchpoint (val_chain);
2014
2015           if (reg_cnt)
2016             {
2017               int i, target_resources_ok, other_type_used;
2018               enum bptype type;
2019
2020               /* Use an exact watchpoint when there's only one memory region to be
2021                  watched, and only one debug register is needed to watch it.  */
2022               b->exact = target_exact_watchpoints && reg_cnt == 1;
2023
2024               /* We need to determine how many resources are already
2025                  used for all other hardware watchpoints plus this one
2026                  to see if we still have enough resources to also fit
2027                  this watchpoint in as well.  */
2028
2029               /* If this is a software watchpoint, we try to turn it
2030                  to a hardware one -- count resources as if B was of
2031                  hardware watchpoint type.  */
2032               type = b->type;
2033               if (type == bp_watchpoint)
2034                 type = bp_hardware_watchpoint;
2035
2036               /* This watchpoint may or may not have been placed on
2037                  the list yet at this point (it won't be in the list
2038                  if we're trying to create it for the first time,
2039                  through watch_command), so always account for it
2040                  manually.  */
2041
2042               /* Count resources used by all watchpoints except B.  */
2043               i = hw_watchpoint_used_count_others (b, type, &other_type_used);
2044
2045               /* Add in the resources needed for B.  */
2046               i += hw_watchpoint_use_count (b);
2047
2048               target_resources_ok
2049                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2050               if (target_resources_ok <= 0)
2051                 {
2052                   int sw_mode = b->ops->works_in_software_mode (b);
2053
2054                   if (target_resources_ok == 0 && !sw_mode)
2055                     error (_("Target does not support this type of "
2056                              "hardware watchpoint."));
2057                   else if (target_resources_ok < 0 && !sw_mode)
2058                     error (_("There are not enough available hardware "
2059                              "resources for this watchpoint."));
2060
2061                   /* Downgrade to software watchpoint.  */
2062                   b->type = bp_watchpoint;
2063                 }
2064               else
2065                 {
2066                   /* If this was a software watchpoint, we've just
2067                      found we have enough resources to turn it to a
2068                      hardware watchpoint.  Otherwise, this is a
2069                      nop.  */
2070                   b->type = type;
2071                 }
2072             }
2073           else if (!b->ops->works_in_software_mode (b))
2074             {
2075               if (!can_use_hw_watchpoints)
2076                 error (_("Can't set read/access watchpoint when "
2077                          "hardware watchpoints are disabled."));
2078               else
2079                 error (_("Expression cannot be implemented with "
2080                          "read/access watchpoint."));
2081             }
2082           else
2083             b->type = bp_watchpoint;
2084
2085           loc_type = (b->type == bp_watchpoint? bp_loc_other
2086                       : bp_loc_hardware_watchpoint);
2087           for (bl = b->loc; bl; bl = bl->next)
2088             bl->loc_type = loc_type;
2089         }
2090
2091       /* If a software watchpoint is not watching any memory, then the
2092          above left it without any location set up.  But,
2093          bpstat_stop_status requires a location to be able to report
2094          stops, so make sure there's at least a dummy one.  */
2095       if (b->type == bp_watchpoint && b->loc == NULL)
2096         software_watchpoint_add_no_memory_location (b, frame_pspace);
2097     }
2098   else if (!within_current_scope)
2099     {
2100       printf_filtered (_("\
2101 Watchpoint %d deleted because the program has left the block\n\
2102 in which its expression is valid.\n"),
2103                        b->number);
2104       watchpoint_del_at_next_stop (b);
2105     }
2106
2107   /* Restore the selected frame.  */
2108   if (frame_saved)
2109     select_frame (frame_find_by_id (saved_frame_id));
2110 }
2111
2112
2113 /* Returns 1 iff breakpoint location should be
2114    inserted in the inferior.  We don't differentiate the type of BL's owner
2115    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2116    breakpoint_ops is not defined, because in insert_bp_location,
2117    tracepoint's insert_location will not be called.  */
2118 static int
2119 should_be_inserted (struct bp_location *bl)
2120 {
2121   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2122     return 0;
2123
2124   if (bl->owner->disposition == disp_del_at_next_stop)
2125     return 0;
2126
2127   if (!bl->enabled || bl->disabled_by_cond
2128       || bl->shlib_disabled || bl->duplicate)
2129     return 0;
2130
2131   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2132     return 0;
2133
2134   /* This is set for example, when we're attached to the parent of a
2135      vfork, and have detached from the child.  The child is running
2136      free, and we expect it to do an exec or exit, at which point the
2137      OS makes the parent schedulable again (and the target reports
2138      that the vfork is done).  Until the child is done with the shared
2139      memory region, do not insert breakpoints in the parent, otherwise
2140      the child could still trip on the parent's breakpoints.  Since
2141      the parent is blocked anyway, it won't miss any breakpoint.  */
2142   if (bl->pspace->breakpoints_not_allowed)
2143     return 0;
2144
2145   /* Don't insert a breakpoint if we're trying to step past its
2146      location, except if the breakpoint is a single-step breakpoint,
2147      and the breakpoint's thread is the thread which is stepping past
2148      a breakpoint.  */
2149   if ((bl->loc_type == bp_loc_software_breakpoint
2150        || bl->loc_type == bp_loc_hardware_breakpoint)
2151       && stepping_past_instruction_at (bl->pspace->aspace,
2152                                        bl->address)
2153       /* The single-step breakpoint may be inserted at the location
2154          we're trying to step if the instruction branches to itself.
2155          However, the instruction won't be executed at all and it may
2156          break the semantics of the instruction, for example, the
2157          instruction is a conditional branch or updates some flags.
2158          We can't fix it unless GDB is able to emulate the instruction
2159          or switch to displaced stepping.  */
2160       && !(bl->owner->type == bp_single_step
2161            && thread_is_stepping_over_breakpoint (bl->owner->thread)))
2162     {
2163       infrun_debug_printf ("skipping breakpoint: stepping past insn at: %s",
2164                            paddress (bl->gdbarch, bl->address));
2165       return 0;
2166     }
2167
2168   /* Don't insert watchpoints if we're trying to step past the
2169      instruction that triggered one.  */
2170   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2171       && stepping_past_nonsteppable_watchpoint ())
2172     {
2173       infrun_debug_printf ("stepping past non-steppable watchpoint. "
2174                            "skipping watchpoint at %s:%d",
2175                            paddress (bl->gdbarch, bl->address), bl->length);
2176       return 0;
2177     }
2178
2179   return 1;
2180 }
2181
2182 /* Same as should_be_inserted but does the check assuming
2183    that the location is not duplicated.  */
2184
2185 static int
2186 unduplicated_should_be_inserted (struct bp_location *bl)
2187 {
2188   int result;
2189   const int save_duplicate = bl->duplicate;
2190
2191   bl->duplicate = 0;
2192   result = should_be_inserted (bl);
2193   bl->duplicate = save_duplicate;
2194   return result;
2195 }
2196
2197 /* Parses a conditional described by an expression COND into an
2198    agent expression bytecode suitable for evaluation
2199    by the bytecode interpreter.  Return NULL if there was
2200    any error during parsing.  */
2201
2202 static agent_expr_up
2203 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2204 {
2205   if (cond == NULL)
2206     return NULL;
2207
2208   agent_expr_up aexpr;
2209
2210   /* We don't want to stop processing, so catch any errors
2211      that may show up.  */
2212   try
2213     {
2214       aexpr = gen_eval_for_expr (scope, cond);
2215     }
2216
2217   catch (const gdb_exception_error &ex)
2218     {
2219       /* If we got here, it means the condition could not be parsed to a valid
2220          bytecode expression and thus can't be evaluated on the target's side.
2221          It's no use iterating through the conditions.  */
2222     }
2223
2224   /* We have a valid agent expression.  */
2225   return aexpr;
2226 }
2227
2228 /* Based on location BL, create a list of breakpoint conditions to be
2229    passed on to the target.  If we have duplicated locations with different
2230    conditions, we will add such conditions to the list.  The idea is that the
2231    target will evaluate the list of conditions and will only notify GDB when
2232    one of them is true.  */
2233
2234 static void
2235 build_target_condition_list (struct bp_location *bl)
2236 {
2237   struct bp_location **locp = NULL, **loc2p;
2238   int null_condition_or_parse_error = 0;
2239   int modified = bl->needs_update;
2240   struct bp_location *loc;
2241
2242   /* Release conditions left over from a previous insert.  */
2243   bl->target_info.conditions.clear ();
2244
2245   /* This is only meaningful if the target is
2246      evaluating conditions and if the user has
2247      opted for condition evaluation on the target's
2248      side.  */
2249   if (gdb_evaluates_breakpoint_condition_p ()
2250       || !target_supports_evaluation_of_breakpoint_conditions ())
2251     return;
2252
2253   /* Do a first pass to check for locations with no assigned
2254      conditions or conditions that fail to parse to a valid agent
2255      expression bytecode.  If any of these happen, then it's no use to
2256      send conditions to the target since this location will always
2257      trigger and generate a response back to GDB.  Note we consider
2258      all locations at the same address irrespective of type, i.e.,
2259      even if the locations aren't considered duplicates (e.g.,
2260      software breakpoint and hardware breakpoint at the same
2261      address).  */
2262   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2263     {
2264       loc = (*loc2p);
2265       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2266         {
2267           if (modified)
2268             {
2269               /* Re-parse the conditions since something changed.  In that
2270                  case we already freed the condition bytecodes (see
2271                  force_breakpoint_reinsertion).  We just
2272                  need to parse the condition to bytecodes again.  */
2273               loc->cond_bytecode = parse_cond_to_aexpr (bl->address,
2274                                                         loc->cond.get ());
2275             }
2276
2277           /* If we have a NULL bytecode expression, it means something
2278              went wrong or we have a null condition expression.  */
2279           if (!loc->cond_bytecode)
2280             {
2281               null_condition_or_parse_error = 1;
2282               break;
2283             }
2284         }
2285     }
2286
2287   /* If any of these happened, it means we will have to evaluate the conditions
2288      for the location's address on gdb's side.  It is no use keeping bytecodes
2289      for all the other duplicate locations, thus we free all of them here.
2290
2291      This is so we have a finer control over which locations' conditions are
2292      being evaluated by GDB or the remote stub.  */
2293   if (null_condition_or_parse_error)
2294     {
2295       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2296         {
2297           loc = (*loc2p);
2298           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2299             {
2300               /* Only go as far as the first NULL bytecode is
2301                  located.  */
2302               if (!loc->cond_bytecode)
2303                 return;
2304
2305               loc->cond_bytecode.reset ();
2306             }
2307         }
2308     }
2309
2310   /* No NULL conditions or failed bytecode generation.  Build a
2311      condition list for this location's address.  If we have software
2312      and hardware locations at the same address, they aren't
2313      considered duplicates, but we still marge all the conditions
2314      anyway, as it's simpler, and doesn't really make a practical
2315      difference.  */
2316   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2317     {
2318       loc = (*loc2p);
2319       if (loc->cond
2320           && is_breakpoint (loc->owner)
2321           && loc->pspace->num == bl->pspace->num
2322           && loc->owner->enable_state == bp_enabled
2323           && loc->enabled
2324           && !loc->disabled_by_cond)
2325         {
2326           /* Add the condition to the vector.  This will be used later
2327              to send the conditions to the target.  */
2328           bl->target_info.conditions.push_back (loc->cond_bytecode.get ());
2329         }
2330     }
2331
2332   return;
2333 }
2334
2335 /* Parses a command described by string CMD into an agent expression
2336    bytecode suitable for evaluation by the bytecode interpreter.
2337    Return NULL if there was any error during parsing.  */
2338
2339 static agent_expr_up
2340 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2341 {
2342   const char *cmdrest;
2343   const char *format_start, *format_end;
2344   struct gdbarch *gdbarch = get_current_arch ();
2345
2346   if (cmd == NULL)
2347     return NULL;
2348
2349   cmdrest = cmd;
2350
2351   if (*cmdrest == ',')
2352     ++cmdrest;
2353   cmdrest = skip_spaces (cmdrest);
2354
2355   if (*cmdrest++ != '"')
2356     error (_("No format string following the location"));
2357
2358   format_start = cmdrest;
2359
2360   format_pieces fpieces (&cmdrest);
2361
2362   format_end = cmdrest;
2363
2364   if (*cmdrest++ != '"')
2365     error (_("Bad format string, non-terminated '\"'."));
2366   
2367   cmdrest = skip_spaces (cmdrest);
2368
2369   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2370     error (_("Invalid argument syntax"));
2371
2372   if (*cmdrest == ',')
2373     cmdrest++;
2374   cmdrest = skip_spaces (cmdrest);
2375
2376   /* For each argument, make an expression.  */
2377
2378   std::vector<struct expression *> argvec;
2379   while (*cmdrest != '\0')
2380     {
2381       const char *cmd1;
2382
2383       cmd1 = cmdrest;
2384       expression_up expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2385       argvec.push_back (expr.release ());
2386       cmdrest = cmd1;
2387       if (*cmdrest == ',')
2388         ++cmdrest;
2389     }
2390
2391   agent_expr_up aexpr;
2392
2393   /* We don't want to stop processing, so catch any errors
2394      that may show up.  */
2395   try
2396     {
2397       aexpr = gen_printf (scope, gdbarch, 0, 0,
2398                           format_start, format_end - format_start,
2399                           argvec.size (), argvec.data ());
2400     }
2401   catch (const gdb_exception_error &ex)
2402     {
2403       /* If we got here, it means the command could not be parsed to a valid
2404          bytecode expression and thus can't be evaluated on the target's side.
2405          It's no use iterating through the other commands.  */
2406     }
2407
2408   /* We have a valid agent expression, return it.  */
2409   return aexpr;
2410 }
2411
2412 /* Based on location BL, create a list of breakpoint commands to be
2413    passed on to the target.  If we have duplicated locations with
2414    different commands, we will add any such to the list.  */
2415
2416 static void
2417 build_target_command_list (struct bp_location *bl)
2418 {
2419   struct bp_location **locp = NULL, **loc2p;
2420   int null_command_or_parse_error = 0;
2421   int modified = bl->needs_update;
2422   struct bp_location *loc;
2423
2424   /* Clear commands left over from a previous insert.  */
2425   bl->target_info.tcommands.clear ();
2426
2427   if (!target_can_run_breakpoint_commands ())
2428     return;
2429
2430   /* For now, limit to agent-style dprintf breakpoints.  */
2431   if (dprintf_style != dprintf_style_agent)
2432     return;
2433
2434   /* For now, if we have any location at the same address that isn't a
2435      dprintf, don't install the target-side commands, as that would
2436      make the breakpoint not be reported to the core, and we'd lose
2437      control.  */
2438   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2439     {
2440       loc = (*loc2p);
2441       if (is_breakpoint (loc->owner)
2442           && loc->pspace->num == bl->pspace->num
2443           && loc->owner->type != bp_dprintf)
2444         return;
2445     }
2446
2447   /* Do a first pass to check for locations with no assigned
2448      conditions or conditions that fail to parse to a valid agent expression
2449      bytecode.  If any of these happen, then it's no use to send conditions
2450      to the target since this location will always trigger and generate a
2451      response back to GDB.  */
2452   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2453     {
2454       loc = (*loc2p);
2455       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2456         {
2457           if (modified)
2458             {
2459               /* Re-parse the commands since something changed.  In that
2460                  case we already freed the command bytecodes (see
2461                  force_breakpoint_reinsertion).  We just
2462                  need to parse the command to bytecodes again.  */
2463               loc->cmd_bytecode
2464                 = parse_cmd_to_aexpr (bl->address,
2465                                       loc->owner->extra_string);
2466             }
2467
2468           /* If we have a NULL bytecode expression, it means something
2469              went wrong or we have a null command expression.  */
2470           if (!loc->cmd_bytecode)
2471             {
2472               null_command_or_parse_error = 1;
2473               break;
2474             }
2475         }
2476     }
2477
2478   /* If anything failed, then we're not doing target-side commands,
2479      and so clean up.  */
2480   if (null_command_or_parse_error)
2481     {
2482       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2483         {
2484           loc = (*loc2p);
2485           if (is_breakpoint (loc->owner)
2486               && loc->pspace->num == bl->pspace->num)
2487             {
2488               /* Only go as far as the first NULL bytecode is
2489                  located.  */
2490               if (loc->cmd_bytecode == NULL)
2491                 return;
2492
2493               loc->cmd_bytecode.reset ();
2494             }
2495         }
2496     }
2497
2498   /* No NULL commands or failed bytecode generation.  Build a command
2499      list for all duplicate locations at this location's address.
2500      Note that here we must care for whether the breakpoint location
2501      types are considered duplicates, otherwise, say, if we have a
2502      software and hardware location at the same address, the target
2503      could end up running the commands twice.  For the moment, we only
2504      support targets-side commands with dprintf, but it doesn't hurt
2505      to be pedantically correct in case that changes.  */
2506   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2507     {
2508       loc = (*loc2p);
2509       if (breakpoint_locations_match (bl, loc)
2510           && loc->owner->extra_string
2511           && is_breakpoint (loc->owner)
2512           && loc->pspace->num == bl->pspace->num
2513           && loc->owner->enable_state == bp_enabled
2514           && loc->enabled
2515           && !loc->disabled_by_cond)
2516         {
2517           /* Add the command to the vector.  This will be used later
2518              to send the commands to the target.  */
2519           bl->target_info.tcommands.push_back (loc->cmd_bytecode.get ());
2520         }
2521     }
2522
2523   bl->target_info.persist = 0;
2524   /* Maybe flag this location as persistent.  */
2525   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2526     bl->target_info.persist = 1;
2527 }
2528
2529 /* Return the kind of breakpoint on address *ADDR.  Get the kind
2530    of breakpoint according to ADDR except single-step breakpoint.
2531    Get the kind of single-step breakpoint according to the current
2532    registers state.  */
2533
2534 static int
2535 breakpoint_kind (struct bp_location *bl, CORE_ADDR *addr)
2536 {
2537   if (bl->owner->type == bp_single_step)
2538     {
2539       struct thread_info *thr = find_thread_global_id (bl->owner->thread);
2540       struct regcache *regcache;
2541
2542       regcache = get_thread_regcache (thr);
2543
2544       return gdbarch_breakpoint_kind_from_current_state (bl->gdbarch,
2545                                                          regcache, addr);
2546     }
2547   else
2548     return gdbarch_breakpoint_kind_from_pc (bl->gdbarch, addr);
2549 }
2550
2551 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2552    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2553    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2554    Returns 0 for success, 1 if the bp_location type is not supported or
2555    -1 for failure.
2556
2557    NOTE drow/2003-09-09: This routine could be broken down to an
2558    object-style method for each breakpoint or catchpoint type.  */
2559 static int
2560 insert_bp_location (struct bp_location *bl,
2561                     struct ui_file *tmp_error_stream,
2562                     int *disabled_breaks,
2563                     int *hw_breakpoint_error,
2564                     int *hw_bp_error_explained_already)
2565 {
2566   gdb_exception bp_excpt;
2567
2568   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2569     return 0;
2570
2571   /* Note we don't initialize bl->target_info, as that wipes out
2572      the breakpoint location's shadow_contents if the breakpoint
2573      is still inserted at that location.  This in turn breaks
2574      target_read_memory which depends on these buffers when
2575      a memory read is requested at the breakpoint location:
2576      Once the target_info has been wiped, we fail to see that
2577      we have a breakpoint inserted at that address and thus
2578      read the breakpoint instead of returning the data saved in
2579      the breakpoint location's shadow contents.  */
2580   bl->target_info.reqstd_address = bl->address;
2581   bl->target_info.placed_address_space = bl->pspace->aspace;
2582   bl->target_info.length = bl->length;
2583
2584   /* When working with target-side conditions, we must pass all the conditions
2585      for the same breakpoint address down to the target since GDB will not
2586      insert those locations.  With a list of breakpoint conditions, the target
2587      can decide when to stop and notify GDB.  */
2588
2589   if (is_breakpoint (bl->owner))
2590     {
2591       build_target_condition_list (bl);
2592       build_target_command_list (bl);
2593       /* Reset the modification marker.  */
2594       bl->needs_update = 0;
2595     }
2596
2597   /* If "set breakpoint auto-hw" is "on" and a software breakpoint was
2598      set at a read-only address, then a breakpoint location will have
2599      been changed to hardware breakpoint before we get here.  If it is
2600      "off" however, error out before actually trying to insert the
2601      breakpoint, with a nicer error message.  */
2602   if (bl->loc_type == bp_loc_software_breakpoint
2603       && !automatic_hardware_breakpoints)
2604     {
2605       mem_region *mr = lookup_mem_region (bl->address);
2606
2607       if (mr != nullptr && mr->attrib.mode != MEM_RW)
2608         {
2609           fprintf_unfiltered (tmp_error_stream,
2610                               _("Cannot insert breakpoint %d.\n"
2611                                 "Cannot set software breakpoint "
2612                                 "at read-only address %s\n"),
2613                               bl->owner->number,
2614                               paddress (bl->gdbarch, bl->address));
2615           return 1;
2616         }
2617     }
2618
2619   if (bl->loc_type == bp_loc_software_breakpoint
2620       || bl->loc_type == bp_loc_hardware_breakpoint)
2621     {
2622       /* First check to see if we have to handle an overlay.  */
2623       if (overlay_debugging == ovly_off
2624           || bl->section == NULL
2625           || !(section_is_overlay (bl->section)))
2626         {
2627           /* No overlay handling: just set the breakpoint.  */
2628           try
2629             {
2630               int val;
2631
2632               val = bl->owner->ops->insert_location (bl);
2633               if (val)
2634                 bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2635             }
2636           catch (gdb_exception &e)
2637             {
2638               bp_excpt = std::move (e);
2639             }
2640         }
2641       else
2642         {
2643           /* This breakpoint is in an overlay section.
2644              Shall we set a breakpoint at the LMA?  */
2645           if (!overlay_events_enabled)
2646             {
2647               /* Yes -- overlay event support is not active, 
2648                  so we must try to set a breakpoint at the LMA.
2649                  This will not work for a hardware breakpoint.  */
2650               if (bl->loc_type == bp_loc_hardware_breakpoint)
2651                 warning (_("hardware breakpoint %d not supported in overlay!"),
2652                          bl->owner->number);
2653               else
2654                 {
2655                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2656                                                              bl->section);
2657                   /* Set a software (trap) breakpoint at the LMA.  */
2658                   bl->overlay_target_info = bl->target_info;
2659                   bl->overlay_target_info.reqstd_address = addr;
2660
2661                   /* No overlay handling: just set the breakpoint.  */
2662                   try
2663                     {
2664                       int val;
2665
2666                       bl->overlay_target_info.kind
2667                         = breakpoint_kind (bl, &addr);
2668                       bl->overlay_target_info.placed_address = addr;
2669                       val = target_insert_breakpoint (bl->gdbarch,
2670                                                       &bl->overlay_target_info);
2671                       if (val)
2672                         bp_excpt
2673                           = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2674                     }
2675                   catch (gdb_exception &e)
2676                     {
2677                       bp_excpt = std::move (e);
2678                     }
2679
2680                   if (bp_excpt.reason != 0)
2681                     fprintf_unfiltered (tmp_error_stream,
2682                                         "Overlay breakpoint %d "
2683                                         "failed: in ROM?\n",
2684                                         bl->owner->number);
2685                 }
2686             }
2687           /* Shall we set a breakpoint at the VMA? */
2688           if (section_is_mapped (bl->section))
2689             {
2690               /* Yes.  This overlay section is mapped into memory.  */
2691               try
2692                 {
2693                   int val;
2694
2695                   val = bl->owner->ops->insert_location (bl);
2696                   if (val)
2697                     bp_excpt = gdb_exception {RETURN_ERROR, GENERIC_ERROR};
2698                 }
2699               catch (gdb_exception &e)
2700                 {
2701                   bp_excpt = std::move (e);
2702                 }
2703             }
2704           else
2705             {
2706               /* No.  This breakpoint will not be inserted.  
2707                  No error, but do not mark the bp as 'inserted'.  */
2708               return 0;
2709             }
2710         }
2711
2712       if (bp_excpt.reason != 0)
2713         {
2714           /* Can't set the breakpoint.  */
2715
2716           /* In some cases, we might not be able to insert a
2717              breakpoint in a shared library that has already been
2718              removed, but we have not yet processed the shlib unload
2719              event.  Unfortunately, some targets that implement
2720              breakpoint insertion themselves can't tell why the
2721              breakpoint insertion failed (e.g., the remote target
2722              doesn't define error codes), so we must treat generic
2723              errors as memory errors.  */
2724           if (bp_excpt.reason == RETURN_ERROR
2725               && (bp_excpt.error == GENERIC_ERROR
2726                   || bp_excpt.error == MEMORY_ERROR)
2727               && bl->loc_type == bp_loc_software_breakpoint
2728               && (solib_name_from_address (bl->pspace, bl->address)
2729                   || shared_objfile_contains_address_p (bl->pspace,
2730                                                         bl->address)))
2731             {
2732               /* See also: disable_breakpoints_in_shlibs.  */
2733               bl->shlib_disabled = 1;
2734               gdb::observers::breakpoint_modified.notify (bl->owner);
2735               if (!*disabled_breaks)
2736                 {
2737                   fprintf_unfiltered (tmp_error_stream, 
2738                                       "Cannot insert breakpoint %d.\n", 
2739                                       bl->owner->number);
2740                   fprintf_unfiltered (tmp_error_stream, 
2741                                       "Temporarily disabling shared "
2742                                       "library breakpoints:\n");
2743                 }
2744               *disabled_breaks = 1;
2745               fprintf_unfiltered (tmp_error_stream,
2746                                   "breakpoint #%d\n", bl->owner->number);
2747               return 0;
2748             }
2749           else
2750             {
2751               if (bl->loc_type == bp_loc_hardware_breakpoint)
2752                 {
2753                   *hw_breakpoint_error = 1;
2754                   *hw_bp_error_explained_already = bp_excpt.message != NULL;
2755                   fprintf_unfiltered (tmp_error_stream,
2756                                       "Cannot insert hardware breakpoint %d%s",
2757                                       bl->owner->number,
2758                                       bp_excpt.message ? ":" : ".\n");
2759                   if (bp_excpt.message != NULL)
2760                     fprintf_unfiltered (tmp_error_stream, "%s.\n",
2761                                         bp_excpt.what ());
2762                 }
2763               else
2764                 {
2765                   if (bp_excpt.message == NULL)
2766                     {
2767                       std::string message
2768                         = memory_error_message (TARGET_XFER_E_IO,
2769                                                 bl->gdbarch, bl->address);
2770
2771                       fprintf_unfiltered (tmp_error_stream,
2772                                           "Cannot insert breakpoint %d.\n"
2773                                           "%s\n",
2774                                           bl->owner->number, message.c_str ());
2775                     }
2776                   else
2777                     {
2778                       fprintf_unfiltered (tmp_error_stream,
2779                                           "Cannot insert breakpoint %d: %s\n",
2780                                           bl->owner->number,
2781                                           bp_excpt.what ());
2782                     }
2783                 }
2784               return 1;
2785
2786             }
2787         }
2788       else
2789         bl->inserted = 1;
2790
2791       return 0;
2792     }
2793
2794   else if (bl->loc_type == bp_loc_hardware_watchpoint
2795            /* NOTE drow/2003-09-08: This state only exists for removing
2796               watchpoints.  It's not clear that it's necessary...  */
2797            && bl->owner->disposition != disp_del_at_next_stop)
2798     {
2799       int val;
2800
2801       gdb_assert (bl->owner->ops != NULL
2802                   && bl->owner->ops->insert_location != NULL);
2803
2804       val = bl->owner->ops->insert_location (bl);
2805
2806       /* If trying to set a read-watchpoint, and it turns out it's not
2807          supported, try emulating one with an access watchpoint.  */
2808       if (val == 1 && bl->watchpoint_type == hw_read)
2809         {
2810           struct bp_location *loc, **loc_temp;
2811
2812           /* But don't try to insert it, if there's already another
2813              hw_access location that would be considered a duplicate
2814              of this one.  */
2815           ALL_BP_LOCATIONS (loc, loc_temp)
2816             if (loc != bl
2817                 && loc->watchpoint_type == hw_access
2818                 && watchpoint_locations_match (bl, loc))
2819               {
2820                 bl->duplicate = 1;
2821                 bl->inserted = 1;
2822                 bl->target_info = loc->target_info;
2823                 bl->watchpoint_type = hw_access;
2824                 val = 0;
2825                 break;
2826               }
2827
2828           if (val == 1)
2829             {
2830               bl->watchpoint_type = hw_access;
2831               val = bl->owner->ops->insert_location (bl);
2832
2833               if (val)
2834                 /* Back to the original value.  */
2835                 bl->watchpoint_type = hw_read;
2836             }
2837         }
2838
2839       bl->inserted = (val == 0);
2840     }
2841
2842   else if (bl->owner->type == bp_catchpoint)
2843     {
2844       int val;
2845
2846       gdb_assert (bl->owner->ops != NULL
2847                   && bl->owner->ops->insert_location != NULL);
2848
2849       val = bl->owner->ops->insert_location (bl);
2850       if (val)
2851         {
2852           bl->owner->enable_state = bp_disabled;
2853
2854           if (val == 1)
2855             warning (_("\
2856 Error inserting catchpoint %d: Your system does not support this type\n\
2857 of catchpoint."), bl->owner->number);
2858           else
2859             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2860         }
2861
2862       bl->inserted = (val == 0);
2863
2864       /* We've already printed an error message if there was a problem
2865          inserting this catchpoint, and we've disabled the catchpoint,
2866          so just return success.  */
2867       return 0;
2868     }
2869
2870   return 0;
2871 }
2872
2873 /* This function is called when program space PSPACE is about to be
2874    deleted.  It takes care of updating breakpoints to not reference
2875    PSPACE anymore.  */
2876
2877 void
2878 breakpoint_program_space_exit (struct program_space *pspace)
2879 {
2880   struct breakpoint *b, *b_temp;
2881   struct bp_location *loc, **loc_temp;
2882
2883   /* Remove any breakpoint that was set through this program space.  */
2884   ALL_BREAKPOINTS_SAFE (b, b_temp)
2885     {
2886       if (b->pspace == pspace)
2887         delete_breakpoint (b);
2888     }
2889
2890   /* Breakpoints set through other program spaces could have locations
2891      bound to PSPACE as well.  Remove those.  */
2892   ALL_BP_LOCATIONS (loc, loc_temp)
2893     {
2894       struct bp_location *tmp;
2895
2896       if (loc->pspace == pspace)
2897         {
2898           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2899           if (loc->owner->loc == loc)
2900             loc->owner->loc = loc->next;
2901           else
2902             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2903               if (tmp->next == loc)
2904                 {
2905                   tmp->next = loc->next;
2906                   break;
2907                 }
2908         }
2909     }
2910
2911   /* Now update the global location list to permanently delete the
2912      removed locations above.  */
2913   update_global_location_list (UGLL_DONT_INSERT);
2914 }
2915
2916 /* Make sure all breakpoints are inserted in inferior.
2917    Throws exception on any error.
2918    A breakpoint that is already inserted won't be inserted
2919    again, so calling this function twice is safe.  */
2920 void
2921 insert_breakpoints (void)
2922 {
2923   struct breakpoint *bpt;
2924
2925   ALL_BREAKPOINTS (bpt)
2926     if (is_hardware_watchpoint (bpt))
2927       {
2928         struct watchpoint *w = (struct watchpoint *) bpt;
2929
2930         update_watchpoint (w, 0 /* don't reparse.  */);
2931       }
2932
2933   /* Updating watchpoints creates new locations, so update the global
2934      location list.  Explicitly tell ugll to insert locations and
2935      ignore breakpoints_always_inserted_mode.  Also,
2936      update_global_location_list tries to "upgrade" software
2937      breakpoints to hardware breakpoints to handle "set breakpoint
2938      auto-hw", so we need to call it even if we don't have new
2939      locations.  */
2940   update_global_location_list (UGLL_INSERT);
2941 }
2942
2943 /* Invoke CALLBACK for each of bp_location.  */
2944
2945 void
2946 iterate_over_bp_locations (walk_bp_location_callback callback)
2947 {
2948   struct bp_location *loc, **loc_tmp;
2949
2950   ALL_BP_LOCATIONS (loc, loc_tmp)
2951     {
2952       callback (loc, NULL);
2953     }
2954 }
2955
2956 /* This is used when we need to synch breakpoint conditions between GDB and the
2957    target.  It is the case with deleting and disabling of breakpoints when using
2958    always-inserted mode.  */
2959
2960 static void
2961 update_inserted_breakpoint_locations (void)
2962 {
2963   struct bp_location *bl, **blp_tmp;
2964   int error_flag = 0;
2965   int val = 0;
2966   int disabled_breaks = 0;
2967   int hw_breakpoint_error = 0;
2968   int hw_bp_details_reported = 0;
2969
2970   string_file tmp_error_stream;
2971
2972   /* Explicitly mark the warning -- this will only be printed if
2973      there was an error.  */
2974   tmp_error_stream.puts ("Warning:\n");
2975
2976   scoped_restore_current_pspace_and_thread restore_pspace_thread;
2977
2978   ALL_BP_LOCATIONS (bl, blp_tmp)
2979     {
2980       /* We only want to update software breakpoints and hardware
2981          breakpoints.  */
2982       if (!is_breakpoint (bl->owner))
2983         continue;
2984
2985       /* We only want to update locations that are already inserted
2986          and need updating.  This is to avoid unwanted insertion during
2987          deletion of breakpoints.  */
2988       if (!bl->inserted || !bl->needs_update)
2989         continue;
2990
2991       switch_to_program_space_and_thread (bl->pspace);
2992
2993       /* For targets that support global breakpoints, there's no need
2994          to select an inferior to insert breakpoint to.  In fact, even
2995          if we aren't attached to any process yet, we should still
2996          insert breakpoints.  */
2997       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2998           && (inferior_ptid == null_ptid || !target_has_execution ()))
2999         continue;
3000
3001       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3002                                     &hw_breakpoint_error, &hw_bp_details_reported);
3003       if (val)
3004         error_flag = val;
3005     }
3006
3007   if (error_flag)
3008     {
3009       target_terminal::ours_for_output ();
3010       error_stream (tmp_error_stream);
3011     }
3012 }
3013
3014 /* Used when starting or continuing the program.  */
3015
3016 static void
3017 insert_breakpoint_locations (void)
3018 {
3019   struct breakpoint *bpt;
3020   struct bp_location *bl, **blp_tmp;
3021   int error_flag = 0;
3022   int val = 0;
3023   int disabled_breaks = 0;
3024   int hw_breakpoint_error = 0;
3025   int hw_bp_error_explained_already = 0;
3026
3027   string_file tmp_error_stream;
3028
3029   /* Explicitly mark the warning -- this will only be printed if
3030      there was an error.  */
3031   tmp_error_stream.puts ("Warning:\n");
3032
3033   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3034
3035   ALL_BP_LOCATIONS (bl, blp_tmp)
3036     {
3037       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3038         continue;
3039
3040       /* There is no point inserting thread-specific breakpoints if
3041          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3042          has BL->OWNER always non-NULL.  */
3043       if (bl->owner->thread != -1
3044           && !valid_global_thread_id (bl->owner->thread))
3045         continue;
3046
3047       switch_to_program_space_and_thread (bl->pspace);
3048
3049       /* For targets that support global breakpoints, there's no need
3050          to select an inferior to insert breakpoint to.  In fact, even
3051          if we aren't attached to any process yet, we should still
3052          insert breakpoints.  */
3053       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3054           && (inferior_ptid == null_ptid || !target_has_execution ()))
3055         continue;
3056
3057       val = insert_bp_location (bl, &tmp_error_stream, &disabled_breaks,
3058                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3059       if (val)
3060         error_flag = val;
3061     }
3062
3063   /* If we failed to insert all locations of a watchpoint, remove
3064      them, as half-inserted watchpoint is of limited use.  */
3065   ALL_BREAKPOINTS (bpt)  
3066     {
3067       int some_failed = 0;
3068       struct bp_location *loc;
3069
3070       if (!is_hardware_watchpoint (bpt))
3071         continue;
3072
3073       if (!breakpoint_enabled (bpt))
3074         continue;
3075
3076       if (bpt->disposition == disp_del_at_next_stop)
3077         continue;
3078       
3079       for (loc = bpt->loc; loc; loc = loc->next)
3080         if (!loc->inserted && should_be_inserted (loc))
3081           {
3082             some_failed = 1;
3083             break;
3084           }
3085       if (some_failed)
3086         {
3087           for (loc = bpt->loc; loc; loc = loc->next)
3088             if (loc->inserted)
3089               remove_breakpoint (loc);
3090
3091           hw_breakpoint_error = 1;
3092           tmp_error_stream.printf ("Could not insert "
3093                                    "hardware watchpoint %d.\n",
3094                                    bpt->number);
3095           error_flag = -1;
3096         }
3097     }
3098
3099   if (error_flag)
3100     {
3101       /* If a hardware breakpoint or watchpoint was inserted, add a
3102          message about possibly exhausted resources.  */
3103       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3104         {
3105           tmp_error_stream.printf ("Could not insert hardware breakpoints:\n\
3106 You may have requested too many hardware breakpoints/watchpoints.\n");
3107         }
3108       target_terminal::ours_for_output ();
3109       error_stream (tmp_error_stream);
3110     }
3111 }
3112
3113 /* Used when the program stops.
3114    Returns zero if successful, or non-zero if there was a problem
3115    removing a breakpoint location.  */
3116
3117 int
3118 remove_breakpoints (void)
3119 {
3120   struct bp_location *bl, **blp_tmp;
3121   int val = 0;
3122
3123   ALL_BP_LOCATIONS (bl, blp_tmp)
3124   {
3125     if (bl->inserted && !is_tracepoint (bl->owner))
3126       val |= remove_breakpoint (bl);
3127   }
3128   return val;
3129 }
3130
3131 /* When a thread exits, remove breakpoints that are related to
3132    that thread.  */
3133
3134 static void
3135 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3136 {
3137   struct breakpoint *b, *b_tmp;
3138
3139   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3140     {
3141       if (b->thread == tp->global_num && user_breakpoint_p (b))
3142         {
3143           b->disposition = disp_del_at_next_stop;
3144
3145           printf_filtered (_("\
3146 Thread-specific breakpoint %d deleted - thread %s no longer in the thread list.\n"),
3147                            b->number, print_thread_id (tp));
3148
3149           /* Hide it from the user.  */
3150           b->number = 0;
3151        }
3152     }
3153 }
3154
3155 /* See breakpoint.h.  */
3156
3157 void
3158 remove_breakpoints_inf (inferior *inf)
3159 {
3160   struct bp_location *bl, **blp_tmp;
3161   int val;
3162
3163   ALL_BP_LOCATIONS (bl, blp_tmp)
3164   {
3165     if (bl->pspace != inf->pspace)
3166       continue;
3167
3168     if (bl->inserted && !bl->target_info.persist)
3169       {
3170         val = remove_breakpoint (bl);
3171         if (val != 0)
3172           return;
3173       }
3174   }
3175 }
3176
3177 static int internal_breakpoint_number = -1;
3178
3179 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3180    If INTERNAL is non-zero, the breakpoint number will be populated
3181    from internal_breakpoint_number and that variable decremented.
3182    Otherwise the breakpoint number will be populated from
3183    breakpoint_count and that value incremented.  Internal breakpoints
3184    do not set the internal var bpnum.  */
3185 static void
3186 set_breakpoint_number (int internal, struct breakpoint *b)
3187 {
3188   if (internal)
3189     b->number = internal_breakpoint_number--;
3190   else
3191     {
3192       set_breakpoint_count (breakpoint_count + 1);
3193       b->number = breakpoint_count;
3194     }
3195 }
3196
3197 static struct breakpoint *
3198 create_internal_breakpoint (struct gdbarch *gdbarch,
3199                             CORE_ADDR address, enum bptype type,
3200                             const struct breakpoint_ops *ops)
3201 {
3202   symtab_and_line sal;
3203   sal.pc = address;
3204   sal.section = find_pc_overlay (sal.pc);
3205   sal.pspace = current_program_space;
3206
3207   breakpoint *b = set_raw_breakpoint (gdbarch, sal, type, ops);
3208   b->number = internal_breakpoint_number--;
3209   b->disposition = disp_donttouch;
3210
3211   return b;
3212 }
3213
3214 static const char *const longjmp_names[] =
3215   {
3216     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3217   };
3218 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3219
3220 /* Per-objfile data private to breakpoint.c.  */
3221 struct breakpoint_objfile_data
3222 {
3223   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3224   struct bound_minimal_symbol overlay_msym {};
3225
3226   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3227   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES] {};
3228
3229   /* True if we have looked for longjmp probes.  */
3230   int longjmp_searched = 0;
3231
3232   /* SystemTap probe points for longjmp (if any).  These are non-owning
3233      references.  */
3234   std::vector<probe *> longjmp_probes;
3235
3236   /* Minimal symbol for "std::terminate()" (if any).  */
3237   struct bound_minimal_symbol terminate_msym {};
3238
3239   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3240   struct bound_minimal_symbol exception_msym {};
3241
3242   /* True if we have looked for exception probes.  */
3243   int exception_searched = 0;
3244
3245   /* SystemTap probe points for unwinding (if any).  These are non-owning
3246      references.  */
3247   std::vector<probe *> exception_probes;
3248 };
3249
3250 static const struct objfile_key<breakpoint_objfile_data>
3251   breakpoint_objfile_key;
3252
3253 /* Minimal symbol not found sentinel.  */
3254 static struct minimal_symbol msym_not_found;
3255
3256 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3257
3258 static int
3259 msym_not_found_p (const struct minimal_symbol *msym)
3260 {
3261   return msym == &msym_not_found;
3262 }
3263
3264 /* Return per-objfile data needed by breakpoint.c.
3265    Allocate the data if necessary.  */
3266
3267 static struct breakpoint_objfile_data *
3268 get_breakpoint_objfile_data (struct objfile *objfile)
3269 {
3270   struct breakpoint_objfile_data *bp_objfile_data;
3271
3272   bp_objfile_data = breakpoint_objfile_key.get (objfile);
3273   if (bp_objfile_data == NULL)
3274     bp_objfile_data = breakpoint_objfile_key.emplace (objfile);
3275   return bp_objfile_data;
3276 }
3277
3278 static void
3279 create_overlay_event_breakpoint (void)
3280 {
3281   const char *const func_name = "_ovly_debug_event";
3282
3283   for (objfile *objfile : current_program_space->objfiles ())
3284     {
3285       struct breakpoint *b;
3286       struct breakpoint_objfile_data *bp_objfile_data;
3287       CORE_ADDR addr;
3288       struct explicit_location explicit_loc;
3289
3290       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3291
3292       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3293         continue;
3294
3295       if (bp_objfile_data->overlay_msym.minsym == NULL)
3296         {
3297           struct bound_minimal_symbol m;
3298
3299           m = lookup_minimal_symbol_text (func_name, objfile);
3300           if (m.minsym == NULL)
3301             {
3302               /* Avoid future lookups in this objfile.  */
3303               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3304               continue;
3305             }
3306           bp_objfile_data->overlay_msym = m;
3307         }
3308
3309       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3310       b = create_internal_breakpoint (objfile->arch (), addr,
3311                                       bp_overlay_event,
3312                                       &internal_breakpoint_ops);
3313       initialize_explicit_location (&explicit_loc);
3314       explicit_loc.function_name = ASTRDUP (func_name);
3315       b->location = new_explicit_location (&explicit_loc);
3316
3317       if (overlay_debugging == ovly_auto)
3318         {
3319           b->enable_state = bp_enabled;
3320           overlay_events_enabled = 1;
3321         }
3322       else
3323        {
3324          b->enable_state = bp_disabled;
3325          overlay_events_enabled = 0;
3326        }
3327     }
3328 }
3329
3330 static void
3331 create_longjmp_master_breakpoint (void)
3332 {
3333   scoped_restore_current_program_space restore_pspace;
3334
3335   for (struct program_space *pspace : program_spaces)
3336     {
3337       set_current_program_space (pspace);
3338
3339       for (objfile *objfile : current_program_space->objfiles ())
3340         {
3341           int i;
3342           struct gdbarch *gdbarch;
3343           struct breakpoint_objfile_data *bp_objfile_data;
3344
3345           gdbarch = objfile->arch ();
3346
3347           bp_objfile_data = get_breakpoint_objfile_data (objfile);
3348
3349           if (!bp_objfile_data->longjmp_searched)
3350             {
3351               std::vector<probe *> ret
3352                 = find_probes_in_objfile (objfile, "libc", "longjmp");
3353
3354               if (!ret.empty ())
3355                 {
3356                   /* We are only interested in checking one element.  */
3357                   probe *p = ret[0];
3358
3359                   if (!p->can_evaluate_arguments ())
3360                     {
3361                       /* We cannot use the probe interface here,
3362                          because it does not know how to evaluate
3363                          arguments.  */
3364                       ret.clear ();
3365                     }
3366                 }
3367               bp_objfile_data->longjmp_probes = ret;
3368               bp_objfile_data->longjmp_searched = 1;
3369             }
3370
3371           if (!bp_objfile_data->longjmp_probes.empty ())
3372             {
3373               for (probe *p : bp_objfile_data->longjmp_probes)
3374                 {
3375                   struct breakpoint *b;
3376
3377                   b = create_internal_breakpoint (gdbarch,
3378                                                   p->get_relocated_address (objfile),
3379                                                   bp_longjmp_master,
3380                                                   &internal_breakpoint_ops);
3381                   b->location = new_probe_location ("-probe-stap libc:longjmp");
3382                   b->enable_state = bp_disabled;
3383                 }
3384
3385               continue;
3386             }
3387
3388           if (!gdbarch_get_longjmp_target_p (gdbarch))
3389             continue;
3390
3391           for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3392             {
3393               struct breakpoint *b;
3394               const char *func_name;
3395               CORE_ADDR addr;
3396               struct explicit_location explicit_loc;
3397
3398               if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3399                 continue;
3400
3401               func_name = longjmp_names[i];
3402               if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3403                 {
3404                   struct bound_minimal_symbol m;
3405
3406                   m = lookup_minimal_symbol_text (func_name, objfile);
3407                   if (m.minsym == NULL)
3408                     {
3409                       /* Prevent future lookups in this objfile.  */
3410                       bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3411                       continue;
3412                     }
3413                   bp_objfile_data->longjmp_msym[i] = m;
3414                 }
3415
3416               addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3417               b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3418                                               &internal_breakpoint_ops);
3419               initialize_explicit_location (&explicit_loc);
3420               explicit_loc.function_name = ASTRDUP (func_name);
3421               b->location = new_explicit_location (&explicit_loc);
3422               b->enable_state = bp_disabled;
3423             }
3424         }
3425     }
3426 }
3427
3428 /* Create a master std::terminate breakpoint.  */
3429 static void
3430 create_std_terminate_master_breakpoint (void)
3431 {
3432   const char *const func_name = "std::terminate()";
3433
3434   scoped_restore_current_program_space restore_pspace;
3435
3436   for (struct program_space *pspace : program_spaces)
3437     {
3438       CORE_ADDR addr;
3439
3440       set_current_program_space (pspace);
3441
3442       for (objfile *objfile : current_program_space->objfiles ())
3443         {
3444           struct breakpoint *b;
3445           struct breakpoint_objfile_data *bp_objfile_data;
3446           struct explicit_location explicit_loc;
3447
3448           bp_objfile_data = get_breakpoint_objfile_data (objfile);
3449
3450           if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3451             continue;
3452
3453           if (bp_objfile_data->terminate_msym.minsym == NULL)
3454             {
3455               struct bound_minimal_symbol m;
3456
3457               m = lookup_minimal_symbol (func_name, NULL, objfile);
3458               if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3459                                        && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3460                 {
3461                   /* Prevent future lookups in this objfile.  */
3462                   bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3463                   continue;
3464                 }
3465               bp_objfile_data->terminate_msym = m;
3466             }
3467
3468           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3469           b = create_internal_breakpoint (objfile->arch (), addr,
3470                                           bp_std_terminate_master,
3471                                           &internal_breakpoint_ops);
3472           initialize_explicit_location (&explicit_loc);
3473           explicit_loc.function_name = ASTRDUP (func_name);
3474           b->location = new_explicit_location (&explicit_loc);
3475           b->enable_state = bp_disabled;
3476         }
3477     }
3478 }
3479
3480 /* Install a master breakpoint on the unwinder's debug hook.  */
3481
3482 static void
3483 create_exception_master_breakpoint (void)
3484 {
3485   const char *const func_name = "_Unwind_DebugHook";
3486
3487   for (objfile *objfile : current_program_space->objfiles ())
3488     {
3489       struct breakpoint *b;
3490       struct gdbarch *gdbarch;
3491       struct breakpoint_objfile_data *bp_objfile_data;
3492       CORE_ADDR addr;
3493       struct explicit_location explicit_loc;
3494
3495       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3496
3497       /* We prefer the SystemTap probe point if it exists.  */
3498       if (!bp_objfile_data->exception_searched)
3499         {
3500           std::vector<probe *> ret
3501             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3502
3503           if (!ret.empty ())
3504             {
3505               /* We are only interested in checking one element.  */
3506               probe *p = ret[0];
3507
3508               if (!p->can_evaluate_arguments ())
3509                 {
3510                   /* We cannot use the probe interface here, because it does
3511                      not know how to evaluate arguments.  */
3512                   ret.clear ();
3513                 }
3514             }
3515           bp_objfile_data->exception_probes = ret;
3516           bp_objfile_data->exception_searched = 1;
3517         }
3518
3519       if (!bp_objfile_data->exception_probes.empty ())
3520         {
3521           gdbarch = objfile->arch ();
3522
3523           for (probe *p : bp_objfile_data->exception_probes)
3524             {
3525               b = create_internal_breakpoint (gdbarch,
3526                                               p->get_relocated_address (objfile),
3527                                               bp_exception_master,
3528                                               &internal_breakpoint_ops);
3529               b->location = new_probe_location ("-probe-stap libgcc:unwind");
3530               b->enable_state = bp_disabled;
3531             }
3532
3533           continue;
3534         }
3535
3536       /* Otherwise, try the hook function.  */
3537
3538       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3539         continue;
3540
3541       gdbarch = objfile->arch ();
3542
3543       if (bp_objfile_data->exception_msym.minsym == NULL)
3544         {
3545           struct bound_minimal_symbol debug_hook;
3546
3547           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3548           if (debug_hook.minsym == NULL)
3549             {
3550               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3551               continue;
3552             }
3553
3554           bp_objfile_data->exception_msym = debug_hook;
3555         }
3556
3557       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3558       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3559                                                  current_top_target ());
3560       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3561                                       &internal_breakpoint_ops);
3562       initialize_explicit_location (&explicit_loc);
3563       explicit_loc.function_name = ASTRDUP (func_name);
3564       b->location = new_explicit_location (&explicit_loc);
3565       b->enable_state = bp_disabled;
3566     }
3567 }
3568
3569 /* Does B have a location spec?  */
3570
3571 static int
3572 breakpoint_event_location_empty_p (const struct breakpoint *b)
3573 {
3574   return b->location != NULL && event_location_empty_p (b->location.get ());
3575 }
3576
3577 void
3578 update_breakpoints_after_exec (void)
3579 {
3580   struct breakpoint *b, *b_tmp;
3581   struct bp_location *bploc, **bplocp_tmp;
3582
3583   /* We're about to delete breakpoints from GDB's lists.  If the
3584      INSERTED flag is true, GDB will try to lift the breakpoints by
3585      writing the breakpoints' "shadow contents" back into memory.  The
3586      "shadow contents" are NOT valid after an exec, so GDB should not
3587      do that.  Instead, the target is responsible from marking
3588      breakpoints out as soon as it detects an exec.  We don't do that
3589      here instead, because there may be other attempts to delete
3590      breakpoints after detecting an exec and before reaching here.  */
3591   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3592     if (bploc->pspace == current_program_space)
3593       gdb_assert (!bploc->inserted);
3594
3595   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3596   {
3597     if (b->pspace != current_program_space)
3598       continue;
3599
3600     /* Solib breakpoints must be explicitly reset after an exec().  */
3601     if (b->type == bp_shlib_event)
3602       {
3603         delete_breakpoint (b);
3604         continue;
3605       }
3606
3607     /* JIT breakpoints must be explicitly reset after an exec().  */
3608     if (b->type == bp_jit_event)
3609       {
3610         delete_breakpoint (b);
3611         continue;
3612       }
3613
3614     /* Thread event breakpoints must be set anew after an exec(),
3615        as must overlay event and longjmp master breakpoints.  */
3616     if (b->type == bp_thread_event || b->type == bp_overlay_event
3617         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3618         || b->type == bp_exception_master)
3619       {
3620         delete_breakpoint (b);
3621         continue;
3622       }
3623
3624     /* Step-resume breakpoints are meaningless after an exec().  */
3625     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3626       {
3627         delete_breakpoint (b);
3628         continue;
3629       }
3630
3631     /* Just like single-step breakpoints.  */
3632     if (b->type == bp_single_step)
3633       {
3634         delete_breakpoint (b);
3635         continue;
3636       }
3637
3638     /* Longjmp and longjmp-resume breakpoints are also meaningless
3639        after an exec.  */
3640     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3641         || b->type == bp_longjmp_call_dummy
3642         || b->type == bp_exception || b->type == bp_exception_resume)
3643       {
3644         delete_breakpoint (b);
3645         continue;
3646       }
3647
3648     if (b->type == bp_catchpoint)
3649       {
3650         /* For now, none of the bp_catchpoint breakpoints need to
3651            do anything at this point.  In the future, if some of
3652            the catchpoints need to something, we will need to add
3653            a new method, and call this method from here.  */
3654         continue;
3655       }
3656
3657     /* bp_finish is a special case.  The only way we ought to be able
3658        to see one of these when an exec() has happened, is if the user
3659        caught a vfork, and then said "finish".  Ordinarily a finish just
3660        carries them to the call-site of the current callee, by setting
3661        a temporary bp there and resuming.  But in this case, the finish
3662        will carry them entirely through the vfork & exec.
3663
3664        We don't want to allow a bp_finish to remain inserted now.  But
3665        we can't safely delete it, 'cause finish_command has a handle to
3666        the bp on a bpstat, and will later want to delete it.  There's a
3667        chance (and I've seen it happen) that if we delete the bp_finish
3668        here, that its storage will get reused by the time finish_command
3669        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3670        We really must allow finish_command to delete a bp_finish.
3671
3672        In the absence of a general solution for the "how do we know
3673        it's safe to delete something others may have handles to?"
3674        problem, what we'll do here is just uninsert the bp_finish, and
3675        let finish_command delete it.
3676
3677        (We know the bp_finish is "doomed" in the sense that it's
3678        momentary, and will be deleted as soon as finish_command sees
3679        the inferior stopped.  So it doesn't matter that the bp's
3680        address is probably bogus in the new a.out, unlike e.g., the
3681        solib breakpoints.)  */
3682
3683     if (b->type == bp_finish)
3684       {
3685         continue;
3686       }
3687
3688     /* Without a symbolic address, we have little hope of the
3689        pre-exec() address meaning the same thing in the post-exec()
3690        a.out.  */
3691     if (breakpoint_event_location_empty_p (b))
3692       {
3693         delete_breakpoint (b);
3694         continue;
3695       }
3696   }
3697 }
3698
3699 int
3700 detach_breakpoints (ptid_t ptid)
3701 {
3702   struct bp_location *bl, **blp_tmp;
3703   int val = 0;
3704   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
3705   struct inferior *inf = current_inferior ();
3706
3707   if (ptid.pid () == inferior_ptid.pid ())
3708     error (_("Cannot detach breakpoints of inferior_ptid"));
3709
3710   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3711   inferior_ptid = ptid;
3712   ALL_BP_LOCATIONS (bl, blp_tmp)
3713   {
3714     if (bl->pspace != inf->pspace)
3715       continue;
3716
3717     /* This function must physically remove breakpoints locations
3718        from the specified ptid, without modifying the breakpoint
3719        package's state.  Locations of type bp_loc_other are only
3720        maintained at GDB side.  So, there is no need to remove
3721        these bp_loc_other locations.  Moreover, removing these
3722        would modify the breakpoint package's state.  */
3723     if (bl->loc_type == bp_loc_other)
3724       continue;
3725
3726     if (bl->inserted)
3727       val |= remove_breakpoint_1 (bl, DETACH_BREAKPOINT);
3728   }
3729
3730   return val;
3731 }
3732
3733 /* Remove the breakpoint location BL from the current address space.
3734    Note that this is used to detach breakpoints from a child fork.
3735    When we get here, the child isn't in the inferior list, and neither
3736    do we have objects to represent its address space --- we should
3737    *not* look at bl->pspace->aspace here.  */
3738
3739 static int
3740 remove_breakpoint_1 (struct bp_location *bl, enum remove_bp_reason reason)
3741 {
3742   int val;
3743
3744   /* BL is never in moribund_locations by our callers.  */
3745   gdb_assert (bl->owner != NULL);
3746
3747   /* The type of none suggests that owner is actually deleted.
3748      This should not ever happen.  */
3749   gdb_assert (bl->owner->type != bp_none);
3750
3751   if (bl->loc_type == bp_loc_software_breakpoint
3752       || bl->loc_type == bp_loc_hardware_breakpoint)
3753     {
3754       /* "Normal" instruction breakpoint: either the standard
3755          trap-instruction bp (bp_breakpoint), or a
3756          bp_hardware_breakpoint.  */
3757
3758       /* First check to see if we have to handle an overlay.  */
3759       if (overlay_debugging == ovly_off
3760           || bl->section == NULL
3761           || !(section_is_overlay (bl->section)))
3762         {
3763           /* No overlay handling: just remove the breakpoint.  */
3764
3765           /* If we're trying to uninsert a memory breakpoint that we
3766              know is set in a dynamic object that is marked
3767              shlib_disabled, then either the dynamic object was
3768              removed with "remove-symbol-file" or with
3769              "nosharedlibrary".  In the former case, we don't know
3770              whether another dynamic object might have loaded over the
3771              breakpoint's address -- the user might well let us know
3772              about it next with add-symbol-file (the whole point of
3773              add-symbol-file is letting the user manually maintain a
3774              list of dynamically loaded objects).  If we have the
3775              breakpoint's shadow memory, that is, this is a software
3776              breakpoint managed by GDB, check whether the breakpoint
3777              is still inserted in memory, to avoid overwriting wrong
3778              code with stale saved shadow contents.  Note that HW
3779              breakpoints don't have shadow memory, as they're
3780              implemented using a mechanism that is not dependent on
3781              being able to modify the target's memory, and as such
3782              they should always be removed.  */
3783           if (bl->shlib_disabled
3784               && bl->target_info.shadow_len != 0
3785               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3786             val = 0;
3787           else
3788             val = bl->owner->ops->remove_location (bl, reason);
3789         }
3790       else
3791         {
3792           /* This breakpoint is in an overlay section.
3793              Did we set a breakpoint at the LMA?  */
3794           if (!overlay_events_enabled)
3795               {
3796                 /* Yes -- overlay event support is not active, so we
3797                    should have set a breakpoint at the LMA.  Remove it.  
3798                 */
3799                 /* Ignore any failures: if the LMA is in ROM, we will
3800                    have already warned when we failed to insert it.  */
3801                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3802                   target_remove_hw_breakpoint (bl->gdbarch,
3803                                                &bl->overlay_target_info);
3804                 else
3805                   target_remove_breakpoint (bl->gdbarch,
3806                                             &bl->overlay_target_info,
3807                                             reason);
3808               }
3809           /* Did we set a breakpoint at the VMA? 
3810              If so, we will have marked the breakpoint 'inserted'.  */
3811           if (bl->inserted)
3812             {
3813               /* Yes -- remove it.  Previously we did not bother to
3814                  remove the breakpoint if the section had been
3815                  unmapped, but let's not rely on that being safe.  We
3816                  don't know what the overlay manager might do.  */
3817
3818               /* However, we should remove *software* breakpoints only
3819                  if the section is still mapped, or else we overwrite
3820                  wrong code with the saved shadow contents.  */
3821               if (bl->loc_type == bp_loc_hardware_breakpoint
3822                   || section_is_mapped (bl->section))
3823                 val = bl->owner->ops->remove_location (bl, reason);
3824               else
3825                 val = 0;
3826             }
3827           else
3828             {
3829               /* No -- not inserted, so no need to remove.  No error.  */
3830               val = 0;
3831             }
3832         }
3833
3834       /* In some cases, we might not be able to remove a breakpoint in
3835          a shared library that has already been removed, but we have
3836          not yet processed the shlib unload event.  Similarly for an
3837          unloaded add-symbol-file object - the user might not yet have
3838          had the chance to remove-symbol-file it.  shlib_disabled will
3839          be set if the library/object has already been removed, but
3840          the breakpoint hasn't been uninserted yet, e.g., after
3841          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3842          always-inserted mode.  */
3843       if (val
3844           && (bl->loc_type == bp_loc_software_breakpoint
3845               && (bl->shlib_disabled
3846                   || solib_name_from_address (bl->pspace, bl->address)
3847                   || shared_objfile_contains_address_p (bl->pspace,
3848                                                         bl->address))))
3849         val = 0;
3850
3851       if (val)
3852         return val;
3853       bl->inserted = (reason == DETACH_BREAKPOINT);
3854     }
3855   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3856     {
3857       gdb_assert (bl->owner->ops != NULL
3858                   && bl->owner->ops->remove_location != NULL);
3859
3860       bl->inserted = (reason == DETACH_BREAKPOINT);
3861       bl->owner->ops->remove_location (bl, reason);
3862
3863       /* Failure to remove any of the hardware watchpoints comes here.  */
3864       if (reason == REMOVE_BREAKPOINT && bl->inserted)
3865         warning (_("Could not remove hardware watchpoint %d."),
3866                  bl->owner->number);
3867     }
3868   else if (bl->owner->type == bp_catchpoint
3869            && breakpoint_enabled (bl->owner)
3870            && !bl->duplicate)
3871     {
3872       gdb_assert (bl->owner->ops != NULL
3873                   && bl->owner->ops->remove_location != NULL);
3874
3875       val = bl->owner->ops->remove_location (bl, reason);
3876       if (val)
3877         return val;
3878
3879       bl->inserted = (reason == DETACH_BREAKPOINT);
3880     }
3881
3882   return 0;
3883 }
3884
3885 static int
3886 remove_breakpoint (struct bp_location *bl)
3887 {
3888   /* BL is never in moribund_locations by our callers.  */
3889   gdb_assert (bl->owner != NULL);
3890
3891   /* The type of none suggests that owner is actually deleted.
3892      This should not ever happen.  */
3893   gdb_assert (bl->owner->type != bp_none);
3894
3895   scoped_restore_current_pspace_and_thread restore_pspace_thread;
3896
3897   switch_to_program_space_and_thread (bl->pspace);
3898
3899   return remove_breakpoint_1 (bl, REMOVE_BREAKPOINT);
3900 }
3901
3902 /* Clear the "inserted" flag in all breakpoints.  */
3903
3904 void
3905 mark_breakpoints_out (void)
3906 {
3907   struct bp_location *bl, **blp_tmp;
3908
3909   ALL_BP_LOCATIONS (bl, blp_tmp)
3910     if (bl->pspace == current_program_space)
3911       bl->inserted = 0;
3912 }
3913
3914 /* Clear the "inserted" flag in all breakpoints and delete any
3915    breakpoints which should go away between runs of the program.
3916
3917    Plus other such housekeeping that has to be done for breakpoints
3918    between runs.
3919
3920    Note: this function gets called at the end of a run (by
3921    generic_mourn_inferior) and when a run begins (by
3922    init_wait_for_inferior).  */
3923
3924
3925
3926 void
3927 breakpoint_init_inferior (enum inf_context context)
3928 {
3929   struct breakpoint *b, *b_tmp;
3930   struct program_space *pspace = current_program_space;
3931
3932   /* If breakpoint locations are shared across processes, then there's
3933      nothing to do.  */
3934   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3935     return;
3936
3937   mark_breakpoints_out ();
3938
3939   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3940   {
3941     if (b->loc && b->loc->pspace != pspace)
3942       continue;
3943
3944     switch (b->type)
3945       {
3946       case bp_call_dummy:
3947       case bp_longjmp_call_dummy:
3948
3949         /* If the call dummy breakpoint is at the entry point it will
3950            cause problems when the inferior is rerun, so we better get
3951            rid of it.  */
3952
3953       case bp_watchpoint_scope:
3954
3955         /* Also get rid of scope breakpoints.  */
3956
3957       case bp_shlib_event:
3958
3959         /* Also remove solib event breakpoints.  Their addresses may
3960            have changed since the last time we ran the program.
3961            Actually we may now be debugging against different target;
3962            and so the solib backend that installed this breakpoint may
3963            not be used in by the target.  E.g.,
3964
3965            (gdb) file prog-linux
3966            (gdb) run               # native linux target
3967            ...
3968            (gdb) kill
3969            (gdb) file prog-win.exe
3970            (gdb) tar rem :9999     # remote Windows gdbserver.
3971         */
3972
3973       case bp_step_resume:
3974
3975         /* Also remove step-resume breakpoints.  */
3976
3977       case bp_single_step:
3978
3979         /* Also remove single-step breakpoints.  */
3980
3981         delete_breakpoint (b);
3982         break;
3983
3984       case bp_watchpoint:
3985       case bp_hardware_watchpoint:
3986       case bp_read_watchpoint:
3987       case bp_access_watchpoint:
3988         {
3989           struct watchpoint *w = (struct watchpoint *) b;
3990
3991           /* Likewise for watchpoints on local expressions.  */
3992           if (w->exp_valid_block != NULL)
3993             delete_breakpoint (b);
3994           else
3995             {
3996               /* Get rid of existing locations, which are no longer
3997                  valid.  New ones will be created in
3998                  update_watchpoint, when the inferior is restarted.
3999                  The next update_global_location_list call will
4000                  garbage collect them.  */
4001               b->loc = NULL;
4002
4003               if (context == inf_starting)
4004                 {
4005                   /* Reset val field to force reread of starting value in
4006                      insert_breakpoints.  */
4007                   w->val.reset (nullptr);
4008                   w->val_valid = false;
4009                 }
4010             }
4011         }
4012         break;
4013       default:
4014         break;
4015       }
4016   }
4017
4018   /* Get rid of the moribund locations.  */
4019   for (bp_location *bl : moribund_locations)
4020     decref_bp_location (&bl);
4021   moribund_locations.clear ();
4022 }
4023
4024 /* These functions concern about actual breakpoints inserted in the
4025    target --- to e.g. check if we need to do decr_pc adjustment or if
4026    we need to hop over the bkpt --- so we check for address space
4027    match, not program space.  */
4028
4029 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4030    exists at PC.  It returns ordinary_breakpoint_here if it's an
4031    ordinary breakpoint, or permanent_breakpoint_here if it's a
4032    permanent breakpoint.
4033    - When continuing from a location with an ordinary breakpoint, we
4034      actually single step once before calling insert_breakpoints.
4035    - When continuing from a location with a permanent breakpoint, we
4036      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4037      the target, to advance the PC past the breakpoint.  */
4038
4039 enum breakpoint_here
4040 breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4041 {
4042   struct bp_location *bl, **blp_tmp;
4043   int any_breakpoint_here = 0;
4044
4045   ALL_BP_LOCATIONS (bl, blp_tmp)
4046     {
4047       if (bl->loc_type != bp_loc_software_breakpoint
4048           && bl->loc_type != bp_loc_hardware_breakpoint)
4049         continue;
4050
4051       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4052       if ((breakpoint_enabled (bl->owner)
4053            || bl->permanent)
4054           && breakpoint_location_address_match (bl, aspace, pc))
4055         {
4056           if (overlay_debugging 
4057               && section_is_overlay (bl->section)
4058               && !section_is_mapped (bl->section))
4059             continue;           /* unmapped overlay -- can't be a match */
4060           else if (bl->permanent)
4061             return permanent_breakpoint_here;
4062           else
4063             any_breakpoint_here = 1;
4064         }
4065     }
4066
4067   return any_breakpoint_here ? ordinary_breakpoint_here : no_breakpoint_here;
4068 }
4069
4070 /* See breakpoint.h.  */
4071
4072 int
4073 breakpoint_in_range_p (const address_space *aspace,
4074                        CORE_ADDR addr, ULONGEST len)
4075 {
4076   struct bp_location *bl, **blp_tmp;
4077
4078   ALL_BP_LOCATIONS (bl, blp_tmp)
4079     {
4080       if (bl->loc_type != bp_loc_software_breakpoint
4081           && bl->loc_type != bp_loc_hardware_breakpoint)
4082         continue;
4083
4084       if ((breakpoint_enabled (bl->owner)
4085            || bl->permanent)
4086           && breakpoint_location_address_range_overlap (bl, aspace,
4087                                                         addr, len))
4088         {
4089           if (overlay_debugging
4090               && section_is_overlay (bl->section)
4091               && !section_is_mapped (bl->section))
4092             {
4093               /* Unmapped overlay -- can't be a match.  */
4094               continue;
4095             }
4096
4097           return 1;
4098         }
4099     }
4100
4101   return 0;
4102 }
4103
4104 /* Return true if there's a moribund breakpoint at PC.  */
4105
4106 int
4107 moribund_breakpoint_here_p (const address_space *aspace, CORE_ADDR pc)
4108 {
4109   for (bp_location *loc : moribund_locations)
4110     if (breakpoint_location_address_match (loc, aspace, pc))
4111       return 1;
4112
4113   return 0;
4114 }
4115
4116 /* Returns non-zero iff BL is inserted at PC, in address space
4117    ASPACE.  */
4118
4119 static int
4120 bp_location_inserted_here_p (struct bp_location *bl,
4121                              const address_space *aspace, CORE_ADDR pc)
4122 {
4123   if (bl->inserted
4124       && breakpoint_address_match (bl->pspace->aspace, bl->address,
4125                                    aspace, pc))
4126     {
4127       if (overlay_debugging
4128           && section_is_overlay (bl->section)
4129           && !section_is_mapped (bl->section))
4130         return 0;               /* unmapped overlay -- can't be a match */
4131       else
4132         return 1;
4133     }
4134   return 0;
4135 }
4136
4137 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4138
4139 int
4140 breakpoint_inserted_here_p (const address_space *aspace, CORE_ADDR pc)
4141 {
4142   struct bp_location **blp, **blp_tmp = NULL;
4143
4144   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4145     {
4146       struct bp_location *bl = *blp;
4147
4148       if (bl->loc_type != bp_loc_software_breakpoint
4149           && bl->loc_type != bp_loc_hardware_breakpoint)
4150         continue;
4151
4152       if (bp_location_inserted_here_p (bl, aspace, pc))
4153         return 1;
4154     }
4155   return 0;
4156 }
4157
4158 /* This function returns non-zero iff there is a software breakpoint
4159    inserted at PC.  */
4160
4161 int
4162 software_breakpoint_inserted_here_p (const address_space *aspace,
4163                                      CORE_ADDR pc)
4164 {
4165   struct bp_location **blp, **blp_tmp = NULL;
4166
4167   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4168     {
4169       struct bp_location *bl = *blp;
4170
4171       if (bl->loc_type != bp_loc_software_breakpoint)
4172         continue;
4173
4174       if (bp_location_inserted_here_p (bl, aspace, pc))
4175         return 1;
4176     }
4177
4178   return 0;
4179 }
4180
4181 /* See breakpoint.h.  */
4182
4183 int
4184 hardware_breakpoint_inserted_here_p (const address_space *aspace,
4185                                      CORE_ADDR pc)
4186 {
4187   struct bp_location **blp, **blp_tmp = NULL;
4188
4189   ALL_BP_LOCATIONS_AT_ADDR (blp, blp_tmp, pc)
4190     {
4191       struct bp_location *bl = *blp;
4192
4193       if (bl->loc_type != bp_loc_hardware_breakpoint)
4194         continue;
4195
4196       if (bp_location_inserted_here_p (bl, aspace, pc))
4197         return 1;
4198     }
4199
4200   return 0;
4201 }
4202
4203 int
4204 hardware_watchpoint_inserted_in_range (const address_space *aspace,
4205                                        CORE_ADDR addr, ULONGEST len)
4206 {
4207   struct breakpoint *bpt;
4208
4209   ALL_BREAKPOINTS (bpt)
4210     {
4211       struct bp_location *loc;
4212
4213       if (bpt->type != bp_hardware_watchpoint
4214           && bpt->type != bp_access_watchpoint)
4215         continue;
4216
4217       if (!breakpoint_enabled (bpt))
4218         continue;
4219
4220       for (loc = bpt->loc; loc; loc = loc->next)
4221         if (loc->pspace->aspace == aspace && loc->inserted)
4222           {
4223             CORE_ADDR l, h;
4224
4225             /* Check for intersection.  */
4226             l = std::max<CORE_ADDR> (loc->address, addr);
4227             h = std::min<CORE_ADDR> (loc->address + loc->length, addr + len);
4228             if (l < h)
4229               return 1;
4230           }
4231     }
4232   return 0;
4233 }
4234
4235 /* See breakpoint.h.  */
4236
4237 bool
4238 is_catchpoint (struct breakpoint *b)
4239 {
4240   return (b->type == bp_catchpoint);
4241 }
4242
4243 /* Clear a bpstat so that it says we are not at any breakpoint.
4244    Also free any storage that is part of a bpstat.  */
4245
4246 void
4247 bpstat_clear (bpstat *bsp)
4248 {
4249   bpstat p;
4250   bpstat q;
4251
4252   if (bsp == 0)
4253     return;
4254   p = *bsp;
4255   while (p != NULL)
4256     {
4257       q = p->next;
4258       delete p;
4259       p = q;
4260     }
4261   *bsp = NULL;
4262 }
4263
4264 bpstats::bpstats (const bpstats &other)
4265   : next (NULL),
4266     bp_location_at (other.bp_location_at),
4267     breakpoint_at (other.breakpoint_at),
4268     commands (other.commands),
4269     print (other.print),
4270     stop (other.stop),
4271     print_it (other.print_it)
4272 {
4273   if (other.old_val != NULL)
4274     old_val = release_value (value_copy (other.old_val.get ()));
4275 }
4276
4277 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4278    is part of the bpstat is copied as well.  */
4279
4280 bpstat
4281 bpstat_copy (bpstat bs)
4282 {
4283   bpstat p = NULL;
4284   bpstat tmp;
4285   bpstat retval = NULL;
4286
4287   if (bs == NULL)
4288     return bs;
4289
4290   for (; bs != NULL; bs = bs->next)
4291     {
4292       tmp = new bpstats (*bs);
4293
4294       if (p == NULL)
4295         /* This is the first thing in the chain.  */
4296         retval = tmp;
4297       else
4298         p->next = tmp;
4299       p = tmp;
4300     }
4301   p->next = NULL;
4302   return retval;
4303 }
4304
4305 /* Find the bpstat associated with this breakpoint.  */
4306
4307 bpstat
4308 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4309 {
4310   if (bsp == NULL)
4311     return NULL;
4312
4313   for (; bsp != NULL; bsp = bsp->next)
4314     {
4315       if (bsp->breakpoint_at == breakpoint)
4316         return bsp;
4317     }
4318   return NULL;
4319 }
4320
4321 /* See breakpoint.h.  */
4322
4323 bool
4324 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4325 {
4326   for (; bsp != NULL; bsp = bsp->next)
4327     {
4328       if (bsp->breakpoint_at == NULL)
4329         {
4330           /* A moribund location can never explain a signal other than
4331              GDB_SIGNAL_TRAP.  */
4332           if (sig == GDB_SIGNAL_TRAP)
4333             return true;
4334         }
4335       else
4336         {
4337           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4338                                                         sig))
4339             return true;
4340         }
4341     }
4342
4343   return false;
4344 }
4345
4346 /* Put in *NUM the breakpoint number of the first breakpoint we are
4347    stopped at.  *BSP upon return is a bpstat which points to the
4348    remaining breakpoints stopped at (but which is not guaranteed to be
4349    good for anything but further calls to bpstat_num).
4350
4351    Return 0 if passed a bpstat which does not indicate any breakpoints.
4352    Return -1 if stopped at a breakpoint that has been deleted since
4353    we set it.
4354    Return 1 otherwise.  */
4355
4356 int
4357 bpstat_num (bpstat *bsp, int *num)
4358 {
4359   struct breakpoint *b;
4360
4361   if ((*bsp) == NULL)
4362     return 0;                   /* No more breakpoint values */
4363
4364   /* We assume we'll never have several bpstats that correspond to a
4365      single breakpoint -- otherwise, this function might return the
4366      same number more than once and this will look ugly.  */
4367   b = (*bsp)->breakpoint_at;
4368   *bsp = (*bsp)->next;
4369   if (b == NULL)
4370     return -1;                  /* breakpoint that's been deleted since */
4371
4372   *num = b->number;             /* We have its number */
4373   return 1;
4374 }
4375
4376 /* See breakpoint.h.  */
4377
4378 void
4379 bpstat_clear_actions (void)
4380 {
4381   bpstat bs;
4382
4383   if (inferior_ptid == null_ptid)
4384     return;
4385
4386   thread_info *tp = inferior_thread ();
4387   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4388     {
4389       bs->commands = NULL;
4390       bs->old_val.reset (nullptr);
4391     }
4392 }
4393
4394 /* Called when a command is about to proceed the inferior.  */
4395
4396 static void
4397 breakpoint_about_to_proceed (void)
4398 {
4399   if (inferior_ptid != null_ptid)
4400     {
4401       struct thread_info *tp = inferior_thread ();
4402
4403       /* Allow inferior function calls in breakpoint commands to not
4404          interrupt the command list.  When the call finishes
4405          successfully, the inferior will be standing at the same
4406          breakpoint as if nothing happened.  */
4407       if (tp->control.in_infcall)
4408         return;
4409     }
4410
4411   breakpoint_proceeded = 1;
4412 }
4413
4414 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4415    or its equivalent.  */
4416
4417 static int
4418 command_line_is_silent (struct command_line *cmd)
4419 {
4420   return cmd && (strcmp ("silent", cmd->line) == 0);
4421 }
4422
4423 /* Execute all the commands associated with all the breakpoints at
4424    this location.  Any of these commands could cause the process to
4425    proceed beyond this point, etc.  We look out for such changes by
4426    checking the global "breakpoint_proceeded" after each command.
4427
4428    Returns true if a breakpoint command resumed the inferior.  In that
4429    case, it is the caller's responsibility to recall it again with the
4430    bpstat of the current thread.  */
4431
4432 static int
4433 bpstat_do_actions_1 (bpstat *bsp)
4434 {
4435   bpstat bs;
4436   int again = 0;
4437
4438   /* Avoid endless recursion if a `source' command is contained
4439      in bs->commands.  */
4440   if (executing_breakpoint_commands)
4441     return 0;
4442
4443   scoped_restore save_executing
4444     = make_scoped_restore (&executing_breakpoint_commands, 1);
4445
4446   scoped_restore preventer = prevent_dont_repeat ();
4447
4448   /* This pointer will iterate over the list of bpstat's.  */
4449   bs = *bsp;
4450
4451   breakpoint_proceeded = 0;
4452   for (; bs != NULL; bs = bs->next)
4453     {
4454       struct command_line *cmd = NULL;
4455
4456       /* Take ownership of the BSP's command tree, if it has one.
4457
4458          The command tree could legitimately contain commands like
4459          'step' and 'next', which call clear_proceed_status, which
4460          frees stop_bpstat's command tree.  To make sure this doesn't
4461          free the tree we're executing out from under us, we need to
4462          take ownership of the tree ourselves.  Since a given bpstat's
4463          commands are only executed once, we don't need to copy it; we
4464          can clear the pointer in the bpstat, and make sure we free
4465          the tree when we're done.  */
4466       counted_command_line ccmd = bs->commands;
4467       bs->commands = NULL;
4468       if (ccmd != NULL)
4469         cmd = ccmd.get ();
4470       if (command_line_is_silent (cmd))
4471         {
4472           /* The action has been already done by bpstat_stop_status.  */
4473           cmd = cmd->next;
4474         }
4475
4476       while (cmd != NULL)
4477         {
4478           execute_control_command (cmd);
4479
4480           if (breakpoint_proceeded)
4481             break;
4482           else
4483             cmd = cmd->next;
4484         }
4485
4486       if (breakpoint_proceeded)
4487         {
4488           if (current_ui->async)
4489             /* If we are in async mode, then the target might be still
4490                running, not stopped at any breakpoint, so nothing for
4491                us to do here -- just return to the event loop.  */
4492             ;
4493           else
4494             /* In sync mode, when execute_control_command returns
4495                we're already standing on the next breakpoint.
4496                Breakpoint commands for that stop were not run, since
4497                execute_command does not run breakpoint commands --
4498                only command_line_handler does, but that one is not
4499                involved in execution of breakpoint commands.  So, we
4500                can now execute breakpoint commands.  It should be
4501                noted that making execute_command do bpstat actions is
4502                not an option -- in this case we'll have recursive
4503                invocation of bpstat for each breakpoint with a
4504                command, and can easily blow up GDB stack.  Instead, we
4505                return true, which will trigger the caller to recall us
4506                with the new stop_bpstat.  */
4507             again = 1;
4508           break;
4509         }
4510     }
4511   return again;
4512 }
4513
4514 /* Helper for bpstat_do_actions.  Get the current thread, if there's
4515    one, is alive and has execution.  Return NULL otherwise.  */
4516
4517 static thread_info *
4518 get_bpstat_thread ()
4519 {
4520   if (inferior_ptid == null_ptid || !target_has_execution ())
4521     return NULL;
4522
4523   thread_info *tp = inferior_thread ();
4524   if (tp->state == THREAD_EXITED || tp->executing)
4525     return NULL;
4526   return tp;
4527 }
4528
4529 void
4530 bpstat_do_actions (void)
4531 {
4532   auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
4533   thread_info *tp;
4534
4535   /* Do any commands attached to breakpoint we are stopped at.  */
4536   while ((tp = get_bpstat_thread ()) != NULL)
4537     {
4538       /* Since in sync mode, bpstat_do_actions may resume the
4539          inferior, and only return when it is stopped at the next
4540          breakpoint, we keep doing breakpoint actions until it returns
4541          false to indicate the inferior was not resumed.  */
4542       if (!bpstat_do_actions_1 (&tp->control.stop_bpstat))
4543         break;
4544     }
4545
4546   cleanup_if_error.release ();
4547 }
4548
4549 /* Print out the (old or new) value associated with a watchpoint.  */
4550
4551 static void
4552 watchpoint_value_print (struct value *val, struct ui_file *stream)
4553 {
4554   if (val == NULL)
4555     fprintf_styled (stream, metadata_style.style (), _("<unreadable>"));
4556   else
4557     {
4558       struct value_print_options opts;
4559       get_user_print_options (&opts);
4560       value_print (val, stream, &opts);
4561     }
4562 }
4563
4564 /* Print the "Thread ID hit" part of "Thread ID hit Breakpoint N" if
4565    debugging multiple threads.  */
4566
4567 void
4568 maybe_print_thread_hit_breakpoint (struct ui_out *uiout)
4569 {
4570   if (uiout->is_mi_like_p ())
4571     return;
4572
4573   uiout->text ("\n");
4574
4575   if (show_thread_that_caused_stop ())
4576     {
4577       const char *name;
4578       struct thread_info *thr = inferior_thread ();
4579
4580       uiout->text ("Thread ");
4581       uiout->field_string ("thread-id", print_thread_id (thr));
4582
4583       name = thr->name != NULL ? thr->name : target_thread_name (thr);
4584       if (name != NULL)
4585         {
4586           uiout->text (" \"");
4587           uiout->field_string ("name", name);
4588           uiout->text ("\"");
4589         }
4590
4591       uiout->text (" hit ");
4592     }
4593 }
4594
4595 /* Generic routine for printing messages indicating why we
4596    stopped.  The behavior of this function depends on the value
4597    'print_it' in the bpstat structure.  Under some circumstances we
4598    may decide not to print anything here and delegate the task to
4599    normal_stop().  */
4600
4601 static enum print_stop_action
4602 print_bp_stop_message (bpstat bs)
4603 {
4604   switch (bs->print_it)
4605     {
4606     case print_it_noop:
4607       /* Nothing should be printed for this bpstat entry.  */
4608       return PRINT_UNKNOWN;
4609       break;
4610
4611     case print_it_done:
4612       /* We still want to print the frame, but we already printed the
4613          relevant messages.  */
4614       return PRINT_SRC_AND_LOC;
4615       break;
4616
4617     case print_it_normal:
4618       {
4619         struct breakpoint *b = bs->breakpoint_at;
4620
4621         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4622            which has since been deleted.  */
4623         if (b == NULL)
4624           return PRINT_UNKNOWN;
4625
4626         /* Normal case.  Call the breakpoint's print_it method.  */
4627         return b->ops->print_it (bs);
4628       }
4629       break;
4630
4631     default:
4632       internal_error (__FILE__, __LINE__,
4633                       _("print_bp_stop_message: unrecognized enum value"));
4634       break;
4635     }
4636 }
4637
4638 /* A helper function that prints a shared library stopped event.  */
4639
4640 static void
4641 print_solib_event (int is_catchpoint)
4642 {
4643   bool any_deleted = !current_program_space->deleted_solibs.empty ();
4644   bool any_added = !current_program_space->added_solibs.empty ();
4645
4646   if (!is_catchpoint)
4647     {
4648       if (any_added || any_deleted)
4649         current_uiout->text (_("Stopped due to shared library event:\n"));
4650       else
4651         current_uiout->text (_("Stopped due to shared library event (no "
4652                                "libraries added or removed)\n"));
4653     }
4654
4655   if (current_uiout->is_mi_like_p ())
4656     current_uiout->field_string ("reason",
4657                                  async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4658
4659   if (any_deleted)
4660     {
4661       current_uiout->text (_("  Inferior unloaded "));
4662       ui_out_emit_list list_emitter (current_uiout, "removed");
4663       for (int ix = 0; ix < current_program_space->deleted_solibs.size (); ix++)
4664         {
4665           const std::string &name = current_program_space->deleted_solibs[ix];
4666
4667           if (ix > 0)
4668             current_uiout->text ("    ");
4669           current_uiout->field_string ("library", name);
4670           current_uiout->text ("\n");
4671         }
4672     }
4673
4674   if (any_added)
4675     {
4676       current_uiout->text (_("  Inferior loaded "));
4677       ui_out_emit_list list_emitter (current_uiout, "added");
4678       bool first = true;
4679       for (so_list *iter : current_program_space->added_solibs)
4680         {
4681           if (!first)
4682             current_uiout->text ("    ");
4683           first = false;
4684           current_uiout->field_string ("library", iter->so_name);
4685           current_uiout->text ("\n");
4686         }
4687     }
4688 }
4689
4690 /* Print a message indicating what happened.  This is called from
4691    normal_stop().  The input to this routine is the head of the bpstat
4692    list - a list of the eventpoints that caused this stop.  KIND is
4693    the target_waitkind for the stopping event.  This
4694    routine calls the generic print routine for printing a message
4695    about reasons for stopping.  This will print (for example) the
4696    "Breakpoint n," part of the output.  The return value of this
4697    routine is one of:
4698
4699    PRINT_UNKNOWN: Means we printed nothing.
4700    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4701    code to print the location.  An example is 
4702    "Breakpoint 1, " which should be followed by
4703    the location.
4704    PRINT_SRC_ONLY: Means we printed something, but there is no need
4705    to also print the location part of the message.
4706    An example is the catch/throw messages, which
4707    don't require a location appended to the end.
4708    PRINT_NOTHING: We have done some printing and we don't need any 
4709    further info to be printed.  */
4710
4711 enum print_stop_action
4712 bpstat_print (bpstat bs, int kind)
4713 {
4714   enum print_stop_action val;
4715
4716   /* Maybe another breakpoint in the chain caused us to stop.
4717      (Currently all watchpoints go on the bpstat whether hit or not.
4718      That probably could (should) be changed, provided care is taken
4719      with respect to bpstat_explains_signal).  */
4720   for (; bs; bs = bs->next)
4721     {
4722       val = print_bp_stop_message (bs);
4723       if (val == PRINT_SRC_ONLY 
4724           || val == PRINT_SRC_AND_LOC 
4725           || val == PRINT_NOTHING)
4726         return val;
4727     }
4728
4729   /* If we had hit a shared library event breakpoint,
4730      print_bp_stop_message would print out this message.  If we hit an
4731      OS-level shared library event, do the same thing.  */
4732   if (kind == TARGET_WAITKIND_LOADED)
4733     {
4734       print_solib_event (0);
4735       return PRINT_NOTHING;
4736     }
4737
4738   /* We reached the end of the chain, or we got a null BS to start
4739      with and nothing was printed.  */
4740   return PRINT_UNKNOWN;
4741 }
4742
4743 /* Evaluate the boolean expression EXP and return the result.  */
4744
4745 static bool
4746 breakpoint_cond_eval (expression *exp)
4747 {
4748   struct value *mark = value_mark ();
4749   bool res = value_true (evaluate_expression (exp));
4750
4751   value_free_to_mark (mark);
4752   return res;
4753 }
4754
4755 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4756
4757 bpstats::bpstats (struct bp_location *bl, bpstat **bs_link_pointer)
4758   : next (NULL),
4759     bp_location_at (bp_location_ref_ptr::new_reference (bl)),
4760     breakpoint_at (bl->owner),
4761     commands (NULL),
4762     print (0),
4763     stop (0),
4764     print_it (print_it_normal)
4765 {
4766   **bs_link_pointer = this;
4767   *bs_link_pointer = &next;
4768 }
4769
4770 bpstats::bpstats ()
4771   : next (NULL),
4772     breakpoint_at (NULL),
4773     commands (NULL),
4774     print (0),
4775     stop (0),
4776     print_it (print_it_normal)
4777 {
4778 }
4779 \f
4780 /* The target has stopped with waitstatus WS.  Check if any hardware
4781    watchpoints have triggered, according to the target.  */
4782
4783 int
4784 watchpoints_triggered (struct target_waitstatus *ws)
4785 {
4786   bool stopped_by_watchpoint = target_stopped_by_watchpoint ();
4787   CORE_ADDR addr;
4788   struct breakpoint *b;
4789
4790   if (!stopped_by_watchpoint)
4791     {
4792       /* We were not stopped by a watchpoint.  Mark all watchpoints
4793          as not triggered.  */
4794       ALL_BREAKPOINTS (b)
4795         if (is_hardware_watchpoint (b))
4796           {
4797             struct watchpoint *w = (struct watchpoint *) b;
4798
4799             w->watchpoint_triggered = watch_triggered_no;
4800           }
4801
4802       return 0;
4803     }
4804
4805   if (!target_stopped_data_address (current_top_target (), &addr))
4806     {
4807       /* We were stopped by a watchpoint, but we don't know where.
4808          Mark all watchpoints as unknown.  */
4809       ALL_BREAKPOINTS (b)
4810         if (is_hardware_watchpoint (b))
4811           {
4812             struct watchpoint *w = (struct watchpoint *) b;
4813
4814             w->watchpoint_triggered = watch_triggered_unknown;
4815           }
4816
4817       return 1;
4818     }
4819
4820   /* The target could report the data address.  Mark watchpoints
4821      affected by this data address as triggered, and all others as not
4822      triggered.  */
4823
4824   ALL_BREAKPOINTS (b)
4825     if (is_hardware_watchpoint (b))
4826       {
4827         struct watchpoint *w = (struct watchpoint *) b;
4828         struct bp_location *loc;
4829
4830         w->watchpoint_triggered = watch_triggered_no;
4831         for (loc = b->loc; loc; loc = loc->next)
4832           {
4833             if (is_masked_watchpoint (b))
4834               {
4835                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4836                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4837
4838                 if (newaddr == start)
4839                   {
4840                     w->watchpoint_triggered = watch_triggered_yes;
4841                     break;
4842                   }
4843               }
4844             /* Exact match not required.  Within range is sufficient.  */
4845             else if (target_watchpoint_addr_within_range (current_top_target (),
4846                                                          addr, loc->address,
4847                                                          loc->length))
4848               {
4849                 w->watchpoint_triggered = watch_triggered_yes;
4850                 break;
4851               }
4852           }
4853       }
4854
4855   return 1;
4856 }
4857
4858 /* Possible return values for watchpoint_check.  */
4859 enum wp_check_result
4860   {
4861     /* The watchpoint has been deleted.  */
4862     WP_DELETED = 1,
4863
4864     /* The value has changed.  */
4865     WP_VALUE_CHANGED = 2,
4866
4867     /* The value has not changed.  */
4868     WP_VALUE_NOT_CHANGED = 3,
4869
4870     /* Ignore this watchpoint, no matter if the value changed or not.  */
4871     WP_IGNORE = 4,
4872   };
4873
4874 #define BP_TEMPFLAG 1
4875 #define BP_HARDWAREFLAG 2
4876
4877 /* Evaluate watchpoint condition expression and check if its value
4878    changed.  */
4879
4880 static wp_check_result
4881 watchpoint_check (bpstat bs)
4882 {
4883   struct watchpoint *b;
4884   struct frame_info *fr;
4885   int within_current_scope;
4886
4887   /* BS is built from an existing struct breakpoint.  */
4888   gdb_assert (bs->breakpoint_at != NULL);
4889   b = (struct watchpoint *) bs->breakpoint_at;
4890
4891   /* If this is a local watchpoint, we only want to check if the
4892      watchpoint frame is in scope if the current thread is the thread
4893      that was used to create the watchpoint.  */
4894   if (!watchpoint_in_thread_scope (b))
4895     return WP_IGNORE;
4896
4897   if (b->exp_valid_block == NULL)
4898     within_current_scope = 1;
4899   else
4900     {
4901       struct frame_info *frame = get_current_frame ();
4902       struct gdbarch *frame_arch = get_frame_arch (frame);
4903       CORE_ADDR frame_pc = get_frame_pc (frame);
4904
4905       /* stack_frame_destroyed_p() returns a non-zero value if we're
4906          still in the function but the stack frame has already been
4907          invalidated.  Since we can't rely on the values of local
4908          variables after the stack has been destroyed, we are treating
4909          the watchpoint in that state as `not changed' without further
4910          checking.  Don't mark watchpoints as changed if the current
4911          frame is in an epilogue - even if they are in some other
4912          frame, our view of the stack is likely to be wrong and
4913          frame_find_by_id could error out.  */
4914       if (gdbarch_stack_frame_destroyed_p (frame_arch, frame_pc))
4915         return WP_IGNORE;
4916
4917       fr = frame_find_by_id (b->watchpoint_frame);
4918       within_current_scope = (fr != NULL);
4919
4920       /* If we've gotten confused in the unwinder, we might have
4921          returned a frame that can't describe this variable.  */
4922       if (within_current_scope)
4923         {
4924           struct symbol *function;
4925
4926           function = get_frame_function (fr);
4927           if (function == NULL
4928               || !contained_in (b->exp_valid_block,
4929                                 SYMBOL_BLOCK_VALUE (function)))
4930             within_current_scope = 0;
4931         }
4932
4933       if (within_current_scope)
4934         /* If we end up stopping, the current frame will get selected
4935            in normal_stop.  So this call to select_frame won't affect
4936            the user.  */
4937         select_frame (fr);
4938     }
4939
4940   if (within_current_scope)
4941     {
4942       /* We use value_{,free_to_}mark because it could be a *long*
4943          time before we return to the command level and call
4944          free_all_values.  We can't call free_all_values because we
4945          might be in the middle of evaluating a function call.  */
4946
4947       int pc = 0;
4948       struct value *mark;
4949       struct value *new_val;
4950
4951       if (is_masked_watchpoint (b))
4952         /* Since we don't know the exact trigger address (from
4953            stopped_data_address), just tell the user we've triggered
4954            a mask watchpoint.  */
4955         return WP_VALUE_CHANGED;
4956
4957       mark = value_mark ();
4958       fetch_subexp_value (b->exp.get (), &pc, &new_val, NULL, NULL, false);
4959
4960       if (b->val_bitsize != 0)
4961         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
4962
4963       /* We use value_equal_contents instead of value_equal because
4964          the latter coerces an array to a pointer, thus comparing just
4965          the address of the array instead of its contents.  This is
4966          not what we want.  */
4967       if ((b->val != NULL) != (new_val != NULL)
4968           || (b->val != NULL && !value_equal_contents (b->val.get (),
4969                                                        new_val)))
4970         {
4971           bs->old_val = b->val;
4972           b->val = release_value (new_val);
4973           b->val_valid = true;
4974           if (new_val != NULL)
4975             value_free_to_mark (mark);
4976           return WP_VALUE_CHANGED;
4977         }
4978       else
4979         {
4980           /* Nothing changed.  */
4981           value_free_to_mark (mark);
4982           return WP_VALUE_NOT_CHANGED;
4983         }
4984     }
4985   else
4986     {
4987       /* This seems like the only logical thing to do because
4988          if we temporarily ignored the watchpoint, then when
4989          we reenter the block in which it is valid it contains
4990          garbage (in the case of a function, it may have two
4991          garbage values, one before and one after the prologue).
4992          So we can't even detect the first assignment to it and
4993          watch after that (since the garbage may or may not equal
4994          the first value assigned).  */
4995       /* We print all the stop information in
4996          breakpoint_ops->print_it, but in this case, by the time we
4997          call breakpoint_ops->print_it this bp will be deleted
4998          already.  So we have no choice but print the information
4999          here.  */
5000
5001       SWITCH_THRU_ALL_UIS ()
5002         {
5003           struct ui_out *uiout = current_uiout;
5004
5005           if (uiout->is_mi_like_p ())
5006             uiout->field_string
5007               ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5008           uiout->message ("\nWatchpoint %pF deleted because the program has "
5009                           "left the block in\n"
5010                           "which its expression is valid.\n",
5011                           signed_field ("wpnum", b->number));
5012         }
5013
5014       /* Make sure the watchpoint's commands aren't executed.  */
5015       b->commands = NULL;
5016       watchpoint_del_at_next_stop (b);
5017
5018       return WP_DELETED;
5019     }
5020 }
5021
5022 /* Return true if it looks like target has stopped due to hitting
5023    breakpoint location BL.  This function does not check if we should
5024    stop, only if BL explains the stop.  */
5025
5026 static int
5027 bpstat_check_location (const struct bp_location *bl,
5028                        const address_space *aspace, CORE_ADDR bp_addr,
5029                        const struct target_waitstatus *ws)
5030 {
5031   struct breakpoint *b = bl->owner;
5032
5033   /* BL is from an existing breakpoint.  */
5034   gdb_assert (b != NULL);
5035
5036   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5037 }
5038
5039 /* Determine if the watched values have actually changed, and we
5040    should stop.  If not, set BS->stop to 0.  */
5041
5042 static void
5043 bpstat_check_watchpoint (bpstat bs)
5044 {
5045   const struct bp_location *bl;
5046   struct watchpoint *b;
5047
5048   /* BS is built for existing struct breakpoint.  */
5049   bl = bs->bp_location_at.get ();
5050   gdb_assert (bl != NULL);
5051   b = (struct watchpoint *) bs->breakpoint_at;
5052   gdb_assert (b != NULL);
5053
5054     {
5055       int must_check_value = 0;
5056       
5057       if (b->type == bp_watchpoint)
5058         /* For a software watchpoint, we must always check the
5059            watched value.  */
5060         must_check_value = 1;
5061       else if (b->watchpoint_triggered == watch_triggered_yes)
5062         /* We have a hardware watchpoint (read, write, or access)
5063            and the target earlier reported an address watched by
5064            this watchpoint.  */
5065         must_check_value = 1;
5066       else if (b->watchpoint_triggered == watch_triggered_unknown
5067                && b->type == bp_hardware_watchpoint)
5068         /* We were stopped by a hardware watchpoint, but the target could
5069            not report the data address.  We must check the watchpoint's
5070            value.  Access and read watchpoints are out of luck; without
5071            a data address, we can't figure it out.  */
5072         must_check_value = 1;
5073
5074       if (must_check_value)
5075         {
5076           wp_check_result e;
5077
5078           try
5079             {
5080               e = watchpoint_check (bs);
5081             }
5082           catch (const gdb_exception &ex)
5083             {
5084               exception_fprintf (gdb_stderr, ex,
5085                                  "Error evaluating expression "
5086                                  "for watchpoint %d\n",
5087                                  b->number);
5088
5089               SWITCH_THRU_ALL_UIS ()
5090                 {
5091                   printf_filtered (_("Watchpoint %d deleted.\n"),
5092                                    b->number);
5093                 }
5094               watchpoint_del_at_next_stop (b);
5095               e = WP_DELETED;
5096             }
5097
5098           switch (e)
5099             {
5100             case WP_DELETED:
5101               /* We've already printed what needs to be printed.  */
5102               bs->print_it = print_it_done;
5103               /* Stop.  */
5104               break;
5105             case WP_IGNORE:
5106               bs->print_it = print_it_noop;
5107               bs->stop = 0;
5108               break;
5109             case WP_VALUE_CHANGED:
5110               if (b->type == bp_read_watchpoint)
5111                 {
5112                   /* There are two cases to consider here:
5113
5114                      1. We're watching the triggered memory for reads.
5115                      In that case, trust the target, and always report
5116                      the watchpoint hit to the user.  Even though
5117                      reads don't cause value changes, the value may
5118                      have changed since the last time it was read, and
5119                      since we're not trapping writes, we will not see
5120                      those, and as such we should ignore our notion of
5121                      old value.
5122
5123                      2. We're watching the triggered memory for both
5124                      reads and writes.  There are two ways this may
5125                      happen:
5126
5127                      2.1. This is a target that can't break on data
5128                      reads only, but can break on accesses (reads or
5129                      writes), such as e.g., x86.  We detect this case
5130                      at the time we try to insert read watchpoints.
5131
5132                      2.2. Otherwise, the target supports read
5133                      watchpoints, but, the user set an access or write
5134                      watchpoint watching the same memory as this read
5135                      watchpoint.
5136
5137                      If we're watching memory writes as well as reads,
5138                      ignore watchpoint hits when we find that the
5139                      value hasn't changed, as reads don't cause
5140                      changes.  This still gives false positives when
5141                      the program writes the same value to memory as
5142                      what there was already in memory (we will confuse
5143                      it for a read), but it's much better than
5144                      nothing.  */
5145
5146                   int other_write_watchpoint = 0;
5147
5148                   if (bl->watchpoint_type == hw_read)
5149                     {
5150                       struct breakpoint *other_b;
5151
5152                       ALL_BREAKPOINTS (other_b)
5153                         if (other_b->type == bp_hardware_watchpoint
5154                             || other_b->type == bp_access_watchpoint)
5155                           {
5156                             struct watchpoint *other_w =
5157                               (struct watchpoint *) other_b;
5158
5159                             if (other_w->watchpoint_triggered
5160                                 == watch_triggered_yes)
5161                               {
5162                                 other_write_watchpoint = 1;
5163                                 break;
5164                               }
5165                           }
5166                     }
5167
5168                   if (other_write_watchpoint
5169                       || bl->watchpoint_type == hw_access)
5170                     {
5171                       /* We're watching the same memory for writes,
5172                          and the value changed since the last time we
5173                          updated it, so this trap must be for a write.
5174                          Ignore it.  */
5175                       bs->print_it = print_it_noop;
5176                       bs->stop = 0;
5177                     }
5178                 }
5179               break;
5180             case WP_VALUE_NOT_CHANGED:
5181               if (b->type == bp_hardware_watchpoint
5182                   || b->type == bp_watchpoint)
5183                 {
5184                   /* Don't stop: write watchpoints shouldn't fire if
5185                      the value hasn't changed.  */
5186                   bs->print_it = print_it_noop;
5187                   bs->stop = 0;
5188                 }
5189               /* Stop.  */
5190               break;
5191             default:
5192               /* Can't happen.  */
5193               break;
5194             }
5195         }
5196       else      /* must_check_value == 0 */
5197         {
5198           /* This is a case where some watchpoint(s) triggered, but
5199              not at the address of this watchpoint, or else no
5200              watchpoint triggered after all.  So don't print
5201              anything for this watchpoint.  */
5202           bs->print_it = print_it_noop;
5203           bs->stop = 0;
5204         }
5205     }
5206 }
5207
5208 /* For breakpoints that are currently marked as telling gdb to stop,
5209    check conditions (condition proper, frame, thread and ignore count)
5210    of breakpoint referred to by BS.  If we should not stop for this
5211    breakpoint, set BS->stop to 0.  */
5212
5213 static void
5214 bpstat_check_breakpoint_conditions (bpstat bs, thread_info *thread)
5215 {
5216   const struct bp_location *bl;
5217   struct breakpoint *b;
5218   /* Assume stop.  */
5219   bool condition_result = true;
5220   struct expression *cond;
5221
5222   gdb_assert (bs->stop);
5223
5224   /* BS is built for existing struct breakpoint.  */
5225   bl = bs->bp_location_at.get ();
5226   gdb_assert (bl != NULL);
5227   b = bs->breakpoint_at;
5228   gdb_assert (b != NULL);
5229
5230   /* Even if the target evaluated the condition on its end and notified GDB, we
5231      need to do so again since GDB does not know if we stopped due to a
5232      breakpoint or a single step breakpoint.  */
5233
5234   if (frame_id_p (b->frame_id)
5235       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5236     {
5237       bs->stop = 0;
5238       return;
5239     }
5240
5241   /* If this is a thread/task-specific breakpoint, don't waste cpu
5242      evaluating the condition if this isn't the specified
5243      thread/task.  */
5244   if ((b->thread != -1 && b->thread != thread->global_num)
5245       || (b->task != 0 && b->task != ada_get_task_number (thread)))
5246     {
5247       bs->stop = 0;
5248       return;
5249     }
5250
5251   /* Evaluate extension language breakpoints that have a "stop" method
5252      implemented.  */
5253   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5254
5255   if (is_watchpoint (b))
5256     {
5257       struct watchpoint *w = (struct watchpoint *) b;
5258
5259       cond = w->cond_exp.get ();
5260     }
5261   else
5262     cond = bl->cond.get ();
5263
5264   if (cond && b->disposition != disp_del_at_next_stop)
5265     {
5266       int within_current_scope = 1;
5267       struct watchpoint * w;
5268
5269       /* We use value_mark and value_free_to_mark because it could
5270          be a long time before we return to the command level and
5271          call free_all_values.  We can't call free_all_values
5272          because we might be in the middle of evaluating a
5273          function call.  */
5274       struct value *mark = value_mark ();
5275
5276       if (is_watchpoint (b))
5277         w = (struct watchpoint *) b;
5278       else
5279         w = NULL;
5280
5281       /* Need to select the frame, with all that implies so that
5282          the conditions will have the right context.  Because we
5283          use the frame, we will not see an inlined function's
5284          variables when we arrive at a breakpoint at the start
5285          of the inlined function; the current frame will be the
5286          call site.  */
5287       if (w == NULL || w->cond_exp_valid_block == NULL)
5288         select_frame (get_current_frame ());
5289       else
5290         {
5291           struct frame_info *frame;
5292
5293           /* For local watchpoint expressions, which particular
5294              instance of a local is being watched matters, so we
5295              keep track of the frame to evaluate the expression
5296              in.  To evaluate the condition however, it doesn't
5297              really matter which instantiation of the function
5298              where the condition makes sense triggers the
5299              watchpoint.  This allows an expression like "watch
5300              global if q > 10" set in `func', catch writes to
5301              global on all threads that call `func', or catch
5302              writes on all recursive calls of `func' by a single
5303              thread.  We simply always evaluate the condition in
5304              the innermost frame that's executing where it makes
5305              sense to evaluate the condition.  It seems
5306              intuitive.  */
5307           frame = block_innermost_frame (w->cond_exp_valid_block);
5308           if (frame != NULL)
5309             select_frame (frame);
5310           else
5311             within_current_scope = 0;
5312         }
5313       if (within_current_scope)
5314         {
5315           try
5316             {
5317               condition_result = breakpoint_cond_eval (cond);
5318             }
5319           catch (const gdb_exception &ex)
5320             {
5321               exception_fprintf (gdb_stderr, ex,
5322                                  "Error in testing breakpoint condition:\n");
5323             }
5324         }
5325       else
5326         {
5327           warning (_("Watchpoint condition cannot be tested "
5328                      "in the current scope"));
5329           /* If we failed to set the right context for this
5330              watchpoint, unconditionally report it.  */
5331         }
5332       /* FIXME-someday, should give breakpoint #.  */
5333       value_free_to_mark (mark);
5334     }
5335
5336   if (cond && !condition_result)
5337     {
5338       bs->stop = 0;
5339     }
5340   else if (b->ignore_count > 0)
5341     {
5342       b->ignore_count--;
5343       bs->stop = 0;
5344       /* Increase the hit count even though we don't stop.  */
5345       ++(b->hit_count);
5346       gdb::observers::breakpoint_modified.notify (b);
5347     }   
5348 }
5349
5350 /* Returns true if we need to track moribund locations of LOC's type
5351    on the current target.  */
5352
5353 static int
5354 need_moribund_for_location_type (struct bp_location *loc)
5355 {
5356   return ((loc->loc_type == bp_loc_software_breakpoint
5357            && !target_supports_stopped_by_sw_breakpoint ())
5358           || (loc->loc_type == bp_loc_hardware_breakpoint
5359               && !target_supports_stopped_by_hw_breakpoint ()));
5360 }
5361
5362 /* See breakpoint.h.  */
5363
5364 bpstat
5365 build_bpstat_chain (const address_space *aspace, CORE_ADDR bp_addr,
5366                     const struct target_waitstatus *ws)
5367 {
5368   struct breakpoint *b;
5369   bpstat bs_head = NULL, *bs_link = &bs_head;
5370
5371   ALL_BREAKPOINTS (b)
5372     {
5373       if (!breakpoint_enabled (b))
5374         continue;
5375
5376       for (bp_location *bl = b->loc; bl != NULL; bl = bl->next)
5377         {
5378           /* For hardware watchpoints, we look only at the first
5379              location.  The watchpoint_check function will work on the
5380              entire expression, not the individual locations.  For
5381              read watchpoints, the watchpoints_triggered function has
5382              checked all locations already.  */
5383           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5384             break;
5385
5386           if (!bl->enabled || bl->disabled_by_cond || bl->shlib_disabled)
5387             continue;
5388
5389           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5390             continue;
5391
5392           /* Come here if it's a watchpoint, or if the break address
5393              matches.  */
5394
5395           bpstat bs = new bpstats (bl, &bs_link);       /* Alloc a bpstat to
5396                                                            explain stop.  */
5397
5398           /* Assume we stop.  Should we find a watchpoint that is not
5399              actually triggered, or if the condition of the breakpoint
5400              evaluates as false, we'll reset 'stop' to 0.  */
5401           bs->stop = 1;
5402           bs->print = 1;
5403
5404           /* If this is a scope breakpoint, mark the associated
5405              watchpoint as triggered so that we will handle the
5406              out-of-scope event.  We'll get to the watchpoint next
5407              iteration.  */
5408           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5409             {
5410               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5411
5412               w->watchpoint_triggered = watch_triggered_yes;
5413             }
5414         }
5415     }
5416
5417   /* Check if a moribund breakpoint explains the stop.  */
5418   if (!target_supports_stopped_by_sw_breakpoint ()
5419       || !target_supports_stopped_by_hw_breakpoint ())
5420     {
5421       for (bp_location *loc : moribund_locations)
5422         {
5423           if (breakpoint_location_address_match (loc, aspace, bp_addr)
5424               && need_moribund_for_location_type (loc))
5425             {
5426               bpstat bs = new bpstats (loc, &bs_link);
5427               /* For hits of moribund locations, we should just proceed.  */
5428               bs->stop = 0;
5429               bs->print = 0;
5430               bs->print_it = print_it_noop;
5431             }
5432         }
5433     }
5434
5435   return bs_head;
5436 }
5437
5438 /* See breakpoint.h.  */
5439
5440 bpstat
5441 bpstat_stop_status (const address_space *aspace,
5442                     CORE_ADDR bp_addr, thread_info *thread,
5443                     const struct target_waitstatus *ws,
5444                     bpstat stop_chain)
5445 {
5446   struct breakpoint *b = NULL;
5447   /* First item of allocated bpstat's.  */
5448   bpstat bs_head = stop_chain;
5449   bpstat bs;
5450   int need_remove_insert;
5451   int removed_any;
5452
5453   /* First, build the bpstat chain with locations that explain a
5454      target stop, while being careful to not set the target running,
5455      as that may invalidate locations (in particular watchpoint
5456      locations are recreated).  Resuming will happen here with
5457      breakpoint conditions or watchpoint expressions that include
5458      inferior function calls.  */
5459   if (bs_head == NULL)
5460     bs_head = build_bpstat_chain (aspace, bp_addr, ws);
5461
5462   /* A bit of special processing for shlib breakpoints.  We need to
5463      process solib loading here, so that the lists of loaded and
5464      unloaded libraries are correct before we handle "catch load" and
5465      "catch unload".  */
5466   for (bs = bs_head; bs != NULL; bs = bs->next)
5467     {
5468       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5469         {
5470           handle_solib_event ();
5471           break;
5472         }
5473     }
5474
5475   /* Now go through the locations that caused the target to stop, and
5476      check whether we're interested in reporting this stop to higher
5477      layers, or whether we should resume the target transparently.  */
5478
5479   removed_any = 0;
5480
5481   for (bs = bs_head; bs != NULL; bs = bs->next)
5482     {
5483       if (!bs->stop)
5484         continue;
5485
5486       b = bs->breakpoint_at;
5487       b->ops->check_status (bs);
5488       if (bs->stop)
5489         {
5490           bpstat_check_breakpoint_conditions (bs, thread);
5491
5492           if (bs->stop)
5493             {
5494               ++(b->hit_count);
5495               gdb::observers::breakpoint_modified.notify (b);
5496
5497               /* We will stop here.  */
5498               if (b->disposition == disp_disable)
5499                 {
5500                   --(b->enable_count);
5501                   if (b->enable_count <= 0)
5502                     b->enable_state = bp_disabled;
5503                   removed_any = 1;
5504                 }
5505               if (b->silent)
5506                 bs->print = 0;
5507               bs->commands = b->commands;
5508               if (command_line_is_silent (bs->commands
5509                                           ? bs->commands.get () : NULL))
5510                 bs->print = 0;
5511
5512               b->ops->after_condition_true (bs);
5513             }
5514
5515         }
5516
5517       /* Print nothing for this entry if we don't stop or don't
5518          print.  */
5519       if (!bs->stop || !bs->print)
5520         bs->print_it = print_it_noop;
5521     }
5522
5523   /* If we aren't stopping, the value of some hardware watchpoint may
5524      not have changed, but the intermediate memory locations we are
5525      watching may have.  Don't bother if we're stopping; this will get
5526      done later.  */
5527   need_remove_insert = 0;
5528   if (! bpstat_causes_stop (bs_head))
5529     for (bs = bs_head; bs != NULL; bs = bs->next)
5530       if (!bs->stop
5531           && bs->breakpoint_at
5532           && is_hardware_watchpoint (bs->breakpoint_at))
5533         {
5534           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5535
5536           update_watchpoint (w, 0 /* don't reparse.  */);
5537           need_remove_insert = 1;
5538         }
5539
5540   if (need_remove_insert)
5541     update_global_location_list (UGLL_MAY_INSERT);
5542   else if (removed_any)
5543     update_global_location_list (UGLL_DONT_INSERT);
5544
5545   return bs_head;
5546 }
5547
5548 static void
5549 handle_jit_event (CORE_ADDR address)
5550 {
5551   struct gdbarch *gdbarch;
5552
5553   infrun_debug_printf ("handling bp_jit_event");
5554
5555   /* Switch terminal for any messages produced by
5556      breakpoint_re_set.  */
5557   target_terminal::ours_for_output ();
5558
5559   gdbarch = get_frame_arch (get_current_frame ());
5560   /* This event is caused by a breakpoint set in `jit_breakpoint_re_set`,
5561      thus it is expected that its objectfile can be found through
5562      minimal symbol lookup.  If it doesn't work (and assert fails), it
5563      most likely means that `jit_breakpoint_re_set` was changes and this
5564      function needs to be updated too.  */
5565   bound_minimal_symbol jit_bp_sym = lookup_minimal_symbol_by_pc (address);
5566   gdb_assert (jit_bp_sym.objfile != nullptr);
5567   jit_event_handler (gdbarch, jit_bp_sym.objfile);
5568
5569   target_terminal::inferior ();
5570 }
5571
5572 /* Prepare WHAT final decision for infrun.  */
5573
5574 /* Decide what infrun needs to do with this bpstat.  */
5575
5576 struct bpstat_what
5577 bpstat_what (bpstat bs_head)
5578 {
5579   struct bpstat_what retval;
5580   bpstat bs;
5581
5582   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5583   retval.call_dummy = STOP_NONE;
5584   retval.is_longjmp = false;
5585
5586   for (bs = bs_head; bs != NULL; bs = bs->next)
5587     {
5588       /* Extract this BS's action.  After processing each BS, we check
5589          if its action overrides all we've seem so far.  */
5590       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5591       enum bptype bptype;
5592
5593       if (bs->breakpoint_at == NULL)
5594         {
5595           /* I suspect this can happen if it was a momentary
5596              breakpoint which has since been deleted.  */
5597           bptype = bp_none;
5598         }
5599       else
5600         bptype = bs->breakpoint_at->type;
5601
5602       switch (bptype)
5603         {
5604         case bp_none:
5605           break;
5606         case bp_breakpoint:
5607         case bp_hardware_breakpoint:
5608         case bp_single_step:
5609         case bp_until:
5610         case bp_finish:
5611         case bp_shlib_event:
5612           if (bs->stop)
5613             {
5614               if (bs->print)
5615                 this_action = BPSTAT_WHAT_STOP_NOISY;
5616               else
5617                 this_action = BPSTAT_WHAT_STOP_SILENT;
5618             }
5619           else
5620             this_action = BPSTAT_WHAT_SINGLE;
5621           break;
5622         case bp_watchpoint:
5623         case bp_hardware_watchpoint:
5624         case bp_read_watchpoint:
5625         case bp_access_watchpoint:
5626           if (bs->stop)
5627             {
5628               if (bs->print)
5629                 this_action = BPSTAT_WHAT_STOP_NOISY;
5630               else
5631                 this_action = BPSTAT_WHAT_STOP_SILENT;
5632             }
5633           else
5634             {
5635               /* There was a watchpoint, but we're not stopping.
5636                  This requires no further action.  */
5637             }
5638           break;
5639         case bp_longjmp:
5640         case bp_longjmp_call_dummy:
5641         case bp_exception:
5642           if (bs->stop)
5643             {
5644               this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5645               retval.is_longjmp = bptype != bp_exception;
5646             }
5647           else
5648             this_action = BPSTAT_WHAT_SINGLE;
5649           break;
5650         case bp_longjmp_resume:
5651         case bp_exception_resume:
5652           if (bs->stop)
5653             {
5654               this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5655               retval.is_longjmp = bptype == bp_longjmp_resume;
5656             }
5657           else
5658             this_action = BPSTAT_WHAT_SINGLE;
5659           break;
5660         case bp_step_resume:
5661           if (bs->stop)
5662             this_action = BPSTAT_WHAT_STEP_RESUME;
5663           else
5664             {
5665               /* It is for the wrong frame.  */
5666               this_action = BPSTAT_WHAT_SINGLE;
5667             }
5668           break;
5669         case bp_hp_step_resume:
5670           if (bs->stop)
5671             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5672           else
5673             {
5674               /* It is for the wrong frame.  */
5675               this_action = BPSTAT_WHAT_SINGLE;
5676             }
5677           break;
5678         case bp_watchpoint_scope:
5679         case bp_thread_event:
5680         case bp_overlay_event:
5681         case bp_longjmp_master:
5682         case bp_std_terminate_master:
5683         case bp_exception_master:
5684           this_action = BPSTAT_WHAT_SINGLE;
5685           break;
5686         case bp_catchpoint:
5687           if (bs->stop)
5688             {
5689               if (bs->print)
5690                 this_action = BPSTAT_WHAT_STOP_NOISY;
5691               else
5692                 this_action = BPSTAT_WHAT_STOP_SILENT;
5693             }
5694           else
5695             {
5696               /* Some catchpoints are implemented with breakpoints.
5697                  For those, we need to step over the breakpoint.  */
5698               if (bs->bp_location_at->loc_type != bp_loc_other)
5699                 this_action = BPSTAT_WHAT_SINGLE;
5700             }
5701           break;
5702         case bp_jit_event:
5703           this_action = BPSTAT_WHAT_SINGLE;
5704           break;
5705         case bp_call_dummy:
5706           /* Make sure the action is stop (silent or noisy),
5707              so infrun.c pops the dummy frame.  */
5708           retval.call_dummy = STOP_STACK_DUMMY;
5709           this_action = BPSTAT_WHAT_STOP_SILENT;
5710           break;
5711         case bp_std_terminate:
5712           /* Make sure the action is stop (silent or noisy),
5713              so infrun.c pops the dummy frame.  */
5714           retval.call_dummy = STOP_STD_TERMINATE;
5715           this_action = BPSTAT_WHAT_STOP_SILENT;
5716           break;
5717         case bp_tracepoint:
5718         case bp_fast_tracepoint:
5719         case bp_static_tracepoint:
5720           /* Tracepoint hits should not be reported back to GDB, and
5721              if one got through somehow, it should have been filtered
5722              out already.  */
5723           internal_error (__FILE__, __LINE__,
5724                           _("bpstat_what: tracepoint encountered"));
5725           break;
5726         case bp_gnu_ifunc_resolver:
5727           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5728           this_action = BPSTAT_WHAT_SINGLE;
5729           break;
5730         case bp_gnu_ifunc_resolver_return:
5731           /* The breakpoint will be removed, execution will restart from the
5732              PC of the former breakpoint.  */
5733           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5734           break;
5735
5736         case bp_dprintf:
5737           if (bs->stop)
5738             this_action = BPSTAT_WHAT_STOP_SILENT;
5739           else
5740             this_action = BPSTAT_WHAT_SINGLE;
5741           break;
5742
5743         default:
5744           internal_error (__FILE__, __LINE__,
5745                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5746         }
5747
5748       retval.main_action = std::max (retval.main_action, this_action);
5749     }
5750
5751   return retval;
5752 }
5753
5754 void
5755 bpstat_run_callbacks (bpstat bs_head)
5756 {
5757   bpstat bs;
5758
5759   for (bs = bs_head; bs != NULL; bs = bs->next)
5760     {
5761       struct breakpoint *b = bs->breakpoint_at;
5762
5763       if (b == NULL)
5764         continue;
5765       switch (b->type)
5766         {
5767         case bp_jit_event:
5768           handle_jit_event (bs->bp_location_at->address);
5769           break;
5770         case bp_gnu_ifunc_resolver:
5771           gnu_ifunc_resolver_stop (b);
5772           break;
5773         case bp_gnu_ifunc_resolver_return:
5774           gnu_ifunc_resolver_return_stop (b);
5775           break;
5776         }
5777     }
5778 }
5779
5780 /* See breakpoint.h.  */
5781
5782 bool
5783 bpstat_should_step ()
5784 {
5785   struct breakpoint *b;
5786
5787   ALL_BREAKPOINTS (b)
5788     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5789       return true;
5790   return false;
5791 }
5792
5793 /* See breakpoint.h.  */
5794
5795 bool
5796 bpstat_causes_stop (bpstat bs)
5797 {
5798   for (; bs != NULL; bs = bs->next)
5799     if (bs->stop)
5800       return true;
5801
5802   return false;
5803 }
5804
5805 \f
5806
5807 /* Compute a string of spaces suitable to indent the next line
5808    so it starts at the position corresponding to the table column
5809    named COL_NAME in the currently active table of UIOUT.  */
5810
5811 static char *
5812 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5813 {
5814   static char wrap_indent[80];
5815   int i, total_width, width, align;
5816   const char *text;
5817
5818   total_width = 0;
5819   for (i = 1; uiout->query_table_field (i, &width, &align, &text); i++)
5820     {
5821       if (strcmp (text, col_name) == 0)
5822         {
5823           gdb_assert (total_width < sizeof wrap_indent);
5824           memset (wrap_indent, ' ', total_width);
5825           wrap_indent[total_width] = 0;
5826
5827           return wrap_indent;
5828         }
5829
5830       total_width += width + 1;
5831     }
5832
5833   return NULL;
5834 }
5835
5836 /* Determine if the locations of this breakpoint will have their conditions
5837    evaluated by the target, host or a mix of both.  Returns the following:
5838
5839     "host": Host evals condition.
5840     "host or target": Host or Target evals condition.
5841     "target": Target evals condition.
5842 */
5843
5844 static const char *
5845 bp_condition_evaluator (struct breakpoint *b)
5846 {
5847   struct bp_location *bl;
5848   char host_evals = 0;
5849   char target_evals = 0;
5850
5851   if (!b)
5852     return NULL;
5853
5854   if (!is_breakpoint (b))
5855     return NULL;
5856
5857   if (gdb_evaluates_breakpoint_condition_p ()
5858       || !target_supports_evaluation_of_breakpoint_conditions ())
5859     return condition_evaluation_host;
5860
5861   for (bl = b->loc; bl; bl = bl->next)
5862     {
5863       if (bl->cond_bytecode)
5864         target_evals++;
5865       else
5866         host_evals++;
5867     }
5868
5869   if (host_evals && target_evals)
5870     return condition_evaluation_both;
5871   else if (target_evals)
5872     return condition_evaluation_target;
5873   else
5874     return condition_evaluation_host;
5875 }
5876
5877 /* Determine the breakpoint location's condition evaluator.  This is
5878    similar to bp_condition_evaluator, but for locations.  */
5879
5880 static const char *
5881 bp_location_condition_evaluator (struct bp_location *bl)
5882 {
5883   if (bl && !is_breakpoint (bl->owner))
5884     return NULL;
5885
5886   if (gdb_evaluates_breakpoint_condition_p ()
5887       || !target_supports_evaluation_of_breakpoint_conditions ())
5888     return condition_evaluation_host;
5889
5890   if (bl && bl->cond_bytecode)
5891     return condition_evaluation_target;
5892   else
5893     return condition_evaluation_host;
5894 }
5895
5896 /* Print the LOC location out of the list of B->LOC locations.  */
5897
5898 static void
5899 print_breakpoint_location (struct breakpoint *b,
5900                            struct bp_location *loc)
5901 {
5902   struct ui_out *uiout = current_uiout;
5903
5904   scoped_restore_current_program_space restore_pspace;
5905
5906   if (loc != NULL && loc->shlib_disabled)
5907     loc = NULL;
5908
5909   if (loc != NULL)
5910     set_current_program_space (loc->pspace);
5911
5912   if (b->display_canonical)
5913     uiout->field_string ("what", event_location_to_string (b->location.get ()));
5914   else if (loc && loc->symtab)
5915     {
5916       const struct symbol *sym = loc->symbol;
5917
5918       if (sym)
5919         {
5920           uiout->text ("in ");
5921           uiout->field_string ("func", sym->print_name (),
5922                                function_name_style.style ());
5923           uiout->text (" ");
5924           uiout->wrap_hint (wrap_indent_at_field (uiout, "what"));
5925           uiout->text ("at ");
5926         }
5927       uiout->field_string ("file",
5928                            symtab_to_filename_for_display (loc->symtab),
5929                            file_name_style.style ());
5930       uiout->text (":");
5931
5932       if (uiout->is_mi_like_p ())
5933         uiout->field_string ("fullname", symtab_to_fullname (loc->symtab));
5934       
5935       uiout->field_signed ("line", loc->line_number);
5936     }
5937   else if (loc)
5938     {
5939       string_file stb;
5940
5941       print_address_symbolic (loc->gdbarch, loc->address, &stb,
5942                               demangle, "");
5943       uiout->field_stream ("at", stb);
5944     }
5945   else
5946     {
5947       uiout->field_string ("pending",
5948                            event_location_to_string (b->location.get ()));
5949       /* If extra_string is available, it could be holding a condition
5950          or dprintf arguments.  In either case, make sure it is printed,
5951          too, but only for non-MI streams.  */
5952       if (!uiout->is_mi_like_p () && b->extra_string != NULL)
5953         {
5954           if (b->type == bp_dprintf)
5955             uiout->text (",");
5956           else
5957             uiout->text (" ");
5958           uiout->text (b->extra_string);
5959         }
5960     }
5961
5962   if (loc && is_breakpoint (b)
5963       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5964       && bp_condition_evaluator (b) == condition_evaluation_both)
5965     {
5966       uiout->text (" (");
5967       uiout->field_string ("evaluated-by",
5968                            bp_location_condition_evaluator (loc));
5969       uiout->text (")");
5970     }
5971 }
5972
5973 static const char *
5974 bptype_string (enum bptype type)
5975 {
5976   struct ep_type_description
5977     {
5978       enum bptype type;
5979       const char *description;
5980     };
5981   static struct ep_type_description bptypes[] =
5982   {
5983     {bp_none, "?deleted?"},
5984     {bp_breakpoint, "breakpoint"},
5985     {bp_hardware_breakpoint, "hw breakpoint"},
5986     {bp_single_step, "sw single-step"},
5987     {bp_until, "until"},
5988     {bp_finish, "finish"},
5989     {bp_watchpoint, "watchpoint"},
5990     {bp_hardware_watchpoint, "hw watchpoint"},
5991     {bp_read_watchpoint, "read watchpoint"},
5992     {bp_access_watchpoint, "acc watchpoint"},
5993     {bp_longjmp, "longjmp"},
5994     {bp_longjmp_resume, "longjmp resume"},
5995     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5996     {bp_exception, "exception"},
5997     {bp_exception_resume, "exception resume"},
5998     {bp_step_resume, "step resume"},
5999     {bp_hp_step_resume, "high-priority step resume"},
6000     {bp_watchpoint_scope, "watchpoint scope"},
6001     {bp_call_dummy, "call dummy"},
6002     {bp_std_terminate, "std::terminate"},
6003     {bp_shlib_event, "shlib events"},
6004     {bp_thread_event, "thread events"},
6005     {bp_overlay_event, "overlay events"},
6006     {bp_longjmp_master, "longjmp master"},
6007     {bp_std_terminate_master, "std::terminate master"},
6008     {bp_exception_master, "exception master"},
6009     {bp_catchpoint, "catchpoint"},
6010     {bp_tracepoint, "tracepoint"},
6011     {bp_fast_tracepoint, "fast tracepoint"},
6012     {bp_static_tracepoint, "static tracepoint"},
6013     {bp_dprintf, "dprintf"},
6014     {bp_jit_event, "jit events"},
6015     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6016     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6017   };
6018
6019   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6020       || ((int) type != bptypes[(int) type].type))
6021     internal_error (__FILE__, __LINE__,
6022                     _("bptypes table does not describe type #%d."),
6023                     (int) type);
6024
6025   return bptypes[(int) type].description;
6026 }
6027
6028 /* For MI, output a field named 'thread-groups' with a list as the value.
6029    For CLI, prefix the list with the string 'inf'. */
6030
6031 static void
6032 output_thread_groups (struct ui_out *uiout,
6033                       const char *field_name,
6034                       const std::vector<int> &inf_nums,
6035                       int mi_only)
6036 {
6037   int is_mi = uiout->is_mi_like_p ();
6038
6039   /* For backward compatibility, don't display inferiors in CLI unless
6040      there are several.  Always display them for MI. */
6041   if (!is_mi && mi_only)
6042     return;
6043
6044   ui_out_emit_list list_emitter (uiout, field_name);
6045
6046   for (size_t i = 0; i < inf_nums.size (); i++)
6047     {
6048       if (is_mi)
6049         {
6050           char mi_group[10];
6051
6052           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf_nums[i]);
6053           uiout->field_string (NULL, mi_group);
6054         }
6055       else
6056         {
6057           if (i == 0)
6058             uiout->text (" inf ");
6059           else
6060             uiout->text (", ");
6061         
6062           uiout->text (plongest (inf_nums[i]));
6063         }
6064     }
6065 }
6066
6067 /* Print B to gdb_stdout.  If RAW_LOC, print raw breakpoint locations
6068    instead of going via breakpoint_ops::print_one.  This makes "maint
6069    info breakpoints" show the software breakpoint locations of
6070    catchpoints, which are considered internal implementation
6071    detail.  */
6072
6073 static void
6074 print_one_breakpoint_location (struct breakpoint *b,
6075                                struct bp_location *loc,
6076                                int loc_number,
6077                                struct bp_location **last_loc,
6078                                int allflag, bool raw_loc)
6079 {
6080   struct command_line *l;
6081   static char bpenables[] = "nynny";
6082
6083   struct ui_out *uiout = current_uiout;
6084   int header_of_multiple = 0;
6085   int part_of_multiple = (loc != NULL);
6086   struct value_print_options opts;
6087
6088   get_user_print_options (&opts);
6089
6090   gdb_assert (!loc || loc_number != 0);
6091   /* See comment in print_one_breakpoint concerning treatment of
6092      breakpoints with single disabled location.  */
6093   if (loc == NULL 
6094       && (b->loc != NULL 
6095           && (b->loc->next != NULL
6096               || !b->loc->enabled || b->loc->disabled_by_cond)))
6097     header_of_multiple = 1;
6098   if (loc == NULL)
6099     loc = b->loc;
6100
6101   annotate_record ();
6102
6103   /* 1 */
6104   annotate_field (0);
6105   if (part_of_multiple)
6106     uiout->field_fmt ("number", "%d.%d", b->number, loc_number);
6107   else
6108     uiout->field_signed ("number", b->number);
6109
6110   /* 2 */
6111   annotate_field (1);
6112   if (part_of_multiple)
6113     uiout->field_skip ("type");
6114   else
6115     uiout->field_string ("type", bptype_string (b->type));
6116
6117   /* 3 */
6118   annotate_field (2);
6119   if (part_of_multiple)
6120     uiout->field_skip ("disp");
6121   else
6122     uiout->field_string ("disp", bpdisp_text (b->disposition));
6123
6124   /* 4 */
6125   annotate_field (3);
6126   if (part_of_multiple)
6127     uiout->field_string ("enabled", (loc->disabled_by_cond ? "N*"
6128                                      : (loc->enabled ? "y" : "n")));
6129   else
6130     uiout->field_fmt ("enabled", "%c", bpenables[(int) b->enable_state]);
6131
6132   /* 5 and 6 */
6133   if (!raw_loc && b->ops != NULL && b->ops->print_one != NULL)
6134     b->ops->print_one (b, last_loc);
6135   else
6136     {
6137       if (is_watchpoint (b))
6138         {
6139           struct watchpoint *w = (struct watchpoint *) b;
6140
6141           /* Field 4, the address, is omitted (which makes the columns
6142              not line up too nicely with the headers, but the effect
6143              is relatively readable).  */
6144           if (opts.addressprint)
6145             uiout->field_skip ("addr");
6146           annotate_field (5);
6147           uiout->field_string ("what", w->exp_string);
6148         }
6149       else if (!is_catchpoint (b) || is_exception_catchpoint (b)
6150                || is_ada_exception_catchpoint (b))
6151         {
6152           if (opts.addressprint)
6153             {
6154               annotate_field (4);
6155               if (header_of_multiple)
6156                 uiout->field_string ("addr", "<MULTIPLE>",
6157                                      metadata_style.style ());
6158               else if (b->loc == NULL || loc->shlib_disabled)
6159                 uiout->field_string ("addr", "<PENDING>",
6160                                      metadata_style.style ());
6161               else
6162                 uiout->field_core_addr ("addr",
6163                                         loc->gdbarch, loc->address);
6164             }
6165           annotate_field (5);
6166           if (!header_of_multiple)
6167             print_breakpoint_location (b, loc);
6168           if (b->loc)
6169             *last_loc = b->loc;
6170         }
6171     }
6172
6173   if (loc != NULL && !header_of_multiple)
6174     {
6175       std::vector<int> inf_nums;
6176       int mi_only = 1;
6177
6178       for (inferior *inf : all_inferiors ())
6179         {
6180           if (inf->pspace == loc->pspace)
6181             inf_nums.push_back (inf->num);
6182         }
6183
6184         /* For backward compatibility, don't display inferiors in CLI unless
6185            there are several.  Always display for MI. */
6186         if (allflag
6187             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6188                 && (program_spaces.size () > 1
6189                     || number_of_inferiors () > 1)
6190                 /* LOC is for existing B, it cannot be in
6191                    moribund_locations and thus having NULL OWNER.  */
6192                 && loc->owner->type != bp_catchpoint))
6193         mi_only = 0;
6194       output_thread_groups (uiout, "thread-groups", inf_nums, mi_only);
6195     }
6196
6197   if (!part_of_multiple)
6198     {
6199       if (b->thread != -1)
6200         {
6201           /* FIXME: This seems to be redundant and lost here; see the
6202              "stop only in" line a little further down.  */
6203           uiout->text (" thread ");
6204           uiout->field_signed ("thread", b->thread);
6205         }
6206       else if (b->task != 0)
6207         {
6208           uiout->text (" task ");
6209           uiout->field_signed ("task", b->task);
6210         }
6211     }
6212
6213   uiout->text ("\n");
6214
6215   if (!part_of_multiple)
6216     b->ops->print_one_detail (b, uiout);
6217
6218   if (part_of_multiple && frame_id_p (b->frame_id))
6219     {
6220       annotate_field (6);
6221       uiout->text ("\tstop only in stack frame at ");
6222       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6223          the frame ID.  */
6224       uiout->field_core_addr ("frame",
6225                               b->gdbarch, b->frame_id.stack_addr);
6226       uiout->text ("\n");
6227     }
6228   
6229   if (!part_of_multiple && b->cond_string)
6230     {
6231       annotate_field (7);
6232       if (is_tracepoint (b))
6233         uiout->text ("\ttrace only if ");
6234       else
6235         uiout->text ("\tstop only if ");
6236       uiout->field_string ("cond", b->cond_string);
6237
6238       /* Print whether the target is doing the breakpoint's condition
6239          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6240       if (is_breakpoint (b)
6241           && breakpoint_condition_evaluation_mode ()
6242           == condition_evaluation_target)
6243         {
6244           uiout->message (" (%pF evals)",
6245                           string_field ("evaluated-by",
6246                                         bp_condition_evaluator (b)));
6247         }
6248       uiout->text ("\n");
6249     }
6250
6251   if (!part_of_multiple && b->thread != -1)
6252     {
6253       /* FIXME should make an annotation for this.  */
6254       uiout->text ("\tstop only in thread ");
6255       if (uiout->is_mi_like_p ())
6256         uiout->field_signed ("thread", b->thread);
6257       else
6258         {
6259           struct thread_info *thr = find_thread_global_id (b->thread);
6260
6261           uiout->field_string ("thread", print_thread_id (thr));
6262         }
6263       uiout->text ("\n");
6264     }
6265   
6266   if (!part_of_multiple)
6267     {
6268       if (b->hit_count)
6269         {
6270           /* FIXME should make an annotation for this.  */
6271           if (is_catchpoint (b))
6272             uiout->text ("\tcatchpoint");
6273           else if (is_tracepoint (b))
6274             uiout->text ("\ttracepoint");
6275           else
6276             uiout->text ("\tbreakpoint");
6277           uiout->text (" already hit ");
6278           uiout->field_signed ("times", b->hit_count);
6279           if (b->hit_count == 1)
6280             uiout->text (" time\n");
6281           else
6282             uiout->text (" times\n");
6283         }
6284       else
6285         {
6286           /* Output the count also if it is zero, but only if this is mi.  */
6287           if (uiout->is_mi_like_p ())
6288             uiout->field_signed ("times", b->hit_count);
6289         }
6290     }
6291
6292   if (!part_of_multiple && b->ignore_count)
6293     {
6294       annotate_field (8);
6295       uiout->message ("\tignore next %pF hits\n",
6296                       signed_field ("ignore", b->ignore_count));
6297     }
6298
6299   /* Note that an enable count of 1 corresponds to "enable once"
6300      behavior, which is reported by the combination of enablement and
6301      disposition, so we don't need to mention it here.  */
6302   if (!part_of_multiple && b->enable_count > 1)
6303     {
6304       annotate_field (8);
6305       uiout->text ("\tdisable after ");
6306       /* Tweak the wording to clarify that ignore and enable counts
6307          are distinct, and have additive effect.  */
6308       if (b->ignore_count)
6309         uiout->text ("additional ");
6310       else
6311         uiout->text ("next ");
6312       uiout->field_signed ("enable", b->enable_count);
6313       uiout->text (" hits\n");
6314     }
6315
6316   if (!part_of_multiple && is_tracepoint (b))
6317     {
6318       struct tracepoint *tp = (struct tracepoint *) b;
6319
6320       if (tp->traceframe_usage)
6321         {
6322           uiout->text ("\ttrace buffer usage ");
6323           uiout->field_signed ("traceframe-usage", tp->traceframe_usage);
6324           uiout->text (" bytes\n");
6325         }
6326     }
6327
6328   l = b->commands ? b->commands.get () : NULL;
6329   if (!part_of_multiple && l)
6330     {
6331       annotate_field (9);
6332       ui_out_emit_tuple tuple_emitter (uiout, "script");
6333       print_command_lines (uiout, l, 4);
6334     }
6335
6336   if (is_tracepoint (b))
6337     {
6338       struct tracepoint *t = (struct tracepoint *) b;
6339
6340       if (!part_of_multiple && t->pass_count)
6341         {
6342           annotate_field (10);
6343           uiout->text ("\tpass count ");
6344           uiout->field_signed ("pass", t->pass_count);
6345           uiout->text (" \n");
6346         }
6347
6348       /* Don't display it when tracepoint or tracepoint location is
6349          pending.   */
6350       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6351         {
6352           annotate_field (11);
6353
6354           if (uiout->is_mi_like_p ())
6355             uiout->field_string ("installed",
6356                                  loc->inserted ? "y" : "n");
6357           else
6358             {
6359               if (loc->inserted)
6360                 uiout->text ("\t");
6361               else
6362                 uiout->text ("\tnot ");
6363               uiout->text ("installed on target\n");
6364             }
6365         }
6366     }
6367
6368   if (uiout->is_mi_like_p () && !part_of_multiple)
6369     {
6370       if (is_watchpoint (b))
6371         {
6372           struct watchpoint *w = (struct watchpoint *) b;
6373
6374           uiout->field_string ("original-location", w->exp_string);
6375         }
6376       else if (b->location != NULL
6377                && event_location_to_string (b->location.get ()) != NULL)
6378         uiout->field_string ("original-location",
6379                              event_location_to_string (b->location.get ()));
6380     }
6381 }
6382
6383 /* See breakpoint.h. */
6384
6385 bool fix_multi_location_breakpoint_output_globally = false;
6386
6387 static void
6388 print_one_breakpoint (struct breakpoint *b,
6389                       struct bp_location **last_loc, 
6390                       int allflag)
6391 {
6392   struct ui_out *uiout = current_uiout;
6393   bool use_fixed_output
6394     = (uiout->test_flags (fix_multi_location_breakpoint_output)
6395        || fix_multi_location_breakpoint_output_globally);
6396
6397   gdb::optional<ui_out_emit_tuple> bkpt_tuple_emitter (gdb::in_place, uiout, "bkpt");
6398   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag, false);
6399
6400   /* The mi2 broken format: the main breakpoint tuple ends here, the locations
6401      are outside.  */
6402   if (!use_fixed_output)
6403     bkpt_tuple_emitter.reset ();
6404
6405   /* If this breakpoint has custom print function,
6406      it's already printed.  Otherwise, print individual
6407      locations, if any.  */
6408   if (b->ops == NULL
6409       || b->ops->print_one == NULL
6410       || allflag)
6411     {
6412       /* If breakpoint has a single location that is disabled, we
6413          print it as if it had several locations, since otherwise it's
6414          hard to represent "breakpoint enabled, location disabled"
6415          situation.
6416
6417          Note that while hardware watchpoints have several locations
6418          internally, that's not a property exposed to users.
6419
6420          Likewise, while catchpoints may be implemented with
6421          breakpoints (e.g., catch throw), that's not a property
6422          exposed to users.  We do however display the internal
6423          breakpoint locations with "maint info breakpoints".  */
6424       if (!is_hardware_watchpoint (b)
6425           && (!is_catchpoint (b) || is_exception_catchpoint (b)
6426               || is_ada_exception_catchpoint (b))
6427           && (allflag
6428               || (b->loc && (b->loc->next
6429                              || !b->loc->enabled
6430                              || b->loc->disabled_by_cond))))
6431         {
6432           gdb::optional<ui_out_emit_list> locations_list;
6433
6434           /* For MI version <= 2, keep the behavior where GDB outputs an invalid
6435              MI record.  For later versions, place breakpoint locations in a
6436              list.  */
6437           if (uiout->is_mi_like_p () && use_fixed_output)
6438             locations_list.emplace (uiout, "locations");
6439
6440           int n = 1;
6441           for (bp_location *loc = b->loc; loc != NULL; loc = loc->next, ++n)
6442             {
6443               ui_out_emit_tuple loc_tuple_emitter (uiout, NULL);
6444               print_one_breakpoint_location (b, loc, n, last_loc,
6445                                              allflag, allflag);
6446             }
6447         }
6448     }
6449 }
6450
6451 static int
6452 breakpoint_address_bits (struct breakpoint *b)
6453 {
6454   int print_address_bits = 0;
6455   struct bp_location *loc;
6456
6457   /* Software watchpoints that aren't watching memory don't have an
6458      address to print.  */
6459   if (is_no_memory_software_watchpoint (b))
6460     return 0;
6461
6462   for (loc = b->loc; loc; loc = loc->next)
6463     {
6464       int addr_bit;
6465
6466       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6467       if (addr_bit > print_address_bits)
6468         print_address_bits = addr_bit;
6469     }
6470
6471   return print_address_bits;
6472 }
6473
6474 /* See breakpoint.h.  */
6475
6476 void
6477 print_breakpoint (breakpoint *b)
6478 {
6479   struct bp_location *dummy_loc = NULL;
6480   print_one_breakpoint (b, &dummy_loc, 0);
6481 }
6482
6483 /* Return true if this breakpoint was set by the user, false if it is
6484    internal or momentary.  */
6485
6486 int
6487 user_breakpoint_p (struct breakpoint *b)
6488 {
6489   return b->number > 0;
6490 }
6491
6492 /* See breakpoint.h.  */
6493
6494 int
6495 pending_breakpoint_p (struct breakpoint *b)
6496 {
6497   return b->loc == NULL;
6498 }
6499
6500 /* Print information on breakpoints (including watchpoints and tracepoints).
6501
6502    If non-NULL, BP_NUM_LIST is a list of numbers and number ranges as
6503    understood by number_or_range_parser.  Only breakpoints included in this
6504    list are then printed.
6505
6506    If SHOW_INTERNAL is true, print internal breakpoints.
6507
6508    If FILTER is non-NULL, call it on each breakpoint and only include the
6509    ones for which it returns true.
6510
6511    Return the total number of breakpoints listed.  */
6512
6513 static int
6514 breakpoint_1 (const char *bp_num_list, bool show_internal,
6515               bool (*filter) (const struct breakpoint *))
6516 {
6517   struct breakpoint *b;
6518   struct bp_location *last_loc = NULL;
6519   int nr_printable_breakpoints;
6520   struct value_print_options opts;
6521   int print_address_bits = 0;
6522   int print_type_col_width = 14;
6523   struct ui_out *uiout = current_uiout;
6524   bool has_disabled_by_cond_location = false;
6525
6526   get_user_print_options (&opts);
6527
6528   /* Compute the number of rows in the table, as well as the size
6529      required for address fields.  */
6530   nr_printable_breakpoints = 0;
6531   ALL_BREAKPOINTS (b)
6532     {
6533       /* If we have a filter, only list the breakpoints it accepts.  */
6534       if (filter && !filter (b))
6535         continue;
6536
6537       /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6538          accept.  Skip the others.  */
6539       if (bp_num_list != NULL && *bp_num_list != '\0')
6540         {
6541           if (show_internal && parse_and_eval_long (bp_num_list) != b->number)
6542             continue;
6543           if (!show_internal && !number_is_in_list (bp_num_list, b->number))
6544             continue;
6545         }
6546
6547       if (show_internal || user_breakpoint_p (b))
6548         {
6549           int addr_bit, type_len;
6550
6551           addr_bit = breakpoint_address_bits (b);
6552           if (addr_bit > print_address_bits)
6553             print_address_bits = addr_bit;
6554
6555           type_len = strlen (bptype_string (b->type));
6556           if (type_len > print_type_col_width)
6557             print_type_col_width = type_len;
6558
6559           nr_printable_breakpoints++;
6560         }
6561     }
6562
6563   {
6564     ui_out_emit_table table_emitter (uiout,
6565                                      opts.addressprint ? 6 : 5,
6566                                      nr_printable_breakpoints,
6567                                      "BreakpointTable");
6568
6569     if (nr_printable_breakpoints > 0)
6570       annotate_breakpoints_headers ();
6571     if (nr_printable_breakpoints > 0)
6572       annotate_field (0);
6573     uiout->table_header (7, ui_left, "number", "Num"); /* 1 */
6574     if (nr_printable_breakpoints > 0)
6575       annotate_field (1);
6576     uiout->table_header (print_type_col_width, ui_left, "type", "Type"); /* 2 */
6577     if (nr_printable_breakpoints > 0)
6578       annotate_field (2);
6579     uiout->table_header (4, ui_left, "disp", "Disp"); /* 3 */
6580     if (nr_printable_breakpoints > 0)
6581       annotate_field (3);
6582     uiout->table_header (3, ui_left, "enabled", "Enb"); /* 4 */
6583     if (opts.addressprint)
6584       {
6585         if (nr_printable_breakpoints > 0)
6586           annotate_field (4);
6587         if (print_address_bits <= 32)
6588           uiout->table_header (10, ui_left, "addr", "Address"); /* 5 */
6589         else
6590           uiout->table_header (18, ui_left, "addr", "Address"); /* 5 */
6591       }
6592     if (nr_printable_breakpoints > 0)
6593       annotate_field (5);
6594     uiout->table_header (40, ui_noalign, "what", "What"); /* 6 */
6595     uiout->table_body ();
6596     if (nr_printable_breakpoints > 0)
6597       annotate_breakpoints_table ();
6598
6599     ALL_BREAKPOINTS (b)
6600       {
6601         QUIT;
6602         /* If we have a filter, only list the breakpoints it accepts.  */
6603         if (filter && !filter (b))
6604           continue;
6605
6606         /* If we have a BP_NUM_LIST string, it is a list of breakpoints to
6607            accept.  Skip the others.  */
6608
6609         if (bp_num_list != NULL && *bp_num_list != '\0')
6610           {
6611             if (show_internal)  /* maintenance info breakpoint */
6612               {
6613                 if (parse_and_eval_long (bp_num_list) != b->number)
6614                   continue;
6615               }
6616             else                /* all others */
6617               {
6618                 if (!number_is_in_list (bp_num_list, b->number))
6619                   continue;
6620               }
6621           }
6622         /* We only print out user settable breakpoints unless the
6623            show_internal is set.  */
6624         if (show_internal || user_breakpoint_p (b))
6625           {
6626             print_one_breakpoint (b, &last_loc, show_internal);
6627             for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
6628               if (loc->disabled_by_cond)
6629                 has_disabled_by_cond_location = true;
6630           }
6631       }
6632   }
6633
6634   if (nr_printable_breakpoints == 0)
6635     {
6636       /* If there's a filter, let the caller decide how to report
6637          empty list.  */
6638       if (!filter)
6639         {
6640           if (bp_num_list == NULL || *bp_num_list == '\0')
6641             uiout->message ("No breakpoints or watchpoints.\n");
6642           else
6643             uiout->message ("No breakpoint or watchpoint matching '%s'.\n",
6644                             bp_num_list);
6645         }
6646     }
6647   else
6648     {
6649       if (last_loc && !server_command)
6650         set_next_address (last_loc->gdbarch, last_loc->address);
6651
6652       if (has_disabled_by_cond_location)
6653         uiout->message (_("(*): Breakpoint condition is invalid at this "
6654                           "location.\n"));
6655     }
6656
6657   /* FIXME?  Should this be moved up so that it is only called when
6658      there have been breakpoints? */
6659   annotate_breakpoints_table_end ();
6660
6661   return nr_printable_breakpoints;
6662 }
6663
6664 /* Display the value of default-collect in a way that is generally
6665    compatible with the breakpoint list.  */
6666
6667 static void
6668 default_collect_info (void)
6669 {
6670   struct ui_out *uiout = current_uiout;
6671
6672   /* If it has no value (which is frequently the case), say nothing; a
6673      message like "No default-collect." gets in user's face when it's
6674      not wanted.  */
6675   if (!*default_collect)
6676     return;
6677
6678   /* The following phrase lines up nicely with per-tracepoint collect
6679      actions.  */
6680   uiout->text ("default collect ");
6681   uiout->field_string ("default-collect", default_collect);
6682   uiout->text (" \n");
6683 }
6684   
6685 static void
6686 info_breakpoints_command (const char *args, int from_tty)
6687 {
6688   breakpoint_1 (args, false, NULL);
6689
6690   default_collect_info ();
6691 }
6692
6693 static void
6694 info_watchpoints_command (const char *args, int from_tty)
6695 {
6696   int num_printed = breakpoint_1 (args, false, is_watchpoint);
6697   struct ui_out *uiout = current_uiout;
6698
6699   if (num_printed == 0)
6700     {
6701       if (args == NULL || *args == '\0')
6702         uiout->message ("No watchpoints.\n");
6703       else
6704         uiout->message ("No watchpoint matching '%s'.\n", args);
6705     }
6706 }
6707
6708 static void
6709 maintenance_info_breakpoints (const char *args, int from_tty)
6710 {
6711   breakpoint_1 (args, true, NULL);
6712
6713   default_collect_info ();
6714 }
6715
6716 static int
6717 breakpoint_has_pc (struct breakpoint *b,
6718                    struct program_space *pspace,
6719                    CORE_ADDR pc, struct obj_section *section)
6720 {
6721   struct bp_location *bl = b->loc;
6722
6723   for (; bl; bl = bl->next)
6724     {
6725       if (bl->pspace == pspace
6726           && bl->address == pc
6727           && (!overlay_debugging || bl->section == section))
6728         return 1;         
6729     }
6730   return 0;
6731 }
6732
6733 /* Print a message describing any user-breakpoints set at PC.  This
6734    concerns with logical breakpoints, so we match program spaces, not
6735    address spaces.  */
6736
6737 static void
6738 describe_other_breakpoints (struct gdbarch *gdbarch,
6739                             struct program_space *pspace, CORE_ADDR pc,
6740                             struct obj_section *section, int thread)
6741 {
6742   int others = 0;
6743   struct breakpoint *b;
6744
6745   ALL_BREAKPOINTS (b)
6746     others += (user_breakpoint_p (b)
6747                && breakpoint_has_pc (b, pspace, pc, section));
6748   if (others > 0)
6749     {
6750       if (others == 1)
6751         printf_filtered (_("Note: breakpoint "));
6752       else /* if (others == ???) */
6753         printf_filtered (_("Note: breakpoints "));
6754       ALL_BREAKPOINTS (b)
6755         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6756           {
6757             others--;
6758             printf_filtered ("%d", b->number);
6759             if (b->thread == -1 && thread != -1)
6760               printf_filtered (" (all threads)");
6761             else if (b->thread != -1)
6762               printf_filtered (" (thread %d)", b->thread);
6763             printf_filtered ("%s%s ",
6764                              ((b->enable_state == bp_disabled
6765                                || b->enable_state == bp_call_disabled)
6766                               ? " (disabled)"
6767                               : ""),
6768                              (others > 1) ? "," 
6769                              : ((others == 1) ? " and" : ""));
6770           }
6771       current_uiout->message (_("also set at pc %ps.\n"),
6772                               styled_string (address_style.style (),
6773                                              paddress (gdbarch, pc)));
6774     }
6775 }
6776 \f
6777
6778 /* Return true iff it is meaningful to use the address member of LOC.
6779    For some breakpoint types, the locations' address members are
6780    irrelevant and it makes no sense to attempt to compare them to
6781    other addresses (or use them for any other purpose either).
6782
6783    More specifically, software watchpoints and catchpoints that are
6784    not backed by breakpoints always have a zero valued location
6785    address and we don't want to mark breakpoints of any of these types
6786    to be a duplicate of an actual breakpoint location at address
6787    zero.  */
6788
6789 static bool
6790 bl_address_is_meaningful (bp_location *loc)
6791 {
6792   return loc->loc_type != bp_loc_other;
6793 }
6794
6795 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6796    true if LOC1 and LOC2 represent the same watchpoint location.  */
6797
6798 static int
6799 watchpoint_locations_match (struct bp_location *loc1, 
6800                             struct bp_location *loc2)
6801 {
6802   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6803   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6804
6805   /* Both of them must exist.  */
6806   gdb_assert (w1 != NULL);
6807   gdb_assert (w2 != NULL);
6808
6809   /* If the target can evaluate the condition expression in hardware,
6810      then we we need to insert both watchpoints even if they are at
6811      the same place.  Otherwise the watchpoint will only trigger when
6812      the condition of whichever watchpoint was inserted evaluates to
6813      true, not giving a chance for GDB to check the condition of the
6814      other watchpoint.  */
6815   if ((w1->cond_exp
6816        && target_can_accel_watchpoint_condition (loc1->address, 
6817                                                  loc1->length,
6818                                                  loc1->watchpoint_type,
6819                                                  w1->cond_exp.get ()))
6820       || (w2->cond_exp
6821           && target_can_accel_watchpoint_condition (loc2->address, 
6822                                                     loc2->length,
6823                                                     loc2->watchpoint_type,
6824                                                     w2->cond_exp.get ())))
6825     return 0;
6826
6827   /* Note that this checks the owner's type, not the location's.  In
6828      case the target does not support read watchpoints, but does
6829      support access watchpoints, we'll have bp_read_watchpoint
6830      watchpoints with hw_access locations.  Those should be considered
6831      duplicates of hw_read locations.  The hw_read locations will
6832      become hw_access locations later.  */
6833   return (loc1->owner->type == loc2->owner->type
6834           && loc1->pspace->aspace == loc2->pspace->aspace
6835           && loc1->address == loc2->address
6836           && loc1->length == loc2->length);
6837 }
6838
6839 /* See breakpoint.h.  */
6840
6841 int
6842 breakpoint_address_match (const address_space *aspace1, CORE_ADDR addr1,
6843                           const address_space *aspace2, CORE_ADDR addr2)
6844 {
6845   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6846            || aspace1 == aspace2)
6847           && addr1 == addr2);
6848 }
6849
6850 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6851    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6852    matches ASPACE2.  On targets that have global breakpoints, the address
6853    space doesn't really matter.  */
6854
6855 static int
6856 breakpoint_address_match_range (const address_space *aspace1,
6857                                 CORE_ADDR addr1,
6858                                 int len1, const address_space *aspace2,
6859                                 CORE_ADDR addr2)
6860 {
6861   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6862            || aspace1 == aspace2)
6863           && addr2 >= addr1 && addr2 < addr1 + len1);
6864 }
6865
6866 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6867    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6868    matches the breakpoint's address space.  On targets that have global
6869    breakpoints, the address space doesn't really matter.  */
6870
6871 static int
6872 breakpoint_location_address_match (struct bp_location *bl,
6873                                    const address_space *aspace,
6874                                    CORE_ADDR addr)
6875 {
6876   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6877                                     aspace, addr)
6878           || (bl->length
6879               && breakpoint_address_match_range (bl->pspace->aspace,
6880                                                  bl->address, bl->length,
6881                                                  aspace, addr)));
6882 }
6883
6884 /* Returns true if the [ADDR,ADDR+LEN) range in ASPACE overlaps
6885    breakpoint BL.  BL may be a ranged breakpoint.  In most targets, a
6886    match happens only if ASPACE matches the breakpoint's address
6887    space.  On targets that have global breakpoints, the address space
6888    doesn't really matter.  */
6889
6890 static int
6891 breakpoint_location_address_range_overlap (struct bp_location *bl,
6892                                            const address_space *aspace,
6893                                            CORE_ADDR addr, int len)
6894 {
6895   if (gdbarch_has_global_breakpoints (target_gdbarch ())
6896       || bl->pspace->aspace == aspace)
6897     {
6898       int bl_len = bl->length != 0 ? bl->length : 1;
6899
6900       if (mem_ranges_overlap (addr, len, bl->address, bl_len))
6901         return 1;
6902     }
6903   return 0;
6904 }
6905
6906 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6907    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6908    true, otherwise returns false.  */
6909
6910 static int
6911 tracepoint_locations_match (struct bp_location *loc1,
6912                             struct bp_location *loc2)
6913 {
6914   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6915     /* Since tracepoint locations are never duplicated with others', tracepoint
6916        locations at the same address of different tracepoints are regarded as
6917        different locations.  */
6918     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6919   else
6920     return 0;
6921 }
6922
6923 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6924    (bl_address_is_meaningful), returns true if LOC1 and LOC2 represent
6925    the same location.  If SW_HW_BPS_MATCH is true, then software
6926    breakpoint locations and hardware breakpoint locations match,
6927    otherwise they don't.  */
6928
6929 static int
6930 breakpoint_locations_match (struct bp_location *loc1,
6931                             struct bp_location *loc2,
6932                             bool sw_hw_bps_match)
6933 {
6934   int hw_point1, hw_point2;
6935
6936   /* Both of them must not be in moribund_locations.  */
6937   gdb_assert (loc1->owner != NULL);
6938   gdb_assert (loc2->owner != NULL);
6939
6940   hw_point1 = is_hardware_watchpoint (loc1->owner);
6941   hw_point2 = is_hardware_watchpoint (loc2->owner);
6942
6943   if (hw_point1 != hw_point2)
6944     return 0;
6945   else if (hw_point1)
6946     return watchpoint_locations_match (loc1, loc2);
6947   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6948     return tracepoint_locations_match (loc1, loc2);
6949   else
6950     /* We compare bp_location.length in order to cover ranged
6951        breakpoints.  Keep this in sync with
6952        bp_location_is_less_than.  */
6953     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6954                                      loc2->pspace->aspace, loc2->address)
6955             && (loc1->loc_type == loc2->loc_type || sw_hw_bps_match)
6956             && loc1->length == loc2->length);
6957 }
6958
6959 static void
6960 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6961                                int bnum, int have_bnum)
6962 {
6963   /* The longest string possibly returned by hex_string_custom
6964      is 50 chars.  These must be at least that big for safety.  */
6965   char astr1[64];
6966   char astr2[64];
6967
6968   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6969   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6970   if (have_bnum)
6971     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6972              bnum, astr1, astr2);
6973   else
6974     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6975 }
6976
6977 /* Adjust a breakpoint's address to account for architectural
6978    constraints on breakpoint placement.  Return the adjusted address.
6979    Note: Very few targets require this kind of adjustment.  For most
6980    targets, this function is simply the identity function.  */
6981
6982 static CORE_ADDR
6983 adjust_breakpoint_address (struct gdbarch *gdbarch,
6984                            CORE_ADDR bpaddr, enum bptype bptype)
6985 {
6986   if (bptype == bp_watchpoint
6987       || bptype == bp_hardware_watchpoint
6988       || bptype == bp_read_watchpoint
6989       || bptype == bp_access_watchpoint
6990       || bptype == bp_catchpoint)
6991     {
6992       /* Watchpoints and the various bp_catch_* eventpoints should not
6993          have their addresses modified.  */
6994       return bpaddr;
6995     }
6996   else if (bptype == bp_single_step)
6997     {
6998       /* Single-step breakpoints should not have their addresses
6999          modified.  If there's any architectural constrain that
7000          applies to this address, then it should have already been
7001          taken into account when the breakpoint was created in the
7002          first place.  If we didn't do this, stepping through e.g.,
7003          Thumb-2 IT blocks would break.  */
7004       return bpaddr;
7005     }
7006   else
7007     {
7008       CORE_ADDR adjusted_bpaddr = bpaddr;
7009
7010       if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7011         {
7012           /* Some targets have architectural constraints on the placement
7013              of breakpoint instructions.  Obtain the adjusted address.  */
7014           adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7015         }
7016
7017       adjusted_bpaddr = address_significant (gdbarch, adjusted_bpaddr);
7018
7019       /* An adjusted breakpoint address can significantly alter
7020          a user's expectations.  Print a warning if an adjustment
7021          is required.  */
7022       if (adjusted_bpaddr != bpaddr)
7023         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7024
7025       return adjusted_bpaddr;
7026     }
7027 }
7028
7029 static bp_loc_type
7030 bp_location_from_bp_type (bptype type)
7031 {
7032   switch (type)
7033     {
7034     case bp_breakpoint:
7035     case bp_single_step:
7036     case bp_until:
7037     case bp_finish:
7038     case bp_longjmp:
7039     case bp_longjmp_resume:
7040     case bp_longjmp_call_dummy:
7041     case bp_exception:
7042     case bp_exception_resume:
7043     case bp_step_resume:
7044     case bp_hp_step_resume:
7045     case bp_watchpoint_scope:
7046     case bp_call_dummy:
7047     case bp_std_terminate:
7048     case bp_shlib_event:
7049     case bp_thread_event:
7050     case bp_overlay_event:
7051     case bp_jit_event:
7052     case bp_longjmp_master:
7053     case bp_std_terminate_master:
7054     case bp_exception_master:
7055     case bp_gnu_ifunc_resolver:
7056     case bp_gnu_ifunc_resolver_return:
7057     case bp_dprintf:
7058       return bp_loc_software_breakpoint;
7059     case bp_hardware_breakpoint:
7060       return bp_loc_hardware_breakpoint;
7061     case bp_hardware_watchpoint:
7062     case bp_read_watchpoint:
7063     case bp_access_watchpoint:
7064       return bp_loc_hardware_watchpoint;
7065     case bp_watchpoint:
7066     case bp_catchpoint:
7067     case bp_tracepoint:
7068     case bp_fast_tracepoint:
7069     case bp_static_tracepoint:
7070       return bp_loc_other;
7071     default:
7072       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7073     }
7074 }
7075
7076 bp_location::bp_location (breakpoint *owner, bp_loc_type type)
7077 {
7078   this->owner = owner;
7079   this->cond_bytecode = NULL;
7080   this->shlib_disabled = 0;
7081   this->enabled = 1;
7082   this->disabled_by_cond = false;
7083
7084   this->loc_type = type;
7085
7086   if (this->loc_type == bp_loc_software_breakpoint
7087       || this->loc_type == bp_loc_hardware_breakpoint)
7088     mark_breakpoint_location_modified (this);
7089
7090   incref ();
7091 }
7092
7093 bp_location::bp_location (breakpoint *owner)
7094   : bp_location::bp_location (owner,
7095                               bp_location_from_bp_type (owner->type))
7096 {
7097 }
7098
7099 /* Allocate a struct bp_location.  */
7100
7101 static struct bp_location *
7102 allocate_bp_location (struct breakpoint *bpt)
7103 {
7104   return bpt->ops->allocate_location (bpt);
7105 }
7106
7107 /* Decrement reference count.  If the reference count reaches 0,
7108    destroy the bp_location.  Sets *BLP to NULL.  */
7109
7110 static void
7111 decref_bp_location (struct bp_location **blp)
7112 {
7113   bp_location_ref_policy::decref (*blp);
7114   *blp = NULL;
7115 }
7116
7117 /* Add breakpoint B at the end of the global breakpoint chain.  */
7118
7119 static breakpoint *
7120 add_to_breakpoint_chain (std::unique_ptr<breakpoint> &&b)
7121 {
7122   struct breakpoint *b1;
7123   struct breakpoint *result = b.get ();
7124
7125   /* Add this breakpoint to the end of the chain so that a list of
7126      breakpoints will come out in order of increasing numbers.  */
7127
7128   b1 = breakpoint_chain;
7129   if (b1 == 0)
7130     breakpoint_chain = b.release ();
7131   else
7132     {
7133       while (b1->next)
7134         b1 = b1->next;
7135       b1->next = b.release ();
7136     }
7137
7138   return result;
7139 }
7140
7141 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7142
7143 static void
7144 init_raw_breakpoint_without_location (struct breakpoint *b,
7145                                       struct gdbarch *gdbarch,
7146                                       enum bptype bptype,
7147                                       const struct breakpoint_ops *ops)
7148 {
7149   gdb_assert (ops != NULL);
7150
7151   b->ops = ops;
7152   b->type = bptype;
7153   b->gdbarch = gdbarch;
7154   b->language = current_language->la_language;
7155   b->input_radix = input_radix;
7156   b->related_breakpoint = b;
7157 }
7158
7159 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7160    that has type BPTYPE and has no locations as yet.  */
7161
7162 static struct breakpoint *
7163 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7164                                      enum bptype bptype,
7165                                      const struct breakpoint_ops *ops)
7166 {
7167   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7168
7169   init_raw_breakpoint_without_location (b.get (), gdbarch, bptype, ops);
7170   return add_to_breakpoint_chain (std::move (b));
7171 }
7172
7173 /* Initialize loc->function_name.  */
7174
7175 static void
7176 set_breakpoint_location_function (struct bp_location *loc)
7177 {
7178   gdb_assert (loc->owner != NULL);
7179
7180   if (loc->owner->type == bp_breakpoint
7181       || loc->owner->type == bp_hardware_breakpoint
7182       || is_tracepoint (loc->owner))
7183     {
7184       const char *function_name;
7185
7186       if (loc->msymbol != NULL
7187           && (MSYMBOL_TYPE (loc->msymbol) == mst_text_gnu_ifunc
7188               || MSYMBOL_TYPE (loc->msymbol) == mst_data_gnu_ifunc))
7189         {
7190           struct breakpoint *b = loc->owner;
7191
7192           function_name = loc->msymbol->linkage_name ();
7193
7194           if (b->type == bp_breakpoint && b->loc == loc
7195               && loc->next == NULL && b->related_breakpoint == b)
7196             {
7197               /* Create only the whole new breakpoint of this type but do not
7198                  mess more complicated breakpoints with multiple locations.  */
7199               b->type = bp_gnu_ifunc_resolver;
7200               /* Remember the resolver's address for use by the return
7201                  breakpoint.  */
7202               loc->related_address = loc->address;
7203             }
7204         }
7205       else
7206         find_pc_partial_function (loc->address, &function_name, NULL, NULL);
7207
7208       if (function_name)
7209         loc->function_name = xstrdup (function_name);
7210     }
7211 }
7212
7213 /* Attempt to determine architecture of location identified by SAL.  */
7214 struct gdbarch *
7215 get_sal_arch (struct symtab_and_line sal)
7216 {
7217   if (sal.section)
7218     return sal.section->objfile->arch ();
7219   if (sal.symtab)
7220     return SYMTAB_OBJFILE (sal.symtab)->arch ();
7221
7222   return NULL;
7223 }
7224
7225 /* Low level routine for partially initializing a breakpoint of type
7226    BPTYPE.  The newly created breakpoint's address, section, source
7227    file name, and line number are provided by SAL.
7228
7229    It is expected that the caller will complete the initialization of
7230    the newly created breakpoint struct as well as output any status
7231    information regarding the creation of a new breakpoint.  */
7232
7233 static void
7234 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7235                      struct symtab_and_line sal, enum bptype bptype,
7236                      const struct breakpoint_ops *ops)
7237 {
7238   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7239
7240   add_location_to_breakpoint (b, &sal);
7241
7242   if (bptype != bp_catchpoint)
7243     gdb_assert (sal.pspace != NULL);
7244
7245   /* Store the program space that was used to set the breakpoint,
7246      except for ordinary breakpoints, which are independent of the
7247      program space.  */
7248   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7249     b->pspace = sal.pspace;
7250 }
7251
7252 /* set_raw_breakpoint is a low level routine for allocating and
7253    partially initializing a breakpoint of type BPTYPE.  The newly
7254    created breakpoint's address, section, source file name, and line
7255    number are provided by SAL.  The newly created and partially
7256    initialized breakpoint is added to the breakpoint chain and
7257    is also returned as the value of this function.
7258
7259    It is expected that the caller will complete the initialization of
7260    the newly created breakpoint struct as well as output any status
7261    information regarding the creation of a new breakpoint.  In
7262    particular, set_raw_breakpoint does NOT set the breakpoint
7263    number!  Care should be taken to not allow an error to occur
7264    prior to completing the initialization of the breakpoint.  If this
7265    should happen, a bogus breakpoint will be left on the chain.  */
7266
7267 struct breakpoint *
7268 set_raw_breakpoint (struct gdbarch *gdbarch,
7269                     struct symtab_and_line sal, enum bptype bptype,
7270                     const struct breakpoint_ops *ops)
7271 {
7272   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (bptype);
7273
7274   init_raw_breakpoint (b.get (), gdbarch, sal, bptype, ops);
7275   return add_to_breakpoint_chain (std::move (b));
7276 }
7277
7278 /* Call this routine when stepping and nexting to enable a breakpoint
7279    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7280    initiated the operation.  */
7281
7282 void
7283 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7284 {
7285   struct breakpoint *b, *b_tmp;
7286   int thread = tp->global_num;
7287
7288   /* To avoid having to rescan all objfile symbols at every step,
7289      we maintain a list of continually-inserted but always disabled
7290      longjmp "master" breakpoints.  Here, we simply create momentary
7291      clones of those and enable them for the requested thread.  */
7292   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7293     if (b->pspace == current_program_space
7294         && (b->type == bp_longjmp_master
7295             || b->type == bp_exception_master))
7296       {
7297         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7298         struct breakpoint *clone;
7299
7300         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7301            after their removal.  */
7302         clone = momentary_breakpoint_from_master (b, type,
7303                                                   &momentary_breakpoint_ops, 1);
7304         clone->thread = thread;
7305       }
7306
7307   tp->initiating_frame = frame;
7308 }
7309
7310 /* Delete all longjmp breakpoints from THREAD.  */
7311 void
7312 delete_longjmp_breakpoint (int thread)
7313 {
7314   struct breakpoint *b, *b_tmp;
7315
7316   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7317     if (b->type == bp_longjmp || b->type == bp_exception)
7318       {
7319         if (b->thread == thread)
7320           delete_breakpoint (b);
7321       }
7322 }
7323
7324 void
7325 delete_longjmp_breakpoint_at_next_stop (int thread)
7326 {
7327   struct breakpoint *b, *b_tmp;
7328
7329   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7330     if (b->type == bp_longjmp || b->type == bp_exception)
7331       {
7332         if (b->thread == thread)
7333           b->disposition = disp_del_at_next_stop;
7334       }
7335 }
7336
7337 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7338    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7339    pointer to any of them.  Return NULL if this system cannot place longjmp
7340    breakpoints.  */
7341
7342 struct breakpoint *
7343 set_longjmp_breakpoint_for_call_dummy (void)
7344 {
7345   struct breakpoint *b, *retval = NULL;
7346
7347   ALL_BREAKPOINTS (b)
7348     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7349       {
7350         struct breakpoint *new_b;
7351
7352         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7353                                                   &momentary_breakpoint_ops,
7354                                                   1);
7355         new_b->thread = inferior_thread ()->global_num;
7356
7357         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7358
7359         gdb_assert (new_b->related_breakpoint == new_b);
7360         if (retval == NULL)
7361           retval = new_b;
7362         new_b->related_breakpoint = retval;
7363         while (retval->related_breakpoint != new_b->related_breakpoint)
7364           retval = retval->related_breakpoint;
7365         retval->related_breakpoint = new_b;
7366       }
7367
7368   return retval;
7369 }
7370
7371 /* Verify all existing dummy frames and their associated breakpoints for
7372    TP.  Remove those which can no longer be found in the current frame
7373    stack.
7374
7375    You should call this function only at places where it is safe to currently
7376    unwind the whole stack.  Failed stack unwind would discard live dummy
7377    frames.  */
7378
7379 void
7380 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7381 {
7382   struct breakpoint *b, *b_tmp;
7383
7384   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7385     if (b->type == bp_longjmp_call_dummy && b->thread == tp->global_num)
7386       {
7387         struct breakpoint *dummy_b = b->related_breakpoint;
7388
7389         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7390           dummy_b = dummy_b->related_breakpoint;
7391         if (dummy_b->type != bp_call_dummy
7392             || frame_find_by_id (dummy_b->frame_id) != NULL)
7393           continue;
7394         
7395         dummy_frame_discard (dummy_b->frame_id, tp);
7396
7397         while (b->related_breakpoint != b)
7398           {
7399             if (b_tmp == b->related_breakpoint)
7400               b_tmp = b->related_breakpoint->next;
7401             delete_breakpoint (b->related_breakpoint);
7402           }
7403         delete_breakpoint (b);
7404       }
7405 }
7406
7407 void
7408 enable_overlay_breakpoints (void)
7409 {
7410   struct breakpoint *b;
7411
7412   ALL_BREAKPOINTS (b)
7413     if (b->type == bp_overlay_event)
7414     {
7415       b->enable_state = bp_enabled;
7416       update_global_location_list (UGLL_MAY_INSERT);
7417       overlay_events_enabled = 1;
7418     }
7419 }
7420
7421 void
7422 disable_overlay_breakpoints (void)
7423 {
7424   struct breakpoint *b;
7425
7426   ALL_BREAKPOINTS (b)
7427     if (b->type == bp_overlay_event)
7428     {
7429       b->enable_state = bp_disabled;
7430       update_global_location_list (UGLL_DONT_INSERT);
7431       overlay_events_enabled = 0;
7432     }
7433 }
7434
7435 /* Set an active std::terminate breakpoint for each std::terminate
7436    master breakpoint.  */
7437 void
7438 set_std_terminate_breakpoint (void)
7439 {
7440   struct breakpoint *b, *b_tmp;
7441
7442   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7443     if (b->pspace == current_program_space
7444         && b->type == bp_std_terminate_master)
7445       {
7446         momentary_breakpoint_from_master (b, bp_std_terminate,
7447                                           &momentary_breakpoint_ops, 1);
7448       }
7449 }
7450
7451 /* Delete all the std::terminate breakpoints.  */
7452 void
7453 delete_std_terminate_breakpoint (void)
7454 {
7455   struct breakpoint *b, *b_tmp;
7456
7457   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7458     if (b->type == bp_std_terminate)
7459       delete_breakpoint (b);
7460 }
7461
7462 struct breakpoint *
7463 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7464 {
7465   struct breakpoint *b;
7466
7467   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7468                                   &internal_breakpoint_ops);
7469
7470   b->enable_state = bp_enabled;
7471   /* location has to be used or breakpoint_re_set will delete me.  */
7472   b->location = new_address_location (b->loc->address, NULL, 0);
7473
7474   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7475
7476   return b;
7477 }
7478
7479 struct lang_and_radix
7480   {
7481     enum language lang;
7482     int radix;
7483   };
7484
7485 /* Create a breakpoint for JIT code registration and unregistration.  */
7486
7487 struct breakpoint *
7488 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7489 {
7490   return create_internal_breakpoint (gdbarch, address, bp_jit_event,
7491                                      &internal_breakpoint_ops);
7492 }
7493
7494 /* Remove JIT code registration and unregistration breakpoint(s).  */
7495
7496 void
7497 remove_jit_event_breakpoints (void)
7498 {
7499   struct breakpoint *b, *b_tmp;
7500
7501   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7502     if (b->type == bp_jit_event
7503         && b->loc->pspace == current_program_space)
7504       delete_breakpoint (b);
7505 }
7506
7507 void
7508 remove_solib_event_breakpoints (void)
7509 {
7510   struct breakpoint *b, *b_tmp;
7511
7512   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7513     if (b->type == bp_shlib_event
7514         && b->loc->pspace == current_program_space)
7515       delete_breakpoint (b);
7516 }
7517
7518 /* See breakpoint.h.  */
7519
7520 void
7521 remove_solib_event_breakpoints_at_next_stop (void)
7522 {
7523   struct breakpoint *b, *b_tmp;
7524
7525   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7526     if (b->type == bp_shlib_event
7527         && b->loc->pspace == current_program_space)
7528       b->disposition = disp_del_at_next_stop;
7529 }
7530
7531 /* Helper for create_solib_event_breakpoint /
7532    create_and_insert_solib_event_breakpoint.  Allows specifying which
7533    INSERT_MODE to pass through to update_global_location_list.  */
7534
7535 static struct breakpoint *
7536 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7537                                  enum ugll_insert_mode insert_mode)
7538 {
7539   struct breakpoint *b;
7540
7541   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7542                                   &internal_breakpoint_ops);
7543   update_global_location_list_nothrow (insert_mode);
7544   return b;
7545 }
7546
7547 struct breakpoint *
7548 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7549 {
7550   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7551 }
7552
7553 /* See breakpoint.h.  */
7554
7555 struct breakpoint *
7556 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7557 {
7558   struct breakpoint *b;
7559
7560   /* Explicitly tell update_global_location_list to insert
7561      locations.  */
7562   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7563   if (!b->loc->inserted)
7564     {
7565       delete_breakpoint (b);
7566       return NULL;
7567     }
7568   return b;
7569 }
7570
7571 /* Disable any breakpoints that are on code in shared libraries.  Only
7572    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7573
7574 void
7575 disable_breakpoints_in_shlibs (void)
7576 {
7577   struct bp_location *loc, **locp_tmp;
7578
7579   ALL_BP_LOCATIONS (loc, locp_tmp)
7580   {
7581     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7582     struct breakpoint *b = loc->owner;
7583
7584     /* We apply the check to all breakpoints, including disabled for
7585        those with loc->duplicate set.  This is so that when breakpoint
7586        becomes enabled, or the duplicate is removed, gdb will try to
7587        insert all breakpoints.  If we don't set shlib_disabled here,
7588        we'll try to insert those breakpoints and fail.  */
7589     if (((b->type == bp_breakpoint)
7590          || (b->type == bp_jit_event)
7591          || (b->type == bp_hardware_breakpoint)
7592          || (is_tracepoint (b)))
7593         && loc->pspace == current_program_space
7594         && !loc->shlib_disabled
7595         && solib_name_from_address (loc->pspace, loc->address)
7596         )
7597       {
7598         loc->shlib_disabled = 1;
7599       }
7600   }
7601 }
7602
7603 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7604    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7605    disabled ones can just stay disabled.  */
7606
7607 static void
7608 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7609 {
7610   struct bp_location *loc, **locp_tmp;
7611   int disabled_shlib_breaks = 0;
7612
7613   ALL_BP_LOCATIONS (loc, locp_tmp)
7614   {
7615     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7616     struct breakpoint *b = loc->owner;
7617
7618     if (solib->pspace == loc->pspace
7619         && !loc->shlib_disabled
7620         && (((b->type == bp_breakpoint
7621               || b->type == bp_jit_event
7622               || b->type == bp_hardware_breakpoint)
7623              && (loc->loc_type == bp_loc_hardware_breakpoint
7624                  || loc->loc_type == bp_loc_software_breakpoint))
7625             || is_tracepoint (b))
7626         && solib_contains_address_p (solib, loc->address))
7627       {
7628         loc->shlib_disabled = 1;
7629         /* At this point, we cannot rely on remove_breakpoint
7630            succeeding so we must mark the breakpoint as not inserted
7631            to prevent future errors occurring in remove_breakpoints.  */
7632         loc->inserted = 0;
7633
7634         /* This may cause duplicate notifications for the same breakpoint.  */
7635         gdb::observers::breakpoint_modified.notify (b);
7636
7637         if (!disabled_shlib_breaks)
7638           {
7639             target_terminal::ours_for_output ();
7640             warning (_("Temporarily disabling breakpoints "
7641                        "for unloaded shared library \"%s\""),
7642                      solib->so_name);
7643           }
7644         disabled_shlib_breaks = 1;
7645       }
7646   }
7647 }
7648
7649 /* Disable any breakpoints and tracepoints in OBJFILE upon
7650    notification of free_objfile.  Only apply to enabled breakpoints,
7651    disabled ones can just stay disabled.  */
7652
7653 static void
7654 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7655 {
7656   struct breakpoint *b;
7657
7658   if (objfile == NULL)
7659     return;
7660
7661   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7662      managed by the user with add-symbol-file/remove-symbol-file.
7663      Similarly to how breakpoints in shared libraries are handled in
7664      response to "nosharedlibrary", mark breakpoints in such modules
7665      shlib_disabled so they end up uninserted on the next global
7666      location list update.  Shared libraries not loaded by the user
7667      aren't handled here -- they're already handled in
7668      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7669      solib_unloaded observer.  We skip objfiles that are not
7670      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7671      main objfile).  */
7672   if ((objfile->flags & OBJF_SHARED) == 0
7673       || (objfile->flags & OBJF_USERLOADED) == 0)
7674     return;
7675
7676   ALL_BREAKPOINTS (b)
7677     {
7678       struct bp_location *loc;
7679       int bp_modified = 0;
7680
7681       if (!is_breakpoint (b) && !is_tracepoint (b))
7682         continue;
7683
7684       for (loc = b->loc; loc != NULL; loc = loc->next)
7685         {
7686           CORE_ADDR loc_addr = loc->address;
7687
7688           if (loc->loc_type != bp_loc_hardware_breakpoint
7689               && loc->loc_type != bp_loc_software_breakpoint)
7690             continue;
7691
7692           if (loc->shlib_disabled != 0)
7693             continue;
7694
7695           if (objfile->pspace != loc->pspace)
7696             continue;
7697
7698           if (loc->loc_type != bp_loc_hardware_breakpoint
7699               && loc->loc_type != bp_loc_software_breakpoint)
7700             continue;
7701
7702           if (is_addr_in_objfile (loc_addr, objfile))
7703             {
7704               loc->shlib_disabled = 1;
7705               /* At this point, we don't know whether the object was
7706                  unmapped from the inferior or not, so leave the
7707                  inserted flag alone.  We'll handle failure to
7708                  uninsert quietly, in case the object was indeed
7709                  unmapped.  */
7710
7711               mark_breakpoint_location_modified (loc);
7712
7713               bp_modified = 1;
7714             }
7715         }
7716
7717       if (bp_modified)
7718         gdb::observers::breakpoint_modified.notify (b);
7719     }
7720 }
7721
7722 /* FORK & VFORK catchpoints.  */
7723
7724 /* An instance of this type is used to represent a fork or vfork
7725    catchpoint.  A breakpoint is really of this type iff its ops pointer points
7726    to CATCH_FORK_BREAKPOINT_OPS.  */
7727
7728 struct fork_catchpoint : public breakpoint
7729 {
7730   /* Process id of a child process whose forking triggered this
7731      catchpoint.  This field is only valid immediately after this
7732      catchpoint has triggered.  */
7733   ptid_t forked_inferior_pid;
7734 };
7735
7736 /* Implement the "insert" breakpoint_ops method for fork
7737    catchpoints.  */
7738
7739 static int
7740 insert_catch_fork (struct bp_location *bl)
7741 {
7742   return target_insert_fork_catchpoint (inferior_ptid.pid ());
7743 }
7744
7745 /* Implement the "remove" breakpoint_ops method for fork
7746    catchpoints.  */
7747
7748 static int
7749 remove_catch_fork (struct bp_location *bl, enum remove_bp_reason reason)
7750 {
7751   return target_remove_fork_catchpoint (inferior_ptid.pid ());
7752 }
7753
7754 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7755    catchpoints.  */
7756
7757 static int
7758 breakpoint_hit_catch_fork (const struct bp_location *bl,
7759                            const address_space *aspace, CORE_ADDR bp_addr,
7760                            const struct target_waitstatus *ws)
7761 {
7762   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7763
7764   if (ws->kind != TARGET_WAITKIND_FORKED)
7765     return 0;
7766
7767   c->forked_inferior_pid = ws->value.related_pid;
7768   return 1;
7769 }
7770
7771 /* Implement the "print_it" breakpoint_ops method for fork
7772    catchpoints.  */
7773
7774 static enum print_stop_action
7775 print_it_catch_fork (bpstat bs)
7776 {
7777   struct ui_out *uiout = current_uiout;
7778   struct breakpoint *b = bs->breakpoint_at;
7779   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7780
7781   annotate_catchpoint (b->number);
7782   maybe_print_thread_hit_breakpoint (uiout);
7783   if (b->disposition == disp_del)
7784     uiout->text ("Temporary catchpoint ");
7785   else
7786     uiout->text ("Catchpoint ");
7787   if (uiout->is_mi_like_p ())
7788     {
7789       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_FORK));
7790       uiout->field_string ("disp", bpdisp_text (b->disposition));
7791     }
7792   uiout->field_signed ("bkptno", b->number);
7793   uiout->text (" (forked process ");
7794   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7795   uiout->text ("), ");
7796   return PRINT_SRC_AND_LOC;
7797 }
7798
7799 /* Implement the "print_one" breakpoint_ops method for fork
7800    catchpoints.  */
7801
7802 static void
7803 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7804 {
7805   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7806   struct value_print_options opts;
7807   struct ui_out *uiout = current_uiout;
7808
7809   get_user_print_options (&opts);
7810
7811   /* Field 4, the address, is omitted (which makes the columns not
7812      line up too nicely with the headers, but the effect is relatively
7813      readable).  */
7814   if (opts.addressprint)
7815     uiout->field_skip ("addr");
7816   annotate_field (5);
7817   uiout->text ("fork");
7818   if (c->forked_inferior_pid != null_ptid)
7819     {
7820       uiout->text (", process ");
7821       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7822       uiout->spaces (1);
7823     }
7824
7825   if (uiout->is_mi_like_p ())
7826     uiout->field_string ("catch-type", "fork");
7827 }
7828
7829 /* Implement the "print_mention" breakpoint_ops method for fork
7830    catchpoints.  */
7831
7832 static void
7833 print_mention_catch_fork (struct breakpoint *b)
7834 {
7835   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7836 }
7837
7838 /* Implement the "print_recreate" breakpoint_ops method for fork
7839    catchpoints.  */
7840
7841 static void
7842 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7843 {
7844   fprintf_unfiltered (fp, "catch fork");
7845   print_recreate_thread (b, fp);
7846 }
7847
7848 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7849
7850 static struct breakpoint_ops catch_fork_breakpoint_ops;
7851
7852 /* Implement the "insert" breakpoint_ops method for vfork
7853    catchpoints.  */
7854
7855 static int
7856 insert_catch_vfork (struct bp_location *bl)
7857 {
7858   return target_insert_vfork_catchpoint (inferior_ptid.pid ());
7859 }
7860
7861 /* Implement the "remove" breakpoint_ops method for vfork
7862    catchpoints.  */
7863
7864 static int
7865 remove_catch_vfork (struct bp_location *bl, enum remove_bp_reason reason)
7866 {
7867   return target_remove_vfork_catchpoint (inferior_ptid.pid ());
7868 }
7869
7870 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7871    catchpoints.  */
7872
7873 static int
7874 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7875                             const address_space *aspace, CORE_ADDR bp_addr,
7876                             const struct target_waitstatus *ws)
7877 {
7878   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7879
7880   if (ws->kind != TARGET_WAITKIND_VFORKED)
7881     return 0;
7882
7883   c->forked_inferior_pid = ws->value.related_pid;
7884   return 1;
7885 }
7886
7887 /* Implement the "print_it" breakpoint_ops method for vfork
7888    catchpoints.  */
7889
7890 static enum print_stop_action
7891 print_it_catch_vfork (bpstat bs)
7892 {
7893   struct ui_out *uiout = current_uiout;
7894   struct breakpoint *b = bs->breakpoint_at;
7895   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7896
7897   annotate_catchpoint (b->number);
7898   maybe_print_thread_hit_breakpoint (uiout);
7899   if (b->disposition == disp_del)
7900     uiout->text ("Temporary catchpoint ");
7901   else
7902     uiout->text ("Catchpoint ");
7903   if (uiout->is_mi_like_p ())
7904     {
7905       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_VFORK));
7906       uiout->field_string ("disp", bpdisp_text (b->disposition));
7907     }
7908   uiout->field_signed ("bkptno", b->number);
7909   uiout->text (" (vforked process ");
7910   uiout->field_signed ("newpid", c->forked_inferior_pid.pid ());
7911   uiout->text ("), ");
7912   return PRINT_SRC_AND_LOC;
7913 }
7914
7915 /* Implement the "print_one" breakpoint_ops method for vfork
7916    catchpoints.  */
7917
7918 static void
7919 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7920 {
7921   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7922   struct value_print_options opts;
7923   struct ui_out *uiout = current_uiout;
7924
7925   get_user_print_options (&opts);
7926   /* Field 4, the address, is omitted (which makes the columns not
7927      line up too nicely with the headers, but the effect is relatively
7928      readable).  */
7929   if (opts.addressprint)
7930     uiout->field_skip ("addr");
7931   annotate_field (5);
7932   uiout->text ("vfork");
7933   if (c->forked_inferior_pid != null_ptid)
7934     {
7935       uiout->text (", process ");
7936       uiout->field_signed ("what", c->forked_inferior_pid.pid ());
7937       uiout->spaces (1);
7938     }
7939
7940   if (uiout->is_mi_like_p ())
7941     uiout->field_string ("catch-type", "vfork");
7942 }
7943
7944 /* Implement the "print_mention" breakpoint_ops method for vfork
7945    catchpoints.  */
7946
7947 static void
7948 print_mention_catch_vfork (struct breakpoint *b)
7949 {
7950   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7951 }
7952
7953 /* Implement the "print_recreate" breakpoint_ops method for vfork
7954    catchpoints.  */
7955
7956 static void
7957 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7958 {
7959   fprintf_unfiltered (fp, "catch vfork");
7960   print_recreate_thread (b, fp);
7961 }
7962
7963 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7964
7965 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7966
7967 /* An instance of this type is used to represent an solib catchpoint.
7968    A breakpoint is really of this type iff its ops pointer points to
7969    CATCH_SOLIB_BREAKPOINT_OPS.  */
7970
7971 struct solib_catchpoint : public breakpoint
7972 {
7973   ~solib_catchpoint () override;
7974
7975   /* True for "catch load", false for "catch unload".  */
7976   bool is_load;
7977
7978   /* Regular expression to match, if any.  COMPILED is only valid when
7979      REGEX is non-NULL.  */
7980   char *regex;
7981   std::unique_ptr<compiled_regex> compiled;
7982 };
7983
7984 solib_catchpoint::~solib_catchpoint ()
7985 {
7986   xfree (this->regex);
7987 }
7988
7989 static int
7990 insert_catch_solib (struct bp_location *ignore)
7991 {
7992   return 0;
7993 }
7994
7995 static int
7996 remove_catch_solib (struct bp_location *ignore, enum remove_bp_reason reason)
7997 {
7998   return 0;
7999 }
8000
8001 static int
8002 breakpoint_hit_catch_solib (const struct bp_location *bl,
8003                             const address_space *aspace,
8004                             CORE_ADDR bp_addr,
8005                             const struct target_waitstatus *ws)
8006 {
8007   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8008   struct breakpoint *other;
8009
8010   if (ws->kind == TARGET_WAITKIND_LOADED)
8011     return 1;
8012
8013   ALL_BREAKPOINTS (other)
8014   {
8015     struct bp_location *other_bl;
8016
8017     if (other == bl->owner)
8018       continue;
8019
8020     if (other->type != bp_shlib_event)
8021       continue;
8022
8023     if (self->pspace != NULL && other->pspace != self->pspace)
8024       continue;
8025
8026     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8027       {
8028         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8029           return 1;
8030       }
8031   }
8032
8033   return 0;
8034 }
8035
8036 static void
8037 check_status_catch_solib (struct bpstats *bs)
8038 {
8039   struct solib_catchpoint *self
8040     = (struct solib_catchpoint *) bs->breakpoint_at;
8041
8042   if (self->is_load)
8043     {
8044       for (so_list *iter : current_program_space->added_solibs)
8045         {
8046           if (!self->regex
8047               || self->compiled->exec (iter->so_name, 0, NULL, 0) == 0)
8048             return;
8049         }
8050     }
8051   else
8052     {
8053       for (const std::string &iter : current_program_space->deleted_solibs)
8054         {
8055           if (!self->regex
8056               || self->compiled->exec (iter.c_str (), 0, NULL, 0) == 0)
8057             return;
8058         }
8059     }
8060
8061   bs->stop = 0;
8062   bs->print_it = print_it_noop;
8063 }
8064
8065 static enum print_stop_action
8066 print_it_catch_solib (bpstat bs)
8067 {
8068   struct breakpoint *b = bs->breakpoint_at;
8069   struct ui_out *uiout = current_uiout;
8070
8071   annotate_catchpoint (b->number);
8072   maybe_print_thread_hit_breakpoint (uiout);
8073   if (b->disposition == disp_del)
8074     uiout->text ("Temporary catchpoint ");
8075   else
8076     uiout->text ("Catchpoint ");
8077   uiout->field_signed ("bkptno", b->number);
8078   uiout->text ("\n");
8079   if (uiout->is_mi_like_p ())
8080     uiout->field_string ("disp", bpdisp_text (b->disposition));
8081   print_solib_event (1);
8082   return PRINT_SRC_AND_LOC;
8083 }
8084
8085 static void
8086 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8087 {
8088   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8089   struct value_print_options opts;
8090   struct ui_out *uiout = current_uiout;
8091
8092   get_user_print_options (&opts);
8093   /* Field 4, the address, is omitted (which makes the columns not
8094      line up too nicely with the headers, but the effect is relatively
8095      readable).  */
8096   if (opts.addressprint)
8097     {
8098       annotate_field (4);
8099       uiout->field_skip ("addr");
8100     }
8101
8102   std::string msg;
8103   annotate_field (5);
8104   if (self->is_load)
8105     {
8106       if (self->regex)
8107         msg = string_printf (_("load of library matching %s"), self->regex);
8108       else
8109         msg = _("load of library");
8110     }
8111   else
8112     {
8113       if (self->regex)
8114         msg = string_printf (_("unload of library matching %s"), self->regex);
8115       else
8116         msg = _("unload of library");
8117     }
8118   uiout->field_string ("what", msg);
8119
8120   if (uiout->is_mi_like_p ())
8121     uiout->field_string ("catch-type", self->is_load ? "load" : "unload");
8122 }
8123
8124 static void
8125 print_mention_catch_solib (struct breakpoint *b)
8126 {
8127   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8128
8129   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8130                    self->is_load ? "load" : "unload");
8131 }
8132
8133 static void
8134 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8135 {
8136   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8137
8138   fprintf_unfiltered (fp, "%s %s",
8139                       b->disposition == disp_del ? "tcatch" : "catch",
8140                       self->is_load ? "load" : "unload");
8141   if (self->regex)
8142     fprintf_unfiltered (fp, " %s", self->regex);
8143   fprintf_unfiltered (fp, "\n");
8144 }
8145
8146 static struct breakpoint_ops catch_solib_breakpoint_ops;
8147
8148 /* See breakpoint.h.  */
8149
8150 void
8151 add_solib_catchpoint (const char *arg, bool is_load, bool is_temp, bool enabled)
8152 {
8153   struct gdbarch *gdbarch = get_current_arch ();
8154
8155   if (!arg)
8156     arg = "";
8157   arg = skip_spaces (arg);
8158
8159   std::unique_ptr<solib_catchpoint> c (new solib_catchpoint ());
8160
8161   if (*arg != '\0')
8162     {
8163       c->compiled.reset (new compiled_regex (arg, REG_NOSUB,
8164                                              _("Invalid regexp")));
8165       c->regex = xstrdup (arg);
8166     }
8167
8168   c->is_load = is_load;
8169   init_catchpoint (c.get (), gdbarch, is_temp, NULL,
8170                    &catch_solib_breakpoint_ops);
8171
8172   c->enable_state = enabled ? bp_enabled : bp_disabled;
8173
8174   install_breakpoint (0, std::move (c), 1);
8175 }
8176
8177 /* A helper function that does all the work for "catch load" and
8178    "catch unload".  */
8179
8180 static void
8181 catch_load_or_unload (const char *arg, int from_tty, int is_load,
8182                       struct cmd_list_element *command)
8183 {
8184   const int enabled = 1;
8185   bool temp = get_cmd_context (command) == CATCH_TEMPORARY;
8186
8187   add_solib_catchpoint (arg, is_load, temp, enabled);
8188 }
8189
8190 static void
8191 catch_load_command_1 (const char *arg, int from_tty,
8192                       struct cmd_list_element *command)
8193 {
8194   catch_load_or_unload (arg, from_tty, 1, command);
8195 }
8196
8197 static void
8198 catch_unload_command_1 (const char *arg, int from_tty,
8199                         struct cmd_list_element *command)
8200 {
8201   catch_load_or_unload (arg, from_tty, 0, command);
8202 }
8203
8204 /* See breakpoint.h.  */
8205
8206 void
8207 init_catchpoint (struct breakpoint *b,
8208                  struct gdbarch *gdbarch, bool temp,
8209                  const char *cond_string,
8210                  const struct breakpoint_ops *ops)
8211 {
8212   symtab_and_line sal;
8213   sal.pspace = current_program_space;
8214
8215   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8216
8217   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8218   b->disposition = temp ? disp_del : disp_donttouch;
8219 }
8220
8221 void
8222 install_breakpoint (int internal, std::unique_ptr<breakpoint> &&arg, int update_gll)
8223 {
8224   breakpoint *b = add_to_breakpoint_chain (std::move (arg));
8225   set_breakpoint_number (internal, b);
8226   if (is_tracepoint (b))
8227     set_tracepoint_count (breakpoint_count);
8228   if (!internal)
8229     mention (b);
8230   gdb::observers::breakpoint_created.notify (b);
8231
8232   if (update_gll)
8233     update_global_location_list (UGLL_MAY_INSERT);
8234 }
8235
8236 static void
8237 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8238                                     bool temp, const char *cond_string,
8239                                     const struct breakpoint_ops *ops)
8240 {
8241   std::unique_ptr<fork_catchpoint> c (new fork_catchpoint ());
8242
8243   init_catchpoint (c.get (), gdbarch, temp, cond_string, ops);
8244
8245   c->forked_inferior_pid = null_ptid;
8246
8247   install_breakpoint (0, std::move (c), 1);
8248 }
8249
8250 /* Exec catchpoints.  */
8251
8252 /* An instance of this type is used to represent an exec catchpoint.
8253    A breakpoint is really of this type iff its ops pointer points to
8254    CATCH_EXEC_BREAKPOINT_OPS.  */
8255
8256 struct exec_catchpoint : public breakpoint
8257 {
8258   ~exec_catchpoint () override;
8259
8260   /* Filename of a program whose exec triggered this catchpoint.
8261      This field is only valid immediately after this catchpoint has
8262      triggered.  */
8263   char *exec_pathname;
8264 };
8265
8266 /* Exec catchpoint destructor.  */
8267
8268 exec_catchpoint::~exec_catchpoint ()
8269 {
8270   xfree (this->exec_pathname);
8271 }
8272
8273 static int
8274 insert_catch_exec (struct bp_location *bl)
8275 {
8276   return target_insert_exec_catchpoint (inferior_ptid.pid ());
8277 }
8278
8279 static int
8280 remove_catch_exec (struct bp_location *bl, enum remove_bp_reason reason)
8281 {
8282   return target_remove_exec_catchpoint (inferior_ptid.pid ());
8283 }
8284
8285 static int
8286 breakpoint_hit_catch_exec (const struct bp_location *bl,
8287                            const address_space *aspace, CORE_ADDR bp_addr,
8288                            const struct target_waitstatus *ws)
8289 {
8290   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8291
8292   if (ws->kind != TARGET_WAITKIND_EXECD)
8293     return 0;
8294
8295   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8296   return 1;
8297 }
8298
8299 static enum print_stop_action
8300 print_it_catch_exec (bpstat bs)
8301 {
8302   struct ui_out *uiout = current_uiout;
8303   struct breakpoint *b = bs->breakpoint_at;
8304   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8305
8306   annotate_catchpoint (b->number);
8307   maybe_print_thread_hit_breakpoint (uiout);
8308   if (b->disposition == disp_del)
8309     uiout->text ("Temporary catchpoint ");
8310   else
8311     uiout->text ("Catchpoint ");
8312   if (uiout->is_mi_like_p ())
8313     {
8314       uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXEC));
8315       uiout->field_string ("disp", bpdisp_text (b->disposition));
8316     }
8317   uiout->field_signed ("bkptno", b->number);
8318   uiout->text (" (exec'd ");
8319   uiout->field_string ("new-exec", c->exec_pathname);
8320   uiout->text ("), ");
8321
8322   return PRINT_SRC_AND_LOC;
8323 }
8324
8325 static void
8326 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8327 {
8328   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8329   struct value_print_options opts;
8330   struct ui_out *uiout = current_uiout;
8331
8332   get_user_print_options (&opts);
8333
8334   /* Field 4, the address, is omitted (which makes the columns
8335      not line up too nicely with the headers, but the effect
8336      is relatively readable).  */
8337   if (opts.addressprint)
8338     uiout->field_skip ("addr");
8339   annotate_field (5);
8340   uiout->text ("exec");
8341   if (c->exec_pathname != NULL)
8342     {
8343       uiout->text (", program \"");
8344       uiout->field_string ("what", c->exec_pathname);
8345       uiout->text ("\" ");
8346     }
8347
8348   if (uiout->is_mi_like_p ())
8349     uiout->field_string ("catch-type", "exec");
8350 }
8351
8352 static void
8353 print_mention_catch_exec (struct breakpoint *b)
8354 {
8355   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8356 }
8357
8358 /* Implement the "print_recreate" breakpoint_ops method for exec
8359    catchpoints.  */
8360
8361 static void
8362 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8363 {
8364   fprintf_unfiltered (fp, "catch exec");
8365   print_recreate_thread (b, fp);
8366 }
8367
8368 static struct breakpoint_ops catch_exec_breakpoint_ops;
8369
8370 static int
8371 hw_breakpoint_used_count (void)
8372 {
8373   int i = 0;
8374   struct breakpoint *b;
8375   struct bp_location *bl;
8376
8377   ALL_BREAKPOINTS (b)
8378   {
8379     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8380       for (bl = b->loc; bl; bl = bl->next)
8381         {
8382           /* Special types of hardware breakpoints may use more than
8383              one register.  */
8384           i += b->ops->resources_needed (bl);
8385         }
8386   }
8387
8388   return i;
8389 }
8390
8391 /* Returns the resources B would use if it were a hardware
8392    watchpoint.  */
8393
8394 static int
8395 hw_watchpoint_use_count (struct breakpoint *b)
8396 {
8397   int i = 0;
8398   struct bp_location *bl;
8399
8400   if (!breakpoint_enabled (b))
8401     return 0;
8402
8403   for (bl = b->loc; bl; bl = bl->next)
8404     {
8405       /* Special types of hardware watchpoints may use more than
8406          one register.  */
8407       i += b->ops->resources_needed (bl);
8408     }
8409
8410   return i;
8411 }
8412
8413 /* Returns the sum the used resources of all hardware watchpoints of
8414    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8415    the sum of the used resources of all hardware watchpoints of other
8416    types _not_ TYPE.  */
8417
8418 static int
8419 hw_watchpoint_used_count_others (struct breakpoint *except,
8420                                  enum bptype type, int *other_type_used)
8421 {
8422   int i = 0;
8423   struct breakpoint *b;
8424
8425   *other_type_used = 0;
8426   ALL_BREAKPOINTS (b)
8427     {
8428       if (b == except)
8429         continue;
8430       if (!breakpoint_enabled (b))
8431         continue;
8432
8433       if (b->type == type)
8434         i += hw_watchpoint_use_count (b);
8435       else if (is_hardware_watchpoint (b))
8436         *other_type_used = 1;
8437     }
8438
8439   return i;
8440 }
8441
8442 void
8443 disable_watchpoints_before_interactive_call_start (void)
8444 {
8445   struct breakpoint *b;
8446
8447   ALL_BREAKPOINTS (b)
8448   {
8449     if (is_watchpoint (b) && breakpoint_enabled (b))
8450       {
8451         b->enable_state = bp_call_disabled;
8452         update_global_location_list (UGLL_DONT_INSERT);
8453       }
8454   }
8455 }
8456
8457 void
8458 enable_watchpoints_after_interactive_call_stop (void)
8459 {
8460   struct breakpoint *b;
8461
8462   ALL_BREAKPOINTS (b)
8463   {
8464     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8465       {
8466         b->enable_state = bp_enabled;
8467         update_global_location_list (UGLL_MAY_INSERT);
8468       }
8469   }
8470 }
8471
8472 void
8473 disable_breakpoints_before_startup (void)
8474 {
8475   current_program_space->executing_startup = 1;
8476   update_global_location_list (UGLL_DONT_INSERT);
8477 }
8478
8479 void
8480 enable_breakpoints_after_startup (void)
8481 {
8482   current_program_space->executing_startup = 0;
8483   breakpoint_re_set ();
8484 }
8485
8486 /* Create a new single-step breakpoint for thread THREAD, with no
8487    locations.  */
8488
8489 static struct breakpoint *
8490 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
8491 {
8492   std::unique_ptr<breakpoint> b (new breakpoint ());
8493
8494   init_raw_breakpoint_without_location (b.get (), gdbarch, bp_single_step,
8495                                         &momentary_breakpoint_ops);
8496
8497   b->disposition = disp_donttouch;
8498   b->frame_id = null_frame_id;
8499
8500   b->thread = thread;
8501   gdb_assert (b->thread != 0);
8502
8503   return add_to_breakpoint_chain (std::move (b));
8504 }
8505
8506 /* Set a momentary breakpoint of type TYPE at address specified by
8507    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
8508    frame.  */
8509
8510 breakpoint_up
8511 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8512                           struct frame_id frame_id, enum bptype type)
8513 {
8514   struct breakpoint *b;
8515
8516   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8517      tail-called one.  */
8518   gdb_assert (!frame_id_artificial_p (frame_id));
8519
8520   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8521   b->enable_state = bp_enabled;
8522   b->disposition = disp_donttouch;
8523   b->frame_id = frame_id;
8524
8525   b->thread = inferior_thread ()->global_num;
8526
8527   update_global_location_list_nothrow (UGLL_MAY_INSERT);
8528
8529   return breakpoint_up (b);
8530 }
8531
8532 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8533    The new breakpoint will have type TYPE, use OPS as its
8534    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
8535
8536 static struct breakpoint *
8537 momentary_breakpoint_from_master (struct breakpoint *orig,
8538                                   enum bptype type,
8539                                   const struct breakpoint_ops *ops,
8540                                   int loc_enabled)
8541 {
8542   struct breakpoint *copy;
8543
8544   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8545   copy->loc = allocate_bp_location (copy);
8546   set_breakpoint_location_function (copy->loc);
8547
8548   copy->loc->gdbarch = orig->loc->gdbarch;
8549   copy->loc->requested_address = orig->loc->requested_address;
8550   copy->loc->address = orig->loc->address;
8551   copy->loc->section = orig->loc->section;
8552   copy->loc->pspace = orig->loc->pspace;
8553   copy->loc->probe = orig->loc->probe;
8554   copy->loc->line_number = orig->loc->line_number;
8555   copy->loc->symtab = orig->loc->symtab;
8556   copy->loc->enabled = loc_enabled;
8557   copy->frame_id = orig->frame_id;
8558   copy->thread = orig->thread;
8559   copy->pspace = orig->pspace;
8560
8561   copy->enable_state = bp_enabled;
8562   copy->disposition = disp_donttouch;
8563   copy->number = internal_breakpoint_number--;
8564
8565   update_global_location_list_nothrow (UGLL_DONT_INSERT);
8566   return copy;
8567 }
8568
8569 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8570    ORIG is NULL.  */
8571
8572 struct breakpoint *
8573 clone_momentary_breakpoint (struct breakpoint *orig)
8574 {
8575   /* If there's nothing to clone, then return nothing.  */
8576   if (orig == NULL)
8577     return NULL;
8578
8579   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
8580 }
8581
8582 breakpoint_up
8583 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8584                                 enum bptype type)
8585 {
8586   struct symtab_and_line sal;
8587
8588   sal = find_pc_line (pc, 0);
8589   sal.pc = pc;
8590   sal.section = find_pc_overlay (pc);
8591   sal.explicit_pc = 1;
8592
8593   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8594 }
8595 \f
8596
8597 /* Tell the user we have just set a breakpoint B.  */
8598
8599 static void
8600 mention (struct breakpoint *b)
8601 {
8602   b->ops->print_mention (b);
8603   current_uiout->text ("\n");
8604 }
8605 \f
8606
8607 static bool bp_loc_is_permanent (struct bp_location *loc);
8608
8609 /* Handle "set breakpoint auto-hw on".
8610
8611    If the explicitly specified breakpoint type is not hardware
8612    breakpoint, check the memory map to see whether the breakpoint
8613    address is in read-only memory.
8614
8615    - location type is not hardware breakpoint, memory is read-only.
8616    We change the type of the location to hardware breakpoint.
8617
8618    - location type is hardware breakpoint, memory is read-write.  This
8619    means we've previously made the location hardware one, but then the
8620    memory map changed, so we undo.
8621 */
8622
8623 static void
8624 handle_automatic_hardware_breakpoints (bp_location *bl)
8625 {
8626   if (automatic_hardware_breakpoints
8627       && bl->owner->type != bp_hardware_breakpoint
8628       && (bl->loc_type == bp_loc_software_breakpoint
8629           || bl->loc_type == bp_loc_hardware_breakpoint))
8630     {
8631       /* When breakpoints are removed, remove_breakpoints will use
8632          location types we've just set here, the only possible problem
8633          is that memory map has changed during running program, but
8634          it's not going to work anyway with current gdb.  */
8635       mem_region *mr = lookup_mem_region (bl->address);
8636
8637       if (mr != nullptr)
8638         {
8639           enum bp_loc_type new_type;
8640
8641           if (mr->attrib.mode != MEM_RW)
8642             new_type = bp_loc_hardware_breakpoint;
8643           else
8644             new_type = bp_loc_software_breakpoint;
8645
8646           if (new_type != bl->loc_type)
8647             {
8648               static bool said = false;
8649
8650               bl->loc_type = new_type;
8651               if (!said)
8652                 {
8653                   fprintf_filtered (gdb_stdout,
8654                                     _("Note: automatically using "
8655                                       "hardware breakpoints for "
8656                                       "read-only addresses.\n"));
8657                   said = true;
8658                 }
8659             }
8660         }
8661     }
8662 }
8663
8664 static struct bp_location *
8665 add_location_to_breakpoint (struct breakpoint *b,
8666                             const struct symtab_and_line *sal)
8667 {
8668   struct bp_location *loc, **tmp;
8669   CORE_ADDR adjusted_address;
8670   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8671
8672   if (loc_gdbarch == NULL)
8673     loc_gdbarch = b->gdbarch;
8674
8675   /* Adjust the breakpoint's address prior to allocating a location.
8676      Once we call allocate_bp_location(), that mostly uninitialized
8677      location will be placed on the location chain.  Adjustment of the
8678      breakpoint may cause target_read_memory() to be called and we do
8679      not want its scan of the location chain to find a breakpoint and
8680      location that's only been partially initialized.  */
8681   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8682                                                 sal->pc, b->type);
8683
8684   /* Sort the locations by their ADDRESS.  */
8685   loc = allocate_bp_location (b);
8686   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8687        tmp = &((*tmp)->next))
8688     ;
8689   loc->next = *tmp;
8690   *tmp = loc;
8691
8692   loc->requested_address = sal->pc;
8693   loc->address = adjusted_address;
8694   loc->pspace = sal->pspace;
8695   loc->probe.prob = sal->prob;
8696   loc->probe.objfile = sal->objfile;
8697   gdb_assert (loc->pspace != NULL);
8698   loc->section = sal->section;
8699   loc->gdbarch = loc_gdbarch;
8700   loc->line_number = sal->line;
8701   loc->symtab = sal->symtab;
8702   loc->symbol = sal->symbol;
8703   loc->msymbol = sal->msymbol;
8704   loc->objfile = sal->objfile;
8705
8706   set_breakpoint_location_function (loc);
8707
8708   /* While by definition, permanent breakpoints are already present in the
8709      code, we don't mark the location as inserted.  Normally one would expect
8710      that GDB could rely on that breakpoint instruction to stop the program,
8711      thus removing the need to insert its own breakpoint, except that executing
8712      the breakpoint instruction can kill the target instead of reporting a
8713      SIGTRAP.  E.g., on SPARC, when interrupts are disabled, executing the
8714      instruction resets the CPU, so QEMU 2.0.0 for SPARC correspondingly dies
8715      with "Trap 0x02 while interrupts disabled, Error state".  Letting the
8716      breakpoint be inserted normally results in QEMU knowing about the GDB
8717      breakpoint, and thus trap before the breakpoint instruction is executed.
8718      (If GDB later needs to continue execution past the permanent breakpoint,
8719      it manually increments the PC, thus avoiding executing the breakpoint
8720      instruction.)  */
8721   if (bp_loc_is_permanent (loc))
8722     loc->permanent = 1;
8723
8724   return loc;
8725 }
8726 \f
8727
8728 /* Return true if LOC is pointing to a permanent breakpoint,
8729    return false otherwise.  */
8730
8731 static bool
8732 bp_loc_is_permanent (struct bp_location *loc)
8733 {
8734   gdb_assert (loc != NULL);
8735
8736   /* If we have a non-breakpoint-backed catchpoint or a software
8737      watchpoint, just return 0.  We should not attempt to read from
8738      the addresses the locations of these breakpoint types point to.
8739      gdbarch_program_breakpoint_here_p, below, will attempt to read
8740      memory.  */
8741   if (!bl_address_is_meaningful (loc))
8742     return false;
8743
8744   scoped_restore_current_pspace_and_thread restore_pspace_thread;
8745   switch_to_program_space_and_thread (loc->pspace);
8746   return gdbarch_program_breakpoint_here_p (loc->gdbarch, loc->address);
8747 }
8748
8749 /* Build a command list for the dprintf corresponding to the current
8750    settings of the dprintf style options.  */
8751
8752 static void
8753 update_dprintf_command_list (struct breakpoint *b)
8754 {
8755   char *dprintf_args = b->extra_string;
8756   char *printf_line = NULL;
8757
8758   if (!dprintf_args)
8759     return;
8760
8761   dprintf_args = skip_spaces (dprintf_args);
8762
8763   /* Allow a comma, as it may have terminated a location, but don't
8764      insist on it.  */
8765   if (*dprintf_args == ',')
8766     ++dprintf_args;
8767   dprintf_args = skip_spaces (dprintf_args);
8768
8769   if (*dprintf_args != '"')
8770     error (_("Bad format string, missing '\"'."));
8771
8772   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8773     printf_line = xstrprintf ("printf %s", dprintf_args);
8774   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8775     {
8776       if (!dprintf_function)
8777         error (_("No function supplied for dprintf call"));
8778
8779       if (dprintf_channel && strlen (dprintf_channel) > 0)
8780         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8781                                   dprintf_function,
8782                                   dprintf_channel,
8783                                   dprintf_args);
8784       else
8785         printf_line = xstrprintf ("call (void) %s (%s)",
8786                                   dprintf_function,
8787                                   dprintf_args);
8788     }
8789   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8790     {
8791       if (target_can_run_breakpoint_commands ())
8792         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8793       else
8794         {
8795           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8796           printf_line = xstrprintf ("printf %s", dprintf_args);
8797         }
8798     }
8799   else
8800     internal_error (__FILE__, __LINE__,
8801                     _("Invalid dprintf style."));
8802
8803   gdb_assert (printf_line != NULL);
8804
8805   /* Manufacture a printf sequence.  */
8806   struct command_line *printf_cmd_line
8807     = new struct command_line (simple_control, printf_line);
8808   breakpoint_set_commands (b, counted_command_line (printf_cmd_line,
8809                                                     command_lines_deleter ()));
8810 }
8811
8812 /* Update all dprintf commands, making their command lists reflect
8813    current style settings.  */
8814
8815 static void
8816 update_dprintf_commands (const char *args, int from_tty,
8817                          struct cmd_list_element *c)
8818 {
8819   struct breakpoint *b;
8820
8821   ALL_BREAKPOINTS (b)
8822     {
8823       if (b->type == bp_dprintf)
8824         update_dprintf_command_list (b);
8825     }
8826 }
8827
8828 /* Create a breakpoint with SAL as location.  Use LOCATION
8829    as a description of the location, and COND_STRING
8830    as condition expression.  If LOCATION is NULL then create an
8831    "address location" from the address in the SAL.  */
8832
8833 static void
8834 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8835                      gdb::array_view<const symtab_and_line> sals,
8836                      event_location_up &&location,
8837                      gdb::unique_xmalloc_ptr<char> filter,
8838                      gdb::unique_xmalloc_ptr<char> cond_string,
8839                      gdb::unique_xmalloc_ptr<char> extra_string,
8840                      enum bptype type, enum bpdisp disposition,
8841                      int thread, int task, int ignore_count,
8842                      const struct breakpoint_ops *ops, int from_tty,
8843                      int enabled, int internal, unsigned flags,
8844                      int display_canonical)
8845 {
8846   int i;
8847
8848   if (type == bp_hardware_breakpoint)
8849     {
8850       int target_resources_ok;
8851
8852       i = hw_breakpoint_used_count ();
8853       target_resources_ok =
8854         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8855                                             i + 1, 0);
8856       if (target_resources_ok == 0)
8857         error (_("No hardware breakpoint support in the target."));
8858       else if (target_resources_ok < 0)
8859         error (_("Hardware breakpoints used exceeds limit."));
8860     }
8861
8862   gdb_assert (!sals.empty ());
8863
8864   for (const auto &sal : sals)
8865     {
8866       struct bp_location *loc;
8867
8868       if (from_tty)
8869         {
8870           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8871           if (!loc_gdbarch)
8872             loc_gdbarch = gdbarch;
8873
8874           describe_other_breakpoints (loc_gdbarch,
8875                                       sal.pspace, sal.pc, sal.section, thread);
8876         }
8877
8878       if (&sal == &sals[0])
8879         {
8880           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8881           b->thread = thread;
8882           b->task = task;
8883
8884           b->cond_string = cond_string.release ();
8885           b->extra_string = extra_string.release ();
8886           b->ignore_count = ignore_count;
8887           b->enable_state = enabled ? bp_enabled : bp_disabled;
8888           b->disposition = disposition;
8889
8890           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8891             b->loc->inserted = 1;
8892
8893           if (type == bp_static_tracepoint)
8894             {
8895               struct tracepoint *t = (struct tracepoint *) b;
8896               struct static_tracepoint_marker marker;
8897
8898               if (strace_marker_p (b))
8899                 {
8900                   /* We already know the marker exists, otherwise, we
8901                      wouldn't see a sal for it.  */
8902                   const char *p
8903                     = &event_location_to_string (b->location.get ())[3];
8904                   const char *endp;
8905
8906                   p = skip_spaces (p);
8907
8908                   endp = skip_to_space (p);
8909
8910                   t->static_trace_marker_id.assign (p, endp - p);
8911
8912                   printf_filtered (_("Probed static tracepoint "
8913                                      "marker \"%s\"\n"),
8914                                    t->static_trace_marker_id.c_str ());
8915                 }
8916               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8917                 {
8918                   t->static_trace_marker_id = std::move (marker.str_id);
8919
8920                   printf_filtered (_("Probed static tracepoint "
8921                                      "marker \"%s\"\n"),
8922                                    t->static_trace_marker_id.c_str ());
8923                 }
8924               else
8925                 warning (_("Couldn't determine the static "
8926                            "tracepoint marker to probe"));
8927             }
8928
8929           loc = b->loc;
8930         }
8931       else
8932         {
8933           loc = add_location_to_breakpoint (b, &sal);
8934           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8935             loc->inserted = 1;
8936         }
8937
8938       /* Do not set breakpoint locations conditions yet.  As locations
8939          are inserted, they get sorted based on their addresses.  Let
8940          the list stabilize to have reliable location numbers.  */
8941
8942       /* Dynamic printf requires and uses additional arguments on the
8943          command line, otherwise it's an error.  */
8944       if (type == bp_dprintf)
8945         {
8946           if (b->extra_string)
8947             update_dprintf_command_list (b);
8948           else
8949             error (_("Format string required"));
8950         }
8951       else if (b->extra_string)
8952         error (_("Garbage '%s' at end of command"), b->extra_string);
8953     }
8954
8955
8956   /* The order of the locations is now stable.  Set the location
8957      condition using the location's number.  */
8958   int loc_num = 1;
8959   for (bp_location *loc = b->loc; loc != nullptr; loc = loc->next)
8960     {
8961       if (b->cond_string != nullptr)
8962         set_breakpoint_location_condition (b->cond_string, loc, b->number,
8963                                            loc_num);
8964
8965       ++loc_num;
8966     }
8967
8968   b->display_canonical = display_canonical;
8969   if (location != NULL)
8970     b->location = std::move (location);
8971   else
8972     b->location = new_address_location (b->loc->address, NULL, 0);
8973   b->filter = std::move (filter);
8974 }
8975
8976 static void
8977 create_breakpoint_sal (struct gdbarch *gdbarch,
8978                        gdb::array_view<const symtab_and_line> sals,
8979                        event_location_up &&location,
8980                        gdb::unique_xmalloc_ptr<char> filter,
8981                        gdb::unique_xmalloc_ptr<char> cond_string,
8982                        gdb::unique_xmalloc_ptr<char> extra_string,
8983                        enum bptype type, enum bpdisp disposition,
8984                        int thread, int task, int ignore_count,
8985                        const struct breakpoint_ops *ops, int from_tty,
8986                        int enabled, int internal, unsigned flags,
8987                        int display_canonical)
8988 {
8989   std::unique_ptr<breakpoint> b = new_breakpoint_from_type (type);
8990
8991   init_breakpoint_sal (b.get (), gdbarch,
8992                        sals, std::move (location),
8993                        std::move (filter),
8994                        std::move (cond_string),
8995                        std::move (extra_string),
8996                        type, disposition,
8997                        thread, task, ignore_count,
8998                        ops, from_tty,
8999                        enabled, internal, flags,
9000                        display_canonical);
9001
9002   install_breakpoint (internal, std::move (b), 0);
9003 }
9004
9005 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9006    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9007    value.  COND_STRING, if not NULL, specified the condition to be
9008    used for all breakpoints.  Essentially the only case where
9009    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9010    function.  In that case, it's still not possible to specify
9011    separate conditions for different overloaded functions, so
9012    we take just a single condition string.
9013    
9014    NOTE: If the function succeeds, the caller is expected to cleanup
9015    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9016    array contents).  If the function fails (error() is called), the
9017    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9018    COND and SALS arrays and each of those arrays contents.  */
9019
9020 static void
9021 create_breakpoints_sal (struct gdbarch *gdbarch,
9022                         struct linespec_result *canonical,
9023                         gdb::unique_xmalloc_ptr<char> cond_string,
9024                         gdb::unique_xmalloc_ptr<char> extra_string,
9025                         enum bptype type, enum bpdisp disposition,
9026                         int thread, int task, int ignore_count,
9027                         const struct breakpoint_ops *ops, int from_tty,
9028                         int enabled, int internal, unsigned flags)
9029 {
9030   if (canonical->pre_expanded)
9031     gdb_assert (canonical->lsals.size () == 1);
9032
9033   for (const auto &lsal : canonical->lsals)
9034     {
9035       /* Note that 'location' can be NULL in the case of a plain
9036          'break', without arguments.  */
9037       event_location_up location
9038         = (canonical->location != NULL
9039            ? copy_event_location (canonical->location.get ()) : NULL);
9040       gdb::unique_xmalloc_ptr<char> filter_string
9041         (lsal.canonical != NULL ? xstrdup (lsal.canonical) : NULL);
9042
9043       create_breakpoint_sal (gdbarch, lsal.sals,
9044                              std::move (location),
9045                              std::move (filter_string),
9046                              std::move (cond_string),
9047                              std::move (extra_string),
9048                              type, disposition,
9049                              thread, task, ignore_count, ops,
9050                              from_tty, enabled, internal, flags,
9051                              canonical->special_display);
9052     }
9053 }
9054
9055 /* Parse LOCATION which is assumed to be a SAL specification possibly
9056    followed by conditionals.  On return, SALS contains an array of SAL
9057    addresses found.  LOCATION points to the end of the SAL (for
9058    linespec locations).
9059
9060    The array and the line spec strings are allocated on the heap, it is
9061    the caller's responsibility to free them.  */
9062
9063 static void
9064 parse_breakpoint_sals (struct event_location *location,
9065                        struct linespec_result *canonical)
9066 {
9067   struct symtab_and_line cursal;
9068
9069   if (event_location_type (location) == LINESPEC_LOCATION)
9070     {
9071       const char *spec = get_linespec_location (location)->spec_string;
9072
9073       if (spec == NULL)
9074         {
9075           /* The last displayed codepoint, if it's valid, is our default
9076              breakpoint address.  */
9077           if (last_displayed_sal_is_valid ())
9078             {
9079               /* Set sal's pspace, pc, symtab, and line to the values
9080                  corresponding to the last call to print_frame_info.
9081                  Be sure to reinitialize LINE with NOTCURRENT == 0
9082                  as the breakpoint line number is inappropriate otherwise.
9083                  find_pc_line would adjust PC, re-set it back.  */
9084               symtab_and_line sal = get_last_displayed_sal ();
9085               CORE_ADDR pc = sal.pc;
9086
9087               sal = find_pc_line (pc, 0);
9088
9089               /* "break" without arguments is equivalent to "break *PC"
9090                  where PC is the last displayed codepoint's address.  So
9091                  make sure to set sal.explicit_pc to prevent GDB from
9092                  trying to expand the list of sals to include all other
9093                  instances with the same symtab and line.  */
9094               sal.pc = pc;
9095               sal.explicit_pc = 1;
9096
9097               struct linespec_sals lsal;
9098               lsal.sals = {sal};
9099               lsal.canonical = NULL;
9100
9101               canonical->lsals.push_back (std::move (lsal));
9102               return;
9103             }
9104           else
9105             error (_("No default breakpoint address now."));
9106         }
9107     }
9108
9109   /* Force almost all breakpoints to be in terms of the
9110      current_source_symtab (which is decode_line_1's default).
9111      This should produce the results we want almost all of the
9112      time while leaving default_breakpoint_* alone.
9113
9114      ObjC: However, don't match an Objective-C method name which
9115      may have a '+' or '-' succeeded by a '['.  */
9116   cursal = get_current_source_symtab_and_line ();
9117   if (last_displayed_sal_is_valid ())
9118     {
9119       const char *spec = NULL;
9120
9121       if (event_location_type (location) == LINESPEC_LOCATION)
9122         spec = get_linespec_location (location)->spec_string;
9123
9124       if (!cursal.symtab
9125           || (spec != NULL
9126               && strchr ("+-", spec[0]) != NULL
9127               && spec[1] != '['))
9128         {
9129           decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9130                             get_last_displayed_symtab (),
9131                             get_last_displayed_line (),
9132                             canonical, NULL, NULL);
9133           return;
9134         }
9135     }
9136
9137   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, NULL,
9138                     cursal.symtab, cursal.line, canonical, NULL, NULL);
9139 }
9140
9141
9142 /* Convert each SAL into a real PC.  Verify that the PC can be
9143    inserted as a breakpoint.  If it can't throw an error.  */
9144
9145 static void
9146 breakpoint_sals_to_pc (std::vector<symtab_and_line> &sals)
9147 {    
9148   for (auto &sal : sals)
9149     resolve_sal_pc (&sal);
9150 }
9151
9152 /* Fast tracepoints may have restrictions on valid locations.  For
9153    instance, a fast tracepoint using a jump instead of a trap will
9154    likely have to overwrite more bytes than a trap would, and so can
9155    only be placed where the instruction is longer than the jump, or a
9156    multi-instruction sequence does not have a jump into the middle of
9157    it, etc.  */
9158
9159 static void
9160 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9161                             gdb::array_view<const symtab_and_line> sals)
9162 {
9163   for (const auto &sal : sals)
9164     {
9165       struct gdbarch *sarch;
9166
9167       sarch = get_sal_arch (sal);
9168       /* We fall back to GDBARCH if there is no architecture
9169          associated with SAL.  */
9170       if (sarch == NULL)
9171         sarch = gdbarch;
9172       std::string msg;
9173       if (!gdbarch_fast_tracepoint_valid_at (sarch, sal.pc, &msg))
9174         error (_("May not have a fast tracepoint at %s%s"),
9175                paddress (sarch, sal.pc), msg.c_str ());
9176     }
9177 }
9178
9179 /* Given TOK, a string specification of condition and thread, as
9180    accepted by the 'break' command, extract the condition
9181    string and thread number and set *COND_STRING and *THREAD.
9182    PC identifies the context at which the condition should be parsed.
9183    If no condition is found, *COND_STRING is set to NULL.
9184    If no thread is found, *THREAD is set to -1.  */
9185
9186 static void
9187 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9188                            char **cond_string, int *thread, int *task,
9189                            char **rest)
9190 {
9191   *cond_string = NULL;
9192   *thread = -1;
9193   *task = 0;
9194   *rest = NULL;
9195   bool force = false;
9196
9197   while (tok && *tok)
9198     {
9199       const char *end_tok;
9200       int toklen;
9201       const char *cond_start = NULL;
9202       const char *cond_end = NULL;
9203
9204       tok = skip_spaces (tok);
9205
9206       if ((*tok == '"' || *tok == ',') && rest)
9207         {
9208           *rest = savestring (tok, strlen (tok));
9209           return;
9210         }
9211
9212       end_tok = skip_to_space (tok);
9213
9214       toklen = end_tok - tok;
9215
9216       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9217         {
9218           tok = cond_start = end_tok + 1;
9219           try
9220             {
9221               parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9222             }
9223           catch (const gdb_exception_error &)
9224             {
9225               if (!force)
9226                 throw;
9227               else
9228                 tok = tok + strlen (tok);
9229             }
9230           cond_end = tok;
9231           *cond_string = savestring (cond_start, cond_end - cond_start);
9232         }
9233       else if (toklen >= 1 && strncmp (tok, "-force-condition", toklen) == 0)
9234         {
9235           tok = tok + toklen;
9236           force = true;
9237         }
9238       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9239         {
9240           const char *tmptok;
9241           struct thread_info *thr;
9242
9243           tok = end_tok + 1;
9244           thr = parse_thread_id (tok, &tmptok);
9245           if (tok == tmptok)
9246             error (_("Junk after thread keyword."));
9247           *thread = thr->global_num;
9248           tok = tmptok;
9249         }
9250       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9251         {
9252           char *tmptok;
9253
9254           tok = end_tok + 1;
9255           *task = strtol (tok, &tmptok, 0);
9256           if (tok == tmptok)
9257             error (_("Junk after task keyword."));
9258           if (!valid_task_id (*task))
9259             error (_("Unknown task %d."), *task);
9260           tok = tmptok;
9261         }
9262       else if (rest)
9263         {
9264           *rest = savestring (tok, strlen (tok));
9265           return;
9266         }
9267       else
9268         error (_("Junk at end of arguments."));
9269     }
9270 }
9271
9272 /* Call 'find_condition_and_thread' for each sal in SALS until a parse
9273    succeeds.  The parsed values are written to COND_STRING, THREAD,
9274    TASK, and REST.  See the comment of 'find_condition_and_thread'
9275    for the description of these parameters and INPUT.  */
9276
9277 static void
9278 find_condition_and_thread_for_sals (const std::vector<symtab_and_line> &sals,
9279                                     const char *input, char **cond_string,
9280                                     int *thread, int *task, char **rest)
9281 {
9282   int num_failures = 0;
9283   for (auto &sal : sals)
9284     {
9285       char *cond = nullptr;
9286       int thread_id = 0;
9287       int task_id = 0;
9288       char *remaining = nullptr;
9289
9290       /* Here we want to parse 'arg' to separate condition from thread
9291          number.  But because parsing happens in a context and the
9292          contexts of sals might be different, try each until there is
9293          success.  Finding one successful parse is sufficient for our
9294          goal.  When setting the breakpoint we'll re-parse the
9295          condition in the context of each sal.  */
9296       try
9297         {
9298           find_condition_and_thread (input, sal.pc, &cond, &thread_id,
9299                                      &task_id, &remaining);
9300           *cond_string = cond;
9301           *thread = thread_id;
9302           *task = task_id;
9303           *rest = remaining;
9304           break;
9305         }
9306       catch (const gdb_exception_error &e)
9307         {
9308           num_failures++;
9309           /* If no sal remains, do not continue.  */
9310           if (num_failures == sals.size ())
9311             throw;
9312         }
9313     }
9314 }
9315
9316 /* Decode a static tracepoint marker spec.  */
9317
9318 static std::vector<symtab_and_line>
9319 decode_static_tracepoint_spec (const char **arg_p)
9320 {
9321   const char *p = &(*arg_p)[3];
9322   const char *endp;
9323
9324   p = skip_spaces (p);
9325
9326   endp = skip_to_space (p);
9327
9328   std::string marker_str (p, endp - p);
9329
9330   std::vector<static_tracepoint_marker> markers
9331     = target_static_tracepoint_markers_by_strid (marker_str.c_str ());
9332   if (markers.empty ())
9333     error (_("No known static tracepoint marker named %s"),
9334            marker_str.c_str ());
9335
9336   std::vector<symtab_and_line> sals;
9337   sals.reserve (markers.size ());
9338
9339   for (const static_tracepoint_marker &marker : markers)
9340     {
9341       symtab_and_line sal = find_pc_line (marker.address, 0);
9342       sal.pc = marker.address;
9343       sals.push_back (sal);
9344    }
9345
9346   *arg_p = endp;
9347   return sals;
9348 }
9349
9350 /* Returns the breakpoint ops appropriate for use with with LOCATION_TYPE and
9351    according to IS_TRACEPOINT.  */
9352
9353 static const struct breakpoint_ops *
9354 breakpoint_ops_for_event_location_type (enum event_location_type location_type,
9355                                         bool is_tracepoint)
9356 {
9357   if (is_tracepoint)
9358     {
9359       if (location_type == PROBE_LOCATION)
9360         return &tracepoint_probe_breakpoint_ops;
9361       else
9362         return &tracepoint_breakpoint_ops;
9363     }
9364   else
9365     {
9366       if (location_type == PROBE_LOCATION)
9367         return &bkpt_probe_breakpoint_ops;
9368       else
9369         return &bkpt_breakpoint_ops;
9370     }
9371 }
9372
9373 /* See breakpoint.h.  */
9374
9375 const struct breakpoint_ops *
9376 breakpoint_ops_for_event_location (const struct event_location *location,
9377                                    bool is_tracepoint)
9378 {
9379   if (location != nullptr)
9380     return breakpoint_ops_for_event_location_type
9381       (event_location_type (location), is_tracepoint);
9382   return is_tracepoint ? &tracepoint_breakpoint_ops : &bkpt_breakpoint_ops;
9383 }
9384
9385 /* See breakpoint.h.  */
9386
9387 int
9388 create_breakpoint (struct gdbarch *gdbarch,
9389                    struct event_location *location,
9390                    const char *cond_string,
9391                    int thread, const char *extra_string,
9392                    int parse_extra,
9393                    int tempflag, enum bptype type_wanted,
9394                    int ignore_count,
9395                    enum auto_boolean pending_break_support,
9396                    const struct breakpoint_ops *ops,
9397                    int from_tty, int enabled, int internal,
9398                    unsigned flags)
9399 {
9400   struct linespec_result canonical;
9401   int pending = 0;
9402   int task = 0;
9403   int prev_bkpt_count = breakpoint_count;
9404
9405   gdb_assert (ops != NULL);
9406
9407   /* If extra_string isn't useful, set it to NULL.  */
9408   if (extra_string != NULL && *extra_string == '\0')
9409     extra_string = NULL;
9410
9411   try
9412     {
9413       ops->create_sals_from_location (location, &canonical, type_wanted);
9414     }
9415   catch (const gdb_exception_error &e)
9416     {
9417       /* If caller is interested in rc value from parse, set
9418          value.  */
9419       if (e.error == NOT_FOUND_ERROR)
9420         {
9421           /* If pending breakpoint support is turned off, throw
9422              error.  */
9423
9424           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9425             throw;
9426
9427           exception_print (gdb_stderr, e);
9428
9429           /* If pending breakpoint support is auto query and the user
9430              selects no, then simply return the error code.  */
9431           if (pending_break_support == AUTO_BOOLEAN_AUTO
9432               && !nquery (_("Make %s pending on future shared library load? "),
9433                           bptype_string (type_wanted)))
9434             return 0;
9435
9436           /* At this point, either the user was queried about setting
9437              a pending breakpoint and selected yes, or pending
9438              breakpoint behavior is on and thus a pending breakpoint
9439              is defaulted on behalf of the user.  */
9440           pending = 1;
9441         }
9442       else
9443         throw;
9444     }
9445
9446   if (!pending && canonical.lsals.empty ())
9447     return 0;
9448
9449   /* Resolve all line numbers to PC's and verify that the addresses
9450      are ok for the target.  */
9451   if (!pending)
9452     {
9453       for (auto &lsal : canonical.lsals)
9454         breakpoint_sals_to_pc (lsal.sals);
9455     }
9456
9457   /* Fast tracepoints may have additional restrictions on location.  */
9458   if (!pending && type_wanted == bp_fast_tracepoint)
9459     {
9460       for (const auto &lsal : canonical.lsals)
9461         check_fast_tracepoint_sals (gdbarch, lsal.sals);
9462     }
9463
9464   /* Verify that condition can be parsed, before setting any
9465      breakpoints.  Allocate a separate condition expression for each
9466      breakpoint.  */
9467   if (!pending)
9468     {
9469       gdb::unique_xmalloc_ptr<char> cond_string_copy;
9470       gdb::unique_xmalloc_ptr<char> extra_string_copy;
9471
9472       if (parse_extra)
9473         {
9474           char *rest;
9475           char *cond;
9476
9477           const linespec_sals &lsal = canonical.lsals[0];
9478
9479           find_condition_and_thread_for_sals (lsal.sals, extra_string,
9480                                               &cond, &thread, &task, &rest);
9481           cond_string_copy.reset (cond);
9482           extra_string_copy.reset (rest);
9483         }
9484       else
9485         {
9486           if (type_wanted != bp_dprintf
9487               && extra_string != NULL && *extra_string != '\0')
9488                 error (_("Garbage '%s' at end of location"), extra_string);
9489
9490           /* Create a private copy of condition string.  */
9491           if (cond_string)
9492             cond_string_copy.reset (xstrdup (cond_string));
9493           /* Create a private copy of any extra string.  */
9494           if (extra_string)
9495             extra_string_copy.reset (xstrdup (extra_string));
9496         }
9497
9498       ops->create_breakpoints_sal (gdbarch, &canonical,
9499                                    std::move (cond_string_copy),
9500                                    std::move (extra_string_copy),
9501                                    type_wanted,
9502                                    tempflag ? disp_del : disp_donttouch,
9503                                    thread, task, ignore_count, ops,
9504                                    from_tty, enabled, internal, flags);
9505     }
9506   else
9507     {
9508       std::unique_ptr <breakpoint> b = new_breakpoint_from_type (type_wanted);
9509
9510       init_raw_breakpoint_without_location (b.get (), gdbarch, type_wanted, ops);
9511       b->location = copy_event_location (location);
9512
9513       if (parse_extra)
9514         b->cond_string = NULL;
9515       else
9516         {
9517           /* Create a private copy of condition string.  */
9518           b->cond_string = cond_string != NULL ? xstrdup (cond_string) : NULL;
9519           b->thread = thread;
9520         }
9521
9522       /* Create a private copy of any extra string.  */
9523       b->extra_string = extra_string != NULL ? xstrdup (extra_string) : NULL;
9524       b->ignore_count = ignore_count;
9525       b->disposition = tempflag ? disp_del : disp_donttouch;
9526       b->condition_not_parsed = 1;
9527       b->enable_state = enabled ? bp_enabled : bp_disabled;
9528       if ((type_wanted != bp_breakpoint
9529            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9530         b->pspace = current_program_space;
9531
9532       install_breakpoint (internal, std::move (b), 0);
9533     }
9534   
9535   if (canonical.lsals.size () > 1)
9536     {
9537       warning (_("Multiple breakpoints were set.\nUse the "
9538                  "\"delete\" command to delete unwanted breakpoints."));
9539       prev_breakpoint_count = prev_bkpt_count;
9540     }
9541
9542   update_global_location_list (UGLL_MAY_INSERT);
9543
9544   return 1;
9545 }
9546
9547 /* Set a breakpoint.
9548    ARG is a string describing breakpoint address,
9549    condition, and thread.
9550    FLAG specifies if a breakpoint is hardware on,
9551    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9552    and BP_TEMPFLAG.  */
9553
9554 static void
9555 break_command_1 (const char *arg, int flag, int from_tty)
9556 {
9557   int tempflag = flag & BP_TEMPFLAG;
9558   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9559                              ? bp_hardware_breakpoint
9560                              : bp_breakpoint);
9561
9562   event_location_up location = string_to_event_location (&arg, current_language);
9563   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
9564     (location.get (), false /* is_tracepoint */);
9565
9566   create_breakpoint (get_current_arch (),
9567                      location.get (),
9568                      NULL, 0, arg, 1 /* parse arg */,
9569                      tempflag, type_wanted,
9570                      0 /* Ignore count */,
9571                      pending_break_support,
9572                      ops,
9573                      from_tty,
9574                      1 /* enabled */,
9575                      0 /* internal */,
9576                      0);
9577 }
9578
9579 /* Helper function for break_command_1 and disassemble_command.  */
9580
9581 void
9582 resolve_sal_pc (struct symtab_and_line *sal)
9583 {
9584   CORE_ADDR pc;
9585
9586   if (sal->pc == 0 && sal->symtab != NULL)
9587     {
9588       if (!find_line_pc (sal->symtab, sal->line, &pc))
9589         error (_("No line %d in file \"%s\"."),
9590                sal->line, symtab_to_filename_for_display (sal->symtab));
9591       sal->pc = pc;
9592
9593       /* If this SAL corresponds to a breakpoint inserted using a line
9594          number, then skip the function prologue if necessary.  */
9595       if (sal->explicit_line)
9596         skip_prologue_sal (sal);
9597     }
9598
9599   if (sal->section == 0 && sal->symtab != NULL)
9600     {
9601       const struct blockvector *bv;
9602       const struct block *b;
9603       struct symbol *sym;
9604
9605       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
9606                                     SYMTAB_COMPUNIT (sal->symtab));
9607       if (bv != NULL)
9608         {
9609           sym = block_linkage_function (b);
9610           if (sym != NULL)
9611             {
9612               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
9613               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
9614                                                  sym);
9615             }
9616           else
9617             {
9618               /* It really is worthwhile to have the section, so we'll
9619                  just have to look harder. This case can be executed
9620                  if we have line numbers but no functions (as can
9621                  happen in assembly source).  */
9622
9623               scoped_restore_current_pspace_and_thread restore_pspace_thread;
9624               switch_to_program_space_and_thread (sal->pspace);
9625
9626               bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (sal->pc);
9627               if (msym.minsym)
9628                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9629             }
9630         }
9631     }
9632 }
9633
9634 void
9635 break_command (const char *arg, int from_tty)
9636 {
9637   break_command_1 (arg, 0, from_tty);
9638 }
9639
9640 void
9641 tbreak_command (const char *arg, int from_tty)
9642 {
9643   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9644 }
9645
9646 static void
9647 hbreak_command (const char *arg, int from_tty)
9648 {
9649   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9650 }
9651
9652 static void
9653 thbreak_command (const char *arg, int from_tty)
9654 {
9655   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9656 }
9657
9658 static void
9659 stop_command (const char *arg, int from_tty)
9660 {
9661   printf_filtered (_("Specify the type of breakpoint to set.\n\
9662 Usage: stop in <function | address>\n\
9663        stop at <line>\n"));
9664 }
9665
9666 static void
9667 stopin_command (const char *arg, int from_tty)
9668 {
9669   int badInput = 0;
9670
9671   if (arg == NULL)
9672     badInput = 1;
9673   else if (*arg != '*')
9674     {
9675       const char *argptr = arg;
9676       int hasColon = 0;
9677
9678       /* Look for a ':'.  If this is a line number specification, then
9679          say it is bad, otherwise, it should be an address or
9680          function/method name.  */
9681       while (*argptr && !hasColon)
9682         {
9683           hasColon = (*argptr == ':');
9684           argptr++;
9685         }
9686
9687       if (hasColon)
9688         badInput = (*argptr != ':');    /* Not a class::method */
9689       else
9690         badInput = isdigit (*arg);      /* a simple line number */
9691     }
9692
9693   if (badInput)
9694     printf_filtered (_("Usage: stop in <function | address>\n"));
9695   else
9696     break_command_1 (arg, 0, from_tty);
9697 }
9698
9699 static void
9700 stopat_command (const char *arg, int from_tty)
9701 {
9702   int badInput = 0;
9703
9704   if (arg == NULL || *arg == '*')       /* no line number */
9705     badInput = 1;
9706   else
9707     {
9708       const char *argptr = arg;
9709       int hasColon = 0;
9710
9711       /* Look for a ':'.  If there is a '::' then get out, otherwise
9712          it is probably a line number.  */
9713       while (*argptr && !hasColon)
9714         {
9715           hasColon = (*argptr == ':');
9716           argptr++;
9717         }
9718
9719       if (hasColon)
9720         badInput = (*argptr == ':');    /* we have class::method */
9721       else
9722         badInput = !isdigit (*arg);     /* not a line number */
9723     }
9724
9725   if (badInput)
9726     printf_filtered (_("Usage: stop at LINE\n"));
9727   else
9728     break_command_1 (arg, 0, from_tty);
9729 }
9730
9731 /* The dynamic printf command is mostly like a regular breakpoint, but
9732    with a prewired command list consisting of a single output command,
9733    built from extra arguments supplied on the dprintf command
9734    line.  */
9735
9736 static void
9737 dprintf_command (const char *arg, int from_tty)
9738 {
9739   event_location_up location = string_to_event_location (&arg, current_language);
9740
9741   /* If non-NULL, ARG should have been advanced past the location;
9742      the next character must be ','.  */
9743   if (arg != NULL)
9744     {
9745       if (arg[0] != ',' || arg[1] == '\0')
9746         error (_("Format string required"));
9747       else
9748         {
9749           /* Skip the comma.  */
9750           ++arg;
9751         }
9752     }
9753
9754   create_breakpoint (get_current_arch (),
9755                      location.get (),
9756                      NULL, 0, arg, 1 /* parse arg */,
9757                      0, bp_dprintf,
9758                      0 /* Ignore count */,
9759                      pending_break_support,
9760                      &dprintf_breakpoint_ops,
9761                      from_tty,
9762                      1 /* enabled */,
9763                      0 /* internal */,
9764                      0);
9765 }
9766
9767 static void
9768 agent_printf_command (const char *arg, int from_tty)
9769 {
9770   error (_("May only run agent-printf on the target"));
9771 }
9772
9773 /* Implement the "breakpoint_hit" breakpoint_ops method for
9774    ranged breakpoints.  */
9775
9776 static int
9777 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9778                                   const address_space *aspace,
9779                                   CORE_ADDR bp_addr,
9780                                   const struct target_waitstatus *ws)
9781 {
9782   if (ws->kind != TARGET_WAITKIND_STOPPED
9783       || ws->value.sig != GDB_SIGNAL_TRAP)
9784     return 0;
9785
9786   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9787                                          bl->length, aspace, bp_addr);
9788 }
9789
9790 /* Implement the "resources_needed" breakpoint_ops method for
9791    ranged breakpoints.  */
9792
9793 static int
9794 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9795 {
9796   return target_ranged_break_num_registers ();
9797 }
9798
9799 /* Implement the "print_it" breakpoint_ops method for
9800    ranged breakpoints.  */
9801
9802 static enum print_stop_action
9803 print_it_ranged_breakpoint (bpstat bs)
9804 {
9805   struct breakpoint *b = bs->breakpoint_at;
9806   struct bp_location *bl = b->loc;
9807   struct ui_out *uiout = current_uiout;
9808
9809   gdb_assert (b->type == bp_hardware_breakpoint);
9810
9811   /* Ranged breakpoints have only one location.  */
9812   gdb_assert (bl && bl->next == NULL);
9813
9814   annotate_breakpoint (b->number);
9815
9816   maybe_print_thread_hit_breakpoint (uiout);
9817
9818   if (b->disposition == disp_del)
9819     uiout->text ("Temporary ranged breakpoint ");
9820   else
9821     uiout->text ("Ranged breakpoint ");
9822   if (uiout->is_mi_like_p ())
9823     {
9824       uiout->field_string ("reason",
9825                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9826       uiout->field_string ("disp", bpdisp_text (b->disposition));
9827     }
9828   uiout->field_signed ("bkptno", b->number);
9829   uiout->text (", ");
9830
9831   return PRINT_SRC_AND_LOC;
9832 }
9833
9834 /* Implement the "print_one" breakpoint_ops method for
9835    ranged breakpoints.  */
9836
9837 static void
9838 print_one_ranged_breakpoint (struct breakpoint *b,
9839                              struct bp_location **last_loc)
9840 {
9841   struct bp_location *bl = b->loc;
9842   struct value_print_options opts;
9843   struct ui_out *uiout = current_uiout;
9844
9845   /* Ranged breakpoints have only one location.  */
9846   gdb_assert (bl && bl->next == NULL);
9847
9848   get_user_print_options (&opts);
9849
9850   if (opts.addressprint)
9851     /* We don't print the address range here, it will be printed later
9852        by print_one_detail_ranged_breakpoint.  */
9853     uiout->field_skip ("addr");
9854   annotate_field (5);
9855   print_breakpoint_location (b, bl);
9856   *last_loc = bl;
9857 }
9858
9859 /* Implement the "print_one_detail" breakpoint_ops method for
9860    ranged breakpoints.  */
9861
9862 static void
9863 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9864                                     struct ui_out *uiout)
9865 {
9866   CORE_ADDR address_start, address_end;
9867   struct bp_location *bl = b->loc;
9868   string_file stb;
9869
9870   gdb_assert (bl);
9871
9872   address_start = bl->address;
9873   address_end = address_start + bl->length - 1;
9874
9875   uiout->text ("\taddress range: ");
9876   stb.printf ("[%s, %s]",
9877               print_core_address (bl->gdbarch, address_start),
9878               print_core_address (bl->gdbarch, address_end));
9879   uiout->field_stream ("addr", stb);
9880   uiout->text ("\n");
9881 }
9882
9883 /* Implement the "print_mention" breakpoint_ops method for
9884    ranged breakpoints.  */
9885
9886 static void
9887 print_mention_ranged_breakpoint (struct breakpoint *b)
9888 {
9889   struct bp_location *bl = b->loc;
9890   struct ui_out *uiout = current_uiout;
9891
9892   gdb_assert (bl);
9893   gdb_assert (b->type == bp_hardware_breakpoint);
9894
9895   uiout->message (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9896                   b->number, paddress (bl->gdbarch, bl->address),
9897                   paddress (bl->gdbarch, bl->address + bl->length - 1));
9898 }
9899
9900 /* Implement the "print_recreate" breakpoint_ops method for
9901    ranged breakpoints.  */
9902
9903 static void
9904 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9905 {
9906   fprintf_unfiltered (fp, "break-range %s, %s",
9907                       event_location_to_string (b->location.get ()),
9908                       event_location_to_string (b->location_range_end.get ()));
9909   print_recreate_thread (b, fp);
9910 }
9911
9912 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9913
9914 static struct breakpoint_ops ranged_breakpoint_ops;
9915
9916 /* Find the address where the end of the breakpoint range should be
9917    placed, given the SAL of the end of the range.  This is so that if
9918    the user provides a line number, the end of the range is set to the
9919    last instruction of the given line.  */
9920
9921 static CORE_ADDR
9922 find_breakpoint_range_end (struct symtab_and_line sal)
9923 {
9924   CORE_ADDR end;
9925
9926   /* If the user provided a PC value, use it.  Otherwise,
9927      find the address of the end of the given location.  */
9928   if (sal.explicit_pc)
9929     end = sal.pc;
9930   else
9931     {
9932       int ret;
9933       CORE_ADDR start;
9934
9935       ret = find_line_pc_range (sal, &start, &end);
9936       if (!ret)
9937         error (_("Could not find location of the end of the range."));
9938
9939       /* find_line_pc_range returns the start of the next line.  */
9940       end--;
9941     }
9942
9943   return end;
9944 }
9945
9946 /* Implement the "break-range" CLI command.  */
9947
9948 static void
9949 break_range_command (const char *arg, int from_tty)
9950 {
9951   const char *arg_start;
9952   struct linespec_result canonical_start, canonical_end;
9953   int bp_count, can_use_bp, length;
9954   CORE_ADDR end;
9955   struct breakpoint *b;
9956
9957   /* We don't support software ranged breakpoints.  */
9958   if (target_ranged_break_num_registers () < 0)
9959     error (_("This target does not support hardware ranged breakpoints."));
9960
9961   bp_count = hw_breakpoint_used_count ();
9962   bp_count += target_ranged_break_num_registers ();
9963   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9964                                                    bp_count, 0);
9965   if (can_use_bp < 0)
9966     error (_("Hardware breakpoints used exceeds limit."));
9967
9968   arg = skip_spaces (arg);
9969   if (arg == NULL || arg[0] == '\0')
9970     error(_("No address range specified."));
9971
9972   arg_start = arg;
9973   event_location_up start_location = string_to_event_location (&arg,
9974                                                                current_language);
9975   parse_breakpoint_sals (start_location.get (), &canonical_start);
9976
9977   if (arg[0] != ',')
9978     error (_("Too few arguments."));
9979   else if (canonical_start.lsals.empty ())
9980     error (_("Could not find location of the beginning of the range."));
9981
9982   const linespec_sals &lsal_start = canonical_start.lsals[0];
9983
9984   if (canonical_start.lsals.size () > 1
9985       || lsal_start.sals.size () != 1)
9986     error (_("Cannot create a ranged breakpoint with multiple locations."));
9987
9988   const symtab_and_line &sal_start = lsal_start.sals[0];
9989   std::string addr_string_start (arg_start, arg - arg_start);
9990
9991   arg++;        /* Skip the comma.  */
9992   arg = skip_spaces (arg);
9993
9994   /* Parse the end location.  */
9995
9996   arg_start = arg;
9997
9998   /* We call decode_line_full directly here instead of using
9999      parse_breakpoint_sals because we need to specify the start location's
10000      symtab and line as the default symtab and line for the end of the
10001      range.  This makes it possible to have ranges like "foo.c:27, +14",
10002      where +14 means 14 lines from the start location.  */
10003   event_location_up end_location = string_to_event_location (&arg,
10004                                                              current_language);
10005   decode_line_full (end_location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
10006                     sal_start.symtab, sal_start.line,
10007                     &canonical_end, NULL, NULL);
10008
10009   if (canonical_end.lsals.empty ())
10010     error (_("Could not find location of the end of the range."));
10011
10012   const linespec_sals &lsal_end = canonical_end.lsals[0];
10013   if (canonical_end.lsals.size () > 1
10014       || lsal_end.sals.size () != 1)
10015     error (_("Cannot create a ranged breakpoint with multiple locations."));
10016
10017   const symtab_and_line &sal_end = lsal_end.sals[0];
10018
10019   end = find_breakpoint_range_end (sal_end);
10020   if (sal_start.pc > end)
10021     error (_("Invalid address range, end precedes start."));
10022
10023   length = end - sal_start.pc + 1;
10024   if (length < 0)
10025     /* Length overflowed.  */
10026     error (_("Address range too large."));
10027   else if (length == 1)
10028     {
10029       /* This range is simple enough to be handled by
10030          the `hbreak' command.  */
10031       hbreak_command (&addr_string_start[0], 1);
10032
10033       return;
10034     }
10035
10036   /* Now set up the breakpoint.  */
10037   b = set_raw_breakpoint (get_current_arch (), sal_start,
10038                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10039   set_breakpoint_count (breakpoint_count + 1);
10040   b->number = breakpoint_count;
10041   b->disposition = disp_donttouch;
10042   b->location = std::move (start_location);
10043   b->location_range_end = std::move (end_location);
10044   b->loc->length = length;
10045
10046   mention (b);
10047   gdb::observers::breakpoint_created.notify (b);
10048   update_global_location_list (UGLL_MAY_INSERT);
10049 }
10050
10051 /*  Return non-zero if EXP is verified as constant.  Returned zero
10052     means EXP is variable.  Also the constant detection may fail for
10053     some constant expressions and in such case still falsely return
10054     zero.  */
10055
10056 static bool
10057 watchpoint_exp_is_const (const struct expression *exp)
10058 {
10059   int i = exp->nelts;
10060
10061   while (i > 0)
10062     {
10063       int oplenp, argsp;
10064
10065       /* We are only interested in the descriptor of each element.  */
10066       operator_length (exp, i, &oplenp, &argsp);
10067       i -= oplenp;
10068
10069       switch (exp->elts[i].opcode)
10070         {
10071         case BINOP_ADD:
10072         case BINOP_SUB:
10073         case BINOP_MUL:
10074         case BINOP_DIV:
10075         case BINOP_REM:
10076         case BINOP_MOD:
10077         case BINOP_LSH:
10078         case BINOP_RSH:
10079         case BINOP_LOGICAL_AND:
10080         case BINOP_LOGICAL_OR:
10081         case BINOP_BITWISE_AND:
10082         case BINOP_BITWISE_IOR:
10083         case BINOP_BITWISE_XOR:
10084         case BINOP_EQUAL:
10085         case BINOP_NOTEQUAL:
10086         case BINOP_LESS:
10087         case BINOP_GTR:
10088         case BINOP_LEQ:
10089         case BINOP_GEQ:
10090         case BINOP_REPEAT:
10091         case BINOP_COMMA:
10092         case BINOP_EXP:
10093         case BINOP_MIN:
10094         case BINOP_MAX:
10095         case BINOP_INTDIV:
10096         case BINOP_CONCAT:
10097         case TERNOP_COND:
10098         case TERNOP_SLICE:
10099
10100         case OP_LONG:
10101         case OP_FLOAT:
10102         case OP_LAST:
10103         case OP_COMPLEX:
10104         case OP_STRING:
10105         case OP_ARRAY:
10106         case OP_TYPE:
10107         case OP_TYPEOF:
10108         case OP_DECLTYPE:
10109         case OP_TYPEID:
10110         case OP_NAME:
10111         case OP_OBJC_NSSTRING:
10112
10113         case UNOP_NEG:
10114         case UNOP_LOGICAL_NOT:
10115         case UNOP_COMPLEMENT:
10116         case UNOP_ADDR:
10117         case UNOP_HIGH:
10118         case UNOP_CAST:
10119
10120         case UNOP_CAST_TYPE:
10121         case UNOP_REINTERPRET_CAST:
10122         case UNOP_DYNAMIC_CAST:
10123           /* Unary, binary and ternary operators: We have to check
10124              their operands.  If they are constant, then so is the
10125              result of that operation.  For instance, if A and B are
10126              determined to be constants, then so is "A + B".
10127
10128              UNOP_IND is one exception to the rule above, because the
10129              value of *ADDR is not necessarily a constant, even when
10130              ADDR is.  */
10131           break;
10132
10133         case OP_VAR_VALUE:
10134           /* Check whether the associated symbol is a constant.
10135
10136              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10137              possible that a buggy compiler could mark a variable as
10138              constant even when it is not, and TYPE_CONST would return
10139              true in this case, while SYMBOL_CLASS wouldn't.
10140
10141              We also have to check for function symbols because they
10142              are always constant.  */
10143           {
10144             struct symbol *s = exp->elts[i + 2].symbol;
10145
10146             if (SYMBOL_CLASS (s) != LOC_BLOCK
10147                 && SYMBOL_CLASS (s) != LOC_CONST
10148                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10149               return false;
10150             break;
10151           }
10152
10153         /* The default action is to return 0 because we are using
10154            the optimistic approach here: If we don't know something,
10155            then it is not a constant.  */
10156         default:
10157           return false;
10158         }
10159     }
10160
10161   return true;
10162 }
10163
10164 /* Watchpoint destructor.  */
10165
10166 watchpoint::~watchpoint ()
10167 {
10168   xfree (this->exp_string);
10169   xfree (this->exp_string_reparse);
10170 }
10171
10172 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10173
10174 static void
10175 re_set_watchpoint (struct breakpoint *b)
10176 {
10177   struct watchpoint *w = (struct watchpoint *) b;
10178
10179   /* Watchpoint can be either on expression using entirely global
10180      variables, or it can be on local variables.
10181
10182      Watchpoints of the first kind are never auto-deleted, and even
10183      persist across program restarts.  Since they can use variables
10184      from shared libraries, we need to reparse expression as libraries
10185      are loaded and unloaded.
10186
10187      Watchpoints on local variables can also change meaning as result
10188      of solib event.  For example, if a watchpoint uses both a local
10189      and a global variables in expression, it's a local watchpoint,
10190      but unloading of a shared library will make the expression
10191      invalid.  This is not a very common use case, but we still
10192      re-evaluate expression, to avoid surprises to the user.
10193
10194      Note that for local watchpoints, we re-evaluate it only if
10195      watchpoints frame id is still valid.  If it's not, it means the
10196      watchpoint is out of scope and will be deleted soon.  In fact,
10197      I'm not sure we'll ever be called in this case.
10198
10199      If a local watchpoint's frame id is still valid, then
10200      w->exp_valid_block is likewise valid, and we can safely use it.
10201
10202      Don't do anything about disabled watchpoints, since they will be
10203      reevaluated again when enabled.  */
10204   update_watchpoint (w, 1 /* reparse */);
10205 }
10206
10207 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10208
10209 static int
10210 insert_watchpoint (struct bp_location *bl)
10211 {
10212   struct watchpoint *w = (struct watchpoint *) bl->owner;
10213   int length = w->exact ? 1 : bl->length;
10214
10215   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10216                                    w->cond_exp.get ());
10217 }
10218
10219 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10220
10221 static int
10222 remove_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10223 {
10224   struct watchpoint *w = (struct watchpoint *) bl->owner;
10225   int length = w->exact ? 1 : bl->length;
10226
10227   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10228                                    w->cond_exp.get ());
10229 }
10230
10231 static int
10232 breakpoint_hit_watchpoint (const struct bp_location *bl,
10233                            const address_space *aspace, CORE_ADDR bp_addr,
10234                            const struct target_waitstatus *ws)
10235 {
10236   struct breakpoint *b = bl->owner;
10237   struct watchpoint *w = (struct watchpoint *) b;
10238
10239   /* Continuable hardware watchpoints are treated as non-existent if the
10240      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10241      some data address).  Otherwise gdb won't stop on a break instruction
10242      in the code (not from a breakpoint) when a hardware watchpoint has
10243      been defined.  Also skip watchpoints which we know did not trigger
10244      (did not match the data address).  */
10245   if (is_hardware_watchpoint (b)
10246       && w->watchpoint_triggered == watch_triggered_no)
10247     return 0;
10248
10249   return 1;
10250 }
10251
10252 static void
10253 check_status_watchpoint (bpstat bs)
10254 {
10255   gdb_assert (is_watchpoint (bs->breakpoint_at));
10256
10257   bpstat_check_watchpoint (bs);
10258 }
10259
10260 /* Implement the "resources_needed" breakpoint_ops method for
10261    hardware watchpoints.  */
10262
10263 static int
10264 resources_needed_watchpoint (const struct bp_location *bl)
10265 {
10266   struct watchpoint *w = (struct watchpoint *) bl->owner;
10267   int length = w->exact? 1 : bl->length;
10268
10269   return target_region_ok_for_hw_watchpoint (bl->address, length);
10270 }
10271
10272 /* Implement the "works_in_software_mode" breakpoint_ops method for
10273    hardware watchpoints.  */
10274
10275 static int
10276 works_in_software_mode_watchpoint (const struct breakpoint *b)
10277 {
10278   /* Read and access watchpoints only work with hardware support.  */
10279   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10280 }
10281
10282 static enum print_stop_action
10283 print_it_watchpoint (bpstat bs)
10284 {
10285   struct breakpoint *b;
10286   enum print_stop_action result;
10287   struct watchpoint *w;
10288   struct ui_out *uiout = current_uiout;
10289
10290   gdb_assert (bs->bp_location_at != NULL);
10291
10292   b = bs->breakpoint_at;
10293   w = (struct watchpoint *) b;
10294
10295   annotate_watchpoint (b->number);
10296   maybe_print_thread_hit_breakpoint (uiout);
10297
10298   string_file stb;
10299
10300   gdb::optional<ui_out_emit_tuple> tuple_emitter;
10301   switch (b->type)
10302     {
10303     case bp_watchpoint:
10304     case bp_hardware_watchpoint:
10305       if (uiout->is_mi_like_p ())
10306         uiout->field_string
10307           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10308       mention (b);
10309       tuple_emitter.emplace (uiout, "value");
10310       uiout->text ("\nOld value = ");
10311       watchpoint_value_print (bs->old_val.get (), &stb);
10312       uiout->field_stream ("old", stb);
10313       uiout->text ("\nNew value = ");
10314       watchpoint_value_print (w->val.get (), &stb);
10315       uiout->field_stream ("new", stb);
10316       uiout->text ("\n");
10317       /* More than one watchpoint may have been triggered.  */
10318       result = PRINT_UNKNOWN;
10319       break;
10320
10321     case bp_read_watchpoint:
10322       if (uiout->is_mi_like_p ())
10323         uiout->field_string
10324           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10325       mention (b);
10326       tuple_emitter.emplace (uiout, "value");
10327       uiout->text ("\nValue = ");
10328       watchpoint_value_print (w->val.get (), &stb);
10329       uiout->field_stream ("value", stb);
10330       uiout->text ("\n");
10331       result = PRINT_UNKNOWN;
10332       break;
10333
10334     case bp_access_watchpoint:
10335       if (bs->old_val != NULL)
10336         {
10337           if (uiout->is_mi_like_p ())
10338             uiout->field_string
10339               ("reason",
10340                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10341           mention (b);
10342           tuple_emitter.emplace (uiout, "value");
10343           uiout->text ("\nOld value = ");
10344           watchpoint_value_print (bs->old_val.get (), &stb);
10345           uiout->field_stream ("old", stb);
10346           uiout->text ("\nNew value = ");
10347         }
10348       else
10349         {
10350           mention (b);
10351           if (uiout->is_mi_like_p ())
10352             uiout->field_string
10353               ("reason",
10354                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10355           tuple_emitter.emplace (uiout, "value");
10356           uiout->text ("\nValue = ");
10357         }
10358       watchpoint_value_print (w->val.get (), &stb);
10359       uiout->field_stream ("new", stb);
10360       uiout->text ("\n");
10361       result = PRINT_UNKNOWN;
10362       break;
10363     default:
10364       result = PRINT_UNKNOWN;
10365     }
10366
10367   return result;
10368 }
10369
10370 /* Implement the "print_mention" breakpoint_ops method for hardware
10371    watchpoints.  */
10372
10373 static void
10374 print_mention_watchpoint (struct breakpoint *b)
10375 {
10376   struct watchpoint *w = (struct watchpoint *) b;
10377   struct ui_out *uiout = current_uiout;
10378   const char *tuple_name;
10379
10380   switch (b->type)
10381     {
10382     case bp_watchpoint:
10383       uiout->text ("Watchpoint ");
10384       tuple_name = "wpt";
10385       break;
10386     case bp_hardware_watchpoint:
10387       uiout->text ("Hardware watchpoint ");
10388       tuple_name = "wpt";
10389       break;
10390     case bp_read_watchpoint:
10391       uiout->text ("Hardware read watchpoint ");
10392       tuple_name = "hw-rwpt";
10393       break;
10394     case bp_access_watchpoint:
10395       uiout->text ("Hardware access (read/write) watchpoint ");
10396       tuple_name = "hw-awpt";
10397       break;
10398     default:
10399       internal_error (__FILE__, __LINE__,
10400                       _("Invalid hardware watchpoint type."));
10401     }
10402
10403   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10404   uiout->field_signed ("number", b->number);
10405   uiout->text (": ");
10406   uiout->field_string ("exp", w->exp_string);
10407 }
10408
10409 /* Implement the "print_recreate" breakpoint_ops method for
10410    watchpoints.  */
10411
10412 static void
10413 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10414 {
10415   struct watchpoint *w = (struct watchpoint *) b;
10416
10417   switch (b->type)
10418     {
10419     case bp_watchpoint:
10420     case bp_hardware_watchpoint:
10421       fprintf_unfiltered (fp, "watch");
10422       break;
10423     case bp_read_watchpoint:
10424       fprintf_unfiltered (fp, "rwatch");
10425       break;
10426     case bp_access_watchpoint:
10427       fprintf_unfiltered (fp, "awatch");
10428       break;
10429     default:
10430       internal_error (__FILE__, __LINE__,
10431                       _("Invalid watchpoint type."));
10432     }
10433
10434   fprintf_unfiltered (fp, " %s", w->exp_string);
10435   print_recreate_thread (b, fp);
10436 }
10437
10438 /* Implement the "explains_signal" breakpoint_ops method for
10439    watchpoints.  */
10440
10441 static int
10442 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10443 {
10444   /* A software watchpoint cannot cause a signal other than
10445      GDB_SIGNAL_TRAP.  */
10446   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10447     return 0;
10448
10449   return 1;
10450 }
10451
10452 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10453
10454 static struct breakpoint_ops watchpoint_breakpoint_ops;
10455
10456 /* Implement the "insert" breakpoint_ops method for
10457    masked hardware watchpoints.  */
10458
10459 static int
10460 insert_masked_watchpoint (struct bp_location *bl)
10461 {
10462   struct watchpoint *w = (struct watchpoint *) bl->owner;
10463
10464   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10465                                         bl->watchpoint_type);
10466 }
10467
10468 /* Implement the "remove" breakpoint_ops method for
10469    masked hardware watchpoints.  */
10470
10471 static int
10472 remove_masked_watchpoint (struct bp_location *bl, enum remove_bp_reason reason)
10473 {
10474   struct watchpoint *w = (struct watchpoint *) bl->owner;
10475
10476   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10477                                         bl->watchpoint_type);
10478 }
10479
10480 /* Implement the "resources_needed" breakpoint_ops method for
10481    masked hardware watchpoints.  */
10482
10483 static int
10484 resources_needed_masked_watchpoint (const struct bp_location *bl)
10485 {
10486   struct watchpoint *w = (struct watchpoint *) bl->owner;
10487
10488   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10489 }
10490
10491 /* Implement the "works_in_software_mode" breakpoint_ops method for
10492    masked hardware watchpoints.  */
10493
10494 static int
10495 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10496 {
10497   return 0;
10498 }
10499
10500 /* Implement the "print_it" breakpoint_ops method for
10501    masked hardware watchpoints.  */
10502
10503 static enum print_stop_action
10504 print_it_masked_watchpoint (bpstat bs)
10505 {
10506   struct breakpoint *b = bs->breakpoint_at;
10507   struct ui_out *uiout = current_uiout;
10508
10509   /* Masked watchpoints have only one location.  */
10510   gdb_assert (b->loc && b->loc->next == NULL);
10511
10512   annotate_watchpoint (b->number);
10513   maybe_print_thread_hit_breakpoint (uiout);
10514
10515   switch (b->type)
10516     {
10517     case bp_hardware_watchpoint:
10518       if (uiout->is_mi_like_p ())
10519         uiout->field_string
10520           ("reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10521       break;
10522
10523     case bp_read_watchpoint:
10524       if (uiout->is_mi_like_p ())
10525         uiout->field_string
10526           ("reason", async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10527       break;
10528
10529     case bp_access_watchpoint:
10530       if (uiout->is_mi_like_p ())
10531         uiout->field_string
10532           ("reason",
10533            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10534       break;
10535     default:
10536       internal_error (__FILE__, __LINE__,
10537                       _("Invalid hardware watchpoint type."));
10538     }
10539
10540   mention (b);
10541   uiout->text (_("\n\
10542 Check the underlying instruction at PC for the memory\n\
10543 address and value which triggered this watchpoint.\n"));
10544   uiout->text ("\n");
10545
10546   /* More than one watchpoint may have been triggered.  */
10547   return PRINT_UNKNOWN;
10548 }
10549
10550 /* Implement the "print_one_detail" breakpoint_ops method for
10551    masked hardware watchpoints.  */
10552
10553 static void
10554 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10555                                     struct ui_out *uiout)
10556 {
10557   struct watchpoint *w = (struct watchpoint *) b;
10558
10559   /* Masked watchpoints have only one location.  */
10560   gdb_assert (b->loc && b->loc->next == NULL);
10561
10562   uiout->text ("\tmask ");
10563   uiout->field_core_addr ("mask", b->loc->gdbarch, w->hw_wp_mask);
10564   uiout->text ("\n");
10565 }
10566
10567 /* Implement the "print_mention" breakpoint_ops method for
10568    masked hardware watchpoints.  */
10569
10570 static void
10571 print_mention_masked_watchpoint (struct breakpoint *b)
10572 {
10573   struct watchpoint *w = (struct watchpoint *) b;
10574   struct ui_out *uiout = current_uiout;
10575   const char *tuple_name;
10576
10577   switch (b->type)
10578     {
10579     case bp_hardware_watchpoint:
10580       uiout->text ("Masked hardware watchpoint ");
10581       tuple_name = "wpt";
10582       break;
10583     case bp_read_watchpoint:
10584       uiout->text ("Masked hardware read watchpoint ");
10585       tuple_name = "hw-rwpt";
10586       break;
10587     case bp_access_watchpoint:
10588       uiout->text ("Masked hardware access (read/write) watchpoint ");
10589       tuple_name = "hw-awpt";
10590       break;
10591     default:
10592       internal_error (__FILE__, __LINE__,
10593                       _("Invalid hardware watchpoint type."));
10594     }
10595
10596   ui_out_emit_tuple tuple_emitter (uiout, tuple_name);
10597   uiout->field_signed ("number", b->number);
10598   uiout->text (": ");
10599   uiout->field_string ("exp", w->exp_string);
10600 }
10601
10602 /* Implement the "print_recreate" breakpoint_ops method for
10603    masked hardware watchpoints.  */
10604
10605 static void
10606 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10607 {
10608   struct watchpoint *w = (struct watchpoint *) b;
10609
10610   switch (b->type)
10611     {
10612     case bp_hardware_watchpoint:
10613       fprintf_unfiltered (fp, "watch");
10614       break;
10615     case bp_read_watchpoint:
10616       fprintf_unfiltered (fp, "rwatch");
10617       break;
10618     case bp_access_watchpoint:
10619       fprintf_unfiltered (fp, "awatch");
10620       break;
10621     default:
10622       internal_error (__FILE__, __LINE__,
10623                       _("Invalid hardware watchpoint type."));
10624     }
10625
10626   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string,
10627                       phex (w->hw_wp_mask, sizeof (CORE_ADDR)));
10628   print_recreate_thread (b, fp);
10629 }
10630
10631 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10632
10633 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10634
10635 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10636
10637 static bool
10638 is_masked_watchpoint (const struct breakpoint *b)
10639 {
10640   return b->ops == &masked_watchpoint_breakpoint_ops;
10641 }
10642
10643 /* accessflag:  hw_write:  watch write, 
10644                 hw_read:   watch read, 
10645                 hw_access: watch access (read or write) */
10646 static void
10647 watch_command_1 (const char *arg, int accessflag, int from_tty,
10648                  bool just_location, bool internal)
10649 {
10650   struct breakpoint *scope_breakpoint = NULL;
10651   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10652   struct value *result;
10653   int saved_bitpos = 0, saved_bitsize = 0;
10654   const char *exp_start = NULL;
10655   const char *exp_end = NULL;
10656   const char *tok, *end_tok;
10657   int toklen = -1;
10658   const char *cond_start = NULL;
10659   const char *cond_end = NULL;
10660   enum bptype bp_type;
10661   int thread = -1;
10662   int pc = 0;
10663   /* Flag to indicate whether we are going to use masks for
10664      the hardware watchpoint.  */
10665   bool use_mask = false;
10666   CORE_ADDR mask = 0;
10667
10668   /* Make sure that we actually have parameters to parse.  */
10669   if (arg != NULL && arg[0] != '\0')
10670     {
10671       const char *value_start;
10672
10673       exp_end = arg + strlen (arg);
10674
10675       /* Look for "parameter value" pairs at the end
10676          of the arguments string.  */
10677       for (tok = exp_end - 1; tok > arg; tok--)
10678         {
10679           /* Skip whitespace at the end of the argument list.  */
10680           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10681             tok--;
10682
10683           /* Find the beginning of the last token.
10684              This is the value of the parameter.  */
10685           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10686             tok--;
10687           value_start = tok + 1;
10688
10689           /* Skip whitespace.  */
10690           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10691             tok--;
10692
10693           end_tok = tok;
10694
10695           /* Find the beginning of the second to last token.
10696              This is the parameter itself.  */
10697           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10698             tok--;
10699           tok++;
10700           toklen = end_tok - tok + 1;
10701
10702           if (toklen == 6 && startswith (tok, "thread"))
10703             {
10704               struct thread_info *thr;
10705               /* At this point we've found a "thread" token, which means
10706                  the user is trying to set a watchpoint that triggers
10707                  only in a specific thread.  */
10708               const char *endp;
10709
10710               if (thread != -1)
10711                 error(_("You can specify only one thread."));
10712
10713               /* Extract the thread ID from the next token.  */
10714               thr = parse_thread_id (value_start, &endp);
10715
10716               /* Check if the user provided a valid thread ID.  */
10717               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10718                 invalid_thread_id_error (value_start);
10719
10720               thread = thr->global_num;
10721             }
10722           else if (toklen == 4 && startswith (tok, "mask"))
10723             {
10724               /* We've found a "mask" token, which means the user wants to
10725                  create a hardware watchpoint that is going to have the mask
10726                  facility.  */
10727               struct value *mask_value, *mark;
10728
10729               if (use_mask)
10730                 error(_("You can specify only one mask."));
10731
10732               use_mask = just_location = true;
10733
10734               mark = value_mark ();
10735               mask_value = parse_to_comma_and_eval (&value_start);
10736               mask = value_as_address (mask_value);
10737               value_free_to_mark (mark);
10738             }
10739           else
10740             /* We didn't recognize what we found.  We should stop here.  */
10741             break;
10742
10743           /* Truncate the string and get rid of the "parameter value" pair before
10744              the arguments string is parsed by the parse_exp_1 function.  */
10745           exp_end = tok;
10746         }
10747     }
10748   else
10749     exp_end = arg;
10750
10751   /* Parse the rest of the arguments.  From here on out, everything
10752      is in terms of a newly allocated string instead of the original
10753      ARG.  */
10754   std::string expression (arg, exp_end - arg);
10755   exp_start = arg = expression.c_str ();
10756   innermost_block_tracker tracker;
10757   expression_up exp = parse_exp_1 (&arg, 0, 0, 0, &tracker);
10758   exp_end = arg;
10759   /* Remove trailing whitespace from the expression before saving it.
10760      This makes the eventual display of the expression string a bit
10761      prettier.  */
10762   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10763     --exp_end;
10764
10765   /* Checking if the expression is not constant.  */
10766   if (watchpoint_exp_is_const (exp.get ()))
10767     {
10768       int len;
10769
10770       len = exp_end - exp_start;
10771       while (len > 0 && isspace (exp_start[len - 1]))
10772         len--;
10773       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10774     }
10775
10776   exp_valid_block = tracker.block ();
10777   struct value *mark = value_mark ();
10778   struct value *val_as_value = nullptr;
10779   fetch_subexp_value (exp.get (), &pc, &val_as_value, &result, NULL,
10780                       just_location);
10781
10782   if (val_as_value != NULL && just_location)
10783     {
10784       saved_bitpos = value_bitpos (val_as_value);
10785       saved_bitsize = value_bitsize (val_as_value);
10786     }
10787
10788   value_ref_ptr val;
10789   if (just_location)
10790     {
10791       int ret;
10792
10793       exp_valid_block = NULL;
10794       val = release_value (value_addr (result));
10795       value_free_to_mark (mark);
10796
10797       if (use_mask)
10798         {
10799           ret = target_masked_watch_num_registers (value_as_address (val.get ()),
10800                                                    mask);
10801           if (ret == -1)
10802             error (_("This target does not support masked watchpoints."));
10803           else if (ret == -2)
10804             error (_("Invalid mask or memory region."));
10805         }
10806     }
10807   else if (val_as_value != NULL)
10808     val = release_value (val_as_value);
10809
10810   tok = skip_spaces (arg);
10811   end_tok = skip_to_space (tok);
10812
10813   toklen = end_tok - tok;
10814   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10815     {
10816       tok = cond_start = end_tok + 1;
10817       innermost_block_tracker if_tracker;
10818       parse_exp_1 (&tok, 0, 0, 0, &if_tracker);
10819
10820       /* The watchpoint expression may not be local, but the condition
10821          may still be.  E.g.: `watch global if local > 0'.  */
10822       cond_exp_valid_block = if_tracker.block ();
10823
10824       cond_end = tok;
10825     }
10826   if (*tok)
10827     error (_("Junk at end of command."));
10828
10829   frame_info *wp_frame = block_innermost_frame (exp_valid_block);
10830
10831   /* Save this because create_internal_breakpoint below invalidates
10832      'wp_frame'.  */
10833   frame_id watchpoint_frame = get_frame_id (wp_frame);
10834
10835   /* If the expression is "local", then set up a "watchpoint scope"
10836      breakpoint at the point where we've left the scope of the watchpoint
10837      expression.  Create the scope breakpoint before the watchpoint, so
10838      that we will encounter it first in bpstat_stop_status.  */
10839   if (exp_valid_block != NULL && wp_frame != NULL)
10840     {
10841       frame_id caller_frame_id = frame_unwind_caller_id (wp_frame);
10842
10843       if (frame_id_p (caller_frame_id))
10844         {
10845           gdbarch *caller_arch = frame_unwind_caller_arch (wp_frame);
10846           CORE_ADDR caller_pc = frame_unwind_caller_pc (wp_frame);
10847
10848           scope_breakpoint
10849             = create_internal_breakpoint (caller_arch, caller_pc,
10850                                           bp_watchpoint_scope,
10851                                           &momentary_breakpoint_ops);
10852
10853           /* create_internal_breakpoint could invalidate WP_FRAME.  */
10854           wp_frame = NULL;
10855
10856           scope_breakpoint->enable_state = bp_enabled;
10857
10858           /* Automatically delete the breakpoint when it hits.  */
10859           scope_breakpoint->disposition = disp_del;
10860
10861           /* Only break in the proper frame (help with recursion).  */
10862           scope_breakpoint->frame_id = caller_frame_id;
10863
10864           /* Set the address at which we will stop.  */
10865           scope_breakpoint->loc->gdbarch = caller_arch;
10866           scope_breakpoint->loc->requested_address = caller_pc;
10867           scope_breakpoint->loc->address
10868             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10869                                          scope_breakpoint->loc->requested_address,
10870                                          scope_breakpoint->type);
10871         }
10872     }
10873
10874   /* Now set up the breakpoint.  We create all watchpoints as hardware
10875      watchpoints here even if hardware watchpoints are turned off, a call
10876      to update_watchpoint later in this function will cause the type to
10877      drop back to bp_watchpoint (software watchpoint) if required.  */
10878
10879   if (accessflag == hw_read)
10880     bp_type = bp_read_watchpoint;
10881   else if (accessflag == hw_access)
10882     bp_type = bp_access_watchpoint;
10883   else
10884     bp_type = bp_hardware_watchpoint;
10885
10886   std::unique_ptr<watchpoint> w (new watchpoint ());
10887
10888   if (use_mask)
10889     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10890                                           &masked_watchpoint_breakpoint_ops);
10891   else
10892     init_raw_breakpoint_without_location (w.get (), NULL, bp_type,
10893                                           &watchpoint_breakpoint_ops);
10894   w->thread = thread;
10895   w->disposition = disp_donttouch;
10896   w->pspace = current_program_space;
10897   w->exp = std::move (exp);
10898   w->exp_valid_block = exp_valid_block;
10899   w->cond_exp_valid_block = cond_exp_valid_block;
10900   if (just_location)
10901     {
10902       struct type *t = value_type (val.get ());
10903       CORE_ADDR addr = value_as_address (val.get ());
10904
10905       w->exp_string_reparse
10906         = current_language->watch_location_expression (t, addr).release ();
10907
10908       w->exp_string = xstrprintf ("-location %.*s",
10909                                   (int) (exp_end - exp_start), exp_start);
10910     }
10911   else
10912     w->exp_string = savestring (exp_start, exp_end - exp_start);
10913
10914   if (use_mask)
10915     {
10916       w->hw_wp_mask = mask;
10917     }
10918   else
10919     {
10920       w->val = val;
10921       w->val_bitpos = saved_bitpos;
10922       w->val_bitsize = saved_bitsize;
10923       w->val_valid = true;
10924     }
10925
10926   if (cond_start)
10927     w->cond_string = savestring (cond_start, cond_end - cond_start);
10928   else
10929     w->cond_string = 0;
10930
10931   if (frame_id_p (watchpoint_frame))
10932     {
10933       w->watchpoint_frame = watchpoint_frame;
10934       w->watchpoint_thread = inferior_ptid;
10935     }
10936   else
10937     {
10938       w->watchpoint_frame = null_frame_id;
10939       w->watchpoint_thread = null_ptid;
10940     }
10941
10942   if (scope_breakpoint != NULL)
10943     {
10944       /* The scope breakpoint is related to the watchpoint.  We will
10945          need to act on them together.  */
10946       w->related_breakpoint = scope_breakpoint;
10947       scope_breakpoint->related_breakpoint = w.get ();
10948     }
10949
10950   if (!just_location)
10951     value_free_to_mark (mark);
10952
10953   /* Finally update the new watchpoint.  This creates the locations
10954      that should be inserted.  */
10955   update_watchpoint (w.get (), 1);
10956
10957   install_breakpoint (internal, std::move (w), 1);
10958 }
10959
10960 /* Return count of debug registers needed to watch the given expression.
10961    If the watchpoint cannot be handled in hardware return zero.  */
10962
10963 static int
10964 can_use_hardware_watchpoint (const std::vector<value_ref_ptr> &vals)
10965 {
10966   int found_memory_cnt = 0;
10967
10968   /* Did the user specifically forbid us to use hardware watchpoints? */
10969   if (!can_use_hw_watchpoints)
10970     return 0;
10971
10972   gdb_assert (!vals.empty ());
10973   struct value *head = vals[0].get ();
10974
10975   /* Make sure that the value of the expression depends only upon
10976      memory contents, and values computed from them within GDB.  If we
10977      find any register references or function calls, we can't use a
10978      hardware watchpoint.
10979
10980      The idea here is that evaluating an expression generates a series
10981      of values, one holding the value of every subexpression.  (The
10982      expression a*b+c has five subexpressions: a, b, a*b, c, and
10983      a*b+c.)  GDB's values hold almost enough information to establish
10984      the criteria given above --- they identify memory lvalues,
10985      register lvalues, computed values, etcetera.  So we can evaluate
10986      the expression, and then scan the chain of values that leaves
10987      behind to decide whether we can detect any possible change to the
10988      expression's final value using only hardware watchpoints.
10989
10990      However, I don't think that the values returned by inferior
10991      function calls are special in any way.  So this function may not
10992      notice that an expression involving an inferior function call
10993      can't be watched with hardware watchpoints.  FIXME.  */
10994   for (const value_ref_ptr &iter : vals)
10995     {
10996       struct value *v = iter.get ();
10997
10998       if (VALUE_LVAL (v) == lval_memory)
10999         {
11000           if (v != head && value_lazy (v))
11001             /* A lazy memory lvalue in the chain is one that GDB never
11002                needed to fetch; we either just used its address (e.g.,
11003                `a' in `a.b') or we never needed it at all (e.g., `a'
11004                in `a,b').  This doesn't apply to HEAD; if that is
11005                lazy then it was not readable, but watch it anyway.  */
11006             ;
11007           else
11008             {
11009               /* Ahh, memory we actually used!  Check if we can cover
11010                  it with hardware watchpoints.  */
11011               struct type *vtype = check_typedef (value_type (v));
11012
11013               /* We only watch structs and arrays if user asked for it
11014                  explicitly, never if they just happen to appear in a
11015                  middle of some value chain.  */
11016               if (v == head
11017                   || (vtype->code () != TYPE_CODE_STRUCT
11018                       && vtype->code () != TYPE_CODE_ARRAY))
11019                 {
11020                   CORE_ADDR vaddr = value_address (v);
11021                   int len;
11022                   int num_regs;
11023
11024                   len = (target_exact_watchpoints
11025                          && is_scalar_type_recursive (vtype))?
11026                     1 : TYPE_LENGTH (value_type (v));
11027
11028                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11029                   if (!num_regs)
11030                     return 0;
11031                   else
11032                     found_memory_cnt += num_regs;
11033                 }
11034             }
11035         }
11036       else if (VALUE_LVAL (v) != not_lval
11037                && deprecated_value_modifiable (v) == 0)
11038         return 0;       /* These are values from the history (e.g., $1).  */
11039       else if (VALUE_LVAL (v) == lval_register)
11040         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11041     }
11042
11043   /* The expression itself looks suitable for using a hardware
11044      watchpoint, but give the target machine a chance to reject it.  */
11045   return found_memory_cnt;
11046 }
11047
11048 void
11049 watch_command_wrapper (const char *arg, int from_tty, bool internal)
11050 {
11051   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11052 }
11053
11054 /* Options for the watch, awatch, and rwatch commands.  */
11055
11056 struct watch_options
11057 {
11058   /* For -location.  */
11059   bool location = false;
11060 };
11061
11062 /* Definitions of options for the "watch", "awatch", and "rwatch" commands.
11063
11064    Historically GDB always accepted both '-location' and '-l' flags for
11065    these commands (both flags being synonyms).  When converting to the
11066    newer option scheme only '-location' is added here.  That's fine (for
11067    backward compatibility) as any non-ambiguous prefix of a flag will be
11068    accepted, so '-l', '-loc', are now all accepted.
11069
11070    What this means is that, if in the future, we add any new flag here
11071    that starts with '-l' then this will break backward compatibility, so
11072    please, don't do that!  */
11073
11074 static const gdb::option::option_def watch_option_defs[] = {
11075   gdb::option::flag_option_def<watch_options> {
11076     "location",
11077     [] (watch_options *opt) { return &opt->location; },
11078     N_("\
11079 This evaluates EXPRESSION and watches the memory to which is refers.\n\
11080 -l can be used as a short form of -location."),
11081   },
11082 };
11083
11084 /* Returns the option group used by 'watch', 'awatch', and 'rwatch'
11085    commands.  */
11086
11087 static gdb::option::option_def_group
11088 make_watch_options_def_group (watch_options *opts)
11089 {
11090   return {{watch_option_defs}, opts};
11091 }
11092
11093 /* A helper function that looks for the "-location" argument and then
11094    calls watch_command_1.  */
11095
11096 static void
11097 watch_maybe_just_location (const char *arg, int accessflag, int from_tty)
11098 {
11099   watch_options opts;
11100   auto grp = make_watch_options_def_group (&opts);
11101   gdb::option::process_options
11102     (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, grp);
11103   if (arg != nullptr && *arg == '\0')
11104     arg = nullptr;
11105
11106   watch_command_1 (arg, accessflag, from_tty, opts.location, false);
11107 }
11108
11109 /* Command completion for 'watch', 'awatch', and 'rwatch' commands.   */
11110 static void
11111 watch_command_completer (struct cmd_list_element *ignore,
11112                          completion_tracker &tracker,
11113                          const char *text, const char * /*word*/)
11114 {
11115   const auto group = make_watch_options_def_group (nullptr);
11116   if (gdb::option::complete_options
11117       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND, group))
11118     return;
11119
11120   const char *word = advance_to_expression_complete_word_point (tracker, text);
11121   expression_completer (ignore, tracker, text, word);
11122 }
11123
11124 static void
11125 watch_command (const char *arg, int from_tty)
11126 {
11127   watch_maybe_just_location (arg, hw_write, from_tty);
11128 }
11129
11130 void
11131 rwatch_command_wrapper (const char *arg, int from_tty, bool internal)
11132 {
11133   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11134 }
11135
11136 static void
11137 rwatch_command (const char *arg, int from_tty)
11138 {
11139   watch_maybe_just_location (arg, hw_read, from_tty);
11140 }
11141
11142 void
11143 awatch_command_wrapper (const char *arg, int from_tty, bool internal)
11144 {
11145   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11146 }
11147
11148 static void
11149 awatch_command (const char *arg, int from_tty)
11150 {
11151   watch_maybe_just_location (arg, hw_access, from_tty);
11152 }
11153 \f
11154
11155 /* Data for the FSM that manages the until(location)/advance commands
11156    in infcmd.c.  Here because it uses the mechanisms of
11157    breakpoints.  */
11158
11159 struct until_break_fsm : public thread_fsm
11160 {
11161   /* The thread that was current when the command was executed.  */
11162   int thread;
11163
11164   /* The breakpoint set at the return address in the caller frame,
11165      plus breakpoints at all the destination locations.  */
11166   std::vector<breakpoint_up> breakpoints;
11167
11168   until_break_fsm (struct interp *cmd_interp, int thread,
11169                    std::vector<breakpoint_up> &&breakpoints)
11170     : thread_fsm (cmd_interp),
11171       thread (thread),
11172       breakpoints (std::move (breakpoints))
11173   {
11174   }
11175
11176   void clean_up (struct thread_info *thread) override;
11177   bool should_stop (struct thread_info *thread) override;
11178   enum async_reply_reason do_async_reply_reason () override;
11179 };
11180
11181 /* Implementation of the 'should_stop' FSM method for the
11182    until(location)/advance commands.  */
11183
11184 bool
11185 until_break_fsm::should_stop (struct thread_info *tp)
11186 {
11187   for (const breakpoint_up &bp : breakpoints)
11188     if (bpstat_find_breakpoint (tp->control.stop_bpstat,
11189                                 bp.get ()) != NULL)
11190       {
11191         set_finished ();
11192         break;
11193       }
11194
11195   return true;
11196 }
11197
11198 /* Implementation of the 'clean_up' FSM method for the
11199    until(location)/advance commands.  */
11200
11201 void
11202 until_break_fsm::clean_up (struct thread_info *)
11203 {
11204   /* Clean up our temporary breakpoints.  */
11205   breakpoints.clear ();
11206   delete_longjmp_breakpoint (thread);
11207 }
11208
11209 /* Implementation of the 'async_reply_reason' FSM method for the
11210    until(location)/advance commands.  */
11211
11212 enum async_reply_reason
11213 until_break_fsm::do_async_reply_reason ()
11214 {
11215   return EXEC_ASYNC_LOCATION_REACHED;
11216 }
11217
11218 void
11219 until_break_command (const char *arg, int from_tty, int anywhere)
11220 {
11221   struct frame_info *frame;
11222   struct gdbarch *frame_gdbarch;
11223   struct frame_id stack_frame_id;
11224   struct frame_id caller_frame_id;
11225   int thread;
11226   struct thread_info *tp;
11227
11228   clear_proceed_status (0);
11229
11230   /* Set a breakpoint where the user wants it and at return from
11231      this function.  */
11232
11233   event_location_up location = string_to_event_location (&arg, current_language);
11234
11235   std::vector<symtab_and_line> sals
11236     = (last_displayed_sal_is_valid ()
11237        ? decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
11238                         get_last_displayed_symtab (),
11239                         get_last_displayed_line ())
11240        : decode_line_1 (location.get (), DECODE_LINE_FUNFIRSTLINE,
11241                         NULL, NULL, 0));
11242
11243   if (sals.empty ())
11244     error (_("Couldn't get information on specified line."));
11245
11246   if (*arg)
11247     error (_("Junk at end of arguments."));
11248
11249   tp = inferior_thread ();
11250   thread = tp->global_num;
11251
11252   /* Note linespec handling above invalidates the frame chain.
11253      Installing a breakpoint also invalidates the frame chain (as it
11254      may need to switch threads), so do any frame handling before
11255      that.  */
11256
11257   frame = get_selected_frame (NULL);
11258   frame_gdbarch = get_frame_arch (frame);
11259   stack_frame_id = get_stack_frame_id (frame);
11260   caller_frame_id = frame_unwind_caller_id (frame);
11261
11262   /* Keep within the current frame, or in frames called by the current
11263      one.  */
11264
11265   std::vector<breakpoint_up> breakpoints;
11266
11267   gdb::optional<delete_longjmp_breakpoint_cleanup> lj_deleter;
11268
11269   if (frame_id_p (caller_frame_id))
11270     {
11271       struct symtab_and_line sal2;
11272       struct gdbarch *caller_gdbarch;
11273
11274       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11275       sal2.pc = frame_unwind_caller_pc (frame);
11276       caller_gdbarch = frame_unwind_caller_arch (frame);
11277
11278       breakpoint_up caller_breakpoint
11279         = set_momentary_breakpoint (caller_gdbarch, sal2,
11280                                     caller_frame_id, bp_until);
11281       breakpoints.emplace_back (std::move (caller_breakpoint));
11282
11283       set_longjmp_breakpoint (tp, caller_frame_id);
11284       lj_deleter.emplace (thread);
11285     }
11286
11287   /* set_momentary_breakpoint could invalidate FRAME.  */
11288   frame = NULL;
11289
11290   /* If the user told us to continue until a specified location, we
11291      don't specify a frame at which we need to stop.  Otherwise,
11292      specify the selected frame, because we want to stop only at the
11293      very same frame.  */
11294   frame_id stop_frame_id = anywhere ? null_frame_id : stack_frame_id;
11295
11296   for (symtab_and_line &sal : sals)
11297     {
11298       resolve_sal_pc (&sal);
11299
11300       breakpoint_up location_breakpoint
11301         = set_momentary_breakpoint (frame_gdbarch, sal,
11302                                     stop_frame_id, bp_until);
11303       breakpoints.emplace_back (std::move (location_breakpoint));
11304     }
11305
11306   tp->thread_fsm = new until_break_fsm (command_interp (), tp->global_num,
11307                                         std::move (breakpoints));
11308
11309   if (lj_deleter)
11310     lj_deleter->release ();
11311
11312   proceed (-1, GDB_SIGNAL_DEFAULT);
11313 }
11314
11315 /* This function attempts to parse an optional "if <cond>" clause
11316    from the arg string.  If one is not found, it returns NULL.
11317
11318    Else, it returns a pointer to the condition string.  (It does not
11319    attempt to evaluate the string against a particular block.)  And,
11320    it updates arg to point to the first character following the parsed
11321    if clause in the arg string.  */
11322
11323 const char *
11324 ep_parse_optional_if_clause (const char **arg)
11325 {
11326   const char *cond_string;
11327
11328   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11329     return NULL;
11330
11331   /* Skip the "if" keyword.  */
11332   (*arg) += 2;
11333
11334   /* Skip any extra leading whitespace, and record the start of the
11335      condition string.  */
11336   *arg = skip_spaces (*arg);
11337   cond_string = *arg;
11338
11339   /* Assume that the condition occupies the remainder of the arg
11340      string.  */
11341   (*arg) += strlen (cond_string);
11342
11343   return cond_string;
11344 }
11345
11346 /* Commands to deal with catching events, such as signals, exceptions,
11347    process start/exit, etc.  */
11348
11349 typedef enum
11350 {
11351   catch_fork_temporary, catch_vfork_temporary,
11352   catch_fork_permanent, catch_vfork_permanent
11353 }
11354 catch_fork_kind;
11355
11356 static void
11357 catch_fork_command_1 (const char *arg, int from_tty,
11358                       struct cmd_list_element *command)
11359 {
11360   struct gdbarch *gdbarch = get_current_arch ();
11361   const char *cond_string = NULL;
11362   catch_fork_kind fork_kind;
11363
11364   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11365   bool temp = (fork_kind == catch_fork_temporary
11366                || fork_kind == catch_vfork_temporary);
11367
11368   if (!arg)
11369     arg = "";
11370   arg = skip_spaces (arg);
11371
11372   /* The allowed syntax is:
11373      catch [v]fork
11374      catch [v]fork if <cond>
11375
11376      First, check if there's an if clause.  */
11377   cond_string = ep_parse_optional_if_clause (&arg);
11378
11379   if ((*arg != '\0') && !isspace (*arg))
11380     error (_("Junk at end of arguments."));
11381
11382   /* If this target supports it, create a fork or vfork catchpoint
11383      and enable reporting of such events.  */
11384   switch (fork_kind)
11385     {
11386     case catch_fork_temporary:
11387     case catch_fork_permanent:
11388       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11389                                           &catch_fork_breakpoint_ops);
11390       break;
11391     case catch_vfork_temporary:
11392     case catch_vfork_permanent:
11393       create_fork_vfork_event_catchpoint (gdbarch, temp, cond_string,
11394                                           &catch_vfork_breakpoint_ops);
11395       break;
11396     default:
11397       error (_("unsupported or unknown fork kind; cannot catch it"));
11398       break;
11399     }
11400 }
11401
11402 static void
11403 catch_exec_command_1 (const char *arg, int from_tty,
11404                       struct cmd_list_element *command)
11405 {
11406   struct gdbarch *gdbarch = get_current_arch ();
11407   const char *cond_string = NULL;
11408   bool temp = get_cmd_context (command) == CATCH_TEMPORARY;
11409
11410   if (!arg)
11411     arg = "";
11412   arg = skip_spaces (arg);
11413
11414   /* The allowed syntax is:
11415      catch exec
11416      catch exec if <cond>
11417
11418      First, check if there's an if clause.  */
11419   cond_string = ep_parse_optional_if_clause (&arg);
11420
11421   if ((*arg != '\0') && !isspace (*arg))
11422     error (_("Junk at end of arguments."));
11423
11424   std::unique_ptr<exec_catchpoint> c (new exec_catchpoint ());
11425   init_catchpoint (c.get (), gdbarch, temp, cond_string,
11426                    &catch_exec_breakpoint_ops);
11427   c->exec_pathname = NULL;
11428
11429   install_breakpoint (0, std::move (c), 1);
11430 }
11431
11432 void
11433 init_ada_exception_breakpoint (struct breakpoint *b,
11434                                struct gdbarch *gdbarch,
11435                                struct symtab_and_line sal,
11436                                const char *addr_string,
11437                                const struct breakpoint_ops *ops,
11438                                int tempflag,
11439                                int enabled,
11440                                int from_tty)
11441 {
11442   if (from_tty)
11443     {
11444       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11445       if (!loc_gdbarch)
11446         loc_gdbarch = gdbarch;
11447
11448       describe_other_breakpoints (loc_gdbarch,
11449                                   sal.pspace, sal.pc, sal.section, -1);
11450       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11451          version for exception catchpoints, because two catchpoints
11452          used for different exception names will use the same address.
11453          In this case, a "breakpoint ... also set at..." warning is
11454          unproductive.  Besides, the warning phrasing is also a bit
11455          inappropriate, we should use the word catchpoint, and tell
11456          the user what type of catchpoint it is.  The above is good
11457          enough for now, though.  */
11458     }
11459
11460   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
11461
11462   b->enable_state = enabled ? bp_enabled : bp_disabled;
11463   b->disposition = tempflag ? disp_del : disp_donttouch;
11464   b->location = string_to_event_location (&addr_string,
11465                                           language_def (language_ada));
11466   b->language = language_ada;
11467 }
11468
11469 \f
11470
11471 /* Compare two breakpoints and return a strcmp-like result.  */
11472
11473 static int
11474 compare_breakpoints (const breakpoint *a, const breakpoint *b)
11475 {
11476   uintptr_t ua = (uintptr_t) a;
11477   uintptr_t ub = (uintptr_t) b;
11478
11479   if (a->number < b->number)
11480     return -1;
11481   else if (a->number > b->number)
11482     return 1;
11483
11484   /* Now sort by address, in case we see, e..g, two breakpoints with
11485      the number 0.  */
11486   if (ua < ub)
11487     return -1;
11488   return ua > ub ? 1 : 0;
11489 }
11490
11491 /* Delete breakpoints by address or line.  */
11492
11493 static void
11494 clear_command (const char *arg, int from_tty)
11495 {
11496   struct breakpoint *b;
11497   int default_match;
11498
11499   std::vector<symtab_and_line> decoded_sals;
11500   symtab_and_line last_sal;
11501   gdb::array_view<symtab_and_line> sals;
11502   if (arg)
11503     {
11504       decoded_sals
11505         = decode_line_with_current_source (arg,
11506                                            (DECODE_LINE_FUNFIRSTLINE
11507                                             | DECODE_LINE_LIST_MODE));
11508       default_match = 0;
11509       sals = decoded_sals;
11510     }
11511   else
11512     {
11513       /* Set sal's line, symtab, pc, and pspace to the values
11514          corresponding to the last call to print_frame_info.  If the
11515          codepoint is not valid, this will set all the fields to 0.  */
11516       last_sal = get_last_displayed_sal ();
11517       if (last_sal.symtab == 0)
11518         error (_("No source file specified."));
11519
11520       default_match = 1;
11521       sals = last_sal;
11522     }
11523
11524   /* We don't call resolve_sal_pc here.  That's not as bad as it
11525      seems, because all existing breakpoints typically have both
11526      file/line and pc set.  So, if clear is given file/line, we can
11527      match this to existing breakpoint without obtaining pc at all.
11528
11529      We only support clearing given the address explicitly 
11530      present in breakpoint table.  Say, we've set breakpoint 
11531      at file:line.  There were several PC values for that file:line,
11532      due to optimization, all in one block.
11533
11534      We've picked one PC value.  If "clear" is issued with another
11535      PC corresponding to the same file:line, the breakpoint won't
11536      be cleared.  We probably can still clear the breakpoint, but 
11537      since the other PC value is never presented to user, user
11538      can only find it by guessing, and it does not seem important
11539      to support that.  */
11540
11541   /* For each line spec given, delete bps which correspond to it.  Do
11542      it in two passes, solely to preserve the current behavior that
11543      from_tty is forced true if we delete more than one
11544      breakpoint.  */
11545
11546   std::vector<struct breakpoint *> found;
11547   for (const auto &sal : sals)
11548     {
11549       const char *sal_fullname;
11550
11551       /* If exact pc given, clear bpts at that pc.
11552          If line given (pc == 0), clear all bpts on specified line.
11553          If defaulting, clear all bpts on default line
11554          or at default pc.
11555
11556          defaulting    sal.pc != 0    tests to do
11557
11558          0              1             pc
11559          1              1             pc _and_ line
11560          0              0             line
11561          1              0             <can't happen> */
11562
11563       sal_fullname = (sal.symtab == NULL
11564                       ? NULL : symtab_to_fullname (sal.symtab));
11565
11566       /* Find all matching breakpoints and add them to 'found'.  */
11567       ALL_BREAKPOINTS (b)
11568         {
11569           int match = 0;
11570           /* Are we going to delete b?  */
11571           if (b->type != bp_none && !is_watchpoint (b))
11572             {
11573               struct bp_location *loc = b->loc;
11574               for (; loc; loc = loc->next)
11575                 {
11576                   /* If the user specified file:line, don't allow a PC
11577                      match.  This matches historical gdb behavior.  */
11578                   int pc_match = (!sal.explicit_line
11579                                   && sal.pc
11580                                   && (loc->pspace == sal.pspace)
11581                                   && (loc->address == sal.pc)
11582                                   && (!section_is_overlay (loc->section)
11583                                       || loc->section == sal.section));
11584                   int line_match = 0;
11585
11586                   if ((default_match || sal.explicit_line)
11587                       && loc->symtab != NULL
11588                       && sal_fullname != NULL
11589                       && sal.pspace == loc->pspace
11590                       && loc->line_number == sal.line
11591                       && filename_cmp (symtab_to_fullname (loc->symtab),
11592                                        sal_fullname) == 0)
11593                     line_match = 1;
11594
11595                   if (pc_match || line_match)
11596                     {
11597                       match = 1;
11598                       break;
11599                     }
11600                 }
11601             }
11602
11603           if (match)
11604             found.push_back (b);
11605         }
11606     }
11607
11608   /* Now go thru the 'found' chain and delete them.  */
11609   if (found.empty ())
11610     {
11611       if (arg)
11612         error (_("No breakpoint at %s."), arg);
11613       else
11614         error (_("No breakpoint at this line."));
11615     }
11616
11617   /* Remove duplicates from the vec.  */
11618   std::sort (found.begin (), found.end (),
11619              [] (const breakpoint *bp_a, const breakpoint *bp_b)
11620              {
11621                return compare_breakpoints (bp_a, bp_b) < 0;
11622              });
11623   found.erase (std::unique (found.begin (), found.end (),
11624                             [] (const breakpoint *bp_a, const breakpoint *bp_b)
11625                             {
11626                               return compare_breakpoints (bp_a, bp_b) == 0;
11627                             }),
11628                found.end ());
11629
11630   if (found.size () > 1)
11631     from_tty = 1;       /* Always report if deleted more than one.  */
11632   if (from_tty)
11633     {
11634       if (found.size () == 1)
11635         printf_unfiltered (_("Deleted breakpoint "));
11636       else
11637         printf_unfiltered (_("Deleted breakpoints "));
11638     }
11639
11640   for (breakpoint *iter : found)
11641     {
11642       if (from_tty)
11643         printf_unfiltered ("%d ", iter->number);
11644       delete_breakpoint (iter);
11645     }
11646   if (from_tty)
11647     putchar_unfiltered ('\n');
11648 }
11649 \f
11650 /* Delete breakpoint in BS if they are `delete' breakpoints and
11651    all breakpoints that are marked for deletion, whether hit or not.
11652    This is called after any breakpoint is hit, or after errors.  */
11653
11654 void
11655 breakpoint_auto_delete (bpstat bs)
11656 {
11657   struct breakpoint *b, *b_tmp;
11658
11659   for (; bs; bs = bs->next)
11660     if (bs->breakpoint_at
11661         && bs->breakpoint_at->disposition == disp_del
11662         && bs->stop)
11663       delete_breakpoint (bs->breakpoint_at);
11664
11665   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11666   {
11667     if (b->disposition == disp_del_at_next_stop)
11668       delete_breakpoint (b);
11669   }
11670 }
11671
11672 /* A comparison function for bp_location AP and BP being interfaced to
11673    std::sort.  Sort elements primarily by their ADDRESS (no matter what
11674    bl_address_is_meaningful says), secondarily by ordering first
11675    permanent elements and terciarily just ensuring the array is sorted
11676    stable way despite std::sort being an unstable algorithm.  */
11677
11678 static int
11679 bp_location_is_less_than (const bp_location *a, const bp_location *b)
11680 {
11681   if (a->address != b->address)
11682     return a->address < b->address;
11683
11684   /* Sort locations at the same address by their pspace number, keeping
11685      locations of the same inferior (in a multi-inferior environment)
11686      grouped.  */
11687
11688   if (a->pspace->num != b->pspace->num)
11689     return a->pspace->num < b->pspace->num;
11690
11691   /* Sort permanent breakpoints first.  */
11692   if (a->permanent != b->permanent)
11693     return a->permanent > b->permanent;
11694
11695   /* Sort by type in order to make duplicate determination easier.
11696      See update_global_location_list.  This is kept in sync with
11697      breakpoint_locations_match.  */
11698   if (a->loc_type < b->loc_type)
11699     return true;
11700
11701   /* Likewise, for range-breakpoints, sort by length.  */
11702   if (a->loc_type == bp_loc_hardware_breakpoint
11703       && b->loc_type == bp_loc_hardware_breakpoint
11704       && a->length < b->length)
11705     return true;
11706
11707   /* Make the internal GDB representation stable across GDB runs
11708      where A and B memory inside GDB can differ.  Breakpoint locations of
11709      the same type at the same address can be sorted in arbitrary order.  */
11710
11711   if (a->owner->number != b->owner->number)
11712     return a->owner->number < b->owner->number;
11713
11714   return a < b;
11715 }
11716
11717 /* Set bp_locations_placed_address_before_address_max and
11718    bp_locations_shadow_len_after_address_max according to the current
11719    content of the bp_locations array.  */
11720
11721 static void
11722 bp_locations_target_extensions_update (void)
11723 {
11724   struct bp_location *bl, **blp_tmp;
11725
11726   bp_locations_placed_address_before_address_max = 0;
11727   bp_locations_shadow_len_after_address_max = 0;
11728
11729   ALL_BP_LOCATIONS (bl, blp_tmp)
11730     {
11731       CORE_ADDR start, end, addr;
11732
11733       if (!bp_location_has_shadow (bl))
11734         continue;
11735
11736       start = bl->target_info.placed_address;
11737       end = start + bl->target_info.shadow_len;
11738
11739       gdb_assert (bl->address >= start);
11740       addr = bl->address - start;
11741       if (addr > bp_locations_placed_address_before_address_max)
11742         bp_locations_placed_address_before_address_max = addr;
11743
11744       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11745
11746       gdb_assert (bl->address < end);
11747       addr = end - bl->address;
11748       if (addr > bp_locations_shadow_len_after_address_max)
11749         bp_locations_shadow_len_after_address_max = addr;
11750     }
11751 }
11752
11753 /* Download tracepoint locations if they haven't been.  */
11754
11755 static void
11756 download_tracepoint_locations (void)
11757 {
11758   struct breakpoint *b;
11759   enum tribool can_download_tracepoint = TRIBOOL_UNKNOWN;
11760
11761   scoped_restore_current_pspace_and_thread restore_pspace_thread;
11762
11763   ALL_TRACEPOINTS (b)
11764     {
11765       struct bp_location *bl;
11766       struct tracepoint *t;
11767       int bp_location_downloaded = 0;
11768
11769       if ((b->type == bp_fast_tracepoint
11770            ? !may_insert_fast_tracepoints
11771            : !may_insert_tracepoints))
11772         continue;
11773
11774       if (can_download_tracepoint == TRIBOOL_UNKNOWN)
11775         {
11776           if (target_can_download_tracepoint ())
11777             can_download_tracepoint = TRIBOOL_TRUE;
11778           else
11779             can_download_tracepoint = TRIBOOL_FALSE;
11780         }
11781
11782       if (can_download_tracepoint == TRIBOOL_FALSE)
11783         break;
11784
11785       for (bl = b->loc; bl; bl = bl->next)
11786         {
11787           /* In tracepoint, locations are _never_ duplicated, so
11788              should_be_inserted is equivalent to
11789              unduplicated_should_be_inserted.  */
11790           if (!should_be_inserted (bl) || bl->inserted)
11791             continue;
11792
11793           switch_to_program_space_and_thread (bl->pspace);
11794
11795           target_download_tracepoint (bl);
11796
11797           bl->inserted = 1;
11798           bp_location_downloaded = 1;
11799         }
11800       t = (struct tracepoint *) b;
11801       t->number_on_target = b->number;
11802       if (bp_location_downloaded)
11803         gdb::observers::breakpoint_modified.notify (b);
11804     }
11805 }
11806
11807 /* Swap the insertion/duplication state between two locations.  */
11808
11809 static void
11810 swap_insertion (struct bp_location *left, struct bp_location *right)
11811 {
11812   const int left_inserted = left->inserted;
11813   const int left_duplicate = left->duplicate;
11814   const int left_needs_update = left->needs_update;
11815   const struct bp_target_info left_target_info = left->target_info;
11816
11817   /* Locations of tracepoints can never be duplicated.  */
11818   if (is_tracepoint (left->owner))
11819     gdb_assert (!left->duplicate);
11820   if (is_tracepoint (right->owner))
11821     gdb_assert (!right->duplicate);
11822
11823   left->inserted = right->inserted;
11824   left->duplicate = right->duplicate;
11825   left->needs_update = right->needs_update;
11826   left->target_info = right->target_info;
11827   right->inserted = left_inserted;
11828   right->duplicate = left_duplicate;
11829   right->needs_update = left_needs_update;
11830   right->target_info = left_target_info;
11831 }
11832
11833 /* Force the re-insertion of the locations at ADDRESS.  This is called
11834    once a new/deleted/modified duplicate location is found and we are evaluating
11835    conditions on the target's side.  Such conditions need to be updated on
11836    the target.  */
11837
11838 static void
11839 force_breakpoint_reinsertion (struct bp_location *bl)
11840 {
11841   struct bp_location **locp = NULL, **loc2p;
11842   struct bp_location *loc;
11843   CORE_ADDR address = 0;
11844   int pspace_num;
11845
11846   address = bl->address;
11847   pspace_num = bl->pspace->num;
11848
11849   /* This is only meaningful if the target is
11850      evaluating conditions and if the user has
11851      opted for condition evaluation on the target's
11852      side.  */
11853   if (gdb_evaluates_breakpoint_condition_p ()
11854       || !target_supports_evaluation_of_breakpoint_conditions ())
11855     return;
11856
11857   /* Flag all breakpoint locations with this address and
11858      the same program space as the location
11859      as "its condition has changed".  We need to
11860      update the conditions on the target's side.  */
11861   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11862     {
11863       loc = *loc2p;
11864
11865       if (!is_breakpoint (loc->owner)
11866           || pspace_num != loc->pspace->num)
11867         continue;
11868
11869       /* Flag the location appropriately.  We use a different state to
11870          let everyone know that we already updated the set of locations
11871          with addr bl->address and program space bl->pspace.  This is so
11872          we don't have to keep calling these functions just to mark locations
11873          that have already been marked.  */
11874       loc->condition_changed = condition_updated;
11875
11876       /* Free the agent expression bytecode as well.  We will compute
11877          it later on.  */
11878       loc->cond_bytecode.reset ();
11879     }
11880 }
11881
11882 /* Called whether new breakpoints are created, or existing breakpoints
11883    deleted, to update the global location list and recompute which
11884    locations are duplicate of which.
11885
11886    The INSERT_MODE flag determines whether locations may not, may, or
11887    shall be inserted now.  See 'enum ugll_insert_mode' for more
11888    info.  */
11889
11890 static void
11891 update_global_location_list (enum ugll_insert_mode insert_mode)
11892 {
11893   struct breakpoint *b;
11894   struct bp_location **locp, *loc;
11895   /* Last breakpoint location address that was marked for update.  */
11896   CORE_ADDR last_addr = 0;
11897   /* Last breakpoint location program space that was marked for update.  */
11898   int last_pspace_num = -1;
11899
11900   /* Used in the duplicates detection below.  When iterating over all
11901      bp_locations, points to the first bp_location of a given address.
11902      Breakpoints and watchpoints of different types are never
11903      duplicates of each other.  Keep one pointer for each type of
11904      breakpoint/watchpoint, so we only need to loop over all locations
11905      once.  */
11906   struct bp_location *bp_loc_first;  /* breakpoint */
11907   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11908   struct bp_location *awp_loc_first; /* access watchpoint */
11909   struct bp_location *rwp_loc_first; /* read watchpoint */
11910
11911   /* Saved former bp_locations array which we compare against the newly
11912      built bp_locations from the current state of ALL_BREAKPOINTS.  */
11913   struct bp_location **old_locp;
11914   unsigned old_locations_count;
11915   gdb::unique_xmalloc_ptr<struct bp_location *> old_locations (bp_locations);
11916
11917   old_locations_count = bp_locations_count;
11918   bp_locations = NULL;
11919   bp_locations_count = 0;
11920
11921   ALL_BREAKPOINTS (b)
11922     for (loc = b->loc; loc; loc = loc->next)
11923       bp_locations_count++;
11924
11925   bp_locations = XNEWVEC (struct bp_location *, bp_locations_count);
11926   locp = bp_locations;
11927   ALL_BREAKPOINTS (b)
11928     for (loc = b->loc; loc; loc = loc->next)
11929       *locp++ = loc;
11930
11931   /* See if we need to "upgrade" a software breakpoint to a hardware
11932      breakpoint.  Do this before deciding whether locations are
11933      duplicates.  Also do this before sorting because sorting order
11934      depends on location type.  */
11935   for (locp = bp_locations;
11936        locp < bp_locations + bp_locations_count;
11937        locp++)
11938     {
11939       loc = *locp;
11940       if (!loc->inserted && should_be_inserted (loc))
11941         handle_automatic_hardware_breakpoints (loc);
11942     }
11943
11944   std::sort (bp_locations, bp_locations + bp_locations_count,
11945              bp_location_is_less_than);
11946
11947   bp_locations_target_extensions_update ();
11948
11949   /* Identify bp_location instances that are no longer present in the
11950      new list, and therefore should be freed.  Note that it's not
11951      necessary that those locations should be removed from inferior --
11952      if there's another location at the same address (previously
11953      marked as duplicate), we don't need to remove/insert the
11954      location.
11955      
11956      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11957      and former bp_location array state respectively.  */
11958
11959   locp = bp_locations;
11960   for (old_locp = old_locations.get ();
11961        old_locp < old_locations.get () + old_locations_count;
11962        old_locp++)
11963     {
11964       struct bp_location *old_loc = *old_locp;
11965       struct bp_location **loc2p;
11966
11967       /* Tells if 'old_loc' is found among the new locations.  If
11968          not, we have to free it.  */
11969       int found_object = 0;
11970       /* Tells if the location should remain inserted in the target.  */
11971       int keep_in_target = 0;
11972       int removed = 0;
11973
11974       /* Skip LOCP entries which will definitely never be needed.
11975          Stop either at or being the one matching OLD_LOC.  */
11976       while (locp < bp_locations + bp_locations_count
11977              && (*locp)->address < old_loc->address)
11978         locp++;
11979
11980       for (loc2p = locp;
11981            (loc2p < bp_locations + bp_locations_count
11982             && (*loc2p)->address == old_loc->address);
11983            loc2p++)
11984         {
11985           /* Check if this is a new/duplicated location or a duplicated
11986              location that had its condition modified.  If so, we want to send
11987              its condition to the target if evaluation of conditions is taking
11988              place there.  */
11989           if ((*loc2p)->condition_changed == condition_modified
11990               && (last_addr != old_loc->address
11991                   || last_pspace_num != old_loc->pspace->num))
11992             {
11993               force_breakpoint_reinsertion (*loc2p);
11994               last_pspace_num = old_loc->pspace->num;
11995             }
11996
11997           if (*loc2p == old_loc)
11998             found_object = 1;
11999         }
12000
12001       /* We have already handled this address, update it so that we don't
12002          have to go through updates again.  */
12003       last_addr = old_loc->address;
12004
12005       /* Target-side condition evaluation: Handle deleted locations.  */
12006       if (!found_object)
12007         force_breakpoint_reinsertion (old_loc);
12008
12009       /* If this location is no longer present, and inserted, look if
12010          there's maybe a new location at the same address.  If so,
12011          mark that one inserted, and don't remove this one.  This is
12012          needed so that we don't have a time window where a breakpoint
12013          at certain location is not inserted.  */
12014
12015       if (old_loc->inserted)
12016         {
12017           /* If the location is inserted now, we might have to remove
12018              it.  */
12019
12020           if (found_object && should_be_inserted (old_loc))
12021             {
12022               /* The location is still present in the location list,
12023                  and still should be inserted.  Don't do anything.  */
12024               keep_in_target = 1;
12025             }
12026           else
12027             {
12028               /* This location still exists, but it won't be kept in the
12029                  target since it may have been disabled.  We proceed to
12030                  remove its target-side condition.  */
12031
12032               /* The location is either no longer present, or got
12033                  disabled.  See if there's another location at the
12034                  same address, in which case we don't need to remove
12035                  this one from the target.  */
12036
12037               /* OLD_LOC comes from existing struct breakpoint.  */
12038               if (bl_address_is_meaningful (old_loc))
12039                 {
12040                   for (loc2p = locp;
12041                        (loc2p < bp_locations + bp_locations_count
12042                         && (*loc2p)->address == old_loc->address);
12043                        loc2p++)
12044                     {
12045                       struct bp_location *loc2 = *loc2p;
12046
12047                       if (loc2 == old_loc)
12048                         continue;
12049
12050                       if (breakpoint_locations_match (loc2, old_loc))
12051                         {
12052                           /* Read watchpoint locations are switched to
12053                              access watchpoints, if the former are not
12054                              supported, but the latter are.  */
12055                           if (is_hardware_watchpoint (old_loc->owner))
12056                             {
12057                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12058                               loc2->watchpoint_type = old_loc->watchpoint_type;
12059                             }
12060
12061                           /* loc2 is a duplicated location. We need to check
12062                              if it should be inserted in case it will be
12063                              unduplicated.  */
12064                           if (unduplicated_should_be_inserted (loc2))
12065                             {
12066                               swap_insertion (old_loc, loc2);
12067                               keep_in_target = 1;
12068                               break;
12069                             }
12070                         }
12071                     }
12072                 }
12073             }
12074
12075           if (!keep_in_target)
12076             {
12077               if (remove_breakpoint (old_loc))
12078                 {
12079                   /* This is just about all we can do.  We could keep
12080                      this location on the global list, and try to
12081                      remove it next time, but there's no particular
12082                      reason why we will succeed next time.
12083                      
12084                      Note that at this point, old_loc->owner is still
12085                      valid, as delete_breakpoint frees the breakpoint
12086                      only after calling us.  */
12087                   printf_filtered (_("warning: Error removing "
12088                                      "breakpoint %d\n"), 
12089                                    old_loc->owner->number);
12090                 }
12091               removed = 1;
12092             }
12093         }
12094
12095       if (!found_object)
12096         {
12097           if (removed && target_is_non_stop_p ()
12098               && need_moribund_for_location_type (old_loc))
12099             {
12100               /* This location was removed from the target.  In
12101                  non-stop mode, a race condition is possible where
12102                  we've removed a breakpoint, but stop events for that
12103                  breakpoint are already queued and will arrive later.
12104                  We apply an heuristic to be able to distinguish such
12105                  SIGTRAPs from other random SIGTRAPs: we keep this
12106                  breakpoint location for a bit, and will retire it
12107                  after we see some number of events.  The theory here
12108                  is that reporting of events should, "on the average",
12109                  be fair, so after a while we'll see events from all
12110                  threads that have anything of interest, and no longer
12111                  need to keep this breakpoint location around.  We
12112                  don't hold locations forever so to reduce chances of
12113                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12114                  SIGTRAP.
12115
12116                  The heuristic failing can be disastrous on
12117                  decr_pc_after_break targets.
12118
12119                  On decr_pc_after_break targets, like e.g., x86-linux,
12120                  if we fail to recognize a late breakpoint SIGTRAP,
12121                  because events_till_retirement has reached 0 too
12122                  soon, we'll fail to do the PC adjustment, and report
12123                  a random SIGTRAP to the user.  When the user resumes
12124                  the inferior, it will most likely immediately crash
12125                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12126                  corrupted, because of being resumed e.g., in the
12127                  middle of a multi-byte instruction, or skipped a
12128                  one-byte instruction.  This was actually seen happen
12129                  on native x86-linux, and should be less rare on
12130                  targets that do not support new thread events, like
12131                  remote, due to the heuristic depending on
12132                  thread_count.
12133
12134                  Mistaking a random SIGTRAP for a breakpoint trap
12135                  causes similar symptoms (PC adjustment applied when
12136                  it shouldn't), but then again, playing with SIGTRAPs
12137                  behind the debugger's back is asking for trouble.
12138
12139                  Since hardware watchpoint traps are always
12140                  distinguishable from other traps, so we don't need to
12141                  apply keep hardware watchpoint moribund locations
12142                  around.  We simply always ignore hardware watchpoint
12143                  traps we can no longer explain.  */
12144
12145               process_stratum_target *proc_target = nullptr;
12146               for (inferior *inf : all_inferiors ())
12147                 if (inf->pspace == old_loc->pspace)
12148                   {
12149                     proc_target = inf->process_target ();
12150                     break;
12151                   }
12152               if (proc_target != nullptr)
12153                 old_loc->events_till_retirement
12154                   = 3 * (thread_count (proc_target) + 1);
12155               else
12156                 old_loc->events_till_retirement = 1;
12157               old_loc->owner = NULL;
12158
12159               moribund_locations.push_back (old_loc);
12160             }
12161           else
12162             {
12163               old_loc->owner = NULL;
12164               decref_bp_location (&old_loc);
12165             }
12166         }
12167     }
12168
12169   /* Rescan breakpoints at the same address and section, marking the
12170      first one as "first" and any others as "duplicates".  This is so
12171      that the bpt instruction is only inserted once.  If we have a
12172      permanent breakpoint at the same place as BPT, make that one the
12173      official one, and the rest as duplicates.  Permanent breakpoints
12174      are sorted first for the same address.
12175
12176      Do the same for hardware watchpoints, but also considering the
12177      watchpoint's type (regular/access/read) and length.  */
12178
12179   bp_loc_first = NULL;
12180   wp_loc_first = NULL;
12181   awp_loc_first = NULL;
12182   rwp_loc_first = NULL;
12183   ALL_BP_LOCATIONS (loc, locp)
12184     {
12185       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12186          non-NULL.  */
12187       struct bp_location **loc_first_p;
12188       b = loc->owner;
12189
12190       if (!unduplicated_should_be_inserted (loc)
12191           || !bl_address_is_meaningful (loc)
12192           /* Don't detect duplicate for tracepoint locations because they are
12193            never duplicated.  See the comments in field `duplicate' of
12194            `struct bp_location'.  */
12195           || is_tracepoint (b))
12196         {
12197           /* Clear the condition modification flag.  */
12198           loc->condition_changed = condition_unchanged;
12199           continue;
12200         }
12201
12202       if (b->type == bp_hardware_watchpoint)
12203         loc_first_p = &wp_loc_first;
12204       else if (b->type == bp_read_watchpoint)
12205         loc_first_p = &rwp_loc_first;
12206       else if (b->type == bp_access_watchpoint)
12207         loc_first_p = &awp_loc_first;
12208       else
12209         loc_first_p = &bp_loc_first;
12210
12211       if (*loc_first_p == NULL
12212           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12213           || !breakpoint_locations_match (loc, *loc_first_p))
12214         {
12215           *loc_first_p = loc;
12216           loc->duplicate = 0;
12217
12218           if (is_breakpoint (loc->owner) && loc->condition_changed)
12219             {
12220               loc->needs_update = 1;
12221               /* Clear the condition modification flag.  */
12222               loc->condition_changed = condition_unchanged;
12223             }
12224           continue;
12225         }
12226
12227
12228       /* This and the above ensure the invariant that the first location
12229          is not duplicated, and is the inserted one.
12230          All following are marked as duplicated, and are not inserted.  */
12231       if (loc->inserted)
12232         swap_insertion (loc, *loc_first_p);
12233       loc->duplicate = 1;
12234
12235       /* Clear the condition modification flag.  */
12236       loc->condition_changed = condition_unchanged;
12237     }
12238
12239   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12240     {
12241       if (insert_mode != UGLL_DONT_INSERT)
12242         insert_breakpoint_locations ();
12243       else
12244         {
12245           /* Even though the caller told us to not insert new
12246              locations, we may still need to update conditions on the
12247              target's side of breakpoints that were already inserted
12248              if the target is evaluating breakpoint conditions.  We
12249              only update conditions for locations that are marked
12250              "needs_update".  */
12251           update_inserted_breakpoint_locations ();
12252         }
12253     }
12254
12255   if (insert_mode != UGLL_DONT_INSERT)
12256     download_tracepoint_locations ();
12257 }
12258
12259 void
12260 breakpoint_retire_moribund (void)
12261 {
12262   for (int ix = 0; ix < moribund_locations.size (); ++ix)
12263     {
12264       struct bp_location *loc = moribund_locations[ix];
12265       if (--(loc->events_till_retirement) == 0)
12266         {
12267           decref_bp_location (&loc);
12268           unordered_remove (moribund_locations, ix);
12269           --ix;
12270         }
12271     }
12272 }
12273
12274 static void
12275 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12276 {
12277
12278   try
12279     {
12280       update_global_location_list (insert_mode);
12281     }
12282   catch (const gdb_exception_error &e)
12283     {
12284     }
12285 }
12286
12287 /* Clear BKP from a BPS.  */
12288
12289 static void
12290 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12291 {
12292   bpstat bs;
12293
12294   for (bs = bps; bs; bs = bs->next)
12295     if (bs->breakpoint_at == bpt)
12296       {
12297         bs->breakpoint_at = NULL;
12298         bs->old_val = NULL;
12299         /* bs->commands will be freed later.  */
12300       }
12301 }
12302
12303 /* Callback for iterate_over_threads.  */
12304 static int
12305 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12306 {
12307   struct breakpoint *bpt = (struct breakpoint *) data;
12308
12309   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12310   return 0;
12311 }
12312
12313 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12314    callbacks.  */
12315
12316 static void
12317 say_where (struct breakpoint *b)
12318 {
12319   struct value_print_options opts;
12320
12321   get_user_print_options (&opts);
12322
12323   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12324      single string.  */
12325   if (b->loc == NULL)
12326     {
12327       /* For pending locations, the output differs slightly based
12328          on b->extra_string.  If this is non-NULL, it contains either
12329          a condition or dprintf arguments.  */
12330       if (b->extra_string == NULL)
12331         {
12332           printf_filtered (_(" (%s) pending."),
12333                            event_location_to_string (b->location.get ()));
12334         }
12335       else if (b->type == bp_dprintf)
12336         {
12337           printf_filtered (_(" (%s,%s) pending."),
12338                            event_location_to_string (b->location.get ()),
12339                            b->extra_string);
12340         }
12341       else
12342         {
12343           printf_filtered (_(" (%s %s) pending."),
12344                            event_location_to_string (b->location.get ()),
12345                            b->extra_string);
12346         }
12347     }
12348   else
12349     {
12350       if (opts.addressprint || b->loc->symtab == NULL)
12351         printf_filtered (" at %ps",
12352                          styled_string (address_style.style (),
12353                                         paddress (b->loc->gdbarch,
12354                                                   b->loc->address)));
12355       if (b->loc->symtab != NULL)
12356         {
12357           /* If there is a single location, we can print the location
12358              more nicely.  */
12359           if (b->loc->next == NULL)
12360             {
12361               const char *filename
12362                 = symtab_to_filename_for_display (b->loc->symtab);
12363               printf_filtered (": file %ps, line %d.",
12364                                styled_string (file_name_style.style (),
12365                                               filename),
12366                                b->loc->line_number);
12367             }
12368           else
12369             /* This is not ideal, but each location may have a
12370                different file name, and this at least reflects the
12371                real situation somewhat.  */
12372             printf_filtered (": %s.",
12373                              event_location_to_string (b->location.get ()));
12374         }
12375
12376       if (b->loc->next)
12377         {
12378           struct bp_location *loc = b->loc;
12379           int n = 0;
12380           for (; loc; loc = loc->next)
12381             ++n;
12382           printf_filtered (" (%d locations)", n);
12383         }
12384     }
12385 }
12386
12387 bp_location::~bp_location ()
12388 {
12389   xfree (function_name);
12390 }
12391
12392 /* Destructor for the breakpoint base class.  */
12393
12394 breakpoint::~breakpoint ()
12395 {
12396   xfree (this->cond_string);
12397   xfree (this->extra_string);
12398 }
12399
12400 static struct bp_location *
12401 base_breakpoint_allocate_location (struct breakpoint *self)
12402 {
12403   return new bp_location (self);
12404 }
12405
12406 static void
12407 base_breakpoint_re_set (struct breakpoint *b)
12408 {
12409   /* Nothing to re-set. */
12410 }
12411
12412 #define internal_error_pure_virtual_called() \
12413   gdb_assert_not_reached ("pure virtual function called")
12414
12415 static int
12416 base_breakpoint_insert_location (struct bp_location *bl)
12417 {
12418   internal_error_pure_virtual_called ();
12419 }
12420
12421 static int
12422 base_breakpoint_remove_location (struct bp_location *bl,
12423                                  enum remove_bp_reason reason)
12424 {
12425   internal_error_pure_virtual_called ();
12426 }
12427
12428 static int
12429 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12430                                 const address_space *aspace,
12431                                 CORE_ADDR bp_addr,
12432                                 const struct target_waitstatus *ws)
12433 {
12434   internal_error_pure_virtual_called ();
12435 }
12436
12437 static void
12438 base_breakpoint_check_status (bpstat bs)
12439 {
12440   /* Always stop.   */
12441 }
12442
12443 /* A "works_in_software_mode" breakpoint_ops method that just internal
12444    errors.  */
12445
12446 static int
12447 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12448 {
12449   internal_error_pure_virtual_called ();
12450 }
12451
12452 /* A "resources_needed" breakpoint_ops method that just internal
12453    errors.  */
12454
12455 static int
12456 base_breakpoint_resources_needed (const struct bp_location *bl)
12457 {
12458   internal_error_pure_virtual_called ();
12459 }
12460
12461 static enum print_stop_action
12462 base_breakpoint_print_it (bpstat bs)
12463 {
12464   internal_error_pure_virtual_called ();
12465 }
12466
12467 static void
12468 base_breakpoint_print_one_detail (const struct breakpoint *self,
12469                                   struct ui_out *uiout)
12470 {
12471   /* nothing */
12472 }
12473
12474 static void
12475 base_breakpoint_print_mention (struct breakpoint *b)
12476 {
12477   internal_error_pure_virtual_called ();
12478 }
12479
12480 static void
12481 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12482 {
12483   internal_error_pure_virtual_called ();
12484 }
12485
12486 static void
12487 base_breakpoint_create_sals_from_location
12488   (struct event_location *location,
12489    struct linespec_result *canonical,
12490    enum bptype type_wanted)
12491 {
12492   internal_error_pure_virtual_called ();
12493 }
12494
12495 static void
12496 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12497                                         struct linespec_result *c,
12498                                         gdb::unique_xmalloc_ptr<char> cond_string,
12499                                         gdb::unique_xmalloc_ptr<char> extra_string,
12500                                         enum bptype type_wanted,
12501                                         enum bpdisp disposition,
12502                                         int thread,
12503                                         int task, int ignore_count,
12504                                         const struct breakpoint_ops *o,
12505                                         int from_tty, int enabled,
12506                                         int internal, unsigned flags)
12507 {
12508   internal_error_pure_virtual_called ();
12509 }
12510
12511 static std::vector<symtab_and_line>
12512 base_breakpoint_decode_location (struct breakpoint *b,
12513                                  struct event_location *location,
12514                                  struct program_space *search_pspace)
12515 {
12516   internal_error_pure_virtual_called ();
12517 }
12518
12519 /* The default 'explains_signal' method.  */
12520
12521 static int
12522 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12523 {
12524   return 1;
12525 }
12526
12527 /* The default "after_condition_true" method.  */
12528
12529 static void
12530 base_breakpoint_after_condition_true (struct bpstats *bs)
12531 {
12532   /* Nothing to do.   */
12533 }
12534
12535 struct breakpoint_ops base_breakpoint_ops =
12536 {
12537   base_breakpoint_allocate_location,
12538   base_breakpoint_re_set,
12539   base_breakpoint_insert_location,
12540   base_breakpoint_remove_location,
12541   base_breakpoint_breakpoint_hit,
12542   base_breakpoint_check_status,
12543   base_breakpoint_resources_needed,
12544   base_breakpoint_works_in_software_mode,
12545   base_breakpoint_print_it,
12546   NULL,
12547   base_breakpoint_print_one_detail,
12548   base_breakpoint_print_mention,
12549   base_breakpoint_print_recreate,
12550   base_breakpoint_create_sals_from_location,
12551   base_breakpoint_create_breakpoints_sal,
12552   base_breakpoint_decode_location,
12553   base_breakpoint_explains_signal,
12554   base_breakpoint_after_condition_true,
12555 };
12556
12557 /* Default breakpoint_ops methods.  */
12558
12559 static void
12560 bkpt_re_set (struct breakpoint *b)
12561 {
12562   /* FIXME: is this still reachable?  */
12563   if (breakpoint_event_location_empty_p (b))
12564     {
12565       /* Anything without a location can't be re-set.  */
12566       delete_breakpoint (b);
12567       return;
12568     }
12569
12570   breakpoint_re_set_default (b);
12571 }
12572
12573 static int
12574 bkpt_insert_location (struct bp_location *bl)
12575 {
12576   CORE_ADDR addr = bl->target_info.reqstd_address;
12577
12578   bl->target_info.kind = breakpoint_kind (bl, &addr);
12579   bl->target_info.placed_address = addr;
12580
12581   if (bl->loc_type == bp_loc_hardware_breakpoint)
12582     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
12583   else
12584     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
12585 }
12586
12587 static int
12588 bkpt_remove_location (struct bp_location *bl, enum remove_bp_reason reason)
12589 {
12590   if (bl->loc_type == bp_loc_hardware_breakpoint)
12591     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12592   else
12593     return target_remove_breakpoint (bl->gdbarch, &bl->target_info, reason);
12594 }
12595
12596 static int
12597 bkpt_breakpoint_hit (const struct bp_location *bl,
12598                      const address_space *aspace, CORE_ADDR bp_addr,
12599                      const struct target_waitstatus *ws)
12600 {
12601   if (ws->kind != TARGET_WAITKIND_STOPPED
12602       || ws->value.sig != GDB_SIGNAL_TRAP)
12603     return 0;
12604
12605   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12606                                  aspace, bp_addr))
12607     return 0;
12608
12609   if (overlay_debugging         /* unmapped overlay section */
12610       && section_is_overlay (bl->section)
12611       && !section_is_mapped (bl->section))
12612     return 0;
12613
12614   return 1;
12615 }
12616
12617 static int
12618 dprintf_breakpoint_hit (const struct bp_location *bl,
12619                         const address_space *aspace, CORE_ADDR bp_addr,
12620                         const struct target_waitstatus *ws)
12621 {
12622   if (dprintf_style == dprintf_style_agent
12623       && target_can_run_breakpoint_commands ())
12624     {
12625       /* An agent-style dprintf never causes a stop.  If we see a trap
12626          for this address it must be for a breakpoint that happens to
12627          be set at the same address.  */
12628       return 0;
12629     }
12630
12631   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
12632 }
12633
12634 static int
12635 bkpt_resources_needed (const struct bp_location *bl)
12636 {
12637   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12638
12639   return 1;
12640 }
12641
12642 static enum print_stop_action
12643 bkpt_print_it (bpstat bs)
12644 {
12645   struct breakpoint *b;
12646   const struct bp_location *bl;
12647   int bp_temp;
12648   struct ui_out *uiout = current_uiout;
12649
12650   gdb_assert (bs->bp_location_at != NULL);
12651
12652   bl = bs->bp_location_at.get ();
12653   b = bs->breakpoint_at;
12654
12655   bp_temp = b->disposition == disp_del;
12656   if (bl->address != bl->requested_address)
12657     breakpoint_adjustment_warning (bl->requested_address,
12658                                    bl->address,
12659                                    b->number, 1);
12660   annotate_breakpoint (b->number);
12661   maybe_print_thread_hit_breakpoint (uiout);
12662
12663   if (uiout->is_mi_like_p ())
12664     {
12665       uiout->field_string ("reason",
12666                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12667       uiout->field_string ("disp", bpdisp_text (b->disposition));
12668     }
12669   if (bp_temp)
12670     uiout->message ("Temporary breakpoint %pF, ",
12671                     signed_field ("bkptno", b->number));
12672   else
12673     uiout->message ("Breakpoint %pF, ",
12674                     signed_field ("bkptno", b->number));
12675
12676   return PRINT_SRC_AND_LOC;
12677 }
12678
12679 static void
12680 bkpt_print_mention (struct breakpoint *b)
12681 {
12682   if (current_uiout->is_mi_like_p ())
12683     return;
12684
12685   switch (b->type)
12686     {
12687     case bp_breakpoint:
12688     case bp_gnu_ifunc_resolver:
12689       if (b->disposition == disp_del)
12690         printf_filtered (_("Temporary breakpoint"));
12691       else
12692         printf_filtered (_("Breakpoint"));
12693       printf_filtered (_(" %d"), b->number);
12694       if (b->type == bp_gnu_ifunc_resolver)
12695         printf_filtered (_(" at gnu-indirect-function resolver"));
12696       break;
12697     case bp_hardware_breakpoint:
12698       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12699       break;
12700     case bp_dprintf:
12701       printf_filtered (_("Dprintf %d"), b->number);
12702       break;
12703     }
12704
12705   say_where (b);
12706 }
12707
12708 static void
12709 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12710 {
12711   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12712     fprintf_unfiltered (fp, "tbreak");
12713   else if (tp->type == bp_breakpoint)
12714     fprintf_unfiltered (fp, "break");
12715   else if (tp->type == bp_hardware_breakpoint
12716            && tp->disposition == disp_del)
12717     fprintf_unfiltered (fp, "thbreak");
12718   else if (tp->type == bp_hardware_breakpoint)
12719     fprintf_unfiltered (fp, "hbreak");
12720   else
12721     internal_error (__FILE__, __LINE__,
12722                     _("unhandled breakpoint type %d"), (int) tp->type);
12723
12724   fprintf_unfiltered (fp, " %s",
12725                       event_location_to_string (tp->location.get ()));
12726
12727   /* Print out extra_string if this breakpoint is pending.  It might
12728      contain, for example, conditions that were set by the user.  */
12729   if (tp->loc == NULL && tp->extra_string != NULL)
12730     fprintf_unfiltered (fp, " %s", tp->extra_string);
12731
12732   print_recreate_thread (tp, fp);
12733 }
12734
12735 static void
12736 bkpt_create_sals_from_location (struct event_location *location,
12737                                 struct linespec_result *canonical,
12738                                 enum bptype type_wanted)
12739 {
12740   create_sals_from_location_default (location, canonical, type_wanted);
12741 }
12742
12743 static void
12744 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12745                              struct linespec_result *canonical,
12746                              gdb::unique_xmalloc_ptr<char> cond_string,
12747                              gdb::unique_xmalloc_ptr<char> extra_string,
12748                              enum bptype type_wanted,
12749                              enum bpdisp disposition,
12750                              int thread,
12751                              int task, int ignore_count,
12752                              const struct breakpoint_ops *ops,
12753                              int from_tty, int enabled,
12754                              int internal, unsigned flags)
12755 {
12756   create_breakpoints_sal_default (gdbarch, canonical,
12757                                   std::move (cond_string),
12758                                   std::move (extra_string),
12759                                   type_wanted,
12760                                   disposition, thread, task,
12761                                   ignore_count, ops, from_tty,
12762                                   enabled, internal, flags);
12763 }
12764
12765 static std::vector<symtab_and_line>
12766 bkpt_decode_location (struct breakpoint *b,
12767                       struct event_location *location,
12768                       struct program_space *search_pspace)
12769 {
12770   return decode_location_default (b, location, search_pspace);
12771 }
12772
12773 /* Virtual table for internal breakpoints.  */
12774
12775 static void
12776 internal_bkpt_re_set (struct breakpoint *b)
12777 {
12778   switch (b->type)
12779     {
12780       /* Delete overlay event and longjmp master breakpoints; they
12781          will be reset later by breakpoint_re_set.  */
12782     case bp_overlay_event:
12783     case bp_longjmp_master:
12784     case bp_std_terminate_master:
12785     case bp_exception_master:
12786       delete_breakpoint (b);
12787       break;
12788
12789       /* This breakpoint is special, it's set up when the inferior
12790          starts and we really don't want to touch it.  */
12791     case bp_shlib_event:
12792
12793       /* Like bp_shlib_event, this breakpoint type is special.  Once
12794          it is set up, we do not want to touch it.  */
12795     case bp_thread_event:
12796       break;
12797     }
12798 }
12799
12800 static void
12801 internal_bkpt_check_status (bpstat bs)
12802 {
12803   if (bs->breakpoint_at->type == bp_shlib_event)
12804     {
12805       /* If requested, stop when the dynamic linker notifies GDB of
12806          events.  This allows the user to get control and place
12807          breakpoints in initializer routines for dynamically loaded
12808          objects (among other things).  */
12809       bs->stop = stop_on_solib_events;
12810       bs->print = stop_on_solib_events;
12811     }
12812   else
12813     bs->stop = 0;
12814 }
12815
12816 static enum print_stop_action
12817 internal_bkpt_print_it (bpstat bs)
12818 {
12819   struct breakpoint *b;
12820
12821   b = bs->breakpoint_at;
12822
12823   switch (b->type)
12824     {
12825     case bp_shlib_event:
12826       /* Did we stop because the user set the stop_on_solib_events
12827          variable?  (If so, we report this as a generic, "Stopped due
12828          to shlib event" message.) */
12829       print_solib_event (0);
12830       break;
12831
12832     case bp_thread_event:
12833       /* Not sure how we will get here.
12834          GDB should not stop for these breakpoints.  */
12835       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12836       break;
12837
12838     case bp_overlay_event:
12839       /* By analogy with the thread event, GDB should not stop for these.  */
12840       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12841       break;
12842
12843     case bp_longjmp_master:
12844       /* These should never be enabled.  */
12845       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12846       break;
12847
12848     case bp_std_terminate_master:
12849       /* These should never be enabled.  */
12850       printf_filtered (_("std::terminate Master Breakpoint: "
12851                          "gdb should not stop!\n"));
12852       break;
12853
12854     case bp_exception_master:
12855       /* These should never be enabled.  */
12856       printf_filtered (_("Exception Master Breakpoint: "
12857                          "gdb should not stop!\n"));
12858       break;
12859     }
12860
12861   return PRINT_NOTHING;
12862 }
12863
12864 static void
12865 internal_bkpt_print_mention (struct breakpoint *b)
12866 {
12867   /* Nothing to mention.  These breakpoints are internal.  */
12868 }
12869
12870 /* Virtual table for momentary breakpoints  */
12871
12872 static void
12873 momentary_bkpt_re_set (struct breakpoint *b)
12874 {
12875   /* Keep temporary breakpoints, which can be encountered when we step
12876      over a dlopen call and solib_add is resetting the breakpoints.
12877      Otherwise these should have been blown away via the cleanup chain
12878      or by breakpoint_init_inferior when we rerun the executable.  */
12879 }
12880
12881 static void
12882 momentary_bkpt_check_status (bpstat bs)
12883 {
12884   /* Nothing.  The point of these breakpoints is causing a stop.  */
12885 }
12886
12887 static enum print_stop_action
12888 momentary_bkpt_print_it (bpstat bs)
12889 {
12890   return PRINT_UNKNOWN;
12891 }
12892
12893 static void
12894 momentary_bkpt_print_mention (struct breakpoint *b)
12895 {
12896   /* Nothing to mention.  These breakpoints are internal.  */
12897 }
12898
12899 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12900
12901    It gets cleared already on the removal of the first one of such placed
12902    breakpoints.  This is OK as they get all removed altogether.  */
12903
12904 longjmp_breakpoint::~longjmp_breakpoint ()
12905 {
12906   thread_info *tp = find_thread_global_id (this->thread);
12907
12908   if (tp != NULL)
12909     tp->initiating_frame = null_frame_id;
12910 }
12911
12912 /* Specific methods for probe breakpoints.  */
12913
12914 static int
12915 bkpt_probe_insert_location (struct bp_location *bl)
12916 {
12917   int v = bkpt_insert_location (bl);
12918
12919   if (v == 0)
12920     {
12921       /* The insertion was successful, now let's set the probe's semaphore
12922          if needed.  */
12923       bl->probe.prob->set_semaphore (bl->probe.objfile, bl->gdbarch);
12924     }
12925
12926   return v;
12927 }
12928
12929 static int
12930 bkpt_probe_remove_location (struct bp_location *bl,
12931                             enum remove_bp_reason reason)
12932 {
12933   /* Let's clear the semaphore before removing the location.  */
12934   bl->probe.prob->clear_semaphore (bl->probe.objfile, bl->gdbarch);
12935
12936   return bkpt_remove_location (bl, reason);
12937 }
12938
12939 static void
12940 bkpt_probe_create_sals_from_location (struct event_location *location,
12941                                       struct linespec_result *canonical,
12942                                       enum bptype type_wanted)
12943 {
12944   struct linespec_sals lsal;
12945
12946   lsal.sals = parse_probes (location, NULL, canonical);
12947   lsal.canonical
12948     = xstrdup (event_location_to_string (canonical->location.get ()));
12949   canonical->lsals.push_back (std::move (lsal));
12950 }
12951
12952 static std::vector<symtab_and_line>
12953 bkpt_probe_decode_location (struct breakpoint *b,
12954                             struct event_location *location,
12955                             struct program_space *search_pspace)
12956 {
12957   std::vector<symtab_and_line> sals = parse_probes (location, search_pspace, NULL);
12958   if (sals.empty ())
12959     error (_("probe not found"));
12960   return sals;
12961 }
12962
12963 /* The breakpoint_ops structure to be used in tracepoints.  */
12964
12965 static void
12966 tracepoint_re_set (struct breakpoint *b)
12967 {
12968   breakpoint_re_set_default (b);
12969 }
12970
12971 static int
12972 tracepoint_breakpoint_hit (const struct bp_location *bl,
12973                            const address_space *aspace, CORE_ADDR bp_addr,
12974                            const struct target_waitstatus *ws)
12975 {
12976   /* By definition, the inferior does not report stops at
12977      tracepoints.  */
12978   return 0;
12979 }
12980
12981 static void
12982 tracepoint_print_one_detail (const struct breakpoint *self,
12983                              struct ui_out *uiout)
12984 {
12985   struct tracepoint *tp = (struct tracepoint *) self;
12986   if (!tp->static_trace_marker_id.empty ())
12987     {
12988       gdb_assert (self->type == bp_static_tracepoint);
12989
12990       uiout->message ("\tmarker id is %pF\n",
12991                       string_field ("static-tracepoint-marker-string-id",
12992                                     tp->static_trace_marker_id.c_str ()));
12993     }
12994 }
12995
12996 static void
12997 tracepoint_print_mention (struct breakpoint *b)
12998 {
12999   if (current_uiout->is_mi_like_p ())
13000     return;
13001
13002   switch (b->type)
13003     {
13004     case bp_tracepoint:
13005       printf_filtered (_("Tracepoint"));
13006       printf_filtered (_(" %d"), b->number);
13007       break;
13008     case bp_fast_tracepoint:
13009       printf_filtered (_("Fast tracepoint"));
13010       printf_filtered (_(" %d"), b->number);
13011       break;
13012     case bp_static_tracepoint:
13013       printf_filtered (_("Static tracepoint"));
13014       printf_filtered (_(" %d"), b->number);
13015       break;
13016     default:
13017       internal_error (__FILE__, __LINE__,
13018                       _("unhandled tracepoint type %d"), (int) b->type);
13019     }
13020
13021   say_where (b);
13022 }
13023
13024 static void
13025 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13026 {
13027   struct tracepoint *tp = (struct tracepoint *) self;
13028
13029   if (self->type == bp_fast_tracepoint)
13030     fprintf_unfiltered (fp, "ftrace");
13031   else if (self->type == bp_static_tracepoint)
13032     fprintf_unfiltered (fp, "strace");
13033   else if (self->type == bp_tracepoint)
13034     fprintf_unfiltered (fp, "trace");
13035   else
13036     internal_error (__FILE__, __LINE__,
13037                     _("unhandled tracepoint type %d"), (int) self->type);
13038
13039   fprintf_unfiltered (fp, " %s",
13040                       event_location_to_string (self->location.get ()));
13041   print_recreate_thread (self, fp);
13042
13043   if (tp->pass_count)
13044     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13045 }
13046
13047 static void
13048 tracepoint_create_sals_from_location (struct event_location *location,
13049                                       struct linespec_result *canonical,
13050                                       enum bptype type_wanted)
13051 {
13052   create_sals_from_location_default (location, canonical, type_wanted);
13053 }
13054
13055 static void
13056 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13057                                    struct linespec_result *canonical,
13058                                    gdb::unique_xmalloc_ptr<char> cond_string,
13059                                    gdb::unique_xmalloc_ptr<char> extra_string,
13060                                    enum bptype type_wanted,
13061                                    enum bpdisp disposition,
13062                                    int thread,
13063                                    int task, int ignore_count,
13064                                    const struct breakpoint_ops *ops,
13065                                    int from_tty, int enabled,
13066                                    int internal, unsigned flags)
13067 {
13068   create_breakpoints_sal_default (gdbarch, canonical,
13069                                   std::move (cond_string),
13070                                   std::move (extra_string),
13071                                   type_wanted,
13072                                   disposition, thread, task,
13073                                   ignore_count, ops, from_tty,
13074                                   enabled, internal, flags);
13075 }
13076
13077 static std::vector<symtab_and_line>
13078 tracepoint_decode_location (struct breakpoint *b,
13079                             struct event_location *location,
13080                             struct program_space *search_pspace)
13081 {
13082   return decode_location_default (b, location, search_pspace);
13083 }
13084
13085 struct breakpoint_ops tracepoint_breakpoint_ops;
13086
13087 /* Virtual table for tracepoints on static probes.  */
13088
13089 static void
13090 tracepoint_probe_create_sals_from_location
13091   (struct event_location *location,
13092    struct linespec_result *canonical,
13093    enum bptype type_wanted)
13094 {
13095   /* We use the same method for breakpoint on probes.  */
13096   bkpt_probe_create_sals_from_location (location, canonical, type_wanted);
13097 }
13098
13099 static std::vector<symtab_and_line>
13100 tracepoint_probe_decode_location (struct breakpoint *b,
13101                                   struct event_location *location,
13102                                   struct program_space *search_pspace)
13103 {
13104   /* We use the same method for breakpoint on probes.  */
13105   return bkpt_probe_decode_location (b, location, search_pspace);
13106 }
13107
13108 /* Dprintf breakpoint_ops methods.  */
13109
13110 static void
13111 dprintf_re_set (struct breakpoint *b)
13112 {
13113   breakpoint_re_set_default (b);
13114
13115   /* extra_string should never be non-NULL for dprintf.  */
13116   gdb_assert (b->extra_string != NULL);
13117
13118   /* 1 - connect to target 1, that can run breakpoint commands.
13119      2 - create a dprintf, which resolves fine.
13120      3 - disconnect from target 1
13121      4 - connect to target 2, that can NOT run breakpoint commands.
13122
13123      After steps #3/#4, you'll want the dprintf command list to
13124      be updated, because target 1 and 2 may well return different
13125      answers for target_can_run_breakpoint_commands().
13126      Given absence of finer grained resetting, we get to do
13127      it all the time.  */
13128   if (b->extra_string != NULL)
13129     update_dprintf_command_list (b);
13130 }
13131
13132 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13133
13134 static void
13135 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13136 {
13137   fprintf_unfiltered (fp, "dprintf %s,%s",
13138                       event_location_to_string (tp->location.get ()),
13139                       tp->extra_string);
13140   print_recreate_thread (tp, fp);
13141 }
13142
13143 /* Implement the "after_condition_true" breakpoint_ops method for
13144    dprintf.
13145
13146    dprintf's are implemented with regular commands in their command
13147    list, but we run the commands here instead of before presenting the
13148    stop to the user, as dprintf's don't actually cause a stop.  This
13149    also makes it so that the commands of multiple dprintfs at the same
13150    address are all handled.  */
13151
13152 static void
13153 dprintf_after_condition_true (struct bpstats *bs)
13154 {
13155   struct bpstats tmp_bs;
13156   struct bpstats *tmp_bs_p = &tmp_bs;
13157
13158   /* dprintf's never cause a stop.  This wasn't set in the
13159      check_status hook instead because that would make the dprintf's
13160      condition not be evaluated.  */
13161   bs->stop = 0;
13162
13163   /* Run the command list here.  Take ownership of it instead of
13164      copying.  We never want these commands to run later in
13165      bpstat_do_actions, if a breakpoint that causes a stop happens to
13166      be set at same address as this dprintf, or even if running the
13167      commands here throws.  */
13168   tmp_bs.commands = bs->commands;
13169   bs->commands = NULL;
13170
13171   bpstat_do_actions_1 (&tmp_bs_p);
13172
13173   /* 'tmp_bs.commands' will usually be NULL by now, but
13174      bpstat_do_actions_1 may return early without processing the whole
13175      list.  */
13176 }
13177
13178 /* The breakpoint_ops structure to be used on static tracepoints with
13179    markers (`-m').  */
13180
13181 static void
13182 strace_marker_create_sals_from_location (struct event_location *location,
13183                                          struct linespec_result *canonical,
13184                                          enum bptype type_wanted)
13185 {
13186   struct linespec_sals lsal;
13187   const char *arg_start, *arg;
13188
13189   arg = arg_start = get_linespec_location (location)->spec_string;
13190   lsal.sals = decode_static_tracepoint_spec (&arg);
13191
13192   std::string str (arg_start, arg - arg_start);
13193   const char *ptr = str.c_str ();
13194   canonical->location
13195     = new_linespec_location (&ptr, symbol_name_match_type::FULL);
13196
13197   lsal.canonical
13198     = xstrdup (event_location_to_string (canonical->location.get ()));
13199   canonical->lsals.push_back (std::move (lsal));
13200 }
13201
13202 static void
13203 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13204                                       struct linespec_result *canonical,
13205                                       gdb::unique_xmalloc_ptr<char> cond_string,
13206                                       gdb::unique_xmalloc_ptr<char> extra_string,
13207                                       enum bptype type_wanted,
13208                                       enum bpdisp disposition,
13209                                       int thread,
13210                                       int task, int ignore_count,
13211                                       const struct breakpoint_ops *ops,
13212                                       int from_tty, int enabled,
13213                                       int internal, unsigned flags)
13214 {
13215   const linespec_sals &lsal = canonical->lsals[0];
13216
13217   /* If the user is creating a static tracepoint by marker id
13218      (strace -m MARKER_ID), then store the sals index, so that
13219      breakpoint_re_set can try to match up which of the newly
13220      found markers corresponds to this one, and, don't try to
13221      expand multiple locations for each sal, given than SALS
13222      already should contain all sals for MARKER_ID.  */
13223
13224   for (size_t i = 0; i < lsal.sals.size (); i++)
13225     {
13226       event_location_up location
13227         = copy_event_location (canonical->location.get ());
13228
13229       std::unique_ptr<tracepoint> tp (new tracepoint ());
13230       init_breakpoint_sal (tp.get (), gdbarch, lsal.sals[i],
13231                            std::move (location), NULL,
13232                            std::move (cond_string),
13233                            std::move (extra_string),
13234                            type_wanted, disposition,
13235                            thread, task, ignore_count, ops,
13236                            from_tty, enabled, internal, flags,
13237                            canonical->special_display);
13238       /* Given that its possible to have multiple markers with
13239          the same string id, if the user is creating a static
13240          tracepoint by marker id ("strace -m MARKER_ID"), then
13241          store the sals index, so that breakpoint_re_set can
13242          try to match up which of the newly found markers
13243          corresponds to this one  */
13244       tp->static_trace_marker_id_idx = i;
13245
13246       install_breakpoint (internal, std::move (tp), 0);
13247     }
13248 }
13249
13250 static std::vector<symtab_and_line>
13251 strace_marker_decode_location (struct breakpoint *b,
13252                                struct event_location *location,
13253                                struct program_space *search_pspace)
13254 {
13255   struct tracepoint *tp = (struct tracepoint *) b;
13256   const char *s = get_linespec_location (location)->spec_string;
13257
13258   std::vector<symtab_and_line> sals = decode_static_tracepoint_spec (&s);
13259   if (sals.size () > tp->static_trace_marker_id_idx)
13260     {
13261       sals[0] = sals[tp->static_trace_marker_id_idx];
13262       sals.resize (1);
13263       return sals;
13264     }
13265   else
13266     error (_("marker %s not found"), tp->static_trace_marker_id.c_str ());
13267 }
13268
13269 static struct breakpoint_ops strace_marker_breakpoint_ops;
13270
13271 static int
13272 strace_marker_p (struct breakpoint *b)
13273 {
13274   return b->ops == &strace_marker_breakpoint_ops;
13275 }
13276
13277 /* Delete a breakpoint and clean up all traces of it in the data
13278    structures.  */
13279
13280 void
13281 delete_breakpoint (struct breakpoint *bpt)
13282 {
13283   struct breakpoint *b;
13284
13285   gdb_assert (bpt != NULL);
13286
13287   /* Has this bp already been deleted?  This can happen because
13288      multiple lists can hold pointers to bp's.  bpstat lists are
13289      especial culprits.
13290
13291      One example of this happening is a watchpoint's scope bp.  When
13292      the scope bp triggers, we notice that the watchpoint is out of
13293      scope, and delete it.  We also delete its scope bp.  But the
13294      scope bp is marked "auto-deleting", and is already on a bpstat.
13295      That bpstat is then checked for auto-deleting bp's, which are
13296      deleted.
13297
13298      A real solution to this problem might involve reference counts in
13299      bp's, and/or giving them pointers back to their referencing
13300      bpstat's, and teaching delete_breakpoint to only free a bp's
13301      storage when no more references were extent.  A cheaper bandaid
13302      was chosen.  */
13303   if (bpt->type == bp_none)
13304     return;
13305
13306   /* At least avoid this stale reference until the reference counting
13307      of breakpoints gets resolved.  */
13308   if (bpt->related_breakpoint != bpt)
13309     {
13310       struct breakpoint *related;
13311       struct watchpoint *w;
13312
13313       if (bpt->type == bp_watchpoint_scope)
13314         w = (struct watchpoint *) bpt->related_breakpoint;
13315       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13316         w = (struct watchpoint *) bpt;
13317       else
13318         w = NULL;
13319       if (w != NULL)
13320         watchpoint_del_at_next_stop (w);
13321
13322       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13323       for (related = bpt; related->related_breakpoint != bpt;
13324            related = related->related_breakpoint);
13325       related->related_breakpoint = bpt->related_breakpoint;
13326       bpt->related_breakpoint = bpt;
13327     }
13328
13329   /* watch_command_1 creates a watchpoint but only sets its number if
13330      update_watchpoint succeeds in creating its bp_locations.  If there's
13331      a problem in that process, we'll be asked to delete the half-created
13332      watchpoint.  In that case, don't announce the deletion.  */
13333   if (bpt->number)
13334     gdb::observers::breakpoint_deleted.notify (bpt);
13335
13336   if (breakpoint_chain == bpt)
13337     breakpoint_chain = bpt->next;
13338
13339   ALL_BREAKPOINTS (b)
13340     if (b->next == bpt)
13341     {
13342       b->next = bpt->next;
13343       break;
13344     }
13345
13346   /* Be sure no bpstat's are pointing at the breakpoint after it's
13347      been freed.  */
13348   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13349      in all threads for now.  Note that we cannot just remove bpstats
13350      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13351      commands are associated with the bpstat; if we remove it here,
13352      then the later call to bpstat_do_actions (&stop_bpstat); in
13353      event-top.c won't do anything, and temporary breakpoints with
13354      commands won't work.  */
13355
13356   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13357
13358   /* Now that breakpoint is removed from breakpoint list, update the
13359      global location list.  This will remove locations that used to
13360      belong to this breakpoint.  Do this before freeing the breakpoint
13361      itself, since remove_breakpoint looks at location's owner.  It
13362      might be better design to have location completely
13363      self-contained, but it's not the case now.  */
13364   update_global_location_list (UGLL_DONT_INSERT);
13365
13366   /* On the chance that someone will soon try again to delete this
13367      same bp, we mark it as deleted before freeing its storage.  */
13368   bpt->type = bp_none;
13369   delete bpt;
13370 }
13371
13372 /* Iterator function to call a user-provided callback function once
13373    for each of B and its related breakpoints.  */
13374
13375 static void
13376 iterate_over_related_breakpoints (struct breakpoint *b,
13377                                   gdb::function_view<void (breakpoint *)> function)
13378 {
13379   struct breakpoint *related;
13380
13381   related = b;
13382   do
13383     {
13384       struct breakpoint *next;
13385
13386       /* FUNCTION may delete RELATED.  */
13387       next = related->related_breakpoint;
13388
13389       if (next == related)
13390         {
13391           /* RELATED is the last ring entry.  */
13392           function (related);
13393
13394           /* FUNCTION may have deleted it, so we'd never reach back to
13395              B.  There's nothing left to do anyway, so just break
13396              out.  */
13397           break;
13398         }
13399       else
13400         function (related);
13401
13402       related = next;
13403     }
13404   while (related != b);
13405 }
13406
13407 static void
13408 delete_command (const char *arg, int from_tty)
13409 {
13410   struct breakpoint *b, *b_tmp;
13411
13412   dont_repeat ();
13413
13414   if (arg == 0)
13415     {
13416       int breaks_to_delete = 0;
13417
13418       /* Delete all breakpoints if no argument.  Do not delete
13419          internal breakpoints, these have to be deleted with an
13420          explicit breakpoint number argument.  */
13421       ALL_BREAKPOINTS (b)
13422         if (user_breakpoint_p (b))
13423           {
13424             breaks_to_delete = 1;
13425             break;
13426           }
13427
13428       /* Ask user only if there are some breakpoints to delete.  */
13429       if (!from_tty
13430           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13431         {
13432           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13433             if (user_breakpoint_p (b))
13434               delete_breakpoint (b);
13435         }
13436     }
13437   else
13438     map_breakpoint_numbers
13439       (arg, [&] (breakpoint *br)
13440        {
13441          iterate_over_related_breakpoints (br, delete_breakpoint);
13442        });
13443 }
13444
13445 /* Return true if all locations of B bound to PSPACE are pending.  If
13446    PSPACE is NULL, all locations of all program spaces are
13447    considered.  */
13448
13449 static int
13450 all_locations_are_pending (struct breakpoint *b, struct program_space *pspace)
13451 {
13452   struct bp_location *loc;
13453
13454   for (loc = b->loc; loc != NULL; loc = loc->next)
13455     if ((pspace == NULL
13456          || loc->pspace == pspace)
13457         && !loc->shlib_disabled
13458         && !loc->pspace->executing_startup)
13459       return 0;
13460   return 1;
13461 }
13462
13463 /* Subroutine of update_breakpoint_locations to simplify it.
13464    Return non-zero if multiple fns in list LOC have the same name.
13465    Null names are ignored.  */
13466
13467 static int
13468 ambiguous_names_p (struct bp_location *loc)
13469 {
13470   struct bp_location *l;
13471   htab_up htab (htab_create_alloc (13, htab_hash_string, streq_hash, NULL,
13472                                    xcalloc, xfree));
13473
13474   for (l = loc; l != NULL; l = l->next)
13475     {
13476       const char **slot;
13477       const char *name = l->function_name;
13478
13479       /* Allow for some names to be NULL, ignore them.  */
13480       if (name == NULL)
13481         continue;
13482
13483       slot = (const char **) htab_find_slot (htab.get (), (const void *) name,
13484                                              INSERT);
13485       /* NOTE: We can assume slot != NULL here because xcalloc never
13486          returns NULL.  */
13487       if (*slot != NULL)
13488         return 1;
13489       *slot = name;
13490     }
13491
13492   return 0;
13493 }
13494
13495 /* When symbols change, it probably means the sources changed as well,
13496    and it might mean the static tracepoint markers are no longer at
13497    the same address or line numbers they used to be at last we
13498    checked.  Losing your static tracepoints whenever you rebuild is
13499    undesirable.  This function tries to resync/rematch gdb static
13500    tracepoints with the markers on the target, for static tracepoints
13501    that have not been set by marker id.  Static tracepoint that have
13502    been set by marker id are reset by marker id in breakpoint_re_set.
13503    The heuristic is:
13504
13505    1) For a tracepoint set at a specific address, look for a marker at
13506    the old PC.  If one is found there, assume to be the same marker.
13507    If the name / string id of the marker found is different from the
13508    previous known name, assume that means the user renamed the marker
13509    in the sources, and output a warning.
13510
13511    2) For a tracepoint set at a given line number, look for a marker
13512    at the new address of the old line number.  If one is found there,
13513    assume to be the same marker.  If the name / string id of the
13514    marker found is different from the previous known name, assume that
13515    means the user renamed the marker in the sources, and output a
13516    warning.
13517
13518    3) If a marker is no longer found at the same address or line, it
13519    may mean the marker no longer exists.  But it may also just mean
13520    the code changed a bit.  Maybe the user added a few lines of code
13521    that made the marker move up or down (in line number terms).  Ask
13522    the target for info about the marker with the string id as we knew
13523    it.  If found, update line number and address in the matching
13524    static tracepoint.  This will get confused if there's more than one
13525    marker with the same ID (possible in UST, although unadvised
13526    precisely because it confuses tools).  */
13527
13528 static struct symtab_and_line
13529 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13530 {
13531   struct tracepoint *tp = (struct tracepoint *) b;
13532   struct static_tracepoint_marker marker;
13533   CORE_ADDR pc;
13534
13535   pc = sal.pc;
13536   if (sal.line)
13537     find_line_pc (sal.symtab, sal.line, &pc);
13538
13539   if (target_static_tracepoint_marker_at (pc, &marker))
13540     {
13541       if (tp->static_trace_marker_id != marker.str_id)
13542         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13543                  b->number, tp->static_trace_marker_id.c_str (),
13544                  marker.str_id.c_str ());
13545
13546       tp->static_trace_marker_id = std::move (marker.str_id);
13547
13548       return sal;
13549     }
13550
13551   /* Old marker wasn't found on target at lineno.  Try looking it up
13552      by string ID.  */
13553   if (!sal.explicit_pc
13554       && sal.line != 0
13555       && sal.symtab != NULL
13556       && !tp->static_trace_marker_id.empty ())
13557     {
13558       std::vector<static_tracepoint_marker> markers
13559         = target_static_tracepoint_markers_by_strid
13560             (tp->static_trace_marker_id.c_str ());
13561
13562       if (!markers.empty ())
13563         {
13564           struct symbol *sym;
13565           struct static_tracepoint_marker *tpmarker;
13566           struct ui_out *uiout = current_uiout;
13567           struct explicit_location explicit_loc;
13568
13569           tpmarker = &markers[0];
13570
13571           tp->static_trace_marker_id = std::move (tpmarker->str_id);
13572
13573           warning (_("marker for static tracepoint %d (%s) not "
13574                      "found at previous line number"),
13575                    b->number, tp->static_trace_marker_id.c_str ());
13576
13577           symtab_and_line sal2 = find_pc_line (tpmarker->address, 0);
13578           sym = find_pc_sect_function (tpmarker->address, NULL);
13579           uiout->text ("Now in ");
13580           if (sym)
13581             {
13582               uiout->field_string ("func", sym->print_name (),
13583                                    function_name_style.style ());
13584               uiout->text (" at ");
13585             }
13586           uiout->field_string ("file",
13587                                symtab_to_filename_for_display (sal2.symtab),
13588                                file_name_style.style ());
13589           uiout->text (":");
13590
13591           if (uiout->is_mi_like_p ())
13592             {
13593               const char *fullname = symtab_to_fullname (sal2.symtab);
13594
13595               uiout->field_string ("fullname", fullname);
13596             }
13597
13598           uiout->field_signed ("line", sal2.line);
13599           uiout->text ("\n");
13600
13601           b->loc->line_number = sal2.line;
13602           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13603
13604           b->location.reset (NULL);
13605           initialize_explicit_location (&explicit_loc);
13606           explicit_loc.source_filename
13607             = ASTRDUP (symtab_to_filename_for_display (sal2.symtab));
13608           explicit_loc.line_offset.offset = b->loc->line_number;
13609           explicit_loc.line_offset.sign = LINE_OFFSET_NONE;
13610           b->location = new_explicit_location (&explicit_loc);
13611
13612           /* Might be nice to check if function changed, and warn if
13613              so.  */
13614         }
13615     }
13616   return sal;
13617 }
13618
13619 /* Returns 1 iff locations A and B are sufficiently same that
13620    we don't need to report breakpoint as changed.  */
13621
13622 static int
13623 locations_are_equal (struct bp_location *a, struct bp_location *b)
13624 {
13625   while (a && b)
13626     {
13627       if (a->address != b->address)
13628         return 0;
13629
13630       if (a->shlib_disabled != b->shlib_disabled)
13631         return 0;
13632
13633       if (a->enabled != b->enabled)
13634         return 0;
13635
13636       if (a->disabled_by_cond != b->disabled_by_cond)
13637         return 0;
13638
13639       a = a->next;
13640       b = b->next;
13641     }
13642
13643   if ((a == NULL) != (b == NULL))
13644     return 0;
13645
13646   return 1;
13647 }
13648
13649 /* Split all locations of B that are bound to PSPACE out of B's
13650    location list to a separate list and return that list's head.  If
13651    PSPACE is NULL, hoist out all locations of B.  */
13652
13653 static struct bp_location *
13654 hoist_existing_locations (struct breakpoint *b, struct program_space *pspace)
13655 {
13656   struct bp_location head;
13657   struct bp_location *i = b->loc;
13658   struct bp_location **i_link = &b->loc;
13659   struct bp_location *hoisted = &head;
13660
13661   if (pspace == NULL)
13662     {
13663       i = b->loc;
13664       b->loc = NULL;
13665       return i;
13666     }
13667
13668   head.next = NULL;
13669
13670   while (i != NULL)
13671     {
13672       if (i->pspace == pspace)
13673         {
13674           *i_link = i->next;
13675           i->next = NULL;
13676           hoisted->next = i;
13677           hoisted = i;
13678         }
13679       else
13680         i_link = &i->next;
13681       i = *i_link;
13682     }
13683
13684   return head.next;
13685 }
13686
13687 /* Create new breakpoint locations for B (a hardware or software
13688    breakpoint) based on SALS and SALS_END.  If SALS_END.NELTS is not
13689    zero, then B is a ranged breakpoint.  Only recreates locations for
13690    FILTER_PSPACE.  Locations of other program spaces are left
13691    untouched.  */
13692
13693 void
13694 update_breakpoint_locations (struct breakpoint *b,
13695                              struct program_space *filter_pspace,
13696                              gdb::array_view<const symtab_and_line> sals,
13697                              gdb::array_view<const symtab_and_line> sals_end)
13698 {
13699   struct bp_location *existing_locations;
13700
13701   if (!sals_end.empty () && (sals.size () != 1 || sals_end.size () != 1))
13702     {
13703       /* Ranged breakpoints have only one start location and one end
13704          location.  */
13705       b->enable_state = bp_disabled;
13706       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13707                            "multiple locations found\n"),
13708                          b->number);
13709       return;
13710     }
13711
13712   /* If there's no new locations, and all existing locations are
13713      pending, don't do anything.  This optimizes the common case where
13714      all locations are in the same shared library, that was unloaded.
13715      We'd like to retain the location, so that when the library is
13716      loaded again, we don't loose the enabled/disabled status of the
13717      individual locations.  */
13718   if (all_locations_are_pending (b, filter_pspace) && sals.empty ())
13719     return;
13720
13721   existing_locations = hoist_existing_locations (b, filter_pspace);
13722
13723   for (const auto &sal : sals)
13724     {
13725       struct bp_location *new_loc;
13726
13727       switch_to_program_space_and_thread (sal.pspace);
13728
13729       new_loc = add_location_to_breakpoint (b, &sal);
13730
13731       /* Reparse conditions, they might contain references to the
13732          old symtab.  */
13733       if (b->cond_string != NULL)
13734         {
13735           const char *s;
13736
13737           s = b->cond_string;
13738           try
13739             {
13740               new_loc->cond = parse_exp_1 (&s, sal.pc,
13741                                            block_for_pc (sal.pc),
13742                                            0);
13743             }
13744           catch (const gdb_exception_error &e)
13745             {
13746               new_loc->disabled_by_cond = true;
13747             }
13748         }
13749
13750       if (!sals_end.empty ())
13751         {
13752           CORE_ADDR end = find_breakpoint_range_end (sals_end[0]);
13753
13754           new_loc->length = end - sals[0].pc + 1;
13755         }
13756     }
13757
13758   /* If possible, carry over 'disable' status from existing
13759      breakpoints.  */
13760   {
13761     struct bp_location *e = existing_locations;
13762     /* If there are multiple breakpoints with the same function name,
13763        e.g. for inline functions, comparing function names won't work.
13764        Instead compare pc addresses; this is just a heuristic as things
13765        may have moved, but in practice it gives the correct answer
13766        often enough until a better solution is found.  */
13767     int have_ambiguous_names = ambiguous_names_p (b->loc);
13768
13769     for (; e; e = e->next)
13770       {
13771         if ((!e->enabled || e->disabled_by_cond) && e->function_name)
13772           {
13773             struct bp_location *l = b->loc;
13774             if (have_ambiguous_names)
13775               {
13776                 for (; l; l = l->next)
13777                   {
13778                     /* Ignore software vs hardware location type at
13779                        this point, because with "set breakpoint
13780                        auto-hw", after a re-set, locations that were
13781                        hardware can end up as software, or vice versa.
13782                        As mentioned above, this is an heuristic and in
13783                        practice should give the correct answer often
13784                        enough.  */
13785                     if (breakpoint_locations_match (e, l, true))
13786                       {
13787                         l->enabled = e->enabled;
13788                         l->disabled_by_cond = e->disabled_by_cond;
13789                         break;
13790                       }
13791                   }
13792               }
13793             else
13794               {
13795                 for (; l; l = l->next)
13796                   if (l->function_name
13797                       && strcmp (e->function_name, l->function_name) == 0)
13798                     {
13799                       l->enabled = e->enabled;
13800                       l->disabled_by_cond = e->disabled_by_cond;
13801                       break;
13802                     }
13803               }
13804           }
13805       }
13806   }
13807
13808   if (!locations_are_equal (existing_locations, b->loc))
13809     gdb::observers::breakpoint_modified.notify (b);
13810 }
13811
13812 /* Find the SaL locations corresponding to the given LOCATION.
13813    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13814
13815 static std::vector<symtab_and_line>
13816 location_to_sals (struct breakpoint *b, struct event_location *location,
13817                   struct program_space *search_pspace, int *found)
13818 {
13819   struct gdb_exception exception;
13820
13821   gdb_assert (b->ops != NULL);
13822
13823   std::vector<symtab_and_line> sals;
13824
13825   try
13826     {
13827       sals = b->ops->decode_location (b, location, search_pspace);
13828     }
13829   catch (gdb_exception_error &e)
13830     {
13831       int not_found_and_ok = 0;
13832
13833       /* For pending breakpoints, it's expected that parsing will
13834          fail until the right shared library is loaded.  User has
13835          already told to create pending breakpoints and don't need
13836          extra messages.  If breakpoint is in bp_shlib_disabled
13837          state, then user already saw the message about that
13838          breakpoint being disabled, and don't want to see more
13839          errors.  */
13840       if (e.error == NOT_FOUND_ERROR
13841           && (b->condition_not_parsed
13842               || (b->loc != NULL
13843                   && search_pspace != NULL
13844                   && b->loc->pspace != search_pspace)
13845               || (b->loc && b->loc->shlib_disabled)
13846               || (b->loc && b->loc->pspace->executing_startup)
13847               || b->enable_state == bp_disabled))
13848         not_found_and_ok = 1;
13849
13850       if (!not_found_and_ok)
13851         {
13852           /* We surely don't want to warn about the same breakpoint
13853              10 times.  One solution, implemented here, is disable
13854              the breakpoint on error.  Another solution would be to
13855              have separate 'warning emitted' flag.  Since this
13856              happens only when a binary has changed, I don't know
13857              which approach is better.  */
13858           b->enable_state = bp_disabled;
13859           throw;
13860         }
13861
13862       exception = std::move (e);
13863     }
13864
13865   if (exception.reason == 0 || exception.error != NOT_FOUND_ERROR)
13866     {
13867       for (auto &sal : sals)
13868         resolve_sal_pc (&sal);
13869       if (b->condition_not_parsed && b->extra_string != NULL)
13870         {
13871           char *cond_string, *extra_string;
13872           int thread, task;
13873
13874           find_condition_and_thread_for_sals (sals, b->extra_string,
13875                                               &cond_string, &thread,
13876                                               &task, &extra_string);
13877           gdb_assert (b->cond_string == NULL);
13878           if (cond_string)
13879             b->cond_string = cond_string;
13880           b->thread = thread;
13881           b->task = task;
13882           if (extra_string)
13883             {
13884               xfree (b->extra_string);
13885               b->extra_string = extra_string;
13886             }
13887           b->condition_not_parsed = 0;
13888         }
13889
13890       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13891         sals[0] = update_static_tracepoint (b, sals[0]);
13892
13893       *found = 1;
13894     }
13895   else
13896     *found = 0;
13897
13898   return sals;
13899 }
13900
13901 /* The default re_set method, for typical hardware or software
13902    breakpoints.  Reevaluate the breakpoint and recreate its
13903    locations.  */
13904
13905 static void
13906 breakpoint_re_set_default (struct breakpoint *b)
13907 {
13908   struct program_space *filter_pspace = current_program_space;
13909   std::vector<symtab_and_line> expanded, expanded_end;
13910
13911   int found;
13912   std::vector<symtab_and_line> sals = location_to_sals (b, b->location.get (),
13913                                                         filter_pspace, &found);
13914   if (found)
13915     expanded = std::move (sals);
13916
13917   if (b->location_range_end != NULL)
13918     {
13919       std::vector<symtab_and_line> sals_end
13920         = location_to_sals (b, b->location_range_end.get (),
13921                             filter_pspace, &found);
13922       if (found)
13923         expanded_end = std::move (sals_end);
13924     }
13925
13926   update_breakpoint_locations (b, filter_pspace, expanded, expanded_end);
13927 }
13928
13929 /* Default method for creating SALs from an address string.  It basically
13930    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13931
13932 static void
13933 create_sals_from_location_default (struct event_location *location,
13934                                    struct linespec_result *canonical,
13935                                    enum bptype type_wanted)
13936 {
13937   parse_breakpoint_sals (location, canonical);
13938 }
13939
13940 /* Call create_breakpoints_sal for the given arguments.  This is the default
13941    function for the `create_breakpoints_sal' method of
13942    breakpoint_ops.  */
13943
13944 static void
13945 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13946                                 struct linespec_result *canonical,
13947                                 gdb::unique_xmalloc_ptr<char> cond_string,
13948                                 gdb::unique_xmalloc_ptr<char> extra_string,
13949                                 enum bptype type_wanted,
13950                                 enum bpdisp disposition,
13951                                 int thread,
13952                                 int task, int ignore_count,
13953                                 const struct breakpoint_ops *ops,
13954                                 int from_tty, int enabled,
13955                                 int internal, unsigned flags)
13956 {
13957   create_breakpoints_sal (gdbarch, canonical,
13958                           std::move (cond_string),
13959                           std::move (extra_string),
13960                           type_wanted, disposition,
13961                           thread, task, ignore_count, ops, from_tty,
13962                           enabled, internal, flags);
13963 }
13964
13965 /* Decode the line represented by S by calling decode_line_full.  This is the
13966    default function for the `decode_location' method of breakpoint_ops.  */
13967
13968 static std::vector<symtab_and_line>
13969 decode_location_default (struct breakpoint *b,
13970                          struct event_location *location,
13971                          struct program_space *search_pspace)
13972 {
13973   struct linespec_result canonical;
13974
13975   decode_line_full (location, DECODE_LINE_FUNFIRSTLINE, search_pspace,
13976                     NULL, 0, &canonical, multiple_symbols_all,
13977                     b->filter.get ());
13978
13979   /* We should get 0 or 1 resulting SALs.  */
13980   gdb_assert (canonical.lsals.size () < 2);
13981
13982   if (!canonical.lsals.empty ())
13983     {
13984       const linespec_sals &lsal = canonical.lsals[0];
13985       return std::move (lsal.sals);
13986     }
13987   return {};
13988 }
13989
13990 /* Reset a breakpoint.  */
13991
13992 static void
13993 breakpoint_re_set_one (breakpoint *b)
13994 {
13995   input_radix = b->input_radix;
13996   set_language (b->language);
13997
13998   b->ops->re_set (b);
13999 }
14000
14001 /* Re-set breakpoint locations for the current program space.
14002    Locations bound to other program spaces are left untouched.  */
14003
14004 void
14005 breakpoint_re_set (void)
14006 {
14007   struct breakpoint *b, *b_tmp;
14008
14009   {
14010     scoped_restore_current_language save_language;
14011     scoped_restore save_input_radix = make_scoped_restore (&input_radix);
14012     scoped_restore_current_pspace_and_thread restore_pspace_thread;
14013
14014     /* breakpoint_re_set_one sets the current_language to the language
14015        of the breakpoint it is resetting (see prepare_re_set_context)
14016        before re-evaluating the breakpoint's location.  This change can
14017        unfortunately get undone by accident if the language_mode is set
14018        to auto, and we either switch frames, or more likely in this context,
14019        we select the current frame.
14020
14021        We prevent this by temporarily turning the language_mode to
14022        language_mode_manual.  We restore it once all breakpoints
14023        have been reset.  */
14024     scoped_restore save_language_mode = make_scoped_restore (&language_mode);
14025     language_mode = language_mode_manual;
14026
14027     /* Note: we must not try to insert locations until after all
14028        breakpoints have been re-set.  Otherwise, e.g., when re-setting
14029        breakpoint 1, we'd insert the locations of breakpoint 2, which
14030        hadn't been re-set yet, and thus may have stale locations.  */
14031
14032     ALL_BREAKPOINTS_SAFE (b, b_tmp)
14033       {
14034         try
14035           {
14036             breakpoint_re_set_one (b);
14037           }
14038         catch (const gdb_exception &ex)
14039           {
14040             exception_fprintf (gdb_stderr, ex,
14041                                "Error in re-setting breakpoint %d: ",
14042                                b->number);
14043           }
14044       }
14045
14046     jit_breakpoint_re_set ();
14047   }
14048
14049   create_overlay_event_breakpoint ();
14050   create_longjmp_master_breakpoint ();
14051   create_std_terminate_master_breakpoint ();
14052   create_exception_master_breakpoint ();
14053
14054   /* Now we can insert.  */
14055   update_global_location_list (UGLL_MAY_INSERT);
14056 }
14057 \f
14058 /* Reset the thread number of this breakpoint:
14059
14060    - If the breakpoint is for all threads, leave it as-is.
14061    - Else, reset it to the current thread for inferior_ptid.  */
14062 void
14063 breakpoint_re_set_thread (struct breakpoint *b)
14064 {
14065   if (b->thread != -1)
14066     {
14067       b->thread = inferior_thread ()->global_num;
14068
14069       /* We're being called after following a fork.  The new fork is
14070          selected as current, and unless this was a vfork will have a
14071          different program space from the original thread.  Reset that
14072          as well.  */
14073       b->loc->pspace = current_program_space;
14074     }
14075 }
14076
14077 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14078    If from_tty is nonzero, it prints a message to that effect,
14079    which ends with a period (no newline).  */
14080
14081 void
14082 set_ignore_count (int bptnum, int count, int from_tty)
14083 {
14084   struct breakpoint *b;
14085
14086   if (count < 0)
14087     count = 0;
14088
14089   ALL_BREAKPOINTS (b)
14090     if (b->number == bptnum)
14091     {
14092       if (is_tracepoint (b))
14093         {
14094           if (from_tty && count != 0)
14095             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14096                              bptnum);
14097           return;
14098         }
14099       
14100       b->ignore_count = count;
14101       if (from_tty)
14102         {
14103           if (count == 0)
14104             printf_filtered (_("Will stop next time "
14105                                "breakpoint %d is reached."),
14106                              bptnum);
14107           else if (count == 1)
14108             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14109                              bptnum);
14110           else
14111             printf_filtered (_("Will ignore next %d "
14112                                "crossings of breakpoint %d."),
14113                              count, bptnum);
14114         }
14115       gdb::observers::breakpoint_modified.notify (b);
14116       return;
14117     }
14118
14119   error (_("No breakpoint number %d."), bptnum);
14120 }
14121
14122 /* Command to set ignore-count of breakpoint N to COUNT.  */
14123
14124 static void
14125 ignore_command (const char *args, int from_tty)
14126 {
14127   const char *p = args;
14128   int num;
14129
14130   if (p == 0)
14131     error_no_arg (_("a breakpoint number"));
14132
14133   num = get_number (&p);
14134   if (num == 0)
14135     error (_("bad breakpoint number: '%s'"), args);
14136   if (*p == 0)
14137     error (_("Second argument (specified ignore-count) is missing."));
14138
14139   set_ignore_count (num,
14140                     longest_to_int (value_as_long (parse_and_eval (p))),
14141                     from_tty);
14142   if (from_tty)
14143     printf_filtered ("\n");
14144 }
14145 \f
14146
14147 /* Call FUNCTION on each of the breakpoints with numbers in the range
14148    defined by BP_NUM_RANGE (an inclusive range).  */
14149
14150 static void
14151 map_breakpoint_number_range (std::pair<int, int> bp_num_range,
14152                              gdb::function_view<void (breakpoint *)> function)
14153 {
14154   if (bp_num_range.first == 0)
14155     {
14156       warning (_("bad breakpoint number at or near '%d'"),
14157                bp_num_range.first);
14158     }
14159   else
14160     {
14161       struct breakpoint *b, *tmp;
14162
14163       for (int i = bp_num_range.first; i <= bp_num_range.second; i++)
14164         {
14165           bool match = false;
14166
14167           ALL_BREAKPOINTS_SAFE (b, tmp)
14168             if (b->number == i)
14169               {
14170                 match = true;
14171                 function (b);
14172                 break;
14173               }
14174           if (!match)
14175             printf_unfiltered (_("No breakpoint number %d.\n"), i);
14176         }
14177     }
14178 }
14179
14180 /* Call FUNCTION on each of the breakpoints whose numbers are given in
14181    ARGS.  */
14182
14183 static void
14184 map_breakpoint_numbers (const char *args,
14185                         gdb::function_view<void (breakpoint *)> function)
14186 {
14187   if (args == NULL || *args == '\0')
14188     error_no_arg (_("one or more breakpoint numbers"));
14189
14190   number_or_range_parser parser (args);
14191
14192   while (!parser.finished ())
14193     {
14194       int num = parser.get_number ();
14195       map_breakpoint_number_range (std::make_pair (num, num), function);
14196     }
14197 }
14198
14199 /* Return the breakpoint location structure corresponding to the
14200    BP_NUM and LOC_NUM values.  */
14201
14202 static struct bp_location *
14203 find_location_by_number (int bp_num, int loc_num)
14204 {
14205   struct breakpoint *b;
14206
14207   ALL_BREAKPOINTS (b)
14208     if (b->number == bp_num)
14209       {
14210         break;
14211       }
14212
14213   if (!b || b->number != bp_num)
14214     error (_("Bad breakpoint number '%d'"), bp_num);
14215   
14216   if (loc_num == 0)
14217     error (_("Bad breakpoint location number '%d'"), loc_num);
14218
14219   int n = 0;
14220   for (bp_location *loc = b->loc; loc != NULL; loc = loc->next)
14221     if (++n == loc_num)
14222       return loc;
14223
14224   error (_("Bad breakpoint location number '%d'"), loc_num);
14225 }
14226
14227 /* Modes of operation for extract_bp_num.  */
14228 enum class extract_bp_kind
14229 {
14230   /* Extracting a breakpoint number.  */
14231   bp,
14232
14233   /* Extracting a location number.  */
14234   loc,
14235 };
14236
14237 /* Extract a breakpoint or location number (as determined by KIND)
14238    from the string starting at START.  TRAILER is a character which
14239    can be found after the number.  If you don't want a trailer, use
14240    '\0'.  If END_OUT is not NULL, it is set to point after the parsed
14241    string.  This always returns a positive integer.  */
14242
14243 static int
14244 extract_bp_num (extract_bp_kind kind, const char *start,
14245                 int trailer, const char **end_out = NULL)
14246 {
14247   const char *end = start;
14248   int num = get_number_trailer (&end, trailer);
14249   if (num < 0)
14250     error (kind == extract_bp_kind::bp
14251            ? _("Negative breakpoint number '%.*s'")
14252            : _("Negative breakpoint location number '%.*s'"),
14253            int (end - start), start);
14254   if (num == 0)
14255     error (kind == extract_bp_kind::bp
14256            ? _("Bad breakpoint number '%.*s'")
14257            : _("Bad breakpoint location number '%.*s'"),
14258            int (end - start), start);
14259
14260   if (end_out != NULL)
14261     *end_out = end;
14262   return num;
14263 }
14264
14265 /* Extract a breakpoint or location range (as determined by KIND) in
14266    the form NUM1-NUM2 stored at &ARG[arg_offset].  Returns a std::pair
14267    representing the (inclusive) range.  The returned pair's elements
14268    are always positive integers.  */
14269
14270 static std::pair<int, int>
14271 extract_bp_or_bp_range (extract_bp_kind kind,
14272                         const std::string &arg,
14273                         std::string::size_type arg_offset)
14274 {
14275   std::pair<int, int> range;
14276   const char *bp_loc = &arg[arg_offset];
14277   std::string::size_type dash = arg.find ('-', arg_offset);
14278   if (dash != std::string::npos)
14279     {
14280       /* bp_loc is a range (x-z).  */
14281       if (arg.length () == dash + 1)
14282         error (kind == extract_bp_kind::bp
14283                ? _("Bad breakpoint number at or near: '%s'")
14284                : _("Bad breakpoint location number at or near: '%s'"),
14285                bp_loc);
14286
14287       const char *end;
14288       const char *start_first = bp_loc;
14289       const char *start_second = &arg[dash + 1];
14290       range.first = extract_bp_num (kind, start_first, '-');
14291       range.second = extract_bp_num (kind, start_second, '\0', &end);
14292
14293       if (range.first > range.second)
14294         error (kind == extract_bp_kind::bp
14295                ? _("Inverted breakpoint range at '%.*s'")
14296                : _("Inverted breakpoint location range at '%.*s'"),
14297                int (end - start_first), start_first);
14298     }
14299   else
14300     {
14301       /* bp_loc is a single value.  */
14302       range.first = extract_bp_num (kind, bp_loc, '\0');
14303       range.second = range.first;
14304     }
14305   return range;
14306 }
14307
14308 /* Extract the breakpoint/location range specified by ARG.  Returns
14309    the breakpoint range in BP_NUM_RANGE, and the location range in
14310    BP_LOC_RANGE.
14311
14312    ARG may be in any of the following forms:
14313
14314    x     where 'x' is a breakpoint number.
14315    x-y   where 'x' and 'y' specify a breakpoint numbers range.
14316    x.y   where 'x' is a breakpoint number and 'y' a location number.
14317    x.y-z where 'x' is a breakpoint number and 'y' and 'z' specify a
14318          location number range.
14319 */
14320
14321 static void
14322 extract_bp_number_and_location (const std::string &arg,
14323                                 std::pair<int, int> &bp_num_range,
14324                                 std::pair<int, int> &bp_loc_range)
14325 {
14326   std::string::size_type dot = arg.find ('.');
14327
14328   if (dot != std::string::npos)
14329     {
14330       /* Handle 'x.y' and 'x.y-z' cases.  */
14331
14332       if (arg.length () == dot + 1 || dot == 0)
14333         error (_("Bad breakpoint number at or near: '%s'"), arg.c_str ());
14334
14335       bp_num_range.first
14336         = extract_bp_num (extract_bp_kind::bp, arg.c_str (), '.');
14337       bp_num_range.second = bp_num_range.first;
14338
14339       bp_loc_range = extract_bp_or_bp_range (extract_bp_kind::loc,
14340                                              arg, dot + 1);
14341     }
14342   else
14343     {
14344       /* Handle x and x-y cases.  */
14345
14346       bp_num_range = extract_bp_or_bp_range (extract_bp_kind::bp, arg, 0);
14347       bp_loc_range.first = 0;
14348       bp_loc_range.second = 0;
14349     }
14350 }
14351
14352 /* Enable or disable a breakpoint location BP_NUM.LOC_NUM.  ENABLE
14353    specifies whether to enable or disable.  */
14354
14355 static void
14356 enable_disable_bp_num_loc (int bp_num, int loc_num, bool enable)
14357 {
14358   struct bp_location *loc = find_location_by_number (bp_num, loc_num);
14359   if (loc != NULL)
14360     {
14361       if (loc->disabled_by_cond && enable)
14362         error (_("Breakpoint %d's condition is invalid at location %d, "
14363                  "cannot enable."), bp_num, loc_num);
14364
14365       if (loc->enabled != enable)
14366         {
14367           loc->enabled = enable;
14368           mark_breakpoint_location_modified (loc);
14369         }
14370       if (target_supports_enable_disable_tracepoint ()
14371           && current_trace_status ()->running && loc->owner
14372           && is_tracepoint (loc->owner))
14373         target_disable_tracepoint (loc);
14374     }
14375   update_global_location_list (UGLL_DONT_INSERT);
14376
14377   gdb::observers::breakpoint_modified.notify (loc->owner);
14378 }
14379
14380 /* Enable or disable a range of breakpoint locations.  BP_NUM is the
14381    number of the breakpoint, and BP_LOC_RANGE specifies the
14382    (inclusive) range of location numbers of that breakpoint to
14383    enable/disable.  ENABLE specifies whether to enable or disable the
14384    location.  */
14385
14386 static void
14387 enable_disable_breakpoint_location_range (int bp_num,
14388                                           std::pair<int, int> &bp_loc_range,
14389                                           bool enable)
14390 {
14391   for (int i = bp_loc_range.first; i <= bp_loc_range.second; i++)
14392     enable_disable_bp_num_loc (bp_num, i, enable);
14393 }
14394
14395 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14396    If from_tty is nonzero, it prints a message to that effect,
14397    which ends with a period (no newline).  */
14398
14399 void
14400 disable_breakpoint (struct breakpoint *bpt)
14401 {
14402   /* Never disable a watchpoint scope breakpoint; we want to
14403      hit them when we leave scope so we can delete both the
14404      watchpoint and its scope breakpoint at that time.  */
14405   if (bpt->type == bp_watchpoint_scope)
14406     return;
14407
14408   bpt->enable_state = bp_disabled;
14409
14410   /* Mark breakpoint locations modified.  */
14411   mark_breakpoint_modified (bpt);
14412
14413   if (target_supports_enable_disable_tracepoint ()
14414       && current_trace_status ()->running && is_tracepoint (bpt))
14415     {
14416       struct bp_location *location;
14417      
14418       for (location = bpt->loc; location; location = location->next)
14419         target_disable_tracepoint (location);
14420     }
14421
14422   update_global_location_list (UGLL_DONT_INSERT);
14423
14424   gdb::observers::breakpoint_modified.notify (bpt);
14425 }
14426
14427 /* Enable or disable the breakpoint(s) or breakpoint location(s)
14428    specified in ARGS.  ARGS may be in any of the formats handled by
14429    extract_bp_number_and_location.  ENABLE specifies whether to enable
14430    or disable the breakpoints/locations.  */
14431
14432 static void
14433 enable_disable_command (const char *args, int from_tty, bool enable)
14434 {
14435   if (args == 0)
14436     {
14437       struct breakpoint *bpt;
14438
14439       ALL_BREAKPOINTS (bpt)
14440         if (user_breakpoint_p (bpt))
14441           {
14442             if (enable)
14443               enable_breakpoint (bpt);
14444             else
14445               disable_breakpoint (bpt);
14446           }
14447     }
14448   else
14449     {
14450       std::string num = extract_arg (&args);
14451
14452       while (!num.empty ())
14453         {
14454           std::pair<int, int> bp_num_range, bp_loc_range;
14455
14456           extract_bp_number_and_location (num, bp_num_range, bp_loc_range);
14457
14458           if (bp_loc_range.first == bp_loc_range.second
14459               && bp_loc_range.first == 0)
14460             {
14461               /* Handle breakpoint ids with formats 'x' or 'x-z'.  */
14462               map_breakpoint_number_range (bp_num_range,
14463                                            enable
14464                                            ? enable_breakpoint
14465                                            : disable_breakpoint);
14466             }
14467           else
14468             {
14469               /* Handle breakpoint ids with formats 'x.y' or
14470                  'x.y-z'.  */
14471               enable_disable_breakpoint_location_range
14472                 (bp_num_range.first, bp_loc_range, enable);
14473             }
14474           num = extract_arg (&args);
14475         }
14476     }
14477 }
14478
14479 /* The disable command disables the specified breakpoints/locations
14480    (or all defined breakpoints) so they're no longer effective in
14481    stopping the inferior.  ARGS may be in any of the forms defined in
14482    extract_bp_number_and_location.  */
14483
14484 static void
14485 disable_command (const char *args, int from_tty)
14486 {
14487   enable_disable_command (args, from_tty, false);
14488 }
14489
14490 static void
14491 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14492                         int count)
14493 {
14494   int target_resources_ok;
14495
14496   if (bpt->type == bp_hardware_breakpoint)
14497     {
14498       int i;
14499       i = hw_breakpoint_used_count ();
14500       target_resources_ok = 
14501         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14502                                             i + 1, 0);
14503       if (target_resources_ok == 0)
14504         error (_("No hardware breakpoint support in the target."));
14505       else if (target_resources_ok < 0)
14506         error (_("Hardware breakpoints used exceeds limit."));
14507     }
14508
14509   if (is_watchpoint (bpt))
14510     {
14511       /* Initialize it just to avoid a GCC false warning.  */
14512       enum enable_state orig_enable_state = bp_disabled;
14513
14514       try
14515         {
14516           struct watchpoint *w = (struct watchpoint *) bpt;
14517
14518           orig_enable_state = bpt->enable_state;
14519           bpt->enable_state = bp_enabled;
14520           update_watchpoint (w, 1 /* reparse */);
14521         }
14522       catch (const gdb_exception &e)
14523         {
14524           bpt->enable_state = orig_enable_state;
14525           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14526                              bpt->number);
14527           return;
14528         }
14529     }
14530
14531   bpt->enable_state = bp_enabled;
14532
14533   /* Mark breakpoint locations modified.  */
14534   mark_breakpoint_modified (bpt);
14535
14536   if (target_supports_enable_disable_tracepoint ()
14537       && current_trace_status ()->running && is_tracepoint (bpt))
14538     {
14539       struct bp_location *location;
14540
14541       for (location = bpt->loc; location; location = location->next)
14542         target_enable_tracepoint (location);
14543     }
14544
14545   bpt->disposition = disposition;
14546   bpt->enable_count = count;
14547   update_global_location_list (UGLL_MAY_INSERT);
14548
14549   gdb::observers::breakpoint_modified.notify (bpt);
14550 }
14551
14552
14553 void
14554 enable_breakpoint (struct breakpoint *bpt)
14555 {
14556   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14557 }
14558
14559 /* The enable command enables the specified breakpoints/locations (or
14560    all defined breakpoints) so they once again become (or continue to
14561    be) effective in stopping the inferior.  ARGS may be in any of the
14562    forms defined in extract_bp_number_and_location.  */
14563
14564 static void
14565 enable_command (const char *args, int from_tty)
14566 {
14567   enable_disable_command (args, from_tty, true);
14568 }
14569
14570 static void
14571 enable_once_command (const char *args, int from_tty)
14572 {
14573   map_breakpoint_numbers
14574     (args, [&] (breakpoint *b)
14575      {
14576        iterate_over_related_breakpoints
14577          (b, [&] (breakpoint *bpt)
14578           {
14579             enable_breakpoint_disp (bpt, disp_disable, 1);
14580           });
14581      });
14582 }
14583
14584 static void
14585 enable_count_command (const char *args, int from_tty)
14586 {
14587   int count;
14588
14589   if (args == NULL)
14590     error_no_arg (_("hit count"));
14591
14592   count = get_number (&args);
14593
14594   map_breakpoint_numbers
14595     (args, [&] (breakpoint *b)
14596      {
14597        iterate_over_related_breakpoints
14598          (b, [&] (breakpoint *bpt)
14599           {
14600             enable_breakpoint_disp (bpt, disp_disable, count);
14601           });
14602      });
14603 }
14604
14605 static void
14606 enable_delete_command (const char *args, int from_tty)
14607 {
14608   map_breakpoint_numbers
14609     (args, [&] (breakpoint *b)
14610      {
14611        iterate_over_related_breakpoints
14612          (b, [&] (breakpoint *bpt)
14613           {
14614             enable_breakpoint_disp (bpt, disp_del, 1);
14615           });
14616      });
14617 }
14618 \f
14619 /* Invalidate last known value of any hardware watchpoint if
14620    the memory which that value represents has been written to by
14621    GDB itself.  */
14622
14623 static void
14624 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14625                                       CORE_ADDR addr, ssize_t len,
14626                                       const bfd_byte *data)
14627 {
14628   struct breakpoint *bp;
14629
14630   ALL_BREAKPOINTS (bp)
14631     if (bp->enable_state == bp_enabled
14632         && bp->type == bp_hardware_watchpoint)
14633       {
14634         struct watchpoint *wp = (struct watchpoint *) bp;
14635
14636         if (wp->val_valid && wp->val != nullptr)
14637           {
14638             struct bp_location *loc;
14639
14640             for (loc = bp->loc; loc != NULL; loc = loc->next)
14641               if (loc->loc_type == bp_loc_hardware_watchpoint
14642                   && loc->address + loc->length > addr
14643                   && addr + len > loc->address)
14644                 {
14645                   wp->val = NULL;
14646                   wp->val_valid = false;
14647                 }
14648           }
14649       }
14650 }
14651
14652 /* Create and insert a breakpoint for software single step.  */
14653
14654 void
14655 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14656                                const address_space *aspace,
14657                                CORE_ADDR next_pc)
14658 {
14659   struct thread_info *tp = inferior_thread ();
14660   struct symtab_and_line sal;
14661   CORE_ADDR pc = next_pc;
14662
14663   if (tp->control.single_step_breakpoints == NULL)
14664     {
14665       tp->control.single_step_breakpoints
14666         = new_single_step_breakpoint (tp->global_num, gdbarch);
14667     }
14668
14669   sal = find_pc_line (pc, 0);
14670   sal.pc = pc;
14671   sal.section = find_pc_overlay (pc);
14672   sal.explicit_pc = 1;
14673   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
14674
14675   update_global_location_list (UGLL_INSERT);
14676 }
14677
14678 /* Insert single step breakpoints according to the current state.  */
14679
14680 int
14681 insert_single_step_breakpoints (struct gdbarch *gdbarch)
14682 {
14683   struct regcache *regcache = get_current_regcache ();
14684   std::vector<CORE_ADDR> next_pcs;
14685
14686   next_pcs = gdbarch_software_single_step (gdbarch, regcache);
14687
14688   if (!next_pcs.empty ())
14689     {
14690       struct frame_info *frame = get_current_frame ();
14691       const address_space *aspace = get_frame_address_space (frame);
14692
14693       for (CORE_ADDR pc : next_pcs)
14694         insert_single_step_breakpoint (gdbarch, aspace, pc);
14695
14696       return 1;
14697     }
14698   else
14699     return 0;
14700 }
14701
14702 /* See breakpoint.h.  */
14703
14704 int
14705 breakpoint_has_location_inserted_here (struct breakpoint *bp,
14706                                        const address_space *aspace,
14707                                        CORE_ADDR pc)
14708 {
14709   struct bp_location *loc;
14710
14711   for (loc = bp->loc; loc != NULL; loc = loc->next)
14712     if (loc->inserted
14713         && breakpoint_location_address_match (loc, aspace, pc))
14714       return 1;
14715
14716   return 0;
14717 }
14718
14719 /* Check whether a software single-step breakpoint is inserted at
14720    PC.  */
14721
14722 int
14723 single_step_breakpoint_inserted_here_p (const address_space *aspace,
14724                                         CORE_ADDR pc)
14725 {
14726   struct breakpoint *bpt;
14727
14728   ALL_BREAKPOINTS (bpt)
14729     {
14730       if (bpt->type == bp_single_step
14731           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
14732         return 1;
14733     }
14734   return 0;
14735 }
14736
14737 /* Tracepoint-specific operations.  */
14738
14739 /* Set tracepoint count to NUM.  */
14740 static void
14741 set_tracepoint_count (int num)
14742 {
14743   tracepoint_count = num;
14744   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14745 }
14746
14747 static void
14748 trace_command (const char *arg, int from_tty)
14749 {
14750   event_location_up location = string_to_event_location (&arg,
14751                                                          current_language);
14752   const struct breakpoint_ops *ops = breakpoint_ops_for_event_location
14753     (location.get (), true /* is_tracepoint */);
14754
14755   create_breakpoint (get_current_arch (),
14756                      location.get (),
14757                      NULL, 0, arg, 1 /* parse arg */,
14758                      0 /* tempflag */,
14759                      bp_tracepoint /* type_wanted */,
14760                      0 /* Ignore count */,
14761                      pending_break_support,
14762                      ops,
14763                      from_tty,
14764                      1 /* enabled */,
14765                      0 /* internal */, 0);
14766 }
14767
14768 static void
14769 ftrace_command (const char *arg, int from_tty)
14770 {
14771   event_location_up location = string_to_event_location (&arg,
14772                                                          current_language);
14773   create_breakpoint (get_current_arch (),
14774                      location.get (),
14775                      NULL, 0, arg, 1 /* parse arg */,
14776                      0 /* tempflag */,
14777                      bp_fast_tracepoint /* type_wanted */,
14778                      0 /* Ignore count */,
14779                      pending_break_support,
14780                      &tracepoint_breakpoint_ops,
14781                      from_tty,
14782                      1 /* enabled */,
14783                      0 /* internal */, 0);
14784 }
14785
14786 /* strace command implementation.  Creates a static tracepoint.  */
14787
14788 static void
14789 strace_command (const char *arg, int from_tty)
14790 {
14791   struct breakpoint_ops *ops;
14792   event_location_up location;
14793
14794   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14795      or with a normal static tracepoint.  */
14796   if (arg && startswith (arg, "-m") && isspace (arg[2]))
14797     {
14798       ops = &strace_marker_breakpoint_ops;
14799       location = new_linespec_location (&arg, symbol_name_match_type::FULL);
14800     }
14801   else
14802     {
14803       ops = &tracepoint_breakpoint_ops;
14804       location = string_to_event_location (&arg, current_language);
14805     }
14806
14807   create_breakpoint (get_current_arch (),
14808                      location.get (),
14809                      NULL, 0, arg, 1 /* parse arg */,
14810                      0 /* tempflag */,
14811                      bp_static_tracepoint /* type_wanted */,
14812                      0 /* Ignore count */,
14813                      pending_break_support,
14814                      ops,
14815                      from_tty,
14816                      1 /* enabled */,
14817                      0 /* internal */, 0);
14818 }
14819
14820 /* Set up a fake reader function that gets command lines from a linked
14821    list that was acquired during tracepoint uploading.  */
14822
14823 static struct uploaded_tp *this_utp;
14824 static int next_cmd;
14825
14826 static char *
14827 read_uploaded_action (void)
14828 {
14829   char *rslt = nullptr;
14830
14831   if (next_cmd < this_utp->cmd_strings.size ())
14832     {
14833       rslt = this_utp->cmd_strings[next_cmd].get ();
14834       next_cmd++;
14835     }
14836
14837   return rslt;
14838 }
14839
14840 /* Given information about a tracepoint as recorded on a target (which
14841    can be either a live system or a trace file), attempt to create an
14842    equivalent GDB tracepoint.  This is not a reliable process, since
14843    the target does not necessarily have all the information used when
14844    the tracepoint was originally defined.  */
14845   
14846 struct tracepoint *
14847 create_tracepoint_from_upload (struct uploaded_tp *utp)
14848 {
14849   const char *addr_str;
14850   char small_buf[100];
14851   struct tracepoint *tp;
14852
14853   if (utp->at_string)
14854     addr_str = utp->at_string.get ();
14855   else
14856     {
14857       /* In the absence of a source location, fall back to raw
14858          address.  Since there is no way to confirm that the address
14859          means the same thing as when the trace was started, warn the
14860          user.  */
14861       warning (_("Uploaded tracepoint %d has no "
14862                  "source location, using raw address"),
14863                utp->number);
14864       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
14865       addr_str = small_buf;
14866     }
14867
14868   /* There's not much we can do with a sequence of bytecodes.  */
14869   if (utp->cond && !utp->cond_string)
14870     warning (_("Uploaded tracepoint %d condition "
14871                "has no source form, ignoring it"),
14872              utp->number);
14873
14874   event_location_up location = string_to_event_location (&addr_str,
14875                                                          current_language);
14876   if (!create_breakpoint (get_current_arch (),
14877                           location.get (),
14878                           utp->cond_string.get (), -1, addr_str,
14879                           0 /* parse cond/thread */,
14880                           0 /* tempflag */,
14881                           utp->type /* type_wanted */,
14882                           0 /* Ignore count */,
14883                           pending_break_support,
14884                           &tracepoint_breakpoint_ops,
14885                           0 /* from_tty */,
14886                           utp->enabled /* enabled */,
14887                           0 /* internal */,
14888                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14889     return NULL;
14890
14891   /* Get the tracepoint we just created.  */
14892   tp = get_tracepoint (tracepoint_count);
14893   gdb_assert (tp != NULL);
14894
14895   if (utp->pass > 0)
14896     {
14897       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
14898                  tp->number);
14899
14900       trace_pass_command (small_buf, 0);
14901     }
14902
14903   /* If we have uploaded versions of the original commands, set up a
14904      special-purpose "reader" function and call the usual command line
14905      reader, then pass the result to the breakpoint command-setting
14906      function.  */
14907   if (!utp->cmd_strings.empty ())
14908     {
14909       counted_command_line cmd_list;
14910
14911       this_utp = utp;
14912       next_cmd = 0;
14913
14914       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL);
14915
14916       breakpoint_set_commands (tp, std::move (cmd_list));
14917     }
14918   else if (!utp->actions.empty ()
14919            || !utp->step_actions.empty ())
14920     warning (_("Uploaded tracepoint %d actions "
14921                "have no source form, ignoring them"),
14922              utp->number);
14923
14924   /* Copy any status information that might be available.  */
14925   tp->hit_count = utp->hit_count;
14926   tp->traceframe_usage = utp->traceframe_usage;
14927
14928   return tp;
14929 }
14930   
14931 /* Print information on tracepoint number TPNUM_EXP, or all if
14932    omitted.  */
14933
14934 static void
14935 info_tracepoints_command (const char *args, int from_tty)
14936 {
14937   struct ui_out *uiout = current_uiout;
14938   int num_printed;
14939
14940   num_printed = breakpoint_1 (args, false, is_tracepoint);
14941
14942   if (num_printed == 0)
14943     {
14944       if (args == NULL || *args == '\0')
14945         uiout->message ("No tracepoints.\n");
14946       else
14947         uiout->message ("No tracepoint matching '%s'.\n", args);
14948     }
14949
14950   default_collect_info ();
14951 }
14952
14953 /* The 'enable trace' command enables tracepoints.
14954    Not supported by all targets.  */
14955 static void
14956 enable_trace_command (const char *args, int from_tty)
14957 {
14958   enable_command (args, from_tty);
14959 }
14960
14961 /* The 'disable trace' command disables tracepoints.
14962    Not supported by all targets.  */
14963 static void
14964 disable_trace_command (const char *args, int from_tty)
14965 {
14966   disable_command (args, from_tty);
14967 }
14968
14969 /* Remove a tracepoint (or all if no argument).  */
14970 static void
14971 delete_trace_command (const char *arg, int from_tty)
14972 {
14973   struct breakpoint *b, *b_tmp;
14974
14975   dont_repeat ();
14976
14977   if (arg == 0)
14978     {
14979       int breaks_to_delete = 0;
14980
14981       /* Delete all breakpoints if no argument.
14982          Do not delete internal or call-dummy breakpoints, these
14983          have to be deleted with an explicit breakpoint number 
14984          argument.  */
14985       ALL_TRACEPOINTS (b)
14986         if (is_tracepoint (b) && user_breakpoint_p (b))
14987           {
14988             breaks_to_delete = 1;
14989             break;
14990           }
14991
14992       /* Ask user only if there are some breakpoints to delete.  */
14993       if (!from_tty
14994           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14995         {
14996           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14997             if (is_tracepoint (b) && user_breakpoint_p (b))
14998               delete_breakpoint (b);
14999         }
15000     }
15001   else
15002     map_breakpoint_numbers
15003       (arg, [&] (breakpoint *br)
15004        {
15005          iterate_over_related_breakpoints (br, delete_breakpoint);
15006        });
15007 }
15008
15009 /* Helper function for trace_pass_command.  */
15010
15011 static void
15012 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15013 {
15014   tp->pass_count = count;
15015   gdb::observers::breakpoint_modified.notify (tp);
15016   if (from_tty)
15017     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15018                      tp->number, count);
15019 }
15020
15021 /* Set passcount for tracepoint.
15022
15023    First command argument is passcount, second is tracepoint number.
15024    If tracepoint number omitted, apply to most recently defined.
15025    Also accepts special argument "all".  */
15026
15027 static void
15028 trace_pass_command (const char *args, int from_tty)
15029 {
15030   struct tracepoint *t1;
15031   ULONGEST count;
15032
15033   if (args == 0 || *args == 0)
15034     error (_("passcount command requires an "
15035              "argument (count + optional TP num)"));
15036
15037   count = strtoulst (args, &args, 10);  /* Count comes first, then TP num.  */
15038
15039   args = skip_spaces (args);
15040   if (*args && strncasecmp (args, "all", 3) == 0)
15041     {
15042       struct breakpoint *b;
15043
15044       args += 3;                        /* Skip special argument "all".  */
15045       if (*args)
15046         error (_("Junk at end of arguments."));
15047
15048       ALL_TRACEPOINTS (b)
15049       {
15050         t1 = (struct tracepoint *) b;
15051         trace_pass_set_count (t1, count, from_tty);
15052       }
15053     }
15054   else if (*args == '\0')
15055     {
15056       t1 = get_tracepoint_by_number (&args, NULL);
15057       if (t1)
15058         trace_pass_set_count (t1, count, from_tty);
15059     }
15060   else
15061     {
15062       number_or_range_parser parser (args);
15063       while (!parser.finished ())
15064         {
15065           t1 = get_tracepoint_by_number (&args, &parser);
15066           if (t1)
15067             trace_pass_set_count (t1, count, from_tty);
15068         }
15069     }
15070 }
15071
15072 struct tracepoint *
15073 get_tracepoint (int num)
15074 {
15075   struct breakpoint *t;
15076
15077   ALL_TRACEPOINTS (t)
15078     if (t->number == num)
15079       return (struct tracepoint *) t;
15080
15081   return NULL;
15082 }
15083
15084 /* Find the tracepoint with the given target-side number (which may be
15085    different from the tracepoint number after disconnecting and
15086    reconnecting).  */
15087
15088 struct tracepoint *
15089 get_tracepoint_by_number_on_target (int num)
15090 {
15091   struct breakpoint *b;
15092
15093   ALL_TRACEPOINTS (b)
15094     {
15095       struct tracepoint *t = (struct tracepoint *) b;
15096
15097       if (t->number_on_target == num)
15098         return t;
15099     }
15100
15101   return NULL;
15102 }
15103
15104 /* Utility: parse a tracepoint number and look it up in the list.
15105    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15106    If the argument is missing, the most recent tracepoint
15107    (tracepoint_count) is returned.  */
15108
15109 struct tracepoint *
15110 get_tracepoint_by_number (const char **arg,
15111                           number_or_range_parser *parser)
15112 {
15113   struct breakpoint *t;
15114   int tpnum;
15115   const char *instring = arg == NULL ? NULL : *arg;
15116
15117   if (parser != NULL)
15118     {
15119       gdb_assert (!parser->finished ());
15120       tpnum = parser->get_number ();
15121     }
15122   else if (arg == NULL || *arg == NULL || ! **arg)
15123     tpnum = tracepoint_count;
15124   else
15125     tpnum = get_number (arg);
15126
15127   if (tpnum <= 0)
15128     {
15129       if (instring && *instring)
15130         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15131                          instring);
15132       else
15133         printf_filtered (_("No previous tracepoint\n"));
15134       return NULL;
15135     }
15136
15137   ALL_TRACEPOINTS (t)
15138     if (t->number == tpnum)
15139     {
15140       return (struct tracepoint *) t;
15141     }
15142
15143   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15144   return NULL;
15145 }
15146
15147 void
15148 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15149 {
15150   if (b->thread != -1)
15151     fprintf_unfiltered (fp, " thread %d", b->thread);
15152
15153   if (b->task != 0)
15154     fprintf_unfiltered (fp, " task %d", b->task);
15155
15156   fprintf_unfiltered (fp, "\n");
15157 }
15158
15159 /* Save information on user settable breakpoints (watchpoints, etc) to
15160    a new script file named FILENAME.  If FILTER is non-NULL, call it
15161    on each breakpoint and only include the ones for which it returns
15162    true.  */
15163
15164 static void
15165 save_breakpoints (const char *filename, int from_tty,
15166                   bool (*filter) (const struct breakpoint *))
15167 {
15168   struct breakpoint *tp;
15169   int any = 0;
15170   int extra_trace_bits = 0;
15171
15172   if (filename == 0 || *filename == 0)
15173     error (_("Argument required (file name in which to save)"));
15174
15175   /* See if we have anything to save.  */
15176   ALL_BREAKPOINTS (tp)
15177   {
15178     /* Skip internal and momentary breakpoints.  */
15179     if (!user_breakpoint_p (tp))
15180       continue;
15181
15182     /* If we have a filter, only save the breakpoints it accepts.  */
15183     if (filter && !filter (tp))
15184       continue;
15185
15186     any = 1;
15187
15188     if (is_tracepoint (tp))
15189       {
15190         extra_trace_bits = 1;
15191
15192         /* We can stop searching.  */
15193         break;
15194       }
15195   }
15196
15197   if (!any)
15198     {
15199       warning (_("Nothing to save."));
15200       return;
15201     }
15202
15203   gdb::unique_xmalloc_ptr<char> expanded_filename (tilde_expand (filename));
15204
15205   stdio_file fp;
15206
15207   if (!fp.open (expanded_filename.get (), "w"))
15208     error (_("Unable to open file '%s' for saving (%s)"),
15209            expanded_filename.get (), safe_strerror (errno));
15210
15211   if (extra_trace_bits)
15212     save_trace_state_variables (&fp);
15213
15214   ALL_BREAKPOINTS (tp)
15215   {
15216     /* Skip internal and momentary breakpoints.  */
15217     if (!user_breakpoint_p (tp))
15218       continue;
15219
15220     /* If we have a filter, only save the breakpoints it accepts.  */
15221     if (filter && !filter (tp))
15222       continue;
15223
15224     tp->ops->print_recreate (tp, &fp);
15225
15226     /* Note, we can't rely on tp->number for anything, as we can't
15227        assume the recreated breakpoint numbers will match.  Use $bpnum
15228        instead.  */
15229
15230     if (tp->cond_string)
15231       fp.printf ("  condition $bpnum %s\n", tp->cond_string);
15232
15233     if (tp->ignore_count)
15234       fp.printf ("  ignore $bpnum %d\n", tp->ignore_count);
15235
15236     if (tp->type != bp_dprintf && tp->commands)
15237       {
15238         fp.puts ("  commands\n");
15239         
15240         current_uiout->redirect (&fp);
15241         try
15242           {
15243             print_command_lines (current_uiout, tp->commands.get (), 2);
15244           }
15245         catch (const gdb_exception &ex)
15246           {
15247           current_uiout->redirect (NULL);
15248             throw;
15249           }
15250
15251         current_uiout->redirect (NULL);
15252         fp.puts ("  end\n");
15253       }
15254
15255     if (tp->enable_state == bp_disabled)
15256       fp.puts ("disable $bpnum\n");
15257
15258     /* If this is a multi-location breakpoint, check if the locations
15259        should be individually disabled.  Watchpoint locations are
15260        special, and not user visible.  */
15261     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15262       {
15263         struct bp_location *loc;
15264         int n = 1;
15265
15266         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15267           if (!loc->enabled)
15268             fp.printf ("disable $bpnum.%d\n", n);
15269       }
15270   }
15271
15272   if (extra_trace_bits && *default_collect)
15273     fp.printf ("set default-collect %s\n", default_collect);
15274
15275   if (from_tty)
15276     printf_filtered (_("Saved to file '%s'.\n"), expanded_filename.get ());
15277 }
15278
15279 /* The `save breakpoints' command.  */
15280
15281 static void
15282 save_breakpoints_command (const char *args, int from_tty)
15283 {
15284   save_breakpoints (args, from_tty, NULL);
15285 }
15286
15287 /* The `save tracepoints' command.  */
15288
15289 static void
15290 save_tracepoints_command (const char *args, int from_tty)
15291 {
15292   save_breakpoints (args, from_tty, is_tracepoint);
15293 }
15294
15295 /* Create a vector of all tracepoints.  */
15296
15297 std::vector<breakpoint *>
15298 all_tracepoints (void)
15299 {
15300   std::vector<breakpoint *> tp_vec;
15301   struct breakpoint *tp;
15302
15303   ALL_TRACEPOINTS (tp)
15304   {
15305     tp_vec.push_back (tp);
15306   }
15307
15308   return tp_vec;
15309 }
15310
15311 \f
15312 /* This help string is used to consolidate all the help string for specifying
15313    locations used by several commands.  */
15314
15315 #define LOCATION_HELP_STRING \
15316 "Linespecs are colon-separated lists of location parameters, such as\n\
15317 source filename, function name, label name, and line number.\n\
15318 Example: To specify the start of a label named \"the_top\" in the\n\
15319 function \"fact\" in the file \"factorial.c\", use\n\
15320 \"factorial.c:fact:the_top\".\n\
15321 \n\
15322 Address locations begin with \"*\" and specify an exact address in the\n\
15323 program.  Example: To specify the fourth byte past the start function\n\
15324 \"main\", use \"*main + 4\".\n\
15325 \n\
15326 Explicit locations are similar to linespecs but use an option/argument\n\
15327 syntax to specify location parameters.\n\
15328 Example: To specify the start of the label named \"the_top\" in the\n\
15329 function \"fact\" in the file \"factorial.c\", use \"-source factorial.c\n\
15330 -function fact -label the_top\".\n\
15331 \n\
15332 By default, a specified function is matched against the program's\n\
15333 functions in all scopes.  For C++, this means in all namespaces and\n\
15334 classes.  For Ada, this means in all packages.  E.g., in C++,\n\
15335 \"func()\" matches \"A::func()\", \"A::B::func()\", etc.  The\n\
15336 \"-qualified\" flag overrides this behavior, making GDB interpret the\n\
15337 specified name as a complete fully-qualified name instead."
15338
15339 /* This help string is used for the break, hbreak, tbreak and thbreak
15340    commands.  It is defined as a macro to prevent duplication.
15341    COMMAND should be a string constant containing the name of the
15342    command.  */
15343
15344 #define BREAK_ARGS_HELP(command) \
15345 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM]\n\
15346 \t[-force-condition] [if CONDITION]\n\
15347 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15348 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15349 guessed probe type), `-probe-stap' (for a SystemTap probe) or \n\
15350 `-probe-dtrace' (for a DTrace probe).\n\
15351 LOCATION may be a linespec, address, or explicit location as described\n\
15352 below.\n\
15353 \n\
15354 With no LOCATION, uses current execution address of the selected\n\
15355 stack frame.  This is useful for breaking on return to a stack frame.\n\
15356 \n\
15357 THREADNUM is the number from \"info threads\".\n\
15358 CONDITION is a boolean expression.\n\
15359 \n\
15360 With the \"-force-condition\" flag, the condition is defined even when\n\
15361 it is invalid for all current locations.\n\
15362 \n" LOCATION_HELP_STRING "\n\n\
15363 Multiple breakpoints at one place are permitted, and useful if their\n\
15364 conditions are different.\n\
15365 \n\
15366 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15367
15368 /* List of subcommands for "catch".  */
15369 static struct cmd_list_element *catch_cmdlist;
15370
15371 /* List of subcommands for "tcatch".  */
15372 static struct cmd_list_element *tcatch_cmdlist;
15373
15374 void
15375 add_catch_command (const char *name, const char *docstring,
15376                    cmd_const_sfunc_ftype *sfunc,
15377                    completer_ftype *completer,
15378                    void *user_data_catch,
15379                    void *user_data_tcatch)
15380 {
15381   struct cmd_list_element *command;
15382
15383   command = add_cmd (name, class_breakpoint, docstring,
15384                      &catch_cmdlist);
15385   set_cmd_sfunc (command, sfunc);
15386   set_cmd_context (command, user_data_catch);
15387   set_cmd_completer (command, completer);
15388
15389   command = add_cmd (name, class_breakpoint, docstring,
15390                      &tcatch_cmdlist);
15391   set_cmd_sfunc (command, sfunc);
15392   set_cmd_context (command, user_data_tcatch);
15393   set_cmd_completer (command, completer);
15394 }
15395
15396 struct breakpoint *
15397 iterate_over_breakpoints (gdb::function_view<bool (breakpoint *)> callback)
15398 {
15399   struct breakpoint *b, *b_tmp;
15400
15401   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15402     {
15403       if (callback (b))
15404         return b;
15405     }
15406
15407   return NULL;
15408 }
15409
15410 /* Zero if any of the breakpoint's locations could be a location where
15411    functions have been inlined, nonzero otherwise.  */
15412
15413 static int
15414 is_non_inline_function (struct breakpoint *b)
15415 {
15416   /* The shared library event breakpoint is set on the address of a
15417      non-inline function.  */
15418   if (b->type == bp_shlib_event)
15419     return 1;
15420
15421   return 0;
15422 }
15423
15424 /* Nonzero if the specified PC cannot be a location where functions
15425    have been inlined.  */
15426
15427 int
15428 pc_at_non_inline_function (const address_space *aspace, CORE_ADDR pc,
15429                            const struct target_waitstatus *ws)
15430 {
15431   struct breakpoint *b;
15432   struct bp_location *bl;
15433
15434   ALL_BREAKPOINTS (b)
15435     {
15436       if (!is_non_inline_function (b))
15437         continue;
15438
15439       for (bl = b->loc; bl != NULL; bl = bl->next)
15440         {
15441           if (!bl->shlib_disabled
15442               && bpstat_check_location (bl, aspace, pc, ws))
15443             return 1;
15444         }
15445     }
15446
15447   return 0;
15448 }
15449
15450 /* Remove any references to OBJFILE which is going to be freed.  */
15451
15452 void
15453 breakpoint_free_objfile (struct objfile *objfile)
15454 {
15455   struct bp_location **locp, *loc;
15456
15457   ALL_BP_LOCATIONS (loc, locp)
15458     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
15459       loc->symtab = NULL;
15460 }
15461
15462 void
15463 initialize_breakpoint_ops (void)
15464 {
15465   static int initialized = 0;
15466
15467   struct breakpoint_ops *ops;
15468
15469   if (initialized)
15470     return;
15471   initialized = 1;
15472
15473   /* The breakpoint_ops structure to be inherit by all kinds of
15474      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15475      internal and momentary breakpoints, etc.).  */
15476   ops = &bkpt_base_breakpoint_ops;
15477   *ops = base_breakpoint_ops;
15478   ops->re_set = bkpt_re_set;
15479   ops->insert_location = bkpt_insert_location;
15480   ops->remove_location = bkpt_remove_location;
15481   ops->breakpoint_hit = bkpt_breakpoint_hit;
15482   ops->create_sals_from_location = bkpt_create_sals_from_location;
15483   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15484   ops->decode_location = bkpt_decode_location;
15485
15486   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15487   ops = &bkpt_breakpoint_ops;
15488   *ops = bkpt_base_breakpoint_ops;
15489   ops->re_set = bkpt_re_set;
15490   ops->resources_needed = bkpt_resources_needed;
15491   ops->print_it = bkpt_print_it;
15492   ops->print_mention = bkpt_print_mention;
15493   ops->print_recreate = bkpt_print_recreate;
15494
15495   /* Ranged breakpoints.  */
15496   ops = &ranged_breakpoint_ops;
15497   *ops = bkpt_breakpoint_ops;
15498   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15499   ops->resources_needed = resources_needed_ranged_breakpoint;
15500   ops->print_it = print_it_ranged_breakpoint;
15501   ops->print_one = print_one_ranged_breakpoint;
15502   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15503   ops->print_mention = print_mention_ranged_breakpoint;
15504   ops->print_recreate = print_recreate_ranged_breakpoint;
15505
15506   /* Internal breakpoints.  */
15507   ops = &internal_breakpoint_ops;
15508   *ops = bkpt_base_breakpoint_ops;
15509   ops->re_set = internal_bkpt_re_set;
15510   ops->check_status = internal_bkpt_check_status;
15511   ops->print_it = internal_bkpt_print_it;
15512   ops->print_mention = internal_bkpt_print_mention;
15513
15514   /* Momentary breakpoints.  */
15515   ops = &momentary_breakpoint_ops;
15516   *ops = bkpt_base_breakpoint_ops;
15517   ops->re_set = momentary_bkpt_re_set;
15518   ops->check_status = momentary_bkpt_check_status;
15519   ops->print_it = momentary_bkpt_print_it;
15520   ops->print_mention = momentary_bkpt_print_mention;
15521
15522   /* Probe breakpoints.  */
15523   ops = &bkpt_probe_breakpoint_ops;
15524   *ops = bkpt_breakpoint_ops;
15525   ops->insert_location = bkpt_probe_insert_location;
15526   ops->remove_location = bkpt_probe_remove_location;
15527   ops->create_sals_from_location = bkpt_probe_create_sals_from_location;
15528   ops->decode_location = bkpt_probe_decode_location;
15529
15530   /* Watchpoints.  */
15531   ops = &watchpoint_breakpoint_ops;
15532   *ops = base_breakpoint_ops;
15533   ops->re_set = re_set_watchpoint;
15534   ops->insert_location = insert_watchpoint;
15535   ops->remove_location = remove_watchpoint;
15536   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15537   ops->check_status = check_status_watchpoint;
15538   ops->resources_needed = resources_needed_watchpoint;
15539   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15540   ops->print_it = print_it_watchpoint;
15541   ops->print_mention = print_mention_watchpoint;
15542   ops->print_recreate = print_recreate_watchpoint;
15543   ops->explains_signal = explains_signal_watchpoint;
15544
15545   /* Masked watchpoints.  */
15546   ops = &masked_watchpoint_breakpoint_ops;
15547   *ops = watchpoint_breakpoint_ops;
15548   ops->insert_location = insert_masked_watchpoint;
15549   ops->remove_location = remove_masked_watchpoint;
15550   ops->resources_needed = resources_needed_masked_watchpoint;
15551   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15552   ops->print_it = print_it_masked_watchpoint;
15553   ops->print_one_detail = print_one_detail_masked_watchpoint;
15554   ops->print_mention = print_mention_masked_watchpoint;
15555   ops->print_recreate = print_recreate_masked_watchpoint;
15556
15557   /* Tracepoints.  */
15558   ops = &tracepoint_breakpoint_ops;
15559   *ops = base_breakpoint_ops;
15560   ops->re_set = tracepoint_re_set;
15561   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15562   ops->print_one_detail = tracepoint_print_one_detail;
15563   ops->print_mention = tracepoint_print_mention;
15564   ops->print_recreate = tracepoint_print_recreate;
15565   ops->create_sals_from_location = tracepoint_create_sals_from_location;
15566   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15567   ops->decode_location = tracepoint_decode_location;
15568
15569   /* Probe tracepoints.  */
15570   ops = &tracepoint_probe_breakpoint_ops;
15571   *ops = tracepoint_breakpoint_ops;
15572   ops->create_sals_from_location = tracepoint_probe_create_sals_from_location;
15573   ops->decode_location = tracepoint_probe_decode_location;
15574
15575   /* Static tracepoints with marker (`-m').  */
15576   ops = &strace_marker_breakpoint_ops;
15577   *ops = tracepoint_breakpoint_ops;
15578   ops->create_sals_from_location = strace_marker_create_sals_from_location;
15579   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15580   ops->decode_location = strace_marker_decode_location;
15581
15582   /* Fork catchpoints.  */
15583   ops = &catch_fork_breakpoint_ops;
15584   *ops = base_breakpoint_ops;
15585   ops->insert_location = insert_catch_fork;
15586   ops->remove_location = remove_catch_fork;
15587   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15588   ops->print_it = print_it_catch_fork;
15589   ops->print_one = print_one_catch_fork;
15590   ops->print_mention = print_mention_catch_fork;
15591   ops->print_recreate = print_recreate_catch_fork;
15592
15593   /* Vfork catchpoints.  */
15594   ops = &catch_vfork_breakpoint_ops;
15595   *ops = base_breakpoint_ops;
15596   ops->insert_location = insert_catch_vfork;
15597   ops->remove_location = remove_catch_vfork;
15598   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15599   ops->print_it = print_it_catch_vfork;
15600   ops->print_one = print_one_catch_vfork;
15601   ops->print_mention = print_mention_catch_vfork;
15602   ops->print_recreate = print_recreate_catch_vfork;
15603
15604   /* Exec catchpoints.  */
15605   ops = &catch_exec_breakpoint_ops;
15606   *ops = base_breakpoint_ops;
15607   ops->insert_location = insert_catch_exec;
15608   ops->remove_location = remove_catch_exec;
15609   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15610   ops->print_it = print_it_catch_exec;
15611   ops->print_one = print_one_catch_exec;
15612   ops->print_mention = print_mention_catch_exec;
15613   ops->print_recreate = print_recreate_catch_exec;
15614
15615   /* Solib-related catchpoints.  */
15616   ops = &catch_solib_breakpoint_ops;
15617   *ops = base_breakpoint_ops;
15618   ops->insert_location = insert_catch_solib;
15619   ops->remove_location = remove_catch_solib;
15620   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15621   ops->check_status = check_status_catch_solib;
15622   ops->print_it = print_it_catch_solib;
15623   ops->print_one = print_one_catch_solib;
15624   ops->print_mention = print_mention_catch_solib;
15625   ops->print_recreate = print_recreate_catch_solib;
15626
15627   ops = &dprintf_breakpoint_ops;
15628   *ops = bkpt_base_breakpoint_ops;
15629   ops->re_set = dprintf_re_set;
15630   ops->resources_needed = bkpt_resources_needed;
15631   ops->print_it = bkpt_print_it;
15632   ops->print_mention = bkpt_print_mention;
15633   ops->print_recreate = dprintf_print_recreate;
15634   ops->after_condition_true = dprintf_after_condition_true;
15635   ops->breakpoint_hit = dprintf_breakpoint_hit;
15636 }
15637
15638 /* Chain containing all defined "enable breakpoint" subcommands.  */
15639
15640 static struct cmd_list_element *enablebreaklist = NULL;
15641
15642 /* See breakpoint.h.  */
15643
15644 cmd_list_element *commands_cmd_element = nullptr;
15645
15646 void _initialize_breakpoint ();
15647 void
15648 _initialize_breakpoint ()
15649 {
15650   struct cmd_list_element *c;
15651
15652   initialize_breakpoint_ops ();
15653
15654   gdb::observers::solib_unloaded.attach (disable_breakpoints_in_unloaded_shlib);
15655   gdb::observers::free_objfile.attach (disable_breakpoints_in_freed_objfile);
15656   gdb::observers::memory_changed.attach (invalidate_bp_value_on_memory_change);
15657
15658   breakpoint_chain = 0;
15659   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15660      before a breakpoint is set.  */
15661   breakpoint_count = 0;
15662
15663   tracepoint_count = 0;
15664
15665   add_com ("ignore", class_breakpoint, ignore_command, _("\
15666 Set ignore-count of breakpoint number N to COUNT.\n\
15667 Usage is `ignore N COUNT'."));
15668
15669   commands_cmd_element = add_com ("commands", class_breakpoint,
15670                                   commands_command, _("\
15671 Set commands to be executed when the given breakpoints are hit.\n\
15672 Give a space-separated breakpoint list as argument after \"commands\".\n\
15673 A list element can be a breakpoint number (e.g. `5') or a range of numbers\n\
15674 (e.g. `5-7').\n\
15675 With no argument, the targeted breakpoint is the last one set.\n\
15676 The commands themselves follow starting on the next line.\n\
15677 Type a line containing \"end\" to indicate the end of them.\n\
15678 Give \"silent\" as the first line to make the breakpoint silent;\n\
15679 then no output is printed when it is hit, except what the commands print."));
15680
15681   const auto cc_opts = make_condition_command_options_def_group (nullptr);
15682   static std::string condition_command_help
15683     = gdb::option::build_help (_("\
15684 Specify breakpoint number N to break only if COND is true.\n\
15685 Usage is `condition [OPTION] N COND', where N is an integer and COND\n\
15686 is an expression to be evaluated whenever breakpoint N is reached.\n\
15687 \n\
15688 Options:\n\
15689 %OPTIONS%"), cc_opts);
15690
15691   c = add_com ("condition", class_breakpoint, condition_command,
15692                condition_command_help.c_str ());
15693   set_cmd_completer_handle_brkchars (c, condition_completer);
15694
15695   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15696 Set a temporary breakpoint.\n\
15697 Like \"break\" except the breakpoint is only temporary,\n\
15698 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15699 by using \"enable delete\" on the breakpoint number.\n\
15700 \n"
15701 BREAK_ARGS_HELP ("tbreak")));
15702   set_cmd_completer (c, location_completer);
15703
15704   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15705 Set a hardware assisted breakpoint.\n\
15706 Like \"break\" except the breakpoint requires hardware support,\n\
15707 some target hardware may not have this support.\n\
15708 \n"
15709 BREAK_ARGS_HELP ("hbreak")));
15710   set_cmd_completer (c, location_completer);
15711
15712   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15713 Set a temporary hardware assisted breakpoint.\n\
15714 Like \"hbreak\" except the breakpoint is only temporary,\n\
15715 so it will be deleted when hit.\n\
15716 \n"
15717 BREAK_ARGS_HELP ("thbreak")));
15718   set_cmd_completer (c, location_completer);
15719
15720   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15721 Enable all or some breakpoints.\n\
15722 Usage: enable [BREAKPOINTNUM]...\n\
15723 Give breakpoint numbers (separated by spaces) as arguments.\n\
15724 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15725 This is used to cancel the effect of the \"disable\" command.\n\
15726 With a subcommand you can enable temporarily."),
15727                   &enablelist, "enable ", 1, &cmdlist);
15728
15729   add_com_alias ("en", "enable", class_breakpoint, 1);
15730
15731   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15732 Enable all or some breakpoints.\n\
15733 Usage: enable breakpoints [BREAKPOINTNUM]...\n\
15734 Give breakpoint numbers (separated by spaces) as arguments.\n\
15735 This is used to cancel the effect of the \"disable\" command.\n\
15736 May be abbreviated to simply \"enable\"."),
15737                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15738
15739   add_cmd ("once", no_class, enable_once_command, _("\
15740 Enable some breakpoints for one hit.\n\
15741 Usage: enable breakpoints once BREAKPOINTNUM...\n\
15742 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15743            &enablebreaklist);
15744
15745   add_cmd ("delete", no_class, enable_delete_command, _("\
15746 Enable some breakpoints and delete when hit.\n\
15747 Usage: enable breakpoints delete BREAKPOINTNUM...\n\
15748 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15749            &enablebreaklist);
15750
15751   add_cmd ("count", no_class, enable_count_command, _("\
15752 Enable some breakpoints for COUNT hits.\n\
15753 Usage: enable breakpoints count COUNT BREAKPOINTNUM...\n\
15754 If a breakpoint is hit while enabled in this fashion,\n\
15755 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15756            &enablebreaklist);
15757
15758   add_cmd ("delete", no_class, enable_delete_command, _("\
15759 Enable some breakpoints and delete when hit.\n\
15760 Usage: enable delete BREAKPOINTNUM...\n\
15761 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15762            &enablelist);
15763
15764   add_cmd ("once", no_class, enable_once_command, _("\
15765 Enable some breakpoints for one hit.\n\
15766 Usage: enable once BREAKPOINTNUM...\n\
15767 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15768            &enablelist);
15769
15770   add_cmd ("count", no_class, enable_count_command, _("\
15771 Enable some breakpoints for COUNT hits.\n\
15772 Usage: enable count COUNT BREAKPOINTNUM...\n\
15773 If a breakpoint is hit while enabled in this fashion,\n\
15774 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15775            &enablelist);
15776
15777   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15778 Disable all or some breakpoints.\n\
15779 Usage: disable [BREAKPOINTNUM]...\n\
15780 Arguments are breakpoint numbers with spaces in between.\n\
15781 To disable all breakpoints, give no argument.\n\
15782 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15783                   &disablelist, "disable ", 1, &cmdlist);
15784   add_com_alias ("dis", "disable", class_breakpoint, 1);
15785   add_com_alias ("disa", "disable", class_breakpoint, 1);
15786
15787   add_cmd ("breakpoints", class_breakpoint, disable_command, _("\
15788 Disable all or some breakpoints.\n\
15789 Usage: disable breakpoints [BREAKPOINTNUM]...\n\
15790 Arguments are breakpoint numbers with spaces in between.\n\
15791 To disable all breakpoints, give no argument.\n\
15792 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15793 This command may be abbreviated \"disable\"."),
15794            &disablelist);
15795
15796   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15797 Delete all or some breakpoints.\n\
15798 Usage: delete [BREAKPOINTNUM]...\n\
15799 Arguments are breakpoint numbers with spaces in between.\n\
15800 To delete all breakpoints, give no argument.\n\
15801 \n\
15802 Also a prefix command for deletion of other GDB objects."),
15803                   &deletelist, "delete ", 1, &cmdlist);
15804   add_com_alias ("d", "delete", class_breakpoint, 1);
15805   add_com_alias ("del", "delete", class_breakpoint, 1);
15806
15807   add_cmd ("breakpoints", class_breakpoint, delete_command, _("\
15808 Delete all or some breakpoints or auto-display expressions.\n\
15809 Usage: delete breakpoints [BREAKPOINTNUM]...\n\
15810 Arguments are breakpoint numbers with spaces in between.\n\
15811 To delete all breakpoints, give no argument.\n\
15812 This command may be abbreviated \"delete\"."),
15813            &deletelist);
15814
15815   add_com ("clear", class_breakpoint, clear_command, _("\
15816 Clear breakpoint at specified location.\n\
15817 Argument may be a linespec, explicit, or address location as described below.\n\
15818 \n\
15819 With no argument, clears all breakpoints in the line that the selected frame\n\
15820 is executing in.\n"
15821 "\n" LOCATION_HELP_STRING "\n\n\
15822 See also the \"delete\" command which clears breakpoints by number."));
15823   add_com_alias ("cl", "clear", class_breakpoint, 1);
15824
15825   c = add_com ("break", class_breakpoint, break_command, _("\
15826 Set breakpoint at specified location.\n"
15827 BREAK_ARGS_HELP ("break")));
15828   set_cmd_completer (c, location_completer);
15829
15830   add_com_alias ("b", "break", class_run, 1);
15831   add_com_alias ("br", "break", class_run, 1);
15832   add_com_alias ("bre", "break", class_run, 1);
15833   add_com_alias ("brea", "break", class_run, 1);
15834
15835   if (dbx_commands)
15836     {
15837       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15838 Break in function/address or break at a line in the current file."),
15839                              &stoplist, "stop ", 1, &cmdlist);
15840       add_cmd ("in", class_breakpoint, stopin_command,
15841                _("Break in function or address."), &stoplist);
15842       add_cmd ("at", class_breakpoint, stopat_command,
15843                _("Break at a line in the current file."), &stoplist);
15844       add_com ("status", class_info, info_breakpoints_command, _("\
15845 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15846 The \"Type\" column indicates one of:\n\
15847 \tbreakpoint     - normal breakpoint\n\
15848 \twatchpoint     - watchpoint\n\
15849 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15850 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15851 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15852 address and file/line number respectively.\n\
15853 \n\
15854 Convenience variable \"$_\" and default examine address for \"x\"\n\
15855 are set to the address of the last breakpoint listed unless the command\n\
15856 is prefixed with \"server \".\n\n\
15857 Convenience variable \"$bpnum\" contains the number of the last\n\
15858 breakpoint set."));
15859     }
15860
15861   add_info ("breakpoints", info_breakpoints_command, _("\
15862 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15863 The \"Type\" column indicates one of:\n\
15864 \tbreakpoint     - normal breakpoint\n\
15865 \twatchpoint     - watchpoint\n\
15866 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15867 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15868 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15869 address and file/line number respectively.\n\
15870 \n\
15871 Convenience variable \"$_\" and default examine address for \"x\"\n\
15872 are set to the address of the last breakpoint listed unless the command\n\
15873 is prefixed with \"server \".\n\n\
15874 Convenience variable \"$bpnum\" contains the number of the last\n\
15875 breakpoint set."));
15876
15877   add_info_alias ("b", "breakpoints", 1);
15878
15879   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15880 Status of all breakpoints, or breakpoint number NUMBER.\n\
15881 The \"Type\" column indicates one of:\n\
15882 \tbreakpoint     - normal breakpoint\n\
15883 \twatchpoint     - watchpoint\n\
15884 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15885 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15886 \tuntil          - internal breakpoint used by the \"until\" command\n\
15887 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15888 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15889 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15890 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15891 address and file/line number respectively.\n\
15892 \n\
15893 Convenience variable \"$_\" and default examine address for \"x\"\n\
15894 are set to the address of the last breakpoint listed unless the command\n\
15895 is prefixed with \"server \".\n\n\
15896 Convenience variable \"$bpnum\" contains the number of the last\n\
15897 breakpoint set."),
15898            &maintenanceinfolist);
15899
15900   add_basic_prefix_cmd ("catch", class_breakpoint, _("\
15901 Set catchpoints to catch events."),
15902                         &catch_cmdlist, "catch ",
15903                         0/*allow-unknown*/, &cmdlist);
15904
15905   add_basic_prefix_cmd ("tcatch", class_breakpoint, _("\
15906 Set temporary catchpoints to catch events."),
15907                         &tcatch_cmdlist, "tcatch ",
15908                         0/*allow-unknown*/, &cmdlist);
15909
15910   add_catch_command ("fork", _("Catch calls to fork."),
15911                      catch_fork_command_1,
15912                      NULL,
15913                      (void *) (uintptr_t) catch_fork_permanent,
15914                      (void *) (uintptr_t) catch_fork_temporary);
15915   add_catch_command ("vfork", _("Catch calls to vfork."),
15916                      catch_fork_command_1,
15917                      NULL,
15918                      (void *) (uintptr_t) catch_vfork_permanent,
15919                      (void *) (uintptr_t) catch_vfork_temporary);
15920   add_catch_command ("exec", _("Catch calls to exec."),
15921                      catch_exec_command_1,
15922                      NULL,
15923                      CATCH_PERMANENT,
15924                      CATCH_TEMPORARY);
15925   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15926 Usage: catch load [REGEX]\n\
15927 If REGEX is given, only stop for libraries matching the regular expression."),
15928                      catch_load_command_1,
15929                      NULL,
15930                      CATCH_PERMANENT,
15931                      CATCH_TEMPORARY);
15932   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15933 Usage: catch unload [REGEX]\n\
15934 If REGEX is given, only stop for libraries matching the regular expression."),
15935                      catch_unload_command_1,
15936                      NULL,
15937                      CATCH_PERMANENT,
15938                      CATCH_TEMPORARY);
15939
15940   const auto opts = make_watch_options_def_group (nullptr);
15941
15942   static const std::string watch_help = gdb::option::build_help (_("\
15943 Set a watchpoint for EXPRESSION.\n\
15944 Usage: watch [-location] EXPRESSION\n\
15945 \n\
15946 Options:\n\
15947 %OPTIONS%\n\
15948 \n\
15949 A watchpoint stops execution of your program whenever the value of\n\
15950 an expression changes."), opts);
15951   c = add_com ("watch", class_breakpoint, watch_command,
15952                watch_help.c_str ());
15953   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15954
15955   static const std::string rwatch_help = gdb::option::build_help (_("\
15956 Set a read watchpoint for EXPRESSION.\n\
15957 Usage: rwatch [-location] EXPRESSION\n\
15958 \n\
15959 Options:\n\
15960 %OPTIONS%\n\
15961 \n\
15962 A read watchpoint stops execution of your program whenever the value of\n\
15963 an expression is read."), opts);
15964   c = add_com ("rwatch", class_breakpoint, rwatch_command,
15965                rwatch_help.c_str ());
15966   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15967
15968   static const std::string awatch_help = gdb::option::build_help (_("\
15969 Set an access watchpoint for EXPRESSION.\n\
15970 Usage: awatch [-location] EXPRESSION\n\
15971 \n\
15972 Options:\n\
15973 %OPTIONS%\n\
15974 \n\
15975 An access watchpoint stops execution of your program whenever the value\n\
15976 of an expression is either read or written."), opts);
15977   c = add_com ("awatch", class_breakpoint, awatch_command,
15978                awatch_help.c_str ());
15979   set_cmd_completer_handle_brkchars (c, watch_command_completer);
15980
15981   add_info ("watchpoints", info_watchpoints_command, _("\
15982 Status of specified watchpoints (all watchpoints if no argument)."));
15983
15984   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15985      respond to changes - contrary to the description.  */
15986   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15987                             &can_use_hw_watchpoints, _("\
15988 Set debugger's willingness to use watchpoint hardware."), _("\
15989 Show debugger's willingness to use watchpoint hardware."), _("\
15990 If zero, gdb will not use hardware for new watchpoints, even if\n\
15991 such is available.  (However, any hardware watchpoints that were\n\
15992 created before setting this to nonzero, will continue to use watchpoint\n\
15993 hardware.)"),
15994                             NULL,
15995                             show_can_use_hw_watchpoints,
15996                             &setlist, &showlist);
15997
15998   can_use_hw_watchpoints = 1;
15999
16000   /* Tracepoint manipulation commands.  */
16001
16002   c = add_com ("trace", class_breakpoint, trace_command, _("\
16003 Set a tracepoint at specified location.\n\
16004 \n"
16005 BREAK_ARGS_HELP ("trace") "\n\
16006 Do \"help tracepoints\" for info on other tracepoint commands."));
16007   set_cmd_completer (c, location_completer);
16008
16009   add_com_alias ("tp", "trace", class_breakpoint, 0);
16010   add_com_alias ("tr", "trace", class_breakpoint, 1);
16011   add_com_alias ("tra", "trace", class_breakpoint, 1);
16012   add_com_alias ("trac", "trace", class_breakpoint, 1);
16013
16014   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16015 Set a fast tracepoint at specified location.\n\
16016 \n"
16017 BREAK_ARGS_HELP ("ftrace") "\n\
16018 Do \"help tracepoints\" for info on other tracepoint commands."));
16019   set_cmd_completer (c, location_completer);
16020
16021   c = add_com ("strace", class_breakpoint, strace_command, _("\
16022 Set a static tracepoint at location or marker.\n\
16023 \n\
16024 strace [LOCATION] [if CONDITION]\n\
16025 LOCATION may be a linespec, explicit, or address location (described below) \n\
16026 or -m MARKER_ID.\n\n\
16027 If a marker id is specified, probe the marker with that name.  With\n\
16028 no LOCATION, uses current execution address of the selected stack frame.\n\
16029 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16030 This collects arbitrary user data passed in the probe point call to the\n\
16031 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16032 by printing the $_sdata variable like any other convenience variable.\n\
16033 \n\
16034 CONDITION is a boolean expression.\n\
16035 \n" LOCATION_HELP_STRING "\n\n\
16036 Multiple tracepoints at one place are permitted, and useful if their\n\
16037 conditions are different.\n\
16038 \n\
16039 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16040 Do \"help tracepoints\" for info on other tracepoint commands."));
16041   set_cmd_completer (c, location_completer);
16042
16043   add_info ("tracepoints", info_tracepoints_command, _("\
16044 Status of specified tracepoints (all tracepoints if no argument).\n\
16045 Convenience variable \"$tpnum\" contains the number of the\n\
16046 last tracepoint set."));
16047
16048   add_info_alias ("tp", "tracepoints", 1);
16049
16050   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16051 Delete specified tracepoints.\n\
16052 Arguments are tracepoint numbers, separated by spaces.\n\
16053 No argument means delete all tracepoints."),
16054            &deletelist);
16055   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16056
16057   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16058 Disable specified tracepoints.\n\
16059 Arguments are tracepoint numbers, separated by spaces.\n\
16060 No argument means disable all tracepoints."),
16061            &disablelist);
16062   deprecate_cmd (c, "disable");
16063
16064   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16065 Enable specified tracepoints.\n\
16066 Arguments are tracepoint numbers, separated by spaces.\n\
16067 No argument means enable all tracepoints."),
16068            &enablelist);
16069   deprecate_cmd (c, "enable");
16070
16071   add_com ("passcount", class_trace, trace_pass_command, _("\
16072 Set the passcount for a tracepoint.\n\
16073 The trace will end when the tracepoint has been passed 'count' times.\n\
16074 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16075 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16076
16077   add_basic_prefix_cmd ("save", class_breakpoint,
16078                         _("Save breakpoint definitions as a script."),
16079                         &save_cmdlist, "save ",
16080                         0/*allow-unknown*/, &cmdlist);
16081
16082   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16083 Save current breakpoint definitions as a script.\n\
16084 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16085 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16086 session to restore them."),
16087                &save_cmdlist);
16088   set_cmd_completer (c, filename_completer);
16089
16090   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16091 Save current tracepoint definitions as a script.\n\
16092 Use the 'source' command in another debug session to restore them."),
16093                &save_cmdlist);
16094   set_cmd_completer (c, filename_completer);
16095
16096   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16097   deprecate_cmd (c, "save tracepoints");
16098
16099   add_basic_prefix_cmd ("breakpoint", class_maintenance, _("\
16100 Breakpoint specific settings.\n\
16101 Configure various breakpoint-specific variables such as\n\
16102 pending breakpoint behavior."),
16103                         &breakpoint_set_cmdlist, "set breakpoint ",
16104                         0/*allow-unknown*/, &setlist);
16105   add_show_prefix_cmd ("breakpoint", class_maintenance, _("\
16106 Breakpoint specific settings.\n\
16107 Configure various breakpoint-specific variables such as\n\
16108 pending breakpoint behavior."),
16109                        &breakpoint_show_cmdlist, "show breakpoint ",
16110                        0/*allow-unknown*/, &showlist);
16111
16112   add_setshow_auto_boolean_cmd ("pending", no_class,
16113                                 &pending_break_support, _("\
16114 Set debugger's behavior regarding pending breakpoints."), _("\
16115 Show debugger's behavior regarding pending breakpoints."), _("\
16116 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16117 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16118 an error.  If auto, an unrecognized breakpoint location results in a\n\
16119 user-query to see if a pending breakpoint should be created."),
16120                                 NULL,
16121                                 show_pending_break_support,
16122                                 &breakpoint_set_cmdlist,
16123                                 &breakpoint_show_cmdlist);
16124
16125   pending_break_support = AUTO_BOOLEAN_AUTO;
16126
16127   add_setshow_boolean_cmd ("auto-hw", no_class,
16128                            &automatic_hardware_breakpoints, _("\
16129 Set automatic usage of hardware breakpoints."), _("\
16130 Show automatic usage of hardware breakpoints."), _("\
16131 If set, the debugger will automatically use hardware breakpoints for\n\
16132 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16133 a warning will be emitted for such breakpoints."),
16134                            NULL,
16135                            show_automatic_hardware_breakpoints,
16136                            &breakpoint_set_cmdlist,
16137                            &breakpoint_show_cmdlist);
16138
16139   add_setshow_boolean_cmd ("always-inserted", class_support,
16140                            &always_inserted_mode, _("\
16141 Set mode for inserting breakpoints."), _("\
16142 Show mode for inserting breakpoints."), _("\
16143 When this mode is on, breakpoints are inserted immediately as soon as\n\
16144 they're created, kept inserted even when execution stops, and removed\n\
16145 only when the user deletes them.  When this mode is off (the default),\n\
16146 breakpoints are inserted only when execution continues, and removed\n\
16147 when execution stops."),
16148                                 NULL,
16149                                 &show_always_inserted_mode,
16150                                 &breakpoint_set_cmdlist,
16151                                 &breakpoint_show_cmdlist);
16152
16153   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16154                         condition_evaluation_enums,
16155                         &condition_evaluation_mode_1, _("\
16156 Set mode of breakpoint condition evaluation."), _("\
16157 Show mode of breakpoint condition evaluation."), _("\
16158 When this is set to \"host\", breakpoint conditions will be\n\
16159 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16160 breakpoint conditions will be downloaded to the target (if the target\n\
16161 supports such feature) and conditions will be evaluated on the target's side.\n\
16162 If this is set to \"auto\" (default), this will be automatically set to\n\
16163 \"target\" if it supports condition evaluation, otherwise it will\n\
16164 be set to \"host\"."),
16165                            &set_condition_evaluation_mode,
16166                            &show_condition_evaluation_mode,
16167                            &breakpoint_set_cmdlist,
16168                            &breakpoint_show_cmdlist);
16169
16170   add_com ("break-range", class_breakpoint, break_range_command, _("\
16171 Set a breakpoint for an address range.\n\
16172 break-range START-LOCATION, END-LOCATION\n\
16173 where START-LOCATION and END-LOCATION can be one of the following:\n\
16174   LINENUM, for that line in the current file,\n\
16175   FILE:LINENUM, for that line in that file,\n\
16176   +OFFSET, for that number of lines after the current line\n\
16177            or the start of the range\n\
16178   FUNCTION, for the first line in that function,\n\
16179   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16180   *ADDRESS, for the instruction at that address.\n\
16181 \n\
16182 The breakpoint will stop execution of the inferior whenever it executes\n\
16183 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16184 range (including START-LOCATION and END-LOCATION)."));
16185
16186   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16187 Set a dynamic printf at specified location.\n\
16188 dprintf location,format string,arg1,arg2,...\n\
16189 location may be a linespec, explicit, or address location.\n"
16190 "\n" LOCATION_HELP_STRING));
16191   set_cmd_completer (c, location_completer);
16192
16193   add_setshow_enum_cmd ("dprintf-style", class_support,
16194                         dprintf_style_enums, &dprintf_style, _("\
16195 Set the style of usage for dynamic printf."), _("\
16196 Show the style of usage for dynamic printf."), _("\
16197 This setting chooses how GDB will do a dynamic printf.\n\
16198 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16199 console, as with the \"printf\" command.\n\
16200 If the value is \"call\", the print is done by calling a function in your\n\
16201 program; by default printf(), but you can choose a different function or\n\
16202 output stream by setting dprintf-function and dprintf-channel."),
16203                         update_dprintf_commands, NULL,
16204                         &setlist, &showlist);
16205
16206   dprintf_function = xstrdup ("printf");
16207   add_setshow_string_cmd ("dprintf-function", class_support,
16208                           &dprintf_function, _("\
16209 Set the function to use for dynamic printf."), _("\
16210 Show the function to use for dynamic printf."), NULL,
16211                           update_dprintf_commands, NULL,
16212                           &setlist, &showlist);
16213
16214   dprintf_channel = xstrdup ("");
16215   add_setshow_string_cmd ("dprintf-channel", class_support,
16216                           &dprintf_channel, _("\
16217 Set the channel to use for dynamic printf."), _("\
16218 Show the channel to use for dynamic printf."), NULL,
16219                           update_dprintf_commands, NULL,
16220                           &setlist, &showlist);
16221
16222   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16223                            &disconnected_dprintf, _("\
16224 Set whether dprintf continues after GDB disconnects."), _("\
16225 Show whether dprintf continues after GDB disconnects."), _("\
16226 Use this to let dprintf commands continue to hit and produce output\n\
16227 even if GDB disconnects or detaches from the target."),
16228                            NULL,
16229                            NULL,
16230                            &setlist, &showlist);
16231
16232   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16233 Target agent only formatted printing, like the C \"printf\" function.\n\
16234 Usage: agent-printf \"format string\", ARG1, ARG2, ARG3, ..., ARGN\n\
16235 This supports most C printf format specifications, like %s, %d, etc.\n\
16236 This is useful for formatted output in user-defined commands."));
16237
16238   automatic_hardware_breakpoints = true;
16239
16240   gdb::observers::about_to_proceed.attach (breakpoint_about_to_proceed);
16241   gdb::observers::thread_exit.attach (remove_threaded_breakpoints);
16242 }
This page took 0.972504 seconds and 4 git commands to generate.